agent

package
v0.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 14 Imported by: 1

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

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidChildTools = errors.New("child cannot have tools parent doesn't have")
)
View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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

func New(cfg Config) *Agent

New creates a new root Agent with the given configuration. Panics if Registry or LLMClient is nil.

func (*Agent) Children

func (a *Agent) Children() []*Agent

Children returns the list of child agents.

func (*Agent) ClearMessages

func (a *Agent) ClearMessages()

ClearMessages resets the conversation history.

func (*Agent) Config

func (a *Agent) Config() 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

func (a *Agent) Continue(ctx context.Context, prompt string) error

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

func (a *Agent) ContinueAsync(ctx context.Context, prompt string) *RunHandle

ContinueAsync continues the agent in the background and returns immediately. Similar to RunAsync but uses Continue() which preserves conversation history.

func (*Agent) Executor

func (a *Agent) Executor() *tool.Executor

Executor returns the agent's tool executor.

func (*Agent) Hooks

func (a *Agent) Hooks() *hooks.Manager

Hooks returns the agent's hook manager, or nil if none was configured.

func (*Agent) ID

func (a *Agent) ID() string

ID returns the hierarchical agent ID.

func (*Agent) Messages

func (a *Agent) Messages() []llm.Message

Messages returns the current conversation history.

func (*Agent) Parent

func (a *Agent) Parent() *Agent

Parent returns the parent agent, or nil for root agents.

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

func (a *Agent) RemoveChild(child *Agent) bool

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

func (a *Agent) Run(ctx context.Context, prompt string) error

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

func (a *Agent) RunAsync(ctx context.Context, prompt string) *RunHandle

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

func (a *Agent) RunChild(ctx context.Context, child *Agent, prompt string) error

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

func (a *Agent) RunChildAsync(ctx context.Context, child *Agent, prompt string) *RunHandle

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

func (a *Agent) SetMessages(messages []llm.Message)

SetMessages sets the conversation history. Use this to restore conversation state from persistence.

func (*Agent) SpawnChild

func (a *Agent) SpawnChild(cfg Config) (*Agent, error)

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

func (a *Agent) SpawnExplorer(cfg Config) (*Agent, error)

SpawnExplorer creates an explorer child agent with the given config overrides.

func (*Agent) SpawnPlanner

func (a *Agent) SpawnPlanner(cfg Config) (*Agent, error)

SpawnPlanner creates a planner child agent with the given config overrides.

func (*Agent) SpawnResearcher

func (a *Agent) SpawnResearcher(cfg Config) (*Agent, error)

SpawnResearcher creates a researcher child agent with the given config overrides.

func (*Agent) SpawnReviewer

func (a *Agent) SpawnReviewer(cfg Config) (*Agent, error)

SpawnReviewer creates a reviewer child agent with the given config overrides.

func (*Agent) SpawnWriter

func (a *Agent) SpawnWriter(cfg Config) (*Agent, error)

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

func (p Preset) Apply(base Config) Config

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

func (p Preset) WithAllowedTools(tools ...string) Preset

WithAllowedTools returns a new preset with the specified allowed tools.

func (Preset) WithDeniedTools

func (p Preset) WithDeniedTools(tools ...string) Preset

WithDeniedTools returns a new preset with the specified denied tools.

func (Preset) WithMaxIterations

func (p Preset) WithMaxIterations(max int) Preset

WithMaxIterations returns a new preset with the specified max iterations.

func (Preset) WithName

func (p Preset) WithName(name string) Preset

WithName returns a new preset with the specified name.

func (Preset) WithSystemPrompt

func (p Preset) WithSystemPrompt(prompt string) Preset

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) Agent

func (h *RunHandle) Agent() *Agent

Agent returns the underlying agent.

func (*RunHandle) Cancel

func (h *RunHandle) Cancel() bool

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

func (h *RunHandle) Duration() time.Duration

Duration returns how long the agent has been running (or ran for if complete).

func (*RunHandle) Err

func (h *RunHandle) Err() error

Err returns the error from execution, if any. Returns nil if still running or completed successfully.

func (*RunHandle) IsComplete

func (h *RunHandle) IsComplete() bool

IsComplete returns true if the agent has finished (success, failure, or cancelled).

func (*RunHandle) Poll

func (h *RunHandle) Poll() (RunStatus, error)

Poll returns the current status and error without blocking. If the agent is still running, err will be nil.

func (*RunHandle) Status

func (h *RunHandle) Status() RunStatus

Status returns the current execution status.

func (*RunHandle) Wait

func (h *RunHandle) Wait() error

Wait blocks until execution completes and returns the error (if any).

func (*RunHandle) WaitWithTimeout

func (h *RunHandle) WaitWithTimeout(timeout time.Duration) error

WaitWithTimeout blocks until execution completes or timeout expires. Returns context.DeadlineExceeded if timeout is reached.

type RunStatus

type RunStatus int32

RunStatus represents the current state of an async agent run.

const (
	RunStatusPending RunStatus = iota
	RunStatusRunning
	RunStatusCompleted
	RunStatusFailed
	RunStatusCancelled
)

func (RunStatus) String

func (s RunStatus) String() string

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL