Versions in this module Expand all Collapse all v0 v0.0.1 Aug 3, 2026 Changes in this version + const IssueMissing + const IssueType + const IssueUnknown + const IssueValue + const ResponseFormatJSONObject + const ResponseFormatJSONSchema + const ResponseFormatText + var ErrAlreadyRunning = errors.New("agent is already running") + var ErrBadContinuation = errors.New("cannot continue from this message role without queued messages") + var ErrContextOverflow = errors.New("context window overflow") + var ErrInjectNilMessage = errors.New("inject message is nil") + var ErrMaxTurns = errors.New("max turns reached") + var ErrNoMessages = errors.New("cannot continue: no messages in context") + var ErrNoModel = errors.New("no model configured") + var ErrProviderAuth = errors.New("provider auth") + var ErrProviderContentFilter = errors.New("provider content filter") + var ErrProviderNetwork = errors.New("provider network") + var ErrProviderOverloaded = errors.New("provider overloaded") + var ErrProviderQuota = errors.New("provider quota exhausted") + var ErrProviderRateLimit = errors.New("provider rate limit") + var ErrProviderStreamIdle = errors.New("provider stream idle") + var ErrProviderTimeout = errors.New("provider timeout") + var ErrRunsHeld = errors.New("agent runs are held") + var ErrStopGuard = errors.New("stop guard escalated: run terminated") + var ErrStreamPartial = errors.New("stream closed without done event") + var ErrToolValidation = errors.New("tool argument validation failed") + func AgentLoop(ctx context.Context, prompts []AgentMessage, agentCtx AgentContext, ...) <-chan Event + func AgentLoopContinue(ctx context.Context, agentCtx AgentContext, config LoopConfig) <-chan Event + func AssertMessageSequence(msgs []Message) error + func ClassifyProvider(err error) error + func ErrorKind(err error) string + func FailoverReason(err error) string + func IsContextOverflow(err error) bool + func IsFailoverEligible(err error) bool + func IsStreamIdleMessage(s string) bool + func ReactivateDeferred(tools []Tool, msgs []AgentMessage) + func ReportToolProgress(ctx context.Context, progress ProgressPayload) + func WithToolProgress(ctx context.Context, fn ToolProgressFunc) context.Context + type ActivityDescriber interface + ActivityDescription func(args json.RawMessage) string + type AfterTurnContext struct + Context AgentContext + Message AgentMessage + ToolResults []ToolResult + TurnIndex int + type AfterTurnHook func(context.Context, AfterTurnContext) error + type Agent struct + func NewAgent(opts ...AgentOption) *Agent + func (a *Agent) Abort() + func (a *Agent) AbortSilent() + func (a *Agent) BaselineContextUsage() *ContextUsage + func (a *Agent) BuildLLMMessages() ([]Message, error) + func (a *Agent) BuildLLMTools() []ToolSpec + func (a *Agent) ClearAllQueues() + func (a *Agent) ClearFollowUpQueue() + func (a *Agent) ClearSteeringQueue() + func (a *Agent) ContextSnapshot() *ContextSnapshot + func (a *Agent) ContextUsage() *ContextUsage + func (a *Agent) Continue(ctx context.Context) error + func (a *Agent) ExportMessages() []Message + func (a *Agent) FollowUp(msg AgentMessage) + func (a *Agent) HasFollowUps() bool + func (a *Agent) HasQueuedMessages() bool + func (a *Agent) HoldRuns() (release func()) + func (a *Agent) ImportMessages(msgs []Message) error + func (a *Agent) Inject(ctx context.Context, msg AgentMessage) (InjectResult, error) + func (a *Agent) Messages() []AgentMessage + func (a *Agent) Prompt(ctx context.Context, input string) error + func (a *Agent) PromptMessages(ctx context.Context, msgs ...AgentMessage) error + func (a *Agent) Reset() + func (a *Agent) SetContextWindow(n int) + func (a *Agent) SetMessageCommitter(fn func(AgentMessage) error) + func (a *Agent) SetMessages(msgs []AgentMessage) error + func (a *Agent) SetModel(m ChatModel) + func (a *Agent) SetPromptCacheKey(key string) + func (a *Agent) SetSystemBlocks(blocks []SystemBlock) + func (a *Agent) SetSystemPrompt(s string) + func (a *Agent) SetThinkingLevel(level ThinkingLevel) + func (a *Agent) SetTools(tools ...Tool) + func (a *Agent) State() AgentState + func (a *Agent) Steer(msg AgentMessage) + func (a *Agent) Subscribe(fn func(Event)) func() + func (a *Agent) TotalUsage() Usage + func (a *Agent) WaitForIdle() + type AgentContext struct + Messages []AgentMessage + SystemBlocks []SystemBlock + SystemPrompt string + Tools []Tool + type AgentMessage interface + Compact func(expect float64) (next AgentMessage, actual float64) + GetRole func() Role + GetTimestamp func() time.Time + HasToolCalls func() bool + Priority func() int + Raw func() AgentMessage + TextContent func() string + ThinkingContent func() string + ToMessage func() (message Message, include bool) + func Collect(events <-chan Event) ([]AgentMessage, error) + func ToAgentMessages(msgs []Message) []AgentMessage + type AgentOption func(*Agent) + func WithAbortMarkerText(inference, toolUse string) AgentOption + func WithAfterTurn(hook AfterTurnHook) AgentOption + func WithBeforeTurn(hook BeforeTurnHook) AgentOption + func WithCacheLastMessage(cacheControl string) AgentOption + func WithContextManager(mgr ContextManager) AgentOption + func WithLengthRecoveryPrompt(prompt string) AgentOption + func WithMaxRetries(n int) AgentOption + func WithMaxToolConcurrency(n int) AgentOption + func WithMaxToolErrors(n int) AgentOption + func WithMaxTurns(n int) AgentOption + func WithMessageCommitter(fn func(AgentMessage) error) AgentOption + func WithMiddlewares(mw ...ToolMiddleware) AgentOption + func WithModel(model ChatModel) AgentOption + func WithOnMessage(fn func(AgentMessage)) AgentOption + func WithPromptCacheKey(key string) AgentOption + func WithStopGuard(guard StopGuard) AgentOption + func WithSystemBlocks(blocks []SystemBlock) AgentOption + func WithSystemPrompt(prompt string) AgentOption + func WithThinkingLevel(level ThinkingLevel) AgentOption + func WithToolGate(gate ToolGate) AgentOption + func WithToolResultMessageFactory(factory func(ToolCall, ToolResult) AgentMessage) AgentOption + func WithTools(tools ...Tool) AgentOption + type AgentState struct + Error string + IsRunning bool + Messages []AgentMessage + PendingToolCalls map[string]struct{} + StreamMessage AgentMessage + SystemPrompt string + Tools []Tool + TotalUsage Usage + type BeforeTurnContext struct + Context AgentContext + TurnIndex int + type BeforeTurnHook func(context.Context, BeforeTurnContext) ([]AgentMessage, error) + type CallConfig struct + APIKey string + MaxTokens int + PromptCacheKey string + ResponseFormat *ResponseFormat + SessionID string + ThinkingBudget int + ThinkingLevel ThinkingLevel + ToolChoice any + func ResolveCallConfig(opts []CallOption) CallConfig + type CallOption func(*CallConfig) + func WithAPIKey(key string) CallOption + func WithCallPromptCacheKey(key string) CallOption + func WithCallSessionID(id string) CallOption + func WithJSONMode() CallOption + func WithJSONSchema(name, description string, schema any, strict bool) CallOption + func WithMaxTokens(tokens int) CallOption + func WithResponseFormat(format *ResponseFormat) CallOption + func WithThinking(level ThinkingLevel) CallOption + func WithThinkingBudget(tokens int) CallOption + func WithToolChoice(choice any) CallOption + type ChatModel interface + Generate func(ctx context.Context, messages []Message, tools []ToolSpec, opts ...CallOption) (*LLMResponse, error) + GenerateStream func(ctx context.Context, messages []Message, tools []ToolSpec, opts ...CallOption) (<-chan StreamEvent, error) + SupportsTools func() bool + type CompactReason string + const CompactReasonManual + const CompactReasonOverflow + const CompactReasonThreshold + type CompactionInfo struct + Committed bool + MessagesAfter int + MessagesBefore int + Reason CompactReason + Summarized bool + TokensAfter int + TokensBefore int + type ConcurrencySafeTool interface + ConcurrencySafe func(args json.RawMessage) bool + type ContentBlock struct + Image *ImageData + Text string + Thinking string + ToolCall *ToolCall + ToolName string + Type ContentType + func ImageBlock(data, mimeType string) ContentBlock + func ImageURLBlock(url string) ContentBlock + func TextBlock(text string) ContentBlock + func ThinkingBlock(thinking string) ContentBlock + func ToolCallBlock(tc ToolCall) ContentBlock + func ToolRefBlock(toolName string) ContentBlock + type ContentTool interface + ExecuteContent func(ctx context.Context, args json.RawMessage) ([]ContentBlock, error) + type ContentType string + const ContentImage + const ContentText + const ContentThinking + const ContentToolCall + const ContentToolRef + type ContextCommitResult struct + Changed bool + CompactedCount int + Compaction *CompactionInfo + KeptCount int + Messages []AgentMessage + SplitTurn bool + Usage *ContextUsage + type ContextDemand struct + Signal string + func CollectContextDemands(messages []AgentMessage) []ContextDemand + type ContextDemandProvider interface + ContextDemands func() []ContextDemand + type ContextEstimateFn func(msgs []AgentMessage) (tokens, usageTokens, trailingTokens int) + type ContextEstimator interface + EstimateContext func([]AgentMessage) (tokens, usageTokens, trailingTokens int) + type ContextItem struct + Reason string + Ref string + Representation string + func CollectContextItems(messages []AgentMessage) []ContextItem + type ContextItemProvider interface + ContextItems func() []ContextItem + type ContextKey struct + Identity string + Kind string + type ContextManager interface + Compact func(ctx context.Context, msgs []AgentMessage, reason CompactReason) (ContextCommitResult, error) + Project func(ctx context.Context, msgs []AgentMessage) (ContextProjection, error) + RecoverOverflow func(ctx context.Context, msgs []AgentMessage, cause error) (ContextRecoveryResult, error) + Snapshot func() *ContextSnapshot + Sync func(msgs []AgentMessage) + Usage func() *ContextUsage + type ContextOverflowError struct + Cause error + func (e *ContextOverflowError) Error() string + func (e *ContextOverflowError) Is(target error) bool + func (e *ContextOverflowError) Unwrap() error + type ContextProjection struct + CommitMessages []AgentMessage + Compaction *CompactionInfo + Messages []AgentMessage + ShouldCommit bool + Usage *ContextUsage + type ContextRecoveryResult struct + Changed bool + CommitMessages []AgentMessage + CompactedCount int + Compaction *CompactionInfo + KeptCount int + ShouldCommit bool + SplitTurn bool + Usage *ContextUsage + View []AgentMessage + type ContextSnapshot struct + ActiveMessages int + BaselineUsage *ContextUsage + ClearedToolResults int + Items []ContextItem + LastChanged bool + LastCompactedCount int + LastKeptCount int + LastSplitTurn bool + Scope string + SummaryMessages int + ToolMessages int + TranscriptMessages int + TrimmedTextBlocks int + Usage *ContextUsage + type ContextUsage struct + ContextWindow int + Percent float64 + Tokens int + TrailingTokens int + UsageTokens int + type ContextWindowProvider interface + ContextWindow func() int + type ContextWindowSetter interface + SetContextWindow func(n int) + type Cost struct + CacheRead float64 + CacheWrite float64 + Input float64 + Output float64 + Total float64 + func (c *Cost) Add(other *Cost) + type DeferActivator interface + Activate func(names ...string) + type DeferFilter interface + IsDeferred func(toolName string) bool + WasDeferred func(toolName string) bool + type DeltaKind string + const DeltaText + const DeltaThinking + const DeltaToolCall + type EndReason string + const EndReasonAborted + const EndReasonError + const EndReasonMaxTurns + const EndReasonStop + type Event struct + Args json.RawMessage + Compaction *CompactionInfo + ContextItems []ContextItem + Delta string + DeltaKind DeltaKind + Err error + IsError bool + Message AgentMessage + NewMessages []AgentMessage + Preview json.RawMessage + Progress *ProgressPayload + Result json.RawMessage + RetryInfo *RetryInfo + Summary *RunSummary + Tool string + ToolID string + ToolLabel string + ToolResults []ToolResult + Type EventType + UpdateKind ToolExecUpdateKind + type EventStream struct + func NewEventStream(source <-chan Event) *EventStream + func (s *EventStream) Done() <-chan struct{} + func (s *EventStream) Events() <-chan Event + func (s *EventStream) Result() ([]AgentMessage, error) + type EventType string + const EventAgentEnd + const EventAgentStart + const EventContextCompacted + const EventContextProjected + const EventError + const EventMessageEnd + const EventMessageStart + const EventMessageUpdate + const EventModelResponse + const EventRetry + const EventToolExecEnd + const EventToolExecStart + const EventToolExecUpdate + const EventTurnEnd + const EventTurnStart + type FuncTool struct + func NewFuncTool(name, description string, schema map[string]any, ...) *FuncTool + func (t *FuncTool) Description() string + func (t *FuncTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error) + func (t *FuncTool) Name() string + func (t *FuncTool) Schema() map[string]any + type GateDecision struct + Allowed bool + Reason string + UpdatedArgs json.RawMessage + type GateRequest struct + Call ToolCall + Preview json.RawMessage + Tool Tool + ToolLabel string + type ImageData struct + Data string + MimeType string + URL string + type InjectDisposition string + const InjectQueued + const InjectResumedIdleRun + const InjectSteeredCurrentRun + type InjectResult struct + Disposition InjectDisposition + type InterruptBehavior string + const InterruptBehaviorBlock + const InterruptBehaviorCancel + type InterruptBehaviorTool interface + InterruptBehavior func(args json.RawMessage) InterruptBehavior + type JSONSchema struct + Description string + Name string + Schema any + Strict *bool + type LLMRequest struct + Messages []Message + Tools []ToolSpec + type LLMResponse struct + Message Message + type LoopConfig struct + AbortMarkerText string + AbortMarkerToolText string + AfterTurn AfterTurnHook + BeforeTurn BeforeTurnHook + CacheLastMessage string + CommitContext func(msgs []AgentMessage, usage *ContextUsage) error + CommitMessage func(msg AgentMessage) error + ContextManager ContextManager + GetFollowUpMessages func() []AgentMessage + GetSteeringMessages func() []AgentMessage + LengthRecoveryPrompt string + MaxRetries int + MaxToolConcurrency int + MaxToolErrors int + MaxTurns int + Middlewares []ToolMiddleware + Model ChatModel + OnMessage func(msg AgentMessage) + PromptCacheKey string + ShouldEmitAbortMarker func() bool + StopAfterTool func(toolName string) bool + StopAfterToolResult func(toolName string, result json.RawMessage) bool + StopGuard StopGuard + ThinkingLevel ThinkingLevel + ToolGate ToolGate + ToolResultMessageFactory func(ToolCall, ToolResult) AgentMessage + type MaxTurnsError struct + Limit int + func (e *MaxTurnsError) Error() string + func (e *MaxTurnsError) Is(target error) bool + type Message struct + Content []ContentBlock + Metadata map[string]any + Role Role + StopReason StopReason + Timestamp time.Time + Usage *Usage + func AbortMsg(text, phase string) Message + func CollectMessages(msgs []AgentMessage) []Message + func RepairMessageSequence(msgs []Message) []Message + func SystemMsg(text string) Message + func ToMessages(messages []AgentMessage) []Message + func ToolResultMsg(toolCallID string, content json.RawMessage, isError bool) Message + func UserMsg(text string) Message + func (m Message) Compact(float64) (AgentMessage, float64) + func (m Message) GetRole() Role + func (m Message) GetTimestamp() time.Time + func (m Message) HasToolCalls() bool + func (m Message) IsEmpty() bool + func (m Message) Priority() int + func (m Message) Raw() AgentMessage + func (m Message) TextContent() string + func (m Message) ThinkingContent() string + func (m Message) ToMessage() (Message, bool) + func (m Message) ToolCalls() []ToolCall + type MessageSequenceIssue struct + AssistantIndex int + Kind MessageSequenceIssueKind + MessageIndex int + ToolCallID string + ToolName string + func ValidateMessageSequence(msgs []Message) []MessageSequenceIssue + type MessageSequenceIssueKind string + const MessageSequenceIssueMissingToolResult + const MessageSequenceIssueOrphanToolResult + type ModelNamer interface + ModelName func() string + type PartialStreamError struct + Partial Message + func (e *PartialStreamError) Error() string + func (e *PartialStreamError) Is(target error) bool + type Previewer interface + Preview func(ctx context.Context, args json.RawMessage) (json.RawMessage, error) + type ProgressPayload struct + Agent string + Args json.RawMessage + Attempt int + Delta string + DeltaKind DeltaKind + IsError bool + Kind ProgressPayloadKind + MaxRetries int + Message string + Meta json.RawMessage + Summary string + Thinking string + Tool string + Turn int + type ProgressPayloadKind string + const ProgressContext + const ProgressRetry + const ProgressSummary + const ProgressThinking + const ProgressToolDelta + const ProgressToolEnd + const ProgressToolError + const ProgressToolStart + const ProgressTurnCounter + type ProviderNamer interface + ProviderName func() string + type ReadOnlyTool interface + ReadOnly func(args json.RawMessage) bool + type ResponseFormat struct + JSONSchema *JSONSchema + Type string + type RetryHinter interface + RetryAfter func() time.Duration + type RetryInfo struct + Attempt int + Delay time.Duration + Err error + MaxRetries int + type RetryableError interface + Retryable func() bool + type Role string + const RoleAssistant + const RoleSystem + const RoleTool + const RoleUser + type RunSummary struct + EndReason EndReason + ToolCalls int + ToolErrors int + TurnCount int + type StopDecision struct + Allow bool + Escalate bool + InjectMessage string + type StopGuard func(ctx context.Context, stop StopInfo) StopDecision + type StopInfo struct + Message Message + Trigger StopTrigger + TurnIndex int + type StopReason string + const StopReasonAborted + const StopReasonError + const StopReasonLength + const StopReasonSafety + const StopReasonStop + const StopReasonToolUse + type StopTrigger string + const StopTriggerAfterTool + const StopTriggerEndTurn + type StreamEvent struct + CompletedToolCall *ToolCall + ContentIndex int + Delta string + Err error + Message Message + StopReason StopReason + Type StreamEventType + type StreamEventType string + const StreamEventDone + const StreamEventError + const StreamEventTextDelta + const StreamEventTextEnd + const StreamEventTextStart + const StreamEventThinkingDelta + const StreamEventThinkingEnd + const StreamEventThinkingStart + const StreamEventToolCallDelta + const StreamEventToolCallEnd + const StreamEventToolCallStart + type StrictSchemaTool interface + StrictSchema func() bool + type SwappableModel struct + func NewSwappableModel(initial ChatModel) *SwappableModel + func (m *SwappableModel) Current() ChatModel + func (m *SwappableModel) Generate(ctx context.Context, messages []Message, tools []ToolSpec, opts ...CallOption) (*LLMResponse, error) + func (m *SwappableModel) GenerateStream(ctx context.Context, messages []Message, tools []ToolSpec, opts ...CallOption) (<-chan StreamEvent, error) + func (m *SwappableModel) ModelName() string + func (m *SwappableModel) ProviderName() string + func (m *SwappableModel) SupportsTools() bool + func (m *SwappableModel) Swap(next ChatModel) + type SystemBlock struct + CacheControl string + Text string + type ThinkingLevel string + const ThinkingAuto + const ThinkingHigh + const ThinkingLow + const ThinkingMax + const ThinkingMedium + const ThinkingMinimal + const ThinkingOff + const ThinkingXHigh + func NormalizeThinkingLevel(level ThinkingLevel) ThinkingLevel + type Tool interface + Description func() string + Execute func(ctx context.Context, args json.RawMessage) (json.RawMessage, error) + Name func() string + Schema func() map[string]any + type ToolCall struct + Args json.RawMessage + ArgsInvalid bool + ArgsParseError string + ArgsRawText string + ID string + Name string + ThoughtSignature string + type ToolExecUpdateKind string + const ToolExecUpdatePreview + const ToolExecUpdateProgress + type ToolExecuteFunc func(ctx context.Context, args json.RawMessage) (json.RawMessage, error) + type ToolGate func(ctx context.Context, req GateRequest) (*GateDecision, error) + type ToolLabeler interface + Label func() string + type ToolMiddleware func(ctx context.Context, call ToolCall, next ToolExecuteFunc) (json.RawMessage, error) + type ToolProgressFunc func(progress ProgressPayload) + type ToolResult struct + Content json.RawMessage + ContentBlocks []ContentBlock + Details any + IsError bool + ToolCallID string + ToolName string + type ToolSpec struct + DeferLoading bool + Description string + Name string + Parameters any + Strict *bool + type ToolValidationError struct + Issues []ValidationIssue + ToolName string + func (e *ToolValidationError) Error() string + func (e *ToolValidationError) Is(target error) bool + type Usage struct + CacheRead int + CacheWrite int + Cost *Cost + Input int + Model string + Output int + Provider string + TotalTokens int + func (u *Usage) Add(other *Usage) + type ValidationIssue struct + Expected string + Hint string + Kind string + Path string + Received string + type ValidationResult struct + ErrorCode int + Message string + OK bool + type Validator interface + Validate func(ctx context.Context, args json.RawMessage) ValidationResult