Documentation
¶
Overview ¶
Package agent is Scribe's agent loop: it builds each model request, streams the response, runs tool calls, and reports everything it does as Events. The TUI, the headless runner and Lectern's session bridge are all consumers of the same Event stream.
Index ¶
- Constants
- Variables
- func BuildSystem(in PromptInput, mode string) string
- func BusTools(id string, bus *AgentBus) []tools.Tool
- func CallID(ctx context.Context) string
- func Collect(ctx context.Context, p llm.Provider, req llm.Request) (string, error)
- func DeferredCatalog(r *tools.Registry, core func(string) bool) string
- func DispatchCancelTool(d *Dispatcher) tools.Tool
- func DumpRequests(w io.Writer) func(step int, modelRef string, req llm.Request)
- func EstimateTokens(msgs []llm.Message) int
- func Ledger(msgs []llm.Message) string
- func ModeBanner(mode string) string
- func ModelFamily(modelRef string) string
- func ParsePlanVerification(md string) []string
- func PeerFeed(id string, bus *AgentBus) func() string
- func PlanDepth(used, window int) string
- func PlanExecutionAllowed(tool string) bool
- func PlanMarkdown(pl *Plan) string
- func PlanOptions() []string
- func PlanOptionsFor(depth string) []string
- func PromptCaches(modelRef string) bool
- func PruneOldToolResults(msgs []llm.Message) []llm.Message
- func PruningApplies(target string, subagent bool) bool
- func ReadCacheTool(inner tools.Tool, bus *AgentBus, id string) tools.Tool
- func RegisterDeferred(r *tools.Registry, d *Deferred)
- func ResultCacheTool(inner tools.Tool, bus *AgentBus, id string) tools.Tool
- func SalvageSucceeds(runErr error, report string) bool
- func SplitPoint(msgs []llm.Message, keep int) int
- func SplitRecent(msgs []llm.Message, keep int) int
- func SubagentReport(a *Agent, runErr error) string
- func SubagentStepTimeout(toolTimeout time.Duration) time.Duration
- func Transcript(msgs []llm.Message, max int) string
- func Unfinished(msgs []llm.Message) bool
- func WithCallID(ctx context.Context, id string) context.Context
- type Agent
- func (a *Agent) Abort()
- func (a *Agent) BeginPlanExecution()
- func (a *Agent) Compact(ctx context.Context, reason string) error
- func (a *Agent) CompactionLog() []Event
- func (a *Agent) ContextEstimate() (used int, estimated bool)
- func (a *Agent) ContextParts() ContextParts
- func (a *Agent) ContextUsed() (int, int)
- func (a *Agent) Continue(ctx context.Context) (TurnStats, error)
- func (a *Agent) CurrentModel() Model
- func (a *Agent) DispatchActive() bool
- func (a *Agent) EndTurn()
- func (a *Agent) Messages() []llm.Message
- func (a *Agent) Mode() string
- func (a *Agent) ModelEvents() []Event
- func (a *Agent) OfferedForTest() map[string]bool
- func (a *Agent) Partial() string
- func (a *Agent) Queued() []string
- func (a *Agent) Reasoning() string
- func (a *Agent) ResetHistory(msgs []llm.Message, mode string)
- func (a *Agent) Run(ctx context.Context, prompt string, images []llm.Part) (out TurnStats, outErr error)
- func (a *Agent) Running() bool
- func (a *Agent) SetActive(active map[string]bool)
- func (a *Agent) SetCompaction(strategy string, keepRecent int)
- func (a *Agent) SetMaxToolResults(n int)
- func (a *Agent) SetMessages(m []llm.Message)
- func (a *Agent) SetMode(m string)
- func (a *Agent) SetModel(m Model)
- func (a *Agent) SetPruning(target string)
- func (a *Agent) SetReasoning(r string)
- func (a *Agent) SetSkills(block string)
- func (a *Agent) SetTabID(id string)
- func (a *Agent) Steer(msg string) bool
- func (a *Agent) SteerWithImages(msg string, images []llm.Part) bool
- func (a *Agent) Usage() (llm.Usage, float64)
- type AgentBus
- func (b *AgentBus) Abort() bool
- func (b *AgentBus) Aborted() bool
- func (b *AgentBus) CachedRead(key, stamp string) (string, bool)
- func (b *AgentBus) ClaimEdit(file, id string) (owner string, conflict bool)
- func (b *AgentBus) Conflicts(file ...string) []string
- func (b *AgentBus) Dispose()
- func (b *AgentBus) ExportCaches() *BusCache
- func (b *AgentBus) Findings() []Finding
- func (b *AgentBus) FindingsExcept(id string) []Finding
- func (b *AgentBus) Post(id, text string)
- func (b *AgentBus) PostFinding(f Finding) error
- func (b *AgentBus) ReadStart(id, key, stamp string) (string, bool, *ReadTicket)
- func (b *AgentBus) SeedCaches(c *BusCache)
- func (b *AgentBus) SetAbort(f func())
- func (b *AgentBus) SetCacheObserver(f func(CacheNote))
- func (b *AgentBus) StoreRead(key, stamp, output string)
- func (b *AgentBus) ToolResult(key string) (tools.Result, bool)
- type AgentInfo
- type BusCache
- type CacheNote
- type CodeMap
- type Compactor
- type ComputerUse
- type ContextParts
- type Deferred
- type DispatchGuard
- type Dispatcher
- type Event
- type EventKind
- type Features
- type Finding
- type Hooks
- type Instruction
- type InstructionSource
- type Model
- type Options
- type Plan
- type PlanFile
- type PlanStep
- type PlanSymbol
- type Planner
- type PromptInput
- type Purpose
- type ReadTicket
- type Sink
- type StepBudget
- type SubagentFactory
- type SubagentObserver
- type SubagentSpec
- type SummaryCompactor
- type Task
- type TaskSkills
- type TurnStats
- type WorkingState
Constants ¶
const ( CacheHit = "hit" CacheWait = "wait" CacheStore = "store" CacheInvalidate = "invalidate" )
Outcomes of a read that goes through the dispatch cache. They are what the subagent's row shows (spec 01 §2.9): a read served from an earlier one, a read held up behind another subagent's, a read kept for the others, and a read that replaced an entry for a file which had changed.
const ( ExploreMaxSteps = 12 CodeMaxSteps = 18 WebMaxSteps = 15 )
Step budgets for subagents (spec 03 §3.5 and §3.9). The app wiring passes them to the agents it builds.
const ( AnswerExecute = "Execute" AnswerClear = "Clear context and execute" AnswerRevise = "Revise" AnswerCancel = "Cancel" )
The answers a user can give to a plan review. The TUI sends these exact strings; Revise is followed by a space and the feedback.
const ( PlanLight = "light" PlanFull = "full" )
Plan depth follows the context in use, as the plan-mode prompt does: at or under half the window a plan is a light checklist, over half it is full.
const ClearedPlanPrefix = "The user approved this plan and chose to clear the planning conversation. "
ClearedPlanPrefix starts the message that hands a plan to a cleared context. The user did not type it, so views do not show it as theirs.
const PlanExecuteLead = "Execute this plan."
PlanExecuteLead opens the user message that starts an approved plan's execution. The TUI shows a message with this lead as a collapsed plan.
Variables ¶
var DefaultInstructionFiles = []string{"scribe", "codex", "claude"}
DefaultInstructionFiles are the sources loaded when config does not say otherwise. The order matters: within a directory, earlier sources come first in the prompt.
var ErrNotEnoughHistory = errors.New("not enough older messages to compact yet")
ErrNotEnoughHistory is returned when fewer than two messages are older than the kept tail, so there is nothing worth compacting.
var ErrNothingToContinue = errors.New("nothing to continue: the last turn finished")
ErrNothingToContinue means the history does not end in an unfinished turn.
var InstructionSources = []InstructionSource{ {ID: "scribe", Label: "Scribe", Files: []string{"SCRIBE.md", ".scribe/SCRIBE.md", ".scribe/instructions.md"}}, {ID: "soulforge", Label: "SoulForge", Files: []string{"SOULFORGE.md", ".soulforge/SOULFORGE.md", ".soulforge/instructions.md"}}, {ID: "claude", Label: "Claude", Files: []string{"CLAUDE.md", ".claude/instructions.md"}}, {ID: "codex", Label: "Codex", Files: []string{"AGENTS.md", ".agents/instructions.md"}}, {ID: "cursorrules", Label: "Cursor", Files: []string{".cursorrules", ".cursor/rules", ".cursor/rules.md"}}, {ID: "github-copilot", Label: "GitHub Copilot", Files: []string{".github/copilot-instructions.md"}}, {ID: "cline", Label: "Cline", Files: []string{".clinerules", ".cline/rules"}}, {ID: "windsurf", Label: "Windsurf", Files: []string{".windsurfrules"}}, {ID: "aider", Label: "Aider", Files: []string{".aider.conf.yml", ".aiderignore"}}, {ID: "amp", Label: "Amp", Files: []string{"AMPLIFY.md", ".amp/instructions.md"}}, }
InstructionSources is the catalogue of sources config can enable by id.
var Modes = []string{"default", "auto", "plan", "architect", "socratic", "challenge"}
Modes in the order Shift+Tab cycles them.
var RestrictedModes = map[string]bool{"plan": true, "architect": true, "socratic": true, "challenge": true}
RestrictedModes only allow read-only tools (plus the planning tools, which are read-only by declaration).
Functions ¶
func BuildSystem ¶
func BuildSystem(in PromptInput, mode string) string
BuildSystem assembles the system prompt for mode. The result is memoised on a hash of every input, so repeated calls with the same input return the same bytes without rebuilding.
func BusTools ¶
BusTools are the tools every subagent of a dispatch gets for the shared bus: report_finding posts a finding for the others and for the parent, and check_findings reads what the others have posted. Both are read-only: they change the bus, not the repository, so explore agents can use them.
func DeferredCatalog ¶
DeferredCatalog renders one line per deferred tool ("- name — description") for the system prompt, in registration order. core names are skipped. Descriptions are cut to their first sentence and 160 characters.
func DispatchCancelTool ¶
func DispatchCancelTool(d *Dispatcher) tools.Tool
DispatchCancelTool is cancel_dispatch for the lead agent (spec 03 section 1.1). It stops one running subagent by id, or the whole dispatch with id "all", while that dispatch is still running. It goes through the same Dispatcher calls as the TUI's /cancel, so both stop agents the same way.
func DumpRequests ¶
DumpRequests returns a RequestDump that writes each model request to w as one JSON object per line: the step, the model ref and the request body. Request headers are left out, and the line is passed through the secret redactor, so a dump can be shared. It backs the API export of a session. Writes are serialised; a write error is ignored, because a dump must never fail the turn it observes.
func EstimateTokens ¶
EstimateTokens is the rough size of msgs (4 chars per token).
func ModeBanner ¶
ModeBanner is the overlay text for a mode, or "" for default and unknown modes. The agent sends it as a latched user message, not in the system prompt.
func ModelFamily ¶
ModelFamily names the prompt family for a model reference such as "anthropic/claude-x" or "openrouter/anthropic/claude-x". It looks at the last path segment only, so the provider name never decides the family. Families: claude, openai, google, deepseek-reasoner, default.
func ParsePlanVerification ¶
ParsePlanVerification reads the "## Verification" checklist back out of plan markdown. It returns nil when the plan has none.
func PeerFeed ¶
PeerFeed returns the hook that hands agent id the findings its peers posted since the last call, so each step sees them without a check_findings call (spec 03 section 3.5). It returns "" when nothing is new. Findings are append-only, so the hook keeps an index; it is called from the agent's loop only.
func PlanDepth ¶
PlanDepth returns the depth for a plan written with used of window tokens in context. An unknown window counts as full, so nothing is hidden.
func PlanExecutionAllowed ¶
PlanExecutionAllowed reports whether tool may run while an approved plan is executed. The agent loop checks it from the approval to the end of the turn.
func PlanMarkdown ¶
PlanMarkdown renders a plan as markdown, without symbols or verification.
func PlanOptions ¶
func PlanOptions() []string
PlanOptions are the choices offered at plan review, in key order (1-4).
func PlanOptionsFor ¶
PlanOptionsFor is the review choices for a plan of the given depth. A light plan has no "Clear & Implement": there is little context to clear.
func PromptCaches ¶
PromptCaches reports whether the provider for modelRef caches the prompt prefix (spec 04 §4.9): Claude explicitly, Google, OpenAI, DeepSeek and the other named families implicitly. Unknown and local models do not, so their code map is live and not frozen.
func PruneOldToolResults ¶
PruneOldToolResults returns msgs with old tool results shortened. It only rewrites the Result text of tool-result parts, so user and assistant messages and the system prompt (which is not in msgs) are unchanged. The input is not modified: a changed message is copied, so the caller's history keeps its own slices. When nothing is pruned the input slice is returned as it is.
A result is pruned only when it is not an error, its tool is not exempt, it is longer than pruneMinChars, and it is older than the newest pruneKeepResults tool results. Pruning is idempotent: a pruned result is shorter than pruneMinChars, so a second pass leaves it alone.
func PruningApplies ¶
PruningApplies reports whether the pruning target covers this agent. The target is config.ContextManagement.Pruning(): main covers the main agent, subagents covers dispatched agents, and both covers each.
func ReadCacheTool ¶
ReadCacheTool wraps a read tool so that a repeated read of an unchanged file is served from the bus, by subagent id. The stamp is the file's size and modification time, so an edit makes the next read a miss. Reads with a path list, line range, symbol or force, and reads with no plain path, go straight to the tool. A cache hit still marks the file read for the edit guard, because the agent did see it.
func RegisterDeferred ¶
RegisterDeferred adds request_tools and release_tools to r.
func ResultCacheTool ¶
ResultCacheTool wraps a tool for the subagents of one dispatch. A read-only call with the same arguments as an earlier one is answered from the bus while the files it read are unchanged. A call that may write clears the results it could have changed, before and after it runs. id names the subagent in the cache notes.
func SalvageSucceeds ¶
SalvageSucceeds says whether a failed subagent's report counts as a done task. The spec counts it as success only when salvage text exists (spec 03 §3.6). A cancellation is never salvaged: the user or the dispatch stopped the run on purpose.
func SplitPoint ¶
SplitPoint returns the index of the first message to keep: the earliest plain user prompt such that the kept tail is at most keep tokens, never splitting a tool call from its result.
The spec keeps the last four messages instead of a token budget. This keeps a token budget on purpose: it keeps more of the in-progress work. The tail moves forward to a user message rather than back, so it stays within the budget and still starts a clean exchange.
func SplitRecent ¶
SplitRecent returns the first index of the kept tail when the newest keep messages are kept verbatim. The cut moves back to the nearest user prompt, so a tool result is never separated from its call and the tail starts a clean exchange (spec 03 section 8.3). It keeps at least keep messages and may keep more; when no user prompt lies before the cut it returns 0.
func SubagentReport ¶
SubagentReport is what a subagent hands back when its run is over. A run that succeeded reports its last answer. A run that failed reports the partial answer of the call that gave up, marked as partial, so the work it did is not lost (spec 03 §3.6). It falls back to the last answer when there is no partial text.
func SubagentStepTimeout ¶
SubagentStepTimeout is the longest one model call of a subagent may run (spec 03 §3.6, getAgentTimeoutMs). It is max(300 s, tool timeout x 2.5), or 24 h when tool timeouts are off. The lead keeps its own watchdog thresholds (agent.Options).
func Transcript ¶
Transcript renders msgs as plain text. Each text part is capped at 6000 characters and each tool result at max.
func Unfinished ¶
Unfinished reports whether a saved history ends in a turn that never got an answer: its last message is a user message (the prompt, a steering note or a reminder the loop appended) or a tool result. An assistant message after the last user message or tool result means the turn finished.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is a conversation with a model that can call tools. It is safe to call Steer, Mode setters and Messages from other goroutines while Run is in progress; Run itself must not be called concurrently.
func (*Agent) Abort ¶
func (a *Agent) Abort()
Abort cancels the running turn and clears queued steering.
func (*Agent) BeginPlanExecution ¶
func (a *Agent) BeginPlanExecution()
BeginPlanExecution marks the rest of this turn as carrying out an approved plan (see PlanExecutionAllowed). It ends with the turn.
func (*Agent) CompactionLog ¶
CompactionLog returns the compactions that started, finished or were refused, oldest first.
func (*Agent) ContextEstimate ¶
ContextEstimate is the context in use: the last response's count, or, before any response has reported one, an estimate from the characters in the system prompt and history. estimated says which it is.
func (*Agent) ContextParts ¶
func (a *Agent) ContextParts() ContextParts
ContextParts returns the estimate. It is zero before the first request.
func (*Agent) ContextUsed ¶
ContextUsed returns the tokens the last request used and the window.
func (*Agent) Continue ¶
Continue re-runs an interrupted turn from the history as it stands. Unlike Run it appends no user message, because the prompt is already in the history; the model simply picks up after the last message it saw. It returns ErrNothingToContinue when the last turn finished.
func (*Agent) CurrentModel ¶
CurrentModel returns the active model.
func (*Agent) DispatchActive ¶
DispatchActive reports whether subagents may be editing the project now: this agent has a dispatch call in flight, or the guard reports one. It implements DispatchGuard, which the shell and git tools consult.
func (*Agent) EndTurn ¶
func (a *Agent) EndTurn()
EndTurn asks the loop to stop after the current tool calls (used by the plan tool, which needs the user to review before anything runs).
func (*Agent) ModelEvents ¶
ModelEvents returns the model log: each model call's usage, and the retries, fallbacks and errors around it, oldest first.
func (*Agent) OfferedForTest ¶
OfferedForTest reports which tool names the next request would carry. It exists for tests in other packages that check deferred loading.
func (*Agent) Partial ¶
Partial is the answer text the last model call left when it failed for good, after its retries. It is "" when that call left no text, or when the last call succeeded.
func (*Agent) ResetHistory ¶
ResetHistory replaces the whole history with msgs and, when mode is not empty, switches to it. Both happen under the agent lock.
func (*Agent) Run ¶
func (a *Agent) Run(ctx context.Context, prompt string, images []llm.Part) (out TurnStats, outErr error)
Run sends prompt (plus optional images) and runs until the model stops calling tools, the turn is aborted, or an error ends it.
func (*Agent) SetActive ¶
SetActive replaces the set of tool names offered to the model (nil = all). It takes effect on the next tool call, even mid-turn.
func (*Agent) SetCompaction ¶
SetCompaction applies the compaction settings from config to the running agent: the strategy ("v1" or "v2") and how many recent messages to keep verbatim (0 keeps the token-sized tail). It only changes a SummaryCompactor; a disabled compaction has no compactor and is left alone. The next compaction uses the new values, so a settings change lands at the next turn.
func (*Agent) SetMaxToolResults ¶
SetMaxToolResults applies the max_tool_results config to the running agent, the way SetCompaction applies the strategy. Zero keeps the default. It only changes a SummaryCompactor; a disabled compaction is left alone.
func (*Agent) SetMessages ¶
SetMessages replaces the history (session resume).
func (*Agent) SetPruning ¶
SetPruning sets which agents have old tool results shortened in the requests they send (config.Pruning*: none, main, subagents, both).
func (*Agent) SetReasoning ¶
SetReasoning changes the reasoning effort.
func (*Agent) SetSkills ¶
SetSkills sets the loaded-skills block the next turn latches. block is the full text of the user message (the app builds it from the loaded skills), or "" when no skill is loaded. Nothing is written to the history here; the next Run latches the change if there is one.
func (*Agent) SetTabID ¶
SetTabID sets the TUI tab id that model-log entries carry. The TUI calls it once, right after it creates the tab and before the first turn.
func (*Agent) Steer ¶
Steer queues a message for the running turn; it is delivered at the next step boundary. Returns false when the queue is full (5).
func (*Agent) SteerWithImages ¶
SteerWithImages queues a message with images (PartImage parts; other parts are dropped). The images are delivered with the message, in the same user turn, at the next step boundary.
type AgentBus ¶
type AgentBus struct {
// contains filtered or unexported fields
}
AgentBus is the state the subagents of one dispatch share: the findings they have reported, which agent first edited each file, and a cache of file reads, so two agents reading the same file do not both pay for it. It lives for one dispatch call and is safe for concurrent use.
func (*AgentBus) Abort ¶
Abort cancels every subagent of the dispatch. It reports false when the dispatch was already cancelled, so the second call says so instead.
func (*AgentBus) CachedRead ¶
CachedRead returns the output of an earlier read of key taken at the same stamp. The stamp changes when the file does, so a stale read is a miss.
func (*AgentBus) ClaimEdit ¶
ClaimEdit records that agent id is editing file. It returns the id of the agent that claimed the file first and whether that is a different agent. The first claim wins; a conflict does not change the owner.
func (*AgentBus) Conflicts ¶
Conflicts lists the files that more than one agent has edited, as "file: agents" messages, sorted. Pass file names to limit the list to those files. It is empty when every file has one editor.
func (*AgentBus) Dispose ¶
func (b *AgentBus) Dispose()
Dispose ends the bus's caches when its tab closes or its dispatch is over. It drops every read and result, wakes any reader still waiting on a read that will not finish, and makes later stores and seeds no-ops. Findings and edit owners are kept, because the dispatch's report is built from them.
func (*AgentBus) ExportCaches ¶
ExportCaches copies what a later dispatch can use. A read keeps its stamp, so an edit since then makes it a miss; the subagent that read it is dropped, since its id means nothing in the next dispatch. A result is left out when it depends on files the cache could not name, because nothing can check it later, and when it is past its TTL. Export returns nil for a nil or disposed bus.
func (*AgentBus) FindingsExcept ¶
FindingsExcept returns the findings not posted by agent id, oldest first.
func (*AgentBus) Post ¶
Post records a finding from agent id. Blank text is ignored. A finding over the limits is dropped; PostFinding says why.
func (*AgentBus) PostFinding ¶
PostFinding records f. Its text is trimmed; blank text is refused. It refuses a finding over maxFindingBytes, and one that would take the bus past maxFindingsBytes, with an error that says what to do instead.
func (*AgentBus) ReadStart ¶
func (b *AgentBus) ReadStart(id, key, stamp string) (string, bool, *ReadTicket)
ReadStart is the cache step of a read by subagent id. A stored read at the same stamp is returned as a hit. A read of that file at that stamp that is running now is waited for, up to readWait, and then served as a hit. Any other read gets a ticket and runs; its caller reports the result through Finish. With no bus or no stamp nothing is cached, and the ticket is nil.
func (*AgentBus) SeedCaches ¶
SeedCaches loads c into a bus that has not run yet, through the same limits as a live store, so a seed cannot push the bus past them. A nil c, or a disposed bus, does nothing.
func (*AgentBus) SetAbort ¶
func (b *AgentBus) SetAbort(f func())
SetAbort gives the bus the function that cancels the dispatch's subagents.
func (*AgentBus) SetCacheObserver ¶
SetCacheObserver sets the function that hears each CacheNote. It is called without the bus lock held, so it may call back into the bus.
type AgentInfo ¶
type AgentInfo struct {
ID string `json:"id"`
Task string `json:"task"`
Role string `json:"role"` // explore | code | web
Status string `json:"status"` // pending | running | done | error
Model string `json:"model"`
Step int `json:"step"`
Tokens llm.Usage `json:"tokens"`
Last string `json:"last,omitempty"` // last tool/action line
Error string `json:"error,omitempty"`
// Cache is the latest dispatch-cache outcome of this subagent's reads:
// hit | wait | store | invalidate. CacheFrom is the subagent it names.
// Both are empty when the dispatch cache is off.
Cache string `json:"cache,omitempty"`
CacheFrom string `json:"cache_from,omitempty"`
}
AgentInfo describes a subagent for the multi-agent display.
type BusCache ¶
type BusCache struct {
// contains filtered or unexported fields
}
BusCache is what a dispatch's bus keeps for the next dispatch in the same tab (spec 03 section 3.2 and 3.8). It holds finished reads and read-only tool results only: no findings, no edit owners, no running reads.
type CacheNote ¶
CacheNote says what the cache did for one subagent's read. From is the subagent whose read supplied the entry (hit) or is being waited on (wait). It is empty when no subagent is named, for example an entry stored before the reader's id was known.
Tool is set for a read-only tool result (bus_results.go), so the tally can count it apart from file reads.
type CodeMap ¶
type CodeMap interface {
FileSymbols(file string) ([]repomap.Symbol, bool)
Impact(file string) (repomap.Impact, error)
}
CodeMap is the part of the code map the dispatcher reads to check and describe a task's targets (spec 03 §3.1). *repomap.Map satisfies it. A nil CodeMap means no map: targets are checked on disk only.
type Compactor ¶
type Compactor interface {
Compact(ctx context.Context, msgs []llm.Message) (kept []llm.Message, summary string, err error)
}
Compactor shrinks a conversation that is close to the context window.
type ComputerUse ¶
type ComputerUse interface {
Run(ctx context.Context, host tools.Host, args json.RawMessage) tools.Result
}
Options configures an Agent. ComputerUse runs the calls of the computer-use tool (internal/scribe/computer). Nil leaves the tool unavailable.
type ContextParts ¶
type ContextParts struct {
System, Tools, Conversation int
}
ContextParts estimates what fills the context, in tokens, from the last request: the system prompt, the tool definitions and the conversation. They are character estimates (about four per token), so they need not add up to the count the provider reports.
type Deferred ¶
type Deferred struct {
// contains filtered or unexported fields
}
Deferred is the per-session set of tools the model has activated. Create it with NewDeferred, pass it in Options.Deferred, and register the request_tools and release_tools tools with RegisterDeferred.
func DeferSubagentTools ¶
DeferSubagentTools makes a subagent's tool list on demand, which is what agentFeatures.on_demand_tools asks for. Only the named core tools that the registry has, and request_tools and release_tools, are offered at first. The rest are listed in the prompt (DeferredCatalog) and loaded when the subagent asks for them.
Call it after every tool the subagent gets is registered, bus tools included. A tool added later is neither core nor active, so it would never be offered.
func NewDeferred ¶
NewDeferred returns a set whose core names are always offered.
type DispatchGuard ¶
type DispatchGuard interface {
DispatchActive() bool
}
DispatchGuard reports whether subagents may be editing the project right now. The agent publishes itself under env.Services["dispatch"] so the shell and git tools can refuse repository changes meanwhile.
type Dispatcher ¶
type Dispatcher struct {
New SubagentFactory
MaxConcurrent int // default 3, clamped to 2..8
Sink Sink
// Hooks, when set, sees each subagent start and finish.
Hooks SubagentObserver
// ArchiveDir receives the full text of a subagent report too long to show
// inline (dispatch_archive.go). Empty saves nothing.
ArchiveDir string
// TaskStatus is told how a task that names a taskId ended: "done" when
// it finished, "blocked" when it failed or never ran. The host uses it to
// mark the task list item. Nil does nothing.
TaskStatus func(taskID, status string)
// Map is the code map. Task targets the map knows are kept without a disk
// check, get their symbol ranges in a "Target files:" block, and get
// warnings about the importers left out of the dispatch (spec 03 §3.1).
// Nil means no map. Set it only to a real map: a typed nil is not nil here.
Map CodeMap
// Skills supplies the skill content that matches each task (spec 03 §3.1).
// Nil adds nothing.
Skills TaskSkills
// Features are the agentFeatures switches. Nil takes DefaultFeatures.
Features *Features
// MaxRetries and MaxStallRetries are passed to every subagent (see
// SubagentSpec). Zero takes the agent default.
MaxRetries int
MaxStallRetries int
// WaitTimeout bounds how long a task waits for the tasks it depends on.
// Zero takes defaultDependencyWait. A task that gives up is skipped with
// the reason, and so are its dependents.
WaitTimeout time.Duration
// contains filtered or unexported fields
}
Dispatcher provides the dispatch tool: parallel subagents.
func (*Dispatcher) CancelAgent ¶
func (d *Dispatcher) CancelAgent(id string) error
CancelAgent stops one subagent of the newest dispatch (the /cancel command). A running subagent is cancelled and reports "cancelled"; a pending one, including one waiting on its depends_on tasks, is marked cancelled and never starts. Other subagents keep running.
func (*Dispatcher) CancelDispatch ¶
func (d *Dispatcher) CancelDispatch() error
CancelDispatch stops the newest dispatch while it runs: every subagent is cancelled and the pending ones never start, as when one of them calls cancel_dispatch. It is the host's stop for a dispatch whose tool call is blocking the model, which cannot make a call of its own until it returns.
func (*Dispatcher) DispatchActive ¶
func (d *Dispatcher) DispatchActive() bool
DispatchActive reports whether a dispatch is running subagents. It implements DispatchGuard.
func (*Dispatcher) DisposeLastBus ¶
func (d *Dispatcher) DisposeLastBus()
DisposeLastBus ends the newest dispatch's bus caches and forgets the bus, so a closed tab does not keep its reads and results alive, and CancelDispatch no longer reaches it. It is safe to call with no dispatch on record.
func (*Dispatcher) Register ¶
func (d *Dispatcher) Register(r *tools.Registry)
Register adds the dispatch tool.
func (*Dispatcher) Status ¶
func (d *Dispatcher) Status() []AgentInfo
Status lists the subagents of the newest dispatch, running or finished, in the order they were started. Nil when no dispatch has run.
type Event ¶
type Event struct {
Kind EventKind `json:"kind"`
At time.Time `json:"at"`
// AgentID is "" for the main agent, else the subagent id.
AgentID string `json:"agent_id,omitempty"`
Text string `json:"text,omitempty"`
Prompt string `json:"prompt,omitempty"`
Model string `json:"model,omitempty"` // provider/model
Mode string `json:"mode,omitempty"`
Step int `json:"step,omitempty"`
CallID string `json:"call_id,omitempty"`
Tool string `json:"tool,omitempty"`
Args json.RawMessage `json:"args,omitempty"`
Result *tools.Result `json:"result,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
Usage llm.Usage `json:"usage,omitempty"`
Total llm.Usage `json:"total,omitempty"`
// CostUSD is the running session total, including subagent cost.
CostUSD float64 `json:"cost_usd,omitempty"`
// StepCostUSD is what this one model call cost, priced at the model that
// ran it (Model). Unlike CostUSD it is not cumulative, so a view can sum
// it per model. It excludes subagent spend, which has no step event.
StepCostUSD float64 `json:"step_cost_usd,omitempty"`
Attempt int `json:"attempt,omitempty"`
MaxAttempts int `json:"max_attempts,omitempty"`
Category llm.ErrorCategory `json:"category,omitempty"`
Delay time.Duration `json:"delay,omitempty"`
// Status is the HTTP status the provider answered with, when it did.
Status int `json:"status,omitempty"`
ContextUsed int `json:"context_used,omitempty"`
ContextWindow int `json:"context_window,omitempty"`
// Estimated marks a context count made from characters, not reported
// by the provider.
Estimated bool `json:"estimated,omitempty"`
Plan *Plan `json:"plan,omitempty"`
Tasks []Task `json:"tasks,omitempty"`
Agent *AgentInfo `json:"agent,omitempty"`
Stats *TurnStats `json:"stats,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
}
Event is one thing the agent did. Only the fields for its Kind are set.
type EventKind ¶
type EventKind string
EventKind discriminates Event.
const ( EvTurnStart EventKind = "turn_start" // Prompt, Model, Mode EvStepStart EventKind = "step_start" // Step (1-based) EvText EventKind = "text" // Text delta EvReasoning EventKind = "reasoning" // Text delta EvToolStart EventKind = "tool_start" // CallID, Tool (args still streaming) EvToolArgs EventKind = "tool_args" // CallID, Text = partial JSON delta EvToolRun EventKind = "tool_run" // CallID, Tool, Args (execution begins) EvToolProgress EventKind = "tool_progress" // CallID, Text (streamed output) EvToolResult EventKind = "tool_result" // CallID, Tool, Result, Duration EvStepFinish EventKind = "step_finish" // Step, Usage (this step), Total, CostUSD (cumulative), StepCostUSD and Model (this step) EvRetry EventKind = "retry" // Attempt, MaxAttempts, Category, Text (reason), Delay EvFallback EventKind = "fallback" // Model (new model ref), Text (reason) EvWarning EventKind = "warning" // Text EvError EventKind = "error" // Category, Text EvSteering EventKind = "steering" // Text (queued user message consumed mid-turn) EvCompactStart EventKind = "compact_start" // Text (reason) EvCompactDone EventKind = "compact_done" // Text (summary), Tokens before/after in Meta EvPlan EventKind = "plan" // Plan (proposed or updated) EvTasks EventKind = "tasks" // Tasks (task_list changed) EvSubagent EventKind = "subagent" // Agent (id, task, status, model, step, tokens) EvContext EventKind = "context" // ContextUsed, ContextWindow (after each step); Estimated before the first response EvNotice EventKind = "notice" // Text: an information note, not a fault EvTurnDone EventKind = "turn_done" // Stats; Text = final answer )
type Features ¶
type Features struct {
// Desloppify runs a cleanup subagent over the files code tasks edited,
// after the dispatch and before the project check. Off by default.
Desloppify bool
// TierRouting lets the app's subagent factory pick the cheap model tier
// for explore and code tasks. The factory reads the flag. On by default.
TierRouting bool
// DispatchCache gives the subagents of one dispatch a shared AgentBus:
// file reads are cached between them, and their findings and edits are
// recorded on it. On by default.
DispatchCache bool
// TargetFileValidation checks each code task's file targets against the
// workdir and notes the ones that do not exist. On by default.
TargetFileValidation bool
// VerifyEdits runs a read-only reviewer after the project check, when
// code tasks changed files. Off by default.
VerifyEdits bool
}
Features are the agentFeatures switches (spec 02 §2.2). They are read by the dispatcher; config wiring fills them in from the user's settings.
func DefaultFeatures ¶
func DefaultFeatures() Features
DefaultFeatures is the feature set when the user has not set one.
type Finding ¶
Finding is one thing a subagent reported to the others. File and Line are optional; when set they anchor the text in the code.
type Hooks ¶
type Hooks interface {
// PreTool runs before a tool call. A non-empty block reason stops the
// call and is returned to the model as the tool's error.
PreTool(ctx context.Context, tool string, args json.RawMessage) (block string)
// PostTool runs after a tool call. Extra text is appended to the
// result the model sees (e.g. formatter or linter output).
PostTool(ctx context.Context, tool string, args json.RawMessage, res tools.Result) (extra string)
// Prompt runs on each user prompt; extra text is added as context, a
// non-empty block reason refuses the prompt.
Prompt(ctx context.Context, prompt string) (extra, block string)
// Stop runs when a turn ends.
Stop(ctx context.Context, stats TurnStats)
}
Hooks lets user hooks observe and veto tool calls. Nil is fine.
type Instruction ¶
type Instruction struct {
Path string
Text string
// Scope is "global" for the Scribe home file and "project" for files
// under the project root. Empty means project scope.
Scope string
// Name is the file as the prompt labels it: relative to the project root
// for project files, the base name for global ones. Empty falls back to Path.
Name string
}
Instruction is one loaded project instruction file.
func LoadInstructions ¶
func LoadInstructions(root, home string, names []string) []Instruction
LoadInstructions reads instruction files for a project. names is a list of source ids (see InstructionSources) and/or literal file names; a name that is not a source id is read as a file name in every directory. A nil list means DefaultInstructionFiles.
Project scope is root and its parents, nearest last so it wins. Global scope is home/instructions.md, loaded only when home is a different directory from root. Each source contributes its first existing non-empty candidate per directory. Files are capped at 40 KB and identified by realpath, so a symlink does not load twice.
type InstructionSource ¶
InstructionSource is a named family of instruction files. The first existing non-empty candidate of each source is used, per directory.
type Model ¶
type Model struct {
Ref string // provider/model, for display and events
ID string // provider-local id sent in requests
Provider llm.Provider
Info llm.ModelInfo
}
Model is one resolved model: the provider that serves it and its metadata.
type Options ¶
type Options struct {
// Computer runs the computer-use tool's calls. The tool is offered to the
// model only when the request asks for it (Anthropic's computer-use tool).
Computer ComputerUse
Model Model
Fallback []Model // tried in order when Model keeps failing
// FallbackFor overrides Fallback for one primary model, keyed by its
// Ref. A model with no entry uses Fallback.
FallbackFor map[string][]Model
Tools *tools.Registry
// Peers, when set, returns the peer findings new since its last call;
// they are added to the next step's hints (PeerFeed).
Peers func() string
// SequentialTools runs every tool call in order. By default consecutive
// read-only calls run in parallel.
SequentialTools bool
// ToolTimeout bounds one tool call; 0 takes 900 s, negative turns the
// bound off. A timed-out call returns an error to the model.
ToolTimeout time.Duration
// Guard is the dispatcher, consulted by DispatchActive. Nil is fine:
// the agent still reports its own dispatch calls.
Guard DispatchGuard
// Active lists the tool names offered to the model (nil = all).
Active map[string]bool
// Env is the template for every tool call (CallID/Mode are filled in).
Env tools.Env
// System builds the system prompt. It is called once per turn so it
// can reflect the current mode; keep its output stable within a turn.
System func(mode string) string
// CodeMap returns the code map text the conversation carries ("" when off).
// It is latched into the history, not the system prompt (codemap_latch.go).
CodeMap func() string
Mode string
MaxTokens int
Reasoning string
Sink Sink
MaxSteps int // 0 = unlimited (main agent)
MaxRetries int // transient retries per step, default 3
// TabID is the TUI tab this agent serves. Model-log entries carry it, so
// the log can say which tab made each call.
TabID string
// Stream watchdog (spec 03 §5.3). FirstTokenTimeout applies until the
// first text or tool call, InterTokenTimeout after that, and StepTimeout
// caps one whole model call. Zero takes the default (180s, 120s, 900s).
// StallTimeout, when set, stands in for the first-token and inter-token
// thresholds that are not set, as it did before those existed.
StallTimeout time.Duration
FirstTokenTimeout time.Duration
InterTokenTimeout time.Duration
StepTimeout time.Duration
// ForceResolveTimeout is how long a cancelled stream is drained before
// the step gives up on it (spec 03 §5.3, forceResolveMs). Zero takes 5 s;
// set values are clamped to 1–30 s.
ForceResolveTimeout time.Duration
// MaxStallRetries is how many times a stalled model call is resumed from
// the text it had produced. Default 3; negative means never resume. Stall
// retries are immediate and do not use MaxRetries.
MaxStallRetries int
// RetryBase is the base delay of transient retries: attempt n waits
// RetryBase×2^n plus up to half of it. Zero takes 1 s (chat); subagents
// use 2 s. Clamped to 250 ms–60 s.
RetryBase time.Duration
// MaxAttempts is the legacy retry count for both kinds: it stands in for
// MaxRetries and MaxStallRetries wherever those are zero (spec 03 §10).
MaxAttempts int
// Budget bounds a subagent's run: step nudges, a tool-less final step and
// a token limit (spec 03 §3.5). Nil for the main agent.
Budget *StepBudget
// Tune edits every model request after it is built, for example to set
// provider options that depend on the conversation. m is the model the
// request goes to (the current one, or a fallback). May be nil.
Tune func(m Model, r *llm.Request)
// RequestDump sees each model request just before it is sent, with its
// step number within the turn and the model ref. It must not keep or
// change the request. Nil is fine; DumpRequests writes them as JSON Lines.
RequestDump func(step int, modelRef string, req llm.Request)
// Redact scrubs secrets from a tool result's Output before it enters the
// history or the events. May be nil.
Redact func(string) string
// BeforeTool sees each tool call just before it runs. It must not change
// the arguments. May be nil.
BeforeTool func(ctx context.Context, name string, args json.RawMessage)
// AfterTool sees each tool call's result after it runs and before Redact,
// and may change it. May be nil.
AfterTool func(ctx context.Context, name string, args json.RawMessage, res *tools.Result)
Compactor Compactor
CompactAt float64 // fraction of the context window, default 0.7; <0 disables
// CompactReset is the fill below which the compaction latch clears. A
// compaction sets the latch and nothing compacts again until the fill
// drops under this, so one oversized step does not compact repeatedly.
// Default 0.4.
CompactReset float64
// Deferred, when set, offers only the core tools plus those the model
// activated with request_tools. Nil offers every tool (subagents).
Deferred *Deferred
// Verify runs the project's quick check (typecheck, else build) when a
// turn edited files and ended without running one. label names the
// command ("" = nothing to check), report is its output on failure.
Verify func(ctx context.Context) (label string, ok bool, report string)
// Recall returns context to attach to a new user prompt (memories,
// mentioned files). May be nil.
Recall func(ctx context.Context, prompt string) string
Hooks Hooks
// Persist is called after every change to the message history so the
// session store can save it. Rewritten=true means earlier messages
// changed (compaction) rather than only new ones being appended.
Persist func(msgs []llm.Message, rewritten bool)
// ID identifies a subagent in events ("" for the main agent).
ID string
// Headers are sent with every model call.
Headers map[string]string
}
type Plan ¶
type Plan struct {
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Steps []PlanStep `json:"steps"`
// Body is the full markdown of the plan as written by the model.
Body string `json:"body,omitempty"`
// Path is where the plan was saved (.scribe/plans/<slug>.md).
Path string `json:"path,omitempty"`
// Verification is the checklist that proves the change works, in order.
Verification []string `json:"verification,omitempty"`
// Files are the files the plan creates, modifies or deletes, each with its
// action. A step's Files name the same paths.
Files []PlanFile `json:"files,omitempty"`
// Depth is "light" (checklist, at or under half the context) or "full".
Depth string `json:"depth,omitempty"`
// Outcome is set on a snapshot the user answered: "approved" (implement
// or clear and implement), "cancelled" or "revision". Feedback carries
// the requested changes.
Outcome string `json:"outcome,omitempty"`
Feedback string `json:"feedback,omitempty"`
}
Plan is a proposed implementation plan (plan mode) and its progress.
type PlanFile ¶
type PlanFile struct {
Path string `json:"path"`
Action string `json:"action"` // create | modify | delete
Description string `json:"description,omitempty"`
}
PlanFile is one file a plan touches and what happens to it.
type PlanStep ¶
type PlanStep struct {
ID string `json:"id"`
Text string `json:"text"`
Status string `json:"status"` // pending | active | done | skipped
Files []string `json:"files,omitempty"`
// Symbols are the code symbols the step adds, modifies, removes or renames.
Symbols []PlanSymbol `json:"symbols,omitempty"`
}
PlanStep is one step of a Plan.
func ParsePlanSteps ¶
ParsePlanSteps reads the steps back out of the markdown that renderPlan produced, for the review panel, with each step's files and symbols. The section ends at the first line that is not a step or a symbol.
type PlanSymbol ¶
type PlanSymbol struct {
Name string `json:"name"`
Kind string `json:"kind,omitempty"` // func, method, type, field, ...
Action string `json:"action,omitempty"` // add | modify | remove | rename
}
PlanSymbol is a code symbol a plan step adds, modifies, removes or renames.
type Planner ¶
type Planner struct {
Agent *Agent // set after the agent is created
Dir string // project root; plans are saved in <Dir>/.scribe/plans
Sink Sink
// contains filtered or unexported fields
}
Planner owns the plan and task list of one agent and provides the plan, update_plan_step, ask_user and task_list tools.
func (*Planner) MarkTask ¶
MarkTask sets the status of the task-list item a dispatch task named (its taskId, spec 03 §3.1). The dispatch calls it with "done" when the task finished and "blocked" when it failed. taskID may hold several ids joined by commas: a dispatch task that absorbed another over the task limit keeps both ids (dispatch_plan.go). An id that matches no item is ignored, because the subagent ran either way and the model should not lose its report over a stale id.
func (*Planner) Register ¶
Register adds the planner's tools. final_response comes with them: both belong to the main agent's registry, and subagents never see either.
type PromptInput ¶
type PromptInput struct {
Workdir string
Date string // YYYY-MM-DD, fixed at session start
Branch string
ModelRef string
Instructions []Instruction
Skills string // skills catalog, one line per skill
MemoryIndex string // counts of saved memories per store (memory.Stores.Index)
Deferred string // deferred tool catalog, one line per tool (may be empty)
// CodeMap is no longer rendered into the system prompt (spec 03 §7.1): the
// map reaches the conversation as a latched message (codemap_latch.go).
// It is kept only so existing callers compile; nothing reads it here.
CodeMap string
// NoMap is true when the code map tools are not registered, so the tool
// guidance must not name them. The zero value keeps the map guidance.
NoMap bool
Extra string // --system text
Subagent string // "" main agent, else "explore" / "code" / "web" / "desloppify"
// GitHub overrides the gh availability check. nil means detect it once
// per process (gh --version succeeds).
GitHub *bool
// Commands is the "Project commands" line (lint, typecheck, test, build)
// from the project's detected profile. Empty when none is detected.
Commands string
// GitContext is the git block: branch, working-tree counts, merge
// conflicts and recent commits. Empty outside a repository. The app
// computes it through the exec package, which caches it briefly.
GitContext string
}
PromptInput is everything the system prompt is built from. Keep it stable within a session: the prompt is cached by the provider and every change costs a cache miss.
type Purpose ¶
type Purpose string
Purpose says why a subagent runs. The factory uses it, with the role, to choose the subagent's model slot.
const ( // PurposeTask is a dispatch task. Its role says which kind of agent. PurposeTask Purpose = "task" // PurposeCleanup is the desloppify pass over the files code tasks edited. PurposeCleanup Purpose = "cleanup" // PurposeReview is the verifyEdits reviewer, run after the project check. PurposeReview Purpose = "review" // PurposeFix is the one follow-up agent that repairs a failing check. PurposeFix Purpose = "fix" )
type ReadTicket ¶
type ReadTicket struct {
// contains filtered or unexported fields
}
ReadTicket is a reader's claim on a read it has to run itself. Finish keeps the result for the other subagents, or only releases the waiters when the read failed. A nil ticket does nothing.
func (*ReadTicket) Finish ¶
func (t *ReadTicket) Finish(output string, ok bool)
Finish ends the read the ticket stands for. A successful read is stored for the others, and the note is store, or invalidate when it replaces an entry for an older stamp. A failed read is not stored. Waiters are released either way. Only the first call has an effect.
type Sink ¶
type Sink func(Event)
Sink receives events. Implementations must not block for long; the TUI forwards into a buffered channel.
type StepBudget ¶
type StepBudget struct {
// Kind is "explore", "code" or "web". Code agents get edit-only tools
// near the end; the wording differs by kind.
Kind string
// NudgeAt is the step from which the wrap-up hint is given (8 for
// explore, 12 for code). Zero means no wrap-up hint.
NudgeAt int
// Window is the context window the token thresholds use: the model's
// window capped at 200 000. Zero means 200 000.
Window int
}
StepBudget shapes a subagent's run (spec 03 §3.5): wrap-up hints as the step cap nears, a tool-less final step, an edit-only window for code agents, a hint after five read-only steps in a row, and a token limit. The cap itself is Options.MaxSteps.
type SubagentFactory ¶
type SubagentFactory func(spec SubagentSpec, sink Sink) *Agent
SubagentFactory builds the subagent a spec describes, whose events go to sink. The app wiring layer supplies it, because it knows which tools and models each role and purpose get.
type SubagentObserver ¶
type SubagentObserver interface {
SubagentStart(ctx context.Context, role, task string)
SubagentStop(ctx context.Context, role, task, errText string)
}
SubagentObserver is implemented by hooks that see each subagent start and finish (the SubagentStart and SubagentStop events). errText is empty when the subagent finished normally.
type SubagentSpec ¶
type SubagentSpec struct {
Role string // "explore", "code" or "web"
Purpose Purpose // why it runs
ID string // its id in events
// MaxRetries and MaxStallRetries are the Options of the same names, from
// the dispatcher's Retries. Zero takes the agent default.
MaxRetries int
MaxStallRetries int
// Bus is the state this subagent shares with the others of its dispatch.
Bus *AgentBus
// ReadCache says whether its reads go through the bus cache (the
// dispatch_cache feature). Findings are shared either way.
ReadCache bool
// Task is the task text, matched against the config's router_rules.
Task string
}
SubagentSpec describes the subagent the dispatcher wants built.
type SummaryCompactor ¶
type SummaryCompactor struct {
Model Model
// KeepTokens is roughly how much recent history to keep verbatim
// (default 20000 estimated tokens).
KeepTokens int
// Strategy is "v2" (default when empty) or "v1".
Strategy string
// KeepRecent, when above zero, keeps that many newest messages verbatim
// instead of the KeepTokens budget (spec 03 section 8.3). The cut moves
// back so a tool result never separates from its call.
KeepRecent int
// MaxToolResults is how many of the newest tool-result summaries the
// working state keeps (spec 03 section 8.5). Zero means the default of
// 30. The working state holds at most 30, so a larger value cannot add
// entries; see keepToolResults.
MaxToolResults int
// ActivePlan returns the plan in effect at compaction time, for the Plan
// section of the working state (spec 03 section 8.5). It is read each
// time a summary is made. Nil, or a nil result, means there is no plan.
ActivePlan func() *Plan
}
SummaryCompactor replaces older history with a summary plus a mechanical ledger of what was touched (files read and edited, commands run, failures), keeping the recent tail verbatim.
Strategy "v2" (the default) builds the summary from the working state (see workingstate.go) and asks a model only to fill gaps when the state is thin. Strategy "v1" always asks the model for a full summary.
type Task ¶
type Task struct {
ID string `json:"id"`
Text string `json:"text"`
Status string `json:"status"` // pending | in_progress | done | cancelled
// StepID links the task to a step of the current plan, so it is shown
// under that step while the step is active.
StepID string `json:"step_id,omitempty"`
}
Task is one task_list entry.
type TaskSkills ¶
TaskSkills supplies the skill content that matches a task's text (spec 03 §3.1). *skills.Set satisfies it. A nil TaskSkills adds nothing.
type TurnStats ¶
type TurnStats struct {
Steps int `json:"steps"`
Tokens llm.Usage `json:"tokens"`
CostUSD float64 `json:"cost_usd"`
ToolCalls []string `json:"tool_calls"`
FilesEdited []string `json:"files_edited"`
FilesRead []string `json:"files_read,omitempty"`
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
Aborted bool `json:"aborted,omitempty"`
// Retries counts the transient and stall retries the run made inside
// its model calls. A subagent's attempt count includes them.
Retries int `json:"retries,omitempty"`
}
TurnStats summarises a finished turn.
func RunClearing ¶
func RunClearing(ctx context.Context, a *Agent, p *Planner, prompt string, images []llm.Part) (TurnStats, error)
RunClearing runs one turn like Agent.Run. If the user answers a plan review with "Clear context and execute" during it, the turn ends, the history is replaced by a single user message holding the saved plan, the mode goes to default, and that message starts the continuation of the turn. It returns the stats of the last run. p may be nil.
func RunPendingExecution ¶
RunPendingExecution carries out the plan approved in the turn that just ended, as a new turn with plan execution on (see PlanExecutionAllowed). It returns false, with no turn run, when no plan is waiting. A plan still waiting after a cancelled context is dropped, so it cannot run later against a conversation the user has moved on from. p may be nil.
type WorkingState ¶
type WorkingState struct {
Task string
UserRequirements []string
// Plan is the active plan at compaction time: its title and each step's
// status (spec 03 section 8.5). Nil when there is no plan. It comes from
// the Planner, not the messages, so it is set by the caller.
Plan *Plan
Environment []string
Files []fileState
Decisions []string
AssistantNotes []string
ToolResults []toolSummary
Failures []string
Discoveries []string
}
WorkingState is the structured record of a conversation that compaction keeps instead of asking a model to summarise it. It is extracted from the messages being compacted, with the caps the spec sets for each field.
func BuildWorkingState ¶
func BuildWorkingState(msgs []llm.Message) WorkingState
BuildWorkingState extracts the working state from msgs in one pass. BuildWorkingState keeps the default number of tool-result summaries.
func (WorkingState) Serialize ¶
func (ws WorkingState) Serialize() string
Serialize writes the state in the fixed section order, omitting empty sections. The output is the summary body used by compaction.
func (WorkingState) Slots ¶
func (ws WorkingState) Slots() int
Slots is the count the spec uses to decide whether the structured state is rich enough to be the whole summary.
Source Files
¶
- agent.go
- banner.go
- budget.go
- bus.go
- bus_cache.go
- bus_export.go
- bus_results.go
- bus_tools.go
- codemap_latch.go
- compact.go
- compact_config.go
- compact_toolres_w23bud.go
- continue.go
- ctxscale.go
- deferred.go
- dispatch.go
- dispatch_archive.go
- dispatch_cacheref.go
- dispatch_plan.go
- dispatch_post.go
- dispatch_run.go
- dispatch_verify.go
- editlock_w40.go
- events.go
- failed_hints.go
- features.go
- final_response.go
- interactive.go
- ondemand_w40.go
- plan_depth.go
- plan_exec.go
- plan_nudge.go
- prompt.go
- pruning.go
- reduce.go
- requestdump.go
- reset.go
- skills_latch.go
- subagent_partial.go
- subagent_timeout.go
- task_reminder.go
- tasklink.go
- textcalls.go
- wait_notice.go
- watchdog.go
- workingstate.go