Documentation
¶
Index ¶
- Constants
- Variables
- func BuildGoalFromContextPrompt(tail []ai.Message) string
- func EstimateTokens(msgs []ai.Message) int
- func GoalFromContextMessages(msgs []ai.Message, n int) ([]ai.Message, error)
- func MemoryOffSnapshot() ai.PromptSnapshot
- func WithBackgroundNotice(ctx context.Context) context.Context
- func WithLifecycleStart(ctx context.Context, callback func()) context.Context
- func WithMemoryOffAuthored(ctx context.Context) context.Context
- func WithRequestObserver(ctx context.Context, observer RequestObserver) context.Context
- func WithTurnSnapshot(ctx context.Context, snapshot ai.PromptSnapshot) context.Context
- func WithUserMessageID(ctx context.Context, id string) context.Context
- func WithUserMessageObserver(ctx context.Context, observe func(ai.Message) error) context.Context
- func WrapReminder(text string) string
- type Agent
- func (a *Agent) AddSubUsage(model string, u ai.Usage)
- func (a *Agent) AddUsage(u ai.Usage)
- func (a *Agent) AllTools() []tools.Tool
- func (a *Agent) AppendUser(content string)
- func (a *Agent) AvailableTools() []tools.Tool
- func (a *Agent) CloseManagedProcesses()
- func (a *Agent) ContextTokens() int
- func (a *Agent) ContextTokensNow() int
- func (a *Agent) ContinueUser(ctx context.Context, messageID string, ev Events) (string, error)
- func (a *Agent) EndSession(ctx context.Context, reason string) error
- func (a *Agent) Experimental() []string
- func (a *Agent) FollowupTask(ctx context.Context, id, text string, ev Events) (string, error)
- func (a *Agent) Foreground() *tools.Foreground
- func (a *Agent) KnownTools() []tools.Tool
- func (a *Agent) LastStopReason() ai.StopReason
- func (a *Agent) LaunchBackground(t *BackgroundTask, worktreePath string)
- func (a *Agent) LoadTodosJSON(s string)
- func (a *Agent) ManualCompact(ctx context.Context, ev Events) error
- func (a *Agent) ManualCompactCommit(ctx context.Context, ev Events, commit func() error) (err error)
- func (a *Agent) ManualNewContext(ctx context.Context, ev Events) error
- func (a *Agent) MemoryEnabled() bool
- func (a *Agent) MessagesSnapshot() []ai.Message
- func (a *Agent) ModelUsage() map[string]ai.Usage
- func (a *Agent) Notify(text string)
- func (a *Agent) PlanMode() bool
- func (a *Agent) RefreshMemory()
- func (a *Agent) RegisterBackground(description, prompt string, o SubModel) *BackgroundTask
- func (a *Agent) RegisterBackgroundContext(parent context.Context, description, prompt string, o SubModel) *BackgroundTask
- func (a *Agent) ResetUsage()
- func (a *Agent) RestoreMessages(messages []ai.Message)
- func (a *Agent) RestoreTask(t BackgroundTask)
- func (a *Agent) RestoreUsage(usage ai.UsageSummary)
- func (a *Agent) SessionIDValue() string
- func (a *Agent) SetCacheKey(key string)
- func (a *Agent) SetHostTools(ts []tools.Tool)
- func (a *Agent) SetMCPTools(ts []tools.Tool)
- func (a *Agent) SetManagedProcesses(m *tools.ManagedProcessManager)
- func (a *Agent) SetMemoryEnabled(enabled bool)
- func (a *Agent) SetMemoryRuntime(runtime MemoryRuntime)
- func (a *Agent) SetMessageRewoundFrom(index int, value string)
- func (a *Agent) SetModel(model ModelConfig) error
- func (a *Agent) SetModelUsage(usage map[string]ai.Usage)
- func (a *Agent) SetOnTodos(fn func(items []Todo))
- func (a *Agent) SetPlanMode(enabled bool)
- func (a *Agent) SetPluginTools(ts []tools.Tool)
- func (a *Agent) SetSessionID(id string)
- func (a *Agent) SetSubUsage(m map[string]ai.Usage)
- func (a *Agent) SetUsage(u ai.Usage)
- func (a *Agent) StartBackground(description, prompt string, o SubModel) *BackgroundTask
- func (a *Agent) StartSession(ctx context.Context) error
- func (a *Agent) StartWait(spec WaitTaskSpec) (*waitTask, error)
- func (a *Agent) StartWaitContext(ctx context.Context, spec WaitTaskSpec) (*waitTask, error)
- func (a *Agent) Steer(text string)
- func (a *Agent) SteerImages(text string, parts []ai.ContentPart)
- func (a *Agent) SteerTask(id, text string) error
- func (a *Agent) SubUsage() map[string]ai.Usage
- func (a *Agent) Tasks() *taskRegistry
- func (a *Agent) TodosJSON() string
- func (a *Agent) TotalUsage() ai.Usage
- func (a *Agent) Turn(ctx context.Context, input string, ev Events) (string, error)
- func (a *Agent) TurnAuthored(ctx context.Context, input string, ev Events) (string, error)
- func (a *Agent) TurnParts(ctx context.Context, input string, parts []ai.ContentPart, ev Events) (string, error)
- func (a *Agent) TurnRunning() bool
- func (a *Agent) TurnWithImages(ctx context.Context, input string, parts []ai.ContentPart, ev Events) (string, error)
- func (a *Agent) Usage() ai.Usage
- func (a *Agent) UsageSummary() ai.UsageSummary
- func (a *Agent) VerifyGoal(ctx context.Context, goal string) (goalloop.Verdict, error)
- func (a *Agent) WaitCancelledTasks()
- func (a *Agent) WaitingOnSubagents() bool
- func (a *Agent) Waits() *waitRegistry
- func (a *Agent) WebSearchFallbackTool() (tools.Tool, bool)
- func (a *Agent) Workflows() *workflow.Manager
- type BackgroundTask
- type ChildInfo
- type ChildResult
- type CompactInfo
- type Events
- type JournaledEvent
- type LSPDiagnosticsReminder
- type MemoryRuntime
- type MemoryTurn
- type ModelConfig
- type Option
- type Reminder
- type ReminderFunc
- type RequestObservation
- type RequestObserver
- type SubModel
- type TaskStatus
- type Todo
- type ToolOutcome
- type WaitStatus
- type WaitTaskSpec
Constants ¶
const (
FeatureWorkflows = "workflows"
)
const GoalFromContextDefaultWindow = 8
const ( // GoalVerifyTimeout bounds the hidden verification request, so a slow or stuck // provider never holds the goal loop. GoalVerifyTimeout = 2 * time.Minute )
const MaxOutputLimitContinuations = 2
MaxOutputLimitContinuations caps how many times one turn resumes a reply that stopped at the output-token limit. After the cap the truncated reply ends the turn.
const MaxStopHookBlocks = 5
MaxStopHookBlocks caps how many times Stop hooks may keep one turn going. The Stop hooks still run when the cap is reached, but their block is ignored.
const ReminderTag = "system-reminder"
ReminderTag wraps context the harness, not the tool, adds to a tool result.
Variables ¶
var ErrBusy = errors.New("agent is busy; wait for the current turn to finish")
var ErrSubagentStopped = errors.New("subagent stopped by the user")
ErrSubagentStopped ends a foreground subagent the user stopped; the parent turn keeps running and sees it as a failed tool call.
Functions ¶
func EstimateTokens ¶
func GoalFromContextMessages ¶
func MemoryOffSnapshot ¶ added in v0.107.6
func MemoryOffSnapshot() ai.PromptSnapshot
MemoryOffSnapshot marks a user message created while memory is off. Every path that adds a user message to History while off must attach it.
func WithBackgroundNotice ¶ added in v0.107.18
WithBackgroundNotice marks the turn's user message as a notice from background work (a wait, a process or subagent finishing) rather than something the user wrote: it is not authored and carries ai.OriginBackground.
func WithLifecycleStart ¶ added in v0.107.0
func WithMemoryOffAuthored ¶ added in v0.107.6
WithMemoryOffAuthored marks the turn's user message as written while memory was off, for input that waited (a queued message) until after memory was turned back on.
func WithRequestObserver ¶ added in v0.107.0
func WithRequestObserver(ctx context.Context, observer RequestObserver) context.Context
func WithTurnSnapshot ¶ added in v0.107.6
WithTurnSnapshot attaches request-only text to the user message of the next turn. The model sees it after the user's words; history and transcripts keep only what the user typed. Desktop slash commands use it to send an expanded prompt template while the conversation still shows "/name args".
func WithUserMessageID ¶ added in v0.107.0
func WithUserMessageObserver ¶ added in v0.107.0
WithUserMessageObserver observes the durable turn identity before model or tool execution.
func WrapReminder ¶ added in v0.107.13
WrapReminder wraps text in a <system-reminder> block.
Types ¶
type Agent ¶
type Agent struct {
Client ai.Client
Model string
ModelName string
Provider string
MaxTokens int
Effort string
Vision bool
NativeWebSearch bool
// WebSearchFallback offers the web_search function tool when the configured
// third-party search service is usable. It stands in for native search on
// turns that ask for web search while the client cannot search natively;
// nil leaves such turns to the provider.
WebSearchFallback func() (tools.Tool, bool)
Temperature *float64
TopP *float64
Tools []tools.Tool
// RequestToolFilter narrows schemas sent to the model; execution still uses AllTools.
RequestToolFilter func([]tools.Tool) []tools.Tool
RunTools []tools.Tool
RunToolsSet bool
Messages []ai.Message
ContextLimit int
CompactClient ai.Client
CompactModel string
CompactProvider string
CompactThreshold float64
// CompactionDir resolves the directory that receives compacted-away turns as
// markdown segments (see compaction_segments.go). Nil or "" disables archiving.
CompactionDir func() string
TaskDefault SubModel
ResolveModel func(model, provider string) (SubModel, error)
MaxTurns int
// ContinueOnOutputLimit resumes a reply cut off by the output-token limit with
// a continuation reminder, at most MaxOutputLimitContinuations times per turn.
ContinueOnOutputLimit bool
WorkingDir string
WorktreeSubagents bool
Todos []Todo
BrowserDisabled bool
ComputerDisabled bool
ComputerConfig config.ComputerConfig
SandboxPolicy *sandbox.Policy
OnOrphanedSteer func(text string)
// Reminders run after each tool call and append <system-reminder> context to its
// result (LSP diagnostics by default). Subagents inherit them.
Reminders []Reminder
Hooks *hooks.Runner
PluginHook func(context.Context, hooks.Event) error
// contains filtered or unexported fields
}
func (*Agent) AppendUser ¶
func (*Agent) AvailableTools ¶ added in v0.107.0
func (*Agent) CloseManagedProcesses ¶ added in v0.107.28
func (a *Agent) CloseManagedProcesses()
CloseManagedProcesses stops the commands the user moved to the background, when the agent owns the manager that took them over, and forgets them: the next command moved to the background starts a fresh manager.
func (*Agent) ContextTokens ¶ added in v0.107.0
func (*Agent) ContextTokensNow ¶ added in v0.107.28
ContextTokensNow is ContextTokens for drawing a frame: it never waits for the transcript lock. While another goroutine holds it, it returns the last count it computed. A UI that blocks in View on an agent lock freezes for good once the lock holder waits on that UI.
func (*Agent) ContinueUser ¶ added in v0.107.0
ContinueUser runs the persisted tail user message without appending another user turn.
func (*Agent) EndSession ¶ added in v0.107.13
EndSession runs the SessionEnd hook for a session StartSession started; it does nothing otherwise. reason is reported to the hook ("exit", "close", ...). A later StartSession starts the session again. Hook failures are returned for logging; they cannot keep the session open.
func (*Agent) Experimental ¶
func (*Agent) FollowupTask ¶
func (*Agent) Foreground ¶ added in v0.107.28
func (a *Agent) Foreground() *tools.Foreground
Foreground tracks this agent's foreground shell commands that the user can move to the background while they run.
func (*Agent) KnownTools ¶ added in v0.107.6
KnownTools are the tools a run may name in its options, including memory tools the switch currently hides, so a run's validation does not depend on the switch.
func (*Agent) LastStopReason ¶ added in v0.103.0
func (a *Agent) LastStopReason() ai.StopReason
func (*Agent) LaunchBackground ¶
func (a *Agent) LaunchBackground(t *BackgroundTask, worktreePath string)
func (*Agent) LoadTodosJSON ¶
func (*Agent) ManualCompactCommit ¶ added in v0.107.0
func (a *Agent) ManualCompactCommit(ctx context.Context, ev Events, commit func() error) (err error)
ManualCompactCommit keeps the turn lock until the caller commits the new context. A cancelled or failed commit restores the previous context and usage ledger.
func (*Agent) ManualNewContext ¶ added in v0.104.0
func (*Agent) MemoryEnabled ¶ added in v0.107.6
func (*Agent) MessagesSnapshot ¶
func (*Agent) Notify ¶ added in v0.107.18
Notify delivers a notice the runtime produced on its own (a wait result, a process exit, a background report) the way Steer delivers user text: into the running turn, or through OnOrphanedSteer when none is running. The message it adds to the history carries ai.OriginBackground.
func (*Agent) RefreshMemory ¶ added in v0.103.0
func (a *Agent) RefreshMemory()
func (*Agent) RegisterBackground ¶
func (a *Agent) RegisterBackground(description, prompt string, o SubModel) *BackgroundTask
func (*Agent) RegisterBackgroundContext ¶ added in v0.103.0
func (*Agent) ResetUsage ¶
func (a *Agent) ResetUsage()
func (*Agent) RestoreMessages ¶ added in v0.107.0
func (*Agent) RestoreTask ¶
func (a *Agent) RestoreTask(t BackgroundTask)
func (*Agent) RestoreUsage ¶ added in v0.103.0
func (a *Agent) RestoreUsage(usage ai.UsageSummary)
func (*Agent) SessionIDValue ¶
func (*Agent) SetCacheKey ¶
func (*Agent) SetHostTools ¶ added in v0.107.28
SetHostTools replaces the tools the desktop host provides. A host tool named like one of Tools takes its place while set; nil restores the agent's own.
func (*Agent) SetMCPTools ¶
func (*Agent) SetManagedProcesses ¶ added in v0.107.28
func (a *Agent) SetManagedProcesses(m *tools.ManagedProcessManager)
SetManagedProcesses makes m take over the commands the user moves to the background, instead of a manager the agent creates and owns. The caller owns m: it delivers its exit notices and closes it.
func (*Agent) SetMemoryEnabled ¶ added in v0.107.6
SetMemoryEnabled toggles memory injection, hidden extraction and memory tools from the next turn on. Stored memories are untouched.
func (*Agent) SetMemoryRuntime ¶ added in v0.107.0
func (a *Agent) SetMemoryRuntime(runtime MemoryRuntime)
func (*Agent) SetMessageRewoundFrom ¶ added in v0.107.0
func (*Agent) SetModel ¶ added in v0.103.0
func (a *Agent) SetModel(model ModelConfig) error
func (*Agent) SetModelUsage ¶ added in v0.103.0
func (*Agent) SetOnTodos ¶
func (*Agent) SetPlanMode ¶ added in v0.103.0
func (*Agent) SetPluginTools ¶ added in v0.103.0
func (*Agent) SetSessionID ¶
func (*Agent) StartBackground ¶
func (a *Agent) StartBackground(description, prompt string, o SubModel) *BackgroundTask
func (*Agent) StartSession ¶ added in v0.103.0
func (*Agent) StartWait ¶
func (a *Agent) StartWait(spec WaitTaskSpec) (*waitTask, error)
func (*Agent) StartWaitContext ¶ added in v0.103.0
func (a *Agent) StartWaitContext(ctx context.Context, spec WaitTaskSpec) (*waitTask, error)
func (*Agent) SteerImages ¶
func (a *Agent) SteerImages(text string, parts []ai.ContentPart)
SteerImages is Steer with images. With no turn running the text alone goes to OnOrphanedSteer, as Steer's does.
func (*Agent) TotalUsage ¶
func (*Agent) TurnAuthored ¶
func (*Agent) TurnRunning ¶
func (*Agent) TurnWithImages ¶
func (*Agent) UsageSummary ¶ added in v0.103.0
func (a *Agent) UsageSummary() ai.UsageSummary
func (*Agent) VerifyGoal ¶ added in v0.107.40
VerifyGoal asks the session's current model, in a hidden request that never enters the history, whether the goal is really met. The request carries only the goal, a bounded excerpt of the recent work and the reply that claimed the goal; it offers no tools. An error (including an unparseable verdict) leaves the decision to the caller, which falls back to accepting the claim.
func (*Agent) WaitCancelledTasks ¶ added in v0.107.33
func (a *Agent) WaitCancelledTasks()
WaitCancelledTasks waits for cancelled background tasks to finish publishing and recording their terminal state. It neither cancels nor waits for live tasks: their lifetime still belongs to the context passed at registration.
func (*Agent) WaitingOnSubagents ¶
func (*Agent) WebSearchFallbackTool ¶ added in v0.107.33
WebSearchFallbackTool returns the web_search tool when this turn asks for web search, the client cannot search natively, and a search service is configured.
type BackgroundTask ¶
type BackgroundTask struct {
ID string
Description string
Prompt string
Status TaskStatus
Report string
StartedAt time.Time
EndedAt time.Time
// ParentToolCallID is the parent's subagent tool call that started it.
ParentToolCallID string
Restored bool
FollowingUp bool
Done chan struct{}
SubMessages []ai.Message
SubUsage ai.Usage
SubModelUsage map[string]ai.Usage
SubSubUsage map[string]ai.Usage
SubModel string
// contains filtered or unexported fields
}
type ChildInfo ¶ added in v0.107.19
type ChildInfo struct {
ID string
Description string
Prompt string
Model string
Provider string
ParentToolCallID string
// Progress returns the subagent's transcript and usage so far; it is safe to
// call while the subagent runs, so observers can save live progress.
Progress func() ([]ai.Message, ai.Usage)
}
ChildInfo describes a foreground subagent to the request observer.
type ChildResult ¶ added in v0.107.19
ChildResult is what a foreground subagent turn ended with.
type CompactInfo ¶
type Events ¶
type Events struct {
OnPhase func(stage string)
OnLifecycle func(event string)
OnText func(delta string)
OnThink func(delta string)
OnHostedSearch func(ai.HostedSearch)
OnToolStart func(id, name, args string)
OnToolEnd func(id, name, result string)
OnToolResult func(id, name string, result tools.Result)
OnToolCall func(id, name, args string)
OnToolOutput func(id, outputSoFar string)
OnSteer func(text string)
// AtToolBoundary runs after a round of tool calls has finished, before the
// turn reads the messages steered into it: a front end holding messages
// typed during the round hands them over here (Steer), so the model reads
// them right after the tool results instead of after the turn.
AtToolBoundary func()
OnCompact func(took, kept int)
OnCompacted func(summary string, cutoff int, info CompactInfo)
OnCompactStart func(took, estTokens int)
OnNewContextStart func(took, estTokens int)
OnNewContext func(cutoff int)
OnUsage func(u ai.Usage)
OnRetry func(ev ai.RetryEvent)
OnDecay func(n int)
// OnOutputLimitContinue fires before the agent resumes a reply that stopped at
// the output-token limit; attempt counts from 1 to MaxOutputLimitContinuations.
OnOutputLimitContinue func(attempt int)
}
type JournaledEvent ¶
type LSPDiagnosticsReminder ¶ added in v0.107.13
type LSPDiagnosticsReminder struct{}
LSPDiagnosticsReminder reports language-server diagnostics for the files a successful tool call mutated, using the process-wide tools.LSP manager.
func (LSPDiagnosticsReminder) Remind ¶ added in v0.107.13
func (LSPDiagnosticsReminder) Remind(ctx context.Context, call ToolOutcome) string
type MemoryRuntime ¶ added in v0.107.0
type MemoryRuntime interface {
Inject(context.Context, string) (string, error)
Completed(context.Context, MemoryTurn)
// Abandoned is called for a turn that ended without completing (stopped,
// failed, plan-mode exit) after its user message entered History. It must
// not take the agent's locks.
Abandoned(sessionID string, user ai.Message)
Tools(func() string) []tools.Tool
Close() error
}
MemoryRuntime owns backend memory injection and hidden extraction. Implementations must keep persistence behind the internal/memory Store seam.
type MemoryTurn ¶ added in v0.107.0
type MemoryTurn struct {
SessionID string
Workdir string
Model string
User ai.Message
History []ai.Message
}
MemoryTurn is the durable input and history snapshot supplied after a real turn.
type ModelConfig ¶ added in v0.103.0
type Option ¶
type Option func(*Agent)
func WithComputerConfig ¶ added in v0.107.6
func WithComputerConfig(cfg config.ComputerConfig) Option
func WithExperimental ¶
func WithMemoryEnabled ¶ added in v0.107.6
WithMemoryEnabled sets the memory master switch at construction.
func WithOutputLimitContinuation ¶ added in v0.107.13
func WithOutputLimitContinuation() Option
WithOutputLimitContinuation enables automatic continuation of replies cut off by the output-token limit (see MaxOutputLimitContinuations).
func WithSystemPromptResolver ¶ added in v0.107.0
WithSystemPromptResolver refreshes factory instructions before each turn.
func WithTurnTimeContext ¶ added in v0.107.6
func WithTurnTimeContext() Option
WithTurnTimeContext supplies current context alongside a clock-free system prompt.
type Reminder ¶ added in v0.107.13
type Reminder interface {
Remind(ctx context.Context, call ToolOutcome) string
}
Reminder runs after every tool call and may return context for the model. The text is wrapped in a <system-reminder> block and appended to the tool result; "" adds nothing. Reminders run on the tool call's goroutine, so they must be safe for concurrent use and should return promptly.
func DefaultReminders ¶ added in v0.107.13
func DefaultReminders() []Reminder
DefaultReminders are installed on every new agent.
type ReminderFunc ¶ added in v0.107.13
type ReminderFunc func(ctx context.Context, call ToolOutcome) string
ReminderFunc adapts a function to Reminder.
func (ReminderFunc) Remind ¶ added in v0.107.13
func (f ReminderFunc) Remind(ctx context.Context, call ToolOutcome) string
type RequestObservation ¶ added in v0.107.0
type RequestObserver ¶ added in v0.107.0
type TaskStatus ¶
type TaskStatus string
const ( TaskRunning TaskStatus = "running" TaskDone TaskStatus = "done" TaskError TaskStatus = "error" TaskCancelled TaskStatus = "cancelled" )
type ToolOutcome ¶ added in v0.107.13
type ToolOutcome struct {
ID string
Name string
Args string
// Result is the tool's result after the PostToolUse hook.
Result tools.Result
// MutatedPaths lists, in order and without duplicates, the resolved paths the call's
// file tools reported mutating (write, edit, LiveAgent Write/Edit/Delete).
MutatedPaths []string
}
ToolOutcome is what a Reminder sees about a finished tool call.
type WaitStatus ¶
type WaitStatus string
const ( WaitRunning WaitStatus = "running" WaitMet WaitStatus = "condition met" WaitTimeout WaitStatus = "timed out" WaitFailed WaitStatus = "command failing" WaitKilled WaitStatus = "cancelled" )
Source Files
¶
- agent.go
- background.go
- background_process.go
- compact_hooks.go
- compact_output_limit.go
- compact_transaction.go
- compaction_segments.go
- computer.go
- context_snapshots.go
- context_tool.go
- decay.go
- events.go
- filelocks.go
- goal_verify.go
- journal.go
- lifecycle.go
- memory.go
- memory_runtime.go
- memory_store_tool.go
- memory_switch.go
- mode.go
- model.go
- model_usage.go
- output_limit.go
- plan_review.go
- prompt_resources.go
- reminders.go
- request_observer.go
- response.go
- session_start.go
- skills.go
- stop_hook.go
- subagent.go
- subagent_control.go
- todo.go
- tool_execution.go
- trajectory_child.go
- turn_observer.go
- wait.go
- workflowtool.go
- worktree.go