Documentation
¶
Index ¶
- Constants
- func AgentIDFromContext(ctx context.Context) (agentpkg.AgentID, bool)
- func AttachmentsFromPublic(items []agentpkg.Attachment) []provider.Attachment
- func AttachmentsToPublic(items []provider.Attachment) []agentpkg.Attachment
- func BoundedParallel[T any, R any](max int, items []T, fn func(T) R) []R
- func BuildContextFilesContext(files []ContextFileInfo) string
- func BuildSkillsContext(skills []SkillInfo) string
- func BuildSubAgentContext() string
- func BuildSystemPrompt(mode string, toolNames []string, cwd string, ruleContent string, ...) string
- func BuildSystemPromptWithOptions(mode string, toolNames []string, cwd string, ruleContent string, ...) string
- func ChatParamsFromPublic(p agentpkg.ChatParams) provider.ChatParams
- func ChatParamsToPublic(p provider.ChatParams) agentpkg.ChatParams
- func CompactionSettingsFromConfig(c config.CompactionSettings) ctxpkg.CompactionSettings
- func ComposeFollowUps(mailbox *MemberMailbox, adapterSteering func() []provider.Message) func(context.Context) []provider.Message
- func ConsumeEvents(ctx context.Context, eventCh <-chan Event, handler EventHandler) error
- func ContentBlockFromPublic(cb agentpkg.ContentBlock) provider.ContentBlock
- func ContentBlockToPublic(cb provider.ContentBlock) agentpkg.ContentBlock
- func ContextUsageToPublic(u *ctxpkg.ContextUsage) *agentpkg.ContextUsage
- func ContextWithAgentID(ctx context.Context, id agentpkg.AgentID) context.Context
- func ContextWithEventChan(ctx context.Context, ch chan<- Event) context.Context
- func ContextWithParentMode(ctx context.Context, mode string) context.Context
- func ContextWithParentRunContext(ctx context.Context, parent context.Context) context.Context
- func EventChanFromContext(ctx context.Context) (chan<- Event, bool)
- func EventToPublic(e Event) agentpkg.Event
- func EventTypeToPublic(t EventType) agentpkg.EventType
- func FileDiffToPublic(d *tools.FileDiff) *agentpkg.FileDiff
- func ForwardChildAgentEvent(ctx context.Context, ch chan<- Event, childID agentpkg.AgentID, ...) bool
- func MessageFromPublic(m agentpkg.Message) provider.Message
- func MessageToPublic(m provider.Message) agentpkg.Message
- func MessagesFromPublic(msgs []agentpkg.Message) []provider.Message
- func MessagesToPublic(msgs []provider.Message) []agentpkg.Message
- func ModelInfoToInternal(m agentpkg.ModelInfo) *provider.Model
- func ModelToPublic(m *provider.Model) agentpkg.ModelInfo
- func NewSubAgentWaitTool(m *AgentManager) tools.Tool
- func ParentModeFromContext(ctx context.Context) (string, bool)
- func ParentRunContextFromContext(ctx context.Context) (context.Context, bool)
- func RegisterDelegateSubAgentTool(registry *tools.Registry, manager *AgentManager)
- func RegisterSubAgentTools(registry *tools.Registry, manager *AgentManager)
- func ResolveMaxTokens(model *provider.Model) int
- func ResolveMaxTokensValue(explicit int, model *provider.Model) int
- func StreamEventFromPublic(e agentpkg.StreamEvent) provider.StreamEvent
- func StreamEventToPublic(e provider.StreamEvent) agentpkg.StreamEvent
- func StreamEventTypeFromPublic(t agentpkg.StreamEventType) provider.StreamEventType
- func StreamEventTypeToPublic(t provider.StreamEventType) agentpkg.StreamEventType
- func SubAgentToolNames() []string
- func TaskPlanToPublic(p *tools.TaskPlan) *agentpkg.TaskPlan
- func ToolCallBlockToPublic(tc *provider.ToolCallBlock) *agentpkg.ToolCallBlock
- func ToolImagesToPublic(images []ToolImage) []agentpkg.ToolImage
- func UsageToPublic(u *provider.Usage) *agentpkg.Usage
- func WrapEventChan(in <-chan Event) <-chan agentpkg.Event
- type AfterToolCallContext
- type Agent
- func (a *Agent) Abort()
- func (a *Agent) Aborted() bool
- func (a *Agent) AskQuestion(ctx context.Context, question string, options []string, explanation string) string
- func (a *Agent) BuildBackgroundChatParams(localTurnID string, msg provider.Message) (provider.ChatParams, error)
- func (a *Agent) BuildBackgroundContinuationParams(localTurnID string) (provider.ChatParams, error)
- func (a *Agent) BuildBackgroundReplayParams(localTurnID string) (provider.ChatParams, error)
- func (a *Agent) CanCompact() bool
- func (a *Agent) Compact(ctx context.Context, ch chan<- Event) error
- func (a *Agent) CompactForced(ctx context.Context, ch chan<- Event) error
- func (a *Agent) DeliverQuestionAnswer(questionID string, answer string) bool
- func (a *Agent) ExecuteBackgroundToolCall(ctx context.Context, tc provider.ToolCallBlock, localTurnID string) <-chan Event
- func (a *Agent) ExecuteBackgroundToolCallOrdered(ctx context.Context, tc provider.ToolCallBlock, localTurnID string, ...) <-chan Event
- func (a *Agent) ExecuteBackgroundToolCallRecovering(ctx context.Context, tc provider.ToolCallBlock, localTurnID string) <-chan Event
- func (a *Agent) GetContext() *AgentContext
- func (a *Agent) GetContextUsage() *ctxpkg.ContextUsage
- func (a *Agent) GetHistoryState() ([]provider.Message, []string)
- func (a *Agent) GetMessages() []provider.Message
- func (a *Agent) HandleApprovalResponse(approvalID string, approved bool)
- func (a *Agent) HandleQuestionResponse(questionID string, answer string)
- func (a *Agent) ID() agentpkg.AgentID
- func (a *Agent) LoadHistoryMessages(messages []provider.Message)
- func (a *Agent) LoadHistoryState(messages []provider.Message, entryIDs []string)
- func (a *Agent) MaxToolConcurrency() int
- func (a *Agent) NeedsApproval(toolName string, args map[string]any) bool
- func (a *Agent) ParentID() agentpkg.AgentID
- func (a *Agent) RequestApproval(ch chan<- Event, toolName string, args map[string]any) bool
- func (a *Agent) RequestQuestion(ctx context.Context, ch chan<- Event, question string, options []string, ...) string
- func (a *Agent) RequestToolApproval(ctx context.Context, ch chan<- Event, toolCallID, toolName string, ...) bool
- func (a *Agent) ResponsesStateFallbackError(err error) bool
- func (a *Agent) Run(ctx context.Context, userMsg string) <-chan Event
- func (a *Agent) RunWithLoadedHistory(ctx context.Context) <-chan Event
- func (a *Agent) RunWithMessages(ctx context.Context, messages []provider.Message) <-chan Event
- func (a *Agent) RunWithUserMessage(ctx context.Context, msg provider.Message) <-chan Event
- func (a *Agent) SetContext(ctx *AgentContext)
- func (a *Agent) SetConversationTurn(turnID, intentID, runID string)
- func (a *Agent) SetForceCompact()
- func (a *Agent) SetMessages(msgs []provider.Message)
- func (a *Agent) ShouldCompact() bool
- type AgentAdapter
- func (a *AgentAdapter) Abort()
- func (a *AgentAdapter) DeliverQuestionAnswer(questionID string, answer string) bool
- func (a *AgentAdapter) GetContext() *agentpkg.AgentContext
- func (a *AgentAdapter) GetContextUsage() *agentpkg.ContextUsage
- func (a *AgentAdapter) GetMessages() []agentpkg.Message
- func (a *AgentAdapter) HandleApprovalResponse(id string, approved bool)
- func (a *AgentAdapter) HandleQuestionResponse(questionID string, answer string)
- func (a *AgentAdapter) ID() agentpkg.AgentID
- func (a *AgentAdapter) LoadHistoryMessages(msgs []agentpkg.Message)
- func (a *AgentAdapter) ParentID() agentpkg.AgentID
- func (a *AgentAdapter) Run(ctx context.Context, userMsg string) <-chan agentpkg.Event
- func (a *AgentAdapter) RunWithMessages(ctx context.Context, msgs []agentpkg.Message) <-chan agentpkg.Event
- func (a *AgentAdapter) SetContext(ctx *agentpkg.AgentContext)
- func (a *AgentAdapter) SetMessages(msgs []agentpkg.Message)
- type AgentContext
- type AgentFactory
- type AgentFactoryOptions
- type AgentLoopConfig
- type AgentManager
- func (m *AgentManager) AddStatusListener(l AgentStatusListener)
- func (m *AgentManager) Children(id agentpkg.AgentID) []agentpkg.AgentID
- func (m *AgentManager) Count() int
- func (m *AgentManager) Create(opts AgentOptions) (agentpkg.Agent, error)
- func (m *AgentManager) Destroy(id agentpkg.AgentID) error
- func (m *AgentManager) DetachChild(id agentpkg.AgentID)
- func (m *AgentManager) Finish(id agentpkg.AgentID, cause error)
- func (m *AgentManager) Get(id agentpkg.AgentID) (agentpkg.Agent, bool)
- func (m *AgentManager) HasRunning() bool
- func (m *AgentManager) HasRunningChildren() bool
- func (m *AgentManager) List() []agentpkg.AgentID
- func (m *AgentManager) MarkCanceled(id agentpkg.AgentID, err error)
- func (m *AgentManager) MarkDone(id agentpkg.AgentID, result string)
- func (m *AgentManager) MarkError(id agentpkg.AgentID, err error)
- func (m *AgentManager) MarkIncomplete(id agentpkg.AgentID, err error)
- func (m *AgentManager) MarkRunning(id agentpkg.AgentID)
- func (m *AgentManager) NotifyMemberQuestion(memberID, displayName, questionID, question string, options []string)
- func (m *AgentManager) Parent(id agentpkg.AgentID) (agentpkg.AgentID, bool)
- func (m *AgentManager) Register(a agentpkg.Agent)
- func (m *AgentManager) SetCancel(id agentpkg.AgentID, cancel context.CancelFunc)
- func (m *AgentManager) SetMemberContext(members *MemberDefRegistry, mailbox *MemberMailbox, expertID string)
- func (m *AgentManager) SetMemberWaitEnabled(enabled bool)
- func (m *AgentManager) Status(id agentpkg.AgentID) (ManagedAgentStatus, bool)
- func (m *AgentManager) Statuses() []ManagedAgentStatus
- func (m *AgentManager) UpdateRuntimeConfig(p provider.Provider, providerName string, model *provider.Model, ...)
- type AgentOptions
- type AgentStatusListener
- type BaseProvider
- type BeforeToolCallContext
- type BeforeToolExecuteContext
- type ChatParams
- type ChildEventMeta
- type Config
- type ContextFileInfo
- type DelegateSubAgentTool
- func (t *DelegateSubAgentTool) Description() string
- func (t *DelegateSubAgentTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *DelegateSubAgentTool) Name() string
- func (t *DelegateSubAgentTool) Parameters() json.RawMessage
- func (t *DelegateSubAgentTool) PromptGuidelines() []string
- func (t *DelegateSubAgentTool) PromptSnippet() string
- type Event
- type EventHandler
- type EventHandlerFunc
- type EventRouter
- func (r *EventRouter) Dispatch(event agentpkg.Event) error
- func (r *EventRouter) GlobalHandlerCount() int
- func (r *EventRouter) HandlerCount(id agentpkg.AgentID) int
- func (r *EventRouter) RegisterAgent(id agentpkg.AgentID, handler RouterEventHandler)
- func (r *EventRouter) RegisterGlobal(handler RouterEventHandler)
- func (r *EventRouter) UnregisterAgent(id agentpkg.AgentID)
- type EventType
- type ExtendBudgetTool
- func (t *ExtendBudgetTool) Description() string
- func (t *ExtendBudgetTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *ExtendBudgetTool) Name() string
- func (t *ExtendBudgetTool) Parameters() json.RawMessage
- func (t *ExtendBudgetTool) PromptGuidelines() []string
- func (t *ExtendBudgetTool) PromptSnippet() string
- type IterationBudgetPolicy
- type ManagedAgentStatus
- type MemberCompletion
- type MemberDef
- type MemberDefRegistry
- type MemberMailbox
- func (m *MemberMailbox) DrainSteering() []provider.Message
- func (m *MemberMailbox) Enqueue(c MemberCompletion)
- func (m *MemberMailbox) HasPending() bool
- func (m *MemberMailbox) PendingSummary() []MemberCompletion
- func (m *MemberMailbox) RunningChildren() bool
- func (m *MemberMailbox) SetRunningPredicate(running func() bool)
- func (m *MemberMailbox) WaitForActivity(ctx context.Context, timeout time.Duration) (bool, error)
- type Model
- type ModelPricing
- type PrepareNextTurnContext
- type Provider
- type ProviderAdapter
- type PublicProviderAdapter
- type RouterEventHandler
- type RouterEventHandlerFunc
- type ShouldStopAfterTurnContext
- type SkillInfo
- type StreamEvent
- type StreamEventType
- type SubAgentAnswerTool
- func (t *SubAgentAnswerTool) Description() string
- func (t *SubAgentAnswerTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *SubAgentAnswerTool) Name() string
- func (t *SubAgentAnswerTool) Parameters() json.RawMessage
- func (t *SubAgentAnswerTool) PromptGuidelines() []string
- func (t *SubAgentAnswerTool) PromptSnippet() string
- type SubAgentDestroyTool
- func (t *SubAgentDestroyTool) Description() string
- func (t *SubAgentDestroyTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *SubAgentDestroyTool) Name() string
- func (t *SubAgentDestroyTool) Parameters() json.RawMessage
- func (t *SubAgentDestroyTool) PromptGuidelines() []string
- func (t *SubAgentDestroyTool) PromptSnippet() string
- type SubAgentPolicy
- type SubAgentSendTool
- func (t *SubAgentSendTool) Description() string
- func (t *SubAgentSendTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *SubAgentSendTool) Name() string
- func (t *SubAgentSendTool) Parameters() json.RawMessage
- func (t *SubAgentSendTool) PromptGuidelines() []string
- func (t *SubAgentSendTool) PromptSnippet() string
- type SubAgentSpawnTool
- func (t *SubAgentSpawnTool) Description() string
- func (t *SubAgentSpawnTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *SubAgentSpawnTool) Name() string
- func (t *SubAgentSpawnTool) Parameters() json.RawMessage
- func (t *SubAgentSpawnTool) PromptGuidelines() []string
- func (t *SubAgentSpawnTool) PromptSnippet() string
- type SubAgentStatusTool
- func (t *SubAgentStatusTool) Description() string
- func (t *SubAgentStatusTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *SubAgentStatusTool) Name() string
- func (t *SubAgentStatusTool) Parameters() json.RawMessage
- func (t *SubAgentStatusTool) PromptGuidelines() []string
- func (t *SubAgentStatusTool) PromptSnippet() string
- type SubAgentWaitTool
- func (t *SubAgentWaitTool) Description() string
- func (t *SubAgentWaitTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
- func (t *SubAgentWaitTool) Name() string
- func (t *SubAgentWaitTool) Parameters() json.RawMessage
- func (t *SubAgentWaitTool) PromptGuidelines() []string
- func (t *SubAgentWaitTool) PromptSnippet() string
- type SystemPromptOptions
- type TaskStatus
- type ThinkingLevel
- type ToolCallBlockResult
- type ToolCallResult
- type ToolImage
- type ToolLaunchHandle
- type ToolLaunchOrder
- type TurnUpdate
Constants ¶
const ( // MemberFollowUpWaitMax bounds how long a team lead waits for its still // running members before the run may end. Member runs have their own // 30-minute per-agent timeout, so this is a safety net, not the normal exit. MemberFollowUpWaitMax = 35 * time.Minute // MemberFollowUpPoll refreshes the "any member still running" check and the // adapter steering probe while waiting. The member wake-up itself is // event-driven through the mailbox activity signal. MemberFollowUpPoll = 2 * time.Second )
const ( MemberStatusDone = "done" MemberStatusError = "error" MemberStatusCanceled = "canceled" MemberStatusIncomplete = "incomplete" )
Member completion statuses carried by MemberCompletion.Status. They match the terminal managed-agent states so adapters can project them uniformly.
const ( MemberItemCompletion = "completion" MemberItemQuestion = "question" )
Member notification kinds. A mailbox item is either a terminal completion or a blocking question the member asked the lead instead of the human.
const ( // DefaultIterationBudgetWallClock is the default total wall-clock cap for one // run. It is exported so the serve run watchdog and durable background-polling // caps agree with the agent loop instead of drifting to a shorter limit that // would cut short a run the policy still allows. DefaultIterationBudgetWallClock = 16 * time.Hour )
const IterationBudgetToolName = "extend_budget"
IterationBudgetToolName is the model-facing renewal tool for the main loop's iteration budget. It is registered only for the session's conversational lead; sub-agents and expert members never receive it (their iteration count is a capability ceiling that may only narrow).
const MemberStatusQuestion = "question"
MemberStatusQuestion is the status projected for MemberItemQuestion entries in subagent_wait summaries.
Variables ¶
This section is empty.
Functions ¶
func AgentIDFromContext ¶
AgentIDFromContext extracts the agent ID from the context.
func AttachmentsFromPublic ¶
func AttachmentsFromPublic(items []agentpkg.Attachment) []provider.Attachment
func AttachmentsToPublic ¶
func AttachmentsToPublic(items []provider.Attachment) []agentpkg.Attachment
func BoundedParallel ¶
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 ¶
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 ¶
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 ¶
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 ComposeFollowUps ¶
func ComposeFollowUps(mailbox *MemberMailbox, adapterSteering func() []provider.Message) func(context.Context) []provider.Message
ComposeFollowUps builds a team lead's would-stop hook: it is called when a turn has no tool calls and therefore would end the run.
Order of precedence:
- adapter steering (for example a queued user message) is returned immediately, so the user keeps control while members are still running;
- pending member notifications are returned so the lead learns about completions and questions;
- only when members are still running does it block — event-driven on the mailbox — until something arrives or the bounded wait expires.
A nil mailbox yields a nil hook so non-team sessions keep the exact prior loop shape.
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.
Cancellation boundary: the Agent loop's terminal events (EventRunFinished/ EventDone/EventError/EventAgentEnd) are sent unconditionally, so a consumer that returns here on ctx.Done can leave a cancelled run parked on one of those sends. In-process adapters that must let the run finish its terminal bookkeeping keep draining the channel (the TUI retires the stream but keeps consuming it); an adapter whose process ends with the command, such as CLI print mode, relies on process teardown instead.
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 ¶
ContextWithAgentID returns a new context with the agent ID attached.
func ContextWithEventChan ¶
ContextWithEventChan returns a new context with the event channel attached.
func ContextWithParentMode ¶
ContextWithParentMode attaches the parent agent's execution mode to the context.
func ContextWithParentRunContext ¶
ContextWithParentRunContext attaches the parent agent run context to a tool context.
func EventChanFromContext ¶
EventChanFromContext extracts the event channel from the context.
func EventToPublic ¶
EventToPublic converts an internal Event to a public agent.Event.
func EventTypeToPublic ¶
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 ¶
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, meta ...ChildEventMeta) 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. The optional meta attaches expert-team member/expert identity to the projected event.
func MessageFromPublic ¶
MessageFromPublic converts a public agent.Message to an internal provider.Message.
func MessageToPublic ¶
MessageToPublic converts an internal provider.Message to a public agent.Message.
func MessagesFromPublic ¶
MessagesFromPublic converts a slice of public messages to internal.
func MessagesToPublic ¶
MessagesToPublic converts a slice of internal messages to public.
func ModelInfoToInternal ¶
ModelInfoToInternal converts a public ModelInfo to an internal *Model.
func ModelToPublic ¶
ModelToPublic converts an internal *provider.Model to a public agent.ModelInfo.
func NewSubAgentWaitTool ¶
func NewSubAgentWaitTool(m *AgentManager) tools.Tool
NewSubAgentWaitTool creates the subagent_wait tool.
func ParentModeFromContext ¶
ParentModeFromContext extracts the parent agent's execution mode.
func ParentRunContextFromContext ¶
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 ¶
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 ¶
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 StreamEventTypeFromPublic ¶
func StreamEventTypeFromPublic(t agentpkg.StreamEventType) provider.StreamEventType
func StreamEventTypeToPublic ¶
func StreamEventTypeToPublic(t provider.StreamEventType) agentpkg.StreamEventType
func SubAgentToolNames ¶
func SubAgentToolNames() []string
SubAgentToolNames returns the canonical async sub-agent toolset, in registration order. Every adapter that installs or uninstalls these tools (factory child registries, expert bind/unbind, channel tool catalogs) must derive its list from here instead of repeating the names: a hand-copied list silently keeps a removed tool alive in one entry point.
A fresh slice is returned so callers cannot mutate the shared definition.
func TaskPlanToPublic ¶
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 ToolImagesToPublic ¶
ToolImagesToPublic converts internal tool result images to the public SDK type. The base64 payload is passed through unchanged.
func UsageToPublic ¶
UsageToPublic converts an internal provider.Usage to public agent.Usage.
func WrapEventChan ¶
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 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) Aborted ¶
Aborted reports whether Abort has been called on this Agent instance. Abort is one-shot and permanent: once the abort channel is closed the instance can never start another run. Callers that cache an Agent (for example a front-end reusing it across prompts) must discard it after an abort instead of reusing it, otherwise every later run would be canceled immediately.
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 ¶
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 ¶
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 ¶
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 ¶
CanCompact reports whether the current conversation has older messages that can be summarized while preserving the configured recent context.
func (*Agent) Compact ¶
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 ¶
CompactForced performs explicit user-requested compaction. It skips preflight compactability checks and allows summary-only checkpoints.
func (*Agent) DeliverQuestionAnswer ¶
DeliverQuestionAnswer resolves a pending question and reports whether the answer was actually delivered. Callers that answer on someone else's behalf (subagent_answer routing a member's question to its lead) use the result to distinguish a delivered answer from a question that was already resolved, expired, or never existed — reporting success there would tell the lead a blocked member had been unblocked when it was not.
func (*Agent) ExecuteBackgroundToolCall ¶
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) ExecuteBackgroundToolCallOrdered ¶
func (a *Agent) ExecuteBackgroundToolCallOrdered(ctx context.Context, tc provider.ToolCallBlock, localTurnID string, allowReadOnlyRecovery bool, launch *ToolLaunchHandle) <-chan Event
ExecuteBackgroundToolCallOrdered runs one call of a background batch that reports its starts in the declared provider order. allowReadOnlyRecovery keeps the normal and recovering entry points available to batch callers, and launch carries the batch position (nil executes unordered, as before).
func (*Agent) ExecuteBackgroundToolCallRecovering ¶
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 ¶
GetHistoryState returns a copy of message history plus aligned session entry IDs.
func (*Agent) GetMessages ¶
GetMessages returns a copy of the current message history.
func (*Agent) HandleApprovalResponse ¶
HandleApprovalResponse processes the user's approval response.
func (*Agent) HandleQuestionResponse ¶
HandleQuestionResponse processes the user's answer to a question. It keeps the silent contract for protocol adapters (an unknown or already resolved ID is ignored); callers that answer on another agent's behalf must use DeliverQuestionAnswer so they never report a false success.
func (*Agent) LoadHistoryMessages ¶
LoadHistoryMessages loads historical messages from session into agent context.
func (*Agent) LoadHistoryState ¶
LoadHistoryState loads historical messages plus their session entry IDs.
func (*Agent) MaxToolConcurrency ¶
MaxToolConcurrency returns the normalized per-batch local tool limit.
func (*Agent) NeedsApproval ¶
NeedsApproval checks if a tool call needs user approval based on the current mode.
func (*Agent) RequestApproval ¶
RequestApproval sends an approval request and waits for the user's response. It has no context-bounded cancellation and is kept for callers that only have an event channel; new callers inside the loop use RequestToolApproval with the run context so a cancelled run can unblock the wait.
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 ¶
func (a *Agent) RequestToolApproval(ctx context.Context, 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.
The approval ID embeds the Agent ID so decision registries keyed by ID (TUI/WebUI/ACP durable decision records) stay unique when several agents of one run raise their own first approval. Per-instance counters alone would collide ("approval-1" from a lead and from each sub-agent).
func (*Agent) ResponsesStateFallbackError ¶
ResponsesStateFallbackError delegates remote state classification to the configured provider without exposing provider-specific types to callers.
func (*Agent) RunWithLoadedHistory ¶
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 ¶
RunWithMessages processes with explicit message history.
func (*Agent) RunWithUserMessage ¶
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 ¶
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 ¶
SetMessages replaces the message history.
func (*Agent) ShouldCompact ¶
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) DeliverQuestionAnswer ¶
func (a *AgentAdapter) DeliverQuestionAnswer(questionID string, answer string) bool
DeliverQuestionAnswer exposes the atomic answer delivery to callers that answer on another agent's behalf; it is intentionally not part of the public QuestionHandler interface so existing implementers keep compiling.
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) RunWithMessages ¶
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
// ExpertIdentity/ExpertRoster are injected into main agents only
// (ParentID == ""); sub-agents never receive the lead persona overlay.
ExpertIdentity string
ExpertRoster string
}
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. Zero uses the
// default limit; a negative value intentionally leaves the loop unbounded
// until it completes or its context is cancelled.
MaxIterations int
// GetSteeringMessages returns messages to inject mid-run.
GetSteeringMessages func() []provider.Message
// GetFollowUpMessages returns messages to process after the agent would stop.
// It may block while adapter-owned work is still running (for example a team
// lead must wait for its members); a non-empty result keeps the run open and
// injects the messages instead of finishing.
GetFollowUpMessages func(ctx context.Context) []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
// IterationBudget governs model-requested iteration renewals. The zero value
// disables renewal and keeps the fixed MaxIterations behavior.
IterationBudget IterationBudgetPolicy
// 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 {
// Expert-team member context, installed once by the runtime assembly
// layer via SetMemberContext before any run starts and treated as
// read-only afterwards. All three are nil/empty when no expert team is
// bound to the session.
Members *MemberDefRegistry
Mailbox *MemberMailbox
ExpertID string
// 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 ¶
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 ¶
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) HasRunning ¶
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) HasRunningChildren ¶
func (m *AgentManager) HasRunningChildren() bool
HasRunningChildren reports whether any managed child (a spawned member or a delegated task) is still running. Team leads use it to avoid ending their run while member results are still in flight.
func (*AgentManager) List ¶
func (m *AgentManager) List() []agentpkg.AgentID
List returns all agent IDs.
func (*AgentManager) MarkCanceled ¶
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 ¶
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) NotifyMemberQuestion ¶
func (m *AgentManager) NotifyMemberQuestion(memberID, displayName, questionID, question string, options []string)
NotifyMemberQuestion queues a member's blocking question for the lead. The mailbox is the only wake path: a blocked subagent_wait returns on the activity signal, and the question is injected as a steering message at the lead's next iteration boundary so the lead can answer it with subagent_answer instead of the member blocking on an answer that can never arrive.
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) SetMemberContext ¶
func (m *AgentManager) SetMemberContext(members *MemberDefRegistry, mailbox *MemberMailbox, expertID string)
SetMemberContext installs the expert-team member context: the roster registry, the session member mailbox, and the bound expert id. Passing nil/empty values clears a previous binding. Callers must set the context during assembly, before any agent run starts; sub-agent tools read these fields directly and rely on that happens-before ordering.
func (*AgentManager) SetMemberWaitEnabled ¶
func (m *AgentManager) SetMemberWaitEnabled(enabled bool)
SetMemberWaitEnabled records whether this manager's lead may hold its run open for still-running members. It is true only for a bound expert team: other sessions still deliver member questions and completions through the mailbox steering drain, but a run may end while members are running so unattended entry points never inherit the team's bounded member wait. Callers must set this during assembly, before any run starts.
func (*AgentManager) Status ¶
func (m *AgentManager) Status(id agentpkg.AgentID) (ManagedAgentStatus, bool)
Status returns a copy of the tracked status for an agent.
func (*AgentManager) Statuses ¶
func (m *AgentManager) Statuses() []ManagedAgentStatus
Statuses returns a sorted copy of all tracked agent statuses.
func (*AgentManager) UpdateRuntimeConfig ¶
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
// Member metadata is a display snapshot for a named expert-team child.
// AgentFactory does not interpret it; AgentManager retains it alongside the
// child lifecycle so adapters can project the same canonical identity.
MemberID string
ExpertID string
MemberDisplayName string
MemberEmoji string
MemberRole string
Mode string
Model *provider.Model
WorkDir string
Tools []string // optional: tool filter
// ExcludeTools removes tools from the resolved child registry after the
// standard mode/tool filtering. Used for children whose callers cannot answer
// a tool's interactive contract (for example a blocking delegate child that
// must not ask questions).
ExcludeTools []string
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
// OwnsSessionMailbox opts an IsSubAgent role back into the session member
// mailbox. The mailbox belongs to the conversational lead, so auxiliary roles
// (ESM critic/audit/recovery) must not inherit it; a team-bound ESM worker
// continuation is the session's lead in ESM mode and sets this explicitly.
OwnsSessionMailbox bool
// AuxiliaryRole marks an agent that is not the session's conversational lead
// even though its shape matches one (a parentless, non-subagent run such as a
// session-bound cron job). Auxiliary agents never drain or wait on the
// session's members, and take precedence over OwnsSessionMailbox.
AuxiliaryRole bool
MultiAgent *bool // optional prompt override
DelegateMode *bool // optional prompt override
Workflows *bool // optional prompt override
}
AgentOptions specifies per-agent overrides.
type AgentStatusListener ¶
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.
type BeforeToolCallContext ¶
type BeforeToolCallContext struct {
AssistantMessage provider.Message
ToolCall provider.ToolCallBlock
Args any
Context *AgentContext
}
BeforeToolCallContext is passed to BeforeToolCall.
type BeforeToolExecuteContext ¶
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 ChildEventMeta ¶
type ChildEventMeta struct {
MemberID string
ExpertID string
MemberDisplayName string
MemberEmoji string
MemberRole string
}
ChildEventMeta carries optional expert-team metadata for forwarded child events. The zero value adds no metadata, keeping existing call sites behavior-identical.
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)
// ExpertIdentity is the runtime-injected expert persona overlay and
// ExpertRoster the team roster + dispatch rules section. Both are
// authoritative runtime content (empty when no expert is bound) rendered
// between project rules and project context.
ExpertIdentity string
ExpertRoster string
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
// Expert-team metadata (additive; empty when no expert team is bound).
// MemberID and ExpertID identify the persona and bundle. The display fields
// are immutable snapshots from the resolved member definition so replaying
// an old event never needs to resolve potentially changed package content.
MemberID string
ExpertID string
MemberDisplayName string
MemberEmoji string
MemberRole string
// 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
// ToolImages carries the image payloads embedded in a completed tool
// result (EventToolExecutionEnd) so adapters can project them as image
// content blocks without re-parsing provider messages. Additive: text-only
// consumers can ignore it.
ToolImages []ToolImage
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 ¶
EventHandler receives agent events from a running request.
type EventHandlerFunc ¶
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 (*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 ExtendBudgetTool ¶
type ExtendBudgetTool struct{}
ExtendBudgetTool lets the model request more iterations when a run is close to its iteration limit but the task is genuinely unfinished. It is stateless: the per-run budget handle is carried on the run context, and the Runtime clamps every request (hard ceiling, renewal count, minimum interval). It is registered only for the session's conversational lead.
func NewExtendBudgetTool ¶
func NewExtendBudgetTool() *ExtendBudgetTool
NewExtendBudgetTool creates the extend_budget tool.
func (*ExtendBudgetTool) Description ¶
func (t *ExtendBudgetTool) Description() string
func (*ExtendBudgetTool) Execute ¶
func (t *ExtendBudgetTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
func (*ExtendBudgetTool) Name ¶
func (t *ExtendBudgetTool) Name() string
func (*ExtendBudgetTool) Parameters ¶
func (t *ExtendBudgetTool) Parameters() json.RawMessage
func (*ExtendBudgetTool) PromptGuidelines ¶
func (t *ExtendBudgetTool) PromptGuidelines() []string
func (*ExtendBudgetTool) PromptSnippet ¶
func (t *ExtendBudgetTool) PromptSnippet() string
type IterationBudgetPolicy ¶
type IterationBudgetPolicy struct {
Soft int
Hard int
RenewFactor float64
MaxRenewals int
MinInterval int
MaxWallClock time.Duration
}
IterationBudgetPolicy bounds the main loop's iteration count and governs model-requested renewals. The zero value disables renewal: the loop keeps the legacy fixed-MaxIterations behavior.
Soft is the initial effective limit, Hard the ceiling renewal may never pass, RenewFactor the fraction of Soft granted per renewal, MaxRenewals the number of grants allowed per run, MinInterval the minimum number of iterations between two grants, and MaxWallClock the total wall-clock cap for one run.
func (IterationBudgetPolicy) Enabled ¶
func (p IterationBudgetPolicy) Enabled() bool
Enabled reports whether renewal is configured (a Hard ceiling above Soft).
func (IterationBudgetPolicy) Normalize ¶
func (p IterationBudgetPolicy) Normalize(soft int) IterationBudgetPolicy
Normalize applies defaults relative to the supplied soft limit (used when the policy leaves Soft unset). A normalized policy is always Enabled.
type ManagedAgentStatus ¶
type ManagedAgentStatus struct {
ID agentpkg.AgentID
ParentID agentpkg.AgentID
MemberID string
ExpertID string
MemberDisplayName string
MemberEmoji string
MemberRole string
State string
Result string
Error string
StartedAt time.Time
UpdatedAt time.Time
}
ManagedAgentStatus captures scheduling state for an agent managed by AgentManager.
type MemberCompletion ¶
type MemberCompletion struct {
Kind string // "" (completion) | MemberItemCompletion | MemberItemQuestion
MemberID string
DisplayName string
Status string // "done" | "error" | "canceled" | "incomplete" | "question"
Payload string // final result, error explanation, or question text
QuestionID string
Options []string
}
MemberCompletion is one member notification queued in a MemberMailbox. For completions, Payload carries the final response (done) or the error text (error/canceled/incomplete). For MemberItemQuestion entries, Payload carries the question text and QuestionID/Options identify the pending request the lead must answer with subagent_answer.
type MemberDef ¶
type MemberDef struct {
ID string
DisplayName string
Emoji string
Role string // "lead" | "member"
Description string
Prompt string // persona system prompt, injected via SystemPromptExtra
Mode string // ""|plan|agent|yolo|os
Tools []string
MaxIterations int
WorkDir string
}
MemberDef is the agent-package view of one expert-team member: a persona prompt plus optional capability overrides. The runtime assembly layer builds these from the bound expert bundle and installs them via AgentManager.SetMemberContext; internal/agent never parses bundle files.
type MemberDefRegistry ¶
type MemberDefRegistry struct {
// contains filtered or unexported fields
}
MemberDefRegistry is an insertion-ordered, concurrency-safe lookup table of member definitions keyed by id.
func NewMemberDefRegistry ¶
func NewMemberDefRegistry(defs []*MemberDef) *MemberDefRegistry
NewMemberDefRegistry builds a registry from defs, preserving insertion order. Nil entries and entries with an empty id are skipped; for duplicate ids the first definition wins.
func (*MemberDefRegistry) Get ¶
func (r *MemberDefRegistry) Get(id string) (*MemberDef, bool)
Get returns the member definition registered for id. A nil registry has no members.
func (*MemberDefRegistry) IDs ¶
func (r *MemberDefRegistry) IDs() []string
IDs returns the registered member ids in insertion order. The result is a copy; a nil registry returns nil.
type MemberMailbox ¶
type MemberMailbox struct {
// contains filtered or unexported fields
}
MemberMailbox is the session-level in-memory queue of member completions. The runtime drains it at agent-loop iteration boundaries through DrainSteering (composed into GetSteeringMessages by the runtime assembly layer); subagent_wait merges a blocked lead into activity through WaitForActivity. A mailbox never wakes or starts a run by itself. The zero value is not usable; create one with NewMemberMailbox. All methods are safe on a nil mailbox so callers can skip nil checks at use sites.
func NewMemberMailbox ¶
func NewMemberMailbox() *MemberMailbox
NewMemberMailbox creates an empty mailbox.
func (*MemberMailbox) DrainSteering ¶
func (m *MemberMailbox) DrainSteering() []provider.Message
DrainSteering removes and returns every queued completion in enqueue order, formatted as system-injected steering messages (one per completion). It returns nil when nothing is pending. The activity hint is drained alongside the queue so a later WaitForActivity does not return on a stale signal.
func (*MemberMailbox) Enqueue ¶
func (m *MemberMailbox) Enqueue(c MemberCompletion)
Enqueue appends a completion to the queue and non-blockingly signals activity so a waiting subagent_wait returns promptly.
func (*MemberMailbox) HasPending ¶
func (m *MemberMailbox) HasPending() bool
HasPending reports whether undelivered completions are queued.
func (*MemberMailbox) PendingSummary ¶
func (m *MemberMailbox) PendingSummary() []MemberCompletion
PendingSummary returns a read-only snapshot of the queued completions without removing them. subagent_wait uses it for its pending list; content delivery stays exclusively with DrainSteering.
func (*MemberMailbox) RunningChildren ¶
func (m *MemberMailbox) RunningChildren() bool
RunningChildren reports whether members are still running. It always reports false when no predicate is installed, so a mailbox that is only used for notifications never blocks a run.
func (*MemberMailbox) SetRunningPredicate ¶
func (m *MemberMailbox) SetRunningPredicate(running func() bool)
SetRunningPredicate installs the "any member still running" probe used by the lead's follow-up hook. Nil clears a previous binding.
func (*MemberMailbox) WaitForActivity ¶
WaitForActivity blocks until the mailbox signals activity, the timeout elapses (timedOut=true, err=nil), or ctx is done (err wraps ctx.Err).
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 ¶
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 (pa *PublicProviderAdapter) Chat(ctx context.Context, params agentpkg.ChatParams) <-chan agentpkg.StreamEvent
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 ¶
RouterEventHandler receives agent events for routing purposes.
type RouterEventHandlerFunc ¶
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 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 SubAgentAnswerTool ¶
type SubAgentAnswerTool struct {
// contains filtered or unexported fields
}
SubAgentAnswerTool answers a blocking question a running member asked the lead. The question is delivered as a [MEMBER_QUESTION] steering message (or a subagent_wait pending entry with status "question"); the member stays blocked until this tool resolves it.
func NewSubAgentAnswerTool ¶
func NewSubAgentAnswerTool(m *AgentManager) *SubAgentAnswerTool
func (*SubAgentAnswerTool) Description ¶
func (t *SubAgentAnswerTool) Description() string
func (*SubAgentAnswerTool) Execute ¶
func (t *SubAgentAnswerTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
func (*SubAgentAnswerTool) Name ¶
func (t *SubAgentAnswerTool) Name() string
func (*SubAgentAnswerTool) Parameters ¶
func (t *SubAgentAnswerTool) Parameters() json.RawMessage
func (*SubAgentAnswerTool) PromptGuidelines ¶
func (t *SubAgentAnswerTool) PromptGuidelines() []string
func (*SubAgentAnswerTool) PromptSnippet ¶
func (t *SubAgentAnswerTool) PromptSnippet() string
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.
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 SubAgentWaitTool ¶
type SubAgentWaitTool struct {
// contains filtered or unexported fields
}
SubAgentWaitTool blocks the calling (lead) agent until the session member mailbox reports activity or a bounded timeout elapses. It only merges the caller into already-scheduled member completions; like the mailbox itself it never wakes or starts a run. The result lists pending completions without their payloads — content is delivered by the mailbox drain at the next iteration boundary.
func (*SubAgentWaitTool) Description ¶
func (t *SubAgentWaitTool) Description() string
func (*SubAgentWaitTool) Execute ¶
func (t *SubAgentWaitTool) Execute(ctx context.Context, params map[string]any) (tools.ToolResult, error)
func (*SubAgentWaitTool) Name ¶
func (t *SubAgentWaitTool) Name() string
func (*SubAgentWaitTool) Parameters ¶
func (t *SubAgentWaitTool) Parameters() json.RawMessage
func (*SubAgentWaitTool) PromptGuidelines ¶
func (t *SubAgentWaitTool) PromptGuidelines() []string
func (*SubAgentWaitTool) PromptSnippet ¶
func (t *SubAgentWaitTool) PromptSnippet() string
type SystemPromptOptions ¶
type SystemPromptOptions struct {
ToolExecutionMode string
MaxToolConcurrency int
Authored bool
// ExpertIdentity and ExpertRoster are runtime-injected expert sections
// rendered after project rules and before project context. They are
// authoritative: identity changes only through bind/unbind/fork, never
// through user text or tool descriptions.
ExpertIdentity string
ExpertRoster string
}
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 ¶
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 ¶
func (s TaskStatus) IsSuccessful() bool
IsSuccessful reports whether the outcome is a successful completion.
func (TaskStatus) IsTerminal ¶
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 ¶
ToolCallBlockResult is returned from BeforeToolCall.
type ToolCallResult ¶
ToolCallResult represents the result of a tool call.
type ToolImage ¶
ToolImage is one image payload extracted from a rich tool result. Data holds the base64-encoded image bytes exactly as the tool produced them.
type ToolLaunchHandle ¶
type ToolLaunchHandle struct {
// contains filtered or unexported fields
}
ToolLaunchHandle owns one call's start checkpoint in a ToolLaunchOrder batch. Every method is safe on a nil handle.
func (*ToolLaunchHandle) Release ¶
func (h *ToolLaunchHandle) Release()
Release reports the start checkpoint for a call that never reached it, so the calls queued behind it can begin. It is idempotent and is normally deferred by the code path that executes the call.
type ToolLaunchOrder ¶
type ToolLaunchOrder struct {
// contains filtered or unexported fields
}
ToolLaunchOrder keeps the *start* of one parallel tool-call batch in the declared provider order without serializing or blocking the batch: calls still run concurrently, still wait for approvals and durable claims independently, and may finish in any order, but call i may not report its start before call i-1 has reported its own. Argument sizes, worker scheduling, and per-call waits in front of the tool can therefore no longer reorder the observable start of a batch.
The order is a chain of one-shot handoffs. Call i closes the signal that releases call i+1 only after its own start has been reported, so the predecessor's start happens before the successor's. A call that leaves before reporting its start (invalid arguments, unknown tool, replayed result) releases its successor through Release, so a failed call never parks the rest of the batch. The only wait is that handoff: it is never held across a tool body, an approval prompt, or a durable claim.
func NewToolLaunchOrder ¶
func NewToolLaunchOrder(calls int) *ToolLaunchOrder
NewToolLaunchOrder prepares the start-order chain for one batch of calls. The first call is always free to start. A non-positive call count returns nil, which yields nil-safe handles.
func (*ToolLaunchOrder) Handle ¶
func (o *ToolLaunchOrder) Handle(index int) *ToolLaunchHandle
Handle returns the ordering handle of one call in the batch. Handles are single-use, single-goroutine, and nil-safe, so sequential and single-call paths may pass nil.
type TurnUpdate ¶
type TurnUpdate struct {
Context *AgentContext
Model *provider.Model
ThinkingLevel provider.ThinkingLevel
}
TurnUpdate is returned from PrepareNextTurn.
Source Files
¶
- agent.go
- agent_approval.go
- agent_context.go
- bridge.go
- compaction.go
- eventloop.go
- events.go
- external_tool_adapter.go
- factory.go
- followup.go
- iteration_budget.go
- iteration_budget_tool.go
- mailbox.go
- manager.go
- max_tokens.go
- memberdef.go
- parallel.go
- provider.go
- router.go
- subagent.go
- subagent_tools.go
- subagent_wait.go
- system_prompt.go
- tool_launch.go