Store session history, preferences, and dated records in one database per home. Commit complete turns, checkpoint tool batches, and compact history by prefix. Add memory search and writes, with previews for ambiguous corrections. Review conversations in the background and support SQLite backup and restore.
798 lines
26 KiB
Go
798 lines
26 KiB
Go
package agent
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/sipeed/picoclaw/pkg/config"
|
|
"github.com/sipeed/picoclaw/pkg/isolation"
|
|
"github.com/sipeed/picoclaw/pkg/logger"
|
|
"github.com/sipeed/picoclaw/pkg/media"
|
|
"github.com/sipeed/picoclaw/pkg/memory"
|
|
"github.com/sipeed/picoclaw/pkg/providers"
|
|
"github.com/sipeed/picoclaw/pkg/routing"
|
|
"github.com/sipeed/picoclaw/pkg/session"
|
|
"github.com/sipeed/picoclaw/pkg/tools"
|
|
)
|
|
|
|
// AgentInstance represents a fully configured agent with its own workspace,
|
|
// session manager, context builder, and tool registry.
|
|
type AgentInstance struct {
|
|
memoryDB *memory.SQLite
|
|
turnStore turnSessionStore
|
|
memoryErr error
|
|
memoryClassificationCtx context.Context
|
|
cancelMemoryClassification context.CancelFunc
|
|
modelMu *sync.RWMutex
|
|
ID string
|
|
Name string
|
|
Model string
|
|
Fallbacks []string
|
|
Workspace string
|
|
MaxIterations int
|
|
MaxTokens int
|
|
Temperature float64
|
|
ThinkingLevel ThinkingLevel
|
|
ThinkingLevelConfigured bool
|
|
ContextWindow int
|
|
SummarizeMessageThreshold int
|
|
SummarizeTokenPercent int
|
|
Provider providers.LLMProvider
|
|
Sessions session.SessionStore
|
|
ContextBuilder *ContextBuilder
|
|
Tools *tools.ToolRegistry
|
|
Definition AgentContextDefinition
|
|
Subagents *config.SubagentsConfig
|
|
SkillsFilter []string
|
|
MCPServerAllowlist map[string]struct{}
|
|
Candidates []providers.FallbackCandidate
|
|
ImageCandidates []providers.FallbackCandidate
|
|
|
|
// Router is non-nil when model routing is configured and the light model
|
|
// was successfully resolved. It scores each incoming message and decides
|
|
// whether to route to LightCandidates or stay with Candidates.
|
|
Router *routing.Router
|
|
// LightCandidates holds the resolved provider candidates for the light model.
|
|
// Pre-computed at agent creation to avoid repeated model_list lookups at runtime.
|
|
LightCandidates []providers.FallbackCandidate
|
|
// LightProvider is the concrete provider instance for the configured light model.
|
|
// It is only used when routing selects the light tier for a turn.
|
|
LightProvider providers.LLMProvider
|
|
// CandidateProviders maps candidate identity keys to per-candidate LLMProvider
|
|
// instances. Config-index keys preserve duplicate model_list entries while
|
|
// provider/model keys remain available for callers without a config identity.
|
|
CandidateProviders map[string]providers.LLMProvider
|
|
}
|
|
|
|
var fallbackAgentModelMu sync.RWMutex
|
|
|
|
type unavailableLLMProvider struct {
|
|
model string
|
|
err error
|
|
}
|
|
|
|
func (p *unavailableLLMProvider) Chat(
|
|
context.Context,
|
|
[]providers.Message,
|
|
[]providers.ToolDefinition,
|
|
string,
|
|
map[string]any,
|
|
) (*providers.LLMResponse, error) {
|
|
return nil, &providers.FailoverError{
|
|
Reason: providers.FailoverNetwork,
|
|
Model: p.model,
|
|
Wrapped: p.err,
|
|
}
|
|
}
|
|
|
|
func (p *unavailableLLMProvider) GetDefaultModel() string { return p.model }
|
|
|
|
// NewAgentInstance creates an agent instance from config.
|
|
func NewAgentInstance(
|
|
agentCfg *config.AgentConfig,
|
|
defaults *config.AgentDefaults,
|
|
cfg *config.Config,
|
|
provider providers.LLMProvider,
|
|
) *AgentInstance {
|
|
if cfg != nil {
|
|
// Keep the subprocess isolation runtime aligned with the latest loaded config
|
|
// before any tools or providers start spawning child processes.
|
|
isolation.Configure(cfg)
|
|
}
|
|
|
|
workspace := resolveAgentWorkspace(agentCfg, defaults)
|
|
os.MkdirAll(workspace, 0o755)
|
|
|
|
definition := loadAgentDefinition(workspace)
|
|
|
|
model := resolveAgentModel(agentCfg, defaults, definition)
|
|
fallbacks := resolveAgentFallbacks(agentCfg, defaults)
|
|
|
|
restrict := defaults.RestrictToWorkspace
|
|
readRestrict := restrict && !defaults.AllowReadOutsideWorkspace
|
|
|
|
// Compile path whitelist patterns from config.
|
|
allowReadPaths := buildAllowReadPatterns(cfg)
|
|
allowWritePaths := compilePatterns(cfg.Tools.AllowWritePaths)
|
|
agentToolAllowlist := resolveAgentToolAllowlist(definition)
|
|
agentMCPServerAllowlist := resolveAgentMCPServerAllowlist(definition)
|
|
|
|
toolsRegistry := tools.NewToolRegistry()
|
|
toolsRegistry.SetAllowlist(agentToolAllowlist)
|
|
|
|
if cfg.Tools.IsToolEnabled("read_file") {
|
|
maxReadFileSize := cfg.Tools.ReadFile.MaxReadFileSize
|
|
switch cfg.Tools.ReadFile.EffectiveMode() {
|
|
case config.ReadFileModeLines:
|
|
toolsRegistry.Register(tools.NewReadFileLinesTool(workspace, readRestrict, maxReadFileSize, allowReadPaths))
|
|
default:
|
|
toolsRegistry.Register(tools.NewReadFileBytesTool(workspace, readRestrict, maxReadFileSize, allowReadPaths))
|
|
}
|
|
}
|
|
if cfg.Tools.IsToolEnabled("edit_file") {
|
|
toolsRegistry.Register(tools.NewEditFileTool(workspace, restrict, allowWritePaths))
|
|
}
|
|
if cfg.Tools.IsToolEnabled("append_file") {
|
|
toolsRegistry.Register(tools.NewAppendFileTool(workspace, restrict, allowWritePaths))
|
|
}
|
|
// Build write_file's copy from the registered editors so it steers the agent
|
|
// to edit_file/append_file only when those tools are actually available.
|
|
if cfg.Tools.IsToolEnabled("write_file") {
|
|
writeTool := tools.NewWriteFileTool(workspace, restrict, allowWritePaths)
|
|
var altTools []string
|
|
if toolsRegistry.HasRegistered("append_file") {
|
|
altTools = append(altTools, "append_file")
|
|
}
|
|
if toolsRegistry.HasRegistered("edit_file") {
|
|
altTools = append(altTools, "edit_file")
|
|
}
|
|
writeTool.SetAlternativeTools(altTools)
|
|
toolsRegistry.Register(writeTool)
|
|
}
|
|
if cfg.Tools.IsToolEnabled("list_dir") {
|
|
toolsRegistry.Register(tools.NewListDirTool(workspace, readRestrict, allowReadPaths))
|
|
}
|
|
if cfg.Tools.IsToolEnabled("exec") {
|
|
execTool, err := tools.NewExecToolWithConfig(workspace, restrict, cfg, allowReadPaths)
|
|
if err != nil {
|
|
logger.ErrorCF("agent", "Failed to initialize exec tool; continuing without exec",
|
|
map[string]any{"error": err.Error()})
|
|
} else {
|
|
toolsRegistry.Register(execTool)
|
|
}
|
|
}
|
|
|
|
memoryDB, memoryErr := memory.Open(memoryDatabasePath(workspace))
|
|
var sessions *session.SQLiteSessionStore
|
|
if memoryErr == nil {
|
|
sessions = session.NewSQLiteSessionStore(memoryDB)
|
|
toolsRegistry.Register(&memorySearchTool{db: memoryDB})
|
|
}
|
|
|
|
mcpDiscoveryActive := agentHasDiscoverableMCPServers(cfg, agentMCPServerAllowlist)
|
|
contextBuilder := NewContextBuilder(workspace).
|
|
WithToolDiscovery(
|
|
mcpDiscoveryActive && cfg.Tools.MCP.Discovery.UseBM25,
|
|
mcpDiscoveryActive && cfg.Tools.MCP.Discovery.UseRegex,
|
|
).
|
|
WithSplitOnMarker(cfg.Agents.Defaults.SplitOnMarker)
|
|
|
|
agentID := routing.DefaultAgentID
|
|
agentName := ""
|
|
var subagents *config.SubagentsConfig
|
|
var skillsFilter []string
|
|
|
|
if agentCfg != nil {
|
|
agentID = routing.NormalizeAgentID(agentCfg.ID)
|
|
agentName = agentCfg.Name
|
|
if definition.Agent != nil && strings.TrimSpace(definition.Agent.Frontmatter.Name) != "" {
|
|
agentName = strings.TrimSpace(definition.Agent.Frontmatter.Name)
|
|
}
|
|
subagents = agentCfg.Subagents
|
|
skillsFilter = resolveAgentSkillsFilter(agentCfg, definition)
|
|
}
|
|
warnOnUnknownAgentMCPServerDeclarations(agentID, workspace, cfg, definition)
|
|
|
|
maxIter := defaults.MaxToolIterations
|
|
if maxIter == 0 {
|
|
maxIter = 20
|
|
}
|
|
|
|
maxTokens := defaults.MaxTokens
|
|
if maxTokens == 0 {
|
|
maxTokens = 8192
|
|
}
|
|
|
|
contextWindow := defaults.ContextWindow
|
|
if contextWindow == 0 {
|
|
// Default heuristic: 4x the output token limit.
|
|
// Most models have context windows well above their output limits
|
|
// (e.g., GPT-4o 128k ctx / 16k out, Claude 200k ctx / 8k out).
|
|
// 4x is a conservative lower bound that avoids premature
|
|
// summarization while remaining safe — the reactive
|
|
// forceCompression handles any overshoot.
|
|
contextWindow = maxTokens * 4
|
|
}
|
|
|
|
temperature := 0.7
|
|
if defaults.Temperature != nil {
|
|
temperature = *defaults.Temperature
|
|
}
|
|
|
|
var thinkingLevelStr string
|
|
if mc, err := cfg.GetModelConfig(model); err == nil {
|
|
thinkingLevelStr = mc.ThinkingLevel
|
|
}
|
|
thinkingLevel := parseThinkingLevel(thinkingLevelStr)
|
|
thinkingLevelConfigured := isConfiguredThinkingLevel(thinkingLevelStr)
|
|
|
|
summarizeMessageThreshold := defaults.SummarizeMessageThreshold
|
|
if summarizeMessageThreshold == 0 {
|
|
summarizeMessageThreshold = 20
|
|
}
|
|
|
|
summarizeTokenPercent := defaults.SummarizeTokenPercent
|
|
if summarizeTokenPercent == 0 {
|
|
summarizeTokenPercent = 75
|
|
}
|
|
|
|
// Resolve fallback candidates
|
|
candidates := resolveModelCandidates(cfg, defaults.Provider, model, fallbacks)
|
|
usesInjectedPrimary := provider != nil &&
|
|
strings.TrimSpace(model) == strings.TrimSpace(defaults.GetModelName())
|
|
if !usesInjectedPrimary && len(candidates) > 0 {
|
|
provider = resolvePrimaryProviderForCandidate(
|
|
cfg,
|
|
workspace,
|
|
agentID,
|
|
candidates[0],
|
|
provider,
|
|
)
|
|
} else if !usesInjectedPrimary {
|
|
provider = resolvePrimaryProviderForAgent(cfg, workspace, agentID, model, provider)
|
|
}
|
|
imageCandidates := resolveModelCandidates(
|
|
cfg,
|
|
defaults.Provider,
|
|
defaults.ImageModel,
|
|
defaults.ImageModelFallbacks,
|
|
)
|
|
|
|
candidateProviders := make(map[string]providers.LLMProvider)
|
|
if len(candidates) > 1 {
|
|
inheritPrimaryProviderForCandidates(
|
|
cfg,
|
|
workspace,
|
|
candidates[0],
|
|
candidates[1:],
|
|
provider,
|
|
candidateProviders,
|
|
)
|
|
populateCandidateProvidersFromCandidates(cfg, workspace, candidates[1:], candidateProviders)
|
|
}
|
|
if strings.TrimSpace(defaults.ImageModel) != "" {
|
|
if len(candidates) > 0 {
|
|
inheritPrimaryProviderForCandidates(
|
|
cfg,
|
|
workspace,
|
|
candidates[0],
|
|
imageCandidates,
|
|
provider,
|
|
candidateProviders,
|
|
)
|
|
}
|
|
populateCandidateProvidersFromCandidates(cfg, workspace, imageCandidates, candidateProviders)
|
|
}
|
|
|
|
// Model routing setup: pre-resolve light model candidates at creation time
|
|
// to avoid repeated model_list lookups on every incoming message.
|
|
var router *routing.Router
|
|
var lightCandidates []providers.FallbackCandidate
|
|
var lightProvider providers.LLMProvider
|
|
if rc := defaults.Routing; rc != nil && rc.Enabled && rc.LightModel != "" {
|
|
resolved := resolveModelCandidates(cfg, defaults.Provider, rc.LightModel, nil)
|
|
if len(resolved) > 0 {
|
|
lightModelCfg, err := resolvedCandidateModelConfig(cfg, resolved[0], workspace)
|
|
if err != nil {
|
|
logger.WarnCF(
|
|
"agent",
|
|
"Routing light model config invalid; routing disabled",
|
|
map[string]any{
|
|
"light_model": rc.LightModel,
|
|
"agent_id": agentID,
|
|
"error": err.Error(),
|
|
},
|
|
)
|
|
} else {
|
|
lp, _, err := providers.CreateProviderFromConfig(lightModelCfg)
|
|
if err != nil {
|
|
logger.WarnCF("agent", "Routing light model provider init failed; routing disabled",
|
|
map[string]any{"light_model": rc.LightModel, "agent_id": agentID, "error": err.Error()})
|
|
} else {
|
|
router = routing.New(routing.RouterConfig{
|
|
LightModel: rc.LightModel,
|
|
Threshold: rc.Threshold,
|
|
})
|
|
lightCandidates = resolved
|
|
lightProvider = lp
|
|
populateCandidateProvidersFromCandidates(cfg, workspace, resolved, candidateProviders)
|
|
}
|
|
}
|
|
} else {
|
|
logger.WarnCF("agent", "Routing light model not found; routing disabled",
|
|
map[string]any{"light_model": rc.LightModel, "agent_id": agentID})
|
|
}
|
|
}
|
|
|
|
classificationCtx, cancelClassification := context.WithCancel(context.Background())
|
|
agent := &AgentInstance{
|
|
memoryClassificationCtx: classificationCtx,
|
|
cancelMemoryClassification: cancelClassification,
|
|
modelMu: &sync.RWMutex{},
|
|
ID: agentID,
|
|
Name: agentName,
|
|
Model: model,
|
|
Fallbacks: fallbacks,
|
|
Workspace: workspace,
|
|
MaxIterations: maxIter,
|
|
MaxTokens: maxTokens,
|
|
Temperature: temperature,
|
|
ThinkingLevel: thinkingLevel,
|
|
ThinkingLevelConfigured: thinkingLevelConfigured,
|
|
ContextWindow: contextWindow,
|
|
SummarizeMessageThreshold: summarizeMessageThreshold,
|
|
SummarizeTokenPercent: summarizeTokenPercent,
|
|
Provider: provider,
|
|
memoryDB: memoryDB,
|
|
memoryErr: memoryErr,
|
|
ContextBuilder: contextBuilder,
|
|
Tools: toolsRegistry,
|
|
Definition: definition,
|
|
Subagents: subagents,
|
|
SkillsFilter: skillsFilter,
|
|
MCPServerAllowlist: agentMCPServerAllowlist,
|
|
Candidates: candidates,
|
|
ImageCandidates: imageCandidates,
|
|
Router: router,
|
|
LightCandidates: lightCandidates,
|
|
LightProvider: lightProvider,
|
|
CandidateProviders: candidateProviders,
|
|
}
|
|
if sessions != nil {
|
|
agent.Sessions = sessions
|
|
agent.turnStore = sessions
|
|
toolsRegistry.Register(&memoryWriteTool{agent: agent})
|
|
}
|
|
return agent
|
|
}
|
|
|
|
// populateCandidateProvidersFromNames resolves each model name (alias or
|
|
// "provider/model") and creates a dedicated LLMProvider for it. Raw references
|
|
// reuse endpoint and credential settings from another model of the same provider.
|
|
func populateCandidateProvidersFromNames(
|
|
cfg *config.Config,
|
|
workspace string,
|
|
names []string,
|
|
out map[string]providers.LLMProvider,
|
|
) {
|
|
if cfg == nil || len(names) == 0 {
|
|
return
|
|
}
|
|
for _, name := range names {
|
|
candidates := resolveModelCandidates(cfg, cfg.Agents.Defaults.Provider, name, nil)
|
|
populateCandidateProvidersFromCandidates(cfg, workspace, candidates, out)
|
|
}
|
|
}
|
|
|
|
func populateCandidateProvidersFromCandidates(
|
|
cfg *config.Config,
|
|
workspace string,
|
|
candidates []providers.FallbackCandidate,
|
|
out map[string]providers.LLMProvider,
|
|
) {
|
|
if cfg == nil {
|
|
return
|
|
}
|
|
for _, candidate := range candidates {
|
|
mc, err := resolvedCandidateModelConfig(cfg, candidate, workspace)
|
|
if err != nil {
|
|
logger.WarnCF("agent",
|
|
"fallback provider: no model_list entry found; will inherit primary provider credentials",
|
|
map[string]any{"name": candidate.DisplayName, "error": err.Error()})
|
|
continue
|
|
}
|
|
key := candidateProviderKey(candidate)
|
|
if _, exists := out[key]; exists {
|
|
continue
|
|
}
|
|
p, _, err := providers.CreateProviderFromConfig(mc)
|
|
if err != nil {
|
|
logger.WarnCF("agent", "fallback provider: failed to create provider",
|
|
map[string]any{"model": mc.Model, "error": err.Error()})
|
|
p = &unavailableLLMProvider{model: candidate.Model, err: err}
|
|
}
|
|
out[key] = p
|
|
runtimeKey := providers.ModelKey(candidate.Provider, candidate.Model)
|
|
if _, exists := out[runtimeKey]; !exists {
|
|
out[runtimeKey] = p
|
|
}
|
|
}
|
|
}
|
|
|
|
func candidateProviderKey(candidate providers.FallbackCandidate) string {
|
|
if candidate.ConfigKey != "" {
|
|
return candidate.ConfigKey
|
|
}
|
|
if candidate.ConfigIndex > 0 {
|
|
return fmt.Sprintf("config_index:%d", candidate.ConfigIndex)
|
|
}
|
|
return providers.ModelKey(candidate.Provider, candidate.Model)
|
|
}
|
|
|
|
func inheritPrimaryProviderForCandidates(
|
|
cfg *config.Config,
|
|
workspace string,
|
|
primaryCandidate providers.FallbackCandidate,
|
|
candidates []providers.FallbackCandidate,
|
|
primaryProvider providers.LLMProvider,
|
|
out map[string]providers.LLMProvider,
|
|
) {
|
|
if primaryProvider == nil {
|
|
return
|
|
}
|
|
primaryProtocol := providers.NormalizeProvider(primaryCandidate.Provider)
|
|
for _, candidate := range candidates {
|
|
key := candidateProviderKey(candidate)
|
|
if out[key] != nil || providers.NormalizeProvider(candidate.Provider) != primaryProtocol {
|
|
continue
|
|
}
|
|
if !candidateCanInheritProvider(cfg, workspace, candidate) {
|
|
continue
|
|
}
|
|
out[key] = primaryProvider
|
|
runtimeKey := providers.ModelKey(candidate.Provider, candidate.Model)
|
|
if out[runtimeKey] == nil {
|
|
out[runtimeKey] = primaryProvider
|
|
}
|
|
}
|
|
}
|
|
|
|
func candidateCanInheritProvider(
|
|
cfg *config.Config,
|
|
workspace string,
|
|
candidate providers.FallbackCandidate,
|
|
) bool {
|
|
modelCfg, err := resolvedCandidateModelConfig(cfg, candidate, workspace)
|
|
return err == nil &&
|
|
strings.TrimSpace(modelCfg.APIBase) == "" &&
|
|
modelCfg.APIKey() == "" &&
|
|
strings.TrimSpace(modelCfg.AuthMethod) == "" &&
|
|
strings.TrimSpace(modelCfg.ConnectMode) == ""
|
|
}
|
|
|
|
func resolvedCandidateModelConfig(
|
|
cfg *config.Config,
|
|
candidate providers.FallbackCandidate,
|
|
workspace string,
|
|
) (*config.ModelConfig, error) {
|
|
if candidate.ConfigIndex > 0 && candidate.ConfigIndex <= len(cfg.ModelList) {
|
|
modelCfg := cfg.ModelList[candidate.ConfigIndex-1]
|
|
if modelCfg != nil && !modelCfg.IsVirtual() &&
|
|
(candidate.ConfigKey == "" ||
|
|
modelConfigResolutionKey(cfg.Agents.Defaults.Provider, modelCfg) == candidate.ConfigKey) {
|
|
return resolvedCandidateModelConfigClone(modelCfg, candidate, workspace), nil
|
|
}
|
|
}
|
|
if candidate.ConfigKey != "" {
|
|
for _, modelCfg := range cfg.ModelList {
|
|
if modelCfg == nil || modelCfg.IsVirtual() ||
|
|
modelConfigResolutionKey(cfg.Agents.Defaults.Provider, modelCfg) != candidate.ConfigKey {
|
|
continue
|
|
}
|
|
return resolvedCandidateModelConfigClone(modelCfg, candidate, workspace), nil
|
|
}
|
|
}
|
|
alias := modelAliasFromCandidateIdentityKey(candidate.IdentityKey)
|
|
for _, modelCfg := range cfg.ModelList {
|
|
if modelCfg == nil || modelCfg.IsVirtual() {
|
|
continue
|
|
}
|
|
if alias != "" && modelCfg.ModelName != alias {
|
|
continue
|
|
}
|
|
provider, modelID := modelProviderAndIDForResolution(cfg.Agents.Defaults.Provider, modelCfg)
|
|
if providers.ModelKey(provider, modelID) != providers.ModelKey(candidate.Provider, candidate.Model) {
|
|
continue
|
|
}
|
|
return resolvedCandidateModelConfigClone(modelCfg, candidate, workspace), nil
|
|
}
|
|
return resolvedRuntimeModelConfig(cfg, candidate.DisplayName, workspace)
|
|
}
|
|
|
|
func resolvedCandidateModelConfigClone(
|
|
modelCfg *config.ModelConfig,
|
|
candidate providers.FallbackCandidate,
|
|
workspace string,
|
|
) *config.ModelConfig {
|
|
clone := *modelCfg
|
|
if strings.TrimSpace(clone.Provider) == "" {
|
|
inferredProvider, _ := providers.SplitModelProviderAndID(clone.Model, "")
|
|
if inferredProvider == "" {
|
|
clone.Provider = candidate.Provider
|
|
}
|
|
}
|
|
if clone.Workspace == "" {
|
|
clone.Workspace = workspace
|
|
}
|
|
return &clone
|
|
}
|
|
|
|
// resolvePrimaryProviderForAgent resolves a dedicated provider for the active
|
|
// primary model when the model points at a model_list entry. This keeps the
|
|
// agent's single-candidate path aligned with the selected model's own
|
|
// provider/api_base/api_key instead of inheriting the process default provider.
|
|
func resolvePrimaryProviderForAgent(
|
|
cfg *config.Config,
|
|
workspace string,
|
|
agentID string,
|
|
model string,
|
|
fallback providers.LLMProvider,
|
|
) providers.LLMProvider {
|
|
model = strings.TrimSpace(model)
|
|
if cfg == nil || model == "" {
|
|
return fallback
|
|
}
|
|
|
|
modelCfg, err := resolvedRuntimeModelConfig(cfg, model, workspace)
|
|
if err != nil {
|
|
return fallback
|
|
}
|
|
|
|
resolvedProvider, _, err := providers.CreateProviderFromConfig(modelCfg)
|
|
if err != nil {
|
|
logger.WarnCF("agent", "Primary model provider init failed",
|
|
map[string]any{
|
|
"agent_id": agentID,
|
|
"model": model,
|
|
"error": err.Error(),
|
|
})
|
|
return &unavailableLLMProvider{model: model, err: err}
|
|
}
|
|
if resolvedProvider == nil {
|
|
return &unavailableLLMProvider{
|
|
model: model,
|
|
err: fmt.Errorf("primary model %q initialized without a provider", model),
|
|
}
|
|
}
|
|
return resolvedProvider
|
|
}
|
|
|
|
func resolvePrimaryProviderForCandidate(
|
|
cfg *config.Config,
|
|
workspace string,
|
|
agentID string,
|
|
candidate providers.FallbackCandidate,
|
|
fallback providers.LLMProvider,
|
|
) providers.LLMProvider {
|
|
if candidate.ConfigKey == "" && candidate.ConfigIndex == 0 {
|
|
return fallback
|
|
}
|
|
modelCfg, err := resolvedCandidateModelConfig(cfg, candidate, workspace)
|
|
if err != nil {
|
|
return &unavailableLLMProvider{model: candidate.Model, err: err}
|
|
}
|
|
resolvedProvider, _, err := providers.CreateProviderFromConfig(modelCfg)
|
|
if err != nil {
|
|
logger.WarnCF("agent", "Primary model provider init failed",
|
|
map[string]any{"agent_id": agentID, "model": candidate.DisplayName, "error": err.Error()})
|
|
return &unavailableLLMProvider{model: candidate.Model, err: err}
|
|
}
|
|
if resolvedProvider == nil {
|
|
return &unavailableLLMProvider{
|
|
model: candidate.Model,
|
|
err: fmt.Errorf("primary model %q initialized without a provider", candidate.DisplayName),
|
|
}
|
|
}
|
|
return resolvedProvider
|
|
}
|
|
|
|
// resolveAgentWorkspace determines the workspace directory for an agent.
|
|
func resolveAgentWorkspace(agentCfg *config.AgentConfig, defaults *config.AgentDefaults) string {
|
|
if agentCfg != nil && strings.TrimSpace(agentCfg.Workspace) != "" {
|
|
return expandHome(strings.TrimSpace(agentCfg.Workspace))
|
|
}
|
|
// Use the configured default workspace (respects PICOCLAW_HOME)
|
|
if agentCfg == nil || agentCfg.Default || agentCfg.ID == "" ||
|
|
routing.NormalizeAgentID(agentCfg.ID) == "main" {
|
|
return expandHome(defaults.Workspace)
|
|
}
|
|
// For named agents without explicit workspace, use default workspace with agent ID suffix
|
|
id := routing.NormalizeAgentID(agentCfg.ID)
|
|
return filepath.Join(expandHome(defaults.Workspace), "..", "workspace-"+id)
|
|
}
|
|
|
|
// resolveAgentModel resolves the primary model for an agent.
|
|
func resolveAgentModel(
|
|
agentCfg *config.AgentConfig,
|
|
defaults *config.AgentDefaults,
|
|
definition AgentContextDefinition,
|
|
) string {
|
|
if definition.Agent != nil && strings.TrimSpace(definition.Agent.Frontmatter.Model) != "" {
|
|
return strings.TrimSpace(definition.Agent.Frontmatter.Model)
|
|
}
|
|
if agentCfg != nil && agentCfg.Model != nil && strings.TrimSpace(agentCfg.Model.Primary) != "" {
|
|
return strings.TrimSpace(agentCfg.Model.Primary)
|
|
}
|
|
return defaults.GetModelName()
|
|
}
|
|
|
|
// resolveAgentFallbacks resolves the fallback models for an agent.
|
|
func resolveAgentFallbacks(agentCfg *config.AgentConfig, defaults *config.AgentDefaults) []string {
|
|
if agentCfg != nil && agentCfg.Model != nil && agentCfg.Model.Fallbacks != nil {
|
|
return agentCfg.Model.Fallbacks
|
|
}
|
|
return defaults.ModelFallbacks
|
|
}
|
|
|
|
func resolveAgentSkillsFilter(
|
|
agentCfg *config.AgentConfig,
|
|
definition AgentContextDefinition,
|
|
) []string {
|
|
if definition.Agent != nil && definition.Agent.Frontmatter.Skills != nil {
|
|
return append([]string(nil), definition.Agent.Frontmatter.Skills...)
|
|
}
|
|
if agentCfg == nil || agentCfg.Skills == nil {
|
|
return nil
|
|
}
|
|
return append([]string(nil), agentCfg.Skills...)
|
|
}
|
|
|
|
func (a *AgentInstance) AllowsMCPServer(serverName string) bool {
|
|
if a == nil || a.MCPServerAllowlist == nil {
|
|
return true
|
|
}
|
|
_, ok := a.MCPServerAllowlist[strings.ToLower(strings.TrimSpace(serverName))]
|
|
return ok
|
|
}
|
|
|
|
func compilePatterns(patterns []string) []*regexp.Regexp {
|
|
compiled := make([]*regexp.Regexp, 0, len(patterns))
|
|
for _, p := range patterns {
|
|
re, err := regexp.Compile(p)
|
|
if err != nil {
|
|
logger.WarnCF("agent", "invalid path pattern in compilePatterns", map[string]any{
|
|
"pattern": p,
|
|
"error": err.Error(),
|
|
})
|
|
continue
|
|
}
|
|
compiled = append(compiled, re)
|
|
}
|
|
return compiled
|
|
}
|
|
|
|
func buildAllowReadPatterns(cfg *config.Config) []*regexp.Regexp {
|
|
var configured []string
|
|
if cfg != nil {
|
|
configured = cfg.Tools.AllowReadPaths
|
|
}
|
|
|
|
compiled := compilePatterns(configured)
|
|
mediaDirPattern := regexp.MustCompile(mediaTempDirPattern())
|
|
for _, pattern := range compiled {
|
|
if pattern.String() == mediaDirPattern.String() {
|
|
return compiled
|
|
}
|
|
}
|
|
|
|
return append(compiled, mediaDirPattern)
|
|
}
|
|
|
|
func mediaTempDirPattern() string {
|
|
sep := regexp.QuoteMeta(string(os.PathSeparator))
|
|
return "^" + regexp.QuoteMeta(filepath.Clean(media.TempDir())) + "(?:" + sep + "|$)"
|
|
}
|
|
|
|
// Close releases resources held by the agent's providers and session store.
|
|
func (a *AgentInstance) Close() error {
|
|
if a.cancelMemoryClassification != nil {
|
|
a.cancelMemoryClassification()
|
|
}
|
|
modelMu := a.modelStateMutex()
|
|
modelMu.Lock()
|
|
defer modelMu.Unlock()
|
|
providerList := make([]providers.LLMProvider, 0, 2+len(a.CandidateProviders))
|
|
providerList = append(providerList, a.Provider, a.LightProvider)
|
|
for _, provider := range a.CandidateProviders {
|
|
providerList = append(providerList, provider)
|
|
}
|
|
closeUniqueStatefulProviders(providerList...)
|
|
if a.Sessions != nil {
|
|
return a.Sessions.Close()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *AgentInstance) modelStateMutex() *sync.RWMutex {
|
|
if a.modelMu == nil {
|
|
return &fallbackAgentModelMu
|
|
}
|
|
return a.modelMu
|
|
}
|
|
|
|
func closeUniqueStatefulProviders(providerList ...providers.LLMProvider) {
|
|
seen := make(map[string]struct{})
|
|
for _, provider := range providerList {
|
|
stateful, ok := provider.(providers.StatefulProvider)
|
|
if !ok || stateful == nil {
|
|
continue
|
|
}
|
|
key := fmt.Sprintf("%T:%p", stateful, stateful)
|
|
if _, exists := seen[key]; exists {
|
|
continue
|
|
}
|
|
seen[key] = struct{}{}
|
|
stateful.Close()
|
|
}
|
|
}
|
|
|
|
func copyInitializedCandidateProviders(
|
|
source map[string]providers.LLMProvider,
|
|
destination map[string]providers.LLMProvider,
|
|
candidates []providers.FallbackCandidate,
|
|
) {
|
|
for _, candidate := range candidates {
|
|
for _, key := range []string{
|
|
candidateProviderKey(candidate),
|
|
providers.ModelKey(candidate.Provider, candidate.Model),
|
|
} {
|
|
if provider := source[key]; provider != nil {
|
|
destination[key] = provider
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func closeUnreferencedStatefulProviders(
|
|
previous map[string]providers.LLMProvider,
|
|
current map[string]providers.LLMProvider,
|
|
retained ...providers.LLMProvider,
|
|
) {
|
|
retainedKeys := make(map[string]struct{}, len(current)+len(retained))
|
|
for _, provider := range current {
|
|
retainedKeys[fmt.Sprintf("%T:%p", provider, provider)] = struct{}{}
|
|
}
|
|
for _, provider := range retained {
|
|
retainedKeys[fmt.Sprintf("%T:%p", provider, provider)] = struct{}{}
|
|
}
|
|
|
|
removed := make([]providers.LLMProvider, 0, len(previous))
|
|
for _, provider := range previous {
|
|
if _, exists := retainedKeys[fmt.Sprintf("%T:%p", provider, provider)]; !exists {
|
|
removed = append(removed, provider)
|
|
}
|
|
}
|
|
closeUniqueStatefulProviders(removed...)
|
|
}
|
|
|
|
var memoryDatabasePath = func(_ string) string { return memory.Path(config.GetHome()) }
|
|
|
|
func expandHome(path string) string {
|
|
if path == "" {
|
|
return path
|
|
}
|
|
if path[0] == '~' {
|
|
home, _ := os.UserHomeDir()
|
|
if len(path) > 1 && path[1] == '/' {
|
|
return home + path[1:]
|
|
}
|
|
return home
|
|
}
|
|
return path
|
|
}
|