agent

package
v2.10.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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

View Source
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.

View Source
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.

View Source
var ErrNothingToContinue = errors.New("nothing to continue: the last turn finished")

ErrNothingToContinue means the history does not end in an unfinished turn.

View Source
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.

View Source
var Modes = []string{"default", "auto", "plan", "architect", "socratic", "challenge"}

Modes in the order Shift+Tab cycles them.

View Source
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

func BusTools(id string, bus *AgentBus) []tools.Tool

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 CallID

func CallID(ctx context.Context) string

CallID is the tool call id in ctx, or "".

func Collect

func Collect(ctx context.Context, p llm.Provider, req llm.Request) (string, error)

Collect runs a request without tools and returns the text.

func DeferredCatalog

func DeferredCatalog(r *tools.Registry, core func(string) bool) string

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

func DumpRequests(w io.Writer) func(step int, modelRef string, req llm.Request)

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

func EstimateTokens(msgs []llm.Message) int

EstimateTokens is the rough size of msgs (4 chars per token).

func Ledger

func Ledger(msgs []llm.Message) string

Ledger lists files read and edited, commands run and failed calls.

func ModeBanner

func ModeBanner(mode string) string

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

func ModelFamily(modelRef string) string

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

func ParsePlanVerification(md string) []string

ParsePlanVerification reads the "## Verification" checklist back out of plan markdown. It returns nil when the plan has none.

func PeerFeed

func PeerFeed(id string, bus *AgentBus) func() string

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

func PlanDepth(used, window int) string

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

func PlanExecutionAllowed(tool string) bool

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

func PlanMarkdown(pl *Plan) string

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

func PlanOptionsFor(depth string) []string

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

func PromptCaches(modelRef string) bool

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

func PruneOldToolResults(msgs []llm.Message) []llm.Message

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

func PruningApplies(target string, subagent bool) bool

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

func ReadCacheTool(inner tools.Tool, bus *AgentBus, id string) tools.Tool

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

func RegisterDeferred(r *tools.Registry, d *Deferred)

RegisterDeferred adds request_tools and release_tools to r.

func ResultCacheTool

func ResultCacheTool(inner tools.Tool, bus *AgentBus, id string) tools.Tool

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

func SalvageSucceeds(runErr error, report string) bool

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

func SplitPoint(msgs []llm.Message, keep int) int

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

func SplitRecent(msgs []llm.Message, keep int) int

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

func SubagentReport(a *Agent, runErr error) string

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

func SubagentStepTimeout(toolTimeout time.Duration) time.Duration

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

func Transcript(msgs []llm.Message, max int) string

Transcript renders msgs as plain text. Each text part is capped at 6000 characters and each tool result at max.

func Unfinished

func Unfinished(msgs []llm.Message) bool

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.

func WithCallID

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

WithCallID returns ctx carrying the id of the tool call about to run, so the tool hooks can report which call they are about (tool_use_id).

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 New

func New(o Options) *Agent

New creates an agent.

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) Compact

func (a *Agent) Compact(ctx context.Context, reason string) error

Compact summarises older history now.

func (*Agent) CompactionLog

func (a *Agent) CompactionLog() []Event

CompactionLog returns the compactions that started, finished or were refused, oldest first.

func (*Agent) ContextEstimate

func (a *Agent) ContextEstimate() (used int, estimated bool)

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

func (a *Agent) ContextUsed() (int, int)

ContextUsed returns the tokens the last request used and the window.

func (*Agent) Continue

func (a *Agent) Continue(ctx context.Context) (TurnStats, error)

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

func (a *Agent) CurrentModel() Model

CurrentModel returns the active model.

func (*Agent) DispatchActive

func (a *Agent) DispatchActive() bool

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) Messages

func (a *Agent) Messages() []llm.Message

Messages returns a copy of the history.

func (*Agent) Mode

func (a *Agent) Mode() string

Mode returns the current mode.

func (*Agent) ModelEvents

func (a *Agent) ModelEvents() []Event

ModelEvents returns the model log: each model call's usage, and the retries, fallbacks and errors around it, oldest first.

func (*Agent) OfferedForTest

func (a *Agent) OfferedForTest() map[string]bool

OfferedForTest reports which tool names the next request would carry. It exists for tests in other packages that check deferred loading.

func (*Agent) Partial

func (a *Agent) Partial() string

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) Queued

func (a *Agent) Queued() []string

Queued returns pending steering messages.

func (*Agent) Reasoning

func (a *Agent) Reasoning() string

Reasoning is the reasoning effort set for the agent's model calls.

func (*Agent) ResetHistory

func (a *Agent) ResetHistory(msgs []llm.Message, mode string)

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) Running

func (a *Agent) Running() bool

Running reports whether a turn is in progress.

func (*Agent) SetActive

func (a *Agent) SetActive(active map[string]bool)

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

func (a *Agent) SetCompaction(strategy string, keepRecent int)

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

func (a *Agent) SetMaxToolResults(n int)

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

func (a *Agent) SetMessages(m []llm.Message)

SetMessages replaces the history (session resume).

func (*Agent) SetMode

func (a *Agent) SetMode(m string)

func (*Agent) SetModel

func (a *Agent) SetModel(m Model)

SetModel switches model for the next step.

func (*Agent) SetPruning

func (a *Agent) SetPruning(target string)

SetPruning sets which agents have old tool results shortened in the requests they send (config.Pruning*: none, main, subagents, both).

func (*Agent) SetReasoning

func (a *Agent) SetReasoning(r string)

SetReasoning changes the reasoning effort.

func (*Agent) SetSkills

func (a *Agent) SetSkills(block string)

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

func (a *Agent) SetTabID(id string)

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

func (a *Agent) Steer(msg string) bool

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

func (a *Agent) SteerWithImages(msg string, images []llm.Part) bool

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.

func (*Agent) Usage

func (a *Agent) Usage() (llm.Usage, float64)

Usage returns cumulative token usage and cost.

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 NewAgentBus

func NewAgentBus() *AgentBus

NewAgentBus returns an empty bus.

func (*AgentBus) Abort

func (b *AgentBus) Abort() bool

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) Aborted

func (b *AgentBus) Aborted() bool

Aborted reports whether the dispatch was cancelled through the bus.

func (*AgentBus) CachedRead

func (b *AgentBus) CachedRead(key, stamp string) (string, bool)

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

func (b *AgentBus) ClaimEdit(file, id string) (owner string, conflict bool)

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

func (b *AgentBus) Conflicts(file ...string) []string

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

func (b *AgentBus) ExportCaches() *BusCache

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) Findings

func (b *AgentBus) Findings() []Finding

Findings returns the findings posted so far, oldest first.

func (*AgentBus) FindingsExcept

func (b *AgentBus) FindingsExcept(id string) []Finding

FindingsExcept returns the findings not posted by agent id, oldest first.

func (*AgentBus) Post

func (b *AgentBus) Post(id, text string)

Post records a finding from agent id. Blank text is ignored. A finding over the limits is dropped; PostFinding says why.

func (*AgentBus) PostFinding

func (b *AgentBus) PostFinding(f Finding) error

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

func (b *AgentBus) SeedCaches(c *BusCache)

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

func (b *AgentBus) SetCacheObserver(f func(CacheNote))

SetCacheObserver sets the function that hears each CacheNote. It is called without the bus lock held, so it may call back into the bus.

func (*AgentBus) StoreRead

func (b *AgentBus) StoreRead(key, stamp, output string)

StoreRead remembers the output of a read of key at stamp.

func (*AgentBus) ToolResult

func (b *AgentBus) ToolResult(key string) (tools.Result, bool)

ToolResult returns the stored result for key when it is still valid: within its TTL and with its files unchanged. An expired or stale entry is dropped.

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

type CacheNote struct {
	Agent   string
	Outcome string
	From    string
	Tool    bool
}

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

func DeferSubagentTools(reg *tools.Registry, core []string) *Deferred

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

func NewDeferred(core []string) *Deferred

NewDeferred returns a set whose core names are always offered.

func (*Deferred) Active

func (d *Deferred) Active() []string

Active returns the activated (non-core) names, sorted.

func (*Deferred) IsCore

func (d *Deferred) IsCore(name string) bool

IsCore reports whether name is 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

type Finding struct {
	Agent string
	File  string
	Line  int
	Text  string
}

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

type InstructionSource struct {
	ID    string
	Label string
	Files []string
}

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

func ParsePlanSteps(md string) []PlanStep

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

func (p *Planner) MarkTask(taskID, status string)

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) Plan

func (p *Planner) Plan() *Plan

Plan returns the current plan (nil when none).

func (*Planner) Register

func (p *Planner) Register(r *tools.Registry)

Register adds the planner's tools. final_response comes with them: both belong to the main agent's registry, and subagents never see either.

func (*Planner) SetPlan

func (p *Planner) SetPlan(pl *Plan)

SetPlan restores a plan (session resume).

func (*Planner) Tasks

func (p *Planner) Tasks() []Task

Tasks returns the task list.

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.

func (SummaryCompactor) Compact

func (c SummaryCompactor) Compact(ctx context.Context, msgs []llm.Message) ([]llm.Message, string, error)

Compact implements Compactor.

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

type TaskSkills interface {
	ForTask(task string) []string
}

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

func RunPendingExecution(ctx context.Context, a *Agent, p *Planner) (TurnStats, bool, error)

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.

Jump to

Keyboard shortcuts

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