mirror of
https://github.com/sipeed/picoclaw.git
synced 2026-06-12 18:08:54 +00:00
26f623ed32
* feat(session): add SessionStore interface and JSONL backend adapter Extract a SessionStore interface from the methods the agent loop uses (AddMessage, GetHistory, SetSummary, TruncateHistory, Save, etc.). Both SessionManager and the new JSONLBackend satisfy this interface, allowing the persistence layer to be swapped transparently. JSONLBackend wraps memory.Store and maps its error-returning API to the fire-and-forget contract that the agent loop expects — write errors are logged, reads return empty defaults on failure. Save() triggers compaction to reclaim space after logical truncation. Part of #1169 * test(session): add JSONLBackend integration tests 8 tests covering the full SessionStore contract through the JSONL backend: message roundtrip, tool calls, summary, truncation with compaction, history replacement, empty sessions, session isolation, and the complete summarization flow (SetSummary → TruncateHistory → Save). Includes compile-time interface satisfaction checks for both SessionManager and JSONLBackend. Part of #1169 * feat(agent): wire JSONL session store into agent loop Replace the concrete *SessionManager field with the SessionStore interface and initialize the JSONL backend by default. Legacy .json session files are auto-migrated on first startup. Falls back to SessionManager if the JSONL store cannot be initialized. The agent loop code (loop.go) requires zero changes — all method calls work identically through the interface. Closes #1169 * fix(session): propagate compact error from Save Save() was swallowing the error returned by Compact and always returning nil. Callers checking Save's return value would never see a compaction failure. Return the error directly so the agent loop can log or handle it as needed. * feat(session): add Close to SessionStore interface Add Close() error to SessionStore so callers can release resources through the interface. JSONLBackend already had Close; this adds a no-op implementation to SessionManager for compatibility. * fix(session): close session stores on shutdown and harden migration - Add Close() to AgentInstance, AgentRegistry, and AgentLoop so JSONL file handles are released during gateway shutdown and CLI exit. - Fall back to SessionManager when migration fails, preventing a split state where some sessions live in JSONL and others remain in JSON. - Add defer agentLoop.Close() in the CLI agent command path. - Document SessionStore interface methods (fire-and-forget contract).
141 lines
3.7 KiB
Go
141 lines
3.7 KiB
Go
package agent
|
|
|
|
import (
|
|
"sync"
|
|
|
|
"github.com/sipeed/picoclaw/pkg/config"
|
|
"github.com/sipeed/picoclaw/pkg/logger"
|
|
"github.com/sipeed/picoclaw/pkg/providers"
|
|
"github.com/sipeed/picoclaw/pkg/routing"
|
|
"github.com/sipeed/picoclaw/pkg/tools"
|
|
)
|
|
|
|
// AgentRegistry manages multiple agent instances and routes messages to them.
|
|
type AgentRegistry struct {
|
|
agents map[string]*AgentInstance
|
|
resolver *routing.RouteResolver
|
|
mu sync.RWMutex
|
|
}
|
|
|
|
// NewAgentRegistry creates a registry from config, instantiating all agents.
|
|
func NewAgentRegistry(
|
|
cfg *config.Config,
|
|
provider providers.LLMProvider,
|
|
) *AgentRegistry {
|
|
registry := &AgentRegistry{
|
|
agents: make(map[string]*AgentInstance),
|
|
resolver: routing.NewRouteResolver(cfg),
|
|
}
|
|
|
|
agentConfigs := cfg.Agents.List
|
|
if len(agentConfigs) == 0 {
|
|
implicitAgent := &config.AgentConfig{
|
|
ID: "main",
|
|
Default: true,
|
|
}
|
|
instance := NewAgentInstance(implicitAgent, &cfg.Agents.Defaults, cfg, provider)
|
|
registry.agents["main"] = instance
|
|
logger.InfoCF("agent", "Created implicit main agent (no agents.list configured)", nil)
|
|
} else {
|
|
for i := range agentConfigs {
|
|
ac := &agentConfigs[i]
|
|
id := routing.NormalizeAgentID(ac.ID)
|
|
instance := NewAgentInstance(ac, &cfg.Agents.Defaults, cfg, provider)
|
|
registry.agents[id] = instance
|
|
logger.InfoCF("agent", "Registered agent",
|
|
map[string]any{
|
|
"agent_id": id,
|
|
"name": ac.Name,
|
|
"workspace": instance.Workspace,
|
|
"model": instance.Model,
|
|
})
|
|
}
|
|
}
|
|
|
|
return registry
|
|
}
|
|
|
|
// GetAgent returns the agent instance for a given ID.
|
|
func (r *AgentRegistry) GetAgent(agentID string) (*AgentInstance, bool) {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
id := routing.NormalizeAgentID(agentID)
|
|
agent, ok := r.agents[id]
|
|
return agent, ok
|
|
}
|
|
|
|
// ResolveRoute determines which agent handles the message.
|
|
func (r *AgentRegistry) ResolveRoute(input routing.RouteInput) routing.ResolvedRoute {
|
|
return r.resolver.ResolveRoute(input)
|
|
}
|
|
|
|
// ListAgentIDs returns all registered agent IDs.
|
|
func (r *AgentRegistry) ListAgentIDs() []string {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
ids := make([]string, 0, len(r.agents))
|
|
for id := range r.agents {
|
|
ids = append(ids, id)
|
|
}
|
|
return ids
|
|
}
|
|
|
|
// CanSpawnSubagent checks if parentAgentID is allowed to spawn targetAgentID.
|
|
func (r *AgentRegistry) CanSpawnSubagent(parentAgentID, targetAgentID string) bool {
|
|
parent, ok := r.GetAgent(parentAgentID)
|
|
if !ok {
|
|
return false
|
|
}
|
|
if parent.Subagents == nil || parent.Subagents.AllowAgents == nil {
|
|
return false
|
|
}
|
|
targetNorm := routing.NormalizeAgentID(targetAgentID)
|
|
for _, allowed := range parent.Subagents.AllowAgents {
|
|
if allowed == "*" {
|
|
return true
|
|
}
|
|
if routing.NormalizeAgentID(allowed) == targetNorm {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ForEachTool calls fn for every tool registered under the given name
|
|
// across all agents. This is useful for propagating dependencies (e.g.
|
|
// MediaStore) to tools after registry construction.
|
|
func (r *AgentRegistry) ForEachTool(name string, fn func(tools.Tool)) {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
for _, agent := range r.agents {
|
|
if t, ok := agent.Tools.Get(name); ok {
|
|
fn(t)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Close releases resources held by all registered agents.
|
|
func (r *AgentRegistry) Close() {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
for _, agent := range r.agents {
|
|
if err := agent.Close(); err != nil {
|
|
logger.WarnCF("agent", "Failed to close agent",
|
|
map[string]any{"agent_id": agent.ID, "error": err.Error()})
|
|
}
|
|
}
|
|
}
|
|
|
|
// GetDefaultAgent returns the default agent instance.
|
|
func (r *AgentRegistry) GetDefaultAgent() *AgentInstance {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
if agent, ok := r.agents["main"]; ok {
|
|
return agent
|
|
}
|
|
for _, agent := range r.agents {
|
|
return agent
|
|
}
|
|
return nil
|
|
}
|