Documentation
¶
Overview ¶
Package agent provides the agent definition and builder API.
Index ¶
- func BuildAll(ctx context.Context, fc *FileConfig, opts ...BuildOption) (map[string]*Agent, error)
- func BuildProvider(cfg ModelConfig) (model.Provider, error)
- func CompressToolCalls(messages []model.Message, maxCalls int) []model.Message
- func ExtractReasoningParts(content string) map[string]string
- func ReadStoredResult(ctx context.Context, store storage.Storage, sessionID, key string) (string, error)
- type Agent
- func (a *Agent) Chat(ctx context.Context, userMessage string) (*model.ChatResponse, error)
- func (a *Agent) ChatStream(ctx context.Context, userMessage string) (<-chan *model.ChatResponse, error)
- func (a *Agent) ChatWithSession(ctx context.Context, sessionID, userMessage string) (*model.ChatResponse, error)
- func (a *Agent) CloseMCP()
- func (a *Agent) ConnectMCP(ctx context.Context) error
- func (a *Agent) Execute(ctx context.Context, task string) (string, error)
- func (a *Agent) Resume(ctx context.Context, sessionID string) (*graph.RunState, error)
- func (a *Agent) Run(ctx context.Context, input map[string]any) (*graph.RunState, error)
- type AgentConfig
- type BuildOption
- type Builder
- func (b *Builder) AddCapability(capability string) *Builder
- func (b *Builder) AddExample(input, output string) *Builder
- func (b *Builder) AddHook(h hooks.Hook) *Builder
- func (b *Builder) AddInputGuardrail(name string, g guardrails.Guardrail) *Builder
- func (b *Builder) AddInstruction(instruction string) *Builder
- func (b *Builder) AddMCPServer(cfg mcp.ServerConfig) *Builder
- func (b *Builder) AddOutputGuardrail(name string, g guardrails.Guardrail) *Builder
- func (b *Builder) AddSkill(s *skill.Skill) *Builder
- func (b *Builder) AddSubAgent(sub *Agent) *Builder
- func (b *Builder) AddTool(def *tool.Definition) *Builder
- func (b *Builder) AddToolkit(tk *tool.Toolkit) *Builder
- func (b *Builder) Build() (*Agent, error)
- func (b *Builder) Description(d string) *Builder
- func (b *Builder) WithBroker(br *stream.Broker) *Builder
- func (b *Builder) WithContextConfig(cfg ContextConfig) *Builder
- func (b *Builder) WithContextPins(fn func(ctx context.Context) []model.Message) *Builder
- func (b *Builder) WithDebug(debug bool) *Builder
- func (b *Builder) WithGraph(g *graph.StateGraph) *Builder
- func (b *Builder) WithHistoryRuns(n int) *Builder
- func (b *Builder) WithInstructionsFn(fn func(ctx context.Context, state map[string]any) []string) *Builder
- func (b *Builder) WithKnowledge(k knowledge.Knowledge) *Builder
- func (b *Builder) WithMaxIterations(n int) *Builder
- func (b *Builder) WithMemory(m *memory.Store) *Builder
- func (b *Builder) WithMemoryManager(m *memory.Manager) *Builder
- func (b *Builder) WithMemoryRecall(cfg RecallConfig) *Builder
- func (b *Builder) WithModel(p model.Provider) *Builder
- func (b *Builder) WithOutputSchema(s map[string]any) *Builder
- func (b *Builder) WithReasoning(strategy ReasoningStrategy) *Builder
- func (b *Builder) WithReasoningModel(p model.Provider) *Builder
- func (b *Builder) WithStorage(s storage.Storage) *Builder
- func (b *Builder) WithSystemPrompt(prompt string) *Builder
- func (b *Builder) WithTracer(t *chronostrace.Collector) *Builder
- func (b *Builder) WithUserID(id string) *Builder
- type ChatSession
- type ContextConfig
- type ContextYAML
- type EvictionResult
- type Example
- type FileConfig
- type ModelConfig
- type ReasoningStrategy
- type RecallConfig
- type StorageConfig
- type TeamConfig
- type ToolConfig
- type ToolHandlerFactory
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildAll ¶
func BuildAll(ctx context.Context, fc *FileConfig, opts ...BuildOption) (map[string]*Agent, error)
BuildAll constructs all agents from a FileConfig. BuildOptions (e.g. WithToolHandler) apply to every agent built.
func BuildProvider ¶ added in v0.10.0
func BuildProvider(cfg ModelConfig) (model.Provider, error)
BuildProvider constructs a model.Provider from a ModelConfig. It is the exported entry point used by callers outside this package (e.g. the CLI wiring a team's router_model) that need the same provider resolution as agent construction.
func CompressToolCalls ¶ added in v0.3.0
CompressToolCalls removes older tool call/result pairs from message history, keeping only the most recent maxCalls pairs. System messages and non-tool messages are always preserved.
func ExtractReasoningParts ¶ added in v0.3.0
ExtractReasoningParts parses a reflection-style response into components.
Types ¶
type Agent ¶
type Agent struct {
ID string
Name string
Description string
UserID string
// Core components
Model model.Provider
Tools *tool.Registry
Skills *skill.Registry
Memory *memory.Store
Storage storage.Storage
Graph *graph.CompiledGraph
// Enhancements
Knowledge knowledge.Knowledge
MemoryManager *memory.Manager
Hooks hooks.Chain
Guardrails *guardrails.Engine
Broker *stream.Broker // SSE broker for real-time event streaming
Tracer *chronostrace.Collector // execution tracer for span-based observability
SessionState map[string]any // persistent cross-turn state
OutputSchema map[string]any // JSON Schema for structured output
NumHistoryRuns int // number of past runs to inject into context
ContextCfg ContextConfig // context window management and summarization
MemoryRecall RecallConfig // automatic semantic long-term recall policy
// ContextPinsFn supplies dynamic pinned context evaluated fresh on every
// turn. Like ContextConfig.PinnedMessages, its output is injected as system
// context and is never summarized or evicted by compaction — but because it
// runs per turn it can reflect live state (e.g. the current task plan). It is
// the decoupled seam the deep-agent preset (WC-A-005) uses to keep the active
// plan pinned without the SDK depending on the planning toolkit.
ContextPinsFn func(ctx context.Context) []model.Message
// System prompt and instructions
SystemPrompt string
Instructions []string
InstructionsFn func(ctx context.Context, state map[string]any) []string
Examples []Example
// Reasoning and iteration control
Reasoning ReasoningStrategy
ReasoningModel model.Provider // separate, more capable model for reasoning steps
Debug bool // when set, logs detailed execution info
MaxIterations int // max tool-calling loop iterations; 0 = default (25)
// MCP servers
MCPClients []*mcp.Client
// Multi-agent
SubAgents []*Agent
MaxConcurrentSubAgents int
Capabilities []string // advertised capabilities for the protocol bus
}
Agent is the top-level agent definition.
func BuildAgent ¶
func BuildAgent(ctx context.Context, cfg *AgentConfig, opts ...BuildOption) (*Agent, error)
BuildAgent constructs a fully-wired *Agent from an AgentConfig.
func (*Agent) Chat ¶
Chat sends a single user message to the agent's model and returns the response. This is a convenience method for agents that have a model but no graph.
func (*Agent) ChatStream ¶ added in v0.7.0
func (a *Agent) ChatStream(ctx context.Context, userMessage string) (<-chan *model.ChatResponse, error)
ChatStream sends a single user message and streams the model's response token by token. It returns a channel of *model.ChatResponse that the caller must drain to completion; the channel is closed when the turn finishes.
Channel protocol:
- Delta chunks have Delta == true and carry a Content fragment to print.
- Exactly one final chunk has Delta == false with the aggregated Usage and StopReason (and empty Content, since the text was already streamed).
- A chunk with Err != nil signals a fatal error; it is the last chunk.
Tool calls are handled transparently: when the model requests tools, the fragments are aggregated, the tools are executed, and the follow-up turn is streamed — so callers see live text across every round.
Note on guardrails/schema: because tokens are emitted as they arrive, output guardrails and OutputSchema are validated only AFTER the full response has been streamed. A validation failure surfaces as a trailing Err chunk, by which point the (rejected) text has already been shown. Use the blocking Chat when you need pre-emission validation.
func (*Agent) ChatWithSession ¶
func (a *Agent) ChatWithSession(ctx context.Context, sessionID, userMessage string) (*model.ChatResponse, error)
ChatWithSession sends a message within a persistent, multi-turn session. When the conversation approaches the model's context window limit, older messages are automatically summarized to stay within budget.
func (*Agent) CloseMCP ¶ added in v0.3.0
func (a *Agent) CloseMCP()
CloseMCP disconnects all MCP server connections.
func (*Agent) ConnectMCP ¶ added in v0.3.0
ConnectMCP connects all configured MCP servers and registers their tools in the agent's tool registry. Call after Build.
func (*Agent) Execute ¶
Execute runs the agent on a text task and returns the text response. Unlike Run, Execute works with just a model — no graph or storage needed. This is the primary entry point for team-based orchestration where agents are lightweight task executors.
type AgentConfig ¶
type AgentConfig struct {
ID string `yaml:"id"`
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
UserID string `yaml:"user_id,omitempty"`
Model ModelConfig `yaml:"model"`
Storage StorageConfig `yaml:"storage,omitempty"`
System string `yaml:"system_prompt,omitempty"`
Instructions []string `yaml:"instructions,omitempty"`
Tools []ToolConfig `yaml:"tools,omitempty"`
Capabilities []string `yaml:"capabilities,omitempty"`
// MCPServers lists Model Context Protocol servers whose tools are
// registered with the agent when ConnectMCP is called after Build.
MCPServers []mcp.ServerConfig `yaml:"mcp_servers,omitempty"`
OutputSchema map[string]any `yaml:"output_schema,omitempty"`
NumHistoryRuns int `yaml:"num_history_runs,omitempty"`
Stream bool `yaml:"stream,omitempty"`
Context ContextYAML `yaml:"context,omitempty"`
// Team nesting: an agent config can reference sub-agents by ID
SubAgents []string `yaml:"sub_agents,omitempty"`
}
AgentConfig is the YAML-serializable definition of a single agent.
type BuildOption ¶ added in v0.5.0
type BuildOption func(*buildOptions)
BuildOption configures BuildAgent/BuildAll. Options are applied per call, so nothing leaks between builds.
func WithToolHandler ¶ added in v0.5.0
func WithToolHandler(name string, factory ToolHandlerFactory) BuildOption
WithToolHandler binds a config tool name to a factory that builds its runtime handler for this build. When the agent being built declares a custom tool whose name matches, the factory supplies the real handler. An empty name or nil factory is ignored. Pass it to BuildAgent/BuildAll:
agent.BuildAgent(ctx, cfg, agent.WithToolHandler("word_count", factory))
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a fluent API for constructing agents.
func (*Builder) AddCapability ¶
func (*Builder) AddExample ¶ added in v0.3.0
func (*Builder) AddInputGuardrail ¶
func (b *Builder) AddInputGuardrail(name string, g guardrails.Guardrail) *Builder
func (*Builder) AddInstruction ¶
func (*Builder) AddMCPServer ¶ added in v0.3.0
func (b *Builder) AddMCPServer(cfg mcp.ServerConfig) *Builder
func (*Builder) AddOutputGuardrail ¶
func (b *Builder) AddOutputGuardrail(name string, g guardrails.Guardrail) *Builder
func (*Builder) AddSubAgent ¶
func (*Builder) AddToolkit ¶ added in v0.3.0
func (*Builder) Description ¶
func (*Builder) WithContextConfig ¶
func (b *Builder) WithContextConfig(cfg ContextConfig) *Builder
func (*Builder) WithContextPins ¶ added in v0.10.0
WithContextPins registers a function that supplies dynamic pinned context, evaluated fresh on every turn and always retained through compaction. See Agent.ContextPinsFn.
func (*Builder) WithHistoryRuns ¶
func (*Builder) WithInstructionsFn ¶ added in v0.3.0
func (*Builder) WithMaxIterations ¶ added in v0.3.0
func (*Builder) WithMemoryRecall ¶ added in v0.10.0
func (b *Builder) WithMemoryRecall(cfg RecallConfig) *Builder
func (*Builder) WithReasoning ¶ added in v0.3.0
func (b *Builder) WithReasoning(strategy ReasoningStrategy) *Builder
WithReasoning configures the agent's reasoning strategy.
func (*Builder) WithReasoningModel ¶ added in v0.3.0
func (*Builder) WithSystemPrompt ¶
func (*Builder) WithTracer ¶
func (b *Builder) WithTracer(t *chronostrace.Collector) *Builder
func (*Builder) WithUserID ¶
type ChatSession ¶
type ChatSession struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
Messages []model.Message `json:"messages"`
Summary string `json:"summary"`
// contains filtered or unexported fields
}
ChatSession manages multi-turn conversation state with automatic context-window summarization.
type ContextConfig ¶
type ContextConfig struct {
MaxContextTokens int `json:"max_context_tokens" yaml:"max_tokens"` // override model default; 0 = use model default
SummarizeThreshold float64 `json:"summarize_threshold" yaml:"summarize_threshold"` // fraction of context window to trigger summarization (default 0.8)
PreserveRecentTurns int `json:"preserve_recent_turns" yaml:"preserve_recent_turns"` // number of recent user/assistant pairs to keep (default 5)
MaxToolResultTokens int `json:"max_tool_result_tokens" yaml:"max_tool_result_tokens"` // max tokens for tool result before eviction (default 20000)
MaxToolCallsFromHistory int `json:"max_tool_calls_from_history" yaml:"max_tool_calls"` // max tool call pairs to keep in history
// PinnedMessages are injected as system context on every turn and are never
// summarized or evicted by compaction. Use them for content that must always
// be visible to the model (policies, invariants, a fixed brief). Set
// programmatically via the builder; there is no YAML surface for structured
// messages, so no yaml tag is advertised.
PinnedMessages []model.Message `json:"pinned_messages,omitempty"`
}
ContextConfig controls context window management and automatic summarization.
Automatic compaction (WC-A-004): when a session conversation approaches the model's context window, ChatWithSession summarizes older turns into a compact running summary and preserves only the most recent turns (see SummarizeThreshold and PreserveRecentTurns). PinnedMessages are always retained verbatim and are never summarized, so critical context — e.g. an operating contract or the active task plan (WC-A-001) — survives every compaction pass.
type ContextYAML ¶
type ContextYAML struct {
MaxTokens int `yaml:"max_tokens,omitempty"`
SummarizeThreshold float64 `yaml:"summarize_threshold,omitempty"`
PreserveRecentTurns int `yaml:"preserve_recent_turns,omitempty"`
}
ContextYAML is the YAML-serializable form of ContextConfig.
type EvictionResult ¶ added in v0.3.0
type EvictionResult struct {
StorageKey string `json:"storage_key"`
Preview string `json:"preview"`
FullSize int `json:"full_size"`
}
EvictionResult holds the outcome of evicting a large tool result.
func EvictLargeResult ¶ added in v0.3.0
func EvictLargeResult(ctx context.Context, store storage.Storage, sessionID, toolName string, result any) (*EvictionResult, error)
EvictLargeResult stores a large tool result in storage and returns a truncated preview with a reference key. The agent can re-read the full result using the read_stored_result built-in tool.
type FileConfig ¶
type FileConfig struct {
Agents []AgentConfig `yaml:"agents"`
Teams []TeamConfig `yaml:"teams,omitempty"`
// Defaults applied to all agents unless overridden
Defaults *AgentConfig `yaml:"defaults,omitempty"`
}
FileConfig is the top-level structure of a Chronos YAML config file. Supports both a single agent and a list of agents, plus optional teams.
func LoadFile ¶
func LoadFile(path string) (*FileConfig, error)
LoadFile parses a YAML config file and returns all agent configs. Searches in order: given path, .chronos/agents.yaml, ~/.chronos/agents.yaml.
func (*FileConfig) FindAgent ¶
func (fc *FileConfig) FindAgent(idOrName string) (*AgentConfig, error)
FindAgent looks up an agent by ID or name (case-insensitive) within a FileConfig.
func (*FileConfig) FindTeam ¶
func (fc *FileConfig) FindTeam(id string) (*TeamConfig, error)
FindTeam looks up a team by ID (case-insensitive) within a FileConfig.
type ModelConfig ¶
type ModelConfig struct {
Provider string `yaml:"provider"` // openai, anthropic, gemini, mistral, ollama, azure, groq, together, deepseek, openrouter, fireworks, perplexity, anyscale, compatible
Model string `yaml:"model,omitempty"` // model ID, e.g. "gpt-4o", "claude-sonnet-4-6"
APIKey string `yaml:"api_key,omitempty"` // literal or ${ENV_VAR}
BaseURL string `yaml:"base_url,omitempty"`
OrgID string `yaml:"org_id,omitempty"`
TimeoutSec int `yaml:"timeout_sec,omitempty"`
// Azure-specific
Endpoint string `yaml:"endpoint,omitempty"`
Deployment string `yaml:"deployment,omitempty"`
APIVersion string `yaml:"api_version,omitempty"`
}
ModelConfig describes which model provider and settings to use.
type ReasoningStrategy ¶ added in v0.3.0
type ReasoningStrategy int
ReasoningStrategy defines the chain-of-thought approach.
const ( ReasoningNone ReasoningStrategy = iota ReasoningCoT // chain-of-thought: "Let's think step by step" ReasoningReflection // think, then critique )
type RecallConfig ¶ added in v0.10.0
type RecallConfig struct {
Disabled bool `json:"disabled" yaml:"disabled"` // opt out of semantic recall
TopK int `json:"top_k" yaml:"top_k"` // memories to recall per turn; 0 = default 5
ScoreThreshold float32 `json:"score_threshold" yaml:"score_threshold"` // drop recalled memories below this score; 0 = keep all
}
RecallConfig controls automatic semantic long-term recall. Recall is enabled by default (zero value) and fires only when the agent has a MemoryManager with an attached vector index (see memory.Manager.WithVectorIndex); otherwise the agent falls back to the legacy full-memory dump, so existing agents are unaffected.
type StorageConfig ¶
type StorageConfig struct {
Backend string `yaml:"backend,omitempty"` // sqlite, postgres (default: sqlite)
DSN string `yaml:"dsn,omitempty"` // connection string or file path
// Connection-pool tuning for the SQL backends (sqlite, postgres). A zero
// value leaves the adapter's built-in default in place.
MaxOpenConns int `yaml:"max_open_conns,omitempty"`
MaxIdleConns int `yaml:"max_idle_conns,omitempty"`
ConnMaxLifetimeSec int `yaml:"conn_max_lifetime_sec,omitempty"`
}
StorageConfig describes the backing store.
type TeamConfig ¶
type TeamConfig struct {
ID string `yaml:"id"`
Name string `yaml:"name"`
Strategy string `yaml:"strategy"` // sequential, parallel, router, coordinator, swarm, hierarchy
Agents []string `yaml:"agents"` // agent IDs (order matters for sequential)
Coordinator string `yaml:"coordinator,omitempty"` // agent ID: coordinator (coordinator strategy) or root supervisor (hierarchy)
MaxConcurrency int `yaml:"max_concurrency,omitempty"` // for parallel strategy
MaxIterations int `yaml:"max_iterations,omitempty"` // for coordinator strategy
ErrorStrategy string `yaml:"error_strategy,omitempty"` // fail_fast, collect, best_effort
// Router selects how the router strategy picks an agent: "model" (default —
// an LLM reasons over agent descriptions) or "capability" (a zero-LLM
// heuristic that matches advertised capabilities against state keys).
Router string `yaml:"router,omitempty"`
// RouterModel optionally overrides which model drives model-based routing.
// When its Provider is empty, the router reuses the first member agent's
// model — set this to route with a cheaper/faster model than the workers.
RouterModel ModelConfig `yaml:"router_model,omitempty"`
// InitialAgent is the entry agent for the swarm strategy (defaults to the
// first listed agent).
InitialAgent string `yaml:"initial_agent,omitempty"`
// MaxHandoffs caps peer-to-peer handoffs in the swarm strategy (0 = default).
MaxHandoffs int `yaml:"max_handoffs,omitempty"`
}
TeamConfig defines a multi-agent team in YAML.
type ToolConfig ¶
type ToolConfig struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Parameters map[string]any `yaml:"parameters,omitempty"` // JSON Schema
}
ToolConfig describes a tool to register on the agent.
type ToolHandlerFactory ¶ added in v0.5.0
type ToolHandlerFactory func(tc ToolConfig) (tool.Handler, error)
ToolHandlerFactory constructs the runtime handler for a config-declared custom tool. It receives the ToolConfig (name, description, JSON-Schema parameters) so the factory can honor the declared contract, and returns the tool.Handler that executes the tool. A non-nil error aborts agent build.
Bind a YAML tool name to a real handler by passing WithToolHandler to BuildAgent/BuildAll, so config-built agents execute working tools instead of no-op placeholders.