agent

package
v1.1.60 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AgentIDFromContext

func AgentIDFromContext(ctx context.Context) (agentpkg.AgentID, bool)

AgentIDFromContext extracts the agent ID from the context.

func BuildContextFilesContext

func BuildContextFilesContext(files []ContextFileInfo) string

BuildContextFilesContext builds context from loaded context files.

func BuildSkillsContext

func BuildSkillsContext(skills []SkillInfo) string

BuildSkillsContext builds context from loaded skills.

func BuildSubAgentContext

func BuildSubAgentContext() string

BuildSubAgentContext returns extra system context for sub-agents.

func BuildSystemPrompt

func BuildSystemPrompt(mode string, toolNames []string, cwd string, ruleContent string, extraContext string, toolSnippets map[string]string, toolGuidelines []string, multiAgent bool, delegateMode bool, workflows bool) string

BuildSystemPrompt constructs the system prompt based on mode and context. ruleContent is the content of .mothx/rule.md (project rules), inserted after the built-in sections but before extraContext (skills + context files like AGENTS.md).

func ChatParamsFromPublic

func ChatParamsFromPublic(p agentpkg.ChatParams) provider.ChatParams

ChatParamsFromPublic converts public ChatParams to internal.

func ChatParamsToPublic

func ChatParamsToPublic(p provider.ChatParams) agentpkg.ChatParams

ChatParamsToPublic converts internal ChatParams to public.

func ConsumeEvents

func ConsumeEvents(ctx context.Context, eventCh <-chan Event, handler EventHandler) error

ConsumeEvents forwards every event from eventCh to handler until the stream closes, the context is canceled, or the handler returns an error.

func ContentBlockFromPublic

func ContentBlockFromPublic(cb agentpkg.ContentBlock) provider.ContentBlock

ContentBlockFromPublic converts a public agent.ContentBlock to internal.

func ContentBlockToPublic

func ContentBlockToPublic(cb provider.ContentBlock) agentpkg.ContentBlock

ContentBlockToPublic converts an internal provider.ContentBlock to public.

func ContextUsageToPublic

func ContextUsageToPublic(u *ctxpkg.ContextUsage) *agentpkg.ContextUsage

ContextUsageToPublic converts internal context usage to public.

func ContextWithAgentID

func ContextWithAgentID(ctx context.Context, id agentpkg.AgentID) context.Context

ContextWithAgentID returns a new context with the agent ID attached.

func ContextWithEventChan

func ContextWithEventChan(ctx context.Context, ch chan<- Event) context.Context

ContextWithEventChan returns a new context with the event channel attached.

func ContextWithParentMode

func ContextWithParentMode(ctx context.Context, mode string) context.Context

ContextWithParentMode attaches the parent agent's execution mode to the context.

func ContextWithParentRunContext

func ContextWithParentRunContext(ctx context.Context, parent context.Context) context.Context

ContextWithParentRunContext attaches the parent agent run context to a tool context.

func EventChanFromContext

func EventChanFromContext(ctx context.Context) (chan<- Event, bool)

EventChanFromContext extracts the event channel from the context.

func EventToPublic

func EventToPublic(e Event) agentpkg.Event

EventToPublic converts an internal Event to a public agent.Event.

func FileDiffToPublic

func FileDiffToPublic(d *tools.FileDiff) *agentpkg.FileDiff

FileDiffToPublic converts an internal tools.FileDiff to public agent.FileDiff.

func ForwardChildAgentEvent

func ForwardChildAgentEvent(ctx context.Context, ch chan<- Event, childID agentpkg.AgentID, e agentpkg.Event) bool

ForwardChildAgentEvent forwards child-agent activity to the parent event stream so frontends can render background progress without mixing child output into the main transcript.

func MessageFromPublic

func MessageFromPublic(m agentpkg.Message) provider.Message

MessageFromPublic converts a public agent.Message to an internal provider.Message.

func MessageToPublic

func MessageToPublic(m provider.Message) agentpkg.Message

MessageToPublic converts an internal provider.Message to a public agent.Message.

func MessagesFromPublic

func MessagesFromPublic(msgs []agentpkg.Message) []provider.Message

MessagesFromPublic converts a slice of public messages to internal.

func MessagesToPublic

func MessagesToPublic(msgs []provider.Message) []agentpkg.Message

MessagesToPublic converts a slice of internal messages to public.

func ModelInfoToInternal

func ModelInfoToInternal(m agentpkg.ModelInfo) *provider.Model

ModelInfoToInternal converts a public ModelInfo to an internal *Model.

func ModelToPublic

func ModelToPublic(m *provider.Model) agentpkg.ModelInfo

ModelToPublic converts an internal *provider.Model to a public agent.ModelInfo.

func ParentModeFromContext

func ParentModeFromContext(ctx context.Context) (string, bool)

ParentModeFromContext extracts the parent agent's execution mode.

func ParentRunContextFromContext

func ParentRunContextFromContext(ctx context.Context) (context.Context, bool)

ParentRunContextFromContext extracts the parent agent run context.

func RegisterDelegateSubAgentTool

func RegisterDelegateSubAgentTool(registry *tools.Registry, manager *AgentManager)

RegisterDelegateSubAgentTool registers the blocking single sub-agent delegation tool. It is independent from the async multi-agent toolset.

func RegisterSubAgentTools

func RegisterSubAgentTools(registry *tools.Registry, manager *AgentManager)

RegisterSubAgentTools registers the built-in sub-agent tools when multi-agent mode is enabled. It is safe to call more than once; Registry.Register replaces existing tools without duplicating their order.

func ResolveMaxTokens

func ResolveMaxTokens(settings *config.Settings, model *provider.Model) int

ResolveMaxTokens returns the explicit global override when set, then a per-model maxTokens value only when it came from user/runtime config. A zero return means the caller/provider should omit the output-token limit when the upstream API permits it.

func ResolveMaxTokensValue

func ResolveMaxTokensValue(explicit int, model *provider.Model) int

ResolveMaxTokensValue returns an explicit per-request value when set; otherwise it leaves the output-token limit unset.

func StreamEventFromPublic

func StreamEventFromPublic(e agentpkg.StreamEvent) provider.StreamEvent

StreamEventFromPublic converts a public StreamEvent to internal.

func StreamEventToPublic

func StreamEventToPublic(e provider.StreamEvent) agentpkg.StreamEvent

StreamEventToPublic converts internal StreamEvent to public.

func TaskPlanToPublic

func TaskPlanToPublic(p *tools.TaskPlan) *agentpkg.TaskPlan

TaskPlanToPublic converts an internal tools.TaskPlan to public agent.TaskPlan.

func ToolCallBlockToPublic

func ToolCallBlockToPublic(tc *provider.ToolCallBlock) *agentpkg.ToolCallBlock

ToolCallBlockToPublic converts an internal provider.ToolCallBlock to public.

func UsageToPublic

func UsageToPublic(u *provider.Usage) *agentpkg.Usage

UsageToPublic converts an internal provider.Usage to public agent.Usage.

func WrapEventChan

func WrapEventChan(in <-chan Event) <-chan agentpkg.Event

WrapEventChan wraps an internal event channel into a public event channel.

Types

type AfterToolCallContext

type AfterToolCallContext struct {
	AssistantMessage provider.Message
	ToolCall         provider.ToolCallBlock
	Args             any
	Result           ToolCallResult
	IsError          bool
	Context          *AgentContext
}

AfterToolCallContext is passed to AfterToolCall.

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent is the core agent loop.

func New

func New(cfg Config, registry *tools.Registry) *Agent

New creates a new agent.

func NewWithLoopConfig

func NewWithLoopConfig(cfg AgentLoopConfig, registry *tools.Registry) *Agent

NewWithLoopConfig creates a new agent with custom loop configuration.

func (*Agent) Abort

func (a *Agent) Abort()

Abort signals the agent to stop processing. Satisfies both internal and public agent.Agent interface.

func (*Agent) AskQuestion

func (a *Agent) AskQuestion(ctx context.Context, question string, options []string, explanation string) string

AskQuestion implements the tools.QuestionAsker interface. It gets the event channel from the context and delegates to RequestQuestion.

func (*Agent) CanCompact

func (a *Agent) CanCompact() bool

CanCompact reports whether the current conversation has older messages that can be summarized while preserving the configured recent context.

func (*Agent) Compact

func (a *Agent) Compact(ctx context.Context, ch chan<- Event) error

Compact performs context compaction using Insert-then-Compress pattern (R4.1-R4.4). Uses the SAME system prompt and tools as the main conversation.

func (*Agent) GetContext

func (a *Agent) GetContext() *AgentContext

GetContext returns a copy of the current agent context.

func (*Agent) GetContextUsage

func (a *Agent) GetContextUsage() *ctxpkg.ContextUsage

GetContextUsage calculates and returns the current context usage.

func (*Agent) GetHistoryState

func (a *Agent) GetHistoryState() ([]provider.Message, []string)

GetHistoryState returns a copy of message history plus aligned session entry IDs.

func (*Agent) GetMessages

func (a *Agent) GetMessages() []provider.Message

GetMessages returns a copy of the current message history.

func (*Agent) HandleApprovalResponse

func (a *Agent) HandleApprovalResponse(approvalID string, approved bool)

HandleApprovalResponse processes the user's approval response.

func (*Agent) HandleQuestionResponse

func (a *Agent) HandleQuestionResponse(questionID string, answer string)

HandleQuestionResponse processes the user's answer to a question.

func (*Agent) ID

func (a *Agent) ID() agentpkg.AgentID

ID returns the agent's unique identifier.

func (*Agent) LoadHistoryMessages

func (a *Agent) LoadHistoryMessages(messages []provider.Message)

LoadHistoryMessages loads historical messages from session into agent context.

func (*Agent) LoadHistoryState

func (a *Agent) LoadHistoryState(messages []provider.Message, entryIDs []string)

LoadHistoryState loads historical messages plus their session entry IDs.

func (*Agent) NeedsApproval

func (a *Agent) NeedsApproval(toolName string, args map[string]any) bool

NeedsApproval checks if a tool call needs user approval based on the current mode.

func (*Agent) ParentID

func (a *Agent) ParentID() agentpkg.AgentID

ParentID returns the parent agent's ID, or empty if top-level.

func (*Agent) RequestApproval

func (a *Agent) RequestApproval(ch chan<- Event, toolName string, args map[string]any) bool

RequestApproval sends an approval request and waits for the user's response.

func (*Agent) RequestQuestion

func (a *Agent) RequestQuestion(ch chan<- Event, question string, options []string, context string) string

RequestQuestion sends a question request and waits for the user's answer.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, userMsg string) <-chan Event

Run processes a user message and streams events back.

func (*Agent) RunWithMessages

func (a *Agent) RunWithMessages(ctx context.Context, messages []provider.Message) <-chan Event

RunWithMessages processes with explicit message history.

func (*Agent) SetContext

func (a *Agent) SetContext(ctx *AgentContext)

SetContext replaces the agent context.

func (*Agent) SetForceCompact

func (a *Agent) SetForceCompact()

SetForceCompact marks the agent for forced compaction on the next turn. Called by /compact command in TUI and Gateway.

func (*Agent) SetMessages

func (a *Agent) SetMessages(msgs []provider.Message)

SetMessages replaces the message history.

func (*Agent) ShouldCompact

func (a *Agent) ShouldCompact() bool

ShouldCompact checks if compaction should trigger. Returns true if context exceeds the threshold OR if forced via SetForceCompact.

type AgentAdapter

type AgentAdapter struct {
	// contains filtered or unexported fields
}

AgentAdapter wraps an internal *Agent and satisfies the public agent.Agent interface.

func NewAgentAdapter

func NewAgentAdapter(a *Agent) *AgentAdapter

NewAgentAdapter creates an adapter that wraps an internal Agent.

func (*AgentAdapter) Abort

func (a *AgentAdapter) Abort()

func (*AgentAdapter) GetContext

func (a *AgentAdapter) GetContext() *agentpkg.AgentContext

func (*AgentAdapter) GetContextUsage

func (a *AgentAdapter) GetContextUsage() *agentpkg.ContextUsage

func (*AgentAdapter) GetMessages

func (a *AgentAdapter) GetMessages() []agentpkg.Message

func (*AgentAdapter) HandleApprovalResponse

func (a *AgentAdapter) HandleApprovalResponse(id string, approved bool)

func (*AgentAdapter) HandleQuestionResponse

func (a *AgentAdapter) HandleQuestionResponse(questionID string, answer string)

func (*AgentAdapter) ID

func (a *AgentAdapter) ID() agentpkg.AgentID

func (*AgentAdapter) LoadHistoryMessages

func (a *AgentAdapter) LoadHistoryMessages(msgs []agentpkg.Message)

func (*AgentAdapter) ParentID

func (a *AgentAdapter) ParentID() agentpkg.AgentID

func (*AgentAdapter) Run

func (a *AgentAdapter) Run(ctx context.Context, userMsg string) <-chan agentpkg.Event

func (*AgentAdapter) RunWithMessages

func (a *AgentAdapter) RunWithMessages(ctx context.Context, msgs []agentpkg.Message) <-chan agentpkg.Event

func (*AgentAdapter) SetContext

func (a *AgentAdapter) SetContext(ctx *agentpkg.AgentContext)

func (*AgentAdapter) SetMessages

func (a *AgentAdapter) SetMessages(msgs []agentpkg.Message)

type AgentContext

type AgentContext struct {
	SystemPrompt string
	Messages     []provider.Message
	Tools        []provider.ToolDefinition
}

AgentContext holds the current agent context.

type AgentFactory

type AgentFactory struct {
	// contains filtered or unexported fields
}

AgentFactory creates Agent instances with consistent configuration.

func NewAgentFactory

func NewAgentFactory(
	provider provider.Provider,
	model *provider.Model,
	settings *config.Settings,
	sandboxMgr *sandbox.Manager,
	extraContext string,
	ruleContent string,
	skillsMgr *skills.Manager,
	compactionSettings ctxpkg.CompactionSettings,
	approvalHandler func(toolCallID, toolName string, args map[string]any) bool,
) *AgentFactory

NewAgentFactory creates a factory with shared configuration.

func NewAgentFactoryWithOptions

func NewAgentFactoryWithOptions(
	provider provider.Provider,
	model *provider.Model,
	settings *config.Settings,
	sandboxMgr *sandbox.Manager,
	extraContext string,
	ruleContent string,
	skillsMgr *skills.Manager,
	compactionSettings ctxpkg.CompactionSettings,
	approvalHandler func(toolCallID, toolName string, args map[string]any) bool,
	opts AgentFactoryOptions,
) *AgentFactory

NewAgentFactoryWithOptions creates a factory with explicit behavior flags.

func (*AgentFactory) Create

func (f *AgentFactory) Create(opts AgentOptions) agentpkg.Agent

Create creates a new Agent with per-agent Registry. Each agent gets its own Registry (with its own workDir, sandbox, JobManager).

func (*AgentFactory) CreateFromPublicOptions

func (f *AgentFactory) CreateFromPublicOptions(b *agentpkg.Builder) agentpkg.Agent

CreateFromPublicOptions creates an agent from public Builder options.

func (*AgentFactory) Provider

func (f *AgentFactory) Provider() provider.Provider

Provider returns the factory's provider (for Builder integration).

func (*AgentFactory) Settings

func (f *AgentFactory) Settings() *config.Settings

Settings returns the factory's settings.

type AgentFactoryOptions

type AgentFactoryOptions struct {
	MultiAgentEnabled bool
	DelegateEnabled   bool
	WorkflowsEnabled  bool
	Allow             *config.AllowConfig
}

AgentFactoryOptions configures AgentFactory behavior.

type AgentLoopConfig

type AgentLoopConfig struct {
	Config

	// ToolExecutionMode determines how tool calls are executed.
	// "sequential": execute one by one
	// "parallel": execute concurrently (default)
	ToolExecutionMode string

	// MaxIterations is the safety limit for agent loop iterations.
	MaxIterations int

	// GetSteeringMessages returns messages to inject mid-run.
	GetSteeringMessages func() []provider.Message

	// GetFollowUpMessages returns messages to process after agent would stop.
	GetFollowUpMessages func() []provider.Message

	// ShouldStopAfterTurn is called after each turn to check if we should stop.
	ShouldStopAfterTurn func(ctx ShouldStopAfterTurnContext) bool

	// PrepareNextTurn is called before the next turn to update context/model.
	PrepareNextTurn func(ctx PrepareNextTurnContext) *TurnUpdate

	// BeforeToolCall is called before a tool is executed.
	BeforeToolCall func(ctx BeforeToolCallContext) *ToolCallBlockResult

	// AfterToolCall is called after a tool finishes executing.
	AfterToolCall func(ctx AfterToolCallContext) *ToolCallResult

	// ContextPressureThreshold is the context usage percentage (0-1) that triggers EventContextPressure.
	// 0 means disabled. Default: 0.55 (55%).
	ContextPressureThreshold float64

	// BudgetPressureThreshold is the remaining iteration ratio (0-1) that triggers EventBudgetPressure.
	// 0 means disabled. Default: 0.20 (remaining 20%).
	BudgetPressureThreshold float64

	// MaxConsecutiveNoText is the max tool-only turns before a stuck-detection warning.
	// 0 means default (95).
	MaxConsecutiveNoText int
}

AgentLoopConfig extends Config with loop-specific settings.

type AgentManager

type AgentManager struct {
	// contains filtered or unexported fields
}

AgentManager manages the lifecycle of all agent instances.

func NewAgentManager

func NewAgentManager(factory *AgentFactory) *AgentManager

NewAgentManager creates a new agent manager.

func (*AgentManager) Children

func (m *AgentManager) Children(id agentpkg.AgentID) []agentpkg.AgentID

Children returns the children of an agent.

func (*AgentManager) Count

func (m *AgentManager) Count() int

Count returns the number of active agents.

func (*AgentManager) Create

func (m *AgentManager) Create(opts AgentOptions) (agentpkg.Agent, error)

Create creates a new agent and registers it. If opts.ParentID is set, validates the parent exists and is a top-level agent.

func (*AgentManager) Destroy

func (m *AgentManager) Destroy(id agentpkg.AgentID) error

Destroy stops and removes an agent and all its children.

func (*AgentManager) Finish

func (m *AgentManager) Finish(id agentpkg.AgentID, cause error)

Finish unregisters a completed top-level agent and cancels any remaining children. Child statuses are retained so callers can inspect why a delegated task stopped. Finish must not abort the completed agent itself: interactive frontends may keep the same agent instance for the next turn, and Abort is a one-way signal.

func (*AgentManager) Get

Get returns an agent by ID.

func (*AgentManager) List

func (m *AgentManager) List() []agentpkg.AgentID

List returns all agent IDs.

func (*AgentManager) MarkDone

func (m *AgentManager) MarkDone(id agentpkg.AgentID, result string)

MarkDone records successful completion and the last reported result.

func (*AgentManager) MarkError

func (m *AgentManager) MarkError(id agentpkg.AgentID, err error)

MarkError records an agent failure.

func (*AgentManager) MarkRunning

func (m *AgentManager) MarkRunning(id agentpkg.AgentID)

MarkRunning records that an agent has started processing a task.

func (*AgentManager) Parent

func (m *AgentManager) Parent(id agentpkg.AgentID) (agentpkg.AgentID, bool)

Parent returns the parent ID of an agent.

func (*AgentManager) Register

func (m *AgentManager) Register(a agentpkg.Agent)

Register adds an already-created top-level agent to the manager.

func (*AgentManager) SetCancel

func (m *AgentManager) SetCancel(id agentpkg.AgentID, cancel context.CancelFunc)

SetCancel records the active run cancel function for an agent.

func (*AgentManager) Status

Status returns a copy of the tracked status for an agent.

type AgentOptions

type AgentOptions struct {
	ID                agentpkg.AgentID
	ParentID          agentpkg.AgentID
	Mode              string
	Model             *provider.Model
	WorkDir           string
	Tools             []string // optional: tool filter
	SystemPromptExtra string   // extra context for this agent
	MaxIterations     int
	ToolExecutionMode string
	Session           *session.Manager
	ApprovalHandler   func(toolCallID, toolName string, args map[string]any) bool // per-agent approval override
	MultiAgent        *bool                                                       // optional prompt override
	DelegateMode      *bool                                                       // optional prompt override
	Workflows         *bool                                                       // optional prompt override
}

AgentOptions specifies per-agent overrides.

type BaseProvider

type BaseProvider struct {
	// contains filtered or unexported fields
}

BaseProvider provides common functionality for provider implementations.

func NewBaseProvider

func NewBaseProvider(name string, models []*provider.Model) BaseProvider

NewBaseProvider creates a new BaseProvider.

func (*BaseProvider) GetModel

func (p *BaseProvider) GetModel(id string) *provider.Model

GetModel returns a model by ID, or nil if not found.

func (*BaseProvider) Models

func (p *BaseProvider) Models() []*provider.Model

Models returns the list of available models.

func (*BaseProvider) Name

func (p *BaseProvider) Name() string

Name returns the provider's name.

type BeforeToolCallContext

type BeforeToolCallContext struct {
	AssistantMessage provider.Message
	ToolCall         provider.ToolCallBlock
	Args             any
	Context          *AgentContext
}

BeforeToolCallContext is passed to BeforeToolCall.

type ChatParams

type ChatParams struct {
	Messages      []provider.Message
	Tools         []provider.ToolDefinition
	SystemPrompt  string
	ThinkingLevel provider.ThinkingLevel
	MaxTokens     int
	ModelID       string
	Abort         chan struct{}
}

ChatParams holds parameters for a chat request.

type Config

type Config struct {
	ID                 agentpkg.AgentID
	ParentID           agentpkg.AgentID
	Provider           provider.Provider
	Vendor             string // user-configured provider/vendor name (e.g. "longcat", "openai")
	Model              *provider.Model
	Mode               string // "plan", "agent", "yolo"
	ThinkingLevel      provider.ThinkingLevel
	MaxTokens          int
	SandboxMgr         *sandbox.Manager
	Settings           *config.Settings
	Allow              *config.AllowConfig // auto-approval (allow.json): autoEdit, editPaths, bash rules
	Session            *session.Manager
	ExtraContext       string // extra context from files and skills
	RuleContent        string // content of .mothx/rule.md (project rules)
	CompactionSettings ctxpkg.CompactionSettings
	ApprovalHandler    func(toolCallID, toolName string, args map[string]any) bool
	MultiAgent         bool // Decision 8: multi-agent mode
	DelegateMode       bool // blocking single sub-agent delegation mode
	Workflows          bool // dynamic workflow orchestration mode
}

Config holds the agent configuration.

type ContextFileInfo

type ContextFileInfo struct {
	Name    string
	Path    string
	Scope   string // "global", "parent", "project"
	Content string
}

ContextFileInfo represents information about a context file.

type DelegateSubAgentTool

type DelegateSubAgentTool struct {
	// contains filtered or unexported fields
}

DelegateSubAgentTool runs exactly one delegated sub-agent task synchronously.

func NewDelegateSubAgentTool

func NewDelegateSubAgentTool(m *AgentManager) *DelegateSubAgentTool

NewDelegateSubAgentTool creates a blocking delegate_subagent tool.

func (*DelegateSubAgentTool) Description

func (t *DelegateSubAgentTool) Description() string

func (*DelegateSubAgentTool) Execute

func (t *DelegateSubAgentTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)

func (*DelegateSubAgentTool) Name

func (t *DelegateSubAgentTool) Name() string

func (*DelegateSubAgentTool) Parameters

func (t *DelegateSubAgentTool) Parameters() json.RawMessage

func (*DelegateSubAgentTool) PromptGuidelines

func (t *DelegateSubAgentTool) PromptGuidelines() []string

func (*DelegateSubAgentTool) PromptSnippet

func (t *DelegateSubAgentTool) PromptSnippet() string

type Event

type Event struct {
	Type    EventType
	AgentID agentpkg.AgentID

	// Agent lifecycle
	Messages []provider.Message

	// Turn lifecycle
	TurnMessage     provider.Message
	TurnToolResults []provider.Message

	// Message lifecycle
	Message provider.Message

	// Stream events
	TextDelta  string
	ThinkDelta string

	// Tool events
	ToolCall      *provider.ToolCallBlock
	ToolCallID    string
	ToolName      string
	ToolArgs      map[string]any
	ToolResult    string
	ToolDiff      *tools.FileDiff
	ToolError     error
	PartialResult any

	// Plan events
	Plan *tools.TaskPlan

	// Approval events
	ApprovalID     string         // Unique ID for approval request
	ApprovalTool   string         // Tool name requiring approval
	ApprovalArgs   map[string]any // Tool arguments
	ApprovalResult bool           // true = approved, false = denied

	// Question events
	QuestionID      string   // Unique ID for question request
	QuestionText    string   // The question to display
	QuestionOptions []string // Predefined options (last one is always "Custom input")
	QuestionContext string   // Optional context/explanation
	QuestionAnswer  string   // User's answer (set in response)

	// Status
	StatusMessage string

	// Completion
	Done       bool
	StopReason string
	Error      error

	// Usage
	Usage *provider.Usage

	// Context usage
	ContextUsage *ctxpkg.ContextUsage

	// Pressure info (for EventContextPressure / EventBudgetPressure)
	PressureMessage string  // Human-readable warning message
	PressureType    string  // "context" or "budget"
	PressurePercent float64 // Usage percentage that triggered the event
}

Event represents an event from the agent to the UI.

type EventHandler

type EventHandler interface {
	HandleAgentEvent(context.Context, Event) error
}

EventHandler receives agent events from a running request.

type EventHandlerFunc

type EventHandlerFunc func(context.Context, Event) error

EventHandlerFunc adapts a function to EventHandler.

func (EventHandlerFunc) HandleAgentEvent

func (f EventHandlerFunc) HandleAgentEvent(ctx context.Context, event Event) error

HandleAgentEvent implements EventHandler.

type EventRouter

type EventRouter struct {
	// contains filtered or unexported fields
}

EventRouter routes events from agents to consumers (UI, parent agents).

func NewEventRouter

func NewEventRouter() *EventRouter

NewEventRouter creates a new event router.

func (*EventRouter) Dispatch

func (r *EventRouter) Dispatch(event agentpkg.Event) error

Dispatch sends an event to the appropriate handlers. Returns the first error from any handler, or nil.

func (*EventRouter) GlobalHandlerCount

func (r *EventRouter) GlobalHandlerCount() int

GlobalHandlerCount returns the number of global handlers (for testing).

func (*EventRouter) HandlerCount

func (r *EventRouter) HandlerCount(id agentpkg.AgentID) int

HandlerCount returns the number of handlers for a given agent (for testing).

func (*EventRouter) RegisterAgent

func (r *EventRouter) RegisterAgent(id agentpkg.AgentID, handler RouterEventHandler)

RegisterAgent registers an event handler for a specific agent.

func (*EventRouter) RegisterGlobal

func (r *EventRouter) RegisterGlobal(handler RouterEventHandler)

RegisterGlobal registers a handler that receives events from all agents.

func (*EventRouter) UnregisterAgent

func (r *EventRouter) UnregisterAgent(id agentpkg.AgentID)

UnregisterAgent removes all handlers for a specific agent.

type EventType

type EventType int

EventType identifies the type of agent event.

const (
	// Agent lifecycle events
	EventAgentStart EventType = iota
	EventAgentEnd

	// Turn lifecycle events (a turn = one assistant response + tool calls/results)
	EventTurnStart
	EventTurnEnd

	// Message lifecycle events
	EventMessageStart
	EventMessageUpdate
	EventMessageEnd

	// Streaming events
	EventTextDelta
	EventThinkDelta

	// Tool execution events
	EventToolCall
	EventToolExecutionStart
	EventToolExecutionUpdate
	EventToolExecutionEnd
	EventToolResult
	EventToolApprovalRequest  // Request user approval for tool execution
	EventToolApprovalResponse // User response to approval request
	EventQuestionRequest      // Ask user a multiple-choice question
	EventQuestionResponse     // User response to question
	EventPlanUpdate           // Structured task plan update

	// Status events
	EventStatus
	EventDone
	EventError
	EventUsage

	// Compaction events
	EventCompactionStart
	EventCompactionEnd

	// Pressure events
	EventContextPressure // Context usage exceeded threshold (one-shot)
	EventBudgetPressure  // Remaining iterations below threshold (one-shot)
)

type ManagedAgentStatus

type ManagedAgentStatus struct {
	ID        agentpkg.AgentID
	ParentID  agentpkg.AgentID
	State     string
	Result    string
	Error     string
	StartedAt time.Time
	UpdatedAt time.Time
}

ManagedAgentStatus captures scheduling state for an agent managed by AgentManager.

type Model

type Model struct {
	ID            string
	Name          string
	Provider      string
	Reasoning     bool
	Input         []string
	Cost          ModelPricing
	ContextWindow int
	MaxTokens     int
}

Model represents a model configuration.

type ModelPricing

type ModelPricing struct {
	Input      float64
	Output     float64
	CacheRead  float64
	CacheWrite float64
}

ModelPricing represents the pricing for a model.

type PrepareNextTurnContext

type PrepareNextTurnContext struct {
	ShouldStopAfterTurnContext
}

PrepareNextTurnContext is passed to PrepareNextTurn.

type Provider

type Provider interface {
	// Chat sends a chat request and returns a channel of streaming events.
	Chat(ctx context.Context, params ChatParams) <-chan StreamEvent

	// Name returns the provider's name (e.g. "openai", "anthropic").
	Name() string

	// Models returns the list of available models.
	Models() []*provider.Model

	// GetModel returns a model by ID, or nil if not found.
	GetModel(id string) *provider.Model
}

Provider is the interface that all LLM providers must implement.

type ProviderAdapter

type ProviderAdapter struct {
	provider.BaseProvider
	// contains filtered or unexported fields
}

ProviderAdapter wraps a public agent.Provider to satisfy the internal provider.Provider interface. This enables the public Builder to supply an external Provider implementation.

func NewProviderAdapter

func NewProviderAdapter(pub agentpkg.Provider) *ProviderAdapter

NewProviderAdapter creates an internal Provider from a public one.

func (*ProviderAdapter) API

func (pa *ProviderAdapter) API() string

API returns the protocol/API type. The public provider interface does not expose API type, so we default to "openai-chat" which is the de-facto standard protocol.

func (*ProviderAdapter) Chat

func (pa *ProviderAdapter) Chat(ctx context.Context, params provider.ChatParams) <-chan provider.StreamEvent

Chat delegates to the public provider, converting between public and internal types.

type PublicProviderAdapter

type PublicProviderAdapter struct {
	// contains filtered or unexported fields
}

PublicProviderAdapter wraps an internal provider.Provider to satisfy the public agentpkg.Provider interface.

func NewPublicProviderAdapter

func NewPublicProviderAdapter(inner provider.Provider) *PublicProviderAdapter

NewPublicProviderAdapter creates a public Provider from an internal one.

func (*PublicProviderAdapter) Chat

func (*PublicProviderAdapter) GetModel

func (pa *PublicProviderAdapter) GetModel(id string) *agentpkg.ModelInfo

func (*PublicProviderAdapter) Models

func (pa *PublicProviderAdapter) Models() []agentpkg.ModelInfo

func (*PublicProviderAdapter) Name

func (pa *PublicProviderAdapter) Name() string

type RouterEventHandler

type RouterEventHandler interface {
	HandleRouterEvent(event agentpkg.Event) error
}

RouterEventHandler receives agent events for routing purposes.

type RouterEventHandlerFunc

type RouterEventHandlerFunc func(event agentpkg.Event) error

RouterEventHandlerFunc adapts a function to RouterEventHandler.

func (RouterEventHandlerFunc) HandleRouterEvent

func (f RouterEventHandlerFunc) HandleRouterEvent(event agentpkg.Event) error

HandleRouterEvent implements RouterEventHandler.

type ShouldStopAfterTurnContext

type ShouldStopAfterTurnContext struct {
	Message     provider.Message
	ToolResults []provider.Message
	Context     *AgentContext
	NewMessages []provider.Message
}

ShouldStopAfterTurnContext is passed to ShouldStopAfterTurn.

type SkillInfo

type SkillInfo struct {
	Name        string
	Description string
	Path        string
}

SkillInfo represents information about a skill.

type StreamEvent

type StreamEvent struct {
	Type       StreamEventType
	TextDelta  string
	ThinkDelta string
	ToolCall   *provider.ToolCallBlock
	Usage      *provider.Usage
	StopReason string
	Error      error
}

StreamEvent represents an event from the LLM stream.

type StreamEventType

type StreamEventType int

StreamEventType identifies the type of stream event.

const (
	StreamStart StreamEventType = iota
	StreamTextDelta
	StreamThinkDelta
	StreamToolCall
	StreamUsage
	StreamDone
	StreamError
)

type SubAgentDestroyTool

type SubAgentDestroyTool struct {
	// contains filtered or unexported fields
}

SubAgentDestroyTool destroys a sub-agent and releases resources.

func NewSubAgentDestroyTool

func NewSubAgentDestroyTool(m *AgentManager) *SubAgentDestroyTool

func (*SubAgentDestroyTool) Description

func (t *SubAgentDestroyTool) Description() string

func (*SubAgentDestroyTool) Execute

func (t *SubAgentDestroyTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)

func (*SubAgentDestroyTool) Name

func (t *SubAgentDestroyTool) Name() string

func (*SubAgentDestroyTool) Parameters

func (t *SubAgentDestroyTool) Parameters() json.RawMessage

func (*SubAgentDestroyTool) PromptGuidelines

func (t *SubAgentDestroyTool) PromptGuidelines() []string

func (*SubAgentDestroyTool) PromptSnippet

func (t *SubAgentDestroyTool) PromptSnippet() string

type SubAgentPolicy

type SubAgentPolicy struct {
	MaxChildren     int           // Maximum number of sub-agents (default 5)
	AllowedModes    []string      // Allowed modes for sub-agents (default ["plan", "agent", "yolo"])
	InheritSandbox  bool          // Inherit parent's sandbox (default true)
	TimeoutPerAgent time.Duration // Per-agent timeout (default 10min)
	TotalTimeout    time.Duration // Total timeout for all sub-agents (default 30min)
}

SubAgentPolicy defines security constraints for sub-agents.

func DefaultSubAgentPolicy

func DefaultSubAgentPolicy() SubAgentPolicy

DefaultSubAgentPolicy returns the default policy.

func (*SubAgentPolicy) Validate

func (p *SubAgentPolicy) Validate(parentID string, mode string, currentChildCount int) error

Validate checks if a sub-agent creation request is allowed.

type SubAgentSendTool

type SubAgentSendTool struct {
	// contains filtered or unexported fields
}

SubAgentSendTool sends a follow-up message to a running sub-agent.

func NewSubAgentSendTool

func NewSubAgentSendTool(m *AgentManager) *SubAgentSendTool

func (*SubAgentSendTool) Description

func (t *SubAgentSendTool) Description() string

func (*SubAgentSendTool) Execute

func (t *SubAgentSendTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)

func (*SubAgentSendTool) Name

func (t *SubAgentSendTool) Name() string

func (*SubAgentSendTool) Parameters

func (t *SubAgentSendTool) Parameters() json.RawMessage

func (*SubAgentSendTool) PromptGuidelines

func (t *SubAgentSendTool) PromptGuidelines() []string

func (*SubAgentSendTool) PromptSnippet

func (t *SubAgentSendTool) PromptSnippet() string

type SubAgentSpawnTool

type SubAgentSpawnTool struct {
	// contains filtered or unexported fields
}

SubAgentSpawnTool creates and starts a sub-agent.

func NewSubAgentSpawnTool

func NewSubAgentSpawnTool(m *AgentManager) *SubAgentSpawnTool

NewSubAgentSpawnTool creates a new subagent_spawn tool.

func (*SubAgentSpawnTool) Description

func (t *SubAgentSpawnTool) Description() string

func (*SubAgentSpawnTool) Execute

func (t *SubAgentSpawnTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)

func (*SubAgentSpawnTool) Name

func (t *SubAgentSpawnTool) Name() string

func (*SubAgentSpawnTool) Parameters

func (t *SubAgentSpawnTool) Parameters() json.RawMessage

func (*SubAgentSpawnTool) PromptGuidelines

func (t *SubAgentSpawnTool) PromptGuidelines() []string

func (*SubAgentSpawnTool) PromptSnippet

func (t *SubAgentSpawnTool) PromptSnippet() string

type SubAgentStatusTool

type SubAgentStatusTool struct {
	// contains filtered or unexported fields
}

SubAgentStatusTool queries sub-agent status and results.

func NewSubAgentStatusTool

func NewSubAgentStatusTool(m *AgentManager) *SubAgentStatusTool

func (*SubAgentStatusTool) Description

func (t *SubAgentStatusTool) Description() string

func (*SubAgentStatusTool) Execute

func (t *SubAgentStatusTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)

func (*SubAgentStatusTool) Name

func (t *SubAgentStatusTool) Name() string

func (*SubAgentStatusTool) Parameters

func (t *SubAgentStatusTool) Parameters() json.RawMessage

func (*SubAgentStatusTool) PromptGuidelines

func (t *SubAgentStatusTool) PromptGuidelines() []string

func (*SubAgentStatusTool) PromptSnippet

func (t *SubAgentStatusTool) PromptSnippet() string

type ThinkingLevel

type ThinkingLevel string

ThinkingLevel represents the thinking/reasoning level.

const (
	ThinkingOff     ThinkingLevel = "off"
	ThinkingMinimal ThinkingLevel = "minimal"
	ThinkingLow     ThinkingLevel = "low"
	ThinkingMedium  ThinkingLevel = "medium"
	ThinkingHigh    ThinkingLevel = "high"
	ThinkingXHigh   ThinkingLevel = "xhigh"
)

type ToolCallBlockResult

type ToolCallBlockResult struct {
	Block  bool
	Reason string
}

ToolCallBlockResult is returned from BeforeToolCall.

type ToolCallResult

type ToolCallResult struct {
	Content   string
	IsError   bool
	Terminate bool
}

ToolCallResult represents the result of a tool call.

type TurnUpdate

type TurnUpdate struct {
	Context       *AgentContext
	Model         *provider.Model
	ThinkingLevel provider.ThinkingLevel
}

TurnUpdate is returned from PrepareNextTurn.

Jump to

Keyboard shortcuts

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