agent

package
v0.209.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 48 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

degenerate.go — the NaN shape, named (register D-118).

A seat whose numerics are broken does not fail loudly: /health is green, /v1/models lists it, a speed probe passes, and every completion comes back as the same token repeated to the cap — `<tool_call>!!!!!!!!!!!!!!!!!!!!…` on the Qwen3.8-27B GSQ seat under vLLM 0.29 with fp8_e5m2 KV through FlashInfer (2026-09-16/17, blackwell-16; the ADR 0048 Amendment 1 arm). Every contract it took reported `unparsed_tool_call` after 126–336 s of that output.

DegenerateRun is the one detector for that shape, so the admission probe (pipeline.ProbeSeatCoherence) and anything else that reads a raw completion judge it the same way.

Package agent implements the local Agent-loop: the canonical "while the model requests tools, execute them and feed results back" cycle (Phase 0 — read-only). It is deliberately model-backend-agnostic (any OpenAI-compatible tool-calling Client) and side-effect-agnostic (tools are injected), so the loop logic is unit-testable without a live model or real tools. Stop conditions and the step budget are owned HERE, in code — never by the model — and an erroring or unknown tool is fed back as data (defer-not- crash), never a panic or an aborted run.

props.go — the SERVER-SIDE half of experiment config pinning (A1, Tier 2 of the 2026-08-21 Phase 2 re-aim). ProbeSeatPin reduces a seat's live llama-server /props answer to a stable hash + a human-readable basis, so a paired cross-seat run can REFUSE to compare rows produced under different serving configs.

Scope honesty — what this pin does and does not buy: it detects drift in the SERVED state (weights file, quant, build, context window, server-side sampler defaults, chat template). It cannot see the harness's own request construction (per-call temperature, the re-pack's enable_thinking:false, profile toolsets) — that half is code, pinned separately by buildinfo.Version + buildinfo.BuildSHA256 on the same wire result. The defect class that invalidated the 2026-08-17 corpus (enable_thinking/GBNF empty content) lived on the REQUEST side; naming this hash alone as the fix for that class would be false, which is why both halves ship together.

repetition.go — the degenerate-loop guard for a final answer (register D-95b).

A small seat asked for a long grounded extraction can stop making progress and start repeating itself, generating the same block until the completion budget runs out. The engine reports that as an ordinary `length` cut (or even as `stop`), so nothing downstream could tell it from an answer that merely ran long: the <node-c> 4B's METHODOLOGY.md digest of 2026-09-14 spent 381 s and its whole final budget emitting one four-line block about twenty times, and the node deferred with the loop riding in `output`.

The guard reads the RETURNED TEXT — it never rewrites what the engine reported. It answers one question: does the tail of this answer consist of the same block, repeated? If so the run treats the final as cut (loop.go), re-issues once with an explicit do-not-repeat instruction on top of the list caps, and trims the repeated tail off the partial the caller sees.

sampling.go — the planner's decoding policy, per call (register D-95b).

The policy travels on the CONTEXT, exactly like the non-thinking render (thinking.go): the Client interface keeps its signature, every fake keeps working, and a client that ignores the value simply decodes as it always did. The loop sets it once per step — the planner policy on tool steps, the final policy on the answer turn and its re-issues — so a seat can be greedy while it calls tools and sampled while it writes prose, which is what the Qwen3-class non-thinking recommendation actually asks for.

thinking.go — hidden reasoning as a first-class fact of a completion.

A THINKING seat (vLLM --reasoning-parser qwen3, llama.cpp --reasoning-format) spends its completion budget in two channels the caller cannot see from the content alone: the think block and the visible answer. Until 0.115.8 the loop could not tell "the model said nothing" from "the model spent every token thinking and was cut before it could answer": both arrived as an empty content string. On 2026-09-10 that indistinguishability cost 20,526 tokens on the <node-b> 27B seat and 9,628 on the <node-c> 4B for zero visible output, then published the empty final as a finished answer (retrospective D-01).

This file gives the loop the three things it needs: a per-call switch that renders the seat's template in non-thinking mode, a classifier that names a starved completion, and a per-call record the corpus keeps so the rigger can see the starvation instead of inferring it from token totals.

window.go — served-context-window discovery. The compaction budget is only as honest as the window it targets: two real runs died with `exceed_context_size` 400s because `--ctx-tokens` assumed 16384 while the serving tier ran `-c 8192` — the budget never engaged before the server refused (flip-decision report 2026-07-24, finding F4). The fix is to ASK the endpoint instead of assuming: llama.cpp's `/props` reports the live n_ctx, and llama-swap proxies it per model under `/upstream/{model}/`.

Index

Constants

View Source
const (
	// StopReasoningStarved: the final completion spent its budget on hidden
	// reasoning and produced no visible content, on the first attempt AND on
	// the one retry with thinking off. Result.StopNote carries the arithmetic.
	StopReasoningStarved = "reasoning_starved"
	// StopEmpty: the model closed with an empty message (finish "stop", no
	// content, no tool calls) twice — once thinking, once not. Not a budget
	// shape: the seat had room and said nothing.
	StopEmpty = "empty"
)

Stop reasons a run can END on besides "done" / "budget" / "error" (Result.StopReason). Both are terminal and carry an EMPTY Output; the node (pipeline/agenttask.go) turns them into a defer instead of re-packing the empty string into a schema-valid, all-empty object.

View Source
const ArchitectPrompt = `` /* 1003-byte string literal not displayed */

ArchitectPrompt is the planning-model system prompt for two-tier mode. It has read/search tools only (NO write) and its whole job is to emit ONE complete, unambiguous plan a separate edit model will execute WITHOUT ever seeing the original request — so the plan must stand alone. Phrasing follows aider's architect prompt (provide direction to your editor engineer; make it unambiguous and complete; do NOT reproduce whole files).

View Source
const CompactionMargin = compactionMargin

CompactionMargin exposes the production safety margin so a measurement can budget exactly as the loop does instead of guessing (Phase D, ADR 0017).

View Source
const DefaultKeepRecent = defaultKeepRecent

DefaultKeepRecent exposes the production keep-recent default so replay callers (the compaction eval's trace harvest) mirror the live loop's pressure instead of silently replaying under a harsher setting.

View Source
const EditorPrompt = `` /* 428-byte string literal not displayed */

EditorPrompt is the edit-model system prompt for two-tier mode. Its sole user message is the architect's plan (no history, not the original request), and it has the write tools the user's --allow-* flags granted.

View Source
const FallbackContextTokens = 8192

FallbackContextTokens is the window assumed when the probe cannot answer — the CONSERVATIVE choice (the smallest window any of our serving tiers runs), matching the loop's own built-in default: a too-small assumption wastes some budget headroom; a too-large one kills runs with server 400s.

View Source
const FinalAnswerTurn = "" /* 252-byte string literal not displayed */

FinalAnswerTurn opens the forced final step (0.115.19, register D-89): the last step of a multi-step run offers no tools and asks for the answer. Exported so a test double standing in for a seat can recognise the call.

View Source
const FinalReissueListCap = "list_cap"

FinalReissueListCap names the one re-issue shape a cut final can earn (register D-95): the final turn asked again, thinking off, with the schema's own list caps spelled out.

View Source
const NoRepeatInstruction = "" /* 176-byte string literal not displayed */

NoRepeatInstruction is the sentence a re-issue adds when the answer it replaces was a repetition loop. It is deliberately concrete — a seat that looped once will loop again on the same request unless it is told what went wrong (the same reason the list-cap instruction says the answer was cut).

View Source
const PagerGate = pagerGate

PagerGate exports the threshold so a reader of recorded runs (the trace-corpus readout) judges a pooled rate against the same number the instrument judges a single run against.

View Source
const ReadFileLineCap = 2000

ReadFileLineCap is the longest line read_file returns: a longer one is cut there and marked, and its rest cannot be reached (offset and limit count lines). Exported so the producers of context documents (research.MaxLineChars) can be pinned under it.

View Source
const (

	// RepackMargin is repackMargin for the node-side re-pack's time bound
	// (pipeline.repackOwed): the time a re-pack is owed is the generation time its
	// own stall allowance already assumes, not a second number.
	RepackMargin = repackMargin
)
View Source
const RulesOff = "off"

RulesOff is the sentinel RulesPath value that disables the default unattended rule table (an explicit opt-out, documented on --rules). It is compared as a literal: a real rule file cannot plausibly be named "off" bare of any path.

View Source
const StopToolCallCut = "tool_call_cut"

StopToolCallCut (register D-114): the seat's tool-call ARGUMENT was cut by the completion budget twice — once at the step budget, once at the wall-fitted final budget the re-issue opened at. Terminal, with an empty Output and the arithmetic in StopNote; the node files it as a BUDGET defer, never infrastructure. Measured 2026-09-15 on the <node-a> 9B llama.cpp seat (step_tokens 1024, a ~3 KB single-call write): llama.cpp answered HTTP 500 "Failed to parse tool call arguments as JSON … invalid string: missing closing quote" at column 2847 and the run was filed against the stack.

View Source
const TokenizerDegradedPrefix = "legacy (degraded: "

TokenizerDegradedPrefix is the stable prefix of every degraded Result.TokenizerPath value. Exported as the ONE contract between tokPath (which writes it) and every consumer that branches on degradation (the CLI stderr note, queue traces) — two independent string literals here would let a wording tweak silently kill the operator-facing note (review finding 2026-08-14).

Variables

View Source
var ErrUnparsedToolCall = errors.New("unparsed tool call in assistant content")

ErrUnparsedToolCall: the server returned an assistant message with no parsed tool calls whose text still carries a tool-call block. The model DID call a tool; the server's tool-call parser did not recognise the format. Treating that text as a final answer is how a misconfigured seat "answers" every contract with garbage (<node-b> 27B, 2026-09-04: hermes parser on a Qwen3 XML template, 8/8 digests failed verification with findings about list_dir).

Functions

func ContextWithProgress added in v0.206.0

func ContextWithProgress(ctx context.Context, fn ProgressFunc) context.Context

ContextWithProgress installs fn for the Chat calls made under ctx — the same pattern as ContextWithSampling: per-call behaviour rides the context so Chat's signature never changes. A nil fn removes an inherited one.

func ContextWithSampling added in v0.206.0

func ContextWithSampling(ctx context.Context, s *Sampling) context.Context

ContextWithSampling returns a context whose next Chat call decodes under s. A zero policy is carried too: it renders today's request byte for byte, and carrying it keeps "unset" and "explicitly default" the same thing.

func ContextWithSeatCheck added in v0.206.0

func ContextWithSeatCheck(ctx context.Context, fn SeatCheckFunc) context.Context

ContextWithSeatCheck attaches the check to ctx for the chat client.

func ContextWithoutThinking added in v0.206.0

func ContextWithoutThinking(ctx context.Context) context.Context

ContextWithoutThinking returns a context whose Chat calls send `chat_template_kwargs: {"enable_thinking": false}`.

func DefaultAuditPath added in v0.206.0

func DefaultAuditPath(base string) string

DefaultAuditPath is the broker audit trail's default home, outside any worktree (Invariant 5): agent-audit.jsonl under the harness install root base (config `home`), else <user home>/.local-offload — the same file the local-agent CLI defaults to. "" when no root can be resolved, which makes Build refuse a browse grant (every browse run must leave a trail). When an earlier release left a trail at the old location, the first call in a process says so on stderr (DefaultStateFile).

func DefaultStateFile added in v0.206.0

func DefaultStateFile(base, name string, warn io.Writer) string

DefaultStateFile is StateFile for a path the caller DEFAULTED (not one the operator named with a flag), and it says when that default moved under an earlier release's feet. Until the install root governed these files they all lived under <user home>/.local-offload, so a node whose `home` points elsewhere now writes a new file and leaves the old one where it was: the append-only trail is split in two and nothing carries the old entries over. When the earlier file or directory exists and is not the one this run writes, one note goes to warn (nil means no notes), once per process, naming both paths and what to do about it. The earlier history is never moved, merged or deleted here: that is the operator's call.

func DegenerateRun added in v0.206.0

func DegenerateRun(content string) (byte, int)

DegenerateRun returns the byte and length of the longest run of ONE repeated NON-WHITESPACE byte in content when that run reaches degenerateRunMin, and (0, 0) otherwise.

Whitespace is excluded on purpose: indentation, blank-line padding and the space runs in an ASCII table are ordinary text, and counting them would flag healthy output. Bytes, not runes: a multi-byte rune repeated 20 times still repeats its own bytes far past the floor, so the byte scan catches it — it simply names a byte of the rune rather than the rune.

func EffectCounts added in v0.206.0

func EffectCounts(recs []EffectRecord) map[EffectStatus]int

EffectCounts aggregates a run's records per status — the summary an MCP caller actually reads ("did anything end up in unknown?").

func EstimateTokens added in v0.206.0

func EstimateTokens(msgs []Msg) int

EstimateTokens exposes the ladder's own token estimator so replay callers measure with the same yardstick the ladder budgets by.

func FinalBudgetFor added in v0.206.0

func FinalBudgetFor(stepBudget int) int

FinalBudgetFor is the final answer's completion budget for a tool-step budget (finalMaxTokens), exported for the wall estimate (register D-03).

func IsCompactionArtifact added in v0.206.0

func IsCompactionArtifact(content string) bool

IsCompactionArtifact reports whether a tool body is a PRODUCT of this ladder — an elision marker (with or without signal residue), a skeleton, or a dedupe reference — rather than raw content. The trace harvest uses it to refuse already-compacted transcripts: replaying compaction-of-compacted text would measure the ladder against its own output and bias every ratio toward 1.

func IsEvidenceReceipt added in v0.206.0

func IsEvidenceReceipt(content string) bool

IsEvidenceReceipt reports whether a tool body is a receipt written by the evidence reducer. Like IsLogCollapseArtifact it is separate from IsCompactionArtifact: that predicate drives the always-on dedupe rung, and a step that is off must not change the default ladder, even for a body that merely quotes the opening line. The trace harvest asks it so it refuses a transcript whose raw output a receipt already replaced; the loop asks it (only with the reducer installed) so a repeated call is re-run.

func IsLogCollapseArtifact added in v0.206.0

func IsLogCollapseArtifact(content string) bool

IsLogCollapseArtifact reports whether a tool body is a PRODUCT of the optional log-collapse rung. It is deliberately separate from IsCompactionArtifact: that predicate also drives the default ladder (the always-on dedupe rung) and the live loop's re-execute-versus-refuse decision, and a rung that is off must not change either, even for a body that merely quotes the header. The trace harvest, which refuses already-compacted transcripts whichever ladder produced them, asks both questions. Wiring the rung into the live loop later must also teach resultDestroyed this predicate.

func IsNotPerformed added in v0.206.0

func IsNotPerformed(err error) bool

IsNotPerformed reports whether err is a NotPerformed sentinel.

func IsThinkingOff added in v0.206.0

func IsThinkingOff(ctx context.Context) bool

IsThinkingOff reports whether ctx asks for a non-thinking render.

func Mem0KeyFromEnvOrFile

func Mem0KeyFromEnvOrFile() string

Mem0KeyFromEnvOrFile resolves the mem0 API key: $MEM0_API_KEY first, then the on-disk key file (~/.mem0/api-key, mode 600 — the mem0 server's own key source). Returns "" if neither is present (memory then stays disabled rather than crashing).

func NotPerformed added in v0.206.0

func NotPerformed(msg string) error

NotPerformed wraps a refusal message for Exec to return as its error. The message is what the model will see as the (non-error) tool result.

func ProbeServedWindow added in v0.206.0

func ProbeServedWindow(ctx context.Context, base, model string) (int, bool)

ProbeServedWindow asks the serving endpoint for model's live context window (n_ctx). It tries, in order:

  1. {base}/upstream/{model}/props — llama-swap's per-model passthrough (the production topology; may cold-start the model, which is acceptable: the caller is about to use exactly that model — EXCEPT under a GPU-lease fence, where modelaffinity.AwaitUpstream holds the request until the card frees or the caller's deadline ends, and it is never sent onto a card a render or an exclusive hold owns);
  2. {base}/props — a bare llama-server.

A trailing /v1 on base is stripped first (props lives at the server root), via the one endpoint-normalization rule in internal/swapclient. Returns (n_ctx, true) on success; (0, false) on any failure — callers fall back, never fail, on an unanswerable probe (a generic OpenAI endpoint has no /props and that is fine).

This is the ONE llama-swap call the harness does not route through pkg/llamaswap, and the reason is the auto-start above: [llamaswap.Client.Props] checks /running first and returns ErrNotLoaded rather than triggering a multi-GB load — the right default for an operator probe, and exactly wrong here. The planner seat is normally COLD at this point, so a refusing probe would silently drop every cold run back to FallbackContextTokens and re-open finding F4. Alias resolution, the package's other reason to exist, buys nothing here: llama-swap resolves aliases on /upstream itself (verified live: both /upstream/embeddinggemma/props and /upstream/local-embed/props answer 200).

func ProbeServedWindowChecked added in v0.206.0

func ProbeServedWindowChecked(ctx context.Context, base, model string) (int, bool, error)

ProbeServedWindowChecked is ProbeServedWindow that also says WHY it did not answer when the reason is the GPU-lease fence (2026-09-22): a render, or an exclusive hold, owns the card and the seat is not resident, so the probe — whose route would LOAD the seat — was never sent. err is then the fence's *modelaffinity.LeaseError (modelaffinity.IsLeaseRefusal), and nil on every other outcome, which keeps the fail-open contract for a broken endpoint. The run launchers use it to defer `capacity` instead of starting a run whose every request would wait behind the same fence.

The fence waits for the card inside ctx's deadline (and coldStartWait), so a render that ends within the caller's admission budget costs a wait, not a defer.

func ProbeUpstreamWindow added in v0.206.0

func ProbeUpstreamWindow(ctx context.Context, base, model string) (int, bool)

ProbeUpstreamWindow is ProbeServedWindow restricted to the llama-swap per-model passthrough — no bare-root fallback. The root /props answers for WHATEVER model is currently loaded, so a multi-model caller (the cascade's TO-3 repack) falling through to it would budget one tier against another tier's window (review finding 2026-08-14). Single-model callers keep ProbeServedWindow's fallback.

func ProbeUpstreamWindowNow added in v0.206.0

func ProbeUpstreamWindowNow(ctx context.Context, base, model string) (int, bool, error)

ProbeUpstreamWindowNow is ProbeUpstreamWindow that does NOT wait behind a GPU-lease fence (2026-09-22): under a render or an exclusive hold over a model that is not resident it returns at once with the fence's *LeaseError, and a cold start is still absorbed when nothing fences the card. For a caller whose NEXT request is a generation that waits at modelaffinity.Admit anyway (the cascade's per-tier re-pack): waiting here too would spend the caller's time twice, and a fenced answer must not be cached as "this tier has no window".

func ReadUsers added in v0.206.0

func ReadUsers(agentNamespace, sharedNamespace string) []string

ReadUsers builds the recall-namespace list for the agent: always the agent's own namespace, plus an optional operator/shared namespace when one is configured. The public build defaults the shared namespace to empty, so an unconfigured agent recalls only its own namespace and carries no operator's personal namespace baked in — an operator opts in by setting it (see the --mem-shared-namespace flag / MEM0_SHARED_NAMESPACE). A whitespace-only value is treated as unset.

func ResolveContextTokens added in v0.206.0

func ResolveContextTokens(flag, probed, configured int, probeOK bool) (int, string)

ResolveContextTokens turns the --ctx-tokens knob + a probe result into the window the loop budgets against, with one honest rule per case:

  • flag <= 0 (auto, the default): the probed window when the probe answers; when the probe FAILS, the seat's CONFIGURED window (config agent_ctx_tokens) when one is known, and FallbackContextTokens only when nothing better is known — never a hardcoded per-tier assumption. The probe now waits out a cold start (coldStartWait), so the configured window is reached only when the endpoint cannot answer inside the caller's budget; before both fixes a cold seat silently ran a 114,688-token window at 8,192 for the WHOLE task (the same agent_run measured 8,192 cold and 114,688 warm, minutes apart). When the probe answers, the SERVED window wins over the configured one — live beats written — and a disagreement is named in the note, because a stale config is exactly what would mislead the fallback path the next time the probe fails;
  • flag > 0 (operator override): the flag wins, but when the probe answered with LESS than the flag a warning names the gap — that exact mismatch (assumed 16384, served 8192) killed real runs before it was measured.

The returned note is "" or a human-readable line for stderr; this function stays pure (no logging) so every drive mode reports identically.

func ResponseShape added in v0.206.0

func ResponseShape(calls []CallRecord) string

ResponseShape summarizes, from a run's call records, how the seat ANSWERED (register D-45): which key carried hidden reasoning (vLLM `reasoning`, llama.cpp `reasoning_content`, or none), whether the server reported reasoning tokens, and how many tool calls were parsed. The 2026-09-04 hermes-vs-qwen3_xml parser mismatch and the 2026-09-10 reasoning-key blind spot were both seat facts the corpus could not show; this is the per-run record that makes the next one visible. Empty when no call ran.

func SetupRan added in v0.206.0

func SetupRan(effects []EffectRecord) int

SetupRan counts the setup actions that EXECUTED (committed or failed) in an effect ledger — the number the wire result and the MCP door report. A refused, unknown-tool or over-budget action ran nothing and is not counted; its Step-0 record says why.

func StateFile added in v0.206.0

func StateFile(base, name string) string

StateFile is where the coding agent keeps one of its own files (the policy audit trail, the ask queue, per-goal traces): name under the harness install root base (config `home`, which every other derived store already follows), else under <user home>/.local-offload, which is where every release before the install root became a knob wrote them. "" when neither can be resolved.

A base that is not absolute counts as no base. config.DefaultBase() answers a bare ".local-offload" when the user home cannot be resolved, and a path relative to the working directory may sit inside the very worktree these files must stay outside of (the audit-outside-the-worktree invariant); "" is what makes Build refuse a browse grant that has no trail.

func SystemPrompt

func SystemPrompt(caps PromptCaps) string

SystemPrompt is the loop's capability-aware system prompt: it advertises only the tools actually granted (read-only by default, +write/+web_fetch/+run_shell when enabled) and labels fetched web content as untrusted data. It is shared by every drive mode (headless CLI, MCP front door, standalone) so the agent's behavior is identical regardless of who supplies the goal.

func TrimRepetitionLoop added in v0.206.0

func TrimRepetitionLoop(s string) (string, string, bool)

TrimRepetitionLoop returns the answer with the repeated tail cut to ONE copy plus a marker, the one-line stop note naming the loop, and whether a loop was found. On a clean answer it is a byte-for-byte no-op with an empty note — it runs on every final.

func UnparsedToolCallMarker added in v0.206.0

func UnparsedToolCallMarker(content string) string

UnparsedToolCallMarker returns the tool-call syntax found in an assistant message's plain text, or "" when there is none. The forms are the ones the engines we run emit: the Qwen3/Hermes XML wrapper, the Qwen3-coder function tag, and the Llama-3 pythonic tag.

Exported since register D-118: the admission-time coherence probe (pipeline.ProbeSeatCoherence) reads the SAME markers the loop does, so a seat whose parser is mismatched is caught before the wall starts rather than after it — one definition, never two that can drift.

Types

type AccelLane added in v0.206.0

type AccelLane struct {
	ID   string
	Call NPUFunc
	// Remote marks a lane that forwards to a fleet node carrying the device
	// (accelremote, Coral Phase B); the tool descriptions say so.
	Remote bool
	// Claims names the tools this lane serves ahead of the listed order
	// (config accelerator_tool_owners, ADR 0068). A claim on a tool the lane's
	// table lacks is ignored, so the first-listed rule still decides it.
	Claims []string
}

AccelLane is one accelerator's in-process lane for the agent loop: the device id (from config.Accelerators) and the func that reaches its sidecar. The builder passes every wired lane in config order (pipeline.NewLoopAccel), and that order is load-bearing — see accelLaneTools.

type Action

type Action struct {
	Kind   ActionKind
	Path   string
	Exists bool
}

Action is a proposed mutating operation. Path is worktree-relative (the worktree FS boundary itself is enforced separately by os.Root); Exists tells the broker whether the target already exists (new vs overwrite).

type ActionKind

type ActionKind string

ActionKind is the class of mutating action the broker gates. P2 covers file mutations; later phases extend this (shell, network) behind the same broker.

const (
	ActWrite  ActionKind = "write"
	ActDelete ActionKind = "delete"
	ActFetch  ActionKind = "fetch" // P3: outbound HTTP(S) GET to a host (egress-allowlist gated)
	ActShell  ActionKind = "shell" // P4.6: run a command inside the OS sandbox (opt-in, audited)
	// ActBrowse (ADR 0060): drive the operator's own browser; Path holds the start
	// URL's lowercased host. Opt-in (WithBrowse), audited, rule-tightenable by host.
	ActBrowse ActionKind = "browse"
	// ActPark records a self-flagged high-risk call parked on an unattended run
	// (Loop.WithParkRecorder → ask queue). Queue/audit vocabulary only — the
	// broker never classifies it and the rule table rejects it implicitly
	// (validate allows write/delete/fetch only).
	ActPark ActionKind = "park"
)
const ActRead ActionKind = "read"

ActRead (register SF-07) is a file READ by an agent tool. Reads are not mutations and never go through Policy.Decide; they pass the read gate below, which every tool that reads file content consults: read_file, summarize_file, search_files, edit_file (it reads the old content) and github_upload_file. A rule table may name the kind (tighten-only, like every other kind).

Not covered, and said so in the docs: the run/shell cage (an allowlisted python, node or git can read any file it can reach, and on native Windows reads are not confined), hard links (a second name for the same file content), and the media tools that read an absolute image path.

type Allowlist

type Allowlist struct {
	// contains filtered or unexported fields
}

Allowlist is the P3 egress host allowlist: a set of canonical hosts plus opt-in, boundary-anchored wildcard suffixes. It is built once and never mutated, so the policy broker that reads it stays deterministic. The zero value permits NOTHING (default-deny) — exactly how P0/P1 grant no network tool at all. The host-matching rule is the security boundary; see canonHost.

func NewAllowlist

func NewAllowlist(entries []string) (Allowlist, error)

NewAllowlist parses bare-hostname entries and "*.host" wildcards into an Allowlist, rejecting any entry that carries a scheme, port, path, userinfo, or backslash (bare hostnames only — the Managed-Agents rule). Empty input yields the deny-all zero value. A "*." prefix becomes a boundary-anchored suffix; any other "*" (mid-label, bare) is rejected by canonHost.

type AuditLog

type AuditLog struct {
	// contains filtered or unexported fields
}

AuditLog is an append-only JSONL record of every brokered decision — kept separate from the savings ledger, never co-mingled.

func NewAuditLog

func NewAuditLog(path string) *AuditLog

NewAuditLog returns a logger writing to path (created on first record).

func (*AuditLog) EndRun added in v0.206.0

func (l *AuditLog) EndRun() error

EndRun closes a chained run with a run_end row carrying the run's decision count and the hash of its last row. Without it the run verifies as OPEN, which `verify --strict` fails. It does not make a cut tail visible on its own: removing the last rows AND the run_end leaves an open run, indistinguishable from a crash (hence --strict). A no-op on a nil or unchained trail, on a run that wrote no decision (a read-only run leaves the trail untouched), and on a second call.

func (*AuditLog) Record

func (l *AuditLog) Record(a Action, d Decision, reason string) error

Record appends one decision as a JSON line and RETURNS any error so the broker can refuse to perform an unauditable allow. A nil receiver is a no-op (nil err).

func (*AuditLog) WithChain added in v0.206.0

func (l *AuditLog) WithChain(runID string) *AuditLog

WithChain turns on the hash chain for this trail (register SF-08): every row it writes from now on carries run_id, seq and prev_sha256, and EndRun closes the run. Set once at build time, before any row. A nil trail stays nil.

type BrowseFunc added in v0.206.0

type BrowseFunc func(ctx context.Context, in BrowseInput) (string, error)

BrowseFunc runs one browse-lane call and returns the lane's result (or its defer) as JSON text. A door supplies it only when this box configured the lane.

type BrowseInput added in v0.206.0

type BrowseInput struct {
	URL        string
	Goal       string
	MaxActions int
	AllowHosts []string
	Unattended bool
}

BrowseInput is what the browse tool hands the browse lane (ADR 0060): the pipeline's runBrowse behind a door-supplied BrowseFunc. AllowHosts and Unattended come from the BUILD, never from the model: the model picks a URL and a goal inside the envelope the operator set.

type BuildConfig

type BuildConfig struct {
	PlannerBase string        // local model base URL (no /v1); required
	Model       string        // planner model id (must support tool-calling); required
	Timeout     time.Duration // per planner-call timeout; default 180s
	MaxSteps    int           // hard step budget; default 12
	MaxTokens   int           // planner max tokens per call; default 1024
	MaxSameTool int           // per-run cap on calls to any one tool name; 0 => Loop's default (8); <0 => disabled

	ReadRoot string      // directory the agent may read (P0 scope); required
	Offload  OffloadFunc // in-process offload (record=false); nil => no offload tools
	NPU      NPUFunc     // in-process accelerator lane (pipeline.NewLoopNPU); nil => no NPU tools
	Accel    []AccelLane // every accelerator lane in config order (pipeline.NewLoopAccel); when set it supersedes NPU

	// SystemPromptOverride, when set, replaces the capability-aware system prompt
	// (P6 flywheel replay evaluates a CANDIDATE planner prompt). Empty => the normal
	// SystemPrompt. The tool set is still capability-gated as usual, so a read-only
	// build stays side-effect-free regardless of the prompt.
	SystemPromptOverride string

	// Unattended: true => every broker "ask" deny-and-queues (no human in the
	// loop). Also the key the default rule table loads on (see RulesPath): a
	// future caller granting mutating capability WITHOUT setting Unattended
	// gets no default table — set this honestly, not as a UI preference.
	Unattended   bool
	AuditPath    string // append-only broker audit JSONL; must live OUTSIDE the worktree
	AskQueuePath string // P5b: reviewable queue of asks deferred on an unattended run (optional)
	// AuditAdvisory (register SF-02, audit_all_doors=warn): a failed audit write is
	// reported once and never turns an allow into a deny. Ignored on a browse run,
	// whose grant requires an enforcing trail.
	AuditAdvisory bool
	// AuditChain (register SF-08, config audit_chain): hash-chain this run's rows on the
	// trail (run_id, seq, prev_sha256) and close the run with EndAudit.
	AuditChain bool
	// EvidenceReducer (config agent_evidence_reducer) installs the evidence-preserving
	// reducer for build and test results over Offload, the cascade seam. Off by
	// default; with no Offload it cannot be installed and Build says so in Notes.
	EvidenceReducer bool
	// AuditEnforcedByKey (SF-02): the trail is enforcing because audit_all_doors=enforce
	// asked for it; a denial it causes then names the key and the way out.
	AuditEnforcedByKey bool
	// ReadFloor (register SF-07, config agent_read_floor) is the read floor's mode for
	// every read tool: "" or "warn" (the default) records reads of secret material,
	// "enforce" refuses them, "off" checks nothing. --rules off also switches it off.
	ReadFloor string
	// RulesPath names the structural risk table (rules.go LoadRules); tighten-only.
	// Empty on an UNATTENDED run loads the embedded default table
	// (unattendedrules.go); the sentinel RulesOff ("off") explicitly disables it.
	RulesPath string
	// EnvRules is the seat's environment-rule table (core.AgentEnvRules,
	// config `agent_env_rules`; envrules.go, ADR 0036). nil/zero = no hooks.
	// Compiled here so an invalid table fails the build by name at every door
	// (CLI exit, MCP defer, fleet defer) instead of no-op'ing at run time.
	EnvRules *core.AgentEnvRules
	// SetupActions (setup.go, ADR 0036 P2): tool calls replayed before the
	// model's first turn. Already validated at the door (core.Validate);
	// whether a tool exists on this seat is answered by the loop as an
	// observation. nil = no replay.
	SetupActions []core.AgentSetupAction
	// Sampling / SamplingFinal are the seat's decoding policy (sampling.go,
	// register D-95b): the planner policy for tool steps and the optional
	// separate policy for the (thinking-off) final answer. Both nil is the
	// request this client has always sent — temperature 0 and nothing else.
	Sampling      *core.AgentSampling
	SamplingFinal *core.AgentSampling
	// Thinking is the planner think-block policy (thinking.go ThinkingMode);
	// "" = ThinkingAuto. Validated by the caller (core.ValidateThinking /
	// ParseThinkingMode) — an unparseable value fails the build by name.
	Thinking string
	// StreamTokenIDs asks the seat for its per-token progress signal on the
	// streamed planner calls (LLMClient.WithStreamTokenIDs). Set ONLY for a
	// seat this box declares as vLLM: its tool parser holds some tool-call
	// arguments back and the stall watch would otherwise see silence.
	StreamTokenIDs bool

	AllowWrite bool // P2: write_file/delete_file in the worktree
	// WriteLimit caps how many files and bytes ONE run may write (the D-06
	// delegation write door). nil = uncapped, which is what the operator's own
	// CLI worktree has always been; the delegation door always sets one.
	WriteLimit *WriteLimit
	AllowFetch bool // P3: web_fetch behind the egress allowlist
	AllowShell bool // P4.6: run_shell in the LINUX OS cage (granted only on Linux + sandbox.Available)
	AllowRun   bool // C7b: `run` — allowlisted direct-exec runner in the OS sandbox (Linux AND Windows)

	AllowOverwrite bool     // open-write: allow overwrite of existing files in the worktree
	AllowDelete    bool     // open-write: allow delete of files in the worktree
	AllowSearch    bool     // web_search (DuckDuckGo); auto-allowlists the search host
	AllowGitHub    bool     // github_api/create_repo/upload_file; auto-allowlists api.github.com
	GitHubToken    string   // token for the GitHub tools (secret; Authorization header only)
	GitHubRepo     string   // default OWNER/NAME for github_upload_file
	Worktree       string   // RW worktree for write/shell; default = ReadRoot
	EgressHosts    []string // web_fetch allowlist (AllowFetch)

	// AllowBrowse grants the `browse` tool (ADR 0060): drive the operator's own
	// browser through the browse lane. Granted only when Browse is set (the door has
	// a configured lane), an AuditPath exists (every run leaves a trail) and, on an
	// UNATTENDED run, BrowseHosts is non-empty. BrowseTimeout bounds one call (the
	// lane's own timeout plus slack; 0 => 6 minutes).
	AllowBrowse   bool
	BrowseHosts   []string
	Browse        BrowseFunc
	BrowseTimeout time.Duration
	// BrowseAgentDoor marks a grant that came from an agent door (agent_run,
	// agent_delegate, a fleet contract): browse is then judged UNATTENDED — host
	// list required, deny-list never lifted — whatever Unattended says, because
	// no human watches that run's browser.
	BrowseAgentDoor bool

	Memory Memory // optional mem0 layer; nil => no memory
}

BuildConfig declares everything a drive mode needs to construct the agent loop identically. The caller supplies the local planner endpoint, the read scope, an in-process offload closure (record=false — e.g. pipeline.NewRecordlessOffload), and which capabilities are opt-in enabled. Build wires the tools + the single deny→ask→allow broker + the loop the SAME way for every mode (CLI, MCP front door, standalone), so the three modes cannot drift.

type BuildResult

type BuildResult struct {
	Loop          *Loop
	Tools         []Tool
	Policy        *Policy
	Worktree      string // resolved RW worktree (empty if no write/shell/run)
	ShellGranted  bool
	RunGranted    bool
	BrowseGranted bool
	Notes         []string
	// Audit is the run's trail (nil when none is attached); EndAudit closes a chained run.
	Audit *AuditLog
}

BuildResult is the assembled loop plus what was actually granted. ShellGranted is false when --allow-shell was requested but the OS cage is unavailable here (fail-closed); Notes are human-readable capability lines the caller can log.

func Build

func Build(cfg BuildConfig) (*BuildResult, error)

Build assembles the agent loop for any drive mode. It is the SINGLE place the tool set + broker + loop are constructed, so the CLI, the MCP front door, and the standalone runner stay at parity by construction. Operational failures (bad paths, audit-inside-worktree, worktree creation) are returned as errors, never os.Exit — the caller decides how to surface them.

func (*BuildResult) EndAudit added in v0.206.0

func (r *BuildResult) EndAudit()

EndAudit closes the run on a chained trail (SF-08). Doors call it once the run is over; a failure is logged, never fatal: the run already happened, and verify then reports the run open.

type CallRecord added in v0.206.0

type CallRecord struct {
	Step             int    `json:"step"`
	MaxTokens        int    `json:"max_tokens"`
	FinishReason     string `json:"finish_reason,omitempty"`
	CompletionTokens int    `json:"completion_tokens,omitempty"`
	ReasoningTokens  int    `json:"reasoning_tokens,omitempty"`
	ContentChars     int    `json:"content_chars,omitempty"`
	ReasoningChars   int    `json:"reasoning_chars,omitempty"`
	ToolCalls        int    `json:"tool_calls,omitempty"`
	ThinkingOff      bool   `json:"thinking_off,omitempty"`
	ReasoningKey     string `json:"reasoning_key,omitempty"`
	// Sampling is the EFFECTIVE decoding policy of this call (sampling.go):
	// temperature=0 for the default, the operator's policy otherwise. A
	// measurement that cannot prove which sampling ran is not a measurement.
	Sampling string `json:"sampling,omitempty"`
	// ForcedFinal marks the forced final step (D-89): no tools offered, the
	// answer asked for, the final budget.
	ForcedFinal bool `json:"forced_final,omitempty"`
	// Ms (0.115.21, register D-03) is the client-measured wall of this
	// completion — request sent to reply decoded, the compaction retry of the
	// same step included. Backend-independent (vLLM reports no timings); the
	// seat's effective decode rate is derived from it (seatrate.Rate).
	Ms int64 `json:"ms,omitempty"`
}

CallRecord is one planner completion as the corpus keeps it (D-47): the per-call facts a starvation diagnosis needs, without transcript bytes. Every Chat the loop makes — a compaction retry, the thinking-off retry — writes one, on every Result return path.

type CeilingError added in v0.206.0

type CeilingError struct {
	Elapsed time.Duration
	Tokens  int
	TokS    float64
	// Queued is the time the run spent in the busy hold; InHold is whether it
	// was still held when the ceiling passed.
	Queued time.Duration
	InHold bool
}

CeilingError: the run was still producing when the safety ceiling passed. Filed as a BUDGET defer — the sizing signal the delegator learns from — unless the run spent its time held behind other requests' work (ADR 0061): then it was not served, a larger budget would not help, and it is capacity (Held reports it; the pipeline files the class).

func (*CeilingError) Error added in v0.206.0

func (e *CeilingError) Error() string

func (*CeilingError) Held added in v0.206.0

func (e *CeilingError) Held() bool

Held reports that the ceiling found a run that was waiting for the seat, not working: held when the ceiling passed, or held for at least half of its time (the same half-the-wall rule contention.CausedTimeout applies to peer waits).

type ChainBreak added in v0.206.0

type ChainBreak struct {
	RunID   string `json:"run_id"`
	Seq     int    `json:"seq,omitempty"`
	Line    int    `json:"line,omitempty"`
	Problem string `json:"problem"`
}

ChainBreak is one place a run's chain does not hold, named by run and seq, or, for a line that is not a JSON row, by its line number.

type Client

type Client interface {
	Chat(ctx context.Context, msgs []Msg, tools []ToolSpec, maxTokens int) (Completion, error)
}

Client is the minimal OpenAI-compatible tool-calling chat interface the loop needs. A concrete implementation targets llama-swap / NIM; tests use a fake.

type CompiledEnvRules added in v0.206.0

type CompiledEnvRules struct {
	// contains filtered or unexported fields
}

CompiledEnvRules is core.AgentEnvRules compiled: regexps built once, lookups indexed. Immutable after CompileEnvRules.

func (*CompiledEnvRules) DeniedTools added in v0.206.0

func (c *CompiledEnvRules) DeniedTools(available []string) []string

DeniedTools applies deny_tools and allow_tools to the registered set: denied wins, allow (when set) keeps only the listed names. Names the loop never registered are ignored — an env table can never add a tool.

func (*CompiledEnvRules) FilterAction added in v0.206.0

func (c *CompiledEnvRules) FilterAction(st *EnvRuleState, a EnvAction) (EnvAction, *EnvBlocked, []EnvRuleHit)

FilterAction blocks a call over its per-tool executed cap, else clamps its numeric arguments to arg_limits. Both are recorded as hits; a clamp keeps the call running with the rewritten args.

func (*CompiledEnvRules) FilterObservation added in v0.206.0

func (c *CompiledEnvRules) FilterObservation(a EnvAction, o EnvObservation) (EnvObservation, []EnvRuleHit)

FilterObservation strips every observation_strip pattern, then bounds the result to max_observation_tokens (head+tail with the loop's elision marker). Strip runs first so a banner does not eat the budget the cap protects.

func (*CompiledEnvRules) ModifyTransition added in v0.206.0

func (c *CompiledEnvRules) ModifyTransition(a EnvAction, o EnvObservation) (EnvObservation, []EnvRuleHit)

ModifyTransition rewrites an ERRORED result whose text matches a rewrite_error pattern into the operator's short line; first match wins. Non-error observations pass untouched.

func (*CompiledEnvRules) Source added in v0.206.0

func (c *CompiledEnvRules) Source() core.AgentEnvRules

Source returns the table this was compiled from (for notes and status).

type Completion

type Completion struct {
	// FirstDeltaMS (0.131.1) is the time from the request being sent to the
	// first streamed delta — the engine-neutral PREFILL measurement (llama.cpp
	// reports prompt_ms in timings; vLLM reports nothing). With the prompt's
	// uncached token count it yields the seat's prefill_tok_s. 0 = not observed.
	FirstDeltaMS float64
	// Serve is the SERVER's accounting for this completion (KV reuse, real
	// token counts, prefill/decode ms) when the backend reports it — nil when
	// it does not. Purely observational: the loop never reads it; the Phase D
	// measurement leg does (ADR 0017).
	Serve        *ServeStats
	Msg          Msg
	FinishReason string
	// Reasoning is the seat's HIDDEN channel for this turn (vLLM `reasoning`,
	// llama.cpp `reasoning_content`), kept apart from the visible content so an
	// empty answer can be told from a starved one (thinking.go). ReasoningKey
	// names the wire key it arrived under ("" = none). ThinkingOff records
	// that this call was rendered in non-thinking mode.
	Reasoning    string
	ReasoningKey string
	ThinkingOff  bool
}

Completion is one model turn: the assistant message plus the finish reason ("tool_calls" => the loop must execute tools and continue; anything else => the loop stops).

func (Completion) Starvation added in v0.206.0

func (c Completion) Starvation(maxTokens int) (kind, basis string, ok bool)

Starvation classifies a completion that carries NO tool calls and NO visible content. kind is StopReasoningStarved when the budget went to hidden reasoning, StopEmpty when the seat simply closed with nothing; basis is the one-line evidence. ok=false when the completion is not empty at all. maxTokens is the budget the call was sent with: a completion that used all of it was cut by the budget whatever finish reason the engine reported (cutByBudget); 0 = unknown, and then only finish "length" counts.

type Decision

type Decision string

Decision is the broker's verdict on a mutating action.

const (
	Allow Decision = "allow" // perform it
	Ask   Decision = "ask"   // needs human approval (unattended => deny-and-queue)
	Deny  Decision = "deny"  // never perform
)
const Warn Decision = "warn"

Warn is the audit-trail decision of a read the floor would deny under enforce but lets through under warn. It is a record, never a verdict a tool acts on.

type DoorAuditPlan added in v0.206.0

type DoorAuditPlan struct {
	Path     string
	Advisory bool
	Refuse   string
	Note     string
	// Enforced: the trail is enforcing because audit_all_doors=enforce asked for it
	// (not a browse grant), so a denial it causes names the key and the way out.
	Enforced bool
}

DoorAuditPlan is what an agent door hands Build for the broker audit trail (register SF-02, config key audit_all_doors).

  • Path: the trail to attach ("" = none, today's behaviour for a run without browse).
  • Advisory: warn mode; a failed write is reported once and never turns an allow into a deny (see Policy.WithAuditAdvisory).
  • Refuse: the door must not run; the reason names the key and the fix.
  • Note: a run that proceeds without the trail the mode asked for says why.

func DoorAudit added in v0.206.0

func DoorAudit(mode string, allowBrowse bool, base string) DoorAuditPlan

DoorAudit maps an audit_all_doors mode onto the trail one agent door attaches; base is the harness install root (config `home`), under which the trail lives ("" = the user home). "" and "off" keep today's behaviour exactly: no trail unless browse asks for one. "warn" attaches an advisory trail; "enforce" an enforcing one (an audit write failure denies the action, as a browse run's trail always has). A browse run keeps its enforcing trail in every mode, because its grant requires one (ADR 0060). An unknown mode refuses the run rather than guessing which record the operator meant.

type EffectRecord added in v0.206.0

type EffectRecord struct {
	Step   int          `json:"step"`
	CallID string       `json:"call_id,omitempty"`
	Tool   string       `json:"tool"`
	Status EffectStatus `json:"status"`
	// Note carries the WHY for non-committed statuses (budget exceeded,
	// refusal class, unknown tool) so the record is auditable without the
	// transcript. Empty for committed.
	Note string `json:"note,omitempty"`
	// Risk is the model's own security_risk annotation on the call ("" when
	// not provided) — recorded for every fate so the flywheel can correlate
	// self-assessed risk with actual outcomes.
	Risk string `json:"risk,omitempty"`
	// ObsChars is the size of the result the MODEL saw for this call, after
	// every environment rule and the loop-boundary cap — the "long
	// observation" axis the rigger diagnoses on (ADR 0036). 0 for a call that
	// produced no bytes.
	ObsChars int `json:"obs_chars,omitempty"`
	// Rule names the environment rule that fired on this call, if any (the
	// last one when several did; RuleHits on the Result has them all).
	Rule string `json:"rule,omitempty"`
	// Setup marks a call replayed from the contract's setup_actions before
	// the model's first turn (Step 0): it ran through the same rules, dispatch
	// and observation hooks as a model call, but the model never issued it.
	Setup bool `json:"setup,omitempty"`
}

EffectRecord is one tool call's execution accounting, in call order.

type EffectStatus added in v0.206.0

type EffectStatus string

EffectStatus classifies what one tool call did to the world.

const (
	// EffectCommitted — the tool ran to completion and returned success. Its
	// effects (if any) are whatever the tool's contract says a success does.
	EffectCommitted EffectStatus = "committed"
	// EffectFailed — the tool ran to completion and returned an error. Effects
	// up to the failure point may exist; the tool got the chance to clean up.
	EffectFailed EffectStatus = "failed"
	// EffectUnknown — the call was STARTED but the loop stopped waiting
	// (per-tool budget exceeded, or the run was cancelled mid-call). The
	// goroutine may still be running; effects are genuinely unknown. Unknown,
	// never none: this is the one status it is dangerous to soften.
	EffectUnknown EffectStatus = "unknown"
	// EffectNone — the call was never executed: unknown tool name, or a
	// circuit-breaker refusal (exact repeat, name cap, disabled tool). The
	// world is untouched by this call.
	EffectNone EffectStatus = "none"
)

type EngineProbe added in v0.206.0

type EngineProbe func(ctx context.Context) (EngineReading, error)

EngineProbe reads the seat's engine. A non-nil error means "cannot tell".

type EngineReading added in v0.206.0

type EngineReading struct {
	// Loading: llama-swap is loading (or evicting) the seat — the cold-load
	// hold's evidence, with State its words for it.
	Loading bool
	State   string
	// Fingerprint changes whenever the engine takes a step for any request;
	// "" = it could not be formed (the seat is not loaded, or no source).
	Fingerprint string
	// TokenFingerprint changes only when the engine PRODUCES tokens (generated
	// or prompt tokens credited, a slot's decoded / prompt-processed counts).
	// "" = the source has no production counter (the token bound is off).
	TokenFingerprint string
	// Summary is one clause for reasons and status ("vllm-metrics: 4
	// running, 0 waiting, 29 preemptions so far").
	Summary string
	// NotLoaded (ADR 0066): llama-swap does not list the seat at all — its
	// engine is gone (crashed, stopped) and nothing is loading it. A reading of
	// nothing, never "idle": with Loading false and no Fingerprint it is what the
	// seat's absence looks like from here.
	NotLoaded bool
	// Refused (ADR 0066): the engine's own address refused the connection while
	// llama-swap still listed the seat — nothing is listening, the engine
	// process is gone. Set only for a LOCAL seat address; a seat behind another
	// machine's llama-swap that this box cannot reach is unreadable, not down.
	Refused bool
	// Running and Waiting are the engine's own request gauges (vLLM running and
	// waiting; llama-server processing and deferred). Waiting is -1 when the
	// source cannot see a queue. 0/0 with no Fingerprint = not read.
	Running, Waiting int
	// PrefillBlind (ADR 0066): the source cannot see a prefill in progress, so an
	// engine that is prefilling reads flat (llama-server /slots without --metrics;
	// vLLM without a KV-usage gauge). Only such an engine keeps the waiting
	// phase's allowance, stretched by the load, inside the flat bound: a source
	// that moves its fingerprint through a prefill needs no stretch, because a
	// fingerprint that does not move is then a hung engine whatever else is queued.
	PrefillBlind bool
}

EngineReading is one look at the seat's engine.

func (EngineReading) Load added in v0.206.0

func (r EngineReading) Load() int

Load is how many requests share the engine right now: running plus waiting (a queue the source cannot see counts as none). 0 = not read.

type EnvAction added in v0.206.0

type EnvAction struct {
	Step   int
	CallID string
	Tool   string
	Args   string // raw JSON arguments; a rewrite replaces this
}

EnvAction is one requested tool call as the hooks see it.

type EnvBlocked added in v0.206.0

type EnvBlocked struct {
	Rule     string
	Reason   string
	Withhold bool
}

EnvBlocked is a filter_action veto: the call never executes and Reason is what the model reads as the (is_error) result. Withhold asks the loop to also stop OFFERING the tool for the rest of the run (structural, like the same-name breaker): a weak model does not reliably read a text refusal, and a capped tool it keeps re-calling would otherwise burn the step budget on blocked calls — the very "budget" failure class this exists to diagnose.

type EnvObservation added in v0.206.0

type EnvObservation struct {
	Content string
	IsError bool
}

EnvObservation is one tool result before it enters the transcript.

type EnvRuleHit added in v0.206.0

type EnvRuleHit struct {
	Step   int    `json:"step"`
	Tool   string `json:"tool"`
	Rule   string `json:"rule"`   // vocabulary key: max_calls_per_tool, arg_limits, rewrite_error, observation_strip, max_observation_tokens
	Effect string `json:"effect"` // blocked | rewrote_args | rewrote_error | stripped | truncated
	Note   string `json:"note,omitempty"`
}

EnvRuleHit records one rule firing — the telemetry the rigger reads.

type EnvRuleState added in v0.206.0

type EnvRuleState struct {
	// contains filtered or unexported fields
}

EnvRuleState is the per-run mutable state the hooks may keep: how many times each tool has EXECUTED (blocked calls do not count — a blocked call changed nothing, and counting it would make a fixated model exhaust a cap it never spent).

func NewEnvRuleState added in v0.206.0

func NewEnvRuleState() *EnvRuleState

NewEnvRuleState returns fresh per-run state.

func (*EnvRuleState) Executed added in v0.206.0

func (s *EnvRuleState) Executed(tool string)

Executed records that tool ran once (Run calls it after a non-blocked dispatch).

type EnvRules added in v0.206.0

type EnvRules interface {
	DeniedTools(available []string) []string
	FilterAction(st *EnvRuleState, a EnvAction) (EnvAction, *EnvBlocked, []EnvRuleHit)
	ModifyTransition(a EnvAction, o EnvObservation) (EnvObservation, []EnvRuleHit)
	FilterObservation(a EnvAction, o EnvObservation) (EnvObservation, []EnvRuleHit)
}

EnvRules is the interceptor interface. DeniedTools is the STATIC half of filter_action: it decides which tool specs are withheld from the model for the whole run (structural, like disabledTools), given the tools the loop actually registered. Every method must be safe for concurrent use; per-run mutable state travels in *EnvRuleState.

func CompileEnvRules added in v0.206.0

func CompileEnvRules(r *core.AgentEnvRules) (EnvRules, error)

CompileEnvRules validates and compiles a table. A nil or zero table compiles to a nil INTERFACE (no rules) so `loop.WithEnvRules(compiled)` is safe without a guard — returning a typed nil pointer here would pass WithEnvRules's nil check and panic on the first call.

type FallbackReason added in v0.21.1

type FallbackReason string

FallbackReason records which path RunTwoTier actually took, so the caller can log it. FallbackNone means the two-tier plan-then-execute path ran; the others mean the architect produced nothing usable and RunTwoTier fell back to a single-model run of the ORIGINAL objective on the editor loop.

const (
	// FallbackNone: the architect produced a usable plan and the editor executed it.
	FallbackNone FallbackReason = ""
	// FallbackDegeneratePlan: the architect returned an empty/degenerate plan
	// (nothing to hand off), so the editor ran the original objective directly.
	FallbackDegeneratePlan FallbackReason = "degenerate-plan"
	// FallbackArchitectError: the architect run errored, so the editor ran the
	// original objective directly.
	FallbackArchitectError FallbackReason = "architect-error"
)

type KVSlotPolicy added in v0.209.0

type KVSlotPolicy struct {
	MinTokens       int
	ToolWaitSaveSec int
}

KVSlotPolicy is the loop's side of the retention: how large a prompt is worth a file (a file is ~80 KB per token) and how long a tool call must be allowed to run before a save is taken around it.

func DefaultKVSlotPolicy added in v0.209.0

func DefaultKVSlotPolicy() KVSlotPolicy

DefaultKVSlotPolicy is the policy a node runs unless told otherwise: 1024 tokens and a 240 s tool cap (the browse tool's 360 s cap is past the 300 s idle unload, run_shell's 120 s is not).

type KVSlotReport added in v0.209.0

type KVSlotReport struct {
	// Restore is the run-start restore, judged on the next completion: "hit", "miss" or "skip:<reason>". Empty when
	// none was attempted (no file for the key yet, or the prompt was under the policy's floor).
	Restore        string `json:"restore,omitempty"`
	RestoredTokens int    `json:"restored_tokens,omitempty"`
	RestoreMS      int64  `json:"restore_ms,omitempty"`
	// Admit is the presence-admission verdict for the run-start key when nothing was restored: "below-min-tokens",
	// "first-sighting" (marked seen), "repeat-saved" or "repeat-save-skip:<reason>".
	Admit            string `json:"admit,omitempty"`
	Saves            int    `json:"saves,omitempty"`
	SavedBytes       int64  `json:"saved_bytes,omitempty"`
	ToolWaitSaves    int    `json:"toolwait_saves,omitempty"`
	ToolWaitRestores int    `json:"toolwait_restores,omitempty"`
	ToolWaitHits     int    `json:"toolwait_hits,omitempty"`
}

KVSlotReport is what the retention did for one run. Present on the Result only when a store was attached.

type KVSlotResult added in v0.209.0

type KVSlotResult struct {
	OK     bool
	Tokens int
	Bytes  int64
	Ms     int64
	Reason string
}

KVSlotResult is the answer of one save or restore. OK means tokens moved; otherwise Reason says why not ("miss", "seat-cold", "unsupported", "shape-mismatch", an error text), and the loop records it as a skip.

type KVSlotStore added in v0.209.0

type KVSlotStore interface {
	// Base is the identity every key is hashed over: the seat's config pin (taken once, at attach time) and the model id.
	Base() string
	// Save writes slot 0 under key; Restore reads it back. Each bounds itself.
	Save(ctx context.Context, key string) KVSlotResult
	Restore(ctx context.Context, key string) KVSlotResult
	// FileExists is whether a slot file for key is on disk; Delete removes it.
	FileExists(key string) bool
	Delete(key string)
	// Rewarm loads the seat through the normal warm path when it is no longer loaded, and reports whether it had to.
	Rewarm(ctx context.Context) (rewarmed bool)
	// Seen is the presence tracker (process-level, bounded): it reports whether key was already seen on this node
	// and marks it seen. A key is saved on its SECOND sighting and restored from the third.
	Seen(key string) bool
}

KVSlotStore is what the loop needs from the node: slot 0 of the run's seat saved to and restored from files keyed by the loop's own hashes.

type LLMClient

type LLMClient struct {
	// contains filtered or unexported fields
}

LLMClient is the concrete OpenAI-compatible tool-calling Client. It targets any /v1/chat/completions endpoint — llama-swap (:11436, keyless) by default, or an NIM endpoint (apiKey set) for the hybrid "ask" escalation. One type, base_url swap. It implements the agent.Client interface.

func NewLLMClient

func NewLLMClient(base, model, apiKey string, timeout time.Duration) *LLMClient

NewLLMClient builds a client. base is the server ROOT, with or without the trailing /v1 — swapclient.BaseURL is the one normalisation rule in the harness and this client goes through it like every other reader of an `endpoint` does. apiKey "" => no Authorization header (local).

Register S-37: it used to trim only a trailing slash and then append "/v1/chat/completions", so a base written as "http://x/v1" — the shape `nim_endpoint` documents, and the shape an operator copies off a vLLM seat's own docs — dialled "/v1/v1/chat/completions". Normalising here rather than at the ~60 construction sites means no caller can reintroduce it; it also keys the modelaffinity ticket on the normalised base, so two clients spelling one endpoint two ways contend on the same gate instead of two.

func (*LLMClient) Chat

func (c *LLMClient) Chat(ctx context.Context, msgs []Msg, tools []ToolSpec, maxTokens int) (Completion, error)

Chat sends the running transcript + tool specs and returns the next completion.

func (*LLMClient) WithStreamTokenIDs added in v0.206.0

func (c *LLMClient) WithStreamTokenIDs(on bool) *LLMClient

WithStreamTokenIDs turns on the engine's per-token progress signal for streamed calls that carry a ProgressFunc (0.140.1). vLLM's parser HOLDS output while the model writes some tool-call arguments — a trailing non-string parameter (an object, an array, a number) until it closes, a call to a name the request did not offer for its whole length — and sends no frame at all meanwhile: measured on the 3-card seat, an offload_extract call with a 40-property `schema` streamed nothing for 62.8 s while the engine generated 1,460 tokens, which the liveness floor (60 s) files as a stall. With `return_token_ids` the same engine sends one frame per engine step carrying the generated ids even when the parser emits no delta (max gap under 0.05 s on the same call), and those ids are exactly the progress the stall watch needs. Only a vLLM seat is asked: other OpenAI-compatible servers may reject an unknown key, and llama.cpp streams its own partial tool-call arguments.

type Loop

type Loop struct {
	// contains filtered or unexported fields
}

Loop runs the canonical agent loop over a fixed tool set.

func NewLoop

func NewLoop(c Client, tools []Tool, maxSteps int) *Loop

NewLoop builds a loop. maxSteps is the hard budget guard (owned in code, not the prompt). A non-positive maxSteps defaults to 1.

func (*Loop) AdvertisedTools added in v0.206.0

func (l *Loop) AdvertisedTools() []string

WithProfile applies a per-task Profile (Task C6): it NARROWS the advertised tools to the INTERSECTION of p.Tools with what is already enabled, optionally overrides the system prompt, and stores the profile's few-shot exemplars for injection in Run. SAFETY INVARIANT: a profile can only narrow — it can NEVER grant a tool the capability flags didn't enable (a name in p.Tools that is not already present is silently ignored), so selecting a profile can never widen the agent's power beyond what --allow-* granted. An empty p.Tools (the "general" default) leaves the tool set untouched. Safe to call after NewLoop and WithWorktree (call it AFTER so a worktree-registered tool like update_plan is present to be kept). AdvertisedTools returns the tool names this loop will actually advertise to the planner, AFTER any profile narrowing. Report this rather than the pre-narrowing BuildResult.Tools snapshot: WithProfile replaces l.specs with a fresh container, so that snapshot never reflects the narrowing and a run that advertises 3 tools would otherwise be reported as advertising 11.

func (*Loop) EnvRulesDenied added in v0.206.0

func (l *Loop) EnvRulesDenied(before []string) []string

EnvRulesDenied reports which registered tools the installed env rules withheld — for builder notes and status.

func (*Loop) ResetRunInstruments added in v0.206.0

func (l *Loop) ResetRunInstruments()

ResetRunInstruments starts the Loop's per-run instruments (the pager gate, the compaction pass count and the prefill accounting) over, so the next Run's report covers that run alone.

Those instruments live on the Loop and accumulate for its whole life, which is right for a Loop built for one run (the agent door builds one per request) and wrong for a Loop that drains a queue: the second goal's report would be the sum of both, and a corpus pooling the per-goal traces would count the first goal twice. The standalone drainer calls this before each goal.

Call it only between runs on a Loop used serially. A Loop shared by concurrent Runs (--serve) keeps one set of accumulators for all of them by design, and a reset there would wipe a run that is still in flight.

func (*Loop) Run

func (l *Loop) Run(ctx context.Context, objective string) (Result, error)

Run executes the loop for objective until the model stops, the step budget is exhausted, or the context is cancelled. It also ends the run, with a *RootGoneError and a Result whose StopReason is "error", when a tool cannot open the workspace root (register C-79): the seat is not given another turn to answer from nothing.

func (*Loop) WithBatchJudge added in v0.206.0

func (l *Loop) WithBatchJudge(on bool) *Loop

WithBatchJudge enables the end-of-run advisory pass. OFF by default; the caller opts in (agent_run judge=true).

func (*Loop) WithContextTokens added in v0.21.1

func (l *Loop) WithContextTokens(n int) *Loop

WithContextTokens sets the model context window (in tokens) that transcript compaction budgets against. Default is defaultCtxTokens (8192, matching the shipped serving templates). A non-positive value is ignored. The derived INPUT budget is ctxTokens - maxTokens - compactionMargin (see inputBudget).

func (*Loop) WithCutFinalReissue added in v0.206.0

func (l *Loop) WithCutFinalReissue(instruction string, minTurn time.Duration) *Loop

WithCutFinalReissue arms the list-cap re-issue of a final answer cut at the completion budget (register D-95): instruction is derived from the contract's output_schema and minTurn is what one more final turn costs on this seat. An empty instruction disarms it — a schemaless contract has no list to cap.

func (*Loop) WithEnvRules added in v0.206.0

func (l *Loop) WithEnvRules(r EnvRules) *Loop

WithEnvRules installs the environment-rule interceptors. Denied tools are removed from the offered specs AND the executable set right here (the narrow-only invariant, same as WithProfile), so a denied name is never advertised and a call to it lands as "unknown tool". nil clears the hooks. Call it AFTER WithProfile: a profile narrows first, env rules narrow again.

func (*Loop) WithEvidenceReducer added in v0.206.0

func (l *Loop) WithEvidenceReducer(offload OffloadFunc) *Loop

WithEvidenceReducer installs the evidence-preserving reducer over the cascade seam the loop's offload tools already use (pipeline's recordless offload: one named tier, no ledger row, no new client). nil = off, the default.

func (*Loop) WithFinalBudgetFit added in v0.206.0

func (l *Loop) WithFinalBudgetFit(fn func(configured int, remaining time.Duration) (int, string)) *Loop

WithFinalBudgetFit installs the wall fit for the final answer's completion budget (register D-95). fn is called with the CONFIGURED budget (finalMaxTokens — its ceiling) and the wall that is left, and returns the budget to run at plus the one-line arithmetic to publish; returning the configured budget, or 0, leaves the run exactly as it was. Installed by the node, which is the only caller that knows the seat's measured rate.

func (*Loop) WithGCFCompact added in v0.206.0

func (l *Loop) WithGCFCompact(on bool) *Loop

WithGCFCompact enables the LOSSLESS GCF rung of the compaction ladder: over budget, older tool bodies that are eligible JSON arrays are re-encoded columnar (internal/gcf, round-trip proven) before any lossy rung runs. The Loop's zero value leaves it off; every production caller defaults it ON since the measured flip decision (ADR 0015).

func (*Loop) WithKVSlots added in v0.209.0

func (l *Loop) WithKVSlots(store KVSlotStore, pol KVSlotPolicy) *Loop

WithKVSlots attaches the retention. A nil store leaves the loop exactly as it was.

func (*Loop) WithLiveness added in v0.206.0

func (l *Loop) WithLiveness(m *Monitor) *Loop

WithLiveness installs the run's stall/ceiling watch (0.131.0). nil = none: the loop then runs under whatever deadline its context carries, as before.

func (*Loop) WithMaxSameTool added in v0.21.1

func (l *Loop) WithMaxSameTool(n int) *Loop

func (*Loop) WithMaxTokens

func (l *Loop) WithMaxTokens(n int) *Loop

func (*Loop) WithMemory

func (l *Loop) WithMemory(m Memory) *Loop

WithMemory attaches a memory layer: the loop recalls relevant context before planning and persists the run outcome when it finishes. nil = no memory.

func (*Loop) WithObserver added in v0.206.0

func (l *Loop) WithObserver(o RunObserver) *Loop

WithObserver installs a RunObserver. nil = none.

func (*Loop) WithParkHighRisk added in v0.206.0

func (l *Loop) WithParkHighRisk(on bool) *Loop

WithParkHighRisk enables unattended parking: a call to a ParkOnHighRisk tool that self-flags security_risk=high is refused (ledgered none, note "parked") instead of executed — there is no human to ask, so high-risk defers to the morning review. OFF by default; the builder enables it for unattended runs. The OpenHands-pattern half of the reshaped judge: the annotation is free (rides the tool call itself, no extra model call, no seat swap) and it can only tighten. An OMITTED annotation is no signal — weak models omit the field routinely, and parking everything unannotated would kill open-write runs — so omission proceeds under the broker exactly as before.

func (*Loop) WithParkRecorder added in v0.206.0

func (l *Loop) WithParkRecorder(f func(tool, args, risk string)) *Loop

WithParkRecorder attaches a durable record hook for parked calls — the builder wires it to the ask queue, so "PARKED for operator review" is a promise the plumbing keeps (review finding #3: without it, a parked call's only trace was the ephemeral response JSON). nil = ledger only.

func (*Loop) WithProfile added in v0.21.1

func (l *Loop) WithProfile(p Profile) *Loop

func (*Loop) WithReadBudgetChars added in v0.206.0

func (l *Loop) WithReadBudgetChars(n int) *Loop

WithReadBudgetChars sets the read_file character budget of a run explicitly (see readBudgetChars for the default). A non-positive value restores the derived default; it never turns the budget off, WithoutReadBudget does.

func (*Loop) WithSampling added in v0.206.0

func (l *Loop) WithSampling(planner, final *Sampling) *Loop

WithSampling installs the seat's decoding policy: planner for every tool step, final for the answer turn and its re-issues. A nil final falls back to the planner policy; both nil is today's behaviour exactly.

func (*Loop) WithSetupActions added in v0.206.0

func (l *Loop) WithSetupActions(actions []core.AgentSetupAction) *Loop

WithSetupActions installs the replay list. nil/empty = no replay, and the loop is byte-identical to a loop that never had the option.

func (*Loop) WithSkeletonPrune added in v0.206.0

func (l *Loop) WithSkeletonPrune(on bool) *Loop

WithSkeletonPrune enables the skeleton rung of the compaction ladder: when the transcript is over budget, older tool bodies are first reduced to signal-preserving skeletons (see skeleton.go) before the bare-marker and whole-turn-drop rungs run. The Loop's zero value leaves it off; every production caller defaults it ON since the measured flip decision (ADR 0015) — with it off, compaction behaves as before this rung existed.

func (*Loop) WithSystem

func (l *Loop) WithSystem(s string) *Loop

WithSystem sets an optional system prompt. WithMaxTokens overrides the per-call completion cap.

func (*Loop) WithThinking added in v0.206.0

func (l *Loop) WithThinking(m ThinkingMode) *Loop

WithThinking sets the planner think-block policy (thinking.go). An empty mode is ThinkingAuto; the caller validates with ParseThinkingMode first.

func (*Loop) WithTokenCalibration added in v0.206.0

func (l *Loop) WithTokenCalibration(on bool) *Loop

WithTokenCalibration enables budget correction from the server's own token counts (ADR 0017). It is **OFF by default**, and that default is measured, not cautious:

  • The estimator really does undercount (density ~1.3-1.4 plus a fixed ~900-token payload, fitted live on real goals), so with a SMALL output reservation the raw budget lets requests through that the server rejects. That is the regime the defect was found in (--max-out 1024 ⇒ budget 6656).
  • But the shipped agent reserves --max-tokens 4096 of the 8192 window, so the input budget is 3584 and roughly 3,700 tokens of slack already absorb the estimator's error. Re-measured at that real default, the ladder fires on its own and compaction prevents an overflow WITHOUT calibration.
  • And calibration is not free: on a live A/B over dense multi-file goals it cut retained tool content by 52% (10,060 → 4,857 chars) and turned a correct answer ("275 lines") into a wrong one ("1 line"). Neither arm hit a server rejection, so that quality was spent defending against a risk that did not materialise at shipped defaults.

Enable it where the output reservation is small relative to the window, or where overflow rejections are actually observed. Leave it off otherwise.

func (*Loop) WithTokenizer added in v0.206.0

func (l *Loop) WithTokenizer(t Tokenizer) *Loop

WithTokenizer attaches the served model's real tokenizer (internal/tokclient pointed at the planner endpoint+model) and thereby switches the ladder's drop rung to the token-exact middle cut (TO-4, cutmiddle.go). nil leaves the legacy estimate-driven rung — the correct configuration for a backend with no /tokenize route. The tokenizer is wrapped sticky here: after one failure every later step skips straight to the legacy rung (fail-open, no per-step network stall), atomically, since --serve shares one *Loop across handlers.

func (*Loop) WithToolResultCap added in v0.21.1

func (l *Loop) WithToolResultCap(n int) *Loop

WithToolResultCap overrides the per-result character cap applied when a tool's output becomes a transcript Msg (see toolResultCapChars). A non-positive value resets to the window-derived default. Use a large value only in tests that need to observe an uncapped result.

func (*Loop) WithToolTimeout added in v0.206.0

func (l *Loop) WithToolTimeout(d time.Duration) *Loop

WithToolTimeout overrides the per-tool-call cap (see defaultToolTimeout). A non-positive value DISABLES capping — only for tests that need to observe an unbounded tool.

func (*Loop) WithWorktree added in v0.21.1

func (l *Loop) WithWorktree(root string) *Loop

WithWorktree gives the loop durable per-workspace working memory rooted at root (Task C5): it loads <root>/AGENT.md once at Run start (fenced as untrusted data), registers the update_plan tool (writes <root>/.agent/plan.md, os.Root-confined), and re-injects the plan on a cadence. An empty root leaves all of that off. Registration of update_plan happens here so the tool appears in the advertised spec set. Safe to call after NewLoop.

func (*Loop) WithoutExemplars added in v0.206.0

func (l *Loop) WithoutExemplars() *Loop

WithMaxSameTool overrides the per-run same-tool call cap (see defaultMaxSameTool). n<=0 disables the cap (unlimited) — use only for tests that specifically need to observe unthrottled repeats. WithoutExemplars drops the profile's few-shot messages for this run. Document- grounded contracts (a goal plus attached context docs — every research digest, most delegate fan-outs) need no tool-call demonstration: the answer is in the file, and on a 4B seat ANY exemplar user turn competes with the objective — measured 2026-09-03 on <node-c>: with the closed, marked, synthetic exemplars of 0.113.1 a digest still answered the exemplar's topic ("does not describe any maintenance windows") for a goal about eviction policies. Call it after WithProfile (WithProfile re-installs the profile's exemplars).

func (*Loop) WithoutForcedFinal added in v0.206.0

func (l *Loop) WithoutForcedFinal() *Loop

WithoutForcedFinal turns the forced final step off (D-89): the last step then offers every tool like any other, and a seat that keeps calling tools ends on `budget` with no answer — the pre-0.115.19 loop. For tests whose subject is another breaker, and for an effect-only run whose last step is meant to be a tool call.

func (*Loop) WithoutReadBudget added in v0.206.0

func (l *Loop) WithoutReadBudget() *Loop

WithoutReadBudget turns the read budget off: every read_file call then counts against the same-name cap, which is the loop as it was before D-103. For tests whose subject is the call count, and the one-line rollback.

type Memory

type Memory interface {
	Recall(ctx context.Context, query string, limit int) ([]Recalled, error)
	Persist(ctx context.Context, text string, meta map[string]string) (string, error)
}

Memory is the loop's optional memory layer: recall relevant context before planning, persist a run outcome after. nil => the loop runs without memory.

type MemoryClient

type MemoryClient struct {
	// contains filtered or unexported fields
}

MemoryClient talks to the mem0 REST server (the agentic-memory system). It is WRITE-ISOLATED by construction: it recalls across readUsers (the agent's own namespace for run-to-run continuity, plus an optional operator/shared namespace for the operator's own knowledge) but only ever WRITES under writeUser, and only at the "evidence" tier — the mem0 server independently rejects any attempt to write the canonical tier (403), so the agent cannot pollute the canonical anchor.

func NewMemoryClient

func NewMemoryClient(base, apiKey string, readUsers []string, writeUser, agentID string, timeout time.Duration) *MemoryClient

NewMemoryClient builds a client. readUsers are the namespaces to recall from; writeUser is the (isolated) namespace to persist to. A trailing slash on base is trimmed.

func (*MemoryClient) Persist

func (c *MemoryClient) Persist(ctx context.Context, text string, meta map[string]string) (string, error)

Persist writes text as an EVIDENCE-tier memory under the isolated writeUser namespace, tagged source=local-agent. It NEVER sends tier=canonical (the server would 403 anyway) — the agent cannot reach the canonical anchor.

func (*MemoryClient) Recall

func (c *MemoryClient) Recall(ctx context.Context, query string, limit int) ([]Recalled, error)

Recall searches each readUser namespace CONCURRENTLY under one short deadline and returns the merged, score-sorted, de-duplicated top-`limit` memories. A per-namespace error is tolerated (that namespace contributes nothing); a total failure returns the last error with whatever was gathered — the caller treats an empty recall as "no memory". Concurrency + the deadline mean a single slow/ wedged namespace can't stall planning.

type Monitor added in v0.206.0

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor owns a run's liveness: a stall timer reset by progress and a ceiling deadline over the parent context. It cancels the context it hands out with a typed cause (context.Cause) so the caller can file the right defer class without guessing from the clock.

func NewMonitor added in v0.206.0

func NewMonitor(parent context.Context, pol StallPolicy, ceiling time.Duration) (context.Context, *Monitor)

NewMonitor wraps parent with a ceiling deadline and a stall watch. The returned context's Deadline() is the ceiling, so every existing reader of ctx.Deadline() (the re-pack floor, the seat-wait budget) keeps working; a stall cancels it early with a *StallError cause. The watch starts in PhaseAdmission. Stop it when the run ends (a deferred Stop, like a deferred cancel).

func (*Monitor) AwaitSeat added in v0.206.0

func (m *Monitor) AwaitSeat(ctx context.Context, sd *SeatDownError) error

AwaitSeat holds the run while its seat is down, under the cold-load hold: it returns nil when the failed step may be re-issued, and the typed give-up (also the run's cause, its context cancelled) when the seat did not come back inside the cold-load ceiling counted from the episode's first verdict, when the seat came back and went down again under the re-issued step, when the run's recoveries are spent, or when there is nothing to wait with (no engine probe or no ceiling). The loop calls it with the verdict the monitor cancelled the call with, or with the one ConfirmSeatDown (or the chat client) made.

A re-issue onto a seat nobody lists is a start attempt, and one that fails is the same episode: the next call waits one poll, then triggers again, until the bound. Only a seat that was SEEN serving earns exactly one re-issue.

func (*Monitor) Cause added in v0.206.0

func (m *Monitor) Cause() error

Cause is why the monitor cancelled: nil (it did not — the parent did, or the run finished), *StallError or *CeilingError.

func (*Monitor) ConfirmSeatDown added in v0.206.0

func (m *Monitor) ConfirmSeatDown(ctx context.Context, cause error) *SeatDownError

ConfirmSeatDown reads the seat after a model call failed like a dead seat (seatFailure) and returns the typed verdict when llama-swap confirms it: nil when the seat reads ready and readable, when it cannot be read, when the monitor has no engine probe, or when the run itself is over.

func (*Monitor) CurrentPhase added in v0.206.0

func (m *Monitor) CurrentPhase() Phase

CurrentPhase is the liveness phase the run is in.

func (*Monitor) MarkSeatLoaded added in v0.206.0

func (m *Monitor) MarkSeatLoaded()

MarkSeatLoaded tells the monitor the seat was just loaded for this run (the admission warm-up loaded it and read it ready). Until the seat's first byte, silence while a request waits is held under the short post-ready bound instead of the prefill clock, never under the cold-load ceiling. A no-op without a cold-load ceiling.

func (*Monitor) PeakLoad added in v0.206.0

func (m *Monitor) PeakLoad() int

PeakLoad is the highest number of requests this run ever saw sharing the seat (its own included): 1 = the run had the seat to itself every time it looked, 0 = it never looked (no sampler answered and no engine reading carried gauges: nothing is known, so nothing may be assumed — a caller must not read 0 as solo). A run with PeakLoad > 1 is not solo: its timings are what a shared seat gives one request, not the seat's rate.

func (*Monitor) Phase added in v0.206.0

func (m *Monitor) Phase(ph Phase, pendingPromptTokens int)

Phase moves the run to ph; a phase change is itself progress. The finished call's tokens are folded into the run total.

func (*Monitor) Progress added in v0.206.0

func (m *Monitor) Progress(tokensSoFar int)

Progress records the current call's token count so far. The first delta of a prefill ends the prefill: the allowance drops to the decoding bound.

func (*Monitor) QueuedTotal added in v0.206.0

func (m *Monitor) QueuedTotal() time.Duration

QueuedTotal is how long the run spent in the busy hold so far: time its requests waited on a seat whose engine was working for others. It is the contention figure the job record and the ledger carry beside the wall.

func (*Monitor) SampleLoad added in v0.206.0

func (m *Monitor) SampleLoad()

SampleLoad reads the load sampler once, outside the lock, and folds it into the run's peak. The loop calls it at each model call's first delta: the end of the prefill window that began with Phase's own sample, so a peer that arrived while this request was prefilling is seen too.

When the sampler saw nobody else (or there is none) and an engine probe is installed, the engine's own gauges are read too, off the caller's goroutine — this runs on the stream reader, which an engine that answers only between batches must not stall — with at most one such read in flight. The registry knows only this box's runs; the engine's running + waiting counts every request on the seat, so a peer the registry cannot see still makes the run not solo.

func (*Monitor) SeatAnswered added in v0.206.0

func (m *Monitor) SeatAnswered()

SeatAnswered tells the monitor the step got its answer: the seat serves, the episode (if one is open) ends as a recovery, and a later death earns its own.

func (*Monitor) SeatCheck added in v0.206.0

func (m *Monitor) SeatCheck(ctx context.Context) (bool, string)

SeatCheck answers the chat client's question — is the seat not serving right now — from one fresh read. False (never true) when it cannot tell.

func (*Monitor) SeatDownTotal added in v0.206.0

func (m *Monitor) SeatDownTotal() time.Duration

SeatDownTotal is the wall this run spent waiting for a downed seat: from the first verdict of each episode to the re-issued call's first byte, or to the wait running out. It covers the whole episode, including the time a re-issued call spent held by llama-swap while it started the seat.

func (*Monitor) SeatReadFailures added in v0.206.0

func (m *Monitor) SeatReadFailures() (int, error)

SeatReadFailures is how many reads of the seat could not be answered while the run judged a failure or waited for the seat, and the last error. A run whose seat cannot be read from here gets no seat-down handling at all — a dead seat reads as an ordinary error — and the caller should say so.

func (*Monitor) SeatRecoveries added in v0.206.0

func (m *Monitor) SeatRecoveries() int

SeatRecoveries is how many times this run's seat went down under it and came back: an episode is counted when the re-issued call's first byte arrives (or the step is answered), never for a re-issue that recovered nothing.

func (*Monitor) SettleLoad added in v0.206.0

func (m *Monitor) SettleLoad(max time.Duration) bool

SettleLoad waits, for at most max, for the engine read SampleLoad started to land. The read is asynchronous so a slow engine never holds the stream reader; a caller about to act on PeakLoad (the run is over, the store is about to hear from it) settles first, or a short run could end before its own witness spoke.

It reports whether the witness has spoken: true when no read was in flight or it landed, false when max ran out with the read still pending. A caller that gets false must treat the run's load as unknown, not as whatever the registry said: the read is pending because the engine answers only between batches, which is when peers are most likely, so "the registry saw nobody" is the one answer that cannot be trusted then. The cost is a sample skipped on a seat whose metrics are chronically slow, never a rate moved by a shared one.

func (*Monitor) Snapshot added in v0.206.0

func (m *Monitor) Snapshot() (tokens int, tokS float64, lastProgress time.Time, allowance time.Duration)

Snapshot is the live telemetry status readers and the job view publish.

func (*Monitor) Stop added in v0.206.0

func (m *Monitor) Stop()

Stop ends the watch and releases the ceiling deadline (the run finished). Idempotent. Like a deferred cancel, it also ends the context it handed out.

func (*Monitor) ToolPhase added in v0.206.0

func (m *Monitor) ToolPhase(cap time.Duration)

ToolPhase moves the run into a tool call whose own cap is `cap` (0 = the policy's ToolTimeout, negative = uncapped). A tool call is progress.

func (*Monitor) WithEngineProbe added in v0.206.0

func (m *Monitor) WithEngineProbe(p EngineProbe) *Monitor

WithEngineProbe installs the busy hold's engine probe (ADR 0061). Without a probe, or with StallPolicy.EngineFlat 0, a silent request is judged alone.

func (*Monitor) WithLoad added in v0.206.0

func (m *Monitor) WithLoad(fn func() int) *Monitor

WithLoad installs the load sampler: how many requests share the seat right now, this run's included (0 or less reads as 1). It is called when a prefill or a re-pack begins, outside the monitor's lock, and must be cheap and safe to call from the loop's goroutine.

func (*Monitor) WithSeatProbe added in v0.206.0

func (m *Monitor) WithSeatProbe(p SeatProbe, onHold func(Phase, time.Duration)) *Monitor

WithSeatProbe installs the cold-load hold's seat probe (0.140.0) and the hook that hears the phase change the monitor makes on its own (into PhaseColdLoad; the first byte ends the hold through the loop's own progress events). With StallPolicy.ColdLoad 0 there is no hold at all, and without a probe only a MarkSeatLoaded warm-up is held: otherwise a silent prefill is a stall, as before.

type Msg

type Msg struct {
	Role       string
	Content    string
	ToolCalls  []ToolCall
	ToolCallID string
	IsError    bool
}

Msg is one chat message in the loop's running transcript. Role is "system" | "user" | "assistant" | "tool". A tool result carries ToolCallID (matching the originating ToolCall.ID) and IsError when the tool failed.

func CompactReplay added in v0.206.0

func CompactReplay(msgs []Msg, budget, keepRecent, protectedPrefix int, opts ReplayOpts) []Msg

CompactReplay runs the production compaction ladder over msgs at budget with the given optional rungs. keepRecent/protectedPrefix follow compact()'s semantics (see above). Replay is estimate-ladder only (no Tokenizer): the eval harness measures offline transcripts with no serving endpoint, so it exercises the legacy drop rung — the same path a tokenizer-less production run takes.

type NPUFunc added in v0.206.0

type NPUFunc func(ctx context.Context, tool string, args map[string]any) (string, error)

NPUFunc is the in-process accelerator capability injected by the loop's builder (wired to the Hailo sidecar via pipeline.NewLoopNPU). Mirrors OffloadFunc: keeping it an injected func keeps this package free of any hailoclient import and unit-testable with a fake. nil => no NPU tools, and the loop's advertised tool list stays byte-identical to a box without the device — the same registration pin as the MCP surface (ADR 0024).

The func returns a STRING result (JSON of the sidecar's dict) and follows defer-not-crash: transport/spawn failures come back as {"deferred":true,...} strings with a nil error, never tool errors, so the loop degrades gracefully instead of aborting the step.

type OffloadFunc

type OffloadFunc func(ctx context.Context, task, input string, params map[string]any) (result string, err error)

OffloadFunc is the in-process offload capability injected by cmd/local-agent (wired to pipeline.RunTier, which is record=false → no ledger/cache/shadow/ exemplar writes). Keeping it an injected func keeps this package free of any pipeline import and unit-testable with a fake. nil => no offload tools.

type PagerReport added in v0.206.0

type PagerReport struct {
	Evictions       int   `json:"evictions"`
	EvictedBytes    int64 `json:"evicted_bytes"`
	DistinctEvicted int   `json:"distinct_evicted"`
	Refetched       int   `json:"refetched_distinct"`
	// RefetchRate is distinct re-fetched over distinct evicted. A POINTER: with nothing
	// evicted there is no rate, and a 0.0 would read as a measured "compaction is perfect" —
	// the conclusion that closes the item. Branch on Basis first.
	RefetchRate *float64 `json:"refetch_rate"`
	Basis       string   `json:"basis"` // "measured" | "insufficient_data"
	Verdict     string   `json:"verdict"`
	// CompactionPasses is how many times the compaction ladder ran in this run (a proactive
	// pass, the harder pass after a context-overflow rejection, and the emergency shrink each
	// count one). A POINTER for the same reason RefetchRate is: nil (JSON null) means no
	// instrument recorded the run, and a measured zero is a real 0 — a run that never
	// compacted. A trace written before this field existed has no key at all, and a reader
	// treats that as unrecorded too.
	CompactionPasses *int `json:"compaction_passes"`
}

PagerReport is the read side, carrying its own gate verdict.

type PagerStats added in v0.206.0

type PagerStats struct {
	// contains filtered or unexported fields
}

PagerStats tracks evicted payloads and whether their content came back.

Mutex-guarded for the same reason PrefillStats is: `--serve` shares one *Loop across concurrent HTTP handlers.

func (*PagerStats) NoteCompaction added in v0.206.0

func (p *PagerStats) NoteCompaction(before, after []Msg)

NoteCompaction records what ONE compaction pass took out of the transcript: every tool body present before that is not present, byte-identical, after.

Byte-identical is the right test and not a strict one: the rungs that collapse a body to a dedupe marker, prune it to a skeleton, or drop it outright all leave the agent without the content it had, which is precisely the state a pager would exist to undo. The loop calls this only for a pass it ran: a transcript proactively over budget, or one compacted again after a server overflow rejection. A run that needs neither never calls it and the happy path stays invisible to the instrument. A call over a non-empty transcript counts as one pass even when the pass left every tracked body in place and evicted nothing.

This is the caller the instrument shipped without. Between R2-13 landing and 0.117.7 nothing called NoteEvicted in production, so the gate read insufficient_data on every real run and could close nothing.

func (*PagerStats) NoteEvicted added in v0.206.0

func (p *PagerStats) NoteEvicted(content string)

NoteEvicted records that a payload left the transcript.

func (*PagerStats) NoteFetched added in v0.206.0

func (p *PagerStats) NoteFetched(content string)

NoteFetched records a tool result entering the transcript, and counts it as a RE-fetch only if identical content was evicted earlier in this run.

Ordering is the whole measurement: content seen for the first time is not a re-fetch, and counting it as one would manufacture the very signal the gate is testing for.

func (*PagerStats) Report added in v0.206.0

func (p *PagerStats) Report() PagerReport

type Phase added in v0.206.0

type Phase string

Phase is where a run is, for the liveness rule. It is finer than the registry's Phase (admission / running / repack): the stall allowance differs between a prefill, a decode and a tool call.

const (
	PhaseAdmission Phase = "admission"
	PhasePrefill   Phase = "prefill"
	PhaseDecoding  Phase = "decoding"
	PhaseTool      Phase = "tool"
	PhaseRepack    Phase = "repack"
	// PhaseColdLoad is a request waiting for its seat to LOAD: the engine is
	// not serving the seat (llama-swap reads it `starting`, or holds the
	// request while it swaps another model out), so no byte can arrive and
	// silence is not a stall. The prefill clock is suspended and a cold-load
	// ceiling bounds the wait instead (0.140.0).
	PhaseColdLoad Phase = "cold-load"
	// PhaseQueued is a request that is silent while its seat's ENGINE keeps
	// working for other requests (ADR 0061, 0.143.0): it waits its turn in the
	// engine's own queue, shares a busy or throttled card, or was preempted and
	// will be recomputed. Silence here is not a stall; the busy hold re-reads
	// the engine every EnginePoll, and only an engine that does no work at all
	// for the flat bound is.
	PhaseQueued Phase = "queued"
)

type Policy

type Policy struct {
	// contains filtered or unexported fields
}

Policy is the deterministic deny→ask→allow broker — the cage that must exist BEFORE any mutating tool is granted. It is the single chokepoint for every effectful action. For an UNATTENDED run, "ask" resolves to deny-and-queue (never proceed without a human), making approval-before-destructive a mechanism rather than a hope.

func NewPolicy

func NewPolicy(unattended bool, audit *AuditLog) *Policy

NewPolicy builds a broker. unattended=true makes every "ask" deny-and-queue. audit may be nil (decisions then aren't logged). Egress is deny-all (no allowlist) — use NewPolicyWithEgress to grant outbound hosts. Every broker carries the built-in secret-material rule floor (rules.go defaultRules).

func NewPolicyWithEgress

func NewPolicyWithEgress(unattended bool, audit *AuditLog, allow Allowlist) *Policy

NewPolicyWithEgress is NewPolicy plus a P3 egress allowlist (the set of hosts web_fetch may reach). An empty allowlist is default-deny. The allowlist is set once and never mutated afterward, so classify stays pure and deterministic.

func (*Policy) Decide

func (p *Policy) Decide(a Action) (Decision, string)

Decide returns the EFFECTIVE decision (resolving ask→deny for unattended runs) plus a reason, and records it to the audit log. This is what tools call. If an ALLOW cannot be audited, it is downgraded to DENY — an unauditable mutation is not performed (a mutating agent must leave a trail).

func (*Policy) Explain added in v0.206.0

func (p *Policy) Explain(a Action) (Decision, Refusal)

Explain is Decide with the structured refusal body (register SF-25): the same decision and reason, and the same single audit record, plus the rule that produced it and what the model can do next. Tools return Refusal.Text() for anything but Allow.

func (*Policy) WithAskQueue

func (p *Policy) WithAskQueue(q *AuditLog) *Policy

WithAskQueue attaches a reviewable queue that records every ask DEFERRED on an unattended run (so a human can review/approve them later). Off by default; the standalone runner sets it. The action is still denied in the moment (unattended ask → deny-and-queue) — this just parks the pending request for review.

func (*Policy) WithAuditAdvisory added in v0.206.0

func (p *Policy) WithAuditAdvisory(on bool) *Policy

WithAuditAdvisory makes the attached audit trail advisory (audit_all_doors=warn): every decision is still written, but a failed write is reported once on the log and never turns an allow into a deny. Set once at build time, before any Decide.

func (*Policy) WithAuditEnforcedByKey added in v0.206.0

func (p *Policy) WithAuditEnforcedByKey(on bool) *Policy

WithAuditEnforcedByKey marks the attached trail as enforcing because of audit_all_doors=enforce (SF-02); set once at build time, before any Decide.

func (*Policy) WithBrowse added in v0.206.0

func (p *Policy) WithBrowse(allowed bool) *Policy

WithBrowse enables (or disables) the ActBrowse capability (ADR 0060). Off by default; Build turns it on only when the browse tool is actually granted. Set once at startup before any Decide, so classify stays deterministic.

func (*Policy) WithRules added in v0.206.0

func (p *Policy) WithRules(rules []Rule) (*Policy, error)

WithRules appends validated rules to the broker's table (after the built-in floor). Set once at startup before any Decide, like every other Policy option, so classify stays pure and deterministic. Returns an error rather than silently dropping an invalid rule — a policy table that half-loads is worse than one that refuses to.

func (*Policy) WithShell

func (p *Policy) WithShell(allowed bool) *Policy

WithShell enables (or disables) the ActShell capability. Off by default; the CLI turns it on only when --allow-shell is set AND the OS sandbox is available. Set once at startup before any Decide, so classify stays deterministic.

func (*Policy) WithWritePosture added in v0.21.1

func (p *Policy) WithWritePosture(overwrite, del bool) *Policy

WithWritePosture sets the "open-write" posture. When overwrite is true the broker ALLOWS overwriting an existing file within the worktree instead of asking; when del is true it ALLOWS delete. This is the "fully open in the worktree" mode — the worktree boundary (os.Root) and the unconditional .git deny remain the safety rail. Off by default; set once at startup before any Decide so classify stays deterministic.

type PrefillReport added in v0.206.0

type PrefillReport struct {
	// Steps with server timings. Zero means NOTHING below was measured.
	ObservedSteps int `json:"observed_steps"`
	// Raw totals, so a reader can recompute anything here independently.
	CacheTokens    int64   `json:"cache_tokens"`
	PrefillTokens  int64   `json:"prefill_tokens"`
	PrefillMS      float64 `json:"prefill_ms"`
	GeneratedToken int64   `json:"generated_tokens"`

	// KVReusePct is the share of PROMPT tokens the server did not have to prefill:
	//
	//	CacheN / (CacheN + PromptN)
	//
	// NOT CacheN/PromptN — that denominator excludes the cached tokens themselves
	// and runs past 100%. LLMClient.ServeStats carries the same warning, and it is
	// repeated here because this is where the number gets published.
	//
	// A POINTER, deliberately. With no observed steps there is no ratio, and a
	// float64 zero would be indistinguishable from a genuine, measured "nothing was
	// reused" — the precise failure this estate has already shipped once, in
	// `duplicate_input_rate`, where an unmeasured 0 would have closed a gate. nil
	// serialises as JSON null; a consumer must branch on Basis first.
	KVReusePct *float64 `json:"kv_reuse_pct"`
	// Basis is the machine-readable discriminator: "measured" | "insufficient_data".
	Basis string `json:"basis"`
	// Source says where the observed steps' numbers came from: "timings" (llama.cpp),
	// "usage" (vLLM usage.prompt_tokens_details.cached_tokens, no prompt_ms) or "mixed".
	// Absent when nothing was observed.
	Source string `json:"source,omitempty"`

	// AvgPrefillPerStep sizes the prize in the unit T2-B would attack. nil when
	// unmeasured, for the same reason as above. The ms average covers only steps that
	// carried timings and is nil for a usage-only run: usage has no prompt_ms, and
	// dividing by every observed step (or publishing 0) would invent a speed.
	AvgPrefillTokensPerStep *float64 `json:"avg_prefill_tokens_per_step"`
	AvgPrefillMSPerStep     *float64 `json:"avg_prefill_ms_per_step"`
}

PrefillReport is the read-side view. It is what a decision gets made from.

type PrefillSample added in v0.206.0

type PrefillSample struct {
	Tokens int64
	MS     float64
}

PrefillSample is one seat call's prefill measurement (0.131.1): the tokens the engine actually had to prefill (prompt minus the cached prefix) and the milliseconds to the first streamed delta. The pipeline folds the largest sample of a run into the seat-rates store as prefill_tok_s — on every engine, since it needs no timings block — and on DEFERRED runs too, so a stalled prefill on an unmeasured seat is measured by the very run it cost.

type PrefillStats added in v0.206.0

type PrefillStats struct {

	// Steps that carried server timings. Tracked separately from the run's step
	// count because a backend that reports no `timings` block yields nil Serve,
	// and "10 steps, 0 of them measured" must never read as "10 steps measured".
	Observed int
	// CacheN is prompt tokens the server served FROM ITS KV CACHE.
	CacheN int64
	// PromptN is prompt tokens the server actually had to prefill.
	PromptN int64
	// PromptMS is wall time spent prefilling — the quantity T2-B would be trying
	// to reduce, and the one that makes the win concrete rather than proportional.
	PromptMS float64
	// PredictedN is generated tokens. Carried so a reader can see prefill cost in
	// proportion to the work the run actually produced.
	PredictedN int64
	// TimedSteps / UsageSteps split Observed by where the step's numbers came from:
	// llama.cpp `timings`, or the OpenAI `usage` block a vLLM seat sends instead.
	// PromptMS exists only on the first kind, so its average divides by TimedSteps.
	TimedSteps int
	UsageSteps int
	// contains filtered or unexported fields
}

PrefillStats accumulates the SERVER's own prefill accounting across one agent run.

Every field is a count, never a rate: rates are computed at read time so a caller cannot accidentally average a set of averages.

Concurrency — this is why the mutex is here and not an afterthought

`--serve` shares ONE *Loop across concurrent HTTP handlers. The token calibrator sitting at the same call site was found mutating a shared slice from several goroutines at once, and is gated OFF by default partly for that reason. This instrument is deliberately always-on — an instrument that has to be switched on is one nobody switches on, and it would then be measuring a special mode rather than real traffic. Always-on therefore obliges it to be safe under exactly the concurrency that caught the calibrator.

func (*PrefillStats) Observe added in v0.206.0

func (p *PrefillStats) Observe(s *ServeStats)

Observe folds one completion's server accounting into the run total.

A nil ServeStats is IGNORED rather than counted as a zero-token step. Counting it would silently drag the reuse ratio toward whatever the absent value implies, which is the same class of defect as publishing a fabricated 0 for a rate nobody measured.

func (*PrefillStats) Report added in v0.206.0

func (p *PrefillStats) Report() PrefillReport

Report renders under the lock and copies the counters out, so a concurrent Observe can neither tear a field nor be blocked for longer than the copy.

type Profile added in v0.21.1

type Profile struct {
	// Name is the CLI selector (e.g. "edit"). "general" is the default no-op.
	Name string
	// Tools is the advertised subset by name. EMPTY means "all currently enabled
	// tools" (the general profile) — no narrowing. A name not among the enabled
	// tools is simply ignored (narrow-only invariant).
	Tools []string
	// System, when non-empty, overrides the loop's system prompt with a prompt
	// tuned for this task shape.
	System string
	// Exemplars are TRUSTED, author-provided few-shot messages showing ONE correct
	// COMPLETE tool cycle for this job: user → assistant(tool_calls) → tool(result).
	// Every assistant message that carries ToolCalls MUST be immediately followed by
	// tool-role messages covering all its ToolCall.IDs — a dangling tool_calls with
	// no matching result violates strict --jinja templates (which this stack pins)
	// and can 400. They are injected right after the system message and before any
	// untrusted recall/AGENT.md/objective.
	//
	// Every exemplar thread must be CLOSED by a final assistant answer and its user
	// turns marked "(worked example, not the task)": an open thread whose topic is a
	// real-world question (the research profile's "latest stable Go version", until
	// 0.113.1) is continued by small seats instead of the objective — the <node-c>
	// 4B's phantom "Go version" digests of 2026-08-31…09-03 that quarantined both
	// fleet nodes. Enforced by TestProfileExemplarsCloseWithAFinalAnswer /
	// TestProfileExemplarUserTurnsAreMarked / TestProfileExemplarsUseNoRealWorldTopic.
	Exemplars []Msg
}

Profile is a per-task tuning of the agent loop: a curated tool SUBSET, an optional tuned system prompt, and 2-3 worked tool-call exemplars injected as messages. It exists because small local models pick tools better with FEWER advertised ("Less is More": 63→71% on an 8B) and with worked examples shown in-context as messages (few-shot: Haiku 11→75%). A profile can only NARROW the already-enabled tool set — never grant a tool the capability flags didn't turn on (enforced in Loop.WithProfile) — so it is safe to select at the CLI.

func LookupProfile added in v0.21.1

func LookupProfile(name string) (Profile, error)

LookupProfile returns the named profile. An unknown name is an error whose message lists every valid profile name (sorted), so a CLI user can recover.

type ProgressFunc added in v0.206.0

type ProgressFunc func(tokensSoFar int)

ProgressFunc hears a completion's progress as the seat streams it: the tokens generated so far for THIS call. Content, reasoning and tool-call argument deltas all count — a token is a token to a liveness rule, and a model that is thinking is producing.

func ProgressFromContext added in v0.206.0

func ProgressFromContext(ctx context.Context) ProgressFunc

ProgressFromContext returns the installed ProgressFunc, or nil.

type PromptCaps added in v0.207.0

type PromptCaps struct {
	AllowWrite     bool // write_file / delete_file
	AllowOverwrite bool // with AllowWrite: overwrite + edit_file instead of create-only
	AllowFetch     bool // web_fetch
	AllowShell     bool // run_shell
	RunGranted     bool // run(command, args)
	AllowSearch    bool // web_search
	AllowGitHub    bool // github_* tools
}

PromptCaps names the capabilities SystemPrompt advertises. The zero value is the read-only prompt.

type Recalled

type Recalled struct {
	ID     string
	Text   string
	Score  float64
	Source string // which namespace (user_id) it came from
}

Recalled is one retrieved memory.

type Refusal added in v0.206.0

type Refusal struct {
	Decision  Decision
	Rule      string
	Reason    string
	NextSteps string
	// Asked: the decision was ask before an unattended run resolved it to deny.
	Asked bool
}

Refusal is the structured body of a deny or ask (register SF-25): the decision, the rule that produced it, the reason, and what the model can do next. It never offers an approval verb: an unattended ask is an operator decision outside the run, not something the model can request, and a refusal that invites "ask for approval" teaches the model to loop on it.

func (Refusal) Text added in v0.206.0

func (r Refusal) Text() string

Text is the tool result the model sees. The first line is the one-line refusal tools returned before SF-25; the rule and the next step follow on their own lines. Each field is flattened to one line, so an operator rule's reason cannot add lines of its own.

type RepetitionLoop added in v0.206.0

type RepetitionLoop struct {
	// Count is the number of consecutive occurrences of the block, the first
	// one included.
	Count int
	// Period is the block's length in non-blank lines (1 = a single repeated
	// line).
	Period int
	// First is the block's first line as the seat wrote it — the evidence
	// quoted in the stop note. Comparison is done on the normalised form;
	// what an operator greps for is the original.
	First string
	// CutAt is the byte offset in the original text where the SECOND
	// occurrence begins. Text before it is the answer plus one copy.
	CutAt int
}

RepetitionLoop is one degenerate loop found in an answer: the block that recurs, how many times, and where the SECOND occurrence starts in the original text (the byte offset the trim cuts at).

func DetectRepetitionLoop added in v0.206.0

func DetectRepetitionLoop(s string) (RepetitionLoop, bool)

DetectRepetitionLoop reports whether the tail of s is the same block repeated at least minRepeats times. It normalises each line (trimmed, inner whitespace collapsed, case-folded) so a loop that drifts in spacing is still one loop, and it ignores blank lines entirely — a run of empty lines is formatting, never a degenerate generation.

type ReplayOpts added in v0.206.0

type ReplayOpts struct {
	GCF      bool
	Skeleton bool
	// SearchResults and LogCollapse switch on the two optional rungs that are
	// default off in production; the compaction eval sets them to measure each.
	SearchResults bool
	LogCollapse   bool
}

ReplayOpts mirrors compactOpts for external replay callers.

type Result

type Result struct {
	Output string // the final assistant content
	Steps  int    // model turns taken
	// TokensIn / TokensOut are the SEAT's own usage summed over every model turn of
	// the run (prompt tokens the server processed, cache hits included; completion
	// tokens it generated). They are what the ledger reports as work the cards did,
	// and they are set on EVERY return — a budget- or error-ended run generated
	// just as many tokens as a finished one. 0 when the backend reports no usage.
	TokensIn   int
	TokensOut  int
	StopReason string // "done" (model finished) | "budget" (hit maxSteps) | "error" | StopReasoningStarved | StopEmpty | "unparsed_tool_call"
	// StopNote is the one-line evidence behind a StopReasoningStarved / StopEmpty
	// stop (the starvation arithmetic of the last empty completion). Empty otherwise.
	StopNote string
	// OutputTruncated: the final answer ended on finish_reason "length" — a
	// correct partial the caller must not mistake for the whole (the 2026-09-10
	// `ledger-02` row: 2,630 chars cut mid-sentence at exactly 1,024 tokens).
	OutputTruncated bool
	// FinalBudgetFit / BudgetNote (0.122.1, register D-95) are the wall fit for
	// the final answer: the budget the final turn actually opened at once the
	// remaining wall was taken into account, and the arithmetic behind it
	// ("final 8192 → 3592 to fit 900 s at 15.0 tok/s"). Both zero/empty when no
	// fit was installed or the configured budget was left untouched — a run
	// that was not narrowed must never publish a note saying it was. Set on
	// EVERY return path (Run wraps run for exactly that reason): the runs that
	// end on the wall are the ones whose sizing most needs reading.
	FinalBudgetFit int
	BudgetNote     string
	// FinalReissue names the re-issue a cut final earned, "" when none —
	// FinalReissueListCap is the only shape there is (D-95). Set whether or not
	// the re-issue then succeeded: a second cut abstains WITH the attempt on
	// the record, so an operator can tell a first cut from a second.
	FinalReissue string
	// Calls is one CallRecord per planner completion, on EVERY return path
	// (thinking.go, D-47): finish reason, completion/reasoning tokens, visible
	// and hidden chars, whether thinking was off. The corpus fact the rigger
	// classifies reasoning-starvation on.
	Calls      []CallRecord
	Transcript []Msg

	// SeatRecoveries (ADR 0066) counts the times the run's seat went down under it
	// and came back: each one is a wait the run survived with its transcript intact
	// and no step spent, counted when the re-issued call's first byte arrived —
	// never for a re-issue that recovered nothing. Set on every return path (Run
	// stamps it from the liveness monitor, the run's single witness); 0 on every run
	// whose seat stayed up.
	SeatRecoveries int

	// Fallback is set only by RunTwoTier (two-tier drive): it records whether the
	// architect/editor plan-then-execute path ran (FallbackNone) or a fallback to a
	// single-model editor run occurred, and why. Empty on ordinary single-loop runs.
	Fallback FallbackReason

	// CompactionsExhausted counts steps where the ladder ran and still could
	// not fit the input budget (best-effort transcript sent anyway) — the
	// honest fit=false telemetry the OmniRoute-harvest design requires instead
	// of silent over-budget requests. 0 on every run that stayed within budget.
	CompactionsExhausted int

	// RuleHits lists every environment rule that fired this run (envrules.go),
	// in call order — the rigger's evidence. nil when no rules are installed
	// or none fired. Present on every return path, like Effects.
	RuleHits []EnvRuleHit

	// TokenCal reports what the budget calibration actually learned this run
	// (ADR 0017). A self-tuning mechanism that cannot be inspected is a
	// mechanism nobody can debug: these fields make its behaviour auditable
	// per run instead of inferred from outcomes.
	TokenCal TokenCalReport

	// Prefill reports the SERVER's own prefill accounting for this run
	// (memory-frontier T2-B, re-aimed): how much of each step's prompt llama.cpp
	// served from its KV cache versus had to prefill again.
	//
	// It exists to DECIDE whether prefix-stability work is worth doing here. The
	// ledger measured the text cascade and killed the original target — a median
	// 177-token prompt, ~12 s/day of prefill in total. But the ledger never sees
	// the agent loop, which re-sends a long system prompt plus tool schemas plus a
	// growing transcript on every single step. This is the missing measurement.
	//
	// Always populated; read Basis before the rate. A run against a backend that
	// reports no timings yields ObservedSteps 0 and Basis "insufficient_data"
	// rather than a fabricated 0% reuse.
	Prefill PrefillReport
	// KVSlot reports what the node-side KV-slot retention did for this run (kvslot.go): the run-start restore and
	// its verdict, the saves, and the tool-wait save/restore. nil when no store was attached.
	KVSlot *KVSlotReport `json:"kvslot,omitempty"`
	// PrefillSamples (0.131.1): per-call (uncached prompt tokens, ms to first
	// delta) — see PrefillSample. Present on deferred runs too.
	PrefillSamples []PrefillSample
	// Pager is the context-pager instrument's report for this run (R2-13,
	// contextpager.go): how much evicted content the agent came BACK for. It is
	// the gate that closes — or opens — the whole pager family, and it can only
	// ever read "insufficient_data" if nothing feeds it, which is exactly what
	// happened between the instrument landing and 0.117.7: PagerStats had no
	// production caller at all, so the 10 % gate could never fire in either
	// direction. Fed here from the compaction path (evictions) and the
	// tool-result boundary (fetches).
	Pager PagerReport

	// TokenizerPath reports which drop rung the compaction ladder is on at the
	// end of the run — the visibility twin of ctx_window for the window probe
	// (a fail-open feature that can be permanently inert with zero evidence is
	// not fail-open, it is fail-unobservable). "" = no tokenizer configured
	// (legacy rung by construction); "token-exact" = the real-tokenizer cut is
	// live; "legacy (degraded: <why>)" = a tokenizer WAS configured but a
	// classified endpoint failure (definitive route absence, or two consecutive
	// transient failures) downgraded this Loop to the legacy rung, with the
	// recorded reason.
	TokenizerPath string `json:"tokenizer_path,omitempty"`

	// ArchTokenizerPath is set only by RunTwoTier (like Fallback): the
	// ARCHITECT tier's TokenizerPath, carried so an architect-only tokenizer
	// degrade is observable — each tier cuts with its own served tokenizer, so
	// the two degrade independently, and returning only the editor's verdict
	// hid a misrouted architect model forever (review finding 2026-08-14).
	ArchTokenizerPath string `json:"arch_tokenizer_path,omitempty"`

	// Effects is the per-call execution ledger (effects.go): one record per
	// tool call the model REQUESTED, in call order, present on every return
	// path including errors. The one consequential distinction it preserves:
	// EffectUnknown (started, then abandoned — effects may exist) vs
	// EffectNone (never executed — the world is untouched).
	Effects []EffectRecord

	// JudgeReport is the end-of-run ADVISORY audit of flagged effects
	// (batchjudge.go): one same-seat completion, only when something was
	// flagged and WithBatchJudge is on. Annotation for the operator — nothing
	// in the codebase makes decisions from it. Empty when off or clean.
	JudgeReport string
}

Result is the outcome of a loop run.

func RunTwoTier added in v0.21.1

func RunTwoTier(ctx context.Context, objective string, architect, editor *Loop) (Result, error)

RunTwoTier runs aider's verified architect/editor one-shot handoff (the best-evidenced small-model decomposition: architect/editor 26.2% vs 20.9% solo, edit-format compliance 67.6%->100%).

Flow (exactly aider's semantics):

  1. The architect loop runs the ORIGINAL objective and produces a full prose plan (Result.Output).
  2. If the plan is non-degenerate, the editor loop runs with that plan as its SOLE user message — Loop.Run always starts a fresh transcript (system + optional recall/AGENT.md + the objective it is given), so passing the plan as the editor's objective naturally gives the editor a fresh context with NO conversation history and NOT the original request. The editor's Result is returned.

It is one-shot: the architect is NOT re-invoked after the editor runs. On a single GPU this is exactly ONE cold model swap (architect model -> editor model), cheap because it is plan-once-then-execute, not per-step alternation.

Fallback (never leave the user with nothing): if the architect errored OR produced no usable plan, RunTwoTier runs the ORIGINAL objective directly on the editor loop as a single-model run and records the reason in Result.Fallback.

type RootGoneError added in v0.206.0

type RootGoneError struct {
	Root string // the absolute workspace root the tool tried to open
	Err  error  // what the operating system answered
}

RootGoneError is a file tool's report that the run's workspace root could not be opened (register C-79). Every tool that reads or writes the workspace opens the root first (scope.open, update_plan), so the directory the run was built over being gone, or unreadable, is the one failure every one of them shares.

It is the box's fault and no model action can undo it, which is why it is a type and not a sentence in a tool result: the loop used to feed it back as an ordinary error observation, the seat then wrote a final answer from nothing ("I could not read the file"), and the run was scored as the model's failure. The loop now ends the run on it (Loop.Run returns it) and the node files the defer as `infrastructure` (pipeline.runAgentTask).

A file that is missing INSIDE a root that opens is not this: that is the model's mistake or the task's, and stays an observation.

func CheckWorkspaceRoot added in v0.206.0

func CheckWorkspaceRoot(root string) *RootGoneError

CheckWorkspaceRoot is the tools' own question asked without a tool call: can the run's workspace root still be opened? It is nil when it can, and otherwise the *RootGoneError a file tool would have answered with. The pipeline asks it where no tool is there to ask (register C-79): the write door's tree is the deliverable, so a tree lost before the door opens, or after the seat's last call, would otherwise surface as a write fault, or as a snapshot of a directory that is not there, which reads as every file deleted.

It goes through openWorkspaceRoot, the one place a failure to open becomes a *RootGoneError, so its answer is a tool's answer byte for byte. It closes the handle it opened: an open handle would hold the directory against its removal on Windows.

func RootGoneOf added in v0.206.0

func RootGoneOf(err error) *RootGoneError

RootGoneOf is the *RootGoneError an error is, or carries, and nil when it is neither: the one question the loop asks of a failed tool call, and the node asks of the error a run ended on.

func (*RootGoneError) Cause added in v0.206.0

func (e *RootGoneError) Cause() string

Cause is the operating system's own words for the failure without the path in front of them ("no such file or directory"), for a sentence that names the root itself and would otherwise print it twice.

func (*RootGoneError) Error added in v0.206.0

func (e *RootGoneError) Error() string

Error is the text the seat always saw for this failure, byte for byte, so a transcript, an effect note and a log line read the same before and after the loop learned to end the run on it. The path is in Err's own text.

func (*RootGoneError) Unwrap added in v0.206.0

func (e *RootGoneError) Unwrap() error

type Rule added in v0.206.0

type Rule struct {
	// Kind is the action class the rule applies to. ActShell is REJECTED at
	// validation: there is nothing structural to match in a command line, and
	// the cage owns shell containment (see the package comment).
	Kind ActionKind `json:"kind"`
	// Glob matches the worktree-relative path (write/delete) or the host
	// (fetch), using path.Match semantics against the slash-cleaned value; a
	// glob without a slash also matches the path's basename, so "*.pem"
	// catches "sub/dir/server.pem".
	Glob string `json:"glob"`
	// Decision must be Deny or Ask — tighten-only, never Allow.
	Decision Decision `json:"decision"`
	Severity Severity `json:"severity"`
	// Reason is what the model (and the audit trail) sees when the rule fires.
	Reason string `json:"reason"`
}

Rule is one structural policy rule. First match wins; evaluated after the unconditional built-in denies (.git) and BEFORE capability/posture defaults, so a rule can veto what posture would have allowed but can never resurrect what the built-ins deny.

func LoadRules added in v0.206.0

func LoadRules(pathname string) ([]Rule, error)

LoadRules reads a JSON rule table (an array of Rule) — the versioned, diffable operator surface. A missing file is an error: pointing the flag at a path that does not exist means the operator THINKS a table is active.

func UnattendedRules added in v0.206.0

func UnattendedRules() ([]Rule, error)

UnattendedRules parses and validates the embedded default table. The embed guarantees presence at runtime regardless of install layout; validation still runs so a bad edit to the JSON fails loudly at Build rather than silently weakening the gate (fail closed, same contract as LoadRules).

type RunObserver added in v0.206.0

type RunObserver interface {
	OnStep(step, tokensOut int)
	OnPhase(phase string)
	// OnProgress hears every streamed delta with the run's token total so far
	// (0.131.0, liveness walls): what a status reader shows as "producing".
	OnProgress(tokensOut int)
	// OnAllowance hears the liveness phase and the stall bound the run is
	// under, so the reader can say "silent 187 s of 214 s allowed in prefill".
	OnAllowance(phase string, allowance time.Duration)
}

RunObserver hears a run's progress as it happens: the step just completed (1-based) with the seat's completion tokens so far, and phase changes the loop knows about ("final" = the forced final step). The run registry (internal/gpuactivity) implements it so a drain or a status reader can see a run between its steps, when the seat's own gauge reads idle (0.117.0).

type Sampling added in v0.206.0

type Sampling = core.AgentSampling

Sampling is the loop's alias for the wire/config type, so callers inside this package never need the core import just to name a policy.

func SamplingFromContext added in v0.206.0

func SamplingFromContext(ctx context.Context) *Sampling

SamplingFromContext returns the policy for this call, nil when none was set.

type SeatCheckFunc added in v0.206.0

type SeatCheckFunc func(ctx context.Context) (down bool, why string)

SeatCheckFunc is the seam the chat client asks before it sleeps on a 5xx: is the seat not serving right now, and why.

func SeatCheckFromContext added in v0.206.0

func SeatCheckFromContext(ctx context.Context) SeatCheckFunc

SeatCheckFromContext returns the attached check, or nil.

type SeatDownError added in v0.206.0

type SeatDownError struct {
	Kind SeatDownKind
	// Phase is where the run's request was waiting when the seat went down.
	Phase Phase
	// Silent is how long the engine had shown no sign of life (a wedge).
	Silent time.Duration
	// Engine is the last engine reading; Note is the evidence in one clause.
	Engine string
	Note   string
	Tokens int
	// Waited is how long the run waited for the seat to come back.
	Waited time.Duration
	// Reissued: the failed step was re-issued after the seat came back and the
	// seat went down again. GaveUp: the wait ran out (or no recovery was left).
	Reissued bool
	GaveUp   bool
	// Attempts is how many re-issues the wait sent to a seat nobody listed (each is
	// a start attempt); LastSeen is what the wait last saw of the seat.
	Attempts int
	LastSeen string
	// contains filtered or unexported fields
}

SeatDownError is the typed outcome of a seat that went down under a run. Its text begins core.SeatDownReason; it wraps the evidence that revealed it (the engine-flat *StallError for a wedge — so a reader that only knows StallError still sees the arithmetic — or the failed call's own error for a death).

func (*SeatDownError) Error added in v0.206.0

func (e *SeatDownError) Error() string

func (*SeatDownError) Unwrap added in v0.206.0

func (e *SeatDownError) Unwrap() error

type SeatDownKind added in v0.206.0

type SeatDownKind string

SeatDownKind says HOW the seat went down.

const (
	// SeatDownWedged: the engine did no work for anyone for the flat bound while
	// llama-swap read the seat loaded. Recovery needs a CHANGE — a restart, or the
	// counters moving again — before a re-issue is worth sending.
	SeatDownWedged SeatDownKind = "wedged"
	// SeatDownDied: llama-swap no longer serves the seat (gone from /running,
	// restarting, or its engine refuses connections).
	SeatDownDied SeatDownKind = "died"
)

type SeatPin added in v0.206.0

type SeatPin struct {
	SHA256 string
	Basis  string
}

SeatPin is a seat's serving-config fingerprint. SHA256 is what pairing logic compares; Basis is the short human-readable summary an operator reads when two hashes differ ("what changed?").

func ProbeSeatPin added in v0.206.0

func ProbeSeatPin(ctx context.Context, base, model string) (SeatPin, bool)

ProbeSeatPin GETs the llama-swap per-model /props passthrough (upstream only — the bare-root /props answers for whatever model happens to be loaded, the exact mis-attribution ProbeUpstreamWindow already refuses) and returns the seat's pin. ok=false on any transport, status, or decode failure: a pin is evidence, and a guess is worse than an absence.

type SeatProbe added in v0.206.0

type SeatProbe func(ctx context.Context) (loading bool, state string, err error)

SeatProbe reads whether the engine is serving the run's seat right now. loading = the seat is not being served (llama-swap `starting`/`stopping`, or absent while the request is held for a swap); state is what the probe saw, for the reason. A non-nil err means "cannot tell": the monitor then keeps the prefill clock running, exactly as it did before probes existed.

type ServeStats added in v0.206.0

type ServeStats struct {
	CacheN            int     `json:"cache_n"`
	PromptN           int     `json:"prompt_n"`
	PromptMS          float64 `json:"prompt_ms"`
	PredictedN        int     `json:"predicted_n"`
	PredictedMS       float64 `json:"predicted_ms"`
	UsagePromptTokens int     `json:"usage_prompt_tokens"`
	UsageCachedTokens int     `json:"usage_cached_tokens"`
	// UsageCachedReported: the server sent usage.prompt_tokens_details.cached_tokens at
	// all. False makes UsageCachedTokens 0-because-absent, which PrefillStats must not
	// read as "nothing was reused" on a backend that sends no timings.
	UsageCachedReported bool `json:"usage_cached_reported,omitempty"`
	// UsageCompletionTokens is the server's own count of tokens it GENERATED for
	// this completion. It is the number the harness ledger needs for "work the seat
	// did" — until 0.115.5 the loop never summed it, so an agent run that generated
	// for minutes was ledgered as 0 (only the structured re-pack's tokens counted).
	UsageCompletionTokens int `json:"usage_completion_tokens"`
	// UsageReasoningTokens is the server's count of completion tokens spent on
	// hidden reasoning (vLLM `usage.completion_tokens_details.reasoning_tokens`).
	// 0 when the backend does not report it — a starvation verdict then rests
	// on the reasoning TEXT and the finish reason instead (Completion.Starvation).
	UsageReasoningTokens int `json:"usage_reasoning_tokens,omitempty"`
}

ServeStats is the SERVER's own accounting for one completion — the only trustworthy source for KV-prefix reuse and REAL token counts (the ladder's own estimator is chars/4 and drifts by content kind).

CacheN is the count of prompt tokens served from the KV cache; PromptN the count actually prefilled. Their sum is the real prompt length, which is why reuse is CacheN/(CacheN+PromptN) and never CacheN/PromptN.

type SetupAction added in v0.206.0

type SetupAction struct {
	Tool string
	Args string
}

SetupAction is the loop-local form of core.AgentSetupAction: the tool by name and its argument object as raw JSON.

type Severity added in v0.206.0

type Severity string

Severity grades a rule hit for the audit trail. It does not change the decision — deny is deny at any severity — but it lets the morning review sort a night's queue by what actually matters.

const (
	SevCritical Severity = "critical"
	SevHigh     Severity = "high"
	SevMedium   Severity = "medium"
	SevLow      Severity = "low"
)

type StallError added in v0.206.0

type StallError struct {
	Phase           Phase
	Silent, Allowed time.Duration
	Tokens          int
	Note            string
	// PostReady: a cold-load stall filed in the hold's post-ready part (the
	// seat had loaded and then sent nothing); ReadySeen: /running read it
	// ready (false = it could not be read).
	PostReady, ReadySeen bool
	// EngineFlat (ADR 0061): the seat's ENGINE did no work for any request
	// for EngineSilent while this request waited in Waited — the seat itself
	// is wedged, not busy. Engine is what the last reading showed.
	EngineFlat   bool
	EngineSilent time.Duration
	Waited       Phase
	Engine       string
	// EngineThrash: the engine kept stepping but produced no token for
	// anyone for EngineSilent (preempt-and-recompute). Unreadable: the stall
	// was filed because the engine could not be read (the reason's note says
	// so) — never reported as "did no work".
	EngineThrash bool
	Unreadable   bool
}

StallError: the seat stopped producing for this run. Filed as an INFRASTRUCTURE defer — the contract was fine, the seat went silent.

func (*StallError) Error added in v0.206.0

func (e *StallError) Error() string

type StallPolicy added in v0.206.0

type StallPolicy struct {
	Admission   time.Duration // allowance while admitting / cold-loading / probing
	PrefillTokS float64       // measured prefill rate; 0 = unknown
	TokS        float64       // measured decode rate; 0 = unknown
	ToolTimeout time.Duration // the loop's per-tool cap (ToolPhase overrides per call)
	Repack      time.Duration // the flat re-pack bound: the least a re-pack may be silent (120 s in production); a known answer size and seat rate raise it (Allowance)
	Floor       time.Duration // no allowance is ever shorter (60 s in production)
	Slack       time.Duration // flat padding on the prefill estimate and a tool's cap (30 s in production)
	// ColdLoad is the ceiling on ONE observed seat load while a request waits
	// for its first byte (0.140.0). 0 = no cold-load hold: a silent prefill is
	// a stall whatever the seat is doing, the pre-0.140.0 rule. It is never
	// unbounded: past it the run files a cold-load stall.
	ColdLoad time.Duration
	// ColdLoadBasis spells how ColdLoad was sized, for the reason text.
	ColdLoadBasis string
	// ColdLoadPoll is the probe cadence while a request waits for its first
	// byte; 0 = defaultColdLoadPoll.
	ColdLoadPoll time.Duration
	// PostReady is the floor of the POST-READY bound: how long a request may
	// stay silent after its seat, freshly loaded, reads ready (0.140.0). The
	// bound is max(PostReady, 2 x the waiting phase's allowance), far shorter
	// than ColdLoad, so a seat that wedges right after loading is seen fast.
	PostReady time.Duration
	// EngineFlat is the busy hold's bound (ADR 0061, 0.143.0): how long the
	// seat's ENGINE may do no work at all — for any request — while this run's
	// request is silent, before the run is declared stalled. The bound applied
	// is max(EngineFlat, the waiting phase's own allowance). 0, or no engine
	// probe installed, = no busy hold: a silent request is judged alone, the
	// pre-0.143.0 rule.
	EngineFlat time.Duration
	// EnginePoll is how often the busy hold re-reads the engine; 0 =
	// defaultEnginePoll.
	EnginePoll time.Duration
	// EngineProbeTimeout bounds one engine read; 0 = defaultEngineProbeTimeout.
	EngineProbeTimeout time.Duration
	// EngineTokenFlat is how long the engine may keep stepping without
	// producing a token for anyone (a preempt-and-recompute thrash) before the
	// run stalls; never below the flat bound. 0 = three flat bounds.
	EngineTokenFlat time.Duration
	// SeatRecoveries (ADR 0066) is how many times ONE run may wait for a downed
	// seat and re-issue the model call that failed, instead of ending: the seat's
	// engine hung with work outstanding, or died and llama-swap no longer serves
	// the seat. The loop holds the transcript, so a recovery loses nothing. 0 =
	// none: a seat-down verdict ends the run, typed. The wait itself is bounded
	// by ColdLoad (and the run's ceiling), so a recovery needs a cold-load
	// ceiling and an engine probe.
	SeatRecoveries int
}

StallPolicy is how long a run may go without a progress event in each phase before it is declared stalled. Liveness is progress: a streamed token, a tool call starting or finishing, a phase change. The allowance is DYNAMIC — prefill of a 214k-token prompt at 2,000 tok/s is 160 s of legitimate silence, not a hang — and it is what status readers show as "allowed".

func (StallPolicy) Allowance added in v0.206.0

func (p StallPolicy) Allowance(ph Phase, pendingPromptTokens int) time.Duration

Allowance is the stall bound for a phase on a seat this run has to itself. pendingPromptTokens is the size of the prompt the seat is prefilling (0 outside prefill); for PhaseRepack it is the expected size of the re-packed answer in tokens.

func (StallPolicy) AllowanceLoad added in v0.206.0

func (p StallPolicy) AllowanceLoad(ph Phase, pendingPromptTokens, load int) time.Duration

AllowanceLoad is Allowance for a seat that `load` requests share, this one included (ADR 0066, register C-66). The measured prefill rate is a single-request rate, and an engine that batches load requests gives each of them about 1/load of it: prefill = pending / (rate / load) x margin + slack, and the re-pack's flat bound stretches by load the same way (the generation estimate that can raise it above the flat bound, sized from the expected answer at the seat's decode rate, is left as it is, like decoding). load <= 1 is Allowance, exactly; the floor stays the definition of a silent SEAT. Decoding is left as it is: its allowance is a count of deltas at the seat's own decode rate, and a seat that decodes at 1/load of it is caught by the same floor.

type StatusError added in v0.206.0

type StatusError struct {
	Code int
	Body string
}

StatusError is a non-200 from the seat's chat route, typed so callers key on the STATUS (never on body prose — the same rule delegate.replaceableRefusal follows for fleet nodes). Its text is unchanged from the old fmt.Errorf so every existing log grep and reason string still matches.

func (*StatusError) Error added in v0.206.0

func (e *StatusError) Error() string

type ThinkingMode added in v0.206.0

type ThinkingMode string

ThinkingMode is the loop's policy for the seat's think block on planner calls (config `agent_thinking`, contract `thinking`, Loop.WithThinking).

ThinkingAuto (""/"auto")  every step thinks; a step that ends empty is
                          re-issued ONCE with thinking off at the final
                          budget (finalMaxTokens), then the run stops with
                          a named reason. The default.
ThinkingOff  ("off")      every planner call renders in non-thinking mode.
                          For grounded extraction on a seat whose think
                          block was measured to starve the answer.
ThinkingOn   ("on")       never send the non-thinking kwarg — for a seat
                          whose template rejects it. The empty-final retry
                          still runs, at the final budget, thinking on.
const (
	ThinkingAuto ThinkingMode = "auto"
	ThinkingOff  ThinkingMode = "off"
	ThinkingOn   ThinkingMode = "on"
)

func ParseThinkingMode added in v0.206.0

func ParseThinkingMode(s string) (ThinkingMode, error)

ParseThinkingMode validates a mode string from config or a contract. The empty string is auto. Anything else is a caller error, named. The vocabulary is exactly core.ValidateThinking's (auto / on / off, case-insensitive) so a value the contract door accepts is one the build accepts, and vice versa.

type TokenCalReport added in v0.206.0

type TokenCalReport struct {
	Observations int     `json:"observations"`
	Fitted       bool    `json:"fitted"`
	Slope        float64 `json:"slope,omitempty"`
	Intercept    float64 `json:"intercept,omitempty"`
	RawBudget    int     `json:"raw_budget"`
	FinalBudget  int     `json:"final_budget"`
}

TokenCalReport is the observable state of the budget calibration at the end of a run. Fitted=false means it never had enough well-spread observations and the budget was left exactly as inputBudget() computed it.

type TokenCalibrator added in v0.206.0

type TokenCalibrator struct {
	// contains filtered or unexported fields
}

func (*TokenCalibrator) Budget added in v0.206.0

func (c *TokenCalibrator) Budget(allowance int) int

Budget converts a REAL-token allowance into the ESTIMATE-space budget the ladder should compact against, so that a transcript passing the ladder's check also fits the server.

Solving real = intercept + slope·estimate ≤ allowance gives estimate ≤ (allowance − intercept)/slope.

With no usable fit it returns the allowance UNCHANGED — today's behaviour exactly, so an uncalibrated loop is byte-identical to before this file existed. The floor mirrors inputBudget()'s: a degenerate fit degrades to a small budget (aggressive compaction) rather than to a negative one.

func (*TokenCalibrator) Fit added in v0.206.0

func (c *TokenCalibrator) Fit() (slope, intercept float64, ok bool)

Fit returns the current (slope, intercept, ok) using a ROBUST median fit (Theil–Sen): the slope is the median of pairwise slopes, the intercept the median residual. Least squares was the obvious choice and the wrong one — it has an unbounded influence function, so one anomalous usage.prompt_tokens (a proxy reporting cumulative or prompt+completion tokens, say) dragged the slope to its clamp and cut the budget for the remainder of the run. A median tolerates a minority of bad readings by construction.

Pairs are only counted when their estimates differ MEANINGFULLY; a near-equal pair yields a noise slope, and requiring a real spread is what stops that noise from reaching the budget.

ok is false until the data can actually support a two-term fit; callers then leave the budget untouched rather than acting on a guess.

func (*TokenCalibrator) Observations added in v0.206.0

func (c *TokenCalibrator) Observations() int

Observations reports how many usable samples the calibrator currently holds.

func (*TokenCalibrator) Observe added in v0.206.0

func (c *TokenCalibrator) Observe(est, real int)

Observe records one (estimate, real) pair for a request the server accepted. Non-positive values are ignored — an unmeasured response must never move the calibration.

type Tokenizer added in v0.206.0

type Tokenizer interface {
	Pieces(ctx context.Context, text string) ([]int, bool)
}

Tokenizer is the seam cutMiddleTurns needs from the real-tokenizer path (internal/tokclient implements it): the byte length of every token piece of text, in order, with ok=false on any failure. Implementations MUST fail open — returning ok=false routes the ladder to the legacy estimate rung.

type Tool

type Tool struct {
	ToolSpec
	Exec func(ctx context.Context, args string) (string, error)
	// Timeout bounds ONE call of this tool. Zero uses the loop default
	// (defaultToolTimeout). It lives on Tool, not ToolSpec, because ToolSpec is
	// the wire format handed to the model — the model has no business seeing it.
	Timeout time.Duration
	// ParkOnHighRisk marks an EFFECTFUL tool whose calls are parked (refused
	// with EffectNone) when the model self-flags security_risk=high and the
	// loop runs unattended (WithParkHighRisk). Self-annotation can only
	// TIGHTEN: there is no risk value that loosens the broker or auto-allows.
	ParkOnHighRisk bool
}

Tool is a ToolSpec plus its executor. Exec receives the raw JSON args and returns a result string; an error is fed back to the model as an is_error tool result (the loop does not abort).

func BrowseTools added in v0.206.0

func BrowseTools(pol *Policy, run BrowseFunc, hosts []string, unattended bool, timeout time.Duration) []Tool

BrowseTools builds the `browse` tool. hosts is the run's allowlist (required on an unattended build — Build refuses the grant otherwise); every call goes through the broker as ActBrowse with the start host as its subject, so --rules can deny or queue hosts and the audit log records each run.

func FetchTools

func FetchTools(pol *Policy) []Tool

FetchTools builds the P3 web_fetch tool, registered ONLY when egress is opted in. With no allowlist the broker denies every host, so the network capability is inert by default — mirroring how P0/P1 advertise no network tool at all.

func GitHubTools added in v0.21.1

func GitHubTools(pol *Policy, token, defaultRepo, worktreeRoot string) []Tool

GitHubTools builds the GitHub toolset. token is required (empty => the tools refuse, defer-not-crash). defaultRepo (owner/name) is used when a call omits the repo. worktreeRoot is where github_upload_file reads local files from.

func ReadOnlyTools

func ReadOnlyTools(root string, offload OffloadFunc, npu NPUFunc) ([]Tool, error)

ReadOnlyTools builds the Phase-0 tool set, scoped to root (the worktree): list_dir + read_file (both confined to root), plus the offload_* tools when an offloader is wired. It registers NO write/shell/network tool — P0 is read-only by construction; broader capability is gated to later phases behind the cage.

Containment is OS-ENFORCED via os.Root: every file access goes through a root handle that refuses to escape — `..`, absolute paths, AND reparse points (symlinks / Windows directory junctions) are all rejected by the kernel-level openat-style traversal, and it FAILS CLOSED (any resolution error => the tool errors, never a silent fall-through). This replaces the earlier hand-rolled EvalSymlinks check, which a fresh-context review proved bypassable by a non-privileged Windows junction.

func ReadOnlyToolsWithLanes added in v0.206.0

func ReadOnlyToolsWithLanes(root string, offload OffloadFunc, npu NPUFunc, lanes []AccelLane) ([]Tool, error)

ReadOnlyToolsWithLanes is ReadOnlyTools with the box's accelerator lanes (Coral design D5). When lanes are given they are the accelerator surface — every device in config order, the shared-name rule applied — and `npu` is ignored; a nil lane list keeps the pre-Coral behaviour (the Hailo lane alone via npu) so every existing caller and test is unchanged.

func RunTools added in v0.21.1

func RunTools(pol *Policy, worktree, scratch string) []Tool

RunTools builds the C7b `run` tool: it runs an ALLOWLISTED program DIRECTLY (no shell) inside the OS sandbox — Argv = [command, args...], never /bin/sh -c, so the executable allowlist is a meaningful control. It is registered only when the caller opts in (--allow-run) AND sandbox.Available() is true; it is gated AGAIN at runtime by the deny→ask→allow broker (audited). worktree is the RW working directory; scratch is a RW temp dir.

func SearchTool added in v0.21.1

func SearchTool(root string) (Tool, error)

SearchTool builds the search_files tool, scoped to root (the worktree). It is read-only and registered alongside list_dir / read_file.

func SearchTools added in v0.21.1

func SearchTools(pol *Policy) []Tool

SearchTools builds the web_search tool. Registered only when the search capability is enabled (which also allowlists the DuckDuckGo host).

func ShellTools

func ShellTools(pol *Policy, worktree, scratch string) []Tool

ShellTools builds the run_shell tool: it executes an arbitrary /bin/sh command line inside the LINUX OS cage (no network, filesystem confined to the worktree (RW) + scratch, dangerous syscalls blocked, i386 ABI closed). run_shell is LINUX-ONLY — the builder grants it only on Linux (an arbitrary command line makes an executable allowlist meaningless, so on Windows the restricted `run` tool is used instead). It is registered only when the caller opts in AND the Linux cage is available; it is gated AGAIN at runtime by the deny→ask→allow broker, which audits every command. worktree is the RW working directory; scratch is a RW temp dir.

func WriteTools

func WriteTools(worktreeRoot string, pol *Policy) ([]Tool, error)

WriteTools builds the Phase-2 MUTATING tools (write_file, delete_file), confined to worktreeRoot via os.Root (the same kernel-enforced, fail-closed, reparse-safe containment used for reads) AND gated by the deny→ask→allow policy broker (the cage). Every mutation is brokered + audited; a non-Allow decision returns a "NOT performed" tool result (defer-not-crash) — the file is untouched and the model can react. These tools are registered ONLY when the caller opts into write capability; P0/P1 stay read-only.

func WriteToolsLimited added in v0.206.0

func WriteToolsLimited(worktreeRoot string, pol *Policy, limit *WriteLimit) ([]Tool, error)

WriteToolsLimited is WriteTools with a per-run byte/file ceiling (the D-06 delegation write door). A nil limit is exactly WriteTools — the operator own CLI worktree keeps the uncapped behaviour it has always had.

The limit is consulted AFTER the broker and immediately BEFORE the bytes are written, so a refusal reads to the model like any other "NOT performed" and the world is untouched. Deliberately not before the broker: a policy denial is the more precise reason, and spending it on a budget message would lose it.

type ToolCall

type ToolCall struct {
	ID   string
	Name string
	Args string // raw JSON arguments
	// contains filtered or unexported fields
}

ToolCall is one tool invocation the model requested.

type ToolSpec

type ToolSpec struct {
	Name        string
	Description string
	Schema      json.RawMessage
}

ToolSpec is the declarative surface advertised to the model.

type VerifyReport added in v0.206.0

type VerifyReport struct {
	Runs      int          `json:"runs"`      // chained runs seen
	Chained   int          `json:"chained"`   // chained rows (run_end rows included)
	Unchained int          `json:"unchained"` // rows written with the chain off
	Open      []string     `json:"open"`      // runs with no run_end (a crash, or a removed tail)
	Late      []string     `json:"late"`      // runs with chained rows after their run_end (an abandoned tool)
	Breaks    []ChainBreak `json:"breaks"`    // the first break of each broken run
}

VerifyReport is what VerifyAuditFile found.

func VerifyAuditFile added in v0.206.0

func VerifyAuditFile(path string) (VerifyReport, error)

VerifyAuditFile checks every chained run in an audit trail: seq runs 1, 2, 3 … without a gap, each row's prev_sha256 is the hash of the run's previous row as written, and the run_end's count and head match the rows before it. An edit, a deletion or a reorder inside a run breaks the chain at the first row after it; only the first break of each run is reported (later rows of a broken run cannot be judged). A row that still chains after its run's run_end is LATE (a tool goroutine abandoned at a timeout can write after the door closed the run), not broken. NOT detectable, by design of an unkeyed per-run chain: a cut tail together with its run_end (reported OPEN, like a crash; `verify --strict` fails open runs), a whole run removed, edits to a run_end's other fields, and a re-chained edit. Unchained rows are counted, not judged.

type WriteLimit added in v0.206.0

type WriteLimit struct {
	// contains filtered or unexported fields
}

WriteLimit is the per-run ceiling on a delegated write door: how many distinct files one contract may touch and how many bytes it may write in total (register D-06). It is enforced at the TOOL, before the bytes reach the disk, so a seat that runs away is told "NOT performed" and can correct — a cap discovered only after the run is a cap the node already paid for.

The delegation door also re-counts the finished write set against the same numbers. Two enforcement points on purpose: this one bounds the node's disk and memory while the loop runs; the second one bounds what crosses the wire, and neither can be the other's proof.

A nil *WriteLimit admits everything. That is the CLI door (local-agent --allow-write), which is an operator at a keyboard with their own worktree and has never had a byte cap; giving it one here would be an unannounced behaviour change to a shipped tool.

func NewWriteLimit added in v0.206.0

func NewWriteLimit(maxFiles, maxBytes int) *WriteLimit

NewWriteLimit builds a limit. Non-positive bounds are treated as "no bound of that kind" rather than "nothing may be written": a zero ceiling that silently refused every write would read in the logs exactly like a broken seat.

func (*WriteLimit) Admit added in v0.206.0

func (l *WriteLimit) Admit(rel string, n int) string

Admit reserves a write of n bytes to rel (a worktree-relative path) and returns the refusal reason, or "" when the write may proceed. The reservation is made BEFORE the write and is NOT released if the write then fails on IO: the accounting is deliberately conservative, because the alternative — a refund path — is a second place for a runaway to slip through.

Re-writing a file already touched does not spend another file slot, so an edit-then-fix cycle on one file stays within a one-file budget; its bytes are charged again, because they were written again.

func (*WriteLimit) Bytes added in v0.206.0

func (l *WriteLimit) Bytes() int

Bytes reports how many bytes have been admitted.

func (*WriteLimit) Files added in v0.206.0

func (l *WriteLimit) Files() int

Files reports how many distinct paths have been admitted.

func (*WriteLimit) Names added in v0.206.0

func (l *WriteLimit) Names() []string

Names lists the admitted paths, sorted.

Jump to

Keyboard shortcuts

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