agent

package
v1.2.96 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 23 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 AttachmentsFromPublic added in v1.1.77

func AttachmentsFromPublic(items []agentpkg.Attachment) []provider.Attachment

func AttachmentsToPublic added in v1.1.77

func AttachmentsToPublic(items []provider.Attachment) []agentpkg.Attachment

func BoundedParallel added in v1.2.87

func BoundedParallel[T any, R any](max int, items []T, fn func(T) R) []R

BoundedParallel applies fn to every item with at most max concurrent workers. Results retain the input order even when calls finish out of order. A non-positive max uses the product default. The helper always drains every item so callers can preserve one result per provider tool call.

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 BuildSystemPromptWithOptions added in v1.2.87

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

BuildSystemPromptWithOptions constructs the system prompt and includes the resolved local tool execution policy.

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 CompactionSettingsFromConfig added in v1.1.77

func CompactionSettingsFromConfig(c config.CompactionSettings) ctxpkg.CompactionSettings

CompactionSettingsFromConfig converts the user-facing settings.json compaction block into the agent-loop compaction settings. All runtimes (CLI, TUI, serve API, channels, ACP, A2A) must build agent compaction settings through this helper so no field is dropped. Zero-valued limits are filled later by NormalizeCompactionSettings inside New and NewWithLoopConfig.

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 EventTypeToPublic added in v1.2.83

func EventTypeToPublic(t EventType) agentpkg.EventType

EventTypeToPublic converts the internal event enum to the public enum. The enums intentionally retain their historical ordering, so this must not be a numeric cast: EventRetry was added in different positions.

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(model *provider.Model) int

ResolveMaxTokens returns the output limit configured for the active model. Known models use a conservative default cap; explicit model configuration is preserved exactly so an explicit value never gets silently changed.

func ResolveMaxTokensValue

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

ResolveMaxTokensValue returns an explicit per-request value when set. An explicit zero on a model disables the output-token parameter; otherwise the configured model limit is used.

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) BuildBackgroundChatParams added in v1.1.77

func (a *Agent) BuildBackgroundChatParams(localTurnID string, msg provider.Message) (provider.ChatParams, error)

BuildBackgroundChatParams creates one durable Responses background request without entering the Agent loop. The caller owns the remote response lifecycle and must not use this as a substitute for RunWithUserMessage.

func (*Agent) BuildBackgroundContinuationParams added in v1.1.77

func (a *Agent) BuildBackgroundContinuationParams(localTurnID string) (provider.ChatParams, error)

BuildBackgroundContinuationParams builds a durable Responses continuation request from already-loaded local history. It does not append a synthetic user message, which is important when a process resumes a remote run.

func (*Agent) BuildBackgroundReplayParams added in v1.1.78

func (a *Agent) BuildBackgroundReplayParams(localTurnID string) (provider.ChatParams, error)

BuildBackgroundReplayParams builds a background request from the local Responses archive, explicitly dropping remote lineage. It is used when a continuation proves that the remote response/conversation state is no longer available.

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) CompactForced added in v1.1.62

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

CompactForced performs explicit user-requested compaction. It skips preflight compactability checks and allows summary-only checkpoints.

func (*Agent) ExecuteBackgroundToolCall added in v1.1.77

func (a *Agent) ExecuteBackgroundToolCall(ctx context.Context, tc provider.ToolCallBlock, localTurnID string) <-chan Event

ExecuteBackgroundToolCall runs one local function tool through the same approval, sandbox and execution-record path as the normal agent loop. The returned event stream is owned by the caller, which may publish approval and progress events while waiting for the result.

func (*Agent) ExecuteBackgroundToolCallRecovering added in v1.1.78

func (a *Agent) ExecuteBackgroundToolCallRecovering(ctx context.Context, tc provider.ToolCallBlock, localTurnID string) <-chan Event

ExecuteBackgroundToolCallRecovering reopens only known read-only tool records left in an interrupted state. Side-effecting records stay guarded by the normal idempotency path and are never retried automatically.

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) MaxToolConcurrency added in v1.2.87

func (a *Agent) MaxToolConcurrency() int

MaxToolConcurrency returns the normalized per-batch local tool limit.

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(ctx context.Context, ch chan<- Event, question string, options []string, context string) string

RequestQuestion sends a question request and waits for the user's answer. It returns an empty string when the agent is aborted or the context is canceled, so unattended runtimes (e.g. channel sessions) never block a run forever on an answer that cannot arrive.

func (*Agent) RequestToolApproval added in v1.1.77

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

RequestToolApproval sends an approval request that retains the provider call identity, allowing a durable server runtime to match a decision after recovery without confusing concurrent function calls.

func (*Agent) ResponsesStateFallbackError added in v1.1.78

func (a *Agent) ResponsesStateFallbackError(err error) bool

ResponsesStateFallbackError delegates remote state classification to the configured provider without exposing provider-specific types to callers.

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) RunWithLoadedHistory added in v1.2.83

func (a *Agent) RunWithLoadedHistory(ctx context.Context) <-chan Event

RunWithLoadedHistory continues an Agent after the shared Runtime has loaded a persisted session history. It deliberately does not append another user message, which is required for a linked retry of an already-accepted intent.

func (*Agent) RunWithMessages

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

RunWithMessages processes with explicit message history.

func (*Agent) RunWithUserMessage added in v1.1.61

func (a *Agent) RunWithUserMessage(ctx context.Context, msg provider.Message) <-chan Event

RunWithUserMessage processes an already-built user message and streams events back.

func (*Agent) SetContext

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

SetContext replaces the agent context.

func (*Agent) SetConversationTurn added in v1.2.92

func (a *Agent) SetConversationTurn(turnID, intentID, runID string)

SetConversationTurn binds a reusable Agent instance to the durable Run it is about to execute. TUI keeps one Agent across prompts, while other adapters usually provide these values at construction time.

func (*Agent) SetForceCompact

func (a *Agent) SetForceCompact()

SetForceCompact marks the agent for forced compaction on the next turn.

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
	ProviderName             string
	Allow                    *config.AllowConfig
	BeforeToolCall           func(ctx BeforeToolCallContext) *ToolCallBlockResult
	BeforeToolExecute        func(ctx BeforeToolExecuteContext) *ToolCallBlockResult
	ForcedMode               string
	ResolveMode              func(manager *session.Manager, requestedMode string) (string, error)
	BeforeToolCallForSession func(manager *session.Manager) func(ctx BeforeToolCallContext) *ToolCallBlockResult
}

AgentFactoryOptions configures AgentFactory behavior.

type AgentLoopConfig

type AgentLoopConfig struct {
	Config

	// ForcedMode is an already-resolved Runtime invariant inherited by managed
	// children. Agent Core does not interpret its source.
	ForcedMode string

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

	// MaxToolConcurrency bounds the number of local tool calls that may be in
	// flight for one tool-call batch. Non-positive values use the shared
	// default from config.
	MaxToolConcurrency int

	// 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

	// BeforeToolExecute is called after approval and durable execution claim,
	// immediately before the tool receives its context. Runtime uses this late
	// fence to revalidate cross-process execution ownership.
	BeforeToolExecute func(ctx BeforeToolExecuteContext) *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) AddStatusListener added in v1.1.79

func (m *AgentManager) AddStatusListener(l AgentStatusListener)

AddStatusListener registers a listener for terminal lifecycle transitions (an agent entering the done or error state). Parent event streams can close before an asynchronously spawned child finishes, so observers that need reliable terminal states must subscribe here instead of relying on forwarded stream events alone.

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) DetachChild added in v1.1.61

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

DetachChild removes a child from its parent's active child list while retaining the child agent, parent link, and status for later inspection.

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) HasRunning added in v1.1.61

func (m *AgentManager) HasRunning() bool

HasRunning reports whether any managed agent is currently executing or ready to execute work. Completed retained agents are history, not active blockers.

func (*AgentManager) List

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

List returns all agent IDs.

func (*AgentManager) MarkCanceled added in v1.1.82

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

MarkCanceled records that an agent's run was canceled (user abort, timeout, or context cancellation). Canceled is a terminal state distinct from error.

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) MarkIncomplete added in v1.1.82

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

MarkIncomplete records that an agent stopped before completing its objective.

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.

func (*AgentManager) Statuses added in v1.1.61

func (m *AgentManager) Statuses() []ManagedAgentStatus

Statuses returns a sorted copy of all tracked agent statuses.

func (*AgentManager) UpdateRuntimeConfig added in v1.1.62

func (m *AgentManager) UpdateRuntimeConfig(p provider.Provider, providerName string, model *provider.Model, settings *config.Settings, allow *config.AllowConfig)

UpdateRuntimeConfig updates the factory used for future agents while keeping existing managed agents untouched.

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
	MaxToolConcurrency int
	Session            *session.Manager
	IsSubAgent         bool                                                        // persist this agent outside the user-continuable session tables
	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 AgentStatusListener added in v1.1.79

type AgentStatusListener func(ManagedAgentStatus)

AgentStatusListener observes lifecycle transitions of managed agents. It is invoked after the manager lock is released, so listeners may call back into the manager (Parent, Status, ...) safely.

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 BeforeToolExecuteContext added in v1.2.96

type BeforeToolExecuteContext struct {
	ToolCall         provider.ToolCallBlock
	Args             any
	Context          *AgentContext
	ExecutionContext context.Context
	RunID            string
	ExecutionKey     string
	SideEffecting    bool
}

BeforeToolExecuteContext is passed to BeforeToolExecute after any approval wait and durable idempotency claim have completed.

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", "os"
	ThinkingLevel      provider.ThinkingLevel
	MaxTokens          int
	MaxTokensUserSet   bool
	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
	// ApprovalDecisionLookup supplies a durable decision for a previously
	// requested tool approval. It is used by recovery paths before creating a
	// new interactive approval request.
	ApprovalDecisionLookup func(toolCallID, toolName string, args map[string]any) (approved bool, found bool)
	MultiAgent             bool // Decision 8: multi-agent mode
	DelegateMode           bool // blocking single sub-agent delegation mode
	Workflows              bool // dynamic workflow orchestration mode
	ConversationTurnID     string
	IntentID               string
	RunID                  string
	ConversationTurn       bool
	RuntimeOwnsTurnEnd     bool
	RuntimeOwnsUserEntry   bool
	UserEntryID            string
}

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
	HostedItem *provider.HostedItem

	// Tool events
	ToolCall           *provider.ToolCallBlock
	ToolCallID         string
	ToolName           string
	ToolArgs           map[string]any
	ToolResult         string
	ToolDiff           *tools.FileDiff
	ToolError          error
	ToolExecutionState string
	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
	ResponseStateFailureClass string // expired, permission, request_failed
	// RetryStatus marks an EventStatus compatibility projection for the
	// following EventRetry. New adapters should consume EventRetry and ignore
	// this marked status to avoid rendering retry progress twice.
	RetryStatus bool

	// Retry information for automatic provider and turn recovery.
	RetryAttempt     int
	RetryMaxAttempts int
	RetryAfterMS     int
	RetryMaxTokens   int
	RetryReason      string
	RetryContinue    bool

	// Completion
	Done       bool
	StopReason string
	Error      error
	// Assistant fields identify the final transcript entry staged for a
	// Runtime-owned terminal transaction. They are populated only on the
	// canonical EventRunFinished event.
	AssistantEntryID string
	AssistantMessage provider.Message
	// Status is the canonical terminal outcome, set on EventRunFinished.
	Status TaskStatus

	// Usage
	Usage *provider.Usage

	// Attachments are provider-neutral citations, files, images, and artifacts
	// produced by the completed turn.
	Attachments []provider.Attachment

	// 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
	EventHostedItem

	// 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
	EventRetry

	// Compaction events
	EventCompactionStart
	EventCompactionEnd

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

	// EventRunFinished is the single canonical terminal event for a run. Exactly
	// one is emitted per run before the legacy EventDone/EventError and the
	// EventAgentEnd lifecycle event. It carries the TaskStatus outcome so consumers do not have to infer success from a mix of
	// EventDone/EventError events and channel-close signals.
	EventRunFinished
)

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", "os"])
	InheritSandbox  bool          // Inherit parent's sandbox (default true)
	TimeoutPerAgent time.Duration // Per-agent timeout (default 30min)
	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 SystemPromptOptions added in v1.2.87

type SystemPromptOptions struct {
	ToolExecutionMode  string
	MaxToolConcurrency int
	Authored           bool
}

SystemPromptOptions controls runtime details that affect tool orchestration. Keeping these values in the prompt makes the model's call grouping agree with the local executor without changing the public BuildSystemPrompt helper.

type TaskStatus added in v1.1.82

type TaskStatus string

TaskStatus is the canonical terminal outcome of an agent run/task. It is carried by the EventRunFinished event and is the single source of truth that TUI, WebUI/Serve, and channel consumers use to classify a finished task.

const (
	// TaskSuccess means the run completed normally and achieved its objective.
	TaskSuccess TaskStatus = "success"
	// TaskIncomplete means the run stopped before achieving its objective
	// (output/context limits, max iterations, stuck detection) without a hard error.
	TaskIncomplete TaskStatus = "incomplete"
	// TaskError means the run terminated due to an error.
	TaskError TaskStatus = "error"
	// TaskFailed is retained as a source-compatible alias for TaskError.
	// Deprecated: use TaskError.
	TaskFailed TaskStatus = TaskError
	// TaskCanceled means the run was canceled by the user, a timeout, or context cancellation.
	TaskCanceled TaskStatus = "canceled"
)

func (TaskStatus) IsSuccessful added in v1.1.82

func (s TaskStatus) IsSuccessful() bool

IsSuccessful reports whether the outcome is a successful completion.

func (TaskStatus) IsTerminal added in v1.1.82

func (s TaskStatus) IsTerminal() bool

IsTerminal reports whether the TaskStatus represents a finished run outcome.

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"
	ThinkingMax     ThinkingLevel = "max"
)

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