Documentation
¶
Overview ¶
Package agent provides the core orchestration loop for GopherAgent.
It contains:
- ReAct loop execution (`AgentLoop`)
- Streaming/blocking run APIs
- Structured error types for `errors.Is`/`errors.As`
- Retry configuration for transient LLM failures
- Hook and event systems for observability/instrumentation
Package agent provides the core ReAct loop, streaming, and orchestration for LLM agents.
Package agent provides the core ReAct loop, streaming, and orchestration for LLM agents.
Index ¶
- Constants
- Variables
- func ConfirmHITLTimeoutFromContext(ctx context.Context) time.Duration
- func ForkAtLastUser(ctx context.Context, sm SessionManager, sessionKey string) (string, error)
- func PatchDanglingToolCalls(msgs []history.Message) []history.Message
- func SessionKeyFromContext(ctx context.Context) (string, bool)
- func ThinkingBudgetFromContext(ctx context.Context) int
- func ToolChainingHint() string
- func WithConfirmHITL(ctx context.Context, fn ConfirmFunc) context.Context
- func WithConfirmHITLTimeout(ctx context.Context, d time.Duration) context.Context
- func WithDynamicContextFunc(ctx context.Context, fn DynamicContextFunc) context.Context
- func WithSessionKey(ctx context.Context, sessionKey string) context.Context
- func WithStructuredOutput(ctx context.Context, so StructuredOutput) context.Context
- func WithSubAgentEmitter(ctx context.Context, fn SubAgentEmitter) context.Context
- func WithThinkingBudget(ctx context.Context, tokens int) context.Context
- type ActionRequiredEvent
- type ActiveTask
- type AgentLoop
- func (al *AgentLoop) ClearSession(sessionKey string)
- func (al *AgentLoop) Configure(opts ...Option) *AgentLoop
- func (al *AgentLoop) Continue(ctx context.Context, sessionKey string) (iter.Seq[StreamEvent], error)
- func (al *AgentLoop) IsPlanMode(sessionKey string) bool
- func (al *AgentLoop) OnEvent(h EventHandler) *AgentLoop
- func (al *AgentLoop) Regenerate(ctx context.Context, sessionKey string) (iter.Seq[StreamEvent], error)
- func (al *AgentLoop) Run(ctx context.Context, sessionKey string, msg history.Message) iter.Seq[StreamEvent]
- func (al *AgentLoop) RunIteration(ctx context.Context, sessionKey string, userInput string) (string, error)
- func (al *AgentLoop) RunIterationMessage(ctx context.Context, sessionKey string, msg history.Message) (string, error)
- func (al *AgentLoop) RunText(ctx context.Context, sessionKey, text string) iter.Seq[StreamEvent]
- func (al *AgentLoop) SetPlanMode(sessionKey string, v bool)
- func (al *AgentLoop) Shutdown(ctx context.Context) error
- type AsyncTaskManager
- func (m *AsyncTaskManager) CancelTask(ctx context.Context, sessionKey, taskID string) error
- func (m *AsyncTaskManager) StartTask(parentCtx context.Context, sessionKey, agentName, description string) (string, error)
- func (m *AsyncTaskManager) SyncTasks(ctx context.Context, sessionKey string) map[string]history.AsyncTask
- func (m *AsyncTaskManager) UpdateTask(taskID, instruction string) error
- func (m *AsyncTaskManager) WithMaxConcurrent(n int) *AsyncTaskManager
- type BeforeLLMHook
- type BudgetTracker
- func (bt *BudgetTracker) Guard() BeforeLLMHook
- func (bt *BudgetTracker) Handler() EventHandler
- func (bt *BudgetTracker) Reset(sessionKey string)
- func (bt *BudgetTracker) Rewind(sessionKey string, refund TokenUsage)
- func (bt *BudgetTracker) Snapshot() map[string]TokenUsage
- func (bt *BudgetTracker) Usage(sessionKey string) TokenUsage
- type CapabilityProvider
- type ConfirmFunc
- type ConfirmPlanFunc
- type ConfirmationGateUnconfiguredError
- type ConsolidateResult
- type Consolidator
- type ContentEvent
- type ContextChangeReason
- type ContextPolicy
- type ContextRef
- type ContextTraceEvent
- type ContinuedEvent
- type DegradedError
- type DegradedEvent
- type DoneEvent
- type DynamicContextFunc
- type ErrorEvent
- type EventHandler
- type EventPayload
- type EventVisitor
- type FirePolicy
- type GenerateJSONRequest
- type HITLDeniedError
- type HITLDeniedEvent
- type HITLTimedOutError
- type HITLTimedOutEvent
- type Hook
- type HookRejectedError
- type IncompleteKind
- type IncompleteResponseError
- type LLMCapabilities
- type LLMFailureError
- type LLMProvider
- type LLMResult
- type LimitExhaustedEvent
- type LimitKind
- type LimitReason
- type MaxItersReachedEvent
- type MemoryConfig
- type MemoryConsolidatedEvent
- type MemoryLoadedEvent
- type MemoryScopeFunc
- type MockProvider
- type ModelPricing
- type Option
- func WithBeforeHook(h Hook) Option
- func WithBeforeLLMHook(h BeforeLLMHook) Option
- func WithCache(c *cache.SearchCache) Option
- func WithConfirmPlan(fn ConfirmPlanFunc) Option
- func WithDynamicContext(fn DynamicContextFunc) Option
- func WithEmitThoughts(emit bool) Option
- func WithHITL(fn ConfirmFunc, timeout time.Duration) Option
- func WithMaxIters(n int) Option
- func WithMaxParallelToolCalls(n int) Option
- func WithMaxTokenBudget(n int) Option
- func WithMaxToolCallsPerSession(n int) Option
- func WithMaxToolCallsPerTurn(n int) Option
- func WithMemory(store memory.Store, cfg MemoryConfig) Option
- func WithMemoryConsolidator(c *Consolidator) Option
- func WithMemoryScope(fn MemoryScopeFunc) Option
- func WithMeter(m metric.Meter) Option
- func WithOnEvent(h EventHandler) Option
- func WithOnToolResult(h ToolResultHook) Option
- func WithPermissions(p PermissionChecker) Option
- func WithPriceTable(table PriceTable, model string) Option
- func WithReflect(rounds int, prompt string) Option
- func WithRequestInvariant(onViolation RequestViolationFunc) Option
- func WithRetry(cfg *RetryConfig) Option
- func WithSpeculativeTools(enable bool) Option
- func WithThinking(tokens int) Option
- func WithToolErrorHintFormatter(fn ToolErrorHintFormatter) Option
- func WithToolSelector(s *tools.Selector) Option
- func WithTracer(t trace.Tracer) Option
- func WithoutAutoCacheSystem() Option
- func WithoutToolChainingHint() Option
- type PendingToolCall
- type PermissionChecker
- type PermissionDecision
- type PermissionDeniedError
- type PermissionRuleSet
- type PlanProposal
- type PriceTable
- type ReflectedEvent
- type RegeneratedEvent
- type RequestViolationFunc
- type RetryAttemptHook
- type RetryConfig
- type RunCostEvent
- type RunResult
- type Scorer
- type ScorerFunc
- type SessionCreatedEvent
- type SessionForker
- type SessionManager
- type SessionQueryable
- type SessionTitler
- type SoftDeletable
- type StreamEvent
- type StreamEventType
- type StructuredOutput
- type SubAgentEmitter
- type TaskListEvent
- type TaskListItem
- type ThoughtEvent
- type TokenUsage
- type ToolCallEvent
- type ToolCallReadyEvent
- type ToolDegradation
- type ToolErrorContext
- type ToolErrorHintFormatter
- type ToolNotFoundError
- type ToolProgressEvent
- type ToolResultHook
- type UnknownEvent
- type UsageEvent
Constants ¶
const ExitPlanModeToolName = "exit_plan_mode"
ExitPlanModeToolName is the canonical name the AgentLoop special-cases when PlanMode is active. Registering a built-in tool (or custom tool) under this name is what lets the model signal "plan is ready".
Variables ¶
var ( // ErrMaxIterations is returned when the loop exhausts MaxIters without a final answer. ErrMaxIterations = errors.New("agent: reached maximum iterations without final answer") // ErrMaxToolCallsPerSession is returned when the cumulative number of // tool calls executed across iterations of a single Run exceeds // AgentLoop.MaxToolCallsPerSession. Distinct from MaxToolCallsPerTurn, // which only caps the wave size within one iteration. ErrMaxToolCallsPerSession = errors.New("agent: cumulative tool-call cap exceeded") // ErrLoopDetected is returned when the anti-loop detector terminates the cycle. ErrLoopDetected = errors.New("agent: infinite loop detected") // ErrDegraded classifies a turn that produced a real answer while some // tool's derived bookkeeping failed — neither a clean success nor a // failure worth retrying. It is never returned from Run (the answer is // good); adopters match it via errors.Is on DegradedEvent.Err. ErrDegraded = errors.New("agent: turn completed with degraded state") // ErrToolNotFound is returned when the LLM requests a tool that is not registered. ErrToolNotFound = errors.New("agent: tool not found") // ErrHITLDenied is returned (as a StreamEvent) when a human-in-the-loop operator // denies execution of a tool. The loop continues; the LLM is told to find a workaround. ErrHITLDenied = errors.New("agent: tool execution denied by human operator") // ErrHITLTimedOut is returned when AgentLoop.ConfirmHITLTimeout fires // before the operator responds. Distinct from ErrHITLDenied so the model // can distinguish "user did not respond in time" from "user said no", // and so adopters can route on the cause (e.g. retry vs. abort). ErrHITLTimedOut = errors.New("agent: human approval timed out") // ErrHookRejected is returned when a BeforeHook rejects the request. ErrHookRejected = errors.New("agent: request rejected by policy hook") // ErrLLMFailure is returned when the LLM provider returns an error during generation. ErrLLMFailure = errors.New("agent: LLM generation failed") // ErrLLMAuth is returned when the provider rejects the request for // authentication or configuration reasons — a missing, invalid, or // revoked API key, or a project without access to the model. // // It is deliberately distinct from ErrLLMFailure because the two demand // opposite responses. A generation failure is transient and retrying is // reasonable; an auth failure is deterministic, so every retry fails // identically. Without the distinction a misconfigured key looks exactly // like a flaky backend: retry loops spin, per-run call and spend budgets // drain against attempts that never had a chance, and the work gets // parked as bad input rather than surfaced as "fix your key". // // Providers classify their own terminal auth responses, so route on the // sentinel rather than matching provider message text: // // if errors.Is(err, agent.ErrLLMAuth) { // return fmt.Errorf("check the provider credentials: %w", err) // } ErrLLMAuth = errors.New("agent: LLM provider authentication or configuration failed") // ErrLLMTruncated is returned when the provider stopped generating // before the response was finished — an output-token cap, typically. // // The danger is that a truncated response is a *valid prefix*: the text // looks fine and only fails when something downstream parses it, so the // operator reads "unexpected end of JSON input" and inspects a schema // that was never wrong. Providers detect the cut at the source, so route // on the sentinel instead of matching decode-error text. // // The cut is a function of this response's length rather than of the // request, so isRetryable leaves it retryable — but a truncation that // already streamed content is not retried, because re-running it would // replay the same text into the consumer's stream. The real fix is a // larger provider token cap or a smaller ask, both caller decisions. ErrLLMTruncated = errors.New("agent: LLM response truncated before completion") // ErrLLMContentBlocked is returned when the provider stopped generating // for a content policy: safety, recitation, a blocklist, or an // unsupported language. // // Deliberately distinct from ErrLLMTruncated because the two demand // opposite responses. A truncation is length-dependent and may pass on // the next attempt; a policy stop is deterministic for a given prompt, // so every retry reproduces it. isRetryable treats it as terminal — the // caller must change the request or surface the block to the user. ErrLLMContentBlocked = errors.New("agent: LLM stopped generating for a content policy") // ErrUnrenderablePart is returned by a provider adapter when a message // carries a history.MediaPart the adapter cannot put on the wire — an // unsupported part type, or a part whose payload is missing. // // Failing is the point. The alternative, dropping the part and sending // the rest, produces a fluent well-formed answer from a model that never // received the media, and nothing distinguishes that from success: not // the response, not the logs, not a schema check. A judge that cannot see // the image it is judging is not a degraded judge, it is a random one. // // Deterministic like ErrLLMAuth, not transient like ErrLLMFailure — the // same message fails identically on every retry. isRetryable treats it as // terminal; the caller must re-encode the part or choose a provider that // supports it. ErrUnrenderablePart = errors.New("agent: message carries a media part this provider cannot render") // ErrContextCancelled is returned when the request context is cancelled mid-loop. ErrContextCancelled = errors.New("agent: operation cancelled") // ErrPermissionDenied is returned (as a StreamEvent) when a configured // PermissionChecker rejects a tool call before it runs. Distinct from // ErrHITLDenied because no human was in the loop — a policy denied it. ErrPermissionDenied = errors.New("agent: tool execution denied by permission policy") // ErrConfirmationGateUnconfigured is returned when a tool requires // confirmation but no ConfirmHITL callback and no PermissionAllow rule // can resolve the gate. The denial is a configuration bug, not a user // rejection — the model is told as much so it does not confabulate // "the user denied it". ErrConfirmationGateUnconfigured = errors.New("agent: tool requires confirmation but no ConfirmHITL handler is configured") // ErrNothingToRegenerate is returned by AgentLoop.Regenerate when the // session has no user message to replay (system-only history, or every // user message was already truncated). The call leaves history and the // stream untouched. ErrNothingToRegenerate = errors.New("agent: no user message to regenerate") // ErrNothingToContinue is returned by AgentLoop.Continue when the // session's last persisted message is a clean final-assistant turn — // the previous run ended naturally, and the caller should send a new // user message instead of trying to extend it. ErrNothingToContinue = errors.New("agent: session ended cleanly; nothing to continue") )
Sentinel errors returned by AgentLoop. Use errors.Is / errors.As for matching.
var DefaultFirePolicy = FirePolicy{MinInterval: 10 * time.Minute}
DefaultFirePolicy is applied when Consolidator.FirePolicy is the zero value. The 10-minute interval matches the typical span of a conversation "burst" and amortizes the LLM cost roughly 10–15× for chat-heavy workloads vs. firing every Run. The first Run for a scope still fires (initial lastFiredAt is zero).
Functions ¶
func ConfirmHITLTimeoutFromContext ¶
ConfirmHITLTimeoutFromContext returns the timeout stamped onto ctx by the parent loop, or 0 if none is present. Sub-agent tools that recover this alongside ConfirmHITLFromContext keep the operator's approval window consistent whether the gate fires at the outer boundary (call_sql_agent) or inside the inner worker (execute_sql).
func ForkAtLastUser ¶
ForkAtLastUser creates a branch that keeps everything before the most recent user message in sessionKey. This is the "redo my last turn" shortcut: after forking, the caller can append a new user message to the new session and run the loop again.
Requires sm to implement SessionForker; returns an error if it does not. Fails if the session has no user messages or the underlying Fork fails.
func PatchDanglingToolCalls ¶
PatchDanglingToolCalls scans message history and injects synthetic tool responses for any tool_call that never received a reply. Adopters slicing session history for ad-hoc LLM calls (titling, summarisation, custom retitle / classification flows) can apply this before the call so the provider doesn't 400 on broken tool_use/tool_result adjacency.
The same routine runs automatically inside the ReAct loop and provider converters — exporting it lets downstream callers that build their own message slices stay safe without duplicating the logic.
Returns the input slice unchanged when no dangling call is detected (no allocation). When patching is required, synthetic tool messages are appended *after* any existing tool responses for the same assistant turn so call order matches the source tool_calls order.
func SessionKeyFromContext ¶
SessionKeyFromContext returns the session key stamped by WithSessionKey. The second return is false when no key is present (typically only in tests or when a tool is invoked outside the agent loop).
func ThinkingBudgetFromContext ¶
ThinkingBudgetFromContext returns the extended-thinking budget stored on ctx, or 0 when no budget was set. Provider adapters call this right before building the request and skip the thinking/reasoning field when zero.
func ToolChainingHint ¶
func ToolChainingHint() string
ToolChainingHint returns the system-prompt snippet that teaches the LLM to chain tool calls via <output_of:<tool_call_id>.<field>> references. The AgentLoop appends this automatically to the system prompt on each turn when at least two tools are registered (disable via DisableToolChainingHint).
Exposed so callers who prefer to own the full system prompt can paste this text verbatim — the loop detects it by sentinel substring and skips the duplicate injection.
func WithConfirmHITL ¶
func WithConfirmHITL(ctx context.Context, fn ConfirmFunc) context.Context
WithConfirmHITL returns a derived ctx that carries fn so a downstream sub-agent tool can recover it via ConfirmHITLFromContext and assign it onto its worker AgentLoop.ConfirmHITL. A nil fn returns ctx unchanged, which is zero-cost when the parent loop has no ConfirmHITL configured.
func WithConfirmHITLTimeout ¶
WithConfirmHITLTimeout returns a derived ctx that carries d so a downstream sub-agent tool can recover it via ConfirmHITLTimeoutFromContext and assign it onto its worker AgentLoop.ConfirmHITLTimeout. A zero d returns ctx unchanged so the helper stays zero-cost when the parent has not opted in to a HITL timeout.
func WithDynamicContextFunc ¶
func WithDynamicContextFunc(ctx context.Context, fn DynamicContextFunc) context.Context
WithDynamicContextFunc returns a derived ctx that carries fn so that any downstream sub-agent tool can recover it via DynamicContextFuncFromContext and install it on its worker loop. A nil fn returns ctx unchanged so this is zero-cost when the parent loop has no DynamicContext configured.
func WithSessionKey ¶
WithSessionKey returns a new context carrying the session key. Tools and integrations should call SessionKeyFromContext rather than building the lookup key themselves.
func WithStructuredOutput ¶
func WithStructuredOutput(ctx context.Context, so StructuredOutput) context.Context
WithStructuredOutput returns ctx with a schema-constrained response request attached. Nil / empty Schema is treated as "no hint" and clears any previously-set request.
The AgentLoop installs this before every GenerateStream call when its StructuredOutput field is set; provider adapters read it with StructuredOutputFromContext.
func WithSubAgentEmitter ¶
func WithSubAgentEmitter(ctx context.Context, fn SubAgentEmitter) context.Context
WithSubAgentEmitter injects an emitter into ctx so tools that run nested agent loops (sub-agents, async workers) can stream their events back to the parent. The agent loop installs one automatically for every tool invocation; tools outside a loop may inject their own for testing.
func WithThinkingBudget ¶
WithThinkingBudget returns ctx with an extended-thinking budget attached. The AgentLoop installs this before every GenerateStream call when its ThinkingBudget field is non-zero; provider adapters read it with ThinkingBudgetFromContext.
Tokens ≤ 0 is treated as "no hint" and removes any budget from ctx.
Types ¶
type ActionRequiredEvent ¶
ActionRequiredEvent signals that a tool invocation needs human approval. Adopters typically gate this through an out-of-band channel (UI prompt, Slack message, webhook) and resume the loop only after the operator responds via the configured ConfirmHITL callback.
type ActiveTask ¶
type ActiveTask struct {
// CancelFunc stops the worker goroutine.
CancelFunc context.CancelFunc
// InstructionChan delivers steering instructions from the main agent to
// the worker. Buffered — senders never block, but excess instructions are
// drained at each iteration boundary.
InstructionChan chan string
}
ActiveTask is the in-memory handle for a running async task. It is removed from AsyncTaskManager.ActiveTasks once the underlying goroutine exits.
type AgentLoop ¶
type AgentLoop struct {
Sessions SessionManager
Tools *tools.Registry
LLM LLMProvider
MaxIters int
EmitThoughts bool
BeforeHooks []Hook
// ConfirmHITL is called when a tool requires human approval.
// If nil, HITL tools are auto-denied with a rejection message.
// If set, the loop blocks until the function returns.
ConfirmHITL ConfirmFunc
// ConfirmHITLTimeout caps how long the HITL gate waits for ConfirmHITL
// to return. Zero (default) means no timeout — the gate blocks until the
// callback returns or ctx is cancelled. When set, the gate wraps the
// callback ctx with this deadline; a ConfirmHITL that respects ctx will
// return false on expiry, the gate emits EventTypeHITLTimedOut, and the
// model receives a timeout-specific directive (distinct from a user
// denial) so it can ask the user to retry rather than seek an alternative.
ConfirmHITLTimeout time.Duration
// Cache provides optional tool result caching with trigram similarity matching.
// If nil, caching is disabled. Set via cache.NewSearchCache().
Cache *cache.SearchCache
// MaxTokenBudget is the estimated token ceiling for the conversation context.
// 0 disables budget enforcement. When the estimated token count exceeds this
// value, the loop applies more aggressive context pruning before the next LLM
// call. Estimation uses a 4-chars/token heuristic (~±20% accuracy for English).
MaxTokenBudget int
// EventHandlers is called for every StreamEvent emitted during the loop.
// Multiple handlers can be registered; all fire in order for each event.
// Register handlers via OnEvent for a fluent API.
EventHandlers []EventHandler
// Retry controls exponential-backoff retry for transient LLM errors.
// nil disables retries. Use DefaultRetryConfig() for sensible defaults.
// Retries are skipped when content has already started streaming to the client.
Retry *RetryConfig
// BeforeLLMHooks fire right before every GenerateStream call (including
// retries). Any non-nil error aborts the iteration. Useful for per-session
// spend caps and policy enforcement; pair with a BudgetTracker for a
// ready-made implementation.
BeforeLLMHooks []BeforeLLMHook
// DynamicContext, when non-nil, is invoked before every GenerateStream
// call and its return value is appended to the system prompt for that
// call only (never persisted to session history). See DynamicContextFunc
// for the hot-path contract and prompt-cache interaction notes.
DynamicContext DynamicContextFunc
// OnToolResult, when non-nil, runs after every successful tool execution
// and may rewrite the result string (or veto it via a non-nil error)
// before it reaches the LLM context, the inline-render path, the cache,
// and the anti-loop tracker. See ToolResultHook for the contract.
OnToolResult ToolResultHook
// ToolSelector, when non-nil, filters the tool list presented to the LLM
// each turn by semantic similarity between the latest user message and
// tool descriptions. Reduces prompt-token cost and improves tool-choice
// accuracy for large catalogs (50+ tools). See tools.NewSelector. A nil
// selector means every registered tool is presented every turn (default).
ToolSelector *tools.Selector
// DisableToolChainingHint suppresses the automatic system-prompt snippet
// that teaches the LLM to chain tool calls via <output_of:ID.path>. By
// default (false), the hint is appended to the system message on every
// LLM call when at least two tools are registered and the prompt does
// not already contain the syntax. Set to true when you have documented
// the syntax yourself or explicitly want to opt out of scheduling.
DisableToolChainingHint bool
// ConfirmPlan runs when the model calls exit_plan_mode while PlanMode is
// true. Returning true approves the plan and clears PlanMode; false
// denies and the tool result asks the model to revise. When nil, the
// loop emits an action_required event and auto-denies until the caller
// approves out-of-band and re-runs the iteration with PlanMode=false.
ConfirmPlan ConfirmPlanFunc
// SpeculativeTools, when true, executes safe tool calls in parallel with
// the remaining LLM stream as soon as their arguments finish streaming —
// trimming one tail-latency round trip per call, ~200ms on average for
// Claude. Eligibility is conservative: HITL-gated tools, exit_plan_mode,
// calls that reference <output_of:...>, and anything while PlanMode is
// active are never speculated. See shouldSpeculate for the exact rules.
//
// Enabling this has no effect unless the provider emits mid-stream
// tool_call_ready events; today that is the Anthropic adapter. Other
// providers fall back to the original post-stream execution path.
SpeculativeTools bool
// ToolErrorHintFormatter customizes the text the loop writes back to
// the model when a tool execution returns an error. nil uses
// defaultToolErrorHint, which wraps the raw error with a short
// structured retry hint. Override to inject domain remediation advice
// (SQL error → "check column exists", filesystem error → "verify the
// path is under /tmp", etc.); the model re-reads the tool result on
// every subsequent turn, so better wording compounds.
ToolErrorHintFormatter ToolErrorHintFormatter
// Reflect runs N serial self-critique passes after the model produces a
// final answer with no pending tool calls. Each pass appends a synthetic
// critique prompt and asks the model to revise its answer; the final
// round's text becomes the canonical response saved to history and
// emitted to callers — unless Scorer is set, in which case the
// best-scoring round wins instead. 0 (default) disables reflection
// entirely.
//
// Reflection is opt-in because it multiplies latency and token cost by
// (1 + N). It targets correctness-critical tasks — SQL generation, code
// synthesis, multi-step analysis — where a second-pass review routinely
// catches mistakes the first pass missed.
Reflect int
// ReflectPrompt overrides the default critique instruction appended at
// each reflection round. Leave empty to use defaultReflectPrompt, which
// is a neutral "review and revise if wrong; otherwise repeat verbatim"
// prompt suitable for most tasks. Override with domain-specific criteria
// (e.g. "check every JOIN condition binds a valid FK") when the default
// misses task-specific pitfalls.
ReflectPrompt string
// Scorer ranks candidate answers so a self-critique pass keeps the
// best round rather than the last one. nil (default) preserves the
// historical last-wins behavior: every non-empty, textually different
// revision is accepted, so a critique round can make the answer worse
// and the earlier text is unrecoverable.
//
// With a Scorer set, the model's original answer is scored as round 0
// and each revision must beat the best score so far to be adopted; a
// revision that scores lower is discarded and the next round critiques
// the best answer instead. The kept round's score rides along on
// ReflectedEvent so a UI can show why.
//
// Costs one Score call per round plus one for the original. See Scorer
// for the latency and token-spend caveats.
//
// Only the self-critique path consumes this today, so setting it with
// Reflect == 0 is inert. The interface is deliberately generic — a
// best-of-K runner is the intended second consumer.
Scorer Scorer
// ThinkingBudget turns on extended reasoning for providers that support
// it. It is a token hint, not a hard cap — see WithThinkingBudget for the
// per-provider mapping. Set to 0 (default) to keep requests on the normal
// non-reasoning path. Anthropic requires a minimum of 1024 tokens and the
// budget must be strictly less than the provider's MaxTokens; the
// Anthropic adapter clamps accordingly.
ThinkingBudget int
// Permissions, when non-nil, is consulted for every tool call before
// the HITL prompt fires. Allow bypasses RequiresConfirmation(); Deny
// short-circuits even for tools that would otherwise run silently;
// Prompt defers to the existing ConfirmHITL flow. Use a
// PermissionRuleSet for the built-in glob-based DSL, or implement
// PermissionChecker directly for custom logic (OPA, database-backed
// ACLs, etc).
Permissions PermissionChecker
// MaxToolCallsPerTurn caps how many tool calls the loop will execute for
// a single LLM turn. 0 (default) means unlimited. When the model returns
// more than N calls, the first N run normally and the remainder are
// dropped with a synthesized tool-error message so the model can see why
// they did not execute. A "thought" event announces the truncation.
MaxToolCallsPerTurn int
// MaxParallelToolCalls caps how many tool calls execute concurrently
// within one dependency wave. Defaults to defaultMaxParallelToolCalls;
// 0 means unlimited. Unlike MaxToolCallsPerTurn this drops nothing — a
// call over the cap waits for a slot, so the wave's result set is
// identical either way. It bounds live resource use (sockets,
// subprocesses, provider rate limits) when a model emits a wide fan-out.
MaxParallelToolCalls int
// MaxToolCallsPerSession caps the cumulative number of tool calls
// scheduled across all iterations of a single Run. 0 (default) means
// unlimited. Distinct from MaxToolCallsPerTurn, which only bounds the
// wave size within one iteration — anti-loop catches identical-arg
// loops, but identical-tool-different-args could otherwise run
// unchecked across many ReAct iterations. When the cap is crossed,
// the loop emits an error event carrying ErrMaxToolCallsPerSession
// and saves the session before returning.
MaxToolCallsPerSession int
// RequestInvariant, when set, receives a description of any broken
// request-path invariant: the pipeline writing through to stored
// history, or a request that a re-derivation cannot reproduce. Nil
// (default) disables the check entirely — no snapshot is taken and the
// cost is one nil comparison per iteration. Set it with
// WithRequestInvariant in development and staging.
RequestInvariant RequestViolationFunc
// AutoCacheSystem, when true, stamps Message.CacheHint=true on the first
// system message of every LLM call. On Anthropic this promotes the
// entire system prompt into the prompt-cache prefix, typically cutting
// input-token cost on that block to ~10% of normal for repeat turns
// within a 5-minute window. Ignored by providers that don't honor
// CacheHint (OpenAI, Gemini). Idempotent.
//
// NewAgentLoop defaults this to true — struct-literal construction
// (&AgentLoop{...}) gets zero-value false and must opt in explicitly.
AutoCacheSystem bool
// Memory, when non-nil, enables cross-session note injection. On
// every Run the loop reads notes for the resolved scope (bounded
// by MemoryCfg), formats them with memory.FormatNotes, and
// appends the block to the system message via a sentinel-tagged
// path that's idempotent across LLM retries within an iteration
// and stable across iterations within a Run. nil disables the
// loader at zero hot-path cost.
Memory memory.Store
// MemoryCfg bounds the loader's per-Run cost. Zero-valued fields
// resolve to documented defaults (TokenBudget=500, MaxNotes=50).
// See MemoryConfig for details.
MemoryCfg MemoryConfig
// MemoryScopeFn resolves the scope key used for memory reads and
// for any Consolidator auto-fires. nil (default) returns sessionKey
// unchanged, isolating memory per-conversation; override to share
// memory across sessions for the same user/tenant (typical pattern
// is to read a user_id from ctx and return "user:" + id).
MemoryScopeFn MemoryScopeFunc
// MemoryConsolidator, when non-nil, fires after every Run that
// terminates in DoneEvent. Runs in a detached goroutine that
// inherits ctx values but is immune to ctx cancellation — the
// caller's request lifetime never aborts an in-flight consolidation.
// Set this together with Memory; setting it without a store is a
// configuration error caught at Consolidate time.
MemoryConsolidator *Consolidator
// PriceTable supplies the rates used to estimate the dollar cost of
// LLM calls whose provider reports none. The loop accumulates
// TokenUsage across every call in a Run and emits a RunCostEvent
// right before DoneEvent. Leaving it nil does not disable the
// rollup: a provider that sets TokenUsage.CostUSD is already exact
// and reports through the same event. Adopters running multi-model
// router setups whose pricing varies per call, against providers
// that report nothing, should leave this nil and roll cost up
// themselves from UsageEvent.
PriceTable PriceTable
// PriceModel is the key looked up in PriceTable for cost
// computation. Set to the canonical name of the model this loop
// drives (e.g. "claude-sonnet-4-6"). Unknown keys produce a
// RunCostEvent with USD=0 and Usage still populated.
PriceModel string
// contains filtered or unexported fields
}
AgentLoop orchestrates the ReAct loop.
func New ¶
func New(sessions SessionManager, registry *tools.Registry, llm LLMProvider, opts ...Option) *AgentLoop
New constructs an AgentLoop with the given session manager, tool registry, LLM provider, and a set of functional options. New is the recommended entry point — it returns a fully-configured loop ready to call Run on.
Defaults applied before options run:
- MaxIters = 15
- EmitThoughts = true (streaming methods); RunIteration suppresses thoughts regardless
- AutoCacheSystem = true
All options listed below override these defaults. Pass no options for a minimal loop that uses the defaults end-to-end.
func NewAgentLoop ¶
func NewAgentLoop(sessions SessionManager, registry *tools.Registry, llm LLMProvider, hooks ...Hook) *AgentLoop
NewAgentLoop creates a new agent with the given session manager, tool registry, and LLM provider. Optional hooks run before each iteration for security/policy enforcement.
func (*AgentLoop) ClearSession ¶
ClearSession removes any per-session state the AgentLoop holds for sessionKey. Today this is just plan-mode state; future per-session fields added to AgentLoop should be cleaned up here too. Idempotent — safe to call on sessions that never entered plan mode.
Call this when you delete a session (e.g. SessionManager.DeleteSession, HTTP disconnect, sub-agent finish) so abandoned plan-mode sessions do not orphan map entries.
func (*AgentLoop) Configure ¶ added in v0.35.0
Configure applies additional options to an already-constructed loop and returns it for chaining. Use it to set options the constructor did not take — notably wiring agent.WithTracer / agent.WithMeter onto a loop produced by the YAML builder, which does not accept Option values. Apply before the first Run; options run in order and later ones win, matching New. nil options are skipped.
loop, _, _, _ := builder.BuildFromYAMLWithSession(...) loop.Configure(agent.WithTracer(tel.Tracer), agent.WithMeter(tel.Meter))
func (*AgentLoop) Continue ¶
func (al *AgentLoop) Continue(ctx context.Context, sessionKey string) (iter.Seq[StreamEvent], error)
Continue resumes the agent loop on sessionKey's current persisted history without appending a new user message. Use it when the previous run hit MaxIters / MaxToolCallsPerSession / a HITL timeout / a user-issued Stop and the user wants the agent to keep going from where it left off.
Returns ErrNothingToContinue when the session's last persisted message is a clean final-assistant turn (no dangling tool calls and no awaiting tool results); the caller should send a new user message instead. patchDanglingToolCalls is applied to the live history before iteration so any half-finished tool wave from the prior run is sealed.
EventTypeContinued is yielded as the first frame so UIs can attach subsequent content to the existing assistant bubble.
func (*AgentLoop) IsPlanMode ¶
IsPlanMode reports whether plan mode is active for sessionKey. Sessions with no entry are treated as normal mode (false). Safe to call concurrently with SetPlanMode and with an in-flight RunIterationStream.
Lifecycle: an entry exists from SetPlanMode(key, true) until either SetPlanMode(key, false) or ClearSession(key). Callers that delete a session (e.g. on HTTP disconnect or sub-agent finish) should call ClearSession to avoid orphaning entries for abandoned plan-mode sessions.
func (*AgentLoop) OnEvent ¶
func (al *AgentLoop) OnEvent(h EventHandler) *AgentLoop
OnEvent registers an EventHandler and returns the AgentLoop for fluent chaining.
loop.OnEvent(metrics.Track).OnEvent(logger.Log)
func (*AgentLoop) Regenerate ¶
func (al *AgentLoop) Regenerate(ctx context.Context, sessionKey string) (iter.Seq[StreamEvent], error)
Regenerate rewinds sessionKey's persisted history to just before the last user message and replays that user message through a fresh iteration. The returned iterator yields the replay stream, with EventTypeRegenerated as the first frame so UIs can mark the previous assistant bubble as superseded before replacement content arrives.
Returns ErrNothingToRegenerate (and a nil iterator) without touching history when no user message exists. The truncation is persisted via SaveHistory before the loop starts so a crash mid-replay never leaves a hybrid history. BeforeHooks fire with the recovered user message's Content, matching the RunIteration contract. Per-session counters (BudgetTracker, MaxToolCallsPerSession) are NOT rewound automatically.
Usage:
seq, err := loop.Regenerate(ctx, sessionKey)
if err != nil { return err }
for ev := range seq { /* ... */ }
func (*AgentLoop) Run ¶
func (al *AgentLoop) Run(ctx context.Context, sessionKey string, msg history.Message) iter.Seq[StreamEvent]
Run streams events from the agent loop as a pull-based iterator. The caller ranges over it; the library owns the underlying goroutine and tears it down when the range loop exits — for any reason, including early break or ctx cancellation.
for ev := range agent.Run(ctx, sessionKey, msg) {
if p, ok := ev.Payload.(agent.ErrorEvent); ok { return p.Err }
// ... handle ev
if userStopped { break } // library cancels the loop, drains
}
Thought events are filtered when AgentLoop.EmitThoughts is false (default). Errors are surfaced as ErrorEvent payloads in-stream; callers that want a terminal Go error type-assert on the payload. For the blocking "return the final answer" shape, use RunIteration.
func (*AgentLoop) RunIteration ¶
func (al *AgentLoop) RunIteration(ctx context.Context, sessionKey string, userInput string) (string, error)
RunIteration provides a fast, blocking response interface (non-streaming). Thoughts are always suppressed — only final content and errors are returned. Implemented on top of Run: drains the iterator, collecting Content events into the returned string and surfacing the first ErrorEvent as a Go error.
func (*AgentLoop) RunIterationMessage ¶
func (al *AgentLoop) RunIterationMessage(ctx context.Context, sessionKey string, msg history.Message) (string, error)
RunIterationMessage is the multimodal-aware variant of RunIteration. The caller controls the appended user message — set Parts to pass image bytes, ToolCallID for tool-result inputs, CacheHint for prompt-cache breakpoints, etc. Role defaults to "user" when empty.
func (*AgentLoop) RunText ¶
RunText is a string-input convenience wrapper around Run for text-only turns. The wrapped history.Message has Role="user" and Content=text.
func (*AgentLoop) SetPlanMode ¶
SetPlanMode toggles plan mode for sessionKey. Setting false removes the session's entry, keeping the map small for the common no-plan-mode path (most sessions never enter plan mode). Safe to call concurrently with IsPlanMode and with an in-flight RunIterationStream — useful for UI controls that flip plan mode mid-conversation.
func (*AgentLoop) Shutdown ¶
Shutdown blocks until every background goroutine the loop launched (today: post-Run consolidators) has finished, or until ctx fires. Returns ctx.Err when the deadline expires with work still in flight.
Typical use lives at the end of an HTTP server's graceful-stop path:
srv.Shutdown(ctx) // stop accepting new requests loop.Shutdown(ctxWithDeadline) // wait for detached bg work
Shutdown does NOT prevent new background work from being scheduled — adopters that need a hard stop should stop calling Run before Shutdown so no new consolidators get spawned. The loop itself stays reusable after Shutdown returns.
Calling Shutdown with no in-flight work returns nil immediately.
type AsyncTaskManager ¶
type AsyncTaskManager struct {
ActiveTasks map[string]*ActiveTask
Sessions SessionManager
Tools *tools.Registry
LLM LLMProvider
// MaxConcurrent caps the number of simultaneously running worker
// goroutines. 0 means unlimited (the default). Set via WithMaxConcurrent.
MaxConcurrent int
// contains filtered or unexported fields
}
AsyncTaskManager owns the lifecycle of background worker agents. Each task runs a separate AgentLoop in its own goroutine with an isolated session key. The task metadata (status, result) is persisted under the *parent* session's AsyncTasks map, while the worker's message history lives under a dedicated per-task session key that is deleted when the worker exits.
When MaxConcurrent is greater than zero, StartTask rejects new tasks beyond that cap with an error rather than queueing. This is a backpressure signal — the caller decides whether to retry, drop, or surface to the user.
func NewAsyncTaskManager ¶
func NewAsyncTaskManager(sessions SessionManager, registry *tools.Registry, llm LLMProvider) *AsyncTaskManager
NewAsyncTaskManager constructs a manager wired to the given dependencies.
func (*AsyncTaskManager) CancelTask ¶
func (m *AsyncTaskManager) CancelTask(ctx context.Context, sessionKey, taskID string) error
CancelTask signals the worker goroutine to stop and marks the task as cancelled in the parent session. Returns an error when taskID is not currently active. ctx supplies caller-stamped values (trace IDs, user IDs) to the session backend; cancellation is intentionally stripped so the final status update survives request-scoped teardown.
func (*AsyncTaskManager) StartTask ¶
func (m *AsyncTaskManager) StartTask(parentCtx context.Context, sessionKey, agentName, description string) (string, error)
StartTask registers a new async task and launches the worker goroutine. Returns the task_id immediately; the worker runs detached from parentCtx so it survives the HTTP request that spawned it.
The worker context is built via context.WithoutCancel(parentCtx): it inherits every value the caller installed (user_id, request_id, tracer spans, dynamic-context func, sub-agent emitter — anything middleware stamped onto ctx) but does NOT inherit the parent's Done channel, so the SSE connection closing won't kill an in-flight Veo poll. Session writes for the task metadata reuse the same WithoutCancel ctx so they keep caller-supplied values too while still surviving caller cancellation.
func (*AsyncTaskManager) SyncTasks ¶
func (m *AsyncTaskManager) SyncTasks(ctx context.Context, sessionKey string) map[string]history.AsyncTask
SyncTasks reconciles persisted task metadata with the manager's in-memory ActiveTasks map. Tasks whose status says "running" but are not present in ActiveTasks are marked "interrupted" (e.g., the process restarted). Returns a snapshot copy of the reconciled task map. ctx supplies caller values to the session backend; cancellation is stripped so reconciliation outlives request-scoped teardown.
func (*AsyncTaskManager) UpdateTask ¶
func (m *AsyncTaskManager) UpdateTask(taskID, instruction string) error
UpdateTask delivers a steering instruction to a running worker. It is non-blocking: if the worker's buffer is full, the instruction is dropped.
func (*AsyncTaskManager) WithMaxConcurrent ¶
func (m *AsyncTaskManager) WithMaxConcurrent(n int) *AsyncTaskManager
WithMaxConcurrent caps the number of simultaneously running worker goroutines at n. StartTask returns an error when the cap is reached. n == 0 removes the cap (unlimited). Typically called once right after NewAsyncTaskManager; changing the cap while tasks are active is allowed but the new cap only applies to subsequent StartTask calls.
type BeforeLLMHook ¶
BeforeLLMHook fires immediately before each GenerateStream call. Returning an error aborts the iteration (the loop emits an error event and exits). Use for per-session budget enforcement, rate limiting, or policy checks. estimatedTokens is a rough (chars/4) pre-call estimate of the prompt size.
type BudgetTracker ¶
type BudgetTracker struct {
// Budget is the maximum cumulative TotalTokens permitted per session.
// A value of 0 disables enforcement (Guard always returns nil) but the
// Handler still records usage so callers can inspect via Usage.
Budget int
// contains filtered or unexported fields
}
BudgetTracker enforces per-session token budgets. It plugs into an AgentLoop in two places:
- Register Handler as an EventHandler to accumulate token usage from the "usage" StreamEvent that providers emit after each LLM call.
- Register Guard as a BeforeLLMHook to deny new LLM calls once the running total for a session exceeds the budget.
The default behavior is to count TotalTokens against a single shared budget per session. Supply a CostFunc to convert tokens into dollars (or any other currency) when you need finer-grained control.
BudgetTracker is safe for concurrent use.
Example:
bt := agent.NewBudgetTracker(100_000) // 100k tokens per session loop.OnEvent(bt.Handler()) loop.BeforeLLMHooks = append(loop.BeforeLLMHooks, bt.Guard())
func NewBudgetTracker ¶
func NewBudgetTracker(budget int) *BudgetTracker
NewBudgetTracker returns a tracker enforcing a cumulative token ceiling per session. Pass 0 to record usage without denying calls.
func (*BudgetTracker) Guard ¶
func (bt *BudgetTracker) Guard() BeforeLLMHook
Guard returns a BeforeLLMHook that denies the next LLM call once the session's cumulative TotalTokens exceeds Budget. Append it to loop.BeforeLLMHooks.
func (*BudgetTracker) Handler ¶
func (bt *BudgetTracker) Handler() EventHandler
Handler returns an EventHandler that accumulates token usage for each "usage" StreamEvent. Register it with loop.OnEvent.
func (*BudgetTracker) Reset ¶
func (bt *BudgetTracker) Reset(sessionKey string)
Reset clears the recorded usage for a session, allowing it to start fresh against the budget. Reset with an empty string clears every session.
func (*BudgetTracker) Rewind ¶
func (bt *BudgetTracker) Rewind(sessionKey string, refund TokenUsage)
Rewind subtracts the given TokenUsage from a session's accumulated total, effectively refunding tokens that were charged but won't be billed.
Use cases:
- The user cancels a turn that was already mid-stream; the tokens that reached the provider get charged but the partial output is discarded. Refund so the user isn't double-billed against their cap.
- Regenerate replaces a prior answer; the old answer's tokens stop counting against the live budget once the new turn lands.
- Sub-agent worker failed cleanly and the parent decides not to retry; refund so the parent's session budget doesn't burn capacity on a dropped result.
Floors at zero per field so a buggy caller can't push the counter negative (which would then under-count future legitimate usage). Refunding a session that has no recorded usage is a no-op.
Safe for concurrent use.
func (*BudgetTracker) Snapshot ¶
func (bt *BudgetTracker) Snapshot() map[string]TokenUsage
Snapshot returns a copy of the per-session token usage recorded by the tracker. The returned map is safe for the caller to read and mutate; it reflects the state at the moment of the call.
func (*BudgetTracker) Usage ¶
func (bt *BudgetTracker) Usage(sessionKey string) TokenUsage
Usage returns a snapshot of the recorded token usage for a session. Returns the zero value when the session has no usage yet.
type CapabilityProvider ¶ added in v0.40.0
type CapabilityProvider interface{ Capabilities() LLMCapabilities }
CapabilityProvider optionally reports an adapter's transport features, so a consumer that requires one (a judge that compares images, a caller that depends on schema enforcement) can reject an unsuitable provider at construction instead of discovering it from a confident, wrong answer.
Three rules make the signal trustworthy; breaking any of them turns it back into a guess:
- Absence means unknown, not false. A provider that does not implement this interface makes no claim, and callers decide how to treat that. Implement it on every adapter — including fakes that support nothing, which is exactly the case the interface exists to catch.
- A decorator around a single LLMProvider must forward that provider's report, and must not implement this interface when the wrapped provider does not — pick the concrete type at construction. Otherwise wiring tracing silently erases a capability the caller checks for, or invents a claim the underlying adapter never made. A multiplexer that cannot know its target in advance (a router) cannot do that, and instead reports the intersection of everything it might dispatch to, counting an undeclared member as supporting nothing: that errs toward a loud rejection at construction rather than a silent wrong answer at run time.
- The report describes the adapter, not the model. A gateway that fronts both text-only and multimodal models answers for the transport it speaks; selecting a model that honours it stays the caller's job.
type ConfirmFunc ¶
ConfirmFunc is called when a tool declares RequiresConfirmation(). It blocks the loop until a human decision is made. Return true to approve execution, false to deny. The toolName and argsJSON are provided for display to the user.
func ConfirmHITLFromContext ¶
func ConfirmHITLFromContext(ctx context.Context) ConfirmFunc
ConfirmHITLFromContext returns the ConfirmFunc stamped onto ctx by the parent loop, or nil if none is present. Sub-agent tools call this immediately after constructing their worker AgentLoop and assign the result so RequiresConfirmation tools inside the sub-agent surface through the same approval path as the outer loop.
type ConfirmPlanFunc ¶
type ConfirmPlanFunc func(ctx context.Context, plan PlanProposal) bool
ConfirmPlanFunc receives the assistant's proposed plan and returns true to approve (loop exits plan mode and resumes normal execution) or false to deny (the model is told to revise via the tool result).
type ConfirmationGateUnconfiguredError ¶
type ConfirmationGateUnconfiguredError struct {
ToolName string
}
ConfirmationGateUnconfiguredError carries the tool name whose confirmation gate could not be resolved. Surfaced when a tool declares RequiresConfirmation()=true but the AgentLoop has no ConfirmHITL callback and no PermissionAllow rule covers the call. This is an operator-side configuration bug — the directive in the tool message tells the model so explicitly.
func (*ConfirmationGateUnconfiguredError) Error ¶
func (e *ConfirmationGateUnconfiguredError) Error() string
func (*ConfirmationGateUnconfiguredError) Is ¶
func (e *ConfirmationGateUnconfiguredError) Is(target error) bool
type ConsolidateResult ¶
ConsolidateResult reports what changed in a single Consolidate call. Useful for telemetry/logging without re-reading the store. The "before" count is the size of the existing scope, "after" is the merged result.
type Consolidator ¶
type Consolidator struct {
// Store is where extracted notes land. Required.
Store memory.Store
// LLM is the provider used to extract and merge notes. Required.
LLM LLMProvider
// Prompt overrides the default merge-and-extract instruction.
// Empty string falls back to defaultConsolidatorPrompt below — a
// neutral template that works across domains.
Prompt string
// MaxNotes caps the curated note count after merge. 0 applies the
// default of 30 — small enough to stay under typical loader
// TokenBudget after FormatNotes overhead, large enough to retain
// the long tail of useful per-user knowledge.
MaxNotes int
// MinTranscriptMessages skips consolidation when the transcript
// has fewer than this many non-system messages. 0 applies the
// default of 3 — anything shorter rarely contains durable
// knowledge worth the LLM round trip.
MinTranscriptMessages int
// FirePolicy controls how often the AgentLoop's post-Run hook
// invokes Consolidate. The zero value applies DefaultFirePolicy
// (MinInterval = 10m, no turn-count throttle) — a sane "don't
// burn money" default for chat workloads where bursts of
// related turns shouldn't each trigger a fresh LLM call. Set
// Disabled = true to skip auto-fire entirely and drive
// Consolidate manually from a cron / logout hook. See FirePolicy
// for the per-field semantics.
//
// Direct calls to Consolidate (outside the AgentLoop hook) bypass
// the policy — adopters running scheduled batch consolidations
// retain full control of timing.
FirePolicy FirePolicy
// contains filtered or unexported fields
}
Consolidator distills a closed session's transcript into Notes, merging with the scope's existing notes so dedupes, refinements, and stale-knowledge pruning happen in one LLM call. The output is the curated full state of the scope; the Store is updated atomically via ReplaceAll.
The merge design is what bounds long-term growth: every Consolidate call sees the prior notes and decides whether to keep, merge, or drop each one. A model that picks variable keys can't accumulate forever because the merger collapses semantic duplicates and caps the output count at MaxNotes.
Concurrency: Consolidate is safe to call concurrently for distinct scopes; same-scope concurrency is allowed but may produce last-writer-wins ReplaceAll behavior. Callers that auto-consolidate after every Run should serialize per-scope (the AgentLoop's fireConsolidator path does this implicitly by running once per Run in a detached goroutine).
func (*Consolidator) Consolidate ¶
func (c *Consolidator) Consolidate(ctx context.Context, scope string, transcript []history.Message) (ConsolidateResult, error)
Consolidate merges the scope's existing notes with knowledge extracted from transcript and atomically replaces the stored set. Returns the before/after counts and any error.
A nil/short transcript (below MinTranscriptMessages) is a no-op that returns the current size with no error — callers can fire Consolidate unconditionally after every Run without filtering.
type ContentEvent ¶
type ContentEvent struct {
Text string `json:"text"`
}
ContentEvent is assistant-produced text shown to the user.
type ContextChangeReason ¶ added in v0.38.0
type ContextChangeReason string
ContextChangeReason classifies why the loop rewrote a message before handing the conversation to the provider. It is a closed enum — the pruner has exactly three ways to shrink a message.
const ( // ContextChangeSoftTrim: a long tool/assistant message had its middle // cut out by the depth-based prune; head and tail survive. ContextChangeSoftTrim ContextChangeReason = "soft-trim" // ContextChangeOutlierDiscarded: the message blew past the outlier // ceiling and its entire payload was replaced by a system notice. This // is the only reason that loses content outright. ContextChangeOutlierDiscarded ContextChangeReason = "outlier-discarded" // ContextChangeArgsTruncated: a tool result was clipped to its first // few hundred runes because the run crossed the token-budget warn // threshold. ContextChangeArgsTruncated ContextChangeReason = "args-truncated" )
type ContextPolicy ¶ added in v0.38.0
type ContextPolicy string
ContextPolicy names which enforceTokenBudget path produced a trace, so a host can tell routine depth pruning apart from budget pressure.
const ( // ContextPolicyDefault is the unbudgeted path — MaxTokenBudget is // unset, so only the standard depth prune ran. ContextPolicyDefault ContextPolicy = "default" // ContextPolicyBudgetWarn: the estimate crossed budgetWarnRatio of // MaxTokenBudget and tool arguments were truncated. ContextPolicyBudgetWarn ContextPolicy = "budget-warn" // ContextPolicyBudgetEmergency: the estimate exceeded MaxTokenBudget // outright and the aggressive shallow prune ran. ContextPolicyBudgetEmergency ContextPolicy = "budget-emergency" )
type ContextRef ¶ added in v0.38.0
type ContextRef struct {
Index int `json:"index"`
Role string `json:"role"`
ToolCallID string `json:"tool_call_id,omitempty"`
CorrelationID string `json:"correlation_id,omitempty"`
Reason ContextChangeReason `json:"reason"`
EstTokensBefore int `json:"est_tokens_before"`
EstTokensAfter int `json:"est_tokens_after"`
}
ContextRef identifies one message the pruner rewrote for a single LLM call. Index is the position in the pre-prune slice; because no pruning path reorders or removes messages, it also indexes the post-prune slice — and, since the loop prunes a transient copy and persists the conversation at full fidelity, the same position in the slice returned by Sessions.History. That is what makes a trace joinable back to the stored transcript.
ToolCallID and CorrelationID are the stable handles for naming a tool result across events — CorrelationID is the agent-generated ID also carried by ToolCallEvent, so a host can join a trimmed message back to the call that produced it. Both are empty for assistant messages.
EstTokensBefore/After use the same 4-chars/token heuristic as MaxTokenBudget enforcement, so they are comparable with the event's totals but are not exact provider counts.
type ContextTraceEvent ¶ added in v0.38.0
type ContextTraceEvent struct {
Policy ContextPolicy `json:"policy"`
Iteration int `json:"iteration"`
Changes []ContextRef `json:"changes"`
EstTokensBefore int `json:"est_tokens_before"`
EstTokensAfter int `json:"est_tokens_after"`
}
ContextTraceEvent is the typed payload of EventTypeContextTrace. It is the answer to "why did the agent forget what I told it earlier" — context pruning runs before every LLM call and, without this, leaves no artifact behind.
Emitted once per LLM call, and only when the pruner actually rewrote a message: a turn whose context comfortably fits produces no events at all. Changes lists every rewritten message with its reason, grouped by the pass that produced it — argument truncation first, then depth pruning — so Index is ascending within a group but not across the whole slice. A given Index appears at most once under the current thresholds (argument truncation clips to well under the soft-trim threshold, and only tool messages are eligible for both) — treat that as an observation, not a guarantee, and do not key a map on Index.
Because the loop prunes a transient copy and leaves session history at full fidelity, the same long tool result is re-trimmed and re-reported on every iteration of a turn. Consumers that log these should expect near-duplicates across a multi-iteration run.
EstTokensBefore/After are whole-conversation estimates that include tool-call arguments, so they will not equal the sum of the per-Change numbers, which cover message content only. Both use the 4-chars/token heuristic MaxTokenBudget enforcement uses — good for spotting how much a prune saved, not for billing.
Iteration is the 0-indexed loop iteration the prune fed.
type ContinuedEvent ¶
type ContinuedEvent struct {
ContinuedFromIndex int `json:"continued_from_index"`
}
ContinuedEvent is the typed payload of EventTypeContinued. ContinuedFromIndex is the index of the last persisted message at the moment Continue was invoked.
type DegradedError ¶ added in v0.38.0
type DegradedError struct {
Units []ToolDegradation
}
DegradedError is the error form of a partial-success terminal, for adopters that classify turns by error rather than by event type. It matches errors.Is(err, ErrDegraded).
It is never returned from Run — a degraded turn produced a real answer, and surfacing it as a returned error would push callers to discard work that landed. It reaches adopters through DegradedEvent.Err.
func (*DegradedError) Error ¶ added in v0.38.0
func (e *DegradedError) Error() string
func (*DegradedError) Is ¶ added in v0.38.0
func (e *DegradedError) Is(target error) bool
Is reports ErrDegraded so errors.Is matches without unwrapping.
type DegradedEvent ¶ added in v0.38.0
type DegradedEvent struct {
Units []ToolDegradation `json:"units"`
Err error `json:"-"`
}
DegradedEvent is the typed payload of EventTypeDegraded — the terminal state that had no representation before: the expensive artifact landed, the derived bookkeeping did not. Reporting it as Done would hide a real inconsistency; reporting it as an error would invite a retry that duplicates work that already succeeded.
Fires only when at least one tool returned a tools.Degradation, and annotates the turn's terminal rather than replacing it, so existing consumers are unaffected. Position depends on how the turn ended:
- Final answer: emitted immediately BEFORE DoneEvent.
- Cap or fatal error (MaxIters, tool-call cap, LLM failure): emitted by a deferred Run-level sweep, so it arrives AFTER the LimitExhaustedEvent / ErrorEvent frame.
The second case matters: a consumer that tears down on the first error frame will miss it. Drain the stream to completion if you need the degradation record from failed turns — which is exactly the turn whose unreliable state most needs repairing.
Units lists every degradation of the Run in the order the tools raised them. Err carries the same information as a *DegradedError for adopters that classify by errors.Is(err, ErrDegraded); it is reconstructed from Units when the event is decoded from the wire.
type DoneEvent ¶
type DoneEvent struct{}
DoneEvent marks the end of the stream — no more events will arrive.
type DynamicContextFunc ¶
DynamicContextFunc returns per-request text to append to the message list at LLM-call time. Return "" to skip. The returned text is NOT persisted to session history — distinguishing this from mutating SessionManager.SystemPrompt.
Typical use cases: today's date, per-session feature flags, dynamic RAG snippets, per-org prompt variants.
Hot-path warning: called on every LLM invocation, which includes retries, Reflect rounds, and every ReAct iteration within a single turn. Do no synchronous I/O here — close over pre-computed state or cache externally with a TTL. A function that does a DB round trip will multiply per-turn latency by the iteration count.
Stability: callers should return values that are stable across the iterations of a single user turn. A timestamp that changes every second defeats prompt caching and can confuse the model across tool-call rounds.
Prompt-cache placement: the text is appended as a NEW message at the tail of the message list, not inserted into the system message. This keeps the historical prefix (system + persisted turns) byte-identical across dynamic changes, so an Anthropic CacheHint on the last persisted user message stays valid regardless of how often the dynamic text rotates. The dynamic tail itself is fresh on every call, which is the correct behavior — fresh content was never going to be cached anyway.
Sub-agent scope: DynamicContext is per-AgentLoop, but the parent loop installs its DynamicContext on the per-tool context.Context before each tool invocation (see loop_execute.go). Sub-agent tools (CallSQLAgentTool, CallSubAgentTool) read it via DynamicContextFuncFromContext and wire it onto their worker loop, so time-sensitive context like "today is …" flows down through agent hierarchies without requiring callers to set it on every nested loop manually.
func DynamicContextFuncFromContext ¶
func DynamicContextFuncFromContext(ctx context.Context) DynamicContextFunc
DynamicContextFuncFromContext returns the DynamicContextFunc stamped onto ctx by the parent loop, or nil if none is present. Sub-agent tools call this immediately after constructing their worker AgentLoop and assign the result to workerLoop.DynamicContext.
type ErrorEvent ¶
ErrorEvent signals a terminal failure for the current iteration. Err holds the structured error (usable with errors.Is / errors.As); Message is its string form for callers that only need display text.
type EventHandler ¶
type EventHandler func(ctx context.Context, sessionKey string, ev StreamEvent)
EventHandler is called for every StreamEvent emitted during the agent loop, including events from LLM providers. It runs synchronously in the loop goroutine. Use for metrics, structured logging, token tracking, or custom analytics. sessionKey identifies which conversation the event belongs to.
type EventPayload ¶
type EventPayload interface {
// contains filtered or unexported methods
}
EventPayload is a sealed interface implemented by every typed event payload. Every payload reports its matching StreamEventType so the Event() helper can build a self-consistent StreamEvent in one call. Use a type switch on the Payload field of a StreamEvent to pattern-match concrete cases:
switch p := ev.Payload.(type) {
case ContentEvent:
buf.WriteString(p.Text)
case UsageEvent:
total += p.Usage.TotalTokens
case ErrorEvent:
return p.Err
}
The sealing method is unexported, so only this package can add payload types — exhaustive matches stay stable across versions.
type EventVisitor ¶
type EventVisitor interface {
VisitContent(ContentEvent)
VisitThought(ThoughtEvent)
VisitToolCall(ToolCallEvent)
VisitToolProgress(ToolProgressEvent)
VisitActionRequired(ActionRequiredEvent)
VisitUsage(UsageEvent)
VisitError(ErrorEvent)
VisitDone(DoneEvent)
VisitReflected(ReflectedEvent)
VisitToolCallReady(ToolCallReadyEvent)
VisitTaskList(TaskListEvent)
VisitMaxItersReached(MaxItersReachedEvent)
VisitSessionCreated(SessionCreatedEvent)
VisitLimitExhausted(LimitExhaustedEvent)
VisitHITLDenied(HITLDeniedEvent)
VisitHITLTimedOut(HITLTimedOutEvent)
VisitRegenerated(RegeneratedEvent)
VisitContinued(ContinuedEvent)
VisitMemoryLoaded(MemoryLoadedEvent)
VisitMemoryConsolidated(MemoryConsolidatedEvent)
VisitRunCost(RunCostEvent)
VisitContextTrace(ContextTraceEvent)
VisitDegraded(DegradedEvent)
VisitUnknown(UnknownEvent)
}
EventVisitor is a typed double-dispatch interface. Implementing it gives the compiler teeth: adding a new payload type forces every visitor in the codebase to handle it.
Prefer the type-switch on ev.Payload for ad-hoc consumers; prefer a visitor when the same handler logic lives across many call sites and you want compiler-enforced exhaustiveness.
type FirePolicy ¶
type FirePolicy struct {
// Disabled, when true, the AgentLoop's post-Run hook never
// auto-fires. Adopters call Consolidate themselves.
Disabled bool
// NTurns suppresses auto-fires until this many completed Runs
// have happened for the same scope since the last fire. 0
// disables this throttle. Useful when conversations are slow
// (one turn per hour) and the time-based throttle alone would
// fire too often relative to information density.
NTurns int
// MinInterval enforces a minimum wall-clock gap between fires
// for the same scope. 0 disables this throttle.
MinInterval time.Duration
}
FirePolicy throttles the AgentLoop's auto-fire path so a long session doesn't bill one LLM call per turn for consolidation.
All three fields are independent; they're evaluated in order with short-circuit semantics:
- Disabled : if true, fire is suppressed unconditionally.
- MinInterval : if non-zero, suppresses fires within wall-clock interval of the prior fire for the same scope.
- NTurns : if non-zero, suppresses fires until N completed Runs have accumulated since the prior fire for the same scope.
Combining MinInterval and NTurns AND's the conditions — both must allow before a fire happens. The first Run for a scope (no prior fire) is always allowed regardless of policy unless Disabled.
Manual Consolidate calls bypass FirePolicy. Adopters running a nightly batch can set Disabled = true and call Consolidate directly from their scheduler.
type GenerateJSONRequest ¶
type GenerateJSONRequest struct {
// Messages is the conversation to send. Must contain at least one user
// message. Keep it short: this is a one-shot call, not a loop.
Messages []history.Message
// Output describes the JSON shape the caller wants back. Schema must
// be non-empty; Name and Description are forwarded when the provider
// supports them (OpenAI, Anthropic synthesizer).
Output StructuredOutput
}
GenerateJSONRequest is the input to GenerateJSON. Messages follow the same shape the AgentLoop passes to an LLMProvider — typically a system message plus a user message describing the task.
type HITLDeniedError ¶
type HITLDeniedError struct {
ToolName string
}
HITLDeniedError carries the tool name that was denied.
func (*HITLDeniedError) Error ¶
func (e *HITLDeniedError) Error() string
func (*HITLDeniedError) Is ¶
func (e *HITLDeniedError) Is(target error) bool
type HITLDeniedEvent ¶
HITLDeniedEvent is the typed payload of EventTypeHITLDenied. Sub-agent wrappers watch for this so they can surface a clear "HITL_BLOCKED: denied" signal to the outer agent.
type HITLTimedOutError ¶
HITLTimedOutError carries the tool name and configured timeout for an expired HITL approval prompt. Surfaced when AgentLoop.ConfirmHITLTimeout elapses before the operator responds, so the model directive can ask the user to retry instead of routing around the gate.
func (*HITLTimedOutError) Error ¶
func (e *HITLTimedOutError) Error() string
func (*HITLTimedOutError) Is ¶
func (e *HITLTimedOutError) Is(target error) bool
type HITLTimedOutEvent ¶
type HITLTimedOutEvent struct {
Tool string `json:"tool"`
Args string `json:"args,omitempty"`
Timeout time.Duration `json:"timeout"`
}
HITLTimedOutEvent is the typed payload of EventTypeHITLTimedOut. Mirrors HITLDeniedEvent and additionally carries the configured Timeout so a UI can show "approval expired after 2m" without reaching back into agent state.
type HookRejectedError ¶
type HookRejectedError struct {
Cause error
}
HookRejectedError carries the underlying hook error.
func (*HookRejectedError) Error ¶
func (e *HookRejectedError) Error() string
func (*HookRejectedError) Is ¶
func (e *HookRejectedError) Is(target error) bool
func (*HookRejectedError) Unwrap ¶
func (e *HookRejectedError) Unwrap() error
type IncompleteKind ¶ added in v0.39.0
type IncompleteKind string
IncompleteKind classifies why a provider stopped generating early. Every provider has its own stop-reason vocabulary ("MAX_TOKENS", "length", "max_tokens"); each translates into these three cases so consumers route on one contract instead of three.
const ( // IncompleteTruncated: an output-length cap cut the response short. IncompleteTruncated IncompleteKind = "truncated" // IncompleteBlocked: a content policy stopped the generation. IncompleteBlocked IncompleteKind = "blocked" // IncompleteOther: neither a length cap nor a policy — a malformed // tool call, or a backend stop the provider does not classify. The // response is still partial, but it matches no sentinel, so retry // behavior stays at the default. IncompleteOther IncompleteKind = "other" )
type IncompleteResponseError ¶ added in v0.39.0
type IncompleteResponseError struct {
// Provider names the vendor package that produced the error, matching
// the error-message prefix convention ("anthropic", "openai", "gemini").
Provider string
// Reason is the provider's own stop reason, verbatim.
Reason string
// Kind is the provider-neutral classification.
Kind IncompleteKind
}
IncompleteResponseError reports a generation that ended before the model finished. Every provider returns it for the same situations — an output cap fired, or a content filter stopped the stream — so an adopter writes one branch rather than one per vendor:
if errors.Is(err, agent.ErrLLMTruncated) {
// raise the provider's token cap, or ask for less
}
Whatever streamed before the stop still rides on the returned LLMResult (content and usage), because it is real output that cost real tokens — it is a prefix, though, never a complete answer. Reason carries the raw provider stop reason for logs; Kind is what routing should key on, via the sentinels above.
func (*IncompleteResponseError) Error ¶ added in v0.39.0
func (e *IncompleteResponseError) Error() string
func (*IncompleteResponseError) Is ¶ added in v0.39.0
func (e *IncompleteResponseError) Is(target error) bool
type LLMCapabilities ¶ added in v0.40.0
LLMCapabilities describes what a provider adapter can put on the wire. It does not promise that every model behind a compatible endpoint supports the feature; dynamic model capability checks remain the caller's job.
type LLMFailureError ¶
type LLMFailureError struct {
Cause error
}
LLMFailureError carries the underlying provider error.
func (*LLMFailureError) Error ¶
func (e *LLMFailureError) Error() string
func (*LLMFailureError) Is ¶
func (e *LLMFailureError) Is(target error) bool
func (*LLMFailureError) Unwrap ¶
func (e *LLMFailureError) Unwrap() error
type LLMProvider ¶
type LLMProvider interface {
GenerateStream(ctx context.Context, memory []history.Message, availableTools *tools.Registry, streamChan chan<- StreamEvent) (LLMResult, error)
}
LLMProvider abstracts the model backend (OpenAI/Gemini/Claude).
type LLMResult ¶
type LLMResult struct {
Content string
ToolCalls []PendingToolCall
Usage TokenUsage
}
LLMResult represents the structured response from the LLM provider. Content is optional — the agent loop accumulates content from "content" stream events. Providers may still set Content for backward compatibility, but it is only used as a fallback when no content events were emitted on the stream. ToolCalls must be populated when the model wants to invoke tools. Usage carries token accounting when the provider reports it.
func GenerateJSON ¶
func GenerateJSON(ctx context.Context, provider LLMProvider, req GenerateJSONRequest) (string, LLMResult, error)
GenerateJSON runs a single schema-constrained generation against the provider, bypassing the ReAct loop entirely. Use this when you just need "LLM, give me JSON matching this shape" without tools or iteration.
The returned string is the raw JSON body as emitted by the provider — use GenerateJSONInto[T] below when you already have a Go type for the response.
GenerateJSON never writes to disk, never touches SessionManager, and never invokes tools. The only ctx interaction is StructuredOutput injection (WithStructuredOutput) and whatever the provider itself reads from ctx (thinking budget, etc).
func GenerateJSONInto ¶
func GenerateJSONInto(ctx context.Context, provider LLMProvider, req GenerateJSONRequest, out any) (LLMResult, error)
GenerateJSONInto runs GenerateJSON and unmarshals the result into out. out must be a pointer to the target type. Returns the provider's LLMResult (usage / etc.) alongside any decoding error.
type LimitExhaustedEvent ¶
type LimitExhaustedEvent struct {
Kind LimitKind `json:"kind"`
Limit int `json:"limit"`
Used int `json:"used,omitempty"`
Reason LimitReason `json:"reason,omitempty"`
}
LimitExhaustedEvent is the typed payload of EventTypeLimitExhausted. Kind identifies which cap fired (see LimitKind constants); Limit is the configured ceiling and Used is the actual count at the moment of the trip. For provider truncation kinds, Used is unset (the provider does not report token usage in the same shape).
Reason is an optional sub-classification — currently used by the Anthropic provider to flag LimitReasonIncompleteToolUse so adopters can distinguish "model cut off cleanly" from "model truncated mid-tool_use, retry required" without inspecting the LLMResult themselves. Zero value = no further detail.
type LimitKind ¶
type LimitKind string
LimitKind enumerates the cap categories surfaced via LimitExhaustedEvent. Custom providers may invent their own kinds — adopters that match exhaustively should use a default branch.
const ( // LimitKindMaxIters: AgentLoop.MaxIters reached without a final answer. LimitKindMaxIters LimitKind = "max_iters" // LimitKindMaxToolCallsPerSession: cumulative tool-call cap exceeded. LimitKindMaxToolCallsPerSession LimitKind = "max_tool_calls_per_session" // LimitKindProviderMaxTokens: the LLM provider truncated the response // because its per-call MaxTokens cap fired. LimitKindProviderMaxTokens LimitKind = "provider_max_tokens" )
type LimitReason ¶
type LimitReason string
LimitReason is an optional sub-classification for LimitExhaustedEvent. Empty reason = "no further detail" (clean truncation, plain cap trip). Anthropic's docs call out the incomplete-tool-use case as one that adopters should handle differently: a clean text truncation can be presented as "model cut off; continue?", but a truncation that ate a tool_use mid-JSON strands the turn (the model wanted to call a tool but never finished naming the arguments) — auto-retry with a larger MaxTokens is the documented recovery. Custom providers may invent their own reasons.
const ( // LimitReasonIncompleteToolUse: the provider truncated the stream // mid-tool_use, leaving a partial JSON Input that the SDK could not // finalize. Adopters should retry the request with a larger MaxTokens // rather than treat the response as complete. Currently emitted by the // Anthropic provider only. LimitReasonIncompleteToolUse LimitReason = "incomplete_tool_use" )
type MaxItersReachedEvent ¶
type MaxItersReachedEvent struct {
Limit int `json:"limit"`
}
MaxItersReachedEvent signals that the loop exhausted its iteration cap without a final answer. Limit echoes AgentLoop.MaxIters at the time of the failure.
type MemoryConfig ¶
type MemoryConfig struct {
// TokenBudget caps the prompt-token cost of the injected memory
// block. 0 applies the default of 500 — enough for ~15 notes at
// typical content length without dominating most system prompts.
// Negative values are treated as 0. Estimation uses a 4-chars/
// token heuristic; accurate within ±20% for English.
TokenBudget int
// MaxNotes caps the per-Run note count passed to FormatNotes. 0
// applies the default of 50 — the typical upper bound a deployment
// wants before TokenBudget would start trimming anyway. Negative
// values are treated as 0.
MaxNotes int
}
MemoryConfig tunes the loader's per-Run cost. The defaults applied by loadMemoryNotes when fields are zero are documented per-field below.
Both bounds are enforced: the loader pulls at most MaxNotes from the store, then trims further to fit TokenBudget. Either alone may be sufficient — TokenBudget is the harder ceiling because it tracks the prompt impact directly; MaxNotes is a cheaper short-circuit that avoids loading huge result sets just to throw most of them away.
type MemoryConsolidatedEvent ¶
type MemoryConsolidatedEvent struct {
Scope string `json:"scope"`
Before int `json:"before"`
After int `json:"after"`
Error string `json:"error,omitempty"`
}
MemoryConsolidatedEvent is the typed payload of EventTypeMemoryConsolidated. Emitted by the detached consolidator goroutine after Consolidate returns — success or failure — so adopters can audit memory writes without polling the store.
Before/After are the scope's note counts pre and post merge. Error is the consolidator's failure string when non-empty; empty means the consolidation succeeded (or was a no-op due to a short transcript). Scope is empty when fail-closed (resolver returned ""), in which case no consolidation ran.
type MemoryLoadedEvent ¶
type MemoryLoadedEvent struct {
Scope string `json:"scope"`
NoteCount int `json:"note_count"`
EstimatedTokens int `json:"estimated_tokens,omitempty"`
}
MemoryLoadedEvent is the typed payload of EventTypeMemoryLoaded. Emitted at the start of every Run with memory enabled — adopters use it to log audit lines, drive UI badges, or detect anomalies (e.g. "agent loaded 0 notes for an authenticated user" → likely a scope-resolution bug).
Scope is the resolved memory scope (the output of MemoryScopeFunc). Empty Scope means the resolver returned "" and memory was skipped fail-closed; the event still fires so audit consumers can record the attempt. NoteCount is the number of notes the loader actually injected (post-Limit, post-TokenBudget trim). EstimatedTokens is the 4-chars/token estimate of the formatted memory block.
type MemoryScopeFunc ¶
MemoryScopeFunc maps an (ctx, sessionKey) pair to the scope used for memory reads and writes. The default — derived inside the loop — returns sessionKey unchanged, which keeps memory isolated per-conversation.
Override to share memory across sessions for the same user/tenant:
agent.WithMemoryScope(func(ctx context.Context, _ string) string {
if u, ok := ctx.Value(userIDKey{}).(string); ok {
return "user:" + u
}
return "anonymous"
})
type MockProvider ¶
type MockProvider struct {
IterationCounter int
}
MockProvider is used exclusively for examples and testing without an API Key. It hardcodes responses based on the tool requested to simulate a real LLM.
func NewMockProvider ¶
func NewMockProvider() *MockProvider
NewMockProvider creates a mock provider for testing and examples.
func (*MockProvider) GenerateStream ¶
func (m *MockProvider) GenerateStream(ctx context.Context, memory []history.Message, registry *tools.Registry, streamChan chan<- StreamEvent) (LLMResult, error)
type ModelPricing ¶
ModelPricing carries per-million-token rates for one model. Adopters populate from their provider's pricing page; the library treats the numbers as opaque floats and multiplies through.
Both fields are dollars per million tokens (e.g. Claude Sonnet at $3 in / $15 out is ModelPricing{InputPerMTokens: 3, OutputPerMTokens: 15}).
type Option ¶
type Option func(*AgentLoop)
Option configures an AgentLoop at construction time. Pass options to New (the recommended entry point) so loop configuration is captured up-front and the runtime state is built atomically:
loop := agent.New(sm, reg, llm,
agent.WithMaxIters(15),
agent.WithRetry(retryCfg),
agent.WithHITL(confirmFn, 2*time.Minute),
agent.WithPermissions(perms),
)
Options compose left-to-right; later options override earlier ones for the same field. The zero option (nil) is allowed for conditional wiring:
opts := []agent.Option{agent.WithMaxIters(15)}
if cfg.cache != nil {
opts = append(opts, agent.WithCache(cfg.cache))
}
loop := agent.New(sm, reg, llm, opts...)
func WithBeforeHook ¶
WithBeforeHook registers a hook that fires before every iteration. Hooks can veto by returning a non-nil error (HookRejectedError surfaces it to the stream). Multiple registrations append; hooks fire in registration order. nil hooks are silently dropped.
func WithBeforeLLMHook ¶
func WithBeforeLLMHook(h BeforeLLMHook) Option
WithBeforeLLMHook registers a per-call gate that fires right before every GenerateStream invocation (including retries). Return non-nil to abort the iteration — typical use is per-session spend caps via BudgetTracker.Guard.
func WithCache ¶
func WithCache(c *cache.SearchCache) Option
WithCache enables tool result caching with trigram similarity matching. nil disables caching (default). Build a cache with cache.NewSearchCache.
func WithConfirmPlan ¶
func WithConfirmPlan(fn ConfirmPlanFunc) Option
WithConfirmPlan registers the plan-approval callback. Fires when the model calls exit_plan_mode while PlanMode is active. Returning true approves the plan and clears PlanMode; false sends the model a revise directive.
func WithDynamicContext ¶
func WithDynamicContext(fn DynamicContextFunc) Option
WithDynamicContext registers a per-call context provider. The returned string is appended to the system prompt for that call only (never persisted). See DynamicContextFunc for the hot-path contract.
func WithEmitThoughts ¶
WithEmitThoughts controls whether streaming methods forward ThoughtEvent frames. Default: true. Set false to silence internal narration in production UIs; RunIteration suppresses thoughts regardless.
func WithHITL ¶
func WithHITL(fn ConfirmFunc, timeout time.Duration) Option
WithHITL wires the human-in-the-loop confirmation callback and an optional timeout. Tools whose Descriptor reports RequiresConfirmation fire the gate before execution. timeout=0 disables the deadline (gate blocks until the callback returns or ctx cancels). A nil fn leaves ConfirmHITL unset — HITL tools will auto-deny.
func WithMaxIters ¶
WithMaxIters caps the number of ReAct iterations per run. The loop emits MaxItersReachedEvent + LimitExhaustedEvent when the cap fires. Default: 15.
func WithMaxParallelToolCalls ¶ added in v0.43.0
WithMaxParallelToolCalls caps how many tool calls run concurrently inside one dependency wave. Defaults to 8; pass 0 for unlimited. Nothing is dropped — calls over the cap wait for a slot, so results are unchanged and only peak resource use differs. Raise it for latency-bound tools (HTTP fan-out), lower it for tools that each hold a scarce resource (database connections, subprocesses).
func WithMaxTokenBudget ¶
WithMaxTokenBudget sets the estimated token ceiling for the conversation context. The loop applies more aggressive pruning when the estimate crosses the budget. 0 (default) disables enforcement.
func WithMaxToolCallsPerSession ¶
WithMaxToolCallsPerSession caps cumulative tool calls across all iterations of a single Run. 0 (default) means unlimited. When the cap trips, the loop emits LimitExhaustedEvent and saves history.
func WithMaxToolCallsPerTurn ¶
WithMaxToolCallsPerTurn caps the wave size for a single iteration. 0 (default) means unlimited. Calls past the cap are short-circuited with a synthesized tool-error and a thought event explaining the drop.
func WithMemory ¶
func WithMemory(store memory.Store, cfg MemoryConfig) Option
WithMemory enables cross-session memory by attaching a Store and a loader configuration. On every Run the loop reads notes for the resolved scope (bounded by cfg) and appends them to the system message. Without this option the memory loader is a no-op at zero hot-path cost. Pair with WithMemoryScope to share memory across sessions for the same user/tenant, and with WithMemoryConsolidator to auto-distill closed sessions into notes.
cfg's zero value applies the documented defaults: TokenBudget=500, MaxNotes=50. Override either field on the call site to tune the per-Run memory cost.
func WithMemoryConsolidator ¶
func WithMemoryConsolidator(c *Consolidator) Option
WithMemoryConsolidator wires a Consolidator that fires after every Run terminating in DoneEvent. Runs detached from the request ctx so HTTP disconnects do not abort the LLM call. Pass nil to disable (default). Setting a consolidator without WithMemory is permitted — the consolidator writes to its own Store reference and the loader reads from al.Memory; in practice the same store backs both.
func WithMemoryScope ¶
func WithMemoryScope(fn MemoryScopeFunc) Option
WithMemoryScope overrides the default scope resolver (which returns sessionKey unchanged). Use to share memory across sessions for the same user: typically read a user_id off ctx and return a stable scope key derived from it. nil keeps the default.
func WithMeter ¶ added in v0.35.0
WithMeter enables OpenTelemetry metrics for the loop. It records a per-iteration latency histogram (gopheragent.agent.iteration.duration). The instrument is built once here so no allocation happens per iteration. nil (the default) disables metrics.
func WithOnEvent ¶
func WithOnEvent(h EventHandler) Option
WithOnEvent registers a per-event handler invoked for every emitted StreamEvent. Multiple registrations append; handlers fire in order. nil handlers are silently dropped.
func WithOnToolResult ¶
func WithOnToolResult(h ToolResultHook) Option
WithOnToolResult registers a post-tool-execution hook that may rewrite the result string or veto it. See ToolResultHook for the contract.
func WithPermissions ¶
func WithPermissions(p PermissionChecker) Option
WithPermissions wires a permission policy consulted for every tool call before HITL fires. See PermissionChecker / NewPermissionRuleSet.
func WithPriceTable ¶
func WithPriceTable(table PriceTable, model string) Option
WithPriceTable supplies the rates used to estimate cost for LLM calls whose provider does not report one. The loop accumulates TokenUsage across every call in a Run and emits RunCostEvent right before DoneEvent, with USD from table[model].
This is only needed for providers that bill silently. A provider that sets TokenUsage.CostUSD is already exact, and RunCostEvent fires for it whether or not a table is configured — leave this unset in that case rather than adding rates the loop will never consult. Adopters with router-style multi-model setups whose pricing varies per call and whose providers report nothing should still roll cost up themselves from UsageEvent.
model is the key looked up in table for cost computation — pass the canonical name of the model this loop drives. Unknown keys produce a RunCostEvent with USD=0 but Usage still populated, so adopters with a dynamic pricing source can compute cost downstream.
func WithReflect ¶
WithReflect enables N serial self-critique passes after the model returns a final answer. Each pass appends a critique prompt and asks the model to revise. Set prompt to "" to use the neutral default. 0 (default) disables reflection; cost and latency multiply by (1 + N).
func WithRequestInvariant ¶ added in v0.43.0
func WithRequestInvariant(onViolation RequestViolationFunc) Option
WithRequestInvariant enables a per-call check at the LLM boundary that the request path neither wrote through to stored history nor produced a request a re-derivation cannot reproduce. onViolation is called synchronously on the loop goroutine with a descriptive error; the turn continues either way, so a handler that fails the build (t.Fatal, panic in a staging binary) is the point.
Off by default. Enabled, it costs one copy of the message headers plus one extra derivation per LLM call — cheap enough for staging, and not something to leave on in a latency-sensitive production path.
func WithRetry ¶
func WithRetry(cfg *RetryConfig) Option
WithRetry configures exponential-backoff retry for transient LLM errors. nil disables retries (default). DefaultRetryConfig() gives a reasonable 3-retry start. Retries are skipped once content has started streaming.
func WithSpeculativeTools ¶
WithSpeculativeTools enables parallel speculation: when a provider surfaces tool_call_ready mid-stream, the loop kicks off safe calls in parallel with the remaining LLM stream. Eligibility excludes HITL-gated tools, plan-mode tools, and <output_of:...>-dependent calls. Default: false. Only Anthropic emits the mid-stream signal today.
func WithThinking ¶
WithThinking turns on extended reasoning for providers that support it. The argument is a token hint; the Anthropic adapter clamps to (1024, MaxTokens). 0 (default) keeps requests on the non-reasoning path. Distinct from agent.WithThinkingBudget which is a ctx decorator used to override the per-iteration budget on a single call.
func WithToolErrorHintFormatter ¶
func WithToolErrorHintFormatter(fn ToolErrorHintFormatter) Option
WithToolErrorHintFormatter customizes the text written back to the model after a tool error. nil (default) uses defaultToolErrorHint. Override to inject domain-specific remediation advice the model can act on next turn.
func WithToolSelector ¶
WithToolSelector enables semantic tool-list filtering per turn. nil (default) means every registered tool is presented every turn. Build a selector with tools.NewSelector.
func WithTracer ¶ added in v0.35.0
WithTracer enables OpenTelemetry tracing of the ReAct loop. Each iteration opens an "agent.iteration" span; because that span rides on the ctx threaded into the LLM call and tool execution, spans produced by the otelllm decorator and the oteltools middleware nest as its children. nil (the default) disables tracing at zero hot-path cost — no span is created and ctx is untouched.
func WithoutAutoCacheSystem ¶
func WithoutAutoCacheSystem() Option
WithoutAutoCacheSystem disables the auto-stamp of CacheHint=true on the first system message of every LLM call. Default behavior is to stamp (Anthropic prompt-cache prefix). Disable when you manage cache breakpoints by hand.
func WithoutToolChainingHint ¶
func WithoutToolChainingHint() Option
WithoutToolChainingHint suppresses the automatic <output_of:...> hint the loop injects into the system prompt when multiple tools are registered. Use when you have documented chaining yourself or want to opt out of the scheduling syntax entirely.
type PendingToolCall ¶
PendingToolCall represents a single tool invocation requested by the LLM.
type PermissionChecker ¶
type PermissionChecker interface {
Check(ctx context.Context, toolName, argsJSON string) PermissionDecision
}
PermissionChecker is consulted before the HITL prompt on every tool call. Implementations must be safe for concurrent use — the loop may run multiple tool calls in parallel within a single wave.
type PermissionDecision ¶
type PermissionDecision int
PermissionDecision is the outcome of a per-call permission check.
The default zero value is PermissionPrompt so a nil / unopinionated check behaves as if no policy existed and the loop falls back to the tool's own RequiresConfirmation() flow.
const ( // PermissionPrompt means the policy has no opinion — the loop // defers to the tool's RequiresConfirmation() and ConfirmHITL. PermissionPrompt PermissionDecision = iota // PermissionAllow auto-approves the call, bypassing HITL even when // the tool declares RequiresConfirmation() = true. Use with care: // this is the knob that turns a "human every 30 seconds" agent // into one you can leave running overnight. PermissionAllow // PermissionDeny blocks the call and surfaces a structured error to // the model, bypassing HITL entirely. Deny overrides everything, // including tools that do not declare RequiresConfirmation(). PermissionDeny // PermissionConfirm forces the HITL gate for this call even when the // tool's descriptor does not declare RequiresConfirmation. // // This is what makes confirmation per-argument rather than per-tool. // RequiresConfirmation is a static field on ToolDescriptor, so without // this a policy could only ever restrict a tool that already prompts — // never escalate one that does not. A tool that is harmless for most // inputs and dangerous for a few had to be split into two registered // tools to get a gate on the dangerous subset. // // rules.Confirm(`write_file(*"/etc/*"*)`) PermissionConfirm )
type PermissionDeniedError ¶
type PermissionDeniedError struct {
ToolName string
}
PermissionDeniedError carries the tool name that was denied by policy.
func (*PermissionDeniedError) Error ¶
func (e *PermissionDeniedError) Error() string
func (*PermissionDeniedError) Is ¶
func (e *PermissionDeniedError) Is(target error) bool
type PermissionRuleSet ¶
type PermissionRuleSet struct {
// contains filtered or unexported fields
}
PermissionRuleSet is a deny-over-allow policy composed of glob patterns. It implements PermissionChecker so it can be assigned to AgentLoop.Permissions directly.
Rule syntax: "ToolName" or "ToolName(glob)". The glob supports the usual shell-style * (any sequence) and ? (any single character); no character classes or ** syntax. When the glob is absent, the rule matches every invocation of ToolName. Globs are matched against the raw argsJSON — implement PermissionChecker directly if you need structured (field-aware) matching.
Evaluation order: Deny rules are checked first, then Allow. The first match wins; if no rule matches the decision is PermissionPrompt and the loop falls back to HITL.
rules := agent.NewPermissionRuleSet().
Allow(`Bash(*"git status"*)`, `WebFetch(*github.com*)`).
Deny(`Bash(*"rm -rf"*)`, `Bash(*"sudo "*)`)
loop.Permissions = rules
func NewPermissionRuleSet ¶
func NewPermissionRuleSet(allow, deny []string) (*PermissionRuleSet, error)
NewPermissionRuleSet parses allow + deny pattern slices and returns a ready-to-use ruleset. Returns an error when any pattern is malformed — adopters loading rules from YAML / env / API input get a typed failure instead of a panic.
Patterns use the shape "ToolName" or "ToolName(glob)" where glob accepts * (any sequence) and ? (any single character). Empty input slices produce an empty ruleset that Check always evaluates to PermissionPrompt.
rs, err := agent.NewPermissionRuleSet(
[]string{"read_file:/etc/*"},
[]string{"write_file:*"},
)
if err != nil { return err }
func (*PermissionRuleSet) AddAllow ¶
func (r *PermissionRuleSet) AddAllow(patterns ...string) error
AddAllow appends one or more patterns to the allow list. Returns an error when any pattern is malformed. Concurrency note: safe to call before the ruleset is shared with an AgentLoop; callers mutating live policies should guard their own writes.
func (*PermissionRuleSet) AddConfirm ¶ added in v0.37.0
func (r *PermissionRuleSet) AddConfirm(patterns ...string) error
AddConfirm appends one or more patterns that force the HITL gate even when the tool's descriptor does not declare RequiresConfirmation. This is how a policy escalates a specific argument shape — a write tool that is routine everywhere except one path, say — without splitting the tool in two just to attach a gate.
Precedence is Deny, then Allow, then Confirm: an explicit allow for the same call wins, so a broad Confirm can be narrowed by a specific Allow.
func (*PermissionRuleSet) AddDeny ¶
func (r *PermissionRuleSet) AddDeny(patterns ...string) error
AddDeny appends one or more patterns to the deny list. Deny takes precedence over Allow at Check time.
func (*PermissionRuleSet) Check ¶
func (r *PermissionRuleSet) Check(_ context.Context, toolName, argsJSON string) PermissionDecision
Check returns PermissionDeny / PermissionAllow / PermissionConfirm / PermissionPrompt for the given call. It is safe for concurrent use once all rules have been registered — internal slices are only appended to by the Add* methods.
type PlanProposal ¶
type PlanProposal struct {
Plan string
RawArgs json.RawMessage
}
PlanProposal is the payload handed to ConfirmPlanFunc when the model calls exit_plan_mode. Plan carries the markdown text from the built-in tool's `plan` argument — the common case. RawArgs is the untouched JSON of the tool call, so a host that registers its own exit_plan_mode tool with a structured argument schema can json.Unmarshal typed steps directly instead of parsing them back out of markdown. Plan is empty when the structured schema has no top-level string `plan` field; RawArgs is always populated.
type PriceTable ¶
type PriceTable map[string]ModelPricing
PriceTable maps a canonical model name to its pricing. Lookups are by exact key; adopters use whatever string they like (the provider's canonical name, an internal tier label) as long as it matches the AgentLoop.PriceModel setting.
func (PriceTable) Compute ¶
func (pt PriceTable) Compute(model string, usage TokenUsage) float64
Compute returns the dollar cost of usage under the named model's pricing, or zero when the model is unknown to the table. Negative inputs are clamped to zero so a buggy accumulator can't surface a "credit" event.
type ReflectedEvent ¶
type ReflectedEvent struct {
Text string `json:"text"`
Round int `json:"round"`
Score *float64 `json:"score,omitempty"`
}
ReflectedEvent delivers a post-critique canonical answer. Round indicates which self-critique pass produced it (1-indexed); consumers typically keep the last seen payload as the authoritative response.
The event fires only for a round the loop actually adopted, so the last-seen-wins contract holds whether or not AgentLoop.Scorer is set. Score is the adopted round's rank under that Scorer, and is nil when no Scorer is configured — a rejected round emits a thought event naming its score instead.
It is a pointer because zero is a legitimate score: a 0–100 rubric can return 0, and the Scorer docs offer negated latency as a valid unit where 0 is the best possible value. A bare float64 with omitempty would erase that score from the wire and make it indistinguishable from "unscored" in Go.
type RegeneratedEvent ¶
type RegeneratedEvent struct {
PreviousAssistantIndex int `json:"previous_assistant_index"`
TruncatedAt int `json:"truncated_at"`
}
RegeneratedEvent is the typed payload of EventTypeRegenerated. PreviousAssistantIndex is the index of the final assistant message in the pre-regenerate history — UIs mark that bubble as superseded. TruncatedAt is the length of the rewound prefix (msgs[:TruncatedAt] is what survived the safe-boundary truncation).
type RequestViolationFunc ¶ added in v0.43.0
RequestViolationFunc receives a description of a broken request-path invariant. It runs synchronously on the loop goroutine, so keep it cheap; panicking or blocking here stalls the turn.
type RetryAttemptHook ¶
RetryAttemptHook fires once per retry attempt, right before the exponential-backoff wait. attempt is 1-indexed (first retry = 1). err is the failure that triggered the retry. nextDelay is how long the loop will sleep before the next call. The hook runs synchronously on the loop goroutine — keep it cheap (log line, metric increment, span event). Adopters use it to answer "is the run slow because of retries or one slow call?" without parsing thought events.
type RetryConfig ¶
type RetryConfig struct {
// MaxRetries is the maximum number of additional attempts after the first failure.
// 0 disables retries (default).
MaxRetries int
// BaseDelay is the initial wait before the first retry (default: 500ms).
BaseDelay time.Duration
// MaxDelay caps the exponential growth (default: 30s).
MaxDelay time.Duration
// OnAttempt, when non-nil, fires once per retry attempt with the
// structured (attempt, err, nextDelay) tuple. See RetryAttemptHook.
OnAttempt RetryAttemptHook
}
RetryConfig controls exponential-backoff retry behaviour for LLM calls. Only transient errors are retried; context cancellation / deadline errors are not. Retry is silently skipped if any "content" event has already been streamed to the client — partial responses cannot be rewound.
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns a sensible default: 3 retries, 500ms base, 30s cap.
type RunCostEvent ¶
type RunCostEvent struct {
Model string `json:"model,omitempty"`
Usage TokenUsage `json:"usage"`
USD float64 `json:"usd"`
}
RunCostEvent is the typed payload of EventTypeRunCost. Emitted at the end of a Run that produced any accounting, when a PriceTable is configured or a provider reported a charge. Adopters surface USD on the UI, push to billing telemetry, or alert on per-Run cost spikes without re-aggregating UsageEvents themselves.
USD is resolved per LLM call and then summed: a call whose provider reported TokenUsage.CostUSD contributes that exact charge, and any other call is estimated from the AgentLoop's Model + PriceTable. So a Run against a self-pricing gateway needs no table at all, and one that mixes backends bills each call the best way available rather than forcing the whole Run into one method.
Usage.CostUSD carries the provider-reported portion alone. Compare it against USD to see how much of the total was billed rather than estimated: equal means the figure is exact, zero means it is all table-derived. When the Model isn't in the table and no provider priced the Run, USD is zero but Usage still reflects the true accumulated tokens — useful for adopters computing cost downstream from a dynamic price source.
type RunResult ¶ added in v0.38.0
RunResult is one candidate answer handed to a Scorer for ranking. It is deliberately narrow: everything a scorer needs to judge a candidate, nothing that ties it to the axis the candidate came from.
Answer is the candidate final-answer text. Messages is the conversation it terminates, including the candidate itself as the last assistant message — read-only; a scorer must not mutate it. Round is the 1-indexed refinement pass for sequential scoring (self-critique), and 0 for the model's original, unrevised answer.
type Scorer ¶ added in v0.38.0
Scorer ranks candidate answers so the loop can keep the best one rather than the last one. Higher scores win; the unit is the implementation's business (a 0–100 rubric, a compile-pass count, a negated latency).
Score is called once per candidate on the loop goroutine, so a slow implementation adds directly to turn latency. It receives the turn's ctx and must honor cancellation. Returning an error drops that candidate from consideration without failing the turn — the loop keeps the best-scoring candidate it did manage to rank.
Implementations that call an LLM to judge multiply the turn's token spend; that spend is invisible to BudgetTracker unless the scorer itself accounts for it.
type ScorerFunc ¶ added in v0.38.0
ScorerFunc adapts a plain function to Scorer.
type SessionCreatedEvent ¶
type SessionCreatedEvent struct {
SessionKey string `json:"session_key"`
}
SessionCreatedEvent is the first frame of a stream when the loop is running a never-before-seen session. Carries the session key so SSE relays can forward the signal to the FE for sidebar pinning, and so integrators can hang one-shot work (auto-title, welcome payload, budget allocation) off the event without racing on history-emptiness.
type SessionForker ¶
type SessionForker interface {
// Fork creates a new session whose message history is a copy of the first
// atIndex messages from sessionKey. atIndex is clamped to the source length
// and snapped backward to a "safe" boundary — the resulting prefix never
// ends mid tool-call / tool-result group, so the forked session is always
// valid input to the agent loop. The behavior summary is copied; async
// tasks are not (they belong to the original session runtime).
//
// Returns the generated new session key. Fails if sessionKey does not exist
// or atIndex is negative.
Fork(ctx context.Context, sessionKey string, atIndex int) (string, error)
}
SessionForker is the optional capability for backends that support forking a session at a given message index. Used by ForkAtLastUser and any "branch this conversation" UI flow. Backends without forking simply don't implement this interface; callers type-assert and report a clear error when the capability is missing.
type SessionManager ¶
type SessionManager interface {
// History returns the persisted message log for sessionKey. Backends that
// cannot read return the error; an unseen session returns (nil, nil).
History(ctx context.Context, sessionKey string) ([]history.Message, error)
// SaveHistory atomically replaces the persisted log with msgs. Combines
// what used to be SetHistory + Save into one call so backends with real
// transactions (MySQL) can commit in a single round trip.
SaveHistory(ctx context.Context, sessionKey string, msgs []history.Message) error
// AsyncTasks returns the snapshot of background tasks parked on sessionKey.
// Backends that cannot read return the error; an unseen session returns
// (empty map, nil).
AsyncTasks(ctx context.Context, sessionKey string) (map[string]history.AsyncTask, error)
// SaveAsyncTasks atomically replaces the task snapshot. Same atomicity
// rationale as SaveHistory.
SaveAsyncTasks(ctx context.Context, sessionKey string, tasks map[string]history.AsyncTask) error
// Delete removes all in-memory and persisted state for sessionKey. Used to
// clean up ephemeral sub-agent and async-worker sessions after they
// complete so they do not accumulate in storage. Deleting a non-existent
// session is a no-op (returns nil). For end-user "delete this conversation"
// flows that need undelete, prefer the SoftDeletable capability.
Delete(ctx context.Context, sessionKey string) error
}
SessionManager is the minimal contract every history backend must provide. It covers the read/write/async-tasks/save/delete surface the agent loop itself touches. Optional capabilities (forking, querying, soft delete) are exposed via the SessionForker / SessionQueryable / SoftDeletable interfaces below — call sites that need them should type-assert at the boundary instead of demanding every backend implement features it does not need. This keeps the core interface within the project's "small interface" budget (CLAUDE.md: 3–6 methods).
type SessionQueryable ¶
type SessionQueryable interface {
// Query returns metadata for sessions whose key starts with prefix.
// Pass an empty prefix to list everything. Soft-deleted sessions are
// filtered out unless opts.IncludeDeleted is true. Result order honors
// opts.OrderBy (default: most recently updated first). Limit/Offset
// drive pagination.
Query(ctx context.Context, prefix string, opts history.SessionQueryOpts) ([]history.SessionMeta, error)
}
SessionQueryable is the optional capability for backends that support listing sessions by key prefix. Used by sidebars, admin UIs, and reporting tools. Backends that only need point lookups do not need to implement this.
type SessionTitler ¶
type SessionTitler interface {
// SetTitle records title against sessionKey. Calling with an empty
// string clears any previously-recorded title. Setting a title on a
// session the backend has not yet seen is permitted (the title is
// retained and joined to the session record once it is created).
SetTitle(ctx context.Context, sessionKey string, title string) error
}
SessionTitler is the optional capability for backends that can attach a human-readable title to a session — typically the auto-generated label from builtin.GenerateTitle rendered in a sidebar / picker UI. Backends that have no place to store metadata (ephemeral in-process caches) simply skip this capability; the SessionMeta.Title field stays empty.
Adopters call SetTitle once per session, usually from the handler that receives EventTypeSessionCreated. The title is then surfaced on every subsequent Query result for that session.
type SoftDeletable ¶
type SoftDeletable interface {
// SoftDelete marks sessionKey as deleted without removing data; reads
// (GetHistory / Query default) treat it as missing, but the row stays
// behind so Restore can undo the action. No-op if already deleted.
SoftDelete(ctx context.Context, sessionKey string) error
// Restore clears the deletion timestamp set by SoftDelete. No-op if
// the session is not soft-deleted.
Restore(ctx context.Context, sessionKey string) error
// PurgeDeletedBefore hard-deletes every soft-deleted session whose
// DeletedAt is strictly older than `before`. Returns the count purged.
// Pair with a periodic goroutine to bound storage growth from the
// soft-delete tail.
PurgeDeletedBefore(ctx context.Context, before time.Time) (int, error)
}
SoftDeletable is the optional capability for backends that support reversible deletion via a tombstone. Backends that only do hard deletes (e.g. ephemeral in-process caches) do not need to implement this.
type StreamEvent ¶
type StreamEvent struct {
// Type tags the kind of event. Always matches Payload's eventType().
Type StreamEventType `json:"type"`
// Source is the emitter tag for forwarded events (e.g. "subagent:foo").
// Empty for events originating from the receiving agent itself.
Source string `json:"source,omitempty"`
// ParentID is the parent session key at the top of the forwarding chain,
// useful for correlating every event back to the user-facing session.
ParentID string `json:"parent_id,omitempty"`
// Payload carries the typed event data. Never nil for events produced by
// the framework; consumers reaching across the wire should still tolerate
// nil from a malformed envelope.
Payload EventPayload `json:"-"`
}
StreamEvent represents a chunk of data sent via SSE. When Type is "error", Err holds the structured error so callers can use errors.Is/As.
Source and ParentID are populated when the event originated inside a sub-agent (or async worker) that forwarded it to a parent stream, giving consumers enough context to group, filter, or render a multi-agent timeline.
- Source — tag describing the emitter, e.g. "subagent:researcher". When a chain forwards through multiple sub-agents, tags are prepended with ">" so the outermost hop appears first ("subagent:A>subagent:B").
- ParentID — the parent session key at the top of the forwarding chain, useful for correlating every event back to the user-facing session.
An event whose Source is empty originates from the receiving agent itself.
func DecorateForwardedEvent ¶
func DecorateForwardedEvent(ev StreamEvent, source, parentSessionKey string) StreamEvent
DecorateForwardedEvent stamps Source and ParentID on an event that is being forwarded from a sub-agent to its parent stream. When the event already carries a Source (i.e. it came from a deeper nested agent), the new tag is prepended with ">" so the outermost hop appears first. ParentID is always overwritten with parentSessionKey — by the time the event reaches the top of the chain, it references the user-facing session.
func Event ¶
func Event(p EventPayload) StreamEvent
Event constructs a StreamEvent for payload p, deriving the Type field from the payload's static type. Source and ParentID default to empty; mutate the returned value if the event needs sub-agent tagging.
func LimitExhaustedStreamEvent ¶
func LimitExhaustedStreamEvent(kind LimitKind, limit, used int) StreamEvent
LimitExhaustedStreamEvent is the public constructor for adopters or custom LLM providers that want to signal a cap fired. The kind should be one of the LimitKind constants when applicable; custom providers may invent their own kind strings.
func (StreamEvent) MarshalJSON ¶
func (ev StreamEvent) MarshalJSON() ([]byte, error)
MarshalJSON serializes the event using a tagged-union envelope. Wire shape:
{"type":"content","source":"...","parent_id":"...","payload":{"text":"hi"}}
SSE consumers can read `type` to dispatch and `payload` to decode the inner structure with one round trip per event.
func (*StreamEvent) UnmarshalJSON ¶
func (ev *StreamEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the envelope and routes the payload bytes through decodePayload. Unknown event types round-trip via UnknownEvent so forward-compatible consumers do not crash.
func (StreamEvent) Visit ¶
func (ev StreamEvent) Visit(v EventVisitor)
Visit dispatches ev to the correct method on v based on the concrete payload type. Zero allocations — Payload is already typed.
type StreamEventType ¶
type StreamEventType string
StreamEventType tags the kind of event carried by StreamEvent. It is a distinct string type so the compiler catches bare-string comparisons and emits against non-constant strings — use the EventType* constants below for every emit and match.
const ( EventTypeContent StreamEventType = "content" EventTypeThought StreamEventType = "thought" EventTypeToolCall StreamEventType = "tool_call" EventTypeToolProgress StreamEventType = "tool_progress" EventTypeActionRequired StreamEventType = "action_required" EventTypeUsage StreamEventType = "usage" EventTypeError StreamEventType = "error" EventTypeDone StreamEventType = "done" // EventTypeReflected carries the canonical answer produced by a // self-critique round. Streaming consumers should treat it as a // replacement for any prior Source="" content that fell in the same // iteration; RunIteration does exactly this by resetting its buffer. EventTypeReflected StreamEventType = "reflected" // EventTypeToolCallReady is emitted mid-stream by providers that // surface a complete tool invocation before the overall response // finishes streaming. EventTypeToolCallReady StreamEventType = "tool_call_ready" // EventTypeTaskList carries the current per-session task list. Consumers // re-render the full list on every event — there is no diff format. EventTypeTaskList StreamEventType = "task_list" // EventTypeMaxItersReached signals that the loop exhausted MaxIters // without a final answer. Emitted right before the legacy error event // carrying ErrMaxIterations so callers using errors.Is keep working; // SSE consumers should prefer this typed signal to distinguish "hit // the cap" from generic errors. EventTypeMaxItersReached StreamEventType = "max_iters_reached" // EventTypeSessionCreated is emitted as the first frame of a stream // when the loop is starting a previously-unseen session. EventTypeSessionCreated StreamEventType = "session_created" // EventTypeLimitExhausted is the canonical signal that a configured // cap fired. Prefer it to the legacy error event for new consumers. EventTypeLimitExhausted StreamEventType = "limit_exhausted" // EventTypeHITLDenied is emitted when the HITL gate resolves to "user // denied". Observational; the per-tool denial directive is already // recorded as a tool message by the loop. EventTypeHITLDenied StreamEventType = "hitl_denied" // EventTypeHITLTimedOut is emitted when AgentLoop.ConfirmHITLTimeout // fires before the operator responds. Distinct from EventTypeHITLDenied // so consumers can route differently. EventTypeHITLTimedOut StreamEventType = "hitl_timed_out" // EventTypeRegenerated marks the start of an AgentLoop.Regenerate replay. EventTypeRegenerated StreamEventType = "regenerated" // EventTypeContinued marks the start of an AgentLoop.Continue resume. EventTypeContinued StreamEventType = "continued" // EventTypeMemoryLoaded is emitted at the start of every Run that // has memory enabled, carrying the resolved scope and the count / // estimated token cost of the notes injected. Use it for audit // logs ("agent loaded N notes for scope user:alice") and to // detect cross-tenant anomalies after the fact. Emitted exactly // once per Run; skipped when memory is disabled or the scope // resolver returned "" (fail-closed path). EventTypeMemoryLoaded StreamEventType = "memory_loaded" // EventTypeMemoryConsolidated is emitted from the detached // consolidator goroutine after Consolidate returns, regardless of // outcome. Carries Before/After counts and any error so adopters // can wire a compliance log without polling the store. EventTypeMemoryConsolidated StreamEventType = "memory_consolidated" // EventTypeRunCost is emitted right before DoneEvent on Runs that // produced a final answer. Carries rolled-up token usage and the // resolved dollar cost. Skipped only when neither a PriceTable is // configured nor any provider reported a charge of its own. EventTypeRunCost StreamEventType = "run_cost" // EventTypeContextTrace records what the pruner rewrote on the way // into one LLM call. Emitted only when a prune actually changed // something, so a turn whose context always fits stays silent. EventTypeContextTrace StreamEventType = "context_trace" // EventTypeDegraded reports that the turn finished with some tool's // derived bookkeeping left inconsistent, even though the turn itself // produced a real answer. Precedes the terminal event, never replaces // it — a consumer that ignores it sees exactly today's behavior. EventTypeDegraded StreamEventType = "degraded" )
Event type constants. Use these instead of string literals when emitting or matching events, so the compiler flags typos and renames stay consistent.
type StructuredOutput ¶
type StructuredOutput struct {
// Name is a short identifier for the schema. OpenAI requires this
// (it surfaces in validation errors). Other providers ignore it.
Name string
// Description is optional free-text explaining the schema's intent.
// Forwarded to providers that expose a description field.
Description string
// Schema is the JSON-Schema object describing the expected response.
// Must be non-nil — an empty schema is not the same as "no schema" and
// will be sent as-is to the provider.
Schema map[string]any
// Strict asks providers to reject any field not declared in Schema.
// OpenAI honors this via json_schema.strict=true; Gemini enforces
// strictly regardless; Anthropic's tool-synthesis path is implicitly
// strict (the tool only accepts the declared shape).
Strict bool
}
StructuredOutput is a provider-neutral request for a JSON-schema-constrained response. Providers translate it to their closest native knob:
- OpenAI (gpt-4o-*, o-series): response_format: {type:"json_schema", json_schema:{name, description, schema, strict}}. Native and strict. Compatible endpoints publishing only the older {type:"json_object"} declare it with openai.WithJSONMode, which moves the schema into the prompt: still JSON, but conformance stops being enforced server-side, so validate the result.
- Gemini (1.5+): response_mime_type:"application/json" + response_schema. Native; Strict is ignored (Gemini always enforces).
- Anthropic Claude: no native JSON mode. Providers synthesize a single tool with the given Schema and force tool_choice, then surface the tool's Input as the assistant's Content. Transparent to callers.
Set via WithStructuredOutput before calling GenerateStream (or use the GenerateJSON helper for one-shot generation outside the ReAct loop).
Schema must be a JSON-Schema object; callers typically build it with SchemaForStruct[T] or hand-write a map[string]any. The exact dialect understood differs by provider: OpenAI and Gemini accept a generous subset of JSON-Schema 2020-12; when in doubt, stick to type/properties/ required/items/enum and you will be fine on all three backends.
func StructuredOutputFromContext ¶
func StructuredOutputFromContext(ctx context.Context) *StructuredOutput
StructuredOutputFromContext returns the schema-constrained request stored on ctx, or nil when none is set. Provider adapters call this right before building the request and skip the JSON-mode fields when nil.
func (*StructuredOutput) MarshalSchema ¶
func (so *StructuredOutput) MarshalSchema() ([]byte, error)
MarshalSchema returns a canonical JSON encoding of the schema, useful for providers that want the schema as a raw JSON string rather than a map. Returns nil, nil when so is nil or has no schema.
type SubAgentEmitter ¶
type SubAgentEmitter func(ev StreamEvent)
SubAgentEmitter forwards a StreamEvent from a sub-agent into its parent agent's stream. Sends must be non-blocking: a stalled parent consumer must never be able to deadlock a sub-agent.
func SubAgentEmitterFromContext ¶
func SubAgentEmitterFromContext(ctx context.Context) SubAgentEmitter
SubAgentEmitterFromContext returns the emitter installed by the enclosing agent loop, or nil when the tool is running outside a loop. Callers should fall back to non-streaming behavior when nil is returned.
type TaskListEvent ¶
type TaskListEvent struct {
Tasks []TaskListItem `json:"tasks"`
}
TaskListEvent is a snapshot of the session's task list emitted whenever a task tool mutates the list. The frontend re-renders the full list on every event; there is no diff format.
type TaskListItem ¶
type TaskListItem struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"` // pending | in_progress | completed
Notes string `json:"notes,omitempty"`
}
TaskListItem is the wire shape of a single task entry inside a TaskListEvent. Mirrors builtin.Task minus timestamps so consumers do not need to import the builtin package to render the list.
type ThoughtEvent ¶
type ThoughtEvent struct {
Message string `json:"message"`
}
ThoughtEvent is internal reasoning / system narration. Suppressed from the final answer by RunIteration; surfaced by RunIterationStream when EmitThoughts is true.
type TokenUsage ¶
type TokenUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
CostUSD float64 `json:"cost_usd,omitempty"`
}
TokenUsage carries per-call token accounting returned by an LLM provider. Providers that do not report usage leave the fields zero.
CostUSD is the dollar amount the provider itself billed for the call, for the backends that return one (gateways that route across vendors typically do). Leave it zero when the provider reports no cost: the loop then falls back to estimating from AgentLoop.PriceTable, and a zero here means "not reported", never "free". A reported cost is the actual charge and beats any table estimate — it already accounts for the model the gateway picked, cache discounts, and per-vendor rates a static table cannot track.
type ToolCallEvent ¶
type ToolCallEvent struct {
ID string `json:"id"`
Name string `json:"name"`
ArgsJSON string `json:"args,omitempty"`
Reused bool `json:"reused,omitempty"`
}
ToolCallEvent announces that the agent is about to execute a tool. ID is the agent-generated correlation ID — it matches the toolCallID parameter on ToolResultHook so observability tooling can pair entry and exit events reliably even when SpeculativeTools=true interleaves parallel calls. Reused is true when the wave executor consumes a speculative result instead of dispatching the tool again.
type ToolCallReadyEvent ¶
type ToolCallReadyEvent struct {
ID string `json:"id"`
Name string `json:"name"`
ArgsJSON string `json:"args,omitempty"`
}
ToolCallReadyEvent announces that a tool invocation has been fully parsed from the LLM stream and is eligible for execution even though the overall response is still streaming. AgentLoop.SpeculativeTools turns this signal into actual parallel execution for safe calls.
type ToolDegradation ¶ added in v0.38.0
type ToolDegradation struct {
Tool string `json:"tool"`
Reason string `json:"reason"`
Artifacts []string `json:"artifacts,omitempty"`
Unreliable []string `json:"unreliable,omitempty"`
}
ToolDegradation is one tool call that half-succeeded, as reported by a tools.Degradation and stamped with the tool that raised it. See tools.Degradation for the field semantics.
type ToolErrorContext ¶
ToolErrorContext carries the full execution context of a failed tool invocation so a custom formatter can build messages aware of the args the model sent, which iteration the failure happened in, and the underlying error (suitable for errors.Is/As checks).
type ToolErrorHintFormatter ¶
type ToolErrorHintFormatter func(ToolErrorContext) string
ToolErrorHintFormatter shapes a failed tool invocation into the text written back to the model as the tool_result content. Because the model re-reads history on the next turn, the wording has a direct effect on whether it recovers: a flat "Error: ..." string gives the model no scaffolding, while a structured hint ("the tool failed with X; retry with corrected arguments or abandon the plan") materially improves first-retry success rates.
The default is defaultToolErrorHint. Override on AgentLoop to inject domain knowledge — e.g. mapping SQL driver errors to remediation suggestions, or stripping noisy traces before they reach the model.
type ToolNotFoundError ¶
type ToolNotFoundError struct {
ToolName string
}
ToolNotFoundError carries the name of the missing tool.
func (*ToolNotFoundError) Error ¶
func (e *ToolNotFoundError) Error() string
func (*ToolNotFoundError) Is ¶
func (e *ToolNotFoundError) Is(target error) bool
type ToolProgressEvent ¶
type ToolProgressEvent struct {
Name string `json:"name"`
ToolCallID string `json:"tool_call_id"`
Message string `json:"message"`
}
ToolProgressEvent is a mid-execution status update emitted by a tool via tools.ReportProgress. Progress is lossy by design — consumers may drop these safely.
type ToolResultHook ¶
type ToolResultHook func(ctx context.Context, toolCallID, toolName, argsJSON, result string, structured any, execErr error) (string, error)
ToolResultHook fires after every tool execution — success or failure — before the result reaches the LLM context, the inline-render path, the cache, or the anti-loop tracker. Adopters get one place to observe every call instead of pairing this hook with an EventTypeError handler.
On the success path, the returned string replaces the original result and a non-nil error from the hook converts the call into a tool error (formatted via formatToolError). On the error path, execErr is the tool's failure; returning a nil error from the hook recovers the call (the returned string becomes the result the LLM sees), while returning a non-nil error replaces execErr — useful for downgrading a noisy provider error to a neutral retry-hint string.
Typical uses: audit logging (log every call regardless of success), rewrite URLs (e.g. local -> CDN), redact secrets, normalize formats, post-validate successful results, or veto/recover failures.
toolCallID is the agent-generated correlation ID matching the EventTypeToolCall event for this dispatch — log it alongside your records so entry events and post-execution audit lines pair up. ctx is the per-tool ctx (carries WithProgressFunc / WithSubAgentEmitter / WithDynamicContextFunc / WithToolCallID).
structured is non-nil only when the executed tool implements tools.StructuredResult. Hooks that mutate output (URL rewrites, redaction, post-validation) should prefer reading typed fields off structured rather than regex-parsing result.
type UnknownEvent ¶
type UnknownEvent struct {
OriginalType StreamEventType `json:"type"`
RawJSON string `json:"raw"`
}
UnknownEvent wraps an event whose Type was not recognized. It preserves the raw wire bytes so forward-compatible consumers can still inspect events produced by a newer version of the framework.
type UsageEvent ¶
type UsageEvent struct {
Usage TokenUsage `json:"usage"`
}
UsageEvent reports token accounting from the most recent LLM call.
Source Files
¶
- anti_loop.go
- async.go
- budget.go
- cache_key.go
- constants.go
- context.go
- context_trace.go
- cost.go
- degraded.go
- doc.go
- dynamic_context.go
- errors.go
- event_types.go
- fork.go
- generate_json.go
- hitl_gate.go
- llm_call.go
- loop_execute.go
- loop_iteration.go
- loop_iteration_helpers.go
- loop_state.go
- loop_stream.go
- memory.go
- mock_provider.go
- options.go
- permissions.go
- plan_mode.go
- plan_mode_gate.go
- plan_response.go
- pruning.go
- reflect.go
- regenerate.go
- request_invariant.go
- retry.go
- scheduler.go
- scorer.go
- soft_landing.go
- speculative.go
- stream_drainer.go
- structured_output.go
- subagent_emitter.go
- telemetry.go
- thinking_budget.go
- tool_chaining_hint.go
- tool_error_hint.go