Documentation
¶
Overview ¶
ABOUTME: Implements the Agent type - the top-level abstraction that wraps ABOUTME: orchestrator with per-agent tool filtering and hierarchy support.
ABOUTME: Implements background agent execution with async result retrieval. ABOUTME: Provides RunAsync, status tracking, and result polling/waiting.
ABOUTME: Defines Config - the configuration struct for creating agents with ABOUTME: specific tool access, LLM clients, and execution settings.
ABOUTME: Provides preset agent configurations for common patterns. ABOUTME: Includes Explorer, Planner, and Researcher presets with sensible defaults.
ABOUTME: Implements transcript persistence for agent resume capability. ABOUTME: Provides JSONL serialization/deserialization of conversation history.
Index ¶
- Variables
- type Agent
- func (a *Agent) Children() []*Agent
- func (a *Agent) ClearMessages()
- func (a *Agent) Config() Config
- func (a *Agent) Continue(ctx context.Context, prompt string) error
- func (a *Agent) ContinueAsync(ctx context.Context, prompt string) *RunHandle
- func (a *Agent) Executor() *tool.Executor
- func (a *Agent) Hooks() *hooks.Manager
- func (a *Agent) ID() string
- func (a *Agent) Messages() []llm.Message
- func (a *Agent) Parent() *Agent
- func (a *Agent) RemoveAllChildren()
- func (a *Agent) RemoveChild(child *Agent) bool
- func (a *Agent) ResetUsage()
- func (a *Agent) RestoreTranscript(t *Transcript) error
- func (a *Agent) Run(ctx context.Context, prompt string) error
- func (a *Agent) RunAsync(ctx context.Context, prompt string) *RunHandle
- func (a *Agent) RunChild(ctx context.Context, child *Agent, prompt string) error
- func (a *Agent) RunChildAsync(ctx context.Context, child *Agent, prompt string) *RunHandle
- func (a *Agent) SaveTranscript() *Transcript
- func (a *Agent) SetMessages(messages []llm.Message)
- func (a *Agent) SpawnChild(cfg Config) (*Agent, error)
- func (a *Agent) SpawnExplorer(cfg Config) (*Agent, error)
- func (a *Agent) SpawnPlanner(cfg Config) (*Agent, error)
- func (a *Agent) SpawnResearcher(cfg Config) (*Agent, error)
- func (a *Agent) SpawnReviewer(cfg Config) (*Agent, error)
- func (a *Agent) SpawnWriter(cfg Config) (*Agent, error)
- func (a *Agent) Subscribe() <-chan orchestrator.Event
- func (a *Agent) Usage() orchestrator.TokenUsage
- type Config
- type Preset
- func (p Preset) Apply(base Config) Config
- func (p Preset) WithAllowedTools(tools ...string) Preset
- func (p Preset) WithDeniedTools(tools ...string) Preset
- func (p Preset) WithMaxIterations(max int) Preset
- func (p Preset) WithName(name string) Preset
- func (p Preset) WithSystemPrompt(prompt string) Preset
- type RunHandle
- func (h *RunHandle) Agent() *Agent
- func (h *RunHandle) Cancel() bool
- func (h *RunHandle) Done() <-chan struct{}
- func (h *RunHandle) Duration() time.Duration
- func (h *RunHandle) Err() error
- func (h *RunHandle) IsComplete() bool
- func (h *RunHandle) Poll() (RunStatus, error)
- func (h *RunHandle) Status() RunStatus
- func (h *RunHandle) Wait() error
- func (h *RunHandle) WaitWithTimeout(timeout time.Duration) error
- type RunStatus
- type Transcript
- func FromMessages(agentID string, messages []llm.Message) *Transcript
- func LoadFromFile(path string) (*Transcript, error)
- func LoadFromFileJSONL(path string) (*Transcript, error)
- func LoadJSON(r io.Reader) (*Transcript, error)
- func LoadJSONL(r io.Reader) (*Transcript, error)
- func NewTranscript(agentID string) *Transcript
- func (t *Transcript) Append(msg llm.Message)
- func (t *Transcript) Len() int
- func (t *Transcript) SaveJSON(w io.Writer) error
- func (t *Transcript) SaveJSONL(w io.Writer) error
- func (t *Transcript) SaveToFile(path string) error
- func (t *Transcript) SaveToFileJSONL(path string) error
- func (t *Transcript) ToMessages() []llm.Message
- type TranscriptEntry
Constants ¶
This section is empty.
Variables ¶
var (
ErrInvalidChildTools = errors.New("child cannot have tools parent doesn't have")
)
var ExplorerPreset = Preset{ Name: "explorer", SystemPrompt: `You are a codebase explorer. Your job is to find information efficiently. Guidelines: - Use search tools (grep, glob) to locate relevant files - Read files to understand structure and patterns - Report findings clearly and concisely - Do not modify any files - Focus on answering the specific question asked`, AllowedTools: []string{ "read_file", "read", "glob", "grep", "search", "list_files", "list_directory", "ls", }, MaxIterations: 20, }
ExplorerPreset creates agents optimized for codebase exploration. Uses read-only tools and a system prompt focused on finding information.
var PlannerPreset = Preset{ Name: "planner", SystemPrompt: `You are a software architect and planner. Your job is to design implementation approaches. Guidelines: - Analyze existing code structure before proposing changes - Create step-by-step implementation plans - Consider edge cases and error handling - Identify dependencies and potential conflicts - Do not implement - only plan - Output structured, actionable plans`, AllowedTools: []string{ "read_file", "read", "glob", "grep", "search", "list_files", "list_directory", "ls", }, MaxIterations: 30, }
PlannerPreset creates agents optimized for planning and design. Uses read-only tools and a system prompt focused on architecture.
var ResearcherPreset = Preset{ Name: "researcher", SystemPrompt: `You are a researcher. Your job is to gather and synthesize information from multiple sources. Guidelines: - Search the codebase for existing patterns and implementations - Use web search for external documentation and best practices - Cross-reference findings from multiple sources - Cite sources for your findings - Summarize key findings clearly - Note any contradictions or uncertainties`, AllowedTools: []string{ "read_file", "read", "glob", "grep", "search", "list_files", "list_directory", "ls", "web_search", "web_fetch", "fetch_url", }, MaxIterations: 40, }
ResearcherPreset creates agents optimized for multi-source research. Can access web and codebase for comprehensive research.
var ReviewerPreset = Preset{ Name: "reviewer", SystemPrompt: `You are a code reviewer. Your job is to analyze code for issues and improvements. Guidelines: - Check for bugs, security issues, and performance problems - Verify code follows project conventions - Look for edge cases and error handling gaps - Suggest specific improvements with examples - Be constructive and actionable - Prioritize issues by severity`, AllowedTools: []string{ "read_file", "read", "glob", "grep", "search", "list_files", "list_directory", "ls", }, MaxIterations: 30, }
ReviewerPreset creates agents optimized for code review. Read-only access with a review-focused system prompt.
var WriterPreset = Preset{
Name: "writer",
SystemPrompt: `You are a code writer. Your job is to implement changes based on specifications.
Guidelines:
- Follow the existing code style and patterns
- Write clean, readable, well-documented code
- Handle errors appropriately
- Write tests for new functionality
- Make minimal, focused changes
- Explain significant design decisions`,
MaxIterations: 50,
}
WriterPreset creates agents optimized for writing and editing files. Has full write access with a focused system prompt.
Functions ¶
This section is empty.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent represents an autonomous agent with its own tool access and config.
func New ¶
New creates a new root Agent with the given configuration. Panics if Registry or LLMClient is nil.
func (*Agent) ClearMessages ¶
func (a *Agent) ClearMessages()
ClearMessages resets the conversation history.
func (*Agent) Config ¶
Config returns a copy of the agent's configuration. The returned config is safe to inspect but should not be modified. Uses lazy initialization to avoid expensive deep copies on every call. Note: The cached config is computed once and never invalidated. Agent configuration is considered immutable after creation.
func (*Agent) Continue ¶
Continue appends the prompt to existing conversation history and runs the think-act loop. Use this for multi-turn conversations where the agent should remember previous exchanges. Use SetMessages() to restore history from persistence before calling Continue().
func (*Agent) ContinueAsync ¶
ContinueAsync continues the agent in the background and returns immediately. Similar to RunAsync but uses Continue() which preserves conversation history.
func (*Agent) RemoveAllChildren ¶
func (a *Agent) RemoveAllChildren()
RemoveAllChildren removes all child agents from this agent. This is useful for bulk cleanup operations.
func (*Agent) RemoveChild ¶
RemoveChild removes a specific child agent from the parent's children list. Returns true if the child was found and removed, false otherwise. This is useful for cleaning up terminated child agents.
func (*Agent) ResetUsage ¶
func (a *Agent) ResetUsage()
ResetUsage clears the token usage statistics.
func (*Agent) RestoreTranscript ¶
func (a *Agent) RestoreTranscript(t *Transcript) error
RestoreTranscript restores conversation history from a transcript. Returns an error if the transcript is for a different agent.
func (*Agent) Run ¶
Run executes the agent's think-act loop with the given prompt. Each call starts fresh with only the new prompt (no conversation history). Use Continue() for multi-turn conversations that preserve history.
func (*Agent) RunAsync ¶
RunAsync executes the agent in the background and returns immediately. The returned RunHandle can be used to check status, wait for completion, or cancel.
func (*Agent) RunChild ¶
RunChild runs a child agent with the given prompt and fires SubagentStop when complete. This is the recommended way to run child agents when you want lifecycle hooks. For direct control without hooks, call child.Run() directly.
func (*Agent) RunChildAsync ¶
RunChildAsync runs a child agent in the background, firing SubagentStop when complete. Combines SpawnChild semantics with async execution.
func (*Agent) SaveTranscript ¶
func (a *Agent) SaveTranscript() *Transcript
SaveTranscript saves the agent's current conversation history to a transcript.
func (*Agent) SetMessages ¶
SetMessages sets the conversation history. Use this to restore conversation state from persistence.
func (*Agent) SpawnChild ¶
SpawnChild creates a child agent with inherited configuration. Child tools are restricted to parent's allowed tools. Child denied tools accumulate (union of parent and child denied). Fires SubagentStart hook if a hook manager is configured.
func (*Agent) SpawnExplorer ¶
SpawnExplorer creates an explorer child agent with the given config overrides.
func (*Agent) SpawnPlanner ¶
SpawnPlanner creates a planner child agent with the given config overrides.
func (*Agent) SpawnResearcher ¶
SpawnResearcher creates a researcher child agent with the given config overrides.
func (*Agent) SpawnReviewer ¶
SpawnReviewer creates a reviewer child agent with the given config overrides.
func (*Agent) SpawnWriter ¶
SpawnWriter creates a writer child agent with the given config overrides.
func (*Agent) Subscribe ¶
func (a *Agent) Subscribe() <-chan orchestrator.Event
Subscribe returns a channel for receiving orchestrator events.
func (*Agent) Usage ¶
func (a *Agent) Usage() orchestrator.TokenUsage
Usage returns a snapshot of the current token usage statistics.
type Config ¶
type Config struct {
// Name identifies this agent (becomes part of hierarchical ID)
Name string
// AllowedTools lists tools this agent can use.
// Empty means inherit from parent or allow all (for root agents).
AllowedTools []string
// DeniedTools lists tools this agent cannot use.
// Takes precedence over AllowedTools.
DeniedTools []string
// Registry is the shared tool registry.
Registry *tool.Registry
// LLMClient is the LLM provider for this agent.
LLMClient llm.Client
// SystemPrompt is an optional custom system prompt.
SystemPrompt string
// ApprovalFunc is called when tools require approval.
ApprovalFunc tool.ApprovalFunc
// MaxIterations limits the think-act loop (0 = default).
MaxIterations int
// HookManager enables lifecycle hooks for this agent and its children.
// If set, fires SubagentStart/SubagentStop events when children are spawned.
HookManager *hooks.Manager
}
Config holds configuration for creating an Agent.
type Preset ¶
type Preset struct {
// Name is the default name for agents using this preset.
Name string
// SystemPrompt is the specialized system prompt for this agent type.
SystemPrompt string
// AllowedTools restricts the agent to these tools only.
// Empty means all tools are allowed.
AllowedTools []string
// DeniedTools prevents the agent from using these tools.
DeniedTools []string
// MaxIterations overrides the default iteration limit.
// 0 means use the default.
MaxIterations int
}
Preset represents a pre-configured agent template.
func (Preset) Apply ¶
Apply returns a new Config based on this preset with optional overrides. Base config values take precedence over preset defaults where specified.
func (Preset) WithAllowedTools ¶
WithAllowedTools returns a new preset with the specified allowed tools.
func (Preset) WithDeniedTools ¶
WithDeniedTools returns a new preset with the specified denied tools.
func (Preset) WithMaxIterations ¶
WithMaxIterations returns a new preset with the specified max iterations.
func (Preset) WithSystemPrompt ¶
WithSystemPrompt returns a new preset with the specified system prompt.
type RunHandle ¶
type RunHandle struct {
// contains filtered or unexported fields
}
RunHandle provides access to a background agent execution.
func (*RunHandle) Cancel ¶
Cancel attempts to cancel the running agent via context cancellation. This requires the original context to have been cancellable. Returns true if the agent was still running when cancel was called.
func (*RunHandle) Done ¶
func (h *RunHandle) Done() <-chan struct{}
Done returns a channel that closes when execution completes.
func (*RunHandle) Duration ¶
Duration returns how long the agent has been running (or ran for if complete).
func (*RunHandle) Err ¶
Err returns the error from execution, if any. Returns nil if still running or completed successfully.
func (*RunHandle) IsComplete ¶
IsComplete returns true if the agent has finished (success, failure, or cancelled).
func (*RunHandle) Poll ¶
Poll returns the current status and error without blocking. If the agent is still running, err will be nil.
type Transcript ¶
type Transcript struct {
AgentID string `json:"agent_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Entries []TranscriptEntry `json:"entries"`
}
Transcript holds conversation history that can be saved and restored.
func FromMessages ¶
func FromMessages(agentID string, messages []llm.Message) *Transcript
FromMessages creates a transcript from existing messages.
func LoadFromFile ¶
func LoadFromFile(path string) (*Transcript, error)
LoadFromFile reads a transcript from a file (JSON format).
func LoadFromFileJSONL ¶
func LoadFromFileJSONL(path string) (*Transcript, error)
LoadFromFileJSONL reads a transcript from a file (JSONL format).
func LoadJSON ¶
func LoadJSON(r io.Reader) (*Transcript, error)
LoadJSON reads a transcript from a JSON object.
func LoadJSONL ¶
func LoadJSONL(r io.Reader) (*Transcript, error)
LoadJSONL reads a transcript from JSONL format.
func NewTranscript ¶
func NewTranscript(agentID string) *Transcript
NewTranscript creates a new transcript for an agent.
func (*Transcript) Append ¶
func (t *Transcript) Append(msg llm.Message)
Append adds a message to the transcript.
func (*Transcript) Len ¶
func (t *Transcript) Len() int
Len returns the number of entries in the transcript.
func (*Transcript) SaveJSON ¶
func (t *Transcript) SaveJSON(w io.Writer) error
SaveJSON writes the transcript as a single JSON object.
func (*Transcript) SaveJSONL ¶
func (t *Transcript) SaveJSONL(w io.Writer) error
SaveJSONL writes the transcript in JSONL format (one entry per line). This format is better for streaming/appending.
func (*Transcript) SaveToFile ¶
func (t *Transcript) SaveToFile(path string) error
SaveToFile writes the transcript to a file (JSON format).
func (*Transcript) SaveToFileJSONL ¶
func (t *Transcript) SaveToFileJSONL(path string) error
SaveToFileJSONL writes the transcript to a file (JSONL format).
func (*Transcript) ToMessages ¶
func (t *Transcript) ToMessages() []llm.Message
ToMessages converts the transcript back to messages.
type TranscriptEntry ¶
type TranscriptEntry struct {
Timestamp time.Time `json:"timestamp"`
Role string `json:"role"`
Content []llm.ContentBlock `json:"content"`
}
TranscriptEntry represents a single entry in the transcript.