core

package
v0.207.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package core holds the shared types used across the local-offload harness.

Index

Constants

View Source
const (
	// AgentWireSchemaVersion is the one contract shape this binary speaks.
	// Any other version is refused at decode — a mismatched peer must defer
	// loudly rather than half-understand a contract.
	AgentWireSchemaVersion = 1

	// AgentContextMaxBytes caps the TOTAL inline context (name+text bytes
	// across all docs) at 256 KiB. This is a TRANSPORT bound only (roast
	// delta 5) — whether the docs actually fit the remote seat's context
	// window is the placement gate's token arithmetic, not this cap.
	AgentContextMaxBytes = 256 << 10

	// AgentContextMaxDocs caps the doc count. Each doc becomes a file in a
	// job-scoped dir on the receiving node; a bounded count keeps that
	// materialization (and the sub-agent's read fan-out) bounded too.
	AgentContextMaxDocs = 16

	// AgentMaxStepsDefault/Cap: default 12, cap 12 for remote contracts
	// (roast delta 5 tightened the pre-roast cap of 24 — ctx honesty: at an
	// 8k seat there is no budget for 24 transcript-growing steps anyway).
	AgentMaxStepsDefault = 12
	AgentMaxStepsCap     = 12

	// AgentTimeoutSecDefault/Cap: the wall a remote contract is EXPECTED to fit
	// in, 300s default, 900s hard cap. It is not a deadline: since 0.131.0 the node
	// ends a run on a stall or on the liveness ceiling (AgentCeilingSecCap, below),
	// and holds only the structured re-pack to the wall, by a token budget and a
	// deadline check before each attempt, never by cutting a request in flight.
	AgentTimeoutSecDefault = 300
	AgentTimeoutSecCap     = 900

	// AgentCeilingSecCap (0.131.0, liveness walls) bounds the SAFETY ceiling a
	// node runs a contract under. Since 0.131.0 the wall above is the
	// EXPECTATION the node reports as wall_sec; what ends a run is a STALL (no
	// progress inside the seat's dynamic allowance) or this ceiling —
	// max(3 x estimate, 2 x wall, 1800 s), never above 4 h. A token-bounded
	// loop (max_steps x max_tokens + final + re-pack) at 1 tok/s ends before it.
	AgentCeilingSecCap   = 14400
	AgentCeilingSecFloor = 1800

	// AgentAdmissionSecDefault is the node's default ADMISSION budget — the
	// window a contract may spend at the cordon, in the llama-swap pre-flight,
	// in the seat's cold-load warm-up and in the coherence probe BEFORE its
	// wall starts (pipeline.admissionBudget; 300 s since 0.115.11, because a
	// vLLM seat takes 125–250 s to load plus a Triton JIT on its first
	// completion).
	//
	// It lives in core, and not only in the pipeline, because the DELEGATOR
	// has to allow for it too (register D-116): a node stamps `running` the
	// moment it claims a job — admission included — so an auto contract's poll
	// clock, which starts at dispatch, must cover admission + wall or it
	// abandons a job on a cold seat while the node is still inside its own
	// wall. internal/delegate cannot import internal/pipeline (the pipeline
	// imports the delegator), so the number is defined once, here, and read by
	// both sides.
	AgentAdmissionSecDefault = 300

	// --- The write door (register D-06). Fixed ceilings, NOT contract fields.
	// A caller cannot raise them (that is the point of a door) and does not
	// need to lower them: `diff_max_files:<n>` already expresses "this leg may
	// touch one file", and two knobs for one job is how they drift apart.
	//
	// AgentWriteMaxFiles caps the distinct paths one contract may touch. Eight
	// is a small implementation leg — a file, its test, and room to be wrong —
	// and anything bigger is a leg that should have been split before it was
	// handed to a 4B.
	AgentWriteMaxFiles = 8
	// AgentWriteMaxBytes caps the TOTAL bytes a contract may write. Generous
	// for an edit and nowhere near enough to matter to the node's disk.
	AgentWriteMaxBytes = 64 << 10
	// AgentWriteDiffMaxBytes caps the rendered unified diff that crosses back.
	// Larger than the write cap because a diff carries context lines and both
	// sides of every change; a diff past this is REFUSED, never truncated — a
	// truncated patch applies as silent damage.
	AgentWriteDiffMaxBytes = 192 << 10
)
View Source
const (
	// DeferClassAbstention: the model was asked, ran, and could not produce a
	// usable answer. The stack is healthy; the work is what failed.
	DeferClassAbstention = "abstention"
	// DeferClassBudget: a ceiling stopped it — step budget or wall clock. The
	// answer may exist behind a larger budget.
	DeferClassBudget = "budget"
	// DeferClassInfrastructure: something in the stack failed — endpoint
	// unreachable, agent build failed, transport died mid-run. Nothing about
	// the task was learned, and NO amount of retrying the same contract helps
	// until an operator fixes the box.
	DeferClassInfrastructure = "infrastructure"
	// DeferClassConfig: the node/contract combination can never work as
	// configured — no seat resolvable, the seat is not served, an unknown
	// profile. Also an operator fix, but of config rather than of a service.
	DeferClassConfig = "config"
	// DeferClassContract: the CALLER'S CONTRACT is what cannot be placed or
	// run, on any node, however healthy the fleet is — no output_schema for a
	// remote placement, a contract already past the origin hop, a token
	// estimate no advertised ceiling can hold. Split out of `config` because
	// `config` counts as a broken stack (delegate.BrokenStackDefer): a caller
	// mistake was exiting non-zero and telling the delegating model that a node
	// was down. The fix belongs to whoever wrote the contract, and it is one
	// they can make without touching a box.
	DeferClassContract = "contract"
	// DeferClassCapacity (0.113.18): every node that could run the contract was
	// full for as long as the delegator was willing to wait (agent_placement_
	// wait_sec), or the contract was SHEDDABLE (priority -1) and no node had an
	// idle slot to give it. The fleet is healthy and the contract is sound —
	// it was simply not this contract's turn. Re-running it later is the fix;
	// no box and no contract needs touching, so it is not a broken stack
	// (delegate.BrokenStackDefer) and not a budget the seat ran out of.
	DeferClassCapacity = "capacity"
	// DeferClassWrite (0.122.0, register D-06): the contract asked for the
	// WRITE door and this node will not open it — `agent_allow_write` is false
	// here, or the finished write set broke a door cap. Neither a broken stack
	// (nothing is wrong with the box) nor an unplaceable contract (another node
	// may well have opted in), so it is its own class: the fix is an opt-in on
	// a node or a smaller change, and re-placing the contract is the right
	// delegator reflex.
	DeferClassWrite = "write"
)

Defer classes: WHY a defer happened, in the four kinds that call for different operator action. The reason string is prose for a human; the class is what a delegator, a dashboard, or an exit code can branch on — without it "the model produced the wrong shape" and "llama-swap is down" arrive as the same quiet green defer, and a broken node reads as a working one.

View Source
const (
	RepackFailedReason = "structured re-pack "
	SchemaFailedReason = "output failed schema"
	// RepackCanceledReason prefixes the defer of a re-pack the CALLER's context
	// ended (the delegator abandoned the poll, the node is shutting down). The
	// answer is intact but nobody is waiting for the object, so the delegator
	// never rescues it, whether or not the node flagged it as a schema miss.
	RepackCanceledReason = "canceled during the structured re-pack"
)

The reason prefixes of a FINISHED loop whose structured re-pack failed (register C-66, PR-4). The executing node writes them (pipeline.runAgentTask: "structured re-pack unreachable: ...", "structured re-pack attempt 3/3 cut by ...", "output failed schema: ...") and a delegator that meets a node which does not yet publish AgentWireResult.SchemaMiss recognizes the shape from them (delegate.SchemaMissRescuable), so constants and not sentences typed twice.

View Source
const (
	BandSheddable = -1
	BandNormal    = 0
	BandUrgent    = 1
)

Scheduling bands (0.113.18) — the delegator stamps one on every dispatch (`priority` in the fleet envelope) and the node's job store orders its backlog by it. Shared here because both sides must agree on the vocabulary and neither package may import the other.

BandSheddable (-1)  measurement / gate traffic: admitted only into an idle
                    execution slot, claimed after band 0, shed when no node
                    is idle; ages into band 0 after 60 s in a backlog.
BandNormal (0)      production digests, reviews, research — the default and
                    what a pre-0.113.18 delegator sends.
BandUrgent (+1)     reserved for an interactive caller; claimed first.
View Source
const (
	AskerHeader    = "X-Offload-Asker"
	PairCardHeader = "X-Offload-Pair-Card"
	PairCardNode   = "node"
	// AskerMaxLen bounds the asker name a node accepts: the value is untrusted, is stored on a ledger row
	// and rides a PAIR card's requester text.
	AskerMaxLen = 64
)

Attribution headers (PAIR routing fixes, D7/D11). Both ride the request that creates work on a fleet node and are ignored by a node that predates them, so a mixed-version fleet behaves as before.

AskerHeader     who asked: the asker's PAIR member name when its emitter is enabled and resolves, else
                its short lowercase hostname. The node records it on its ledger row (Requester).
PairCardHeader  PairCardNode, sent ONLY when the asker will not card the job itself (its PAIR emitter
                is not enabled): the serving node then emits the card. An asker that sends nothing
                (every older build) keeps today's behaviour, so a job is never carded twice.
View Source
const (
	OriginHeader   = "X-Offload-Origin"
	RunClassHeader = "X-Offload-Run-Class"
)

Origin headers (register D-101, ADR 0087). Like the attribution headers above they ride the request that creates work on a fleet node, are sent only when non-empty, and are ignored by a node that predates them.

OriginHeader    the asker's session label (ledger.CleanOrigin: printable ASCII, at most 96 bytes, else none).
                The node stamps it on its own ledger row as origin_session.
RunClassHeader  the asker's run class (ledger.CleanClass: a short [a-z0-9_-] token; "production" is never sent).
                The node stamps it as run_class, and only for a request it can authenticate.
View Source
const (
	MarginScaleMatched = "matched"
	MarginScaleFull    = "full"
)

The two decision-margin scales (register D-130). A row's margin means nothing without its scale: MarginScaleMatched normalises over matched class tokens only (historic, ~10x higher), MarginScaleFull over every alternative at the decision position. An EMPTY scale on a stored row predates the flag and reads as matched.

View Source
const (
	ErrClassGPUBusy     = "gpu_busy"
	ErrClassGPUQueued   = "gpu_queued"
	ErrClassComposeBusy = "compose_busy"
)

The err_class values of a call that did not run because ANOTHER job held what it needed: a media call that waited its window and left a place in line (gpu_queued, the answer carries a waiter_token), a call that waited and left none (gpu_busy), and a composition that waited its window for the process's one compose slot (compose_busy: the slot is not a GPU card, a composition is CPU-class, but the call is in the same position, nothing ran and the answer says to call again). All three are congestion, not failure (register C-89: "a busy card is a place in line"), and the PAIR card of such a call closes accordingly (pairworkloads.cardOutcome). The producers are in internal/pipeline (deferForLease, runVisionGen, runTranscribe, runComposeVideo) and main.go's image batch.

View Source
const AccelImageCap = 8 << 20

AccelImageCap bounds an image shipped inside an accel job, both directions.

View Source
const AgentEnvRulesMinObservationTokens = 64

AgentEnvRulesMinObservationTokens is the floor for MaxObservationTokens: below ~64 tokens (256 chars) the head+tail cut has no room for its elision marker and degrades to a silent head-only hard cut — a truncated result the model cannot tell was truncated is worse than no cap.

View Source
const AgentSetupActionsMax = 8

AgentSetupActionsMax bounds a contract's replay list. Eight is more than a grounded contract needs (one read per context doc, ≤ AgentContextMaxDocs would be 16 — but a contract that needs sixteen pre-reads is asking the seat to hold sixteen documents at once, which no small seat does well).

View Source
const AgentSetupArgsMaxBytes = 4 << 10

AgentSetupArgsMaxBytes bounds one action's argument object on the wire.

View Source
const AgentTraceNoteMax = 160

AgentTraceNoteMax bounds AgentTraceStep.Note.

View Source
const AnswerWrapperMax = 200

AnswerWrapperMax is the most prose (fences, "Here is the result:", a closing line) that may surround a JSON object for it to count as the answer when the object is under half of the text.

View Source
const CallDeadlineReasonPrefix = "call deadline reached"

CallDeadlineReasonPrefix opens the reason of every subtask a delegation call's whole-call deadline cut (ADR 0065, register C-67): "call deadline reached; N unfinished — this subtask ...". It is a STABLE key: the delegator publishes it on the wire, the ledger and the corpus, and readers that must not mistake such a row for a seat's own failure (the rigger, a per-call wall readback) match on it. One constant, so no reader keeps a private copy of the words.

View Source
const ContextClassLong = "long"

ContextClassLong is the one non-default context_class a contract may carry: "this needs a long window", said explicitly by the caller. Named so the MCP doors' InputSchema, the placement table and ValidateWithCap agree on the literal instead of each spelling it.

View Source
const ErrClassBadInput = "bad_input"

ErrClassBadInput is the err_class of a call whose own input cannot be processed as given: an audio file with no audio stream (F21), a picture that does not load. Nothing is wrong with the stack or the contract, and no other node or retry changes the answer; the file does. The ledger files it under the reason code bad_input.

View Source
const ErrClassFFmpegUnavailable = "ffmpeg_unavailable"

ErrClassFFmpegUnavailable is the err_class of a call that could not run because ffmpeg could not be run at all: not on the PATH, or the configured path is wrong. The stack is at fault, not the caller's file. The ledger files it under the reason code config (the same class the media runners already write).

View Source
const ErrClassGPULeaseUnavailable = "gpu_lease_unavailable"

ErrClassGPULeaseUnavailable is the err_class of a media call that did not run because its lease could not be taken for a reason that is not another job's hold: a lease location the node cannot use, or a host-RAM need that no state of the host admits. Nothing ran (the only producer, internal/pipeline deferForLease, sees acquisition errors and nothing else), so a router that placed the call on a node with it may place the call elsewhere. It is not CardHeld: no other job is in the way, so the call has no place in line to wait for.

View Source
const ErrClassNoNodeConfigured = "no_node_configured"

ErrClassNoNodeConfigured is the err_class of a media call the delegator could not place because EVERY node of its roster was left out for a configuration fact: the node does not serve the task, a route the call needs is not configured on it, it cannot carry refine=false, or the tailnet guard refused its roster entry. Nothing ran and waiting does not change any of it, so it is not CardHeld (no place in line is coming); a roster with one node that is merely busy, text-leased or out of reach never gets it, because that node may take the call later. The only producer is internal/mediaremote (pickNodeFor).

View Source
const FeatEscalationUnavailable = "escalation_unavailable"

FeatEscalationUnavailable is the Feat marker written when the confidence gate is skipped because the cascade has no escalation tier (see the Feat comment on Meta).

View Source
const ForcedFinalToolCallReason = "forced final step: no tools were offered and the answer was asked for"

ForcedFinalToolCallReason opens the stop note, and so sits inside the defer reason ("step budget exhausted (N steps): forced final step: ..."), of a run whose forced final step (the last step: no tools offered, the answer asked for) was answered with a tool call, written as text or parsed, even after the seat was re-asked once with that quoted. It is a constant and not a sentence typed in three places because the loop writes it, the rigger reads it to put the shape on its own axis instead of "a task too large for one contract", and the delegator reads it to give the contract another seat (delegate.FinalToolCallDefer).

View Source
const IncoherentSeatReason = "seat incoherent at warm: "

IncoherentSeatReason prefixes the defer a broken seat earns at admission (register D-118). It is a CONSTANT and not a sentence typed twice: the executing node writes the reason with it (pipeline.runAgentTask, mcpserver.handleAgentRun) and the delegator matches on it to decide the contract is worth one retry on another node (delegate.IncoherentSeatDefer), so producer and consumer cannot drift.

It stays a reason prefix rather than a new defer class on purpose: the class is `infrastructure` because that is exactly what it is — the stack under this seat is broken and no amount of re-asking it helps — and a new class would read as an unknown one on every pre-D-118 node in a mixed-version fleet.

View Source
const RootGoneReason = "workspace root unavailable: "

RootGoneReason prefixes the defer a run files when its own file tools, or its write door, could not open its workspace root (register C-79): the directory the seat reads (the contract's context documents, or the write door's tree) was no longer there, because a sweep, a cleaner or an operator took it, or the disk under it failed, and every file tool answered "workspace root unavailable". The fault is the box's, never the contract's or the model's, so the class is `infrastructure`. Before it the seat was left to write a final answer from nothing ("I could not read the file") and the run was scored as a failed verification.

Like SeatDownReason it is a CONSTANT and a reason prefix, not a new defer class, so a node without it still reads as a plain infrastructure defer in a mixed-version fleet. The loop's own tool error opens with the same words (agent.RootGoneError), the executing node writes the defer with it (pipeline.runAgentTask) and the delegator matches on it (delegate.RootGoneDefer) to give the contract a second placement, which materializes a root of its own.

View Source
const SeatDownReason = "seat down: "

SeatDownReason prefixes the defer a run earns when its seat's engine went down under it and did not come back inside the run's recovery wait (ADR 0066, register C-72): the engine hung with work outstanding, or died and llama-swap no longer serves the seat (gone from /running, restarting, refusing reads). Like IncoherentSeatReason it is a CONSTANT and a reason prefix, not a new defer class — the class stays `infrastructure`, because a class a node without ADR 0066 does not know would read as unknown in a mixed-version fleet — and the executing node writes the reason with it while the delegator matches on it (delegate.SeatDownDefer) to give the contract a second placement on ANOTHER node. A node-filed defer is an observed terminal, so re-placing it cannot produce a duplicate run.

View Source
const SeatNotServingReason = "seat not serving: "

SeatNotServingReason prefixes the defer a run files when llama-swap answered a 5xx for its seat and the answer outlived the contention budget while the seat was not known to be down (ADR 0066): a start that failed, a health check that timed out. It is NOT contention — `seat contended: ` is a 429 only — so operators grep and tools count it separately (scripts/parallel-sessions-gate.ps1 does).

View Source
const SeatWarmFailedReason = "seat warm-up failed: "

SeatWarmFailedReason prefixes the defer a seat earns when its admission warm-up is refused with a server error and there is positive evidence the seat never came up (register C-76, agent_warm_failure_defer): llama-swap could not start the seat's process (an engine that exits at start answers 500 "upstream command exited prematurely"). The class is `infrastructure`, and a constant rather than a sentence typed twice so the delegator keys on it (delegate.SeatWarmFailedDefer: one retry on another node, the case another node serves) without matching prose.

View Source
const TenantHeader = "X-Offload-Tenant"

TenantHeader carries the delegator's tenant id on a dispatch (0.113.18).

Variables

View Source
var ErrAgentEnvRules = errors.New("agent_env_rules")

ErrAgentEnvRules wraps every Validate failure so a door can classify it (a fleet node defers by CONFIG class: the table is the box's, not the contract's) without matching on message text.

View Source
var ErrAgentSetupActions = errors.New("agent contract: setup_actions")

ErrAgentSetupActions wraps every setup-action validation failure so a door can classify it by identity (a contract-class defer: the contract, not the box, is what needs fixing).

View Source
var ErrNoMediaPlace = errors.New("this machine keeps no place in its line for the call")

ErrNoMediaPlace says the box keeps no place in line for this call: a host that does not lease cards keeps no tokens, a call that runs under a lease it inherited has a card chosen for it, a card table that would not read or an allocator that finds nothing to queue on gives it no card to hold a place on. The ticket then waits without local seniority and says so in its answer; it is never an error for the call.

Functions

func AcceptedFields added in v0.206.0

func AcceptedFields(acceptance []string) []string

AcceptedFields returns the schema fields the acceptance checks read (min_items and nonempty; the any-of nonempty reads every name it lists; a contains, regex or not_contains qualified @field=<name>: reads the one field it names), in check order, without repeats. Checks that do not parse, and checks that read no field (an unqualified contains, regex or not_contains, diff_*, and the @answer: and @grounded: qualifiers), are skipped.

func AnswerList added in v0.206.0

func AnswerList(text string) ([]any, bool)

AnswerList decodes the JSON array a final answer IS: the whole text, or the one fenced block of it when the text around the fence is a short lead-in, as a list. It is stricter than AnswerObject on purpose: an array of anything is also how prose writes a footnote or an example, so the array must BE the answer (nothing but a fence and a short lead-in around it) before its items count, and only items that can hold a finding do (an object, a text, a list), never a number.

func AnswerObject added in v0.206.0

func AnswerObject(text string) (map[string]any, bool)

AnswerObject decodes the JSON object a final answer IS: the text trimmed to its outermost {...} span, with fences and a short preamble or tail around it allowed. The object must BE the answer and not an aside inside it, so a code sample in a long prose answer is not one (the same rule a direct structured answer is taken by). ok is false for anything else.

func CardHeld added in v0.206.0

func CardHeld(errClass string) bool

CardHeld reports whether errClass says the call was held back by another job's hold on what it needed (the GPU card, or a composition's one slot). It decides by class and never by reason text: the reason is a sentence for a person.

func ClampBand added in v0.206.0

func ClampBand(b int) int

ClampBand folds any integer into the three bands.

func CloseOnPanic added in v0.206.0

func CloseOnPanic(h RemoteAttribution)

CloseOnPanic is deferred right after BeginRemote (defer core.CloseOnPanic(h)): a lane that panics after it opened the call's card (in the dispatch, the poll or the fetch) would leave the card queued and the call without its row, until the orphan sweep of a later process closes it "harness process exited". The panic closes the call as a deferred one carrying the panic's text, then goes on: the door dies of it, and the card says what happened. On a normal return it does nothing, because every return of a lane has already finished or discarded the handle, and a second Finish is a no-op. It is the same close pipeline.closeCall gives a local call. recover works only in the deferred function itself, which is why this is a function to defer and not a helper to call from one.

func ContentItems added in v0.206.0

func ContentItems(list []any) int

ContentItems counts the items of a list that hold something a reader could call content: an empty string, null, false, zero, or an empty list or object is the schema's empty value.

func DropPlace added in v0.206.0

func DropPlace(runner any, token string)

DropPlace forgets the place token names on runner.

func IsLedgerMarker added in v0.207.0

func IsLedgerMarker(key string) bool

IsLedgerMarker reports whether a Feat key is a marker rather than a routing feature.

func KeepPlace added in v0.206.0

func KeepPlace(runner any, token string) bool

KeepPlace refreshes the place token names on runner; false when runner keeps none or the place is gone.

func ListsEmptied added in v0.206.0

func ListsEmptied(structured []byte, schema map[string]any, answer string) string

ListsEmptied says so when a structured object lost the lists its answer held: "" when it did not, else one finding per emptied list, each ready to stand alone in a defer reason or an acceptance failure. schema is the contract's output schema (only its array properties are read, along nested object properties).

The comparison is by key. A list the schema asks for and the answer also has under the same path is compared with that list and nothing else: an answer that says `"stale": []` has nothing to lose, whatever else it lists. Only when the answer shares no list path with the schema do its lists under paths the schema does not define count (at any depth of nested objects, and an answer that is itself a list counts as one), and then the object must hold SOME item in the lists the schema asks for. A legitimately empty answer that says so with the schema's own key therefore passes. One that lists what it checked under a key of its own does not, and that false refusal costs an honest defer and a re-placement, not a wrong success (see the header for what keeps it so).

func ListsTrimmed added in v0.206.0

func ListsTrimmed(structured []byte, schema map[string]any, answer string) string

ListsTrimmed says how many list items a structured object kept when it kept fewer than its answer held ("" when it kept them all, or when the answer is no object to count): a schema's maxItems the answer broke, or a seat that dropped items. It is a note for the result, not a reason to reject: the object is faithful as far as it goes, and the answer rides beside it.

func MarginScaleOf added in v0.206.0

func MarginScaleOf(fullDenominator bool) string

MarginScaleOf names the scale a box emits under the full-denominator flag.

func MarginScaleOfRow added in v0.206.0

func MarginScaleOfRow(rowScale string) string

MarginScaleOfRow reads a STORED row's scale, where empty means the row was written before the flag existed and is therefore on the matched scale.

func MarkPlace added in v0.206.0

func MarkPlace(runner any, token string, hostRAMOnly bool) bool

MarkPlace records on runner whether the place token names waits only on host RAM; false when runner keeps no marks.

func MarkWorking added in v0.206.0

func MarkWorking(ctx context.Context)

MarkWorking tells whoever tracks this call that its real work has started. A context without a mark ignores it.

func NameNode added in v0.206.0

func NameNode(h RemoteAttribution, base, nodeID, fleetJobID string)

NameNode tells h which node the call ran on, when h can be told. A handle that cannot (the no-op handle, a test double) ignores it, and a handle that was already dispatched keeps the node it was dispatched to.

func ProjectFields

func ProjectFields(data json.RawMessage, keys []string) json.RawMessage

ProjectFields reduces the JSON object `data` to only the given top-level keys (the harness's fastcontext citation pattern: let the caller pull only the fields it needs and leave the verbose rest on disk / out of context). It is best-effort and never errors:

  • an empty key list returns data unchanged;
  • if data is not a JSON object (e.g. an array) or is invalid JSON, it is returned unchanged (projection does not apply);
  • keys absent from data are skipped (no error, no null).

Nested/dotted-path and array-element projection are a documented follow-up; top-level selection covers the common case (drop segments[], keep gist, etc.).

func ReportProgress added in v0.206.0

func ReportProgress(ctx context.Context, p LiveProgress)

ReportProgress hands p to the installed sink, if any.

func ReportWall added in v0.206.0

func ReportWall(ctx context.Context, sec int)

ReportWall publishes the wall (in seconds) the run is executing under. A context with no reporter, or a non-positive wall, does nothing.

func RequireAcceptanceFields added in v0.206.0

func RequireAcceptanceFields(schema json.RawMessage, acceptance []string) json.RawMessage

RequireAcceptanceFields is RequireFields over the fields the acceptance checks name.

func RequireFields added in v0.206.0

func RequireFields(schema json.RawMessage, fields []string) json.RawMessage

RequireFields returns schema with every listed field added to its `required` list, in the order given after whatever the schema already required (the gbnf builder reads `required` first for field order, so the caller's own order is never disturbed). A field the schema does not declare under `properties` is left out: it could never be produced, and requiring it would turn an acceptance failure into an unsatisfiable schema. When nothing needs adding, or the schema is not an object with a properties map, the input is returned byte for byte. The rest of the schema is carried through untouched; only the top-level key order of a changed schema is normalized.

func SanitizeAsker added in v0.206.0

func SanitizeAsker(s string) string

SanitizeAsker reduces an untrusted asker name to printable text of at most AskerMaxLen characters: control and non-printing characters are dropped, runs of whitespace fold to one space. "" = none.

func SchemaTypeIs added in v0.206.0

func SchemaTypeIs(spec map[string]any, typ string) bool

SchemaTypeIs reports whether a schema spec declares the type, either as the string form ("array") or among a list of types (["array","null"], how a nullable list is written).

func SelectKeys

func SelectKeys(csv string) []string

SelectKeys parses a comma-separated --select value into a clean key list. Whitespace is trimmed and empty entries dropped; "" yields nil (no selection).

func ValidateAgentSetupActions added in v0.206.0

func ValidateAgentSetupActions(actions []AgentSetupAction) error

ValidateAgentSetupActions holds a replay list to the wire rules: count, tool-name shape (a bare identifier — the same characters a tool spec name carries; whitespace inside or around it is a bug, not a name), and a bounded JSON OBJECT per action (an array or scalar is rejected here, not discovered as a decoder error inside the tool on the node). Whether the tool EXISTS on the executing seat is a run-time fact (profiles narrow the set per box), so it is answered by the loop as an observation, never here.

func ValidateBrowseHosts added in v0.206.0

func ValidateBrowseHosts(allow bool, hosts []string) error

ValidateBrowseHosts holds a contract's browse grant to its envelope: with allow_browse, 1-32 bare host names (no scheme, port, path or wildcard); without it, no hosts at all (a host list that grants nothing is a caller mistake).

func ValidateContextClass added in v0.206.0

func ValidateContextClass(s string) error

ValidateContextClass accepts the closed vocabulary of the placement hint ("" or long). Shared by the contract validator and the MCP front doors so a caller that misspells it is told the same thing on every surface — a hint silently dropped would place a 200k-token contract on the default seat and fail it at the window, far from the typo.

func ValidateThinking added in v0.206.0

func ValidateThinking(s string) error

ValidateThinking accepts the closed vocabulary of the planner think-block policy ("" / auto / on / off, case-insensitive). Shared by the contract validator and the config loader so both doors refuse the same strings.

func ValidateWriteRoot added in v0.206.0

func ValidateWriteRoot(root string) error

ValidateWriteRoot holds a contract's write_root to a safe RELATIVE directory path. "" is the read-only default and always valid.

The rules are the strictest platform's, applied on every platform, for the same reason validDocName's are: a contract is a WIRE object validated on the delegator and again on a node that may be a different operating system, so a Linux-only check would accept a path the Windows node then resolves somewhere else. os.Root is the real containment; this is the layer that refuses the shapes whose DAMAGE is done before os.Root ever sees them (a caller believing it scoped a write to one directory when it did not).

func WithProgressReport added in v0.206.0

func WithProgressReport(ctx context.Context, fn func(LiveProgress)) context.Context

WithProgressReport installs the sink a lane reports its LiveProgress to — the fleet node's job record. Same shape as WithWallReport.

func WithWallReport added in v0.206.0

func WithWallReport(ctx context.Context, fn func(sec int)) context.Context

WithWallReport returns a context whose ReportWall calls fn. fn must be safe to call from the run's own goroutine and may be called more than once; the LAST value wins (a wall is stamped once today).

func WithWorkingMark added in v0.206.0

func WithWorkingMark(ctx context.Context, fn func()) context.Context

WithWorkingMark returns a context whose MarkWorking calls fn. fn must be safe to call more than once and from any goroutine.

Types

type AcceptanceCheck added in v0.206.0

type AcceptanceCheck struct {
	Kind AcceptanceKind
	Arg  string // substring, or field name for the field verbs (the authority qualifier is not part of it)
	N    int    // min_items threshold
	// Authority is the level of an authority-qualified contains:, regex: or
	// not_contains: check (acceptance_authority.go); AuthNone for every other check.
	Authority Authority
	// contains filtered or unexported fields
}

AcceptanceCheck is one parsed acceptance assertion. Construct via ParseAcceptanceCheck — a zero AcceptanceCheck fails every Eval.

func ParseAcceptanceCheck added in v0.206.0

func ParseAcceptanceCheck(s string) (AcceptanceCheck, error)

ParseAcceptanceCheck parses one DSL string. Unfalsifiable shapes are parse ERRORS, not no-ops: "contains:" matches everything and "min_items:f:0" can never fail, so accepting them would silently weaken the verifiability gate that Acceptance exists to enforce (a contract with only such checks would count as "verifiable" while verifying nothing).

func (AcceptanceCheck) Eval added in v0.206.0

func (c AcceptanceCheck) Eval(res AgentWireResult) (pass bool, reason string)

Eval runs the check against a result. reason is empty exactly when pass is true; on failure it names the check and what was observed, because these reasons surface verbatim in the delegator's merge decision and the delegation ledger — "failed" without a why is unactionable telemetry.

func (AcceptanceCheck) Fields added in v0.206.0

func (c AcceptanceCheck) Fields() []string

Fields returns the structured fields the check reads, in the order named: one for min_items and for a single-name nonempty, one per alternative for the any-of nonempty, one for a contains, regex or not_contains qualified @field=<name>:, and none for every verb that reads no field (an unqualified contains, regex or not_contains, the @answer: and @grounded: qualifiers, diff_*). Exposed so the schema helpers (AcceptedFields) read the check the way Eval does instead of splitting the argument a second time.

func (AcceptanceCheck) Grade added in v0.206.0

Grade runs the check against a result and the contract's context documents and returns pass, fail or unknown. An unqualified check is graded exactly as Eval grades it (so it is never unknown). A qualified check reads only the evidence its level names, and an empty or absent evidence set is unknown. docs is only read at the grounded level; Eval passes none, so a grounded check can never be closed by it.

func (AcceptanceCheck) Pattern added in v0.206.0

func (c AcceptanceCheck) Pattern() *regexp.Regexp

Pattern returns the compiled regex for an AccRegex check (nil for every other kind, and for a zero AcceptanceCheck). Exposed so consumers that analyze checks — the intake lint — reuse the parse-time compilation instead of recompiling, which would re-introduce a can-never-fail error branch whose correctness silently depends on staying dead.

type AcceptanceKind added in v0.206.0

type AcceptanceKind string

AcceptanceKind is the closed verb set of the v1 acceptance DSL.

const (
	AccContains    AcceptanceKind = "contains"
	AccNotContains AcceptanceKind = "not_contains"
	AccRegex       AcceptanceKind = "regex"
	AccMinItems    AcceptanceKind = "min_items"
	AccNonempty    AcceptanceKind = "nonempty"
	// The write-door verbs (0.122.0, register D-06) read the RESULT'S WRITE
	// SET — the paths the seat actually changed — not its prose. They are the
	// only acceptance a write contract can carry that a talkative seat cannot
	// satisfy by talking.
	AccDiffTouches  AcceptanceKind = "diff_touches"
	AccDiffMaxFiles AcceptanceKind = "diff_max_files"
)

type AcceptanceOutcome added in v0.206.0

type AcceptanceOutcome struct {
	Check     string    // the DSL string as written
	Verdict   Verdict   // pass, fail or unknown
	Authority Authority // the level the check demanded; AuthNone for an unqualified check
	Reason    string
}

AcceptanceOutcome is one graded check. Reason is empty exactly when Verdict is VerdictPass and always opens with the check itself, because failures are classified by that prefix.

type AgentCallRecord added in v0.206.0

type AgentCallRecord 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"`
	ForcedFinal      bool   `json:"forced_final,omitempty"`
	// Ms (0.115.21): the client-measured wall of the completion.
	Ms int64 `json:"ms,omitempty"`
	// Sampling (0.123.3, D-95b) is the EFFECTIVE decoding policy of this
	// completion ("temperature=0" for the default). A measurement that cannot
	// prove which sampling ran is not a measurement. Omitempty: a node that
	// predates the field reports none, never "the default".
	Sampling string `json:"sampling,omitempty"`
}

AgentCallRecord is one planner completion as the corpus keeps it (the wire projection of agent.CallRecord). No transcript bytes — counts only.

type AgentContract added in v0.206.0

type AgentContract struct {
	SchemaVersion int             `json:"schema_version"`          // AgentWireSchemaVersion
	Goal          string          `json:"goal"`                    // required, self-contained
	Context       []ContextDoc    `json:"context,omitempty"`       // inline docs, total ≤ the cap (AgentContextMaxBytes by default; ValidateWithCap for a composite box)
	OutputSchema  json.RawMessage `json:"output_schema,omitempty"` // JSON Schema for structured output (gbnf subset)
	Acceptance    []string        `json:"acceptance,omitempty"`    // AcceptanceCheck DSL strings, delegator-evaluated
	Profile       string          `json:"profile,omitempty"`       // agent profile name; default "research"-class read-only
	// Thinking (0.115.8) is the planner think-block policy for this contract:
	// "" / "auto" (think; an empty final is re-issued once with thinking off),
	// "off" (every planner call in non-thinking mode — grounded extraction on
	// a seat whose think block starves the answer), "on" (never send the
	// non-thinking kwarg). Overrides the executing node's `agent_thinking`.
	Thinking   string `json:"thinking,omitempty"`
	MaxSteps   int    `json:"max_steps,omitempty"`   // default AgentMaxStepsDefault, clamped to AgentMaxStepsCap
	TimeoutSec int    `json:"timeout_sec,omitempty"` // default AgentTimeoutSecDefault, clamped to AgentTimeoutSecCap
	Depth      int    `json:"depth"`                 // 0 = origin; ≥1 ⇒ delegate tool NEVER registered
	// TimeoutAuto (register D-03, 0.126.0) marks a TimeoutSec the CALLER never
	// set: intake stamped the wire default and the executing node may size the
	// wall from its seat's measured rate instead, anywhere inside
	// [AgentTimeoutSecDefault, AgentTimeoutSecCap], reporting what it ran under
	// as AgentWireResult.WallSec. Two defaults used to turn "unset" into a
	// legitimate-looking 300 before anything downstream could tell it from a
	// caller who asked for 300 (intake.go and DecodeAgentContract), which is why
	// this is a wire field and not a sentinel value. Never set alongside a
	// caller's own timeout_sec; never set on a retry (its wall is what is left).
	// An older node ignores it and runs the default, exactly as before.
	TimeoutAuto bool `json:"timeout_auto,omitempty"`
	// SetupActions (agentsetup.go, 0.113.24): tool calls the loop replays before
	// the model's first turn; ≤ AgentSetupActionsMax, charged to the wall and
	// never to max_steps. Optional; a node one release behind ignores it (the
	// decoder keeps unknown fields) and reports no setup_ran.
	SetupActions []AgentSetupAction `json:"setup_actions,omitempty"`
	// WriteRoot (0.122.0, register D-06) opens the WRITE door: the directory,
	// RELATIVE to the run read root, that the seat may create and change files
	// under. "" (the default and every pre-0.119 contract) is read-only, with
	// no write tool registered at all. "." is the whole read root.
	//
	// Relative, not absolute, on purpose. The contract is self-contained: the
	// node materializes its OWN copy of the inline context docs and has never
	// seen the delegator filesystem, so an absolute delegator-box path would
	// name nothing on the executing node. A relative root resolves to an
	// absolute directory inside the read root on whichever box runs it — the
	// containment the door needs — and it is enforced by os.Root at the
	// syscall layer rather than by comparing two path strings.
	//
	// The write set is NEVER applied by the harness. It comes back as a
	// unified diff (AgentWireResult.Diff) for the caller to review and apply.
	WriteRoot string `json:"write_root,omitempty"`
	// AllowBrowse (0.141.0, ADR 0060) asks for the agent `browse` tool: drive the
	// executing node's OWN operator browser through its browse lane. BrowseHosts
	// is the run's host allowlist and is REQUIRED with it (an agent door is judged
	// unattended for browse). A node refuses the contract at ack unless it opted
	// in (agent_allow_browse) and configured the lane; the delegation door admits
	// it only on route "local".
	AllowBrowse bool     `json:"allow_browse,omitempty"`
	BrowseHosts []string `json:"browse_hosts,omitempty"`
	// ContextClass (ADR 0052, 0.116.0) is the caller's explicit ask for a
	// long-window seat: "" (the placement table decides from the token
	// estimate) or ContextClassLong. It is an INPUT to placement, never a seat
	// name — on a composite box "long" enters the triple layer's 262k seat
	// under the feasibility check and the display-card guards; on a plain box
	// it is accepted and ignored, so one contract can go to any node. Closed
	// vocabulary: an unknown class would silently fall back to the default
	// layer and the caller would never learn its ask was misspelt.
	ContextClass string `json:"context_class,omitempty"`
	// Layer is the layer this contract runs on: the one the DELEGATOR placed it
	// on when it chose a composite remote node, or the one the CALLER named on
	// the door (register A-100: a box's second layer whose agent seat is not
	// the planner default, reachable by name only). R5: ONE placement rule —
	// a caller-named layer is decided FOR that layer on the delegator (a node
	// that does not declare it is ineligible) and the node re-runs the same
	// decision with its OWN live readers, so the display-card guards are
	// evaluated where the card is. Empty on an unnamed local run and on a
	// dispatch to a single-layer node; a box that does not declare the named
	// layer defers by name rather than running on its planner seat.
	// Held to the layer-id shape that config.ValidateLayers enforces because
	// the node uses it as a seat lookup key, and a name that validates there
	// must always be dispatchable here.
	Layer string `json:"layer,omitempty"`
	// Door is the surface that admitted this contract (register A-102 (e)):
	// an MCP tool name (agent_delegate, offload_ask, offload_review_diff,
	// offload_research, agent_rig), a CLI command (cli:delegate,
	// cli:research) or fleet for a contract a node received with none.
	// Documentary: it travels on the wire so the executing node's ledger row
	// names the delegator's door, and it never routes anything.
	Door string `json:"door,omitempty"`
}

AgentContract is the versioned, self-contained delegation request (§S2). Self-contained means: everything the remote loop may read is INLINE in Context — the remote node never reaches back into the delegator's filesystem or session.

func DecodeAgentContract added in v0.206.0

func DecodeAgentContract(r io.Reader) (AgentContract, error)

DecodeAgentContract reads one contract from r, tolerating unknown fields (roast delta 4), refusing any schema_version but AgentWireSchemaVersion, clamping MaxSteps/TimeoutSec into their remote ceilings (roast delta 5), then running the full Validate at the default transport cap (AgentContextMaxBytes). Errors here are caller mistakes — the fleet server maps them to 400s at ACK time, so a malformed contract dies with a clear reason before any model loads. A node that admits more inline context than the default (a composite box, config.AgentContextCapBytes()) decodes through DecodeAgentContractWithCap — otherwise a contract the delegator admitted at its own cap is refused at the remote's ACK and the remote's long seat is unreachable over the wire.

func DecodeAgentContractWithCap added in v0.206.0

func DecodeAgentContractWithCap(r io.Reader, maxBytes int) (AgentContract, error)

DecodeAgentContractWithCap is DecodeAgentContract validating through ValidateWithCap(maxBytes) instead of the fixed default: same schema gate, same MaxSteps/TimeoutSec clamps, only the inline-context ceiling is the box's. A non-positive maxBytes falls back to the default cap exactly as ValidateWithCap does — an unset config never admits an unbounded context.

func (AgentContract) Validate added in v0.206.0

func (c AgentContract) Validate() error

Validate checks everything about a contract that does not depend on where it runs: required goal, depth sign, the closed context_class / layer vocabularies, context caps and doc-name hygiene, OutputSchema gbnf-compilability, and Acceptance DSL well-formedness. Both sides run it — the delegator before dispatch (fail before the network) and the node inside DecodeAgentContract (never trust the wire). It validates at the default transport cap (AgentContextMaxBytes); a box that admits more passes its own cap through ValidateWithCap.

func (AgentContract) ValidateWithCap added in v0.206.0

func (c AgentContract) ValidateWithCap(maxBytes int) error

ValidateWithCap is Validate with the inline-context cap chosen by the box (0.116.0). The cap is a parameter because it scales with the hardware: a composite box's config.AgentContextCapBytes() is min(2 MiB, largest layer seat window × 3), and at chars/3 a 256 KiB contract estimates ~87k tokens — a 163,840 window could never overflow, so behind the fixed constant both long seats would be dead code. Every other rule is box-independent and runs identically under both entry points. A non-positive maxBytes falls back to the default cap: tolerance is for vocabulary, never for resource ceilings, so a zero from an unset config must never admit an unbounded context.

type AgentEnvRules added in v0.206.0

type AgentEnvRules struct {
	// DenyTools removes these tools from what the model is offered — a
	// structural constraint (the spec is not sent), not a text refusal. Names
	// not among the enabled tools are ignored (narrow-only, like profiles).
	DenyTools []string `json:"deny_tools,omitempty"`
	// AllowTools, when non-empty, keeps ONLY these tools (everything else is
	// denied). It can never add a tool the capability flags / profile did not
	// enable. DenyTools wins over AllowTools on a conflict.
	AllowTools []string `json:"allow_tools,omitempty"`
	// MaxCallsPerTool caps how many times ONE named tool may EXECUTE in a run;
	// the N+1th call is blocked with a reason the model reads. Finer than the
	// loop's global same-name cap (max_same_tool), which stays in force.
	MaxCallsPerTool map[string]int `json:"max_calls_per_tool,omitempty"`
	// ArgLimits clamps NUMERIC arguments per tool: tool → argument → cap. An
	// argument above the cap is rewritten to the cap (the call still runs);
	// non-numeric or absent arguments are untouched. Typical: read_file.limit.
	ArgLimits map[string]map[string]float64 `json:"arg_limits,omitempty"`
	// MaxObservationTokens bounds ONE tool result before it enters the
	// transcript (chars ≈ tokens×4, the loop's own estimate), head+tail with
	// an elision marker — the per-seat version of the loop's window-derived
	// cap, for seats whose window is big but whose attention is not. Minimum
	// AgentEnvRulesMinObservationTokens; the loop-boundary cap still applies
	// after it, so the effective bound is the smaller of the two.
	MaxObservationTokens int `json:"max_observation_tokens,omitempty"`
	// ObservationStrip is a list of Go regexps removed from every tool result
	// (banners, cookie notices, progress bars, base64 blobs). Each is
	// validated at load; a pattern that fails to compile fails the config.
	ObservationStrip []string `json:"observation_strip,omitempty"`
	// RewriteError maps a raw tool ERROR (is_error results only) whose text
	// matches `match` to a short, model-readable `text`. First match wins.
	RewriteError []AgentErrorRewrite `json:"rewrite_error,omitempty"`
}

AgentEnvRules is the CLOSED vocabulary of environment rules a seat's agent loop runs under (config key `agent_env_rules`, per box / per fleet node; `local-agent --env-rules <file>` overrides it for a scratch validation).

The shape is envharness's (google-research/envharness, adopted 2026-09-07, item 7 of the operator order): three interceptors around every tool call — filter_action (may block or rewrite the call) → modify_transition (rewrites the result of an errored call) → filter_observation (strips and bounds what the model gets to read). What is deliberately NOT adopted is envharness's LLM-written rule code (`rules_code` executed in-process): a rule here is DATA — typed, validated at load, diffable, and testable — never generated code. The rigger (P3 of the same order) proposes changes to this table; an operator applies them.

This is a different table from the structural RISK rules (`--rules`, internal/agent/rules.go): those decide what the broker may let an effectful action DO to the world (deny/ask, tighten-only, security). These shape how a WEAK SEAT behaves inside the loop (what it may call, how often, how much of a result it reads). The two never overlap: a risk rule never rewrites an observation; an env rule never grants an effect.

Every field is additive and optional: a nil/zero table is byte-identical to the pre-key loop.

func (*AgentEnvRules) IsZero added in v0.206.0

func (r *AgentEnvRules) IsZero() bool

IsZero reports whether the table would change nothing.

func (*AgentEnvRules) Summary added in v0.206.0

func (r *AgentEnvRules) Summary() string

Summary is the one-line operator description used in notes and status: which knobs are set, in a stable order, nothing about their values that could grow unbounded.

func (*AgentEnvRules) Validate added in v0.206.0

func (r *AgentEnvRules) Validate() error

Validate rejects a table that could never be applied as written: negative caps, empty tool names, regexps that do not compile, a rewrite with no text. It runs wherever the table is loaded (config, the CLI override, the rigger's proposals) so a bad rule fails by name, never silently no-ops.

type AgentErrorRewrite added in v0.206.0

type AgentErrorRewrite struct {
	Match string `json:"match"`
	Text  string `json:"text"`
}

AgentErrorRewrite is one modify_transition entry: an error matching Match (Go regexp, applied to the raw error text) is replaced by Text.

type AgentPager added in v0.206.0

type AgentPager struct {
	// Basis is "measured" (something was evicted, so the re-fetch question was posed) or
	// "insufficient_data" (nothing was evicted; the counts below are real zeros, and the gate
	// is not read from this run).
	Basis            string `json:"basis"`
	Evictions        int    `json:"evictions"`
	EvictedBytes     int64  `json:"evicted_bytes"`
	DistinctEvicted  int    `json:"distinct_evicted"`
	Refetched        int    `json:"refetched_distinct"`
	CompactionPasses int    `json:"compaction_passes"`
}

AgentPager is the wire form of the loop's context-pager report (internal/agent PagerReport). The key names are the loop report's own, so one decoder reads both a standalone trace file and a delegation-log row. The re-fetch rate is not carried: it is refetched_distinct over distinct_evicted, computed by a reader that pools runs, never averaged per run.

type AgentRepackAttempt added in v0.206.0

type AgentRepackAttempt struct {
	// Attempt is the attempt's number, 1-based, in the order tried. A skipped
	// attempt carries the number it would have had.
	Attempt int `json:"attempt"`
	// Lane is how the request was constrained: "grammar" (a GBNF grammar on the
	// completion route), "json_schema" (a vLLM seat's structured_outputs) or
	// "chat" (the grammar-free chat route).
	Lane string `json:"lane"`
	// MaxTokens is the completion budget the request carried (0 when the attempt
	// was skipped). ClampedFrom is the budget it would have carried had the time
	// left in the wall not narrowed it (0 when it was not narrowed).
	MaxTokens   int `json:"max_tokens,omitempty"`
	ClampedFrom int `json:"clamped_from,omitempty"`
	// TokensOut is the completion tokens the seat generated for the attempt,
	// whether or not its answer was usable.
	TokensOut int `json:"tokens_out,omitempty"`
	// FinishReason is the engine's own ("stop", "length"); empty when no
	// completion came back.
	FinishReason string `json:"finish_reason,omitempty"`
	// Ms is the attempt's wall.
	Ms int64 `json:"ms,omitempty"`
	// Head and Tail are the first and last bytes of what the seat wrote, whitespace
	// kept: a run to the cap shows its shape here, a whitespace tail or a loop
	// included. Short answers carry the head only.
	Head string `json:"head,omitempty"`
	Tail string `json:"tail,omitempty"`
	// Skipped is true for an attempt that was never sent, and Why says why. On an
	// attempt that WAS sent, Why says how it failed (empty on the one that produced
	// the object).
	Skipped bool   `json:"skipped,omitempty"`
	Why     string `json:"why,omitempty"`
}

AgentRepackAttempt is one attempt of the node's structured re-pack as the corpus keeps it (register C-80): counts and a short clip of what the seat wrote, never the transcript.

type AgentSampling added in v0.206.0

type AgentSampling struct {
	Temperature       *float64 `json:"temperature,omitempty"`
	TopP              *float64 `json:"top_p,omitempty"`
	TopK              *int     `json:"top_k,omitempty"`
	PresencePenalty   *float64 `json:"presence_penalty,omitempty"`
	RepetitionPenalty *float64 `json:"repetition_penalty,omitempty"`
}

AgentSampling is the planner's decoding policy for one seat (config `agent_sampling` / `agent_sampling_final`, register D-95b).

The agent client has always sent `temperature: 0` and nothing else, which is the right default for tool-calling and grounded extraction — and is also the setting every Qwen3-class model card warns against for NON-THINKING generation, because greedy decoding is exactly what makes a small seat fall into a degenerate repetition loop (the <node-c> 4B's METHODOLOGY.md digest, 2026-09-14). This type is how an operator gives a MEASURED seat a different policy without changing the default for anyone else.

Every field is a pointer: unset means "do not send this key", so a zero AgentSampling reproduces today's request byte for byte. There is no house-recommended value here on purpose — a sampling setting is a per-seat measurement, and baking one in would make every node inherit a number that was measured somewhere else.

func (*AgentSampling) IsZero added in v0.206.0

func (s *AgentSampling) IsZero() bool

IsZero reports whether nothing is set — the default, today's behaviour.

func (*AgentSampling) Summary added in v0.206.0

func (s *AgentSampling) Summary() string

Summary renders the EFFECTIVE sampling of a call, in the order the wire carries it — what `calls[].sampling` publishes so a measurement can prove which policy a run actually used. A zero policy renders the default the client has always sent, never an empty string: "no sampling recorded" and "the default was used" must not read the same.

func (*AgentSampling) Validate added in v0.206.0

func (s *AgentSampling) Validate(key string) error

Validate refuses values no OpenAI-compatible backend accepts, at the config door rather than as a 400 in the middle of a delegated run.

type AgentSetupAction added in v0.206.0

type AgentSetupAction struct {
	Tool string          `json:"tool"`
	Args json.RawMessage `json:"args,omitempty"`
}

AgentSetupAction is one replayed tool call: the tool by name and its argument object as the model would have sent it.

func SeedContextReads added in v0.206.0

func SeedContextReads(docs []ContextDoc) []AgentSetupAction

SeedContextReads builds the replay list a node can prepend for a grounded contract it is about to run: one read_file per context doc, in contract order, named exactly as the node materializes them (the doc name IS the file name under the read root). The node knows the names; the delegator would only be guessing them — which is why this is a node-side key (agent_seed_context_reads) and not something every contract author types. nil for a contract with no docs.

func (AgentSetupAction) ArgsJSON added in v0.206.0

func (a AgentSetupAction) ArgsJSON() string

ArgsJSON returns the argument object as the loop dispatches it: "{}" for an absent/empty args so a tool's decoder always sees an object.

type AgentTraceStep added in v0.206.0

type AgentTraceStep struct {
	Step     int    `json:"step"`
	Tool     string `json:"tool"`
	Status   string `json:"status"`              // committed | failed | unknown | none (agent.EffectStatus)
	ObsChars int    `json:"obs_chars,omitempty"` // size of the result the model saw, after every rule and cap
	Rule     string `json:"rule,omitempty"`      // env rule that fired on this call, e.g. "max_calls_per_tool"
	Setup    bool   `json:"setup,omitempty"`     // replayed from the contract's setup_actions before turn 1 (step 0)
	// Note (0.113.26, the rigger's evidence): for a call that did NOT commit —
	// failed, none, unknown — the first AgentTraceNoteMax bytes of what the
	// model was told (the tool's error, the breaker's refusal, the rule's
	// reason). Empty on committed calls: the corpus keeps facts about the
	// run, never result bytes. Without it a `rewrite_error` rule could not be
	// authored from the corpus (design council 2026-09-07).
	Note string `json:"note,omitempty"`
}

AgentTraceStep is one tool call of a run as the CORPUS sees it (wire result `trace`): enough for the rigger to diagnose a failure axis — which tool, what became of it, how much the model was given to read, and which environment rule (if any) decided — without the transcript bytes.

type AgentWireResult added in v0.206.0

type AgentWireResult struct {
	SchemaVersion int             `json:"schema_version"` // AgentWireSchemaVersion
	NodeID        string          `json:"node_id"`
	Seat          string          `json:"seat"`                 // resolved planner model
	Output        string          `json:"output"`               // final assistant text
	Structured    json.RawMessage `json:"structured,omitempty"` // present iff OutputSchema given AND validated
	Steps         int             `json:"steps"`
	StopReason    string          `json:"stop_reason"`
	// StopNote (0.115.8): the one-line evidence behind a `reasoning_starved` /
	// `empty` stop — the starvation arithmetic of the last empty completion
	// (finish reason, reasoning vs completion tokens, which wire key). Empty
	// on every other stop.
	StopNote string `json:"stop_note,omitempty"`
	// OutputTruncated (0.115.8): the final answer ended on finish_reason
	// "length" — a correct PARTIAL the caller must not read as the whole.
	OutputTruncated bool   `json:"output_truncated,omitempty"`
	Deferred        bool   `json:"deferred"`
	Reason          string `json:"reason,omitempty"`
	// SchemaMiss (register C-66, PR-4) marks a defer whose agent loop FINISHED: the
	// answer is intact in Output, complete (not cut at the completion budget) and
	// only its structuring failed — the structured re-pack was stalled, unreachable,
	// cut or answered a shape the schema refused. It is what lets the delegator
	// re-pack the answer itself instead of counting a finished loop as lost work
	// (80 of 80 killed re-packs on 2026-09-29 carried a finished answer). Set with
	// Deferred and never without Output; a node that predates the field omits it and
	// the delegator recognizes the same shape from stop_reason and the reason prefix.
	SchemaMiss bool `json:"schema_miss,omitempty"`
	// DeferClass is the machine-branchable WHY behind Deferred (one of the
	// DeferClass* constants). Additive and omitempty: a pre-0.65 node's result
	// decodes with an empty class, which readers must treat as "unknown", never
	// as abstention.
	DeferClass string `json:"defer_class,omitempty"`
	WallMs     int64  `json:"wall_ms"`
	TokensOut  int    `json:"tokens_out,omitempty"`
	// SeatTokensIn is the prompt-token count the seat processed over the whole
	// run (every turn, cache hits included) — work the cards did, never a saving:
	// the ledger keeps it apart from tokens_in, which the summary counts as tokens
	// saved. Additive, omitempty (0.115.5); carried on DEFERRED results too.
	SeatTokensIn int `json:"seat_tokens_in,omitempty"`
	// Wall sizing (0.115.21, register D-03). SeatTokS is this run's effective
	// decode rate (completion tokens per second of call wall over completions
	// of ≥ 1,024 tokens; 0 = no qualifying completion). WallEstimateSec is the
	// wall the contract was estimated to need on this seat BEFORE the loop ran
	// (cold load + think block + tool steps + final answer at the seat's
	// remembered rate); MinTurnSec is a cold load plus one turn at the final
	// budget — the least wall a retry is worth (D-46); WallNote names the
	// arithmetic, or why there is none. Published, never imposed: the run
	// proceeds under the contract's timeout_sec exactly as before.
	// Re-pack accounting (0.115.23, register D-91): how long the structured
	// re-pack ran, how many seat completions it spent, and why it stopped or
	// was skipped. A re-pack of a 12 KB length-cut answer on the 4B ran three
	// full re-generations (~690 s) into the 900 s wall on 2026-09-10 and
	// turned a finished loop into a budget defer with nothing on the wire to
	// say where the time went.
	RepackMs       int64  `json:"repack_ms,omitempty"`
	RepackAttempts int    `json:"repack_attempts,omitempty"`
	RepackNote     string `json:"repack_note,omitempty"`
	// RepackAttemptsDetail (register C-80) is what each re-pack attempt did, in
	// order: its lane, the max_tokens it asked for, the tokens the seat spent, why
	// it ended, a short head and tail of what it wrote, and the attempts that were
	// SKIPPED with the arithmetic that skipped them. repack_attempts counts only the
	// requests actually sent, and a failed attempt left no other trace: one re-pack
	// ran 1,670 s over three attempts and nothing on the wire could say what any of
	// them produced. Additive and omitempty: a node that predates the field omits
	// it, and a delegator that predates it ignores it.
	RepackAttemptsDetail []AgentRepackAttempt `json:"repack_attempts_detail,omitempty"`
	SeatTokS             float64              `json:"seat_tok_s,omitempty"`
	// ObservedTokS (0.131.1) is the liveness monitor's smoothed decode rate over
	// the run's streamed deltas — descriptive, present on short runs the
	// calibrated SeatTokS (>= 1,024-token completions only) skips. The ledger's
	// tok_per_s prefers SeatTokS, then this; the seat-rates store reads only
	// SeatTokS, so a short sample never taints calibration.
	ObservedTokS    float64 `json:"observed_tok_s,omitempty"`
	WallEstimateSec int     `json:"wall_estimate_sec,omitempty"`
	MinTurnSec      int     `json:"min_turn_sec,omitempty"`
	WallNote        string  `json:"wall_note,omitempty"`
	// WallSec (register D-03, 0.126.0) is the wall the NODE sized this run to —
	// a timeout_auto contract, the seat-rate estimate clamped to the wire
	// bounds — stamped before admission, so a defer at the cordon carries it
	// too (what WOULD have run). Omitted when the contract named its own
	// timeout_sec, or when the seat had no rate yet and the wire default ran.
	WallSec int `json:"wall_sec,omitempty"`
	// Liveness (0.131.0): the ceiling the run executed under, the stall
	// allowance it was under when it ended (or was ended), and its last
	// progress event. A `stalled:` or `ceiling` reason reads against these.
	CeilingSec        int   `json:"ceiling_sec,omitempty"`
	StallAllowanceSec int   `json:"stall_allowance_sec,omitempty"`
	LastProgressMs    int64 `json:"last_progress_ms,omitempty"`
	// Final-budget fit (0.122.1, register D-95). FinalBudgetFit is the
	// final-answer completion budget the run actually opened at once the
	// REMAINING wall was taken into account — never above the configured rule
	// (4× the step budget, cap 8,192), floored at 1,024; BudgetNote is the
	// arithmetic ("final 8192 → 3592 to fit 900 s at 15.0 tok/s (split with the
	// output_schema re-pack)"). Both absent when the seat has no measured rate
	// or the configured budget fitted as it was: an un-narrowed run must not
	// publish a narrowing note. Measured 2026-09-14 on the <node-c> 4B seat: a
	// schema contract's 8,192-token final plus its re-pack owed ≈ 1,420 s
	// against a 900 s wall, and hit the wall instead of answering.
	FinalBudgetFit int    `json:"final_budget_fit,omitempty"`
	BudgetNote     string `json:"budget_note,omitempty"`
	// FinalReissue names the re-issue a cut final earned — "list_cap" is the
	// only shape (D-95): the final turn asked once more, thinking off, at the
	// same budget, with the schema's own list caps spelled out. Present whether
	// or not it then succeeded, so a first cut and a second are distinguishable
	// without opening calls[].
	FinalReissue string `json:"final_reissue,omitempty"`
	// ContentionWaitSec is the wall this contract spent waiting on a peer-held
	// seat (seatwait: llama-swap 429 / 503 not-ready / 500 src=llama-swap).
	// Counted, never silent: the number that says whether the fix traded
	// defers for latency. Omitted when zero; a pre-0.111 node's result reads as
	// "not measured".
	ContentionWaitSec float64 `json:"contention_wait_sec,omitempty"`
	// QueuedMs (0.143.0, ADR 0061) is the wall this contract's requests spent
	// in the liveness monitor's busy hold: silent while the seat's ENGINE kept
	// working for other requests (its queue, a shared or throttled card, a
	// preemption). That is contention the run waited out instead of a stall
	// kill. Omitted when zero; a pre-0.143 node's result reads as "not
	// measured".
	QueuedMs int64 `json:"queued_ms,omitempty"`
	// AdmissionWaitSec is the pre-flight spent BEFORE the wall started
	// (RunAgentTask's admission gate): waiting for llama-swap to finish another
	// model's swap and, since 0.115.11, loading the seat itself when it was not
	// resident (the cold-load warm-up). Zero = omitted = nothing was swapping,
	// the seat was already loaded, or the gate is disabled.
	AdmissionWaitSec float64 `json:"admission_wait_sec,omitempty"`
	// AdmissionNote names what the admission gate could NOT settle or what it
	// did — a probe failure (fail-open), a spent budget, the seat's cold load
	// ("cold load Ns outside the wall"), or a warm-up llama-swap never
	// confirmed — so a wire reader can tell "nothing was swapping" from "the
	// gate could not tell" from "the seat was loaded here".
	AdmissionNote string `json:"admission_note,omitempty"`
	// CtxWindowNote is the served-window resolver's own line for this run:
	// which window the loop budgeted against and WHERE it came from — the live
	// probe, this box's configured agent_ctx_tokens, or the conservative
	// fallback. Both doors used to discard it, so an 8,192-token run on a
	// 131,072-token seat looked identical on the wire to a correct one, and the
	// only symptom was a task that compacted for no reason. Empty = a run old
	// enough not to report it.
	CtxWindowNote string `json:"ctx_window_note,omitempty"`
	// CoherenceNote reports the post-warm SEAT COHERENCE probe (register
	// D-118): one ≤ 96-token completion, charged to admission, that asks the
	// seat to call read_file and answer DONE. Empty = the probe did not run
	// (policy "off", a warm seat under the default "cold" policy, no admission
	// budget left, or a pre-D-118 node). Non-empty on every run where it DID
	// run — coherent, inconclusive, or broken — so a wire reader can tell "the
	// seat answered sanely" from "nobody asked".
	//
	// A broken verdict is also a defer: class `infrastructure`, reason prefixed
	// IncoherentSeatReason, before the wall ever starts.
	CoherenceNote string `json:"coherence_note,omitempty"`
	// SeatRecoveries (ADR 0066) is how many times this run's seat went
	// down under it and the run waited for the seat and re-issued the failed
	// step instead of ending — the transcript is the loop's, so nothing done so
	// far was lost. SeatDownWaitSec is the wall the run spent waiting for a
	// downed seat (from the moment the seat was called down to its recovery or
	// to the wait running out); a delegator credits it back to the contract's
	// budget when it re-places a `seat down:` defer, because time spent on a
	// dead seat is not time the contract worked. Both omitted when zero; a
	// result from a node without ADR 0066 reads as "not measured".
	SeatRecoveries  int     `json:"seat_recoveries,omitempty"`
	SeatDownWaitSec float64 `json:"seat_down_wait_sec,omitempty"`

	// --- A1 config pinning (0.81.0, Tier 2 of the Phase 2 re-aim). Stamped by
	// runAgentTask only when the seat DEMONSTRABLY SERVED this run (the loop
	// completed its chat traffic) — a config/infrastructure defer that fired
	// before any model call carries no pins, because probing /props on a
	// non-resident seat would cold-start a model as a telemetry side effect.
	// All omitempty: a pre-0.81 node's result decodes with every pin empty,
	// which readers MUST treat as "unknown config — refuse to pair", never as
	// a pinned value (same additive rule as DeferClass above).
	//
	// Two halves, deliberately: SeatConfig* pins the SERVER (weights, quant,
	// build, window, template, server sampler defaults) via agent.ProbeSeatPin;
	// HarnessVersion + HarnessBuildSHA256 pin the REQUEST-side code (per-call
	// temperature, the re-pack's enable_thinking:false, profile toolsets) —
	// the side the 2026-08-17 corpus-invalidating defect actually lived on.
	HarnessVersion     string `json:"harness_version,omitempty"`
	HarnessBuildSHA256 string `json:"harness_build_sha256,omitempty"`
	SeatConfigSHA256   string `json:"seat_config_sha256,omitempty"`
	SeatConfigBasis    string `json:"seat_config_basis,omitempty"`
	// ResponseShape (0.115.13, register D-45) is the seat's OBSERVED answer
	// shape on this run — which wire key carried hidden reasoning (`reasoning`
	// on vLLM, `reasoning_content` on llama.cpp, none), whether reasoning
	// tokens were reported, how many tool calls parsed, how many completions
	// ran. The pin above says what the seat IS; this says how it answered —
	// the two seat facts (parser mismatch 2026-09-04, reasoning-key blind spot
	// 2026-09-10) the corpus could not show. Omitempty: absent when no
	// completion ran or on a pre-0.115.13 node.
	ResponseShape string `json:"response_shape,omitempty"`

	// --- Node-side prefill accounting (T2-B), previously ledger-only. The
	// node's ledger row already carried these; the DELEGATOR could not see
	// them, so the standing delegation-log corpus recorded a remote run's
	// prefill economics nowhere ("computed then discarded", the Tier 1 defect
	// class). Zero values are omitted — a pre-0.81 node's result reads as
	// "not measured", never as "zero prefill".
	PrefillSteps  int     `json:"prefill_steps,omitempty"`
	PrefillTokens int64   `json:"prefill_tokens,omitempty"`
	CacheTokens   int64   `json:"cache_tokens,omitempty"`
	PrefillMS     float64 `json:"prefill_ms,omitempty"`

	// --- Context-pager gate and compaction passes. The loop measures both and
	// the wire dropped them, so the delegation log could not say how often the compaction
	// ladder ran or whether the seat fetched back what it evicted. A POINTER with omitempty:
	// the key is absent on a node that predates the field and on a run that never reached
	// the loop, and PRESENT (zeros included) on every run the loop returned from, a
	// write-class deferral included, so a reader separates "not recorded" from "recorded,
	// nothing happened".
	Pager *AgentPager `json:"pager,omitempty"`

	// --- Step trace (ADR 0036, 0.113.22). One entry per tool call the loop
	// handled: tool, fate, how much the model read, which environment rule
	// decided. Bounded by max_steps × calls-per-step, no transcript bytes.
	// This is what the corpus lacked for a per-step diagnosis (2026-09-07: 51
	// of 58 failed 4B rows stop at exactly 2 steps with empty schema fields,
	// and the corpus could not say what those two steps did). Omitempty: a
	// pre-0.113.22 node's result reads as "no trace", never as "no calls".
	Trace []AgentTraceStep `json:"trace,omitempty"`
	// --- The write door (0.122.0, register D-06). Present only on a contract
	// that opened it. Diff is the unified diff of everything that changed under
	// write_root during the run, a/ and b/ prefixed so it applies with
	// `git apply -p1`; DiffFiles lists the touched paths in the same order the
	// diff renders them. The harness applies NEITHER — reviewing and applying
	// the change is the caller's job, and that is the whole safety story of
	// letting a 4B write anything at all.
	//
	// WriteNote says what the door did when there is no diff to read: the node
	// has not opted in, the write set broke a cap, nothing was written. Absent
	// on a read-only contract, which is how a reader tells "no write door" from
	// "write door, nothing written".
	Diff      string   `json:"diff,omitempty"`
	DiffFiles []string `json:"diff_files,omitempty"`
	WriteNote string   `json:"write_note,omitempty"`
	// RulesFired counts environment-rule hits on this run (0 = none / no table).
	RulesFired int `json:"rules_fired,omitempty"`
	// SetupRan counts the contract's setup actions (agentsetup.go) that were
	// EXECUTED before the model's first turn (committed or failed — a refused,
	// unknown-tool or over-budget action is not counted; the trace's setup
	// entries carry the per-action status). 0 on a node that predates the
	// field, so a mixed-version fleet shows where the replay did not happen.
	SetupRan int `json:"setup_ran,omitempty"`
	// Calls (0.115.8, D-47): one entry per planner completion — finish reason,
	// completion and reasoning tokens, visible and hidden chars, tool-call
	// count, whether thinking was off. Set before the defer branches, on every
	// result shape, so a starved run's arithmetic is in the corpus rather than
	// reconstructed from token totals. Omitempty: a pre-0.115.8 node emits none.
	Calls []AgentCallRecord `json:"calls,omitempty"`
	// Placed (ADR 0052, 0.116.0) is the placement decision the node made for
	// this run — layer, seat, device pin and the reason, or the guard that
	// refused on a defer. nil and omitted on a non-composite node, so a
	// pre-0.116 node's result and a plain box's result are byte-identical;
	// a reader treats nil as "one implicit layer", never as "unplaced".
	Placed *Placed `json:"placed,omitempty"`
}

AgentWireResult is the versioned result envelope — the only thing that crosses back from a remote agent run (§S2). Deferred is a SUCCESS shape at the job level (the node did its job: it reported it could not complete the contract), mirroring the cascade's defer semantics.

type Authority added in v0.206.0

type Authority int

Authority is the strength of the evidence a check reads, ordered weakest first. The zero value is "no authority claimed".

const (
	AuthNone Authority = iota
	AuthAnswer
	AuthField
	AuthGrounded
)

func ClosedAt added in v0.206.0

func ClosedAt(outcomes []AcceptanceOutcome) (closed Authority, ok bool)

ClosedAt is the authority a set of graded checks closes at: the weakest authority among them, and only when every one passed. An unqualified check counts as AuthNone, so a single one pulls the whole set down to none; a fail, an unknown, or an empty set leaves it open (ok false). It is how a caller states "this contract was closed at grounded authority" and has the claim refused when its weakest check was only an answer. The delegator states it on what it publishes (delegate.EvalAcceptanceGraded: the result's acceptance_authority).

func (Authority) AtLeast added in v0.206.0

func (a Authority) AtLeast(b Authority) bool

AtLeast reports whether a is as strong as b or stronger.

func (Authority) String added in v0.206.0

func (a Authority) String() string

String is the name the qualifier and the reasons use.

type ContextDoc added in v0.206.0

type ContextDoc struct {
	Name string `json:"name"`
	Text string `json:"text"`
}

ContextDoc is one inline context document. Name is a future FILENAME on the receiving node (materialized under the job's context dir), which is why Validate holds it to flat-filename shape — no separators, no traversal.

type EscalationSource added in v0.206.0

type EscalationSource string

Meta is per-call telemetry returned to the caller and recorded in the ledger. EscalationSource is the CLOSED set of reasons a call climbed a tier.

Closed on purpose. The ledger already carried a free-text `reason`, but only on DEFERRED entries — a successful escalation recorded nothing, so the one question the telemetry needed to answer ("did the model's self-report send this up, or did a structural signal?") could not be answered from the data. Bounded cardinality is what makes it groupable; a sentence is not.

Ordering note for readers: the pipeline evaluates the quality gates in the order verifier -> schema -> grounding -> self-confidence -> margin -> confhead, and records the FIRST that fired, so these values are mutually exclusive per call.

const (
	EscNone EscalationSource = "" // did not escalate

	// EscSelfConfidence: the model's own `confidence` field fell below
	// classify_min_confidence. This is the only SELF-DECLARED gate in the
	// cascade; every other value below is structural.
	EscSelfConfidence EscalationSource = "self_confidence"
	// EscMargin: the logprob decision margin over the label/decision tokens
	// fell below the per-task threshold. Structural — derived from the
	// distribution, not from anything the model said about itself.
	EscMargin EscalationSource = "margin"
	// EscConfhead: the learned p(correct) head predicted below its conformal
	// threshold. Structural.
	EscConfhead EscalationSource = "confhead"
	// EscSchema: output parsed but failed schema validation.
	EscSchema EscalationSource = "schema"
	// EscGrounding: extract produced values absent from the source text.
	EscGrounding EscalationSource = "grounding"
	// EscVerifier: parse/verify failure (malformed or truncated output).
	EscVerifier EscalationSource = "verifier"
	// EscRetries: retries exhausted without a valid answer.
	EscRetries EscalationSource = "retries"
)

type LaneHolder added in v0.206.0

type LaneHolder struct {
	Epoch        uint64   `json:"epoch"`
	Class        string   `json:"class"`
	Reason       string   `json:"reason,omitempty"`
	RemainingSec int      `json:"remaining_sec,omitempty"`
	Devices      []string `json:"devices,omitempty"`
}

LaneHolder is one live lease in the way, as `gpu status` would list it.

type LaneProber added in v0.206.0

type LaneProber interface {
	MediaLaneFree(ctx context.Context, req Request) LaneVerdict
}

LaneProber is implemented by a Runner that can answer the question above. It reads and never writes: no lease, no place in line, no ledger row, no card of any kind.

type LaneVerdict added in v0.206.0

type LaneVerdict struct {
	// Free: the lane would take the call now, OR the prober cannot say (a task it does not model, a lease this process
	// inherited, a card table that would not read). A router acts on a false Free, and on a true Free that is not Unjudged.
	Free bool `json:"free"`
	// Why is the sentence for a person: what is in the way when Free is false, or why the prober could not judge when
	// Free is true and the answer is not a plain yes. Empty for a plain yes.
	Why string `json:"why,omitempty"`
	// Holders are the live leases in the way (the cards the call would use, or any lease when it needs the whole node).
	Holders []LaneHolder `json:"holders,omitempty"`
	// Ahead is how many callers hold a place in line that the call would queue behind (live waiters and tokens).
	Ahead int `json:"ahead,omitempty"`
	// HostRAM is the host-RAM guard's own sentence when the memory, not the card, is what is short.
	HostRAM string `json:"host_ram,omitempty"`
	// Unjudged: the prober TRIED to read the lane and could not (the card table did not read inside its bound, the lease
	// directory did not open). Free is true then only because the real admission will judge, so a router must not take it
	// for a lane that is free: it looks at the rest of the cluster first (the card table is slowest to read exactly when a
	// heavy render holds the card) and keeps this machine's lane as the answer when no node can take the call. It is not
	// set when the prober does not model the call at all (another task, a binding without a lane, a lease the process
	// inherited): there the lane is not in question and the call runs on it.
	Unjudged bool `json:"unjudged,omitempty"`
}

LaneVerdict is a prober's answer for one request.

func ProbeLane added in v0.206.0

func ProbeLane(ctx context.Context, runner any, req Request) LaneVerdict

ProbeLane asks runner whether req would take its local lane now. A runner that cannot say (a test double, a node's own runner, nil) reports a free lane, so the call is the one that existed before the probe did.

func (LaneVerdict) HostRAMOnly added in v0.206.0

func (v LaneVerdict) HostRAMOnly() bool

HostRAMOnly says the verdict found nothing in the way but host RAM: no lease on the cards and nobody ahead in line.

type ListLoss added in v0.206.0

type ListLoss struct {
	Path   string // where the answer held it: "stale", "report.outdated"; "" for an answer that is itself a list
	Held   int    // its items that hold content
	Shared bool   // the schema has a list of this very path, which is the one that came back short
}

ListLoss is a list of the answer that the object did not carry.

func ListsLost added in v0.206.0

func ListsLost(structured []byte, schema map[string]any, answer string) []ListLoss

ListsLost returns the lists the refusal of ListsEmptied is about (nil when there is none): the same-named list that came back empty, or the lists of the answer no schema list is named for. The prompt that follows a refused attempt is built from it, so it names what was lost and not every list the answer holds.

type ListSite added in v0.206.0

type ListSite struct {
	Path []string
	Spec map[string]any
}

ListSite is one array property of the schema: its path ("report.items") and its spec.

func SchemaListSites added in v0.206.0

func SchemaListSites(schema map[string]any) []ListSite

SchemaListSites returns the array properties of a schema, through the properties of nested object properties, sorted by path so a finding reads the same on every run.

func (ListSite) Label added in v0.206.0

func (s ListSite) Label() string

func (ListSite) MaxItems added in v0.206.0

func (s ListSite) MaxItems() int

MaxItems is the schema's bound on the list, 0 when it sets none.

type LiveProgress added in v0.206.0

type LiveProgress struct {
	Step           int     `json:"step,omitempty"`
	TokensOut      int     `json:"tokens_out,omitempty"`
	TokS           float64 `json:"tok_s,omitempty"`
	Phase          string  `json:"phase,omitempty"`
	LastProgressMs int64   `json:"last_progress_ms,omitempty"`
	AllowanceMs    int64   `json:"allowance_ms,omitempty"`
	CeilingSec     int     `json:"ceiling_sec,omitempty"`
}

The WALL REPORT (register D-116).

A contract whose caller named no timeout_sec is stamped `timeout_auto` and the EXECUTING node sizes the wall from its own seat's measured rate, inside the wire bounds. Until this existed, that number reached the delegator only on the FINAL result (AgentWireResult.WallSec) — which is exactly the case a dead node never produces. So the delegator, which cannot see the wall the node chose, held its poll clock open to the cap for every auto contract; the 0.126.0 review wrote that down as an accepted cost.

The report closes it from the node's side: the lane that stamps the wall publishes it, the fleet node writes it onto the job record, and the job's poll payload carries it while the job is still RUNNING. It is a context value rather than a parameter because the lane that knows the wall (pipeline.runAgentTask) and the lane that owns the job record (fleetnode.Server) are three call frames apart through an interface, and a node door that sets no reporter simply reports nothing — the previous behaviour, exactly. LiveProgress is a running job's liveness as the executing lane reports it and the fleet node publishes it on every poll (0.131.0): the delegator keeps polling while LastProgressMs keeps moving inside AllowanceMs.

type MediaPlace added in v0.206.0

type MediaPlace struct {
	// Token names the place (a gpulease token id). The local run that finally serves the ticket carries it as its
	// waiter_token.
	Token string
	// Since is when the call first joined the line: the arrival time every give-up and every resume keeps.
	Since time.Time
	// Devices are the cards the call would queue on (empty: the whole node).
	Devices []string
}

MediaPlace is a place in the local line.

func LeavePlace added in v0.206.0

func LeavePlace(ctx context.Context, runner any, req Request, since time.Time) (MediaPlace, error)

LeavePlace asks runner to keep req's place in its line. A runner that cannot (a test double, a node's own runner, nil) answers ErrNoMediaPlace, so the call goes on without local seniority.

type Meta

type Meta struct {
	TokensIn  int `json:"tokens_in"`
	TokensOut int `json:"tokens_out"`
	// SeatTokensIn: prompt tokens an agent seat processed for this task (work,
	// not savings) — see core.AgentWireResult.SeatTokensIn. Omitted when zero.
	SeatTokensIn int     `json:"seat_tokens_in,omitempty"`
	LatencyMs    int64   `json:"latency_ms"`
	TokPerSec    float64 `json:"tok_per_s"`
	CacheHit     bool    `json:"cache_hit"`
	Model        string  `json:"model"`
	Retries      int     `json:"retries"`
	// Escalations counts how many cascade tiers were climbed before this result
	// (0 = answered by the entry tier; >0 = a bigger local model was needed).
	Escalations int `json:"escalations,omitempty"`
	// Reasoning marks a result produced by the terminal local reasoning tier (a
	// reclaimed cloud deferral). It runs on the SAME model as the escalation tier
	// (the escalation model) and so shares Model — this flag is what tells the two apart in the
	// ledger / `stats` reports.
	Reasoning bool `json:"reasoning,omitempty"`
	// --- self-learning signals (logged to the ledger; free, no extra inference) ---
	Margin float64 `json:"margin,omitempty"` // logprob decision margin (triage/classify); 0 = N/A
	// MarginScale names WHICH denominator Margin was computed over (register
	// D-130): "matched" (the historic scale: matched class tokens only) or
	// "full" (every alternative at the decision position). Empty = no margin was
	// resolved, and an old ROW without the field reads as "matched". The two
	// scales differ by ~10x and must never be pooled.
	MarginScale string `json:"margin_scale,omitempty"`
	// MarginDeclaredMass is the share of the raw mass that landed on a legal
	// class (matched/all, 0..1) and MarginAmbiguous the number of alternatives
	// credited to no class because they prefixed more than one. Both are
	// computed in BOTH modes, so the data to re-derive a full-scale threshold
	// accumulates before the flag is ever flipped.
	MarginDeclaredMass float64 `json:"margin_declared_mass,omitempty"`
	MarginAmbiguous    int     `json:"margin_ambiguous,omitempty"`
	Truncated          bool    `json:"truncated,omitempty"`        // hit token limit
	Grounded           *bool   `json:"grounded,omitempty"`         // extract/summary values appear in source (nil = N/A)
	EscalatedAgreed    *bool   `json:"escalated_agreed,omitempty"` // higher tier agreed with the smaller (nil = no escalation)
	ErrClass           string  `json:"err_class,omitempty"`        // oom|timeout|http_5xx|conn_refused on infra failure; disk_full = an output volume was full, over its quota or read-only (ENOSPC/EDQUOT/EROFS, read from the errno, never from prose); gpu_busy = vision call skipped, a gen job held the GPU lock (LO-1); gpu_queued = a media call with no card yet, holding a place in line (the answer carries a waiter_token)
	// Node / Placement say WHERE a vision task ran when the route decided
	// (0.116.0): Node is the fleet node_id that served it, Placement the
	// route's reason ("remote: local gpu busy", "remote: forced", "local: no
	// eligible node (…)"). Both omitempty — a plain local call publishes
	// byte-identically to before the route existed.
	Node      string `json:"node,omitempty"`
	Placement string `json:"placement,omitempty"`
	// The agent job behind an agent row (0.124.0, register D-101): the run's
	// job id, step count, stop reason and structured re-pack wall, copied from
	// the wire result at finish so the ledger row carries them. All omitempty:
	// a cascade call publishes byte-identically to before.
	JobID string `json:"job_id,omitempty"`
	// ParentJobID is the delegator's job id when the delegator placed this run
	// on the box's own seat (register C-62): the ledger then writes this row
	// as an INNER row of that job instead of a second job.
	ParentJobID string `json:"parent_job_id,omitempty"`
	// CallID is the id of the PAIR card the call opened when it started (the
	// CallTracker returns it from Begin): stamped by Pipeline.Run, mapped onto
	// ledger.Entry.CallID, so the call's own row closes that card and no other.
	// Empty for a call that opened no card; omitempty, so such a call publishes
	// byte-identically to before.
	CallID string `json:"call_id,omitempty"`
	// CardsCarried is the work, in tokens through the cards, of this call's EARLIER
	// attempts whose rows went to the ledger as inner rows (a cascade climb,
	// plan D12). Record writes cards_tokens 0 on an inner row, so the call's own row
	// adds this figure to its own and a share reader's total counts that work once.
	// In-process bookkeeping only (`json:"-"`): never published.
	CardsCarried int `json:"-"`
	// QueuedMs is the agent run's busy-hold wall (ADR 0061): time its requests
	// waited on a seat whose engine was working for others.
	QueuedMs   int64  `json:"queued_ms,omitempty"`
	Steps      int    `json:"steps,omitempty"`
	StopReason string `json:"stop_reason,omitempty"`
	RepackMs   int64  `json:"repack_ms,omitempty"`
	// RepackAttempts: the re-pack's completion count beside its wall, so the
	// ledger row can separate one slow attempt from a three-attempt loop —
	// the figure the D-129 engine route is measured on.
	RepackAttempts int                `json:"repack_attempts,omitempty"`
	Feat           map[string]float64 `json:"feat,omitempty"` // cheap input features for the entry-tier router
	// TierPack records how a climbed-to tier's input was packed (TO-3): empty
	// on entry-tier calls; "token-exact (full source)" / "token-exact (cut
	// K/N tokens)" when the tier re-read the original against its own window;
	// "entry-inherited (<why>)" when the repack failed open to the entry
	// packing. The fail-open must be observable, never inferred (TO-4 rule).
	TierPack string `json:"tier_pack,omitempty"`
	// Feat keys that are MARKERS, not features: written on the ledger row so a condition is
	// recorded, never emitted by featurize at inference, so a trainer that learned a weight on
	// one would read it as 0 on every live call and skew its scores. IsLedgerMarker names them;
	// the router's feature order skips them. FeatEscalationUnavailable: the confidence gate had
	// nowhere to escalate to (escalation_model empty or the workhorse itself).
	//
	// EscSource names WHICH gate sent this call up a tier. Closed set (see
	// EscalationSource) so it aggregates; a free-text reason does not.
	// Measured gap 2026-08-11: a SUCCESSFUL escalation recorded no reason at
	// all, so "which gate fired" was unreadable from telemetry and no change
	// to the gating could be evaluated after the fact. Empty on calls that
	// never escalated.
	EscSource EscalationSource `json:"esc_source,omitempty"`
	// --- call identity (memory-frontier Phase 0.1) ---------------------------
	// The ledger recorded THAT a call happened but never WHAT it was about, so
	// every "measure the duplicate rate / prefix reuse / counterfactual replay"
	// question was structurally unanswerable from telemetry — each one needed a
	// bespoke throwaway script, and the ones needing the input text could not be
	// answered at all. These are HASHES, never content: they make calls
	// groupable and comparable without turning the ledger into a transcript
	// store (which was rejected on privacy/brand-isolation grounds).
	//
	// InputSHA256 fingerprints the ORIGINAL caller input (pre-trim), so repeats
	// are countable across tiers and across machines running identical models.
	InputSHA256 string `json:"input_sha256,omitempty"`
	// PromptPrefixSHA256 fingerprints the assembled prompt's STABLE prefix (the
	// bytes before the volatile tail). Two calls sharing it are two calls whose
	// KV prefix llama.cpp could reuse — which is what makes prefix-reuse work
	// measurable instead of assumed.
	PromptPrefixSHA256 string `json:"prompt_prefix_sha256,omitempty"`
	// ContextHash fingerprints the DECISION ARTIFACTS in force for this call
	// (router weights, confhead, exemplar selection, template version, seed).
	// It turns every hot-reload into a free A/B: rows split into buckets by
	// which artifact set produced them, so a change's effect is attributable
	// rather than anecdotal. Cheap because the 30s content-hash watcher already
	// computes the component hashes for reload; this only threads them through.
	ContextHash string `json:"context_hash,omitempty"`
	// ExemplarIDs lists the exemplars actually injected into this prompt. Nobody
	// can answer "which exemplars actually fire?" today; with this the histogram
	// is one query, and a power-law answer means the selection set can be pruned.
	ExemplarIDs []string `json:"exemplar_ids,omitempty"`
	// CacheBypass names why this call could neither read nor write the result
	// cache, when that happened for a reason other than "no cache configured".
	//
	// It exists because the alternative is a genuine silent failure: a media file
	// whose content identity cannot be established is deliberately not cached
	// (T2-A2 — keying on anything but content is what produces false hits), and
	// with no field for it that call is byte-identical in telemetry to an ordinary
	// cold miss. An input on a flaky mount would then re-run whisper at full cost
	// on every call, forever, while the ledger showed a healthy run of cache
	// misses and the hit-rate dashboard invited exactly the wrong diagnosis.
	CacheBypass string `json:"cache_bypass,omitempty"`
	// --- agent-loop prefill accounting (memory-frontier T2-B) ---
	//
	// The instrument that produces these shipped in 0.65.0 and works, but its output
	// went nowhere durable: PrefillReport rode home on the in-process Result and on a
	// local-agent stderr line, neither of which survives the call. So the question it
	// exists to answer -- does the agent loop have a repeated prefix worth stabilising?
	// -- still could not be answered from real traffic. These fields land it in the
	// ledger, where every other measurement in this program accrues.
	//
	// PrefillSteps is the DISCRIMINATOR, not a statistic: it counts steps whose backend
	// actually reported timings. Present (>0) means the rest were measured; absent means
	// unmeasured. Without it, prefill_tokens:0 is ambiguous between "the server reused
	// everything" and "nothing was ever observed" -- opposite conclusions.
	PrefillSteps int `json:"prefill_steps,omitempty"`
	// AgentProfile is the agent profile this run actually resolved to.
	//
	// It is chosen at internal/pipeline/agenttask.go (contract.Profile, defaulting to
	// "research") and was previously used to configure the loop and then discarded -- the
	// same "computed then thrown away" defect the prefill fields above were added to close.
	//
	// It matters because profile is the single largest measured lever on small seats
	// (0 -> 72% recall on a 6GB tier came from changing nothing but this), so a prefill or
	// quality figure aggregated across profiles is an average over materially different
	// configurations. Without it, per-(seat, profile) cost cannot be separated at all.
	AgentProfile string `json:"agent_profile,omitempty"`
	// ExemplarsDropped: the profile's few-shot was withheld because the contract is
	// document-grounded (0.113.2).
	ExemplarsDropped bool    `json:"exemplars_dropped,omitempty"`
	PrefillTokens    int64   `json:"prefill_tokens,omitempty"`
	CacheTokens      int64   `json:"cache_tokens,omitempty"`
	PrefillMS        float64 `json:"prefill_ms,omitempty"`
	// CacheHitInLoop marks a cache hit served from an entry that was WRITTEN by
	// the agent loop's in-loop offload (T2-D) rather than by a recorded,
	// caller-facing call.
	//
	// Why it exists: in-loop calls run with a nil ledger precisely so the harness
	// talking to itself cannot inflate savings. Since T2-D they share the result
	// cache, so a later caller-facing call CAN hit an entry the loop produced.
	// The saving to that caller is real and is still counted — but the cache-hit
	// rate is a gate this plan reads, and it must be possible to tell how much of
	// it the harness generated for itself. Without this field that split is
	// unrecoverable after the fact.
	CacheHitInLoop bool `json:"cache_hit_in_loop,omitempty"`
	// Placed (ADR 0052, 0.116.0) records which layer and seat a composite box
	// served this call on, and why. nil — omitted — on a plain box, so the
	// ledger row and every caller-facing result stay byte-identical where no
	// layers are declared. It rides on Meta because Meta is the one telemetry
	// carrier that reaches both the caller and the ledger; a decision recorded
	// anywhere else would be "computed then discarded", the defect class the
	// prefill fields above were added to close.
	Placed *Placed `json:"placed,omitempty"`
	// Door is the Request.Door carried through to telemetry, so the ledger row
	// names the surface that admitted the call (register A-102). Copied in
	// Pipeline.Run and mapped onto ledger.Entry.Door; omitempty, so a caller
	// that stamps no door publishes byte-identically to before.
	Door string `json:"door,omitempty"`
	// FleetJobID is the Request.FleetJobID carried through to telemetry (ADR 0064):
	// the id a fleet node's ledger row is joined to the delegator's row on. Copied
	// in Pipeline.Run and mapped onto ledger.Entry.FleetJobID; omitempty, so a call
	// no fleet node dispatched publishes byte-identically to before.
	FleetJobID string `json:"fleet_job_id,omitempty"`
	// Requester is the Request.Requester carried through to telemetry: who a fleet node's
	// row was run for. Copied in Pipeline.Run and mapped onto ledger.Entry.Requester; omitempty.
	Requester string `json:"requester,omitempty"`
	// AskerSession and AskerClass are the Request.OriginSession and Request.RunClass carried through to
	// telemetry: the session and run class a fleet node's row was run for (ADR 0087). Copied in Pipeline.Run
	// and mapped onto ledger.Entry.OriginSession and ledger.Entry.RunClass. `json:"-"`: Meta is marshalled
	// whole into a node's poll results, and the asker's session id must not be echoed back through them.
	// Named apart from the node's own ProcessOrigin so the two are never confused.
	AskerSession string `json:"-"`
	AskerClass   string `json:"-"`
	// License is the license of the media binding that produced this result (ADR
	// 0058: a named family always declares one; a default binding may). Mapped onto
	// ledger.Entry.License so the ledger can answer "which renders came out of a
	// non-commercial model?"; omitempty, so a text call publishes byte-identically.
	License string `json:"license,omitempty"`
}

type NodeNamer added in v0.206.0

type NodeNamer interface {
	Ran(base, nodeID, fleetJobID string)
}

NodeNamer is implemented by an attribution handle that can be told which node a call ran on WITHOUT opening a card. A call that dispatches learns the node from Dispatched, which also opens the call's card; the process that adopts a placed ticket of an owner that ended (internal/mediaremote) never dispatches, because the ended process's card is already open and a second would be a double, so without this its ledger row names no node: the only other place the node appears is the placement note's "; ran on <node>" tail, and the ledger keeps just the first 120 bytes of a placement while the lane sentence ahead of that tail is longer.

type NopAttribution added in v0.206.0

type NopAttribution struct{}

NopAttribution is the handle for a call nobody attributes.

func (NopAttribution) Bounce added in v0.206.0

func (NopAttribution) Bounce(Result)

func (NopAttribution) Discard added in v0.206.0

func (NopAttribution) Discard(string)

func (NopAttribution) Dispatched added in v0.206.0

func (NopAttribution) Dispatched(string, string, string)

func (NopAttribution) Finish added in v0.206.0

func (NopAttribution) Finish(Result)

func (NopAttribution) Running added in v0.206.0

func (NopAttribution) Running()

type PlaceKeeper added in v0.206.0

type PlaceKeeper interface {
	// LeaveMediaPlace records req's place in the local line and returns it. since is the arrival time to keep (zero:
	// now). A request that carries a waiter_token that can still be resumed keeps that token's id and its arrival
	// time instead, so a caller that already holds a place in line brings it along.
	LeaveMediaPlace(ctx context.Context, req Request, since time.Time) (MediaPlace, error)
	// KeepMediaPlace records that the place token names is still wanted, so it keeps holding against later callers.
	// It refreshes a place that exists and never writes one: false means the place is gone (spent, pruned or never
	// was).
	KeepMediaPlace(token string) bool
	// DropMediaPlace forgets the place (the call was served, or no longer wants it). A token that names nothing is
	// harmless.
	DropMediaPlace(token string)
}

PlaceKeeper is implemented by a Runner that can keep a call's place in its local line.

type PlaceMarker added in v0.206.0

type PlaceMarker interface {
	// MarkMediaPlace refreshes the place token names, as KeepMediaPlace does, and records whether its call's last reading of
	// the lane found only host RAM in the way. Such a place does not hold its cards against a request that declares no host
	// RAM, as a waiter on host RAM does not.
	MarkMediaPlace(token string, hostRAMOnly bool) bool
}

PlaceMarker is implemented by a PlaceKeeper whose places can say what their call waits for (gpulease.Token.WaitingFor).

type Placed added in v0.206.0

type Placed struct {
	// Tier is the composed tier the layer belongs to (blackwell-16 for the
	// single layer of a blackwell-3x16 box). Omitted when the layer carries no
	// tier of its own.
	Tier string `json:"tier,omitempty"`
	// Layer is always present when the block is: a Placed with no layer would
	// be a decision that names nothing.
	Layer string `json:"layer"`
	// Role is the seat role inside the layer (router | agent | long | ocr | …).
	Role string `json:"role,omitempty"`
	// Seat is the llama-swap id or alias that served the work.
	Seat string `json:"seat,omitempty"`
	// Devices is the SEAT's CUDA_VISIBLE_DEVICES pin, never the layer's list
	// of alternative device sets (R3) — a reader must be able to say which
	// cards actually held the work.
	Devices []string `json:"devices,omitempty"`
	// CtxTokens is the seat's window as declared in config — never probed, so
	// no status path loads a model to fill this in.
	CtxTokens int `json:"ctx_tokens,omitempty"`
	// Reason is always present: prose for the operator that says why THIS
	// layer/seat (or why none), including a recorded-only saturation note
	// such as "pair at 32/32 in flight — queued in the seat" (R2).
	Reason string `json:"reason"`
	// Guard names the guard that refused (display_floor | presence | host_ram)
	// on a defer, so a guard defer is branchable, never just a sentence.
	Guard string `json:"guard,omitempty"`
	// Evicts names the seat this placement displaces on a shared device set,
	// when the decision knows it (the pair's long seat evicting the agent
	// seat), so a capacity wait can say what it is waiting to avoid.
	Evicts string `json:"evicts,omitempty"`
}

Placed is the placement decision published on every result a composite box produces (ADR 0052, 0.116.0): which tier, layer and seat served the work, on which device pin, and why — or, on a defer, which guard refused. It exists because the composite-tier spec's fourth defect was "placement is invisible": a result named neither the cards nor the seat that served it, so a pair-seat run read the same as a 3-card one and a defer caused by the display-card floor read the same as one caused by a full seat.

nil means "the box is not composite". Every carrier (AgentWireResult, Meta, the delegate wire) declares it `omitempty`, so a box whose config declares no layers stays byte-identical on the wire, in the ledger and on every status surface — the Global Constraint every composite change is pinned against.

The block is published under the key `placed`. The older `placement` REASON STRING on delegate results is untouched: the opencode plugin and fleet_smoke read it as text, and this block is additive beside it.

type RemoteAttribution added in v0.206.0

type RemoteAttribution interface {
	// Dispatched names the node a call is about to be sent to: base is the dispatch URL, nodeID the
	// fleet node id from its health, fleetJobID the id the node will know the job by. It opens the
	// call's one PAIR card (queued) on that node.
	Dispatched(base, nodeID, fleetJobID string)
	// Running reports that the node says the job has started: the card turns running, once.
	Running()
	// Finish ends the call with its result: one asker ledger row, and the card's terminal frame when
	// a node was chosen. A call that never reached a node still gets its row but no card.
	Finish(res Result)
	// Discard ends a call whose remote attempt is not the final answer because the auto route fell
	// back to a local run (the pipeline writes that run's own row). An attempt that never reached a
	// node writes nothing at all; one that did is finished as a deferred call with reason, so its
	// card is closed failed and the node time it took is on the ledger.
	Discard(reason string)
	// Bounce ends ONE attempt of a call that is going on to another node: the node it was dispatched to
	// took the job and handed it back (another job holds its card, or it could not take its lease), so
	// nothing ran there. The attempt's card closes quiet (completed, never started) whatever err_class the
	// answer carried, because a bounced attempt ran nothing and the class does not decide that. No ledger
	// row is written (the call has one row, and its Finish writes it), and the handle is armed again: the
	// next Dispatched opens a card on the node the call was placed on next. Before any dispatch, or after
	// the call ended, it does nothing.
	Bounce(res Result)
}

RemoteAttribution is one remote call's attribution handle. Every method is safe to call in any order and more than once; after Finish or Discard the rest are no-ops.

func BeginRemote added in v0.206.0

func BeginRemote(runner any, req Request, route string) RemoteAttribution

BeginRemote starts attribution of a remote call on runner, or returns the no-op handle when the runner does not implement RemoteAttributor.

type RemoteAttributor added in v0.206.0

type RemoteAttributor interface {
	BeginRemote(req Request, route string) RemoteAttribution
}

RemoteAttributor is implemented by a Runner that can attribute a remote call. route is the normalized route the caller asked for (local, auto or remote).

type Request

type Request struct {
	Task   TaskType       `json:"task"`
	Input  string         `json:"input"`            // the text to operate on
	Image  string         `json:"image,omitempty"`  // vqa: a local image path or a data:image/... URI
	Video  string         `json:"video,omitempty"`  // video_describe: a local video file path
	Audio  string         `json:"audio,omitempty"`  // transcribe: a local audio/video file path
	Params map[string]any `json:"params,omitempty"` // labels []string, schema map, question string, max_points int
	// Door names the surface that admitted this call: an MCP tool name
	// ("offload_summarize"), a CLI command ("cli:summarize"), or "fleet" for a
	// request a fleet node received from a delegator. Register A-102: every
	// cascade row in the live ledger carried no door, so nobody could tell which
	// surface produced a cascade call. Documentary only — it NEVER routes,
	// gates or selects a tier, and a forwarded request keeps its origin door.
	Door string `json:"door,omitempty"`
	// FleetJobID is the id the delegator dispatched this job under, stamped by a
	// fleet node on the request it builds for a dispatched or pulled job (ADR 0064,
	// register C-63). It rides to the ledger row as Meta.FleetJobID so the node's
	// row and the delegator's row for the same run join on one equality instead of
	// on a guess at latency. Documentary only, like Door: it NEVER routes, gates or
	// keys a cache — a field of its own rather than a Params entry precisely
	// because Params feeds the result-cache key, and a job-unique id there would
	// make every dispatched request miss.
	FleetJobID string `json:"fleet_job_id,omitempty"`
	// Requester is the asker's name (AskerHeader, sanitized), stamped by a fleet node on the request it
	// builds for a job another box asked for. It rides to the ledger row as Meta.Requester so the
	// node's row says who the work was for. Documentary only, like Door and FleetJobID: it never
	// routes, gates or keys a cache.
	Requester string `json:"requester,omitempty"`
	// OriginSession and RunClass are the asker's session label and run class (OriginHeader and
	// RunClassHeader, cleaned), stamped by a fleet node on the request it builds for a job another box
	// asked for. They ride to the ledger row as Meta.AskerSession and Meta.AskerClass, so the node's row
	// names the session it worked for (ADR 0087). Documentary only, like Requester: they never route, gate or
	// key a cache. In-process only (`json:"-"`): a wire body must not be able to name its own session or class.
	OriginSession string `json:"-"`
	RunClass      string `json:"-"`
	// ParentJobID is set by a COMPOSITE call (extract_image, inpaint's auto-text
	// mask) on the sub-request it issues: the sub-call's ledger row is then an
	// INNER row of the composite's own row (register C-62), never a second call
	// and never a PAIR card of its own. In-process only (`json:"-"`): a wire
	// request must not be able to mark its own row inner, which would hide it
	// from every job counter and every card.
	ParentJobID string `json:"-"`
	// Resumable says the door that admitted this call can hand a place in line back to its
	// caller AND take it again: it returns the answer's data (the waiter_token) and accepts
	// waiter_token on the next call. Only the MCP server sets it. A media call that waited its
	// window with no card leaves a place-keeping token only for such a door; for the CLI verbs,
	// the fleet dispatch (the delegator re-places, it never resumes) and the image batch a
	// token could never be claimed, and would hold a card back from the next caller for the
	// 30 s grace, so they get the plain "gpu busy" defer. It is never decoded from, or encoded
	// to, the wire: a remote delegator cannot ask a node to keep a place for it. Like Door it
	// never routes, gates or selects a tier.
	Resumable bool `json:"-"`
}

Request is a normalized offload request handed to the pipeline.

type Result

type Result struct {
	OK       bool   `json:"ok"`
	Deferred bool   `json:"deferred,omitempty"`
	Reason   string `json:"reason,omitempty"`
	// DeferClass is the defer's class (the DeferClass* vocabulary in
	// agentwire.go) on the results that carry one — today the vision route's
	// placement defers (0.116.0), whose "no eligible node" must be branchable
	// as `capacity` and "no remotes configured" as `config`. Empty on every
	// other result, so the pipeline's own defers publish byte-identically.
	DeferClass string          `json:"defer_class,omitempty"`
	Data       json.RawMessage `json:"result,omitempty"`
	Partial    string          `json:"partial,omitempty"`
	Meta       Meta            `json:"meta"`
}

Result is the harness outcome. On success Data holds the validated task output. On a defer, Deferred is true and the caller (Claude) should handle the task itself.

func Deferf

func Deferf(reason, partial string, meta Meta) Result

Deferf builds a deferred Result (harness could not complete; Claude should).

type TaskType

type TaskType string

TaskType is one of the supported offload task kinds.

const (
	TaskSummarize TaskType = "summarize"
	TaskClassify  TaskType = "classify"
	TaskExtract   TaskType = "extract"
	TaskTriage    TaskType = "triage"
	TaskVQA       TaskType = "vqa"
	TaskOCR       TaskType = "ocr"
	// TaskExtractImage is a COMPOSITE: OCR the image, then run the existing text
	// extract over the OCR text (its GBNF grammar + verbatim grounding + schema).
	// It is NOT a vision task (it composes ocr + extract, each of which dispatches
	// itself), so it is deliberately excluded from isVisionTask.
	TaskExtractImage TaskType = "extract_image"
	// TaskAssessImage is a GBNF-constrained QA over an image: emit
	// {has_people, has_text, matches_brief, notes} so a generated render can be
	// checked against hard exclusions (no people / no text). It IS a vision task
	// (single multimodal call with a grammar), so it is in isVisionTask.
	TaskAssessImage TaskType = "assess_image"
	// TaskVideoDescribe samples frames from a video and asks the VLM a free-text
	// question about them. Frames are fed to the SAME multi-image vision path as
	// vqa; it is its own branch (frame sampling happens first), so it is NOT in
	// isVisionTask.
	TaskVideoDescribe TaskType = "video_describe"
	// TaskVideoWatch watches a video END TO END: the pipeline splits it into
	// time windows, runs each window's sampled frames (absolute timestamps)
	// through the vision seat with the same question, then synthesizes the
	// per-window notes into one answer on the text seat. video_describe sees
	// only the first max_frames/fps seconds; this sees the whole file.
	TaskVideoWatch TaskType = "video_watch"
	// TaskTranscribe converts a local audio/video file to text on a free local
	// whisper.cpp whisper-server (STT). The audio NEVER passes through the text
	// Gemma cascade; it is dispatched directly in pipeline.Run (no prompt, no
	// grammar), like extract_image. Returns {gist, segments[]} + writes SRT.
	TaskTranscribe TaskType = "transcribe"
	// TaskForecast forecasts numeric time series on a local Timestral model served by a
	// llama-swap forecast seat. Input is the canonical JSON payload the forecast server
	// takes; the series NEVER passes through the text cascade (dispatched directly in
	// pipeline.Run, no prompt, no grammar). Returns the server's quantile forecast object.
	TaskForecast TaskType = "forecast"
	// TaskGenerateImage renders a text prompt to a PNG on the LOCAL ComfyUI (SDXL/
	// RealVisXL) for free. Its own branch in pipeline.Run (no prompt cascade, no
	// grammar) — it shells out to render/comfy-generate.mjs, which takes the shared
	// GPU lock and starts/stops ComfyUI. Returns {image_path,width,height,seed}.
	TaskGenerateImage TaskType = "generate_image"
	// TaskInpaintImage generatively re-renders ONLY the masked region of an existing
	// image on the LOCAL ComfyUI (masked re-denoise via VAEEncodeForInpaint; SDXL-class
	// binding required — see config inpaint_*). Its own branch in pipeline.Run — it
	// shells out to render/comfy-inpaint.mjs via internal/gpugen (shared GPU lock +
	// ComfyUI lifecycle). Returns {image_path, seed}.
	TaskInpaintImage TaskType = "inpaint_image"
	// TaskEditImageGenerative rewrites a WHOLE image from a text instruction on the
	// LOCAL ComfyUI, with NO mask (Qwen-Image-Edit class: the model reads the source
	// through its own vision encoder). The third and last edit-shaped route —
	// TaskEditImage is deterministic PIL ops and TaskInpaintImage needs a mask.
	// Its own branch in pipeline.Run — shells out to render/comfy-edit.mjs via
	// internal/gpugen (shared GPU lock + ComfyUI lifecycle). Returns {image_path, seed}.
	TaskEditImageGenerative TaskType = "edit_image_generative"
	// TaskUpscaleImage enlarges a local image with an ESRGAN-family model on the LOCAL
	// ComfyUI (UpscaleModelLoader + ImageUpscaleWithModel; this machine's upscale_model
	// binding). Model-synthesized detail at the model's native factor, optionally
	// rescaled or pinned to a size — enlargement, not a faithful restore. Its own branch
	// in pipeline.Run — shells out to render/comfy-upscale.mjs via internal/gpugen
	// (shared GPU lock + ComfyUI lifecycle). Returns {image_path, model, width, height}.
	TaskUpscaleImage TaskType = "upscale_image"
	// TaskGenerateSVG renders a brand-agnostic parametric SVG component (gauge,
	// comparison-bar, chromatogram, icon) from a JSON spec via internal/svgkit —
	// pure Go, no model/GPU. Its own branch in pipeline.Run. params: kind (string),
	// spec (object), out (string path). Returns {svg_path, width, height}.
	TaskGenerateSVG TaskType = "generate_svg"
	// TaskGenerateVideo animates a still into a short b-roll clip on the LOCAL
	// ComfyUI (HunyuanVideo 1.5 480p I2V / Wan 2.2). Its own branch in pipeline.Run
	// (no text cascade, no grammar) — it shells out to render/comfy-video.mjs via
	// internal/gpugen, which takes the shared single-slot GPU lock and starts/stops
	// ComfyUI with process-tree-kill on timeout. Returns {video_path, seed} plus
	// license/commercial_use when the family declares them.
	TaskGenerateVideo TaskType = "generate_video"
	// TaskAnimateCharacter retargets the motion of a driver VIDEO onto a reference
	// character IMAGE on the LOCAL ComfyUI (WAN-Animate-2 distilled — identity-
	// preserving character animation, the roster's only video-driven retargeting).
	// Its own branch in pipeline.Run (no text cascade, no grammar) — it shells out
	// to render/comfy-animate.mjs via internal/gpugen, which takes the shared
	// single-slot GPU lock and starts/stops ComfyUI with process-tree-kill on
	// timeout. Returns {video_path, seed}.
	TaskAnimateCharacter TaskType = "animate_character"
	// TaskGenerateAudio synthesizes audio on the LOCAL GPU: kind=voice (Chatterbox
	// TTS via render/tts.mjs, no ComfyUI) or kind=music (ACE-Step via ComfyUI). Its
	// own branch in pipeline.Run, dispatching by kind to VoiceGenScript/MusicGenScript
	// through internal/gpugen (shared GPU lock + process-tree-kill). Returns
	// {audio_path, kind, seed}.
	TaskGenerateAudio TaskType = "generate_audio"
	// TaskEditImage applies a deterministic edit pipeline (crop/resize/convert/
	// composite/text, plus GIMP flatten_design for .xcf/.psd) via internal/mediaops.
	// Pure CPU — NO GPU lock, runs in parallel with renders. Own branch in
	// pipeline.Run. Returns {image_path, width, height, ops_applied, layers?}.
	TaskEditImage TaskType = "edit_image"
	// TaskMedia runs one ffmpeg av operation (trim/concat/extract_frames/convert/
	// mux_audio/probe) via internal/mediaops. Pure CPU — NO GPU lock. Own branch
	// in pipeline.Run. Returns op-specific JSON.
	TaskMedia TaskType = "media"
	// TaskComposeVideo renders an HTML/CSS COMPOSITION (a vetted template + variables,
	// an inline single-file html, or a project dir) to video with HyperFrames —
	// headless Chrome in software GL + ffmpeg, deterministic frame by frame. CPU-class:
	// NO GPU lease and no withGpuSlot (ADR 0026), only its own in-process slot. Its own
	// branch in pipeline.Run — it shells out to render/compose-hyperframes.mjs, the
	// only door to the env-scrubbed CLI (ADR 0059). Returns {video_path |
	// frames_dir, duration_sec, fps, frames, width, height, has_alpha, has_audio,
	// codec, render_ms, lint, check, snapshots}.
	TaskComposeVideo TaskType = "compose_video"
	// TaskBrowse drives the operator's own, already-running Chromium browser toward a
	// natural-language goal (ADR 0060). OPT-IN: its own branch in pipeline.Run spawns
	// the sidecar (setup/browse/runner.py) over a stdio protocol; the harness
	// proxies the sidecar's typed choices to a LOOPBACK decision endpoint and writes its
	// field values on the local seat with a grammar. No GPU lease, its own slot. Returns
	// {status, model_done, final{url,title,text}, actions, steps, decisions, text_calls,
	// decision_model, decision_cost_usd, capture_path, captured}.
	TaskBrowse TaskType = "browse"
	// TaskRunGraph executes an arbitrary ComfyUI API-format graph + satisfies its node
	// manifest on the LOCAL ComfyUI. 100% generic — the caller owns graph semantics.
	// Its own branch in pipeline.Run — it shells out to render/comfy-run-graph.mjs via
	// internal/rungraph (shared GPU lock + ComfyUI lifecycle + manifest satisfaction).
	// Returns a node-addressed output envelope {outputs, image_path, unverified_models}.
	TaskRunGraph TaskType = "run_graph"
	// TaskPipelineJob runs an externally-provided pipeline CLI this node is
	// configured for (internal/config Config.Pipelines, keyed by the pipeline's
	// task_type name, e.g. "scene-swap") as a fleet task. Unlike every hardcoded
	// route above, this one is 100% config-driven: adding a new pipeline needs
	// no code change, only a new internal/config Config.Pipelines entry (script,
	// workdir, timeout_sec, artifacts). Its own branch in pipeline.Run — it
	// shells out to the configured script, like TaskRunGraph shells out to
	// comfy-run-graph.mjs. Returns pipeline-defined result fields.
	TaskPipelineJob TaskType = "pipeline-job"
	// TaskAgentRun executes a self-contained delegation contract (agentwire.go
	// AgentContract) with the node's OWN local agent.Build loop: read-only over
	// the contract's materialized ContextDocs, no delegate tool (hop limit 1),
	// planner = this node's agent_model. Its own branch in pipeline.Run (no
	// prompt cascade — the contract IS the task). Returns a marshaled
	// AgentWireResult; a defer is a SUCCESS shape (job done, contract unmet),
	// mirroring the cascade's defer semantics.
	TaskAgentRun TaskType = "agent"
	// TaskAccel runs ONE accelerator tool (a Coral or RKNPU lane; the Hailo-8L is
	// local-only and never runs as a fleet task, register E-08) on this node on
	// behalf of a box that lacks the device (Coral design Phase B, 0.115.0).
	// Payload {accelerator, tool, args, image_b64?, image_name?}: the image
	// travels as bytes (cap AccelImageCap), lands in a job-scoped dir and
	// args.image_path is rewritten to it; a mask the tool writes there comes
	// back as mask_b64. It never touches the text endpoint, so it is exempt
	// from the fleet concurrency cap, and it never forwards again (a node runs
	// only its LOCAL lanes for this task — hop limit 1 by construction).
	TaskAccel TaskType = "accel"
)

func (TaskType) Valid

func (t TaskType) Valid() bool

Valid reports whether t is a known task type.

type Verdict added in v0.206.0

type Verdict string

Verdict is the three-valued result of a graded check. Unknown is not a pass.

const (
	VerdictPass    Verdict = "pass"
	VerdictFail    Verdict = "fail"
	VerdictUnknown Verdict = "unknown"
)

Jump to

Keyboard shortcuts

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