agent

package
v0.0.43 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: GPL-3.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultConsecutiveToolErrorLimit = 3

DefaultConsecutiveToolErrorLimit is the consecutive all-error tool-turn threshold that triggers a corrective escalation note.

View Source
const DefaultMaxToolOutputBytes = 64 * 1024

DefaultMaxToolOutputBytes caps model-facing tool output when RunConfig.MaxToolOutputBytes is 0. 64 KB (~16K tokens) bounds the context cost of a single pathological tool call while staying generous enough for file reads and command output (codex-cli truncates exec output at ~10K tokens at history-record time for the same reason).

View Source
const DefaultMaxToolResultBytes = eventStreamMaxToolBytes

DefaultMaxToolResultBytes is the default cap for tool result/input content.

View Source
const DefaultMaxTurns = 100

DefaultMaxTurns is used when RunConfig.MaxTurns is 0.

View Source
const DefaultModelCallTimeout = 10 * time.Minute

DefaultModelCallTimeout bounds a single model generation attempt when RunConfig.ModelCallTimeout is 0. It is generous enough for slow, high-reasoning generations over large contexts, but finite so a hung provider connection can never freeze a run indefinitely.

View Source
const DefaultStopGateMaxBlocks = 8

DefaultStopGateMaxBlocks caps consecutive StopGate blocks before the gate is bypassed.

View Source
const DefaultSubAgentMaxTurns = 50

DefaultSubAgentMaxTurns is used when RunConfig.SubAgentMaxTurns is 0.

View Source
const MaxEvents = 20
View Source
const RecommendedHandoffPromptPrefix = `# System context
You are part of a multi-agent system designed to make agent coordination and execution easy. Agents use two primary abstractions: tools and handoffs. Handoffs transfer control to another agent that is better suited for the task, and are achieved by calling a handoff function, generally named ` + "`transfer_to_<agent_name>`" + `. Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.`

RecommendedHandoffPromptPrefix is a system-prompt preamble that orients an agent within a multi-agent system. Prepending it to an agent's instructions helps the model treat handoffs as seamless background transfers instead of narrating them to the user. It mirrors the guidance shipped by other agent frameworks for handoff-aware agents.

Variables

View Source
var Items = ItemHelpers{}

ItemHelpers provides utility functions for working with RunItem slices.

Functions

func BuildRunBudgetContext

func BuildRunBudgetContext(maxTurns int) string

BuildRunBudgetContext tells the top-level agent how large its runner budget is without using sub-agent language.

func BuildSubAgentBudgetContext

func BuildSubAgentBudgetContext(maxTurns int) string

BuildSubAgentBudgetContext tells a sub-agent how large its runner budget is and how to preserve useful output if the task is broader than that budget.

func BuildSubAgentDependencyContext

func BuildSubAgentDependencyContext(tasks []SubAgentTask) string

BuildSubAgentDependencyContext formats completed dependency outputs for a downstream task. Dependency results are data, not instructions.

func BuildSubAgentMonitorContext

func BuildSubAgentMonitorContext(tasks []SubAgentTask) string

BuildSubAgentMonitorContext formats active sub-agent task state for the parent when it tries to final-answer before managed child work is terminal.

func BuildSubAgentResultsContext

func BuildSubAgentResultsContext(tasks []SubAgentTask) string

BuildSubAgentResultsContext formats terminal sub-agent task outputs for the parent agent. Results are data, not instructions.

func BuildWorkspaceContext

func BuildWorkspaceContext(workDir string, toolAccess ToolAccessLevel) string

BuildWorkspaceContext creates a concise environment context block that tells the sub-agent its working directory and tool capabilities. This prevents the model from guessing wrong paths and hallucinating missing tools.

func CompactionDefaultsForModel

func CompactionDefaultsForModel(model string) (triggerTokens, targetTokens int)

CompactionDefaultsForModel returns tuned compaction thresholds based on the model's context window. Trigger fires when ~10% of context remains (90% used). Target compacts down to ~50% of context window.

This is the STATIC fallback used only when authoritative provider metadata (the /models endpoint) is unavailable for the model. It deliberately errs toward SMALLER windows for unknown/small variants: over-compaction merely wastes a little context, but under-compaction lets a run blow past the real limit and hang (see the gpt-5.3-codex-spark freeze). Small fast variants (-spark/-nano/-mini/-lite/-flash) are therefore capped conservatively even though some of them advertise larger windows; provider metadata overrides these when present.

func ExtractAskUserQuestion

func ExtractAskUserQuestion(input json.RawMessage) string

ExtractAskUserQuestion extracts the question text from an AskUserQuestion tool call.

func ExtractBashCommand

func ExtractBashCommand(input json.RawMessage) string

ExtractBashCommand extracts the command string from a Bash tool call input.

func ExtractCompactionSummary

func ExtractCompactionSummary(items []RunItem) string

func ExtractFilePath

func ExtractFilePath(input json.RawMessage) string

ExtractFilePath extracts the file_path from a tool call input (Read, Edit, Write).

func ExtractGlobPattern

func ExtractGlobPattern(input json.RawMessage) string

ExtractGlobPattern extracts the pattern from a Glob tool call input.

func ExtractGrepPattern

func ExtractGrepPattern(input json.RawMessage) string

ExtractGrepPattern extracts the pattern from a Grep tool call input.

func ExtractLSPOperation

func ExtractLSPOperation(input json.RawMessage) (string, string)

ExtractLSPOperation extracts the operation and file path from an LSP tool call.

func ExtractPath added in v0.0.8

func ExtractPath(input json.RawMessage) string

ExtractPath extracts the path from tool inputs that use a "path" field (e.g. read_file, list_files).

func FormatToolNames

func FormatToolNames(names []string) string

FormatToolNames formats a list of tool names for compact logging.

func ParentCallIDFromContext

func ParentCallIDFromContext(ctx context.Context) string

ParentCallIDFromContext extracts the parent tool call ID, if any.

func ParseModelPrefix

func ParseModelPrefix(name string) (prefix, model string)

ParseModelPrefix splits a "prefix/model" string into its components. If there is no "/" the prefix is empty and model is the full string.

func ResolveModelForProvider

func ResolveModelForProvider(model, provider string) string

ResolveModelForProvider maps short aliases and provider-incompatible model names to sensible defaults for the selected provider.

Prefer using MultiProvider.GetModel() which handles this internally. This function is kept for call sites that need resolution without constructing a Model.

func SpanParentIDFromContext

func SpanParentIDFromContext(ctx context.Context) string

SpanParentIDFromContext extracts the current nested-run parent span ID.

func TaskIDFromContext

func TaskIDFromContext(ctx context.Context) string

TaskIDFromContext extracts the current subagent task ID, if any.

func ToolCallIDFromContext

func ToolCallIDFromContext(ctx context.Context) string

ToolCallIDFromContext extracts the current tool call ID, if any.

func Truncate

func Truncate(s string, n int) string

Truncate trims whitespace, replaces newlines with spaces, and truncates to n runes.

func TruncateBytes

func TruncateBytes(s string, n int) string

TruncateBytes truncates a string to at most n bytes, appending "..." if truncated.

func TruncateMiddle added in v0.0.8

func TruncateMiddle(s string, n int) string

TruncateMiddle truncates s to at most n runes by keeping the head and tail and eliding the middle. Use this for model-facing payloads (sub-agent results, command output) where the conclusion at the end of the text is usually as important as the beginning; tail-truncation would drop it.

func WithNestedRunConfig

func WithNestedRunConfig(ctx context.Context, cfg RunConfig) context.Context

func WithParentCallID

func WithParentCallID(ctx context.Context, id string) context.Context

WithParentCallID returns a context carrying the given parent tool call ID.

func WithRecommendedHandoffInstructions

func WithRecommendedHandoffInstructions(instructions string) string

WithRecommendedHandoffInstructions returns the given instructions prefixed with RecommendedHandoffPromptPrefix. If instructions is empty, only the prefix is returned.

func WithTaskID

func WithTaskID(ctx context.Context, id string) context.Context

WithTaskID returns a context carrying the current subagent task ID.

func WithToolCallID

func WithToolCallID(ctx context.Context, id string) context.Context

WithToolCallID returns a context carrying the current tool call ID.

func WithTraceContext

func WithTraceContext(ctx context.Context, trace *Trace, processor TracingProcessor, parentSpanID string) context.Context

WithTraceContext returns a context carrying trace config for nested runs.

Types

type Agent

type Agent struct {
	Name               string
	Instructions       string                                     // static instructions
	InstructionsFn     func(ctx *RunContext, agent *Agent) string // dynamic instructions (used if set)
	Model              string                                     // model name, resolved to Model impl at runtime
	FallbackModels     []string                                   // ordered cross-provider fallback models for failed model calls
	ModelSettings      ModelSettings
	Tools              []Tool
	MCPServers         []string   // host-provided MCP server names for prompt context
	Handoffs           []*Handoff // in-process agent handoffs
	InputGuardrails    []InputGuardrail
	OutputGuardrails   []OutputGuardrail
	OutputType         *OutputSchema // nil = plain string output
	Hooks              AgentHooks    // per-agent lifecycle hooks
	ToolUseBehavior    ToolUseBehavior
	StopAtTools        *StopAtTools
	ToolsToFinalOutput *ToolsToFinalOutputResult
	HandoffDescription string // description when this agent is a handoff target
}

Agent defines an AI agent with its configuration, tools, and behavior.

func (*Agent) AsTool

func (a *Agent) AsTool(runner *Runner, opts ...AsToolOption) Tool

AsTool returns a Tool that runs this agent as a nested sub-agent. When called, the tool input becomes the user message and the agent's final text output becomes the tool result. Options can override the tool name/description or post-process the sub-agent result before it is returned to the parent (custom output extraction).

func (*Agent) Clone

func (a *Agent) Clone(opts ...AgentOption) *Agent

Clone returns a shallow copy of the agent with optional overrides applied.

func (*Agent) GetAllTools

func (a *Agent) GetAllTools(ctx *RunContext) []Tool

GetAllTools returns all tools available to this agent: explicit tools + handoff-generated tools.

func (*Agent) GetInstructions

func (a *Agent) GetInstructions(ctx *RunContext) string

GetInstructions resolves the agent's instructions, preferring InstructionsFn if set.

type AgentError

type AgentError struct {
	Message string
	Cause   error
}

AgentError is the base error type for agent operations.

func (*AgentError) Error

func (e *AgentError) Error() string

func (*AgentError) Unwrap

func (e *AgentError) Unwrap() error

type AgentHooks

type AgentHooks interface {
	OnStart(ctx *RunContext, agent *Agent)
	OnEnd(ctx *RunContext, agent *Agent, output any)
	OnHandoff(ctx *RunContext, agent *Agent, target *Agent)
	OnToolStart(ctx *RunContext, agent *Agent, tool Tool, call ToolCallData)
	OnToolEnd(ctx *RunContext, agent *Agent, tool Tool, call ToolCallData, result ToolResult)
}

AgentHooks defines per-agent lifecycle callbacks.

type AgentLogger

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

AgentLogger provides structured, level-aware logging for the agent pod. Normal mode logs every event concisely (turns, tools, phases, model responses). Debug mode adds full tool inputs/outputs, instructions, and conversation items.

func NewAgentLogger

func NewAgentLogger(level LogLevel) *AgentLogger

NewAgentLogger creates a logger at the given level.

func (*AgentLogger) AutoContinue

func (l *AgentLogger) AutoContinue(count int, reason string)

AutoContinue logs an auto-continue event.

func (*AgentLogger) Debugf

func (l *AgentLogger) Debugf(format string, args ...any)

Debugf logs only in debug mode.

func (*AgentLogger) Error

func (l *AgentLogger) Error(msg string)

Error logs an error.

func (*AgentLogger) Errorf

func (l *AgentLogger) Errorf(format string, args ...any)

Errorf logs a formatted error.

func (*AgentLogger) Event

func (l *AgentLogger) Event(ev ContentEvent)

Event logs an EventStream event to stdout.

func (*AgentLogger) Infof

func (l *AgentLogger) Infof(format string, args ...any)

Infof always logs.

func (*AgentLogger) InputItems

func (l *AgentLogger) InputItems(items []RunItem)

InputItems logs conversation items sent to the model. Normal: count + role summary. Debug: full content.

func (*AgentLogger) Instructions

func (l *AgentLogger) Instructions(instructions string)

Instructions logs system instructions. Full dump in debug, length-only in normal.

func (*AgentLogger) IsDebug

func (l *AgentLogger) IsDebug() bool

func (*AgentLogger) ModelResponse

func (l *AgentLogger) ModelResponse(model string, textCount, toolCount, thinkingCount int, inputTokens, outputTokens int64, stopReason string)

ModelResponse logs a model response summary.

func (*AgentLogger) ParallelToolCalls

func (l *AgentLogger) ParallelToolCalls(names []string)

ParallelToolCalls logs parallel tool execution.

func (*AgentLogger) ToolExec

func (l *AgentLogger) ToolExec(name, callID string, inputLen int)

ToolExec logs a tool execution start.

func (*AgentLogger) ToolResult

func (l *AgentLogger) ToolResult(name, callID string, isError bool, output string)

ToolResult logs a tool result. Full output in debug, length-only in normal.

func (*AgentLogger) Tools

func (l *AgentLogger) Tools(toolNames []string, handoffNames []string, accessLevel ToolAccessLevel)

Tools logs tool and handoff summary.

func (*AgentLogger) Turn

func (l *AgentLogger) Turn(turn int, agent, model string)

Turn logs the start of a new LLM turn.

func (*AgentLogger) TurnEnd

func (l *AgentLogger) TurnEnd(turn int)

TurnEnd logs end of turn payload.

func (*AgentLogger) Warn

func (l *AgentLogger) Warn(msg string)

Warn logs a warning.

func (*AgentLogger) Warnf

func (l *AgentLogger) Warnf(format string, args ...any)

Warnf logs a formatted warning.

type AgentMeta

type AgentMeta struct {
	Description  string
	Prompt       string
	SubagentType string
	Model        string
	Isolation    string
}

AgentMeta holds metadata about a running subagent.

func ExtractAgentMeta

func ExtractAgentMeta(input json.RawMessage) AgentMeta

ExtractAgentMeta extracts metadata from an Agent tool call input.

type AgentOption

type AgentOption func(*Agent)

AgentOption is a functional option for Agent.Clone().

func WithHandoffs

func WithHandoffs(handoffs ...*Handoff) AgentOption

WithHandoffs overrides the agent handoffs.

func WithInstructions

func WithInstructions(instructions string) AgentOption

WithInstructions overrides the agent instructions.

func WithModel

func WithModel(model string) AgentOption

WithModel overrides the agent model.

func WithName

func WithName(name string) AgentOption

WithName overrides the agent name.

func WithOutputType

func WithOutputType(schema *OutputSchema) AgentOption

WithOutputType overrides the agent output type.

func WithStopAtTools

func WithStopAtTools(stop *StopAtTools) AgentOption

WithStopAtTools configures tool names that stop the run after their results.

func WithTools

func WithTools(tools ...Tool) AgentOption

WithTools overrides the agent tools.

func WithToolsToFinalOutput

func WithToolsToFinalOutput(result *ToolsToFinalOutputResult) AgentOption

WithToolsToFinalOutput configures whether a stopping tool result becomes final output.

type AgentSpanData

type AgentSpanData struct {
	AgentName    string
	Instructions string
}

AgentSpanData records data about an agent invocation.

type AsToolOption

type AsToolOption func(*agentTool)

AsToolOption configures an agent-as-tool wrapper produced by Agent.AsTool.

func WithAsToolDescription

func WithAsToolDescription(desc string) AsToolOption

WithAsToolDescription overrides the tool description for an agent-as-tool wrapper.

func WithAsToolName

func WithAsToolName(name string) AsToolOption

WithAsToolName overrides the generated tool name for an agent-as-tool wrapper.

func WithAsToolOutputExtractor

func WithAsToolOutputExtractor(fn func(*RunResult) string) AsToolOption

WithAsToolOutputExtractor sets a function that transforms the sub-agent's RunResult into the string returned to the parent agent. Use it to return a compact, structured, or filtered view of the sub-agent's work instead of its raw final text. If the extractor returns an empty string, the wrapper falls back to the sub-agent's final text.

type CompactionConfig

type CompactionConfig struct {
	Enabled                     bool
	TriggerTokens               int
	TargetTokens                int
	PreserveRecentItems         int
	PreserveInitialUserMessages int
	SummaryBulletLimit          int
	// UseLLMSummary asks the active model to write the compaction summary
	// (findings, decisions, state, pending work) instead of the mechanical
	// tool/file digest. Falls back to the deterministic summary whenever the
	// model call fails or produces an unusable result.
	UseLLMSummary bool
}

CompactionConfig controls proactive context compaction.

func DefaultCompactionConfig

func DefaultCompactionConfig() CompactionConfig

DefaultCompactionConfig returns a conservative default policy for long-running sessions.

type CompactionData

type CompactionData struct {
	ID               string `json:"id,omitempty"`
	Content          string `json:"content,omitempty"` // provider summary of compacted context
	EncryptedContent string `json:"encrypted_content,omitempty"`
	CreatedBy        string `json:"created_by,omitempty"`
}

CompactionData holds an opaque provider compaction item.

type CompactionModelResolver added in v0.0.24

type CompactionModelResolver func(ctx context.Context, model string) (triggerTokens, targetTokens int, ok bool)

CompactionModelResolver resolves model-specific compaction thresholds for a (possibly provider-prefixed) model name. It returns tuned trigger/target token thresholds — typically derived from authoritative provider metadata (the /models endpoint), falling back to CompactionDefaultsForModel. ok=false means "use the configured defaults unchanged".

The runner consults this once per turn against the model actually being used, so a sub-agent running a different model than its parent compacts at its own model's context window instead of inheriting the parent's thresholds. Implementations must be safe for concurrent use and should cache results.

type CompactionPlan added in v0.0.37

type CompactionPlan struct {
	// Items is the deterministically compacted history (summary already inserted).
	Items []RunItem
	// Removed are the original items that were collapsed into the summary.
	Removed []RunItem
	// Protected is the set of source indices preserved verbatim.
	Protected map[int]struct{}
	// Source is the original, uncompacted history the plan was built from.
	Source []RunItem
	// After is the estimated token size of Items.
	After int
}

CompactionPlan is a selected compaction split: the deterministic compacted items plus the raw removed items, so callers can regenerate the summary (e.g. with an LLM) without re-running the selection search.

func PlanRunItemsCompactionForRequest added in v0.0.37

func PlanRunItemsCompactionForRequest(items []RunItem, cfg CompactionConfig, requestOverheadTokens int) (CompactionPlan, int, bool, string)

PlanRunItemsCompactionForRequest is the plan-returning variant of MaybeCompactRunItemsForRequest. The returned plan's After includes the request overhead so it is directly comparable with the returned before.

func (CompactionPlan) RebuildWithSummary added in v0.0.37

func (p CompactionPlan) RebuildWithSummary(summaryBody string) []RunItem

RebuildWithSummary rebuilds the compacted history using a replacement summary body. The body is prefixed with the standard compaction marker and scope line so downstream extraction (ExtractCompactionSummary) keeps working.

type CompactionResult

type CompactionResult struct {
	Items   []RunItem
	Usage   Usage
	Raw     any
	Summary string
}

CompactionResult is the provider-native compacted context window.

type CompactionSpanData

type CompactionSpanData struct {
	TokensBefore int
	TokensAfter  int
}

CompactionSpanData records data about context compaction.

type ContentEvent

type ContentEvent struct {
	Timestamp time.Time `json:"ts"`
	Type      string    `json:"type"`
	Session   int32     `json:"session"`

	// Content
	Message string `json:"message,omitempty"`

	// Tool identification and I/O
	Tool           string `json:"tool,omitempty"`
	ToolUseID      string `json:"tool_use_id,omitempty"`
	ParentCallID   string `json:"parent_call_id,omitempty"`
	IsError        bool   `json:"is_error,omitempty"`
	AgentName      string `json:"agent_name,omitempty"`
	InputRaw       string `json:"input_raw,omitempty"`
	Output         string `json:"output,omitempty"`
	ToolDurationMS int64  `json:"tool_duration_ms,omitempty"`

	// Workflow location
	Phase string `json:"phase,omitempty"`

	LLMAttempt int32  `json:"llm_attempt,omitempty"`
	LLMScope   string `json:"llm_scope,omitempty"`

	AttemptNumber       int32  `json:"attempt_number,omitempty"`
	AttemptStatus       string `json:"attempt_status,omitempty"`
	Scope               string `json:"scope,omitempty"`
	RequestedModel      string `json:"requested_model,omitempty"`
	ResolvedModel       string `json:"resolved_model,omitempty"`
	CanonicalModel      string `json:"canonical_model,omitempty"`
	Provider            string `json:"provider,omitempty"`
	Turn                int32  `json:"turn,omitempty"`
	UsageAvailable      bool   `json:"usage_available,omitempty"`
	HasPromptTokens     bool   `json:"has_prompt_tokens,omitempty"`
	HasCompletionTokens bool   `json:"has_completion_tokens,omitempty"`
	HasTotalTokens      bool   `json:"has_total_tokens,omitempty"`
	PromptTokens        int64  `json:"prompt_tokens,omitempty"`
	CompletionTokens    int64  `json:"completion_tokens,omitempty"`
	TotalTokens         int64  `json:"total_tokens,omitempty"`
	AttemptLatencyMs    int64  `json:"attempt_latency_ms,omitempty"`
	RetryPlanned        bool   `json:"retry_planned,omitempty"`
	RetryAfterMs        int64  `json:"retry_after_ms,omitempty"`
	FallbackPlanned     bool   `json:"fallback_planned,omitempty"`
	FallbackFromModel   string `json:"fallback_from_model,omitempty"`
	FallbackToModel     string `json:"fallback_to_model,omitempty"`
	FallbackReason      string `json:"fallback_reason,omitempty"`
	FailureKind         string `json:"failure_kind,omitempty"`

	// Subagent status
	TaskID string `json:"task_id,omitempty"`
	Status string `json:"status,omitempty"`

	// Subagent metadata (populated on subagent_started/subagent_completed)
	SubagentType  string `json:"subagent_type,omitempty"`
	SubagentModel string `json:"subagent_model,omitempty"`

	// Subagent prompt/result (for activity log display)
	SubagentPrompt     string `json:"subagent_prompt,omitempty"`
	SubagentResultText string `json:"subagent_result_text,omitempty"`

	// Subagent completion metrics
	SubagentToolCount  int32   `json:"subagent_tool_count,omitempty"`
	SubagentTokens     int64   `json:"subagent_tokens,omitempty"`
	SubagentDurationMs int64   `json:"subagent_duration_ms,omitempty"`
	SubagentCostUsd    float64 `json:"subagent_cost_usd,omitempty"`
	SubagentCostKnown  bool    `json:"subagent_cost_known,omitempty"`
	SubagentNumTurns   int32   `json:"subagent_num_turns,omitempty"`
	SubagentStopReason string  `json:"subagent_stop_reason,omitempty"`

	// Subagent progress snapshot fields.
	SubagentDependsOn         []string `json:"subagent_depends_on,omitempty"`
	SubagentWaitingOn         []string `json:"subagent_waiting_on,omitempty"`
	SubagentCurrentStep       string   `json:"subagent_current_step,omitempty"`
	SubagentLastTool          string   `json:"subagent_last_tool,omitempty"`
	SubagentFilesWritten      int      `json:"subagent_files_written,omitempty"`
	SubagentMessagesReceived  int      `json:"subagent_messages_received,omitempty"`
	SubagentLastParentMessage string   `json:"subagent_last_parent_message,omitempty"`

	// Step inference (exploring, implementing, committing, etc.)
	Step string `json:"step,omitempty"`

	// Session init metadata (populated on system_init events)
	Model          string   `json:"model,omitempty"`
	PermissionMode string   `json:"permission_mode,omitempty"`
	Cwd            string   `json:"cwd,omitempty"`
	MaxTurns       int32    `json:"max_turns,omitempty"`
	Tools          []string `json:"tools,omitempty"`
	McpServers     []string `json:"mcp_servers,omitempty"`

	// Session end metrics (populated on session_end events)
	CostUsd                  float64 `json:"cost_usd,omitempty"`
	CostKnown                bool    `json:"cost_known,omitempty"`
	InputTokens              int64   `json:"input_tokens,omitempty"`
	OutputTokens             int64   `json:"output_tokens,omitempty"`
	CacheReadInputTokens     int64   `json:"cache_read_input_tokens,omitempty"`
	CacheCreationInputTokens int64   `json:"cache_creation_input_tokens,omitempty"`
	NumTurns                 int32   `json:"num_turns,omitempty"`
	DurationMs               int64   `json:"duration_ms,omitempty"`
	StopReason               string  `json:"stop_reason,omitempty"`

	// Context compaction metadata.
	TokensBefore int32 `json:"tokens_before,omitempty"`
	TokensAfter  int32 `json:"tokens_after,omitempty"`

	// Hook decision data
	HookName string `json:"hook_name,omitempty"`
	Decision string `json:"decision,omitempty"`
	Reason   string `json:"reason,omitempty"`
}

ContentEvent is a thin real-time event for host UIs and log sinks. Content, status, and key metrics for live display. Full structural observability lives in OTel spans.

type ContextCompactor

type ContextCompactor interface {
	SupportsContextCompaction() bool
	CompactContext(ctx context.Context, req ModelRequest) (*CompactionResult, error)
}

ContextCompactor is implemented by models that support provider-native context compaction, such as OpenAI Responses compaction.

type Conversation

type Conversation struct {
	Items []RunItem
}

Conversation manages the message history for an agent run. Unlike the old implementation that stored []anthropic.Message, this uses the RunItem-based history format.

func NewConversation

func NewConversation() *Conversation

NewConversation creates an empty conversation.

func NewConversationFromItems

func NewConversationFromItems(items []RunItem) *Conversation

NewConversationFromItems creates a conversation with existing items.

func (*Conversation) AllText

func (c *Conversation) AllText() string

AllText returns all concatenated message text.

func (*Conversation) Append

func (c *Conversation) Append(items ...RunItem)

Append adds items to the conversation.

func (*Conversation) Clear

func (c *Conversation) Clear()

Clear removes all items.

func (*Conversation) Copy

func (c *Conversation) Copy() *Conversation

Copy returns a deep copy of the conversation.

func (*Conversation) LastText

func (c *Conversation) LastText() string

LastText returns the text of the last message item.

func (*Conversation) Len

func (c *Conversation) Len() int

Len returns the number of items.

func (*Conversation) ToolCalls

func (c *Conversation) ToolCalls() []ToolCallData

ToolCalls returns all tool call data.

type EventStream

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

EventStream writes thin real-time events for UI and log consumers. It replaces ProgressTracker's NDJSON LogEntry writing for content events. Structural/metrics data is handled by OTel spans instead.

func NewChildEventStream

func NewChildEventStream(parent *EventStream, taskID string) *EventStream

NewChildEventStream creates a child stream for a subagent. Shares the writer and write mutex, auto-tags events with taskID.

func NewEventStream

func NewEventStream(w io.Writer) *EventStream

NewEventStream creates a stream that writes thin events to w.

func (*EventStream) Emit

func (es *EventStream) Emit(ev ContentEvent)

Emit writes a stream event. Auto-tags with session, phase, step, and taskID. Also mirrors to stdout via the attached logger.

func (*EventStream) EmitCompaction

func (es *EventStream) EmitCompaction(tokensBefore, tokensAfter int, summary string)

func (*EventStream) EmitHookDecision

func (es *EventStream) EmitHookDecision(hookName, toolName, decision, reason string)

EmitHookDecision emits a hook/guardrail decision event.

func (*EventStream) EmitLLMAttempt

func (es *EventStream) EmitLLMAttempt(args ...interface{})

func (*EventStream) EmitSessionEnd

func (es *EventStream) EmitSessionEnd(status string, costUsd float64, costKnown bool, inputTokens, outputTokens, cacheRead, cacheCreate int64, numTurns int, durationMs int64, stopReason string)

EmitSessionEnd emits a session end marker with final metrics.

func (*EventStream) EmitSubagentCompleted

func (es *EventStream) EmitSubagentCompleted(taskID, status, description string, toolCount int32, tokens int64, durationMs int64, costUsd float64, costKnown bool, numTurns int32, stopReason, resultText string)

EmitSubagentCompleted emits a subagent lifecycle completion event with metrics.

func (*EventStream) EmitSubagentStarted

func (es *EventStream) EmitSubagentStarted(taskID, toolUseID, description, subagentType, model, prompt string)

EmitSubagentStarted emits a subagent lifecycle start event with full metadata.

func (*EventStream) EmitSubagentTaskStatus

func (es *EventStream) EmitSubagentTaskStatus(task SubAgentTask, message string)

EmitSubagentTaskStatus emits a compact subagent status/progress snapshot.

func (*EventStream) EmitSystemInit

func (es *EventStream) EmitSystemInit(model, permissionMode, cwd string, maxTurns int, toolsList, mcpServers []string)

EmitSystemInit emits a session initialization event with full metadata.

func (*EventStream) EmitText

func (es *EventStream) EmitText(text string, agentName ...string)

EmitText emits an assistant text event.

func (*EventStream) EmitThinking

func (es *EventStream) EmitThinking(thinking string, agentName ...string)

EmitThinking emits an assistant thinking event.

func (*EventStream) EmitToolEnd

func (es *EventStream) EmitToolEnd(toolName, toolUseID, parentCallID string, isError bool, agentName, output string, durationMS int64)

EmitToolEnd emits a tool completion event with output and duration.

func (*EventStream) EmitToolStart

func (es *EventStream) EmitToolStart(toolName, toolUseID, parentCallID, inputSummary, agentName, inputRaw string)

EmitToolStart emits a tool invocation event with optional raw input.

func (*EventStream) SetLogger

func (es *EventStream) SetLogger(l *AgentLogger)

SetLogger attaches a logger that mirrors every event to stdout.

func (*EventStream) SetPhase

func (es *EventStream) SetPhase(name string)

SetPhase updates the host-defined phase label stamped onto emitted events.

func (*EventStream) SetSession

func (es *EventStream) SetSession(num int32)

SetSession updates the session number.

func (*EventStream) SetStep

func (es *EventStream) SetStep(step string)

SetStep updates the current workflow step.

func (*EventStream) Subscribe

func (es *EventStream) Subscribe(buffer int) (<-chan ContentEvent, func())

Subscribe returns a live in-process stream of content events emitted through this EventStream. Child streams share the same subscription bus. The returned unsubscribe function closes the channel.

type FunctionSpanData

type FunctionSpanData struct {
	ToolName string
	Input    string
	Output   string
	IsError  bool
}

FunctionSpanData records data about a tool/function execution.

type FunctionTool

type FunctionTool struct {
	ToolName        string
	ToolDescription string
	Schema          json.RawMessage
	Fn              func(ctx context.Context, input json.RawMessage) (string, error)
	ReadOnly        bool
	Approval        bool
	Timeout         int
}

FunctionTool is a convenience tool built from a plain function.

func (*FunctionTool) Description

func (t *FunctionTool) Description() string

func (*FunctionTool) Execute

func (t *FunctionTool) Execute(ctx context.Context, input json.RawMessage, _ string) (ToolResult, error)

func (*FunctionTool) InputSchema

func (t *FunctionTool) InputSchema() json.RawMessage

func (*FunctionTool) IsEnabled

func (t *FunctionTool) IsEnabled(ctx *RunContext) bool

func (*FunctionTool) IsReadOnly

func (t *FunctionTool) IsReadOnly() bool

func (*FunctionTool) Name

func (t *FunctionTool) Name() string

func (*FunctionTool) NeedsApproval

func (t *FunctionTool) NeedsApproval() bool

func (*FunctionTool) TimeoutSeconds

func (t *FunctionTool) TimeoutSeconds() int

type GenerationSpanData

type GenerationSpanData struct {
	RequestedModel               string
	ResolvedModel                string
	ModelProvider                string
	ModelCanonical               string
	AttemptNumber                int32
	Turn                         int32
	Scope                        string
	TaskID                       string
	Status                       string
	UsageAvailable               bool
	PromptTokens                 int64
	CompletionTokens             int64
	CacheReadTokens              int64
	CacheCreateTokens            int64
	TotalTokens                  int64
	CostUSD                      float64
	CostKnown                    bool
	LatencyMS                    int64
	Success                      bool
	Error                        string
	RetryScheduled               bool
	RetryAfterMS                 int64
	FallbackScheduled            bool
	FallbackFromModel            string
	FallbackToModel              string
	FallbackReason               string
	FailureKind                  string
	ToolCount                    int32
	InputItemCount               int32
	OutputItemCount              int32
	InstructionsLength           int32
	InputTokenEstimate           int32
	RequestOverheadTokenEstimate int32
	TotalRequestTokenEstimate    int32
	Request                      *LLMRequestSnapshot
	Response                     *LLMResponseSnapshot
}

GenerationSpanData records data about a model generation.

type GuardrailResult

type GuardrailResult struct {
	Output            any
	TripwireTriggered bool
}

GuardrailResult is the outcome of a guardrail check.

type GuardrailSpanData

type GuardrailSpanData struct {
	GuardrailName string
	Triggered     bool
}

GuardrailSpanData records data about a guardrail check.

type Handoff

type Handoff struct {
	Agent       *Agent
	ToolName    string // defaults to "transfer_to_{name}"
	Description string
	InputFilter func(input []RunItem, history []RunItem) []RunItem
	InputType   *OutputSchema

	// OnHandoff is an optional callback fired when the model triggers this
	// handoff. It receives the raw JSON arguments the model supplied for the
	// handoff tool call (validated against InputType when InputType is set).
	// Use it to record escalation data, seed shared state, or run side effects
	// before control transfers to the target agent.
	OnHandoff func(ctx *RunContext, input json.RawMessage)

	// IsEnabledFn, when set, gates whether this handoff is exposed to the model
	// for the current run context. Returning false hides the handoff tool, so
	// hosts can enable/disable handoffs per phase or per state without rebuilding
	// the agent. A nil IsEnabledFn means the handoff is always enabled.
	IsEnabledFn func(ctx *RunContext) bool
}

Handoff defines an agent-to-agent handoff.

func NewHandoff

func NewHandoff(target *Agent, opts ...HandoffOption) *Handoff

NewHandoff creates a Handoff to the target agent.

func (*Handoff) ToTool

func (h *Handoff) ToTool() Tool

ToTool returns a Tool that triggers this handoff when called.

type HandoffCallData

type HandoffCallData struct {
	FromAgent string `json:"from_agent"`
	ToAgent   string `json:"to_agent"`
}

HandoffCallData records an agent-to-agent handoff request.

type HandoffHistoryConfig

type HandoffHistoryConfig struct {
	Enabled             bool
	MaxTokens           int
	TargetTokens        int
	PreserveRecentItems int
	SummaryBulletLimit  int
}

HandoffHistoryConfig controls how much history is forwarded across handoffs.

type HandoffOption

type HandoffOption func(*Handoff)

HandoffOption is a functional option for NewHandoff.

func WithDescription

func WithDescription(desc string) HandoffOption

WithDescription overrides the default description.

func WithInputFilter

func WithInputFilter(fn func(input []RunItem, history []RunItem) []RunItem) HandoffOption

WithInputFilter sets an input filter for the handoff.

func WithInputType

func WithInputType(schema *OutputSchema) HandoffOption

WithInputType sets the structured input schema the model must satisfy when triggering the handoff. The validated arguments are passed to OnHandoff.

func WithIsEnabled

func WithIsEnabled(fn func(ctx *RunContext) bool) HandoffOption

WithIsEnabled gates whether the handoff is exposed to the model for a given run context. A handoff with a predicate returning false is hidden.

func WithOnHandoff

func WithOnHandoff(fn func(ctx *RunContext, input json.RawMessage)) HandoffOption

WithOnHandoff sets a callback fired with the model-supplied handoff arguments when this handoff is triggered, before control transfers to the target agent.

func WithToolName

func WithToolName(name string) HandoffOption

WithToolName overrides the default tool name.

type HandoffOutputData

type HandoffOutputData struct {
	FromAgent string `json:"from_agent"`
	ToAgent   string `json:"to_agent"`
}

HandoffOutputData records the completion of a handoff.

type HandoffSpanData

type HandoffSpanData struct {
	FromAgent string
	ToAgent   string
}

HandoffSpanData records data about an agent handoff.

type HookEvent

type HookEvent struct {
	ToolName string
	Type     string
}

HookEvent captures the context of a hook invocation for recording.

type HookResult

type HookResult struct {
	Decision string
	Reason   string
}

HookResult captures the outcome of a hook invocation for recording.

type ImageAttachment

type ImageAttachment struct {
	MediaType string `json:"media_type"`
	Data      string `json:"data"`
}

ImageAttachment is a base64-encoded image attached to a user message.

type ImmediateInputPoller

type ImmediateInputPoller func(context.Context) ([]RunItem, error)

ImmediateInputPoller injects user messages at runner interruptible boundaries. Returned items should usually be user message RunItems (Agent == nil).

type InputGuardrail

type InputGuardrail struct {
	Name string
	Fn   func(ctx *RunContext, agent *Agent, input []RunItem) (*GuardrailResult, error)
}

InputGuardrail validates input before it reaches the model.

type InputGuardrailResult

type InputGuardrailResult struct {
	GuardrailName     string
	Output            any
	TripwireTriggered bool
}

InputGuardrailResult is the outcome of an input guardrail check.

type InputGuardrailTripwireTriggered

type InputGuardrailTripwireTriggered struct {
	GuardrailName string
	Result        GuardrailResult
}

InputGuardrailTripwireTriggered is returned when an input guardrail's tripwire fires.

func (*InputGuardrailTripwireTriggered) Error

type Interruption

type Interruption struct {
	ToolName   string          `json:"tool_name"`
	ToolInput  json.RawMessage `json:"tool_input"`
	ToolCallID string          `json:"tool_call_id"`
}

Interruption records why a run was paused (e.g. tool needs approval).

type ItemHelpers

type ItemHelpers struct{}

ItemHelpers contains methods for extracting data from RunItem slices.

func (ItemHelpers) ExtractLastText

func (ItemHelpers) ExtractLastText(items []RunItem) string

ExtractLastText returns the text from the last message item, or empty string.

func (ItemHelpers) ExtractText

func (ItemHelpers) ExtractText(items []RunItem) string

ExtractText concatenates all message text from the items.

func (ItemHelpers) ExtractToolCalls

func (ItemHelpers) ExtractToolCalls(items []RunItem) []ToolCallData

ExtractToolCalls returns all tool call data from the items.

type LLMCompaction

type LLMCompaction struct {
	ID               string `json:"id,omitempty"`
	Content          string `json:"content,omitempty"`
	EncryptedContent string `json:"encrypted_content,omitempty"`
	CreatedBy        string `json:"created_by,omitempty"`
}

type LLMOutputSchema

type LLMOutputSchema struct {
	Name   string          `json:"name"`
	Schema json.RawMessage `json:"schema,omitempty"`
	Strict bool            `json:"strict"`
}

type LLMReasoning

type LLMReasoning struct {
	ID               string `json:"id,omitempty"`
	Text             string `json:"text,omitempty"`
	Thinking         string `json:"thinking,omitempty"`
	Signature        string `json:"signature,omitempty"`
	RedactedData     string `json:"redacted_data,omitempty"`
	EncryptedContent string `json:"encrypted_content,omitempty"`
}

type LLMRequestSnapshot

type LLMRequestSnapshot struct {
	AgentName                    string               `json:"agent_name,omitempty"`
	Model                        string               `json:"model,omitempty"`
	Instructions                 string               `json:"instructions,omitempty"`
	InputItems                   []LLMRunItemSnapshot `json:"input_items,omitempty"`
	Tools                        []LLMToolSnapshot    `json:"tools,omitempty"`
	Settings                     ModelSettings        `json:"settings,omitempty"`
	OutputSchema                 *LLMOutputSchema     `json:"output_schema,omitempty"`
	InputTokenEstimate           int                  `json:"input_token_estimate,omitempty"`
	RequestOverheadTokenEstimate int                  `json:"request_overhead_token_estimate,omitempty"`
	TotalTokenEstimate           int                  `json:"total_token_estimate,omitempty"`
}

LLMRequestSnapshot is the serializable, analysis-oriented form of a model request. It intentionally excludes executable callbacks while preserving the text, tool schemas, settings, and structured input that shaped the call.

func BuildLLMRequestSnapshot

func BuildLLMRequestSnapshot(agentName string, req ModelRequest) *LLMRequestSnapshot

BuildLLMRequestSnapshot captures the full provider-agnostic request envelope sent to the model.

type LLMResponseSnapshot

type LLMResponseSnapshot struct {
	Items          []LLMRunItemSnapshot `json:"items,omitempty"`
	Usage          Usage                `json:"usage,omitempty"`
	Texts          []string             `json:"texts,omitempty"`
	Reasoning      []LLMReasoning       `json:"reasoning,omitempty"`
	ReasoningTexts []string             `json:"reasoning_texts,omitempty"`
	ThinkingTexts  []string             `json:"thinking_texts,omitempty"`
	ToolCalls      []LLMToolCall        `json:"tool_calls,omitempty"`
	Raw            json.RawMessage      `json:"raw,omitempty"`
	RawAvailable   bool                 `json:"raw_available"`
	RawError       string               `json:"raw_error,omitempty"`
}

LLMResponseSnapshot is the serializable, analysis-oriented form of a model response, including explicit provider-returned reasoning/thinking items when the provider exposes them.

func BuildLLMResponseSnapshot

func BuildLLMResponseSnapshot(resp *ModelResponse) *LLMResponseSnapshot

BuildLLMResponseSnapshot captures the full provider-agnostic response envelope returned by the model.

type LLMRunItemSnapshot

type LLMRunItemSnapshot struct {
	Type          string             `json:"type"`
	AgentName     string             `json:"agent_name,omitempty"`
	MessageText   string             `json:"message_text,omitempty"`
	ToolCall      *LLMToolCall       `json:"tool_call,omitempty"`
	ToolOutput    *ToolOutputData    `json:"tool_output,omitempty"`
	HandoffCall   *HandoffCallData   `json:"handoff_call,omitempty"`
	HandoffOutput *HandoffOutputData `json:"handoff_output,omitempty"`
	Reasoning     *LLMReasoning      `json:"reasoning,omitempty"`
	ReasoningText string             `json:"reasoning_text,omitempty"`
	ThinkingText  string             `json:"thinking_text,omitempty"`
	Compaction    *LLMCompaction     `json:"compaction,omitempty"`
	ToolApproval  *LLMToolApproval   `json:"tool_approval,omitempty"`
}

LLMRunItemSnapshot is a compact, non-recursive representation of a RunItem.

func SnapshotRunItems

func SnapshotRunItems(items []RunItem) []LLMRunItemSnapshot

type LLMToolApproval

type LLMToolApproval struct {
	ToolName string          `json:"tool_name,omitempty"`
	Input    json.RawMessage `json:"input,omitempty"`
	CallID   string          `json:"call_id,omitempty"`
	Approved bool            `json:"approved"`
}

type LLMToolCall

type LLMToolCall struct {
	ID    string          `json:"id,omitempty"`
	Name  string          `json:"name,omitempty"`
	Input json.RawMessage `json:"input,omitempty"`
}

type LLMToolSnapshot

type LLMToolSnapshot struct {
	Name           string          `json:"name"`
	Description    string          `json:"description,omitempty"`
	InputSchema    json.RawMessage `json:"input_schema,omitempty"`
	ReadOnly       bool            `json:"read_only"`
	NeedsApproval  bool            `json:"needs_approval"`
	TimeoutSeconds int             `json:"timeout_seconds,omitempty"`
}

func SnapshotTools

func SnapshotTools(tools []Tool) []LLMToolSnapshot

type LogLevel

type LogLevel int

LogLevel controls agent pod log verbosity.

const (
	LogLevelNormal LogLevel = iota
	LogLevelDebug
)

type MaxTurnsExceeded

type MaxTurnsExceeded struct {
	MaxTurns int
}

MaxTurnsExceeded is returned when Runner.Run exceeds the configured max turns.

func (*MaxTurnsExceeded) Error

func (e *MaxTurnsExceeded) Error() string

type MessageOutput

type MessageOutput struct {
	Text string `json:"text"`
	// Images carries inbound image attachments for multimodal user messages.
	// Outbound model messages leave this empty.
	Images []ImageAttachment `json:"images,omitempty"`
}

MessageOutput holds text content from the model.

type ModeModelRouting

type ModeModelRouting struct {
	DefaultModel   string
	FallbackModels []string
	ReasoningLevel string
	TextVerbosity  string
	RoleOverrides  map[string]ModeRoleModelRouting
}

ModeModelRouting contains SDK-native model routing knobs.

type ModeReasoningLevel

type ModeReasoningLevel string

ModeReasoningLevel is an SDK-native reasoning effort label.

const (
	ReasoningNone   ModeReasoningLevel = "none"
	ReasoningLow    ModeReasoningLevel = "low"
	ReasoningMedium ModeReasoningLevel = "medium"
	ReasoningHigh   ModeReasoningLevel = "high"
	ReasoningXHigh  ModeReasoningLevel = "xhigh"
)

type ModeRoleModelRouting

type ModeRoleModelRouting struct {
	Model          string
	FallbackModels []string
	ReasoningLevel string
	TextVerbosity  string
}

ModeRoleModelRouting contains routing overrides for one specialist role.

type ModeRoutingResolution

type ModeRoutingResolution struct {
	Model          string
	FallbackModels []string
	ReasoningLevel string
	TextVerbosity  string
	ModelSettings  ModelSettings
}

ModeRoutingResolution is the effective top-level or per-role routing result after applying mode defaults, role overrides, and reasoning settings.

func ResolveModeRouting

func ResolveModeRouting(baseModel, provider string, routing *ModeModelRouting) ModeRoutingResolution

ResolveModeRouting resolves the effective model and reasoning for the top-level agent from the mode's default routing.

func ResolveRoleModeRouting

func ResolveRoleModeRouting(
	baseModel, provider, roleName string,
	routing *ModeModelRouting,
) ModeRoutingResolution

ResolveRoleModeRouting resolves the effective model and reasoning for a specialist role. Priority: 1. mode role override 2. mode defaults

type ModeTextVerbosity

type ModeTextVerbosity string

ModeTextVerbosity is an SDK-native text verbosity label.

const (
	TextVerbosityLow    ModeTextVerbosity = "low"
	TextVerbosityMedium ModeTextVerbosity = "medium"
	TextVerbosityHigh   ModeTextVerbosity = "high"
)

type Model

type Model interface {
	// GetResponse sends a request and returns a complete response.
	GetResponse(ctx context.Context, req ModelRequest) (*ModelResponse, error)

	// StreamResponse sends a request and returns a streaming response.
	StreamResponse(ctx context.Context, req ModelRequest) (*ModelStream, error)

	// GetRetryAdvice determines whether a failed call should be retried.
	GetRetryAdvice(err error) *ModelRetryAdvice

	// CalculateCost returns the USD cost for the given usage.
	CalculateCost(usage Usage) float64

	// Provider returns the provider name ("anthropic" or "openai").
	Provider() string
}

Model is the provider-agnostic interface for LLM interaction. Implementations exist for Anthropic and OpenAI.

type ModelBehaviorError

type ModelBehaviorError struct {
	Message string
	Model   string
}

ModelBehaviorError indicates the model produced invalid or unexpected output.

func (*ModelBehaviorError) Error

func (e *ModelBehaviorError) Error() string

type ModelIdentity

type ModelIdentity struct {
	Raw       string
	Provider  string
	Canonical string
}

func NormalizeModelIdentity

func NormalizeModelIdentity(raw string, provider string) ModelIdentity

type ModelNameNormalizer added in v0.0.8

type ModelNameNormalizer interface {
	NormalizeModelName(name string) string
}

ModelNameNormalizer is an optional ModelProvider extension. Providers that route by model-name prefix implement it to report the model name that should be sent in API requests after routing.

type ModelProvider

type ModelProvider interface {
	// GetModel returns a Model for the given name.
	// The name may be a bare model identifier (e.g. "claude-sonnet-4-6")
	// or include a provider prefix (e.g. "anthropic/claude-sonnet-4-6").
	GetModel(name string) (Model, error)

	// Close releases any resources held by this provider.
	Close() error
}

ModelProvider resolves model name strings to Model implementations. This is the extension point for adding new LLM providers.

type ModelRequest

type ModelRequest struct {
	Model               string
	Instructions        string
	Input               []RunItem
	Tools               []Tool
	Settings            ModelSettings
	OutputSchema        *OutputSchema
	CompactionThreshold int
}

ModelRequest contains everything needed for a model call.

type ModelResponse

type ModelResponse struct {
	Items     []RunItem
	Usage     Usage
	Raw       any     // provider-specific raw response for debugging
	CostUSD   float64 // estimated cost in USD (set by runner after model returns)
	CostKnown bool    // whether cost estimate is considered reliable
}

ModelResponse is the complete response from a model call.

func (*ModelResponse) ToRunItems

func (r *ModelResponse) ToRunItems() []RunItem

ToRunItems returns the items from this response.

type ModelRetryAdvice

type ModelRetryAdvice struct {
	ShouldRetry  bool
	RetryAfterMS int64
	Reason       string
}

ModelRetryAdvice is returned by Model.GetRetryAdvice to indicate whether a failed call should be retried.

type ModelSettings

type ModelSettings struct {
	Temperature       *float64 `json:"temperature,omitempty"`
	MaxTokens         int      `json:"max_tokens,omitempty"`
	TopP              *float64 `json:"top_p,omitempty"`
	ToolChoice        string   `json:"tool_choice,omitempty"` // "auto", "none", "required", or specific tool name
	ParallelToolCalls *bool    `json:"parallel_tool_calls,omitempty"`
	ThinkingBudget    int      `json:"thinking_budget,omitempty"`
	ReasoningEffort   string   `json:"reasoning_effort,omitempty"` // "minimal", "low", "medium", "high", "xhigh"
	TextVerbosity     string   `json:"text_verbosity,omitempty"`   // "low", "medium", "high"
	StopSequences     []string `json:"stop_sequences,omitempty"`
}

ModelSettings configures model behavior.

func ModeReasoningSettings

func ModeReasoningSettings(level any) ModelSettings

ModeReasoningSettings converts a reasoning level into concrete provider settings. The budgets stay below the default Anthropic max token limit so "high" reasoning still leaves room for the final answer.

func ModeRoutingSettings

func ModeRoutingSettings(reasoning any, verbosity any) ModelSettings

ModeRoutingSettings converts mode routing behavior knobs into provider settings for a single model request.

func ModeTextVerbositySettings

func ModeTextVerbositySettings(level any) ModelSettings

ModeTextVerbositySettings converts a verbosity level into concrete OpenAI Responses text.verbosity settings.

func (ModelSettings) Merge

func (s ModelSettings) Merge(other ModelSettings) ModelSettings

Merge returns a new ModelSettings with overrides from other applied. Non-zero/non-nil values in other take precedence.

type ModelStream

type ModelStream struct {
	Events <-chan ModelStreamEvent
	// contains filtered or unexported fields
}

ModelStream provides streaming access to a model response.

func NewModelStream

func NewModelStream(events <-chan ModelStreamEvent, done chan *ModelResponse) *ModelStream

func (*ModelStream) Final

func (s *ModelStream) Final() *ModelResponse

Final blocks until the stream completes and returns the full response.

type ModelStreamEvent

type ModelStreamEvent struct {
	Type     ModelStreamEventType
	Delta    string         // for Delta events
	Item     *RunItem       // for ItemDone events
	Response *ModelResponse // for Complete events
	Error    error          // for Error events
}

ModelStreamEvent is a single event from a streaming model call.

type ModelStreamEventType

type ModelStreamEventType int

ModelStreamEventType identifies the kind of model stream event.

const (
	ModelStreamDelta          ModelStreamEventType = iota // partial text/tool content
	ModelStreamItemDone                                   // complete item ready
	ModelStreamComplete                                   // stream finished
	ModelStreamError                                      // terminal stream error
	ModelStreamReasoningDelta                             // partial reasoning/thinking content
)

type ModelUsageEntry

type ModelUsageEntry struct {
	InputTokens              int64 `json:"input_tokens"`
	OutputTokens             int64 `json:"output_tokens"`
	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
}

ModelUsageEntry holds per-model token usage.

type MultiProvider

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

MultiProvider dispatches model requests to registered providers by prefix.

Model names may be prefixed with a provider name and a slash:

"anthropic/claude-sonnet-4-6" → AnthropicProvider with model "claude-sonnet-4-6"
"openai/gpt-4.1"             → OpenAIProvider with model "gpt-4.1"
"gpt-4.1"                    → default provider (openai) with model "gpt-4.1"

func NewMultiProvider

func NewMultiProvider(defaultPrefix string) *MultiProvider

NewMultiProvider creates a MultiProvider with the given default prefix. The default prefix is used when a model name contains no "/" separator.

func (*MultiProvider) Close

func (mp *MultiProvider) Close() error

Close releases resources for all registered providers.

func (*MultiProvider) GetModel

func (mp *MultiProvider) GetModel(name string) (Model, error)

GetModel parses the model name for a provider prefix and delegates to the appropriate registered provider.

func (*MultiProvider) NormalizeModelName added in v0.0.8

func (mp *MultiProvider) NormalizeModelName(name string) string

NormalizeModelName strips the provider prefix only when it routes to a registered provider, preserving model IDs that contain "/" as part of the ID (e.g. "openrouter/anthropic/claude-..." → "anthropic/claude-...", while an unregistered "anthropic/claude-..." prefix stays intact).

func (*MultiProvider) Register

func (mp *MultiProvider) Register(prefix string, p ModelProvider)

Register adds a provider under the given prefix.

type MultiTracingProcessor

type MultiTracingProcessor struct {
	Processors []TracingProcessor
}

MultiTracingProcessor fans out events to multiple processors.

func (*MultiTracingProcessor) Flush

func (m *MultiTracingProcessor) Flush()

func (*MultiTracingProcessor) OnSpanEnd

func (m *MultiTracingProcessor) OnSpanEnd(s *Span)

func (*MultiTracingProcessor) OnSpanStart

func (m *MultiTracingProcessor) OnSpanStart(s *Span)

func (*MultiTracingProcessor) OnTraceEnd

func (m *MultiTracingProcessor) OnTraceEnd(t *Trace)

func (*MultiTracingProcessor) OnTraceStart

func (m *MultiTracingProcessor) OnTraceStart(t *Trace)

type NestedRunConfig

type NestedRunConfig struct {
	MaxTurns                  int
	CompactionConfig          CompactionConfig
	CompactionRecorder        func(tokensBefore, tokensAfter int, summary string)
	CompactionFailureReporter func(scope, reason string, tokensBefore, tokensAfter int)
	HandoffHistory            HandoffHistoryConfig
	ToolAccessLevel           ToolAccessLevel
	ToolPolicy                *ToolPolicy
	ToolInputGuardrails       []ToolInputGuardrail
	ToolOutputGuardrails      []ToolOutputGuardrail
	UntrustedToolOutputs      *bool
	MaxToolOutputBytes        int
}

func NestedRunConfigFromContext

func NestedRunConfigFromContext(ctx context.Context) (NestedRunConfig, bool)

type NoOpAgentHooks

type NoOpAgentHooks struct{}

NoOpAgentHooks is an AgentHooks implementation that does nothing.

func (NoOpAgentHooks) OnEnd

func (NoOpAgentHooks) OnEnd(_ *RunContext, _ *Agent, _ any)

func (NoOpAgentHooks) OnHandoff

func (NoOpAgentHooks) OnHandoff(_ *RunContext, _ *Agent, _ *Agent)

func (NoOpAgentHooks) OnStart

func (NoOpAgentHooks) OnStart(_ *RunContext, _ *Agent)

func (NoOpAgentHooks) OnToolEnd

func (NoOpAgentHooks) OnToolEnd(_ *RunContext, _ *Agent, _ Tool, _ ToolCallData, _ ToolResult)

func (NoOpAgentHooks) OnToolStart

func (NoOpAgentHooks) OnToolStart(_ *RunContext, _ *Agent, _ Tool, _ ToolCallData)

type NoOpRunHooks

type NoOpRunHooks struct{}

NoOpRunHooks is a RunHooks implementation that does nothing.

func (NoOpRunHooks) OnAgentEnd

func (NoOpRunHooks) OnAgentEnd(_ *RunContext, _ *Agent, _ any)

func (NoOpRunHooks) OnAgentStart

func (NoOpRunHooks) OnAgentStart(_ *RunContext, _ *Agent)

func (NoOpRunHooks) OnHandoff

func (NoOpRunHooks) OnHandoff(_ *RunContext, _ *Agent, _ *Agent)

func (NoOpRunHooks) OnLLMEnd

func (NoOpRunHooks) OnLLMEnd(_ *RunContext, _ *Agent, _ *ModelResponse)

func (NoOpRunHooks) OnLLMStart

func (NoOpRunHooks) OnLLMStart(_ *RunContext, _ *Agent)

func (NoOpRunHooks) OnToolEnd

func (NoOpRunHooks) OnToolEnd(_ *RunContext, _ *Agent, _ Tool, _ ToolCallData, _ ToolResult)

func (NoOpRunHooks) OnToolStart

func (NoOpRunHooks) OnToolStart(_ *RunContext, _ *Agent, _ Tool, _ ToolCallData)

type NoOpTracingProcessor

type NoOpTracingProcessor struct{}

NoOpTracingProcessor is a TracingProcessor that does nothing.

func (NoOpTracingProcessor) Flush

func (NoOpTracingProcessor) Flush()

func (NoOpTracingProcessor) OnSpanEnd

func (NoOpTracingProcessor) OnSpanEnd(*Span)

func (NoOpTracingProcessor) OnSpanStart

func (NoOpTracingProcessor) OnSpanStart(*Span)

func (NoOpTracingProcessor) OnTraceEnd

func (NoOpTracingProcessor) OnTraceEnd(*Trace)

func (NoOpTracingProcessor) OnTraceStart

func (NoOpTracingProcessor) OnTraceStart(*Trace)

type OutputGuardrail

type OutputGuardrail struct {
	Name string
	Fn   func(ctx *RunContext, agent *Agent, output any) (*GuardrailResult, error)
}

OutputGuardrail validates model output before it's returned.

type OutputGuardrailResult

type OutputGuardrailResult struct {
	GuardrailName     string
	Output            any
	TripwireTriggered bool
}

OutputGuardrailResult is the outcome of an output guardrail check.

type OutputGuardrailTripwireTriggered

type OutputGuardrailTripwireTriggered struct {
	GuardrailName string
	Result        GuardrailResult
}

OutputGuardrailTripwireTriggered is returned when an output guardrail's tripwire fires.

func (*OutputGuardrailTripwireTriggered) Error

type OutputSchema

type OutputSchema struct {
	Name    string          `json:"name"`
	Schema  json.RawMessage `json:"schema"`
	Strict  bool            `json:"strict"`
	ParseFn func(raw string) (any, error)
}

OutputSchema defines a structured output format for an Agent.

func NewOutputSchema

func NewOutputSchema(name string, schema json.RawMessage) *OutputSchema

NewOutputSchema creates a new output schema with strict validation enabled.

func (*OutputSchema) Validate

func (s *OutputSchema) Validate(raw string) (any, error)

Validate checks that raw JSON conforms to the schema by attempting to parse it. Returns the parsed value on success, or an error describing the validation failure.

type PlatformHooks

type PlatformHooks struct {
	Tracker     *ProgressTracker
	EventStream *EventStream
	Turn        int // current conversation turn, set by caller
	// Activity optionally tracks file operations for parent visibility.
	// Set on child hooks to let the parent query sub-agent activity.
	Activity *SubAgentActivity
	// contains filtered or unexported fields
}

PlatformHooks bridges the Runner lifecycle to RunProgress and EventWriter. Content events go to EventWriter; structural/metrics data goes to OTel spans through TracingProcessor and snapshots through RunProgress.

func NewPlatformHooks

func NewPlatformHooks(tracker *ProgressTracker, es *EventStream) *PlatformHooks

NewPlatformHooks creates a PlatformHooks bridging to the given tracker and event stream.

func (*PlatformHooks) OnAgentEnd

func (h *PlatformHooks) OnAgentEnd(_ *RunContext, agent *Agent, _ any)

func (*PlatformHooks) OnAgentStart

func (h *PlatformHooks) OnAgentStart(_ *RunContext, agent *Agent)

func (*PlatformHooks) OnHandoff

func (h *PlatformHooks) OnHandoff(_ *RunContext, from *Agent, to *Agent)

func (*PlatformHooks) OnLLMEnd

func (h *PlatformHooks) OnLLMEnd(_ *RunContext, agent *Agent, response *ModelResponse)

func (*PlatformHooks) OnLLMStart

func (h *PlatformHooks) OnLLMStart(_ *RunContext, _ *Agent)

func (*PlatformHooks) OnToolEnd

func (h *PlatformHooks) OnToolEnd(runCtx *RunContext, agent *Agent, tool Tool, call ToolCallData, result ToolResult)

func (*PlatformHooks) OnToolStart

func (h *PlatformHooks) OnToolStart(runCtx *RunContext, agent *Agent, tool Tool, call ToolCallData)

type ProgressEvent

type ProgressEvent struct {
	Timestamp time.Time `json:"timestamp"`
	EventType string    `json:"eventType"`
	Summary   string    `json:"summary"`
}

ProgressEvent is a high-level event stored in the ring buffer.

type ProgressSnapshot

type ProgressSnapshot struct {
	CurrentStep              string
	SessionNumber            int32
	LastActivity             string
	AgentCount               int32
	ToolCallCount            int32
	CostUsd                  float64
	InputTokens              int64
	OutputTokens             int64
	CacheReadInputTokens     int64
	CacheCreationInputTokens int64
	ModelUsage               map[string]ModelUsageEntry
	ApiRetries               int32
	Events                   []ProgressEvent
}

ProgressSnapshot is a point-in-time copy of the tracker state for host status updates.

type ProgressTracker

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

ProgressTracker accumulates state from the native agent loop. Metrics (cost, tokens, tool calls) are tracked in memory and exposed via Snapshot() for host status updates. Content events go through EventStream; structural observability through OTel spans.

func NewChildTracker

func NewChildTracker(parent *ProgressTracker, taskID string) *ProgressTracker

NewChildTracker creates a child tracker for a subagent. It has its own counters (doesn't affect parent's snapshot).

func NewProgressTracker

func NewProgressTracker(opts ...TrackerOption) *ProgressTracker

NewProgressTracker creates a tracker that aggregates run metrics.

func (*ProgressTracker) CurrentStep

func (t *ProgressTracker) CurrentStep() string

CurrentStep returns the currently inferred workflow step.

func (*ProgressTracker) DrainPendingEvents

func (t *ProgressTracker) DrainPendingEvents() []ProgressEvent

DrainPendingEvents returns and clears pending session-level events.

func (*ProgressTracker) LastAssistantText

func (t *ProgressTracker) LastAssistantText() string

LastAssistantText returns the full text from the most recent assistant message.

func (*ProgressTracker) LastAssistantThinking

func (t *ProgressTracker) LastAssistantThinking() string

LastAssistantThinking returns the thinking content from the most recent assistant message.

func (*ProgressTracker) RecordAPIRetry

func (t *ProgressTracker) RecordAPIRetry(errorCode string, retryAfterMS int64, attempt int32, maxRetries int32)

RecordAPIRetry logs an API retry event.

func (*ProgressTracker) RecordAssistantText

func (t *ProgressTracker) RecordAssistantText(text string)

RecordAssistantText logs assistant text content.

func (*ProgressTracker) RecordAssistantThinking

func (t *ProgressTracker) RecordAssistantThinking(thinking string)

RecordAssistantThinking logs assistant thinking content.

func (*ProgressTracker) RecordCompactBoundary

func (t *ProgressTracker) RecordCompactBoundary(tokensBefore, tokensAfter int, _ string)

RecordCompactBoundary logs a context compaction event with token counts.

func (*ProgressTracker) RecordHookDecision

func (t *ProgressTracker) RecordHookDecision(event HookEvent, result HookResult)

RecordHookDecision logs the result of dispatching a pre/post-tool hook.

func (*ProgressTracker) RecordLLMUsage

func (t *ProgressTracker) RecordLLMUsage(model string, costUSD float64, usage Usage)

RecordLLMUsage accumulates cost and token counts from a single LLM call so the tracker's Snapshot() stays current between session-complete events.

func (*ProgressTracker) RecordLifecycleEvent

func (t *ProgressTracker) RecordLifecycleEvent(eventType string, message string)

RecordLifecycleEvent logs a normalized lifecycle event.

func (*ProgressTracker) RecordSessionComplete

func (t *ProgressTracker) RecordSessionComplete(model string, costUSD float64, numTurns int, usage Usage, duration time.Duration, stopReason string)

RecordSessionComplete logs session completion with final metrics. Note: cost/token accumulation is handled per-call by RecordLLMUsage; this method only emits the session_complete event and OTel span.

func (*ProgressTracker) RecordSubagentCompleted

func (t *ProgressTracker) RecordSubagentCompleted(taskID, status, summary string, costUSD float64, numTurns int, usage Usage, stopReason string, filesRead, filesWritten []string)

RecordSubagentCompleted logs subagent completion.

func (*ProgressTracker) RecordSubagentProgress

func (t *ProgressTracker) RecordSubagentProgress(taskID string, toolCount int32, totalTokens int64, durationMS int64, lastToolName string)

RecordSubagentProgress logs subagent progress (metrics only).

func (*ProgressTracker) RecordSubagentStarted

func (t *ProgressTracker) RecordSubagentStarted(taskID, toolUseID, description, subagentType, model, isolation, prompt string)

RecordSubagentStarted logs a subagent launch.

func (*ProgressTracker) RecordSystemInit

func (t *ProgressTracker) RecordSystemInit(model, cwd string, toolsList []string, maxTurns int, mcpServers []string, permissionMode agentpolicy.PermissionMode)

RecordSystemInit logs a system initialization event.

func (*ProgressTracker) RecordToolResult

func (t *ProgressTracker) RecordToolResult(toolUseID, toolName, output string, isError bool, durationMS int64, agentName string, parentCallID string)

RecordToolResult logs a tool execution result.

func (*ProgressTracker) RecordToolUse

func (t *ProgressTracker) RecordToolUse(toolName, inputSummary, toolUseID string, turn int, rawInput string, agentName string, parentCallID string)

RecordToolUse logs a tool invocation.

func (*ProgressTracker) SessionNumber

func (t *ProgressTracker) SessionNumber() int32

SessionNumber returns the current session number.

func (*ProgressTracker) SetRootSpanID

func (t *ProgressTracker) SetRootSpanID(id string)

SetRootSpanID sets the parent span ID for all record.go-emitted spans. Call this when the agentrun-level trace is created and update when phases change.

func (*ProgressTracker) SetSession

func (t *ProgressTracker) SetSession(num int32, step string)

SetSession sets the session number and initial step.

func (*ProgressTracker) SetStep

func (t *ProgressTracker) SetStep(step string)

SetStep sets the current step.

func (*ProgressTracker) SetTracingProcessor

func (t *ProgressTracker) SetTracingProcessor(tp TracingProcessor)

SetTracingProcessor sets the OTel tracing processor for structural span emission.

func (*ProgressTracker) Snapshot

func (t *ProgressTracker) Snapshot() ProgressSnapshot

Snapshot returns a point-in-time copy of the tracker state.

func (*ProgressTracker) WriteResult

func (t *ProgressTracker) WriteResult(status, prURL, errMsg, failedStep string)

WriteResult records a terminal result summary for compatibility with hosts that use the progress tracker as their status source.

type ReasoningData

type ReasoningData struct {
	ID               string `json:"id,omitempty"`
	Text             string `json:"text,omitempty"`
	Signature        string `json:"signature,omitempty"`
	RedactedData     string `json:"redacted_data,omitempty"`
	EncryptedContent string `json:"encrypted_content,omitempty"`
}

ReasoningData holds model reasoning/thinking content.

type RetryBackoffSettings

type RetryBackoffSettings struct {
	InitialDelayMS int
	MaxDelayMS     int
	Multiplier     float64
}

RetryBackoffSettings controls exponential backoff.

type RetryPolicy

type RetryPolicy struct {
	MaxRetries int
	Backoff    RetryBackoffSettings
}

RetryPolicy configures automatic retry behavior for model calls.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns a sensible default retry policy.

func (*RetryPolicy) DelayForAttempt

func (p *RetryPolicy) DelayForAttempt(attempt int) time.Duration

DelayForAttempt calculates the backoff delay for a given retry attempt (0-indexed).

type RetrySpanData

type RetrySpanData struct {
	ErrorCode    string
	RetryAfterMS int64
	Attempt      int32
	MaxRetries   int32
}

RetrySpanData records data about an API retry.

type RunConfig

type RunConfig struct {
	MaxTurns         int           // default 100
	SubAgentMaxTurns int           // default 50 for nested specialist runs
	Hooks            RunHooks      // run-level lifecycle hooks
	ModelSettings    ModelSettings // override agent's model settings
	ModelOverride    string        // override agent's model name
	FallbackModels   []string      // ordered cross-provider fallback models for failed model calls
	TracingDisabled  bool
	TracingProcessor TracingProcessor // export spans to external systems

	// Trace, if set, is used instead of creating a new trace per Run().
	// This allows multiple Run() calls (e.g. across phases) to share a single
	// OTel trace so all spans appear in one waterfall.
	Trace *Trace

	// ParentSpanID is the span under which runner-created spans (generation,
	// function, handoff) are nested. Typically set to the current phase span ID.
	// Falls back to Trace.ID if empty.
	ParentSpanID string

	ImmediateInputPoller      ImmediateInputPoller
	CompactionConfig          CompactionConfig
	CompactionModelResolver   CompactionModelResolver
	CompactionRecorder        func(tokensBefore, tokensAfter int, summary string)
	CompactionFailureReporter func(scope, reason string, tokensBefore, tokensAfter int)
	CompactionCarryForward    func(ctx context.Context) string
	HandoffHistory            HandoffHistoryConfig

	// Tool guardrails — per-tool-call validation (distinct from agent-level guardrails).
	ToolInputGuardrails  []ToolInputGuardrail
	ToolOutputGuardrails []ToolOutputGuardrail

	// WorkDir is the working directory for tool execution (bash cwd, path resolution).
	// Typically set to the cloned repo directory so all tools operate inside the repo.
	WorkDir string

	// ErrorHandler is called when the run encounters an error. If set, the handler
	// decides whether to retry, abort, or continue. If nil, errors abort immediately.
	ErrorHandler RunErrorHandler

	// RetryPolicy optionally retries model-call errors. Provider retry advice
	// and ErrorHandler still run; this policy is an SDK-level fallback.
	RetryPolicy *RetryPolicy

	// AdditionalInstructions are appended to the agent instructions for this run.
	AdditionalInstructions string
	// ModeInstructions is a deprecated alias for AdditionalInstructions.
	// It is retained so operator-era callers keep working.
	ModeInstructions string

	WorkingStateContext    string          // durable working-state summary appended to compaction carry-forward
	ToolAccessLevel        ToolAccessLevel // controls tool access tier (full/read-only)
	ToolPolicy             *ToolPolicy     // optional approval and timeout policy applied to tools
	MaxConcurrentSubAgents int             // 0 = unlimited
	ForceFinalSummaryTurn  bool            // reserve the final turn for a no-tool summary instead of hard-failing

	// RequireCompletionConfirmation bounces the model's first final answer
	// back with a verification prompt; only a second consecutive final answer
	// ends the run. Any tool call or handoff in between resets the
	// confirmation. Prevents premature completion on long autonomous tasks
	// (Terminus 2 double-confirm pattern).
	RequireCompletionConfirmation bool

	// PlanRecitation, when set, is invoked before every model request and its
	// non-empty return value is appended as the final input message of that
	// request only — it is never persisted to run history. Reciting the
	// current plan/goals at the context tail keeps them in the model's
	// high-attention window (the todo.md recitation pattern) while leaving
	// the cache-stable instruction prefix and append-only history untouched.
	PlanRecitation func(ctx context.Context) string

	// ConsecutiveToolErrorLimit escalates when this many consecutive tool
	// turns produce only errors: the runner injects a corrective note telling
	// the model to change approach or report the blocker (the 12-factor
	// three-strike rule). 0 uses DefaultConsecutiveToolErrorLimit; negative
	// disables escalation.
	ConsecutiveToolErrorLimit int

	// StopGate is a deterministic finalization gate. When set, it runs on
	// every candidate final answer; returning ok=false blocks finalization
	// and feeds the feedback back to the model. After StopGateMaxBlocks
	// consecutive blocks (default DefaultStopGateMaxBlocks) the gate is
	// bypassed so a broken gate cannot loop forever (Claude Code stop-hook
	// pattern). Consecutive-block tracking resets when the model makes
	// progress with tools.
	StopGate func(ctx context.Context, finalText string) (ok bool, feedback string)
	// StopGateMaxBlocks caps consecutive StopGate blocks. 0 = default.
	StopGateMaxBlocks int

	// FinalAnswerVerifier, when set, reviews the candidate final answer once
	// per run (after StopGate passes). Non-empty feedback is injected and the
	// run continues instead of finalizing — typically wired to a read-only
	// critic sub-agent that tries to refute the result (adversarial
	// verification). Errors from the verifier are logged and ignored.
	FinalAnswerVerifier func(ctx context.Context, finalText string) (feedback string, err error)

	// MaxToolOutputBytes caps the tool result content fed back to the model as
	// next-turn input. Oversized outputs are middle-truncated (head and tail
	// preserved) so conclusions survive. Hooks, traces, and the event stream
	// still receive the raw output. 0 uses DefaultMaxToolOutputBytes; negative
	// disables the cap.
	MaxToolOutputBytes int

	// Debug enables verbose logging (full instructions, tool I/O, conversation items).
	Debug bool

	// UntrustedToolOutputs controls whether tool result content is wrapped with
	// "BEGIN UNTRUSTED TOOL OUTPUT … END UNTRUSTED TOOL OUTPUT" delimiters before
	// it becomes part of the next model turn's input. This mitigates prompt-
	// injection attacks where tool output (e.g. a fetched web page) attempts to
	// override the agent's instructions in subsequent turns.
	//
	// Semantics: nil (zero value) defaults to true (wrap) — secure by default.
	// Set to a pointer to false to opt out (e.g. for trusted in-process tools
	// where wrapping would interfere with downstream formatting). See
	// docs/security.md.
	UntrustedToolOutputs *bool

	// ModelCallTimeout bounds a single model generation attempt (including the
	// provider-native compaction call). A hung or unresponsive provider request
	// is cancelled after this duration so the attempt fails (and is then
	// retried/fallen-back per policy) instead of freezing the run forever — the
	// failure mode that previously required a kill -9. The timeout applies
	// per-attempt, so retries each get a fresh budget. 0 uses
	// DefaultModelCallTimeout; negative disables the per-call timeout.
	ModelCallTimeout time.Duration
}

RunConfig configures a single run of the Runner.

func (*RunConfig) EffectiveConsecutiveToolErrorLimit added in v0.0.9

func (c *RunConfig) EffectiveConsecutiveToolErrorLimit() int

EffectiveConsecutiveToolErrorLimit returns the escalation threshold, or 0 when escalation is disabled.

func (*RunConfig) EffectiveMaxToolOutputBytes added in v0.0.8

func (c *RunConfig) EffectiveMaxToolOutputBytes() int

EffectiveMaxToolOutputBytes returns the model-facing tool output cap. Returns 0 when the cap is disabled (negative configuration).

func (*RunConfig) EffectiveMaxTurns

func (c *RunConfig) EffectiveMaxTurns() int

EffectiveMaxTurns returns MaxTurns or DefaultMaxTurns if unset.

func (*RunConfig) EffectiveStopGateMaxBlocks added in v0.0.9

func (c *RunConfig) EffectiveStopGateMaxBlocks() int

EffectiveStopGateMaxBlocks returns the consecutive-block cap for StopGate.

func (*RunConfig) EffectiveSubAgentMaxTurns

func (c *RunConfig) EffectiveSubAgentMaxTurns() int

EffectiveSubAgentMaxTurns returns SubAgentMaxTurns or DefaultSubAgentMaxTurns if unset.

func (*RunConfig) IsReadOnly

func (c *RunConfig) IsReadOnly() bool

IsReadOnly returns true if the tool access level restricts to read-only tools.

func (*RunConfig) ShouldTagUntrustedToolOutputs

func (c *RunConfig) ShouldTagUntrustedToolOutputs() bool

ShouldTagUntrustedToolOutputs reports whether tool outputs should be tagged as untrusted before being fed back to the model. Defaults to true.

type RunContext

type RunContext struct {
	Usage     Usage
	Config    RunConfig
	WorkDir   string
	TaskName  string
	Namespace string
	// Tracing: processor exports spans; trace collects them for the run.
	TracingProcessor TracingProcessor
	Trace            *Trace
	// SpanParentID is the default parent for spans created inside this run
	// (generation, tool, handoff). Hosts may set this to a workflow/span ID.
	SpanParentID string
	// ToolAccessLevel is the tool access tier for this run.
	ToolAccessLevel ToolAccessLevel
	// contains filtered or unexported fields
}

RunContext holds runtime state for a single run. RunContext carries per-run SDK state for hooks, tools, tracing, and host metadata.

func (*RunContext) Context

func (c *RunContext) Context() context.Context

Context returns the underlying context.Context.

type RunErrorAction

type RunErrorAction int

RunErrorAction specifies what to do after an error.

const (
	ErrorActionRetry RunErrorAction = iota
	ErrorActionAbort
	ErrorActionContinue
)

type RunErrorData

type RunErrorData struct {
	Error error
	Agent *Agent
	Turn  int
}

RunErrorData provides context about a run-level error.

type RunErrorDetails

type RunErrorDetails struct {
	Error error
	Agent *Agent
	Turn  int
	Items []RunItem
}

RunErrorDetails provides structured context about a run-level error.

func (*RunErrorDetails) Unwrap

func (e *RunErrorDetails) Unwrap() error

type RunErrorHandler

type RunErrorHandler func(RunErrorData) RunErrorHandlerResult

RunErrorHandler decides what to do when a run encounters an error.

type RunErrorHandlerResult

type RunErrorHandlerResult struct {
	Action  RunErrorAction
	Message string
}

RunErrorHandlerResult is the decision from an error handler.

type RunHooks

type RunHooks interface {
	OnAgentStart(ctx *RunContext, agent *Agent)
	OnAgentEnd(ctx *RunContext, agent *Agent, output any)
	OnHandoff(ctx *RunContext, from *Agent, to *Agent)
	OnToolStart(ctx *RunContext, agent *Agent, tool Tool, call ToolCallData)
	OnToolEnd(ctx *RunContext, agent *Agent, tool Tool, call ToolCallData, result ToolResult)
	OnLLMStart(ctx *RunContext, agent *Agent)
	OnLLMEnd(ctx *RunContext, agent *Agent, response *ModelResponse)
}

RunHooks defines run-level lifecycle callbacks. These are called once per run, not per agent within a run.

type RunItem

type RunItem struct {
	Type          RunItemType
	Agent         *Agent
	Message       *MessageOutput
	ToolCall      *ToolCallData
	ToolOutput    *ToolOutputData
	HandoffCall   *HandoffCallData
	HandoffOutput *HandoffOutputData
	Reasoning     *ReasoningData
	Compaction    *CompactionData
	ToolApproval  *ToolApprovalData
}

RunItem is a single item produced during a run. Exactly one of the data fields is non-nil, matching Type.

func MaybeCompactHandoffInput

func MaybeCompactHandoffInput(items []RunItem, cfg HandoffHistoryConfig) ([]RunItem, int, int, bool, string)

MaybeCompactHandoffInput applies a narrower compaction policy for handoff payloads.

func MaybeCompactRunItems

func MaybeCompactRunItems(items []RunItem, cfg CompactionConfig) ([]RunItem, int, int, bool, string)

MaybeCompactRunItems reduces history size while preserving the original task framing and the most recent turn context.

func MaybeCompactRunItemsForRequest

func MaybeCompactRunItemsForRequest(items []RunItem, cfg CompactionConfig, requestOverheadTokens int) ([]RunItem, int, int, bool, string)

MaybeCompactRunItemsForRequest applies compaction against the estimated full request size, not just the persisted run items. Instructions, tool schemas, output reserve, and a safety buffer consume the same model context window.

func RemoveAllToolsHandoffInputFilter

func RemoveAllToolsHandoffInputFilter(input []RunItem, _ []RunItem) []RunItem

RemoveAllToolsHandoffInputFilter is a prebuilt handoff InputFilter that strips every tool call and tool output item from the history handed to the receiving agent. This keeps the target agent focused on the conversation without inheriting potentially large or irrelevant tool-call noise from the prior agent. Pass it via WithInputFilter.

type RunItemType

type RunItemType int

RunItemType identifies the kind of item in a run.

const (
	RunItemMessage RunItemType = iota
	RunItemToolCall
	RunItemToolOutput
	RunItemHandoffCall
	RunItemHandoffOutput
	RunItemReasoning
	RunItemToolApproval
	RunItemCompaction
)

type RunResult

type RunResult struct {
	FinalOutput                any // string or structured (parsed from OutputSchema)
	LastAgent                  *Agent
	NewItems                   []RunItem
	RawResponses               []ModelResponse
	InputGuardrailResults      []InputGuardrailResult
	OutputGuardrailResults     []OutputGuardrailResult
	ToolInputGuardrailResults  []ToolGuardrailResult
	ToolOutputGuardrailResults []ToolGuardrailResult
	Usage                      Usage
	Interruption               *Interruption   // non-nil if run was interrupted (e.g. approval gate); first of Interruptions
	Interruptions              []*Interruption // all pending interruptions from the turn (parallel tool calls can trigger several)
	LastResponseID             string          // last model response ID for continuation
}

RunResult is the outcome of a Runner.Run() call.

func (*RunResult) AllInterruptions added in v0.0.34

func (r *RunResult) AllInterruptions() []*Interruption

AllInterruptions returns every pending interruption from the run. It falls back to the singular Interruption field for results built before the Interruptions slice existed.

func (*RunResult) FinalText

func (r *RunResult) FinalText() string

FinalText returns the final output as a string, or empty if not a string output.

func (*RunResult) IsInterrupted

func (r *RunResult) IsInterrupted() bool

IsInterrupted returns true if the run was interrupted.

func (*RunResult) ToInputList

func (r *RunResult) ToInputList() []RunItem

ToInputList converts the result's items into a format suitable for resuming a run.

func (*RunResult) ToState

func (r *RunResult) ToState() *RunState

ToState converts the result into a RunState for resuming an interrupted run.

type RunState

type RunState struct {
	Items          []RunItem
	LastAgent      *Agent
	Interruption   *Interruption
	Interruptions  []*Interruption
	LastResponseID string
}

RunState captures enough state to resume an interrupted run.

type Runner

type Runner struct {

	// DefaultHooks are applied to sub-agent runs that don't specify their own hooks.
	// This ensures nested agent tool calls (e.g. agent_explore → Grep) appear in the
	// activity log alongside the parent's events.
	DefaultHooks RunHooks
	// contains filtered or unexported fields
}

Runner executes agents. It holds the Model implementation and orchestrates the run loop.

func NewRunner

func NewRunner(provider string) (*Runner, error)

NewRunner creates a Runner for the given provider ("anthropic" or "openai").

func NewRunnerWithModel

func NewRunnerWithModel(model Model) *Runner

NewRunnerWithModel creates a Runner with an existing Model implementation.

func NewRunnerWithProvider

func NewRunnerWithProvider(provider ModelProvider) *Runner

NewRunnerWithProvider creates a Runner backed by the given ModelProvider. The provider resolves model names to Model implementations on each call.

func (*Runner) CalculateCost

func (r *Runner) CalculateCost(usage Usage) float64

CalculateCost returns the USD cost estimate for the given usage. Safe to call regardless of how the runner was constructed.

func (*Runner) ExecuteApprovedTool

func (r *Runner) ExecuteApprovedTool(ctx context.Context, agent *Agent, call ToolCallData, cfg RunConfig) (RunItem, []ToolGuardrailResult, []ToolGuardrailResult, bool, error)

ExecuteApprovedTool resumes a previously interrupted approval request using the same runner preparation path as ordinary tool execution. The tool has already been approved by the host, so this method executes the matching tool directly while still applying access adapters, IsEnabled filtering, policy timeouts, hooks, tracing, and tool input/output guardrails.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, agent *Agent, input []RunItem, cfg RunConfig) (*RunResult, error)

Run executes an agent with the given input and returns the result. It runs the agent loop: LLM call → process response → tools/handoff/final → repeat.

func (*Runner) RunStreamed

func (r *Runner) RunStreamed(ctx context.Context, agent *Agent, input []RunItem, cfg RunConfig) *StreamedRunResult

RunStreamed executes an agent with streaming, returning events via a channel.

type SessionSpanData

type SessionSpanData struct {
	Model                    string
	CostUSD                  float64
	NumTurns                 int
	DurationMS               int64
	InputTokens              int64
	OutputTokens             int64
	CacheReadInputTokens     int64
	CacheCreationInputTokens int64
	StopReason               string
}

SessionSpanData records data about a complete session (cost, tokens, duration).

type Span

type Span struct {
	ID        string
	ParentID  string
	Name      string
	StartTime time.Time
	EndTime   time.Time
	Data      SpanData
}

Span represents a single operation within a trace.

func NewSpan

func NewSpan(name string, parentID string, data SpanData) *Span

NewSpan creates a new span.

func (*Span) DurationMS

func (s *Span) DurationMS() int64

DurationMS returns the span duration in milliseconds.

func (*Span) Finish

func (s *Span) Finish()

Finish marks the span as complete.

type SpanData

type SpanData interface {
	// contains filtered or unexported methods
}

SpanData is a marker interface for span-specific data.

type StopAtTools

type StopAtTools struct {
	ToolNames []string
}

StopAtTools configures tool names that cause the run to stop when called.

func (*StopAtTools) Contains

func (s *StopAtTools) Contains(name string) bool

Contains checks if the given tool name is in the stop list.

type StreamEvent

type StreamEvent struct {
	Type        StreamEventType
	RawResponse *ModelResponse
	Item        *RunItem
	NewAgent    *Agent
	Content     *ContentEvent
	SubAgent    *SubAgentStreamEvent
	Delta       string
	Name        string // e.g. "tool_call_item.created"
}

StreamEvent is emitted during streamed runs.

type StreamEventType

type StreamEventType int

StreamEventType identifies the kind of stream event.

const (
	StreamEventRawResponse StreamEventType = iota
	StreamEventRunItem
	StreamEventAgentUpdated
	StreamEventContent
	StreamEventSubAgent
)

type StreamedRunResult

type StreamedRunResult struct {
	Events <-chan StreamEvent
	// contains filtered or unexported fields
}

StreamedRunResult provides access to streaming events and the final result.

func (*StreamedRunResult) Err

func (s *StreamedRunResult) Err() error

Err returns the terminal error from a streamed run, if any. Call it after FinalResult or after Events has closed. FinalResult keeps the original non-breaking API shape, so this method is the error side channel for streamed runs.

func (*StreamedRunResult) FinalResult

func (s *StreamedRunResult) FinalResult() *RunResult

FinalResult blocks until the run completes and returns the result.

type SubAgentActivity

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

SubAgentActivity is a thread-safe ledger tracking file operations and tool activity for a sub-agent task. It is populated by PlatformHooks and read by the parent via subagent_status (detail="activity").

func NewSubAgentActivity

func NewSubAgentActivity() *SubAgentActivity

NewSubAgentActivity creates a new empty activity ledger.

func (*SubAgentActivity) BriefStatus

func (a *SubAgentActivity) BriefStatus() (currentStep, lastTool string, filesWritten int)

BriefStatus returns the summary fields for populating SubAgentTask.

func (*SubAgentActivity) RecordToolEnd

func (a *SubAgentActivity) RecordToolEnd(toolName, inputSummary string, isError bool, durationMS int64)

RecordToolEnd records that a tool has finished executing.

func (*SubAgentActivity) RecordToolStart

func (a *SubAgentActivity) RecordToolStart(toolName, inputSummary string)

RecordToolStart records that a tool has started executing.

func (*SubAgentActivity) Snapshot

func (a *SubAgentActivity) Snapshot(includeRecent bool) SubAgentActivitySnapshot

Snapshot returns a thread-safe copy of the activity state.

type SubAgentActivityEntry

type SubAgentActivityEntry struct {
	Timestamp  time.Time `json:"timestamp"`
	Tool       string    `json:"tool"`
	Summary    string    `json:"summary"` // file path, command, or pattern
	IsError    bool      `json:"is_error,omitempty"`
	DurationMS int64     `json:"duration_ms,omitempty"`
}

SubAgentActivityEntry records a single tool invocation by a sub-agent.

type SubAgentActivitySnapshot

type SubAgentActivitySnapshot struct {
	CurrentStep  string                  `json:"current_step,omitempty"`
	CurrentTool  string                  `json:"current_tool,omitempty"`
	CurrentInput string                  `json:"current_tool_input,omitempty"`
	FilesRead    []string                `json:"files_read"`
	FilesWritten []string                `json:"files_written"`
	RecentTools  []SubAgentActivityEntry `json:"recent_activity,omitempty"`
}

SubAgentActivitySnapshot is a point-in-time copy of activity state.

type SubAgentDependencyPolicy

type SubAgentDependencyPolicy string

SubAgentDependencyPolicy controls how a task treats terminal dependency status.

const (
	// SubAgentDependencyAllSuccess starts the task only when every dependency completed.
	SubAgentDependencyAllSuccess SubAgentDependencyPolicy = "all_success"
	// SubAgentDependencyAllTerminal starts the task once dependencies are terminal,
	// even if some failed or were cancelled.
	SubAgentDependencyAllTerminal SubAgentDependencyPolicy = "all_terminal"
)

func NormalizeSubAgentDependencyPolicy

func NormalizeSubAgentDependencyPolicy(policy SubAgentDependencyPolicy) SubAgentDependencyPolicy

NormalizeSubAgentDependencyPolicy maps empty/unknown policy values to the conservative default.

type SubAgentRegistry

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

SubAgentRegistry tracks async sub-agent tasks spawned by the orchestrator. Tasks run in managed goroutines and can be polled/waited on across turns.

func NewSubAgentRegistry

func NewSubAgentRegistry(cfg SubAgentRegistryConfig) *SubAgentRegistry

NewSubAgentRegistry creates a new registry for tracking async sub-agent tasks.

func (*SubAgentRegistry) Cancel

func (r *SubAgentRegistry) Cancel(taskID string) error

Cancel cancels a running task.

func (*SubAgentRegistry) CollectResult

func (r *SubAgentRegistry) CollectResult(taskID string) (*SubAgentTask, error)

CollectResult returns the result of a completed task.

func (*SubAgentRegistry) Configure

func (r *SubAgentRegistry) Configure(cfg SubAgentRegistryConfig)

Configure refreshes host/runtime wiring for future spawned sub-agents while preserving already tracked tasks. Hosts that rebuild runners per user turn should call this with the current turn's runner, hooks, policy, and agents before reusing a session-scoped registry.

func (*SubAgentRegistry) EmitActiveTaskStatuses

func (r *SubAgentRegistry) EmitActiveTaskStatuses(message string)

EmitActiveTaskStatuses emits compact progress snapshots for all non-terminal managed tasks. Hosts use these events to keep UIs fresh while the SDK waits for final-join results in code rather than asking the parent model to poll.

func (*SubAgentRegistry) FinalJoinSnapshot

func (r *SubAgentRegistry) FinalJoinSnapshot() (results []SubAgentTask, active []SubAgentTask)

FinalJoinSnapshot returns currently undelivered terminal results and active managed tasks without blocking. Terminal results returned by this method are marked delivered so they are injected into the parent exactly once.

func (*SubAgentRegistry) GetActivity

func (r *SubAgentRegistry) GetActivity(taskID string, includeRecent bool) (*SubAgentActivitySnapshot, error)

GetActivity returns an activity snapshot for a task.

func (*SubAgentRegistry) GetStatus

func (r *SubAgentRegistry) GetStatus(taskID string) (*SubAgentTask, error)

GetStatus returns the current status of a task.

func (*SubAgentRegistry) HasActiveTasks

func (r *SubAgentRegistry) HasActiveTasks() bool

HasActiveTasks returns true if any task is pending or running.

func (*SubAgentRegistry) HasPendingFinalJoinTasks

func (r *SubAgentRegistry) HasPendingFinalJoinTasks() bool

HasPendingFinalJoinTasks returns true if managed sub-agent supervision should still affect parent finalization: either a task is active, or a terminal result has not yet been delivered to the parent.

func (*SubAgentRegistry) ListTasks

func (r *SubAgentRegistry) ListTasks() []*SubAgentTask

ListTasks returns all tasks in insertion order.

func (*SubAgentRegistry) MarshalTaskList

func (r *SubAgentRegistry) MarshalTaskList() string

MarshalTaskList returns a JSON summary of all tasks.

func (*SubAgentRegistry) SendMessage

func (r *SubAgentRegistry) SendMessage(taskID, message string) error

SendMessage queues a parent steering message for an active sub-agent task. The child receives queued messages at the next interruptible runner boundary, before the next model request.

func (*SubAgentRegistry) SetAllowedAgents

func (r *SubAgentRegistry) SetAllowedAgents(allowed []string)

SetAllowedAgents restricts which agents can be spawned to only those in the allowed list. When allowed is nil/empty, all agents are available. Called per-phase so orchestrator phases can restrict which sub-agents are visible.

func (*SubAgentRegistry) SetCompactionConfig

func (r *SubAgentRegistry) SetCompactionConfig(cfg CompactionConfig)

SetCompactionConfig updates the compaction policy for future spawned sub-agents. The policy is captured at spawn time so long-running child tasks keep a stable context-management policy.

func (*SubAgentRegistry) SetMaxTurns

func (r *SubAgentRegistry) SetMaxTurns(maxTurns int)

SetMaxTurns updates the turn budget for future spawned sub-agents.

func (*SubAgentRegistry) SetToolAccessLevel

func (r *SubAgentRegistry) SetToolAccessLevel(level ToolAccessLevel)

SetToolAccessLevel updates the tool access level for future spawned sub-agents. Called per-phase so sub-agents inherit the correct level when the orchestrator phase changes (e.g., from read-only decompose to orchestrator execute).

func (*SubAgentRegistry) SpawnAsync

func (r *SubAgentRegistry) SpawnAsync(ctx context.Context, agentName, message string, toolAccessOverride ToolAccessLevel) (string, error)

SpawnAsync launches a sub-agent in a managed goroutine and returns the task ID. The sub-agent runs runner.Run() asynchronously. The caller can poll/wait for results. If toolAccessOverride is non-empty, it overrides the registry's default for this task (e.g., "read-only" for explore agents that should not modify files).

func (*SubAgentRegistry) SpawnAsyncWithOptions

func (r *SubAgentRegistry) SpawnAsyncWithOptions(ctx context.Context, agentName, message string, opts SubAgentSpawnOptions) (string, error)

SpawnAsyncWithOptions launches a sub-agent with dependency and context forwarding controls. Dependencies must be existing task IDs; use the subagent tool's tasks array when callers want to describe a whole DAG by logical keys in one call.

func (*SubAgentRegistry) WaitForAny

func (r *SubAgentRegistry) WaitForAny(ctx context.Context, timeoutMS int64) (*SubAgentTask, error)

WaitForAny blocks until any task changes state or the timeout expires. Returns the changed task or nil on timeout.

func (*SubAgentRegistry) WaitForTask

func (r *SubAgentRegistry) WaitForTask(ctx context.Context, taskID string, timeoutMS int64) (*SubAgentTask, error)

WaitForTask blocks until a specific task reaches a terminal status.

func (*SubAgentRegistry) WaitForTasks

func (r *SubAgentRegistry) WaitForTasks(ctx context.Context, taskIDs []string, timeoutMS int64) ([]SubAgentTask, error)

WaitForTasks blocks until every requested task reaches a terminal status.

func (*SubAgentRegistry) WaitForUndeliveredResults

func (r *SubAgentRegistry) WaitForUndeliveredResults(ctx context.Context) ([]SubAgentTask, error)

WaitForUndeliveredResults blocks until all currently active managed sub-agent tasks finish, then returns terminal results that have not already been delivered to the parent through CollectResult, FinalJoinSnapshot, or this method.

type SubAgentRegistryConfig

type SubAgentRegistryConfig struct {
	MaxConcurrent           int // 0 = unlimited
	Runner                  *Runner
	Agents                  map[string]*Agent // name → agent
	Tracker                 *ProgressTracker
	EventStream             *EventStream
	WorkDir                 string
	ToolAccessLevel         ToolAccessLevel
	ToolPolicy              *ToolPolicy
	CompactionConfig        CompactionConfig
	CompactionModelResolver CompactionModelResolver
	MaxTurns                int
}

SubAgentRegistryConfig configures the registry.

type SubAgentSpawnOptions

type SubAgentSpawnOptions struct {
	ToolAccessOverride       ToolAccessLevel
	DependsOn                []string
	DependencyPolicy         SubAgentDependencyPolicy
	IncludeDependencyResults *bool
}

SubAgentSpawnOptions configures an async sub-agent spawn.

type SubAgentStreamEvent

type SubAgentStreamEvent struct {
	TaskID            string
	AgentName         string
	Status            string
	Message           string
	ToolUseID         string
	ParentCallID      string
	DependsOn         []string
	WaitingOn         []string
	CurrentStep       string
	LastTool          string
	FilesWritten      int
	MessagesReceived  int
	LastParentMessage string
	ToolCount         int32
	Tokens            int64
	DurationMS        int64
	CostUSD           float64
	CostKnown         bool
	NumTurns          int32
	StopReason        string
	ResultText        string
}

SubAgentStreamEvent is the typed, first-class streamed view of sub-agent runtime progress. It is derived from ContentEvent subagent_status events.

func SubAgentStreamEventFromContentEvent

func SubAgentStreamEventFromContentEvent(ev ContentEvent) (*SubAgentStreamEvent, bool)

SubAgentStreamEventFromContentEvent extracts a typed sub-agent event from a content event. It returns false for non-subagent events.

type SubAgentTask

type SubAgentTask struct {
	ID                string                   `json:"id"`
	AgentName         string                   `json:"agent_name"`
	Status            SubAgentTaskStatus       `json:"status"`
	Message           string                   `json:"message"`
	StartedAt         time.Time                `json:"started_at"`
	Duration          time.Duration            `json:"duration,omitempty"`
	Result            string                   `json:"result,omitempty"`
	Error             string                   `json:"error,omitempty"`
	ToolCount         int32                    `json:"tool_count,omitempty"`
	Tokens            int64                    `json:"tokens,omitempty"`
	DependsOn         []string                 `json:"depends_on,omitempty"`
	WaitingOn         []string                 `json:"waiting_on,omitempty"`
	DependencyPolicy  SubAgentDependencyPolicy `json:"dependency_policy,omitempty"`
	MessagesReceived  int                      `json:"messages_received,omitempty"`
	LastParentMessage string                   `json:"last_parent_message,omitempty"`

	// Live activity fields populated from the activity ledger.
	CurrentStep  string `json:"current_step,omitempty"`
	LastTool     string `json:"last_tool,omitempty"`
	FilesWritten int    `json:"files_written,omitempty"`
}

SubAgentTask represents a sub-agent running asynchronously in a managed goroutine.

func (*SubAgentTask) IsTerminal

func (t *SubAgentTask) IsTerminal() bool

IsTerminal returns true if the task has reached a final state.

type SubAgentTaskStatus

type SubAgentTaskStatus string

SubAgentTaskStatus represents the lifecycle state of an async sub-agent task.

const (
	SubAgentTaskPending   SubAgentTaskStatus = "pending"
	SubAgentTaskWaiting   SubAgentTaskStatus = "waiting"
	SubAgentTaskRunning   SubAgentTaskStatus = "running"
	SubAgentTaskCompleted SubAgentTaskStatus = "completed"
	SubAgentTaskFailed    SubAgentTaskStatus = "failed"
	SubAgentTaskCancelled SubAgentTaskStatus = "cancelled"
)

type SubagentSpanData

type SubagentSpanData struct {
	TaskID       string
	Type         string // role name or type
	Description  string
	Model        string
	Status       string // initializing, running, completed, failed
	CostUSD      float64
	NumTurns     int
	TotalTokens  int64
	InputTokens  int64
	OutputTokens int64
	ToolCount    int32
	DurationMS   int64
	StopReason   string
	Isolation    string
	Prompt       string
	ResultText   string
	FilesRead    []string // files the subagent read
	FilesWritten []string // files the subagent modified
}

SubagentSpanData records data about a subagent lifecycle.

type Tool

type Tool interface {
	Name() string
	Description() string
	InputSchema() json.RawMessage
	Execute(ctx context.Context, input json.RawMessage, workDir string) (ToolResult, error)
	IsReadOnly() bool
	IsEnabled(ctx *RunContext) bool
	NeedsApproval() bool
	TimeoutSeconds() int
}

Tool is the interface for all tools available to agents.

func WrapWithPolicy

func WrapWithPolicy(t Tool, approval bool, timeout int) Tool

WrapWithPolicy wraps a tool with approval and timeout settings. If neither policy applies, it returns the original tool unchanged.

Approval semantics: when approval=true, NeedsApproval() returns true even for tools whose own implementation hardcodes NeedsApproval()=false (notably the signal tools in pkg/agentsdk/tools/signal/*: finish, plan, present_plan, question). The wrapper's approval flag is therefore an *override* — hosts that opt these tools into approval gating via tool policy will see approval prompts despite the inner tool's default. The reverse is not true: approval=false leaves the inner tool's NeedsApproval() decision intact.

type ToolAccessAdapter

type ToolAccessAdapter interface {
	ToolForAccess(level ToolAccessLevel) Tool
}

ToolAccessAdapter lets a host application provide a safer tool implementation for a specific access level.

type ToolAccessLevel

type ToolAccessLevel string

ToolAccessLevel controls which tools are available during a run.

const (
	ToolAccessLevelFull     ToolAccessLevel = "full"
	ToolAccessLevelReadOnly ToolAccessLevel = "read-only"
)

func NormalizeToolAccessLevel

func NormalizeToolAccessLevel(level ToolAccessLevel) ToolAccessLevel

NormalizeToolAccessLevel maps caller/user-facing access strings to the runner's two enforcement tiers. Empty means the historical default (full). Unknown non-empty values fail closed to read-only so a typo cannot silently grant write tools.

type ToolApprovalData

type ToolApprovalData struct {
	ToolName string          `json:"tool_name"`
	Input    json.RawMessage `json:"input"`
	CallID   string          `json:"call_id"`
	Approved bool            `json:"approved"`
}

ToolApprovalData records a tool approval request or response.

type ToolCallData

type ToolCallData struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

ToolCallData represents a tool invocation by the model.

type ToolGuardrailResult

type ToolGuardrailResult struct {
	GuardrailName     string
	ToolName          string
	Output            any
	TripwireTriggered bool
}

ToolGuardrailResult is the outcome of a per-tool guardrail check.

type ToolInputGuardrail

type ToolInputGuardrail struct {
	Name string
	Fn   func(ctx *RunContext, agent *Agent, tool Tool, input json.RawMessage) (*GuardrailResult, error)
}

ToolInputGuardrail validates a tool's input arguments before execution.

type ToolInputGuardrailTripwireTriggered

type ToolInputGuardrailTripwireTriggered struct {
	GuardrailName string
	ToolName      string
	Result        GuardrailResult
}

ToolInputGuardrailTripwireTriggered is returned when a tool input guardrail's tripwire fires.

func (*ToolInputGuardrailTripwireTriggered) Error

type ToolOutputData

type ToolOutputData struct {
	CallID  string `json:"call_id"`
	Content string `json:"content"`
	IsError bool   `json:"is_error,omitempty"`
}

ToolOutputData holds the result of a tool execution.

type ToolOutputGuardrail

type ToolOutputGuardrail struct {
	Name string
	Fn   func(ctx *RunContext, agent *Agent, tool Tool, result ToolResult) (*GuardrailResult, error)
}

ToolOutputGuardrail validates a tool's output after execution.

type ToolOutputGuardrailTripwireTriggered

type ToolOutputGuardrailTripwireTriggered struct {
	GuardrailName string
	ToolName      string
	Result        GuardrailResult
}

ToolOutputGuardrailTripwireTriggered is returned when a tool output guardrail's tripwire fires.

func (*ToolOutputGuardrailTripwireTriggered) Error

type ToolPolicy

type ToolPolicy struct {
	// ApprovalRequired indicates non-read-only tools need approval.
	ApprovalRequired bool
	// DefaultTimeout in seconds for all tool calls (0 = no timeout).
	DefaultTimeout int
}

ToolPolicy holds host-supplied approval and timeout settings.

type ToolResult

type ToolResult struct {
	Content     string
	IsError     bool
	ShouldPause bool // When true, the runner breaks so the outer loop can handle the event.
}

ToolResult is the outcome of a tool execution.

type ToolTimeoutError

type ToolTimeoutError struct {
	ToolName string
	Timeout  time.Duration
}

ToolTimeoutError is returned when a tool execution exceeds its timeout.

func (*ToolTimeoutError) Error

func (e *ToolTimeoutError) Error() string

type ToolUseBehavior

type ToolUseBehavior int

ToolUseBehavior controls what happens after tool calls complete.

const (
	// RunLLMAgain runs the LLM again with the tool results (default).
	RunLLMAgain ToolUseBehavior = iota
	// StopOnFirstTool returns immediately after the first tool result.
	StopOnFirstTool
)

type ToolsToFinalOutputResult

type ToolsToFinalOutputResult struct {
	IsFinalOutput bool
	Output        json.RawMessage
}

ToolsToFinalOutputResult indicates whether tool results should be treated as the final output.

type Trace

type Trace struct {
	ID        string
	Name      string
	StartTime time.Time
	EndTime   time.Time
	Spans     []*Span
	// contains filtered or unexported fields
}

Trace represents a complete execution trace (one Runner.Run invocation).

func NewTrace

func NewTrace(name string) *Trace

NewTrace creates a new trace.

func TraceFromContext

func TraceFromContext(ctx context.Context) *Trace

TraceFromContext extracts the active trace for nested runs.

func (*Trace) AddSpan

func (t *Trace) AddSpan(s *Span)

AddSpan appends a span to the trace.

func (*Trace) Finish

func (t *Trace) Finish()

Finish marks the trace as complete.

type TracingProcessor

type TracingProcessor interface {
	OnTraceStart(trace *Trace)
	OnTraceEnd(trace *Trace)
	OnSpanStart(span *Span)
	OnSpanEnd(span *Span)
	Flush()
}

TracingProcessor receives trace and span lifecycle events. Implement this to export traces to external systems.

func TracingProcessorFromContext

func TracingProcessorFromContext(ctx context.Context) TracingProcessor

TracingProcessorFromContext extracts the active tracing processor.

type TrackerOption

type TrackerOption func(*ProgressTracker)

TrackerOption configures a ProgressTracker.

func WithMaxToolResultBytes

func WithMaxToolResultBytes(n int) TrackerOption

WithMaxToolResultBytes sets the maximum size for tool result/input content in the event stream. Values <= 0 disable truncation.

func WithTracingProcessor

func WithTracingProcessor(tp TracingProcessor) TrackerOption

WithTracingProcessor sets the OTel tracing processor for emitting structural spans.

type Usage

type Usage struct {
	Requests          int   `json:"requests"`
	InputTokens       int64 `json:"input_tokens"`
	OutputTokens      int64 `json:"output_tokens"`
	CacheReadTokens   int64 `json:"cache_read_tokens,omitempty"`
	CacheCreateTokens int64 `json:"cache_create_tokens,omitempty"`
}

Usage tracks token consumption across model calls.

func (*Usage) Add

func (u *Usage) Add(other Usage)

Add merges another Usage into this one.

func (*Usage) TotalTokens

func (u *Usage) TotalTokens() int64

TotalTokens returns input + output tokens.

type UserError

type UserError struct {
	Message string
}

UserError indicates invalid user input.

func (*UserError) Error

func (e *UserError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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