@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,696 lines • 133 kB
TypeScript
/**
* The WIRE frames: the `TaskEvent` union every consumer switches on, and every satellite it
* discriminates with — the per-message identity envelope, the brain-status phases and retry classes,
* the tool activity beat, the human-input source/delivery words, the delegation task type, the
* human-input projection and the compaction outcome. This is the file a change to a frame touches, and
* nothing else. Layer 0 vocabulary; `types.ts` re-exports every name below, so no consumer's import
* changes.
*/
import type { ActorAssertion, UserAttachmentKind, UserAttachmentOutcome } from "../internal/llm.js";
import type { TaskResult } from "./task-result.js";
import type { TaskNotificationPayload } from "./task-notification.js";
import type { ProviderCondition, ProviderConditionSource } from "../brain/provider-dialect.js";
import type { AttachmentSource } from "./attachment-source.js";
import type { BrainStatusSeat, ToolGatePhase } from "./tool-gate-phase.js";
import type { ClassicEventName } from "./mods/classic-events.js";
import type { UserPromptSubmitEvent } from "./hooks.js";
/**
* Identity fields carried by every CONTENT event of a task stream (design/99 §E2 — lightweight message
* identity). Both are OPTIONAL and ADDITIVE; a consumer that ignores them is unchanged.
*
* - `eventId` — a core-minted, time-sortable (uuidv7) unique id stamped on each emitted content event. Gives
* a live UI a stable handle to correlate/dedup streamed events and to map its own client-side message ids
* back to a core anchor. (The durable-anchor mapping for resume-at — which eventIds are restartable
* transcript positions — is finalized by the E18 `resumeAt` seam; this field is the stable handle it builds on.)
* - `parentToolCallId` — present ONLY when this task runs as a sub-agent spawned under a parent task's tool
* call (threaded via the trusted `RunInternals.parentToolCallId`, sourced from the spawning tool's
* `ToolExecuteContext.toolCallId`). Lets a consumer attribute streamed content to the delegation subtree it
* belongs to WITHOUT core physically merging the child stream into the parent (the child's RESULT still
* re-enters the parent MODEL context only through the `delimitUntrusted` fence — observability threading and
* model-context isolation are kept separate, so prompt-cache and the injection boundary are untouched).
*/
export interface TaskEventIdentity {
eventId?: string;
parentToolCallId?: string;
/**
* design/122 S2 (the `WorkflowRun.sourceTaskId` family, NOT a second `taskId` — that
* field already exists on `task_progress` and a duplicate would bite consumers) — the ORIGINATING task's
* canonical id (the leg's single task id mint: a background sub-agent's registry task id, else the
* declared task id, else the session id), stamped ONLY on the content events of a task running AS A
* SUB-AGENT (same condition as {@link parentToolCallId}). A consumer of the C1 forward channel
* (`forwardSubagentEvents`) can key a child's content events by the child task directly, without an
* alias table. A TOP-LEVEL task's own events carry NO `sourceTaskId` (absent = the consumer's current
* task). Additive; a consumer that ignores it is unchanged.
*/
sourceTaskId?: string;
/**
* design/151 S2 (MED-10 live-tail) — the BACKGROUND agent's `a*` registry
* handle, stamped on every event a background child's lane forwards up the host `onForwardEvent`
* channel (content deltas, tool events, progress). THE live-tail routing key: a serving layer
* pipes "what is agent aXX doing right now" straight off the host forward stream — no uuid→a*
* alias table (the BCE spawn frame's sessionId mapping) needed. Sync/steer children carry NO tag
* (no a* row exists); `wa*` workflow rows stay on their own observer lane. Additive; a consumer
* that ignores it is unchanged.
* NESTED bg-in-bg (server[1523] 对等复审 4a): each background boundary OVERWRITES the tag as the
* frame crosses it — on the HOST wire, the whole subtree's frames carry the OUTERMOST a* handle
* (the host-addressable row). Per-frame nesting attribution rides `parentToolCallId`, never this
* field; a consumer splitting an outer stream into per-descendant views keys on that.
*/
bgAgentId?: string;
}
/**
* design/99 §E3/§E10 — a liveness phase of the run's model calls, surfaced so a UI can show why a
* turn is stalled (the engine otherwise absorbs these silently in its connect/retry loop). The PHASE
* itself is provider-NEUTRAL — a graduated bucket this engine mints, never a provider taxonomy or a
* `stop_reason`. The one provider-stated number that does cross this channel is the failing attempt's
* HTTP status, and it travels on its own named seat ({@link BrainStatus.errorStatus}) in the retry
* context only; the phase and the {@link BrainStatus.detail} hint stay free of it.
* A CLOSED union (type-safe) covering the core brain layer and the loop's continuation of a cut answer; a deployment
* that surfaces its OWN states (e.g. E25 token-refresh `authenticating`) does so on its own channel, not by widening this.
*/
export type BrainStatusPhase = "rate_limited" | "retrying" | "reconnecting" | "circuit_open"
/**
* TERMINAL frames closing a sequence a consumer may have pinned a row for. For a model CALL that waited (a retry
* wait, or a `waiting` trail — #530) exactly one is emitted, and only for such a call: `recovered` = the call was
* served after the wait (a later attempt, its output arriving, or the call ending on what had arrived when its
* stream was cut), `gave_up` = the call ended in an error (retries spent, cancelled, or the provider's own error). For
* a CONTINUATION (`continuing`) one per sequence: `recovered` = the continuing turn was not cut (or went on to tool calls),
* `gave_up` = cut again with none left, failed, or the run ended before the next one was sent; a cancelled call adds none.
* Both mean the same thing to a renderer — stop showing the retry state.
*/
| "recovered" | "gave_up"
/**
* A WAIT for the model's output, before any failure: a watchdog is armed on the segment being waited on
* ({@link BrainStatus.waitSegment}) and nothing has arrived on it yet. Emitted once the wait has lasted
* `WAITING_AFTER_MS` and every `WAITING_EVERY_MS` after while it goes on; a wait whose watchdog fires at the threshold
* itself is emitted once at that instant, before the frame announcing the cut. Carries `elapsedMs` / `timeoutMs` /
* `atTimeout`, never a retry countdown (a wait is OBSERVED, not announced). Closed by the call's terminal frame.
* No frame at all when no watchdog is armed on the segment.
*/
| "waiting"
/**
* The run asks the model to CONTINUE an answer whose stream was cut after output had arrived (silent past its idle
* window, or the connection closed under it): what arrived is kept; emitted as the continuing request is sent. Carries
* `attempt` / `maxRetries`; closed by `recovered` / `gave_up`. Minted by the run's loop, not by a model call.
*/
| "continuing";
/**
* WHY a retry wait is happening, as a closed, provider-NEUTRAL bucket — the companion to
* {@link BrainStatusPhase}, which says what the brain is doing about it. A consumer rendering an
* unattended progress line ("no answer for three minutes") needs the reason. (The status has its own seat,
* {@link BrainStatus.errorStatus}; this bucket is the reason a consumer RENDERS and the only carrier for the
* transport classes, which have no status at all.) Values are about the SHAPE of the failure, never its
* provider taxonomy:
* - `connect_refused` — the attempt got a definite negative about the way to the target (nothing accepts
* at that address, the name has no address, or the proxy on the way refused the tunnel). This is the class
* the SHORT retry lane serves.
* - `transport` — any other transport-level failure: a connect timeout, a reset, a mid-stream
* tear. No verdict about the target; the full ladder applies.
* - `stall` — no failure was observed on the link at all: THIS process cancelled its own
* request because one of its stall watchdogs reached its deadline while the stream produced
* nothing. The distinction from `transport` is WHO GAVE UP: a `transport` frame reports something
* that happened to the call, a `stall` frame reports a local deadline. It is not a verdict on the
* remedy — a blackholed connection produces silence too, and silence is what a watchdog measures.
* - `rate_limit` — the provider asked the caller to slow down.
* - `server` — the provider reported a failure on its own side.
* - `http` — a response the status predicate calls terminal, retried anyway because the
* provider's own explicit retry verdict said to.
* - `output_cap` — not a failure of the connection at all: the request is being re-sent with a
* lowered output cap after the provider reported the context limit exceeded (no backoff).
* - `capability` — a request that tried a capability the model's entry does not declare (the thinking parameters) failed
* before any answer, however it failed; the same request goes without it, as the call would have sent it (no backoff; one
* more billed request; `errorStatus` only when a status stated the failure). `attempt` / `maxRetries` are this lane's own (1 of 1).
*/
export type BrainRetryErrClass = "connect_refused" | "transport" | "stall" | "rate_limit" | "server" | "http" | "output_cap" | "capability";
export type { BrainStatusSeat, ToolGatePhase };
/**
* WHAT a `hook_progress` frame's screen holds — the station it screens on, and that station's subject: on
* `classic.PreToolUse`, the call (`toolCallId`, the same id as its `tool_start` / `tool_progress` / `tool_end`); on
* `classic.UserPromptSubmit`, the entrance (`source`, the screen's own `e.source`) and the input's correlation id when the
* entrance has one (`inputId`: every entrance but the objective, which has none to name — never fabricated).
*/
export type HookProgressSubject = {
readonly event: Extract<ClassicEventName, "classic.PreToolUse">;
readonly toolCallId: string;
} | {
readonly event: Extract<ClassicEventName, "classic.UserPromptSubmit">;
readonly source: UserPromptSubmitEvent["source"];
readonly inputId?: string;
};
/** design/99 §E3/§E10 — the payload of a {@link TaskEvent} `status` event (and the brain→runner signal). */
export interface BrainStatus {
phase: BrainStatusPhase;
/** Optional neutral, human-readable hint. Stays free of provider/HTTP detail even now that
* {@link errorStatus} exists: the machine-readable status has its own seat, and interpolating it
* into the prose too would make one fact travel in two spellings a consumer has to reconcile.
* (CC parity: its own retry banner renders a TRANSLATED sentence — "No response from API",
* "Connection dropped" — while the raw status rides the structured key beside it.) */
detail?: string;
/** Seconds until the brain's next retry attempt (from the honored backoff / `Retry-After`), when known. */
retryInSec?: number;
/** Millisecond precision of {@link retryInSec}, for a client that renders a countdown.
* A wait longer than the re-announce slice is re-emitted with the REMAINING time, so a consumer
* that simply overwrites its row always shows a live number instead of a stale one. */
retryInMs?: number;
/**
* The WALL-CLOCK instant the announced wait is expected to end — `Date.now() + retryInMs`, read at
* the moment the frame is emitted, in the EMITTING core process's clock. Stamped centrally at the
* one emit point, so the invariant is total: present exactly when {@link retryInMs} is present, and
* absent on every frame that announces no wait (`recovered` / `gave_up`, and the immediate
* output-cap re-send, which takes no backoff).
*
* WHY IT IS PRODUCED HERE rather than derived by the consumer: `Date.now() + retryInMs` is only
* correct for a reader that received the frame instantly, so a countdown built several process hops
* away restarts on every re-announced slice instead of converging.
*
* CLOCK DOMAIN, stated to remove the ambiguity: WALL CLOCK (`Date.now()`, epoch ms), NOT a monotonic
* reading. A consumer must not compare it against its own monotonic timers, and must treat it as
* approximate across a clock adjustment — {@link retryInMs} stays the authoritative RELATIVE quantity.
*/
retryAtMs?: number;
/** On a `waiting` frame: how long the current wait has lasted, ms, when the frame is emitted (the emitting process's
* clock). Each segment ({@link waitSegment}) counts its own; a `next_token` wait restarts at every content delta. */
elapsedMs?: number;
/** On a `waiting` frame: the ceiling of the segment, ms — the first-byte window, the first-token watchdog, the idle
* window once output began — so a consumer can render "45s of 300s". Absent on every other phase. */
timeoutMs?: number;
/** On every `waiting` frame (absent elsewhere): WHICH wait it is. `response_headers` — the `fetch()` call to the headers
* (connect, upload, and whatever the gateway does before it answers; the engine cannot see these apart);
* `first_token` — the headers to the first content delta (a thinking delta counts); `next_token` — the silence after
* a content delta, until the next one. */
waitSegment?: "response_headers" | "first_token" | "next_token";
/** On every `waiting` frame (absent elsewhere): what the engine does if this wait reaches {@link timeoutMs}, judged by the reading
* the cut itself acts on. `retry` — the attempt is cut and the engine tries again (the same request, or the request without the keys
* of a thinking tier the entry does not declare): a forecast, not a promise that a request goes out (it is judged for sending, and can
* be refused); `keep` — output arrived: the call ends with it, marked cut (`continuing`); `fail` — nothing more is tried: the call fails. */
atTimeout?: "retry" | "keep" | "fail";
/**
* On a retry-wait frame (`phase: "reconnecting"`, `errClass: "stall"`) for an attempt this process ended
* because the HOST WAS SUSPENDED across the wait — the machine slept, or the process was stopped — how long,
* ms: the sum of the gaps longer than five seconds between the engine's once-a-second readings of the wall
* clock, from the start of the wait the attempt was in (response headers, first token, or the silence
* between deltas). The attempt is ended at the first reading where this exceeds half of that wait's window,
* and is re-sent on a fresh connection. Absent on every other frame — a stall a deadline cut carries none.
*/
sleptMs?: number;
/** 1-based index of the attempt that just failed (the wait precedes attempt `attempt + 1`); same numbering as the
* `brain.retry` telemetry frame — on `continuing`, the continuation's number in the current run of cut turns. Absent
* on frames that are neither. */
attempt?: number;
/** The retry budget of THIS lane, so a consumer can render "attempt 3 of 10" (on `continuing`: the continuations allowed
* in a row). Lane, not engine: a failure class served by a shorter ladder reports that ladder's budget. */
maxRetries?: number;
/** Why this wait is happening ({@link BrainRetryErrClass}). Present on retry-wait frames whose cause
* the engine classified; absent on frames that are not a retry wait (`recovered`/`gave_up`) and on a
* `circuit_open` fast-fail, which is a local verdict rather than an observed failure. */
errClass?: BrainRetryErrClass;
/**
* #506 ㋑ — the HTTP status of the attempt that just failed, on the frame announcing the RETRY of it.
* The one provider-stated number this channel carries; everything else about the failure still
* crosses as the engine's own graduated buckets ({@link phase} / {@link errClass}).
*
* WHY IT IS HERE AT ALL, given the channel spent its life refusing it: a UI that must tell an
* operator whether to wait or to go fix something needs the status, and the two neutral buckets
* cannot supply it — `rate_limit` covers a 429 the provider will clear on its own AND a 429 that
* means the account is out of quota, and `server` covers a 500 alongside a 503 behind a load
* balancer. CC states the same number on the same occasion (`system/api_retry.error_status`, read
* off `APIError.status`), so a serving layer forwarding this frame no longer has to choose between
* matching CC's payload and honoring this channel's contract.
*
* PRESENCE — an api_retry context whose attempt got a response that NAMES the failure, and nothing
* else. Present on the connect-ladder retry wait (`rate_limited` / `retrying` / `reconnecting` when
* a response came back) and on the output-cap re-send (the provider's own 400). ABSENT — never
* zeroed, never null — for:
* · a transport failure (`connect_refused` / `transport` at the connect leg): no response existed,
* so no status was ever stated. This is the arm CC spells as an explicit `null`; here it is
* absence, for the same reason every other seat on this interface uses absence, and the fact is
* still TOTAL rather than guessable — {@link errClass} names those two classes by construction.
* · a mid-stream tear (tiers B/C): its response's own status was a SUCCESS, and a status that
* failed nothing must not be published as the cause of a retry.
* · a `circuit_open` fast-fail: a local verdict, nothing was sent, nobody answered.
* · the terminal `recovered` / `gave_up` frames: they announce no attempt.
* Same "only a status that names the failure travels" predicate as the assistant frame's
* {@link AssistantMessage.apiErrorStatus} (one helper, both sites) — a 2xx never travels here either,
* which is reachable on this path via a provider's own `x-should-retry` verdict on a success status.
*
* OPTIONAL, not CC's nullable-REQUIRED, and the difference is CC's own: CC dedicates a whole message
* (`system/api_retry`) to the retry occasion and can therefore require the key on it, while this
* interface is ONE shape shared by every phase — the same geometry as CC's shared
* `control_request_progress` frame, where CC itself makes the key optional.
*/
errorStatus?: number;
/**
* What the provider said about the account or its capacity on the response being retried — one word of
* `PROVIDER_CONDITIONS`, judged off the provider dialect table keyed by where the request went
* (`brain/provider-dialect.ts`). Fills the gap {@link errorStatus} states: {@link errClass} `rate_limit`
* buckets a 429 that clears on its own with one the provider pinned on the account. Only the RETRYABLE words
* ride a retry frame (`throttled` / `overloaded` / `unknown`): a response judged `quota_exhausted` or
* `stop_other` is not retried — its word rides the terminal (`terminal.detail.providerCondition`) — unless
* the provider's own `x-should-retry: true` sent it back into the ladder, in which case the frame states the
* word the response was judged by.
*
* PRESENCE — exactly the connect-ladder backoff frames that carry {@link errorStatus}: a response named the
* failure. ABSENT on a transport failure, a stall, a mid-stream tear, the output-cap re-send (a re-shaped
* request, not a provider condition), `circuit_open`, and the terminal `recovered` / `gave_up` frames. A
* consumer reads absence as "not judged" — the same reading as `unknown`: back off, do not claim a quota.
*/
providerCondition?: ProviderCondition;
/** Which evidence {@link providerCondition} rests on (`unified_header` / `provider_code` / `status`). Present
* exactly when it is. */
providerConditionSource?: ProviderConditionSource;
/**
* What the provider said about the response being retried, in its own sentence — the error envelope's `error.message`, after the one pass
* over a remote's words (the request's declared values and credential shapes masked, a URL or a multi-segment path withheld, one line, at most
* 240 code points). The same member, the same pass and the same bound as `terminal.detail.providerMessage`.
*
* PRESENCE — beside {@link providerCondition}, when the failed attempt's body was read and parsed as a provider envelope that states a sentence:
* a 429 and any other retried 4xx. ABSENT where the ladder decides without reading the body (a 5xx, 408, 409), on a plain-text, torn, unended
* or empty body, and on every frame {@link providerCondition} is absent from. Absence says the provider stated no trusted sentence — never an
* empty string.
*/
providerMessage?: string;
/**
* WHOSE model call this frame is about ({@link BrainStatusSeat}), on every phase — a 429 backoff, a reconnect, a
* `circuit_open` fast-fail or a first-token wait all describe ONE call, and the person watching needs to know it is not their
* turn's. PRESENCE: `"classifier"` exactly on a frame about a call made for the auto-mode classifier lane
* (whichever rung's model it was asked on: the classifier seat's, or the main model standing in behind it). ABSENT =
* the run's own turn: the engine does not state a seat for the person's own model, so a consumer reads absence as "the
* main loop" — never as "unknown". Additive and optional: a consumer that never reads it renders every frame as before.
*/
seat?: BrainStatusSeat;
/**
* @contract status.tool_call_id — the tool call the {@link seat}'s model call is judging, the same id as that call's
* `tool_start` / `tool_progress` / `tool_end`: present exactly on a frame that names `seat: "classifier"`, since every
* classification is asked about one gated call. Absent on the run's own turn's frames. A classification that answers
* before any liveness frame is due reports none — a frame's absence is never evidence that no classifier ran (the call's
* `tool_end.gate` is that record).
*/
toolCallId?: string;
}
/**
* design/97 CORE-8 (③): one lightweight TOOL-ACTIVITY beat surfaced from a running task, for a per-agent live
* "last N tool calls" drill-down. A trusted run-scoped sink ({@link RunInternals.onActivity}) receives one at
* each tool start + end. Structural (name/phase/ids) + a SHORT redacted primary `arg` for display — NOT the full
* ARGS or OUTPUT (those carry untrusted/host data; the workflow layer surfaces redacted prompt/output separately).
*/
export interface ToolActivity {
phase: "start" | "end";
toolCallId: string;
toolName: string;
/** wall-clock stamp (epoch ms, `Date.now` read at the emitting Runner where the frame is
* minted). Carried on BOTH beats: the `start` beat stamps the moment the tool call began, the `end`
* beat the moment it settled — so a consumer derives per-call duration (`end.at − start.at`) and
* inter-call idle (an `end.at` → the NEXT `start.at`). Additive/optional: frames recorded by older
* producers simply lack it (a consumer must treat absence as "unknown", never as 0). */
at?: number;
/** design/99 MF-W: a SHORT primary-arg summary for the monitor's `Read(path)` / `Bash(grep …)` display — the
* single most salient input ABBREVIATED (command→name, path→basename, url→origin+path) + SECRET-SCRUBBED +
* truncated (~80 code points). Set on `phase: "start"`. NOT the full args object, and NOT `redactHostLeaks`
* (that over-redacts the path the monitor needs); the abbreviation + scrub is the leak boundary since the value
* is persisted + SSE-forwarded. See `primaryActivityArg`. */
arg?: string;
/** Set on `phase: "end"` — whether the tool call errored. */
isError?: boolean;
}
/**
* design/171 §5.2/§6.2 — which carrier a piece of human input arrived on. `"external"` = the
* notify() event lane; `"system"` = NOT human input (machine-authored text riding a human-input
* code path) — the speaker projection is a guaranteed no-op for it.
*/
export type HumanInputSource = "objective" | "steer" | "next_turn" | "wake" | "external" | "system";
/** design/171 §6.2 — how a human input was disposed of when its event was emitted:
* `"applied"` = delivered into a model turn; `"queued"` = accepted, awaiting the next turn
* boundary; `"parked_for_wake"` = parked for the session's next run (torn-down lane);
* `"blocked"` (design/373 §4.3, additive — closed-set add, consumers named in the ship post) =
* a PARKED entry was withheld at resume redelivery — the screen runs on EVERY resume kind that
* drains parked steers (policy_ask / dry_run_review / plan_review / resource_limit, wake
* included) — by the deployment's `userPromptSubmit` screen (block verdict, or a fail-closed
* non-answer/crash): the row was consumed, the frame never reached the model, and the sibling
* `steering.parked_input_blocked` notice names the same inputId — "park 时收下、redeliver 时被筛"
* is auditable, never a silent disappearance. */
export type HumanInputDelivery = "applied" | "queued" | "parked_for_wake" | "blocked";
/**
* The fleet-task kinds a DELEGATED run can honestly claim, derived from (never a second spelling of)
* {@link TaskNotificationPayload}'s `task_type` vocabulary — the same axis a consumer already keys
* notifications on. The other members of that union name non-agent lanes (a background shell command,
* a monitor, an externally-produced notification), which no delegated run is; deriving rather than
* re-listing is what keeps the two faces from drifting into two vocabularies.
*/
export type DelegationTaskType = Extract<TaskNotificationPayload["task_type"], "background_agent" | "workflow">;
/**
* Who asked for a tool call no model message carried: an extension's own call (`$.tool.call`), by its registration name.
* A display and audit fact only — the call runs under the run's principal, rules, mode and approver, and the name decides
* nothing. Carried by the call's `tool_start` / `tool_end` and by the approval card an ask for it puts to the person.
*/
export interface ExtensionRequester {
readonly kind: "extension";
readonly name: string;
}
/**
* Who replaced the arguments the gate let a tool call go with, one entry per replacement: an extension of this leg by its
* registration name (its `classic.PreToolUse` answer's `updatedInput`); the leg's restriction chain (`policy` — the bytes came
* back in the chain's answer, whoever inside it wrote them: the deployment's `ToolPolicy`, a constraint the leg inherited (an
* ancestor leg's screening among them), an approver a layer consults itself — the layer word a refusal of that chain carries); or
* the approver of the call's ask, who answered with other arguments (`approver` — whether a person or the host's own approver is
* the frame's `gate.settlement.who`).
*/
export type RewriteAuthor = ExtensionRequester | {
readonly kind: "policy";
} | {
readonly kind: "approver";
};
/** The arguments the gate let a call go with when they are not the ones it took ({@link RewriteAuthor} names who replaced them). */
export interface ToolInputRewrite {
/** One entry per replacement that changed the arguments, in the order they were made (a judge that changed them twice is named twice). */
readonly by: readonly RewriteAuthor[];
/** The arguments the gate let the call go with, as the gate's frozen plain-data projection of them (the `finalInput` it records:
* a member that is not plain data — a bigint, a cycle's closing member — reads as a `[not recorded: …]` marker). */
readonly input: unknown;
}
/** Streaming events surfaced from a running task (for live UIs). */
export type TaskEvent = ({
type: "text_delta";
delta: string;
} & TaskEventIdentity) | ({
/**
* The assistant's streaming PROSE SEGMENT is COMPLETE: the model closed the text content
* block whose bytes just streamed as `text_delta`s. This is the explicit segment boundary a
* REMOTE consumer needs so it never has to guess segment ends from wire silence. CC-aligned: block
* completion IS the segmentation signal there (CC's agent stream yields each finished content block at
* the provider's `content_block_stop`), and this event is that same boundary surfaced on the TaskEvent
* wire.
*
* `content` = the FULL text of the completed segment as the brain closed it — a consumer commits
* the segment from it instead of trusting its own delta stitching. It is not a promise about the
* committed message: when the turn finalizes the brain may still trim a degenerate cut's looped tail,
* add engine notes as blocks of their own, or (opt-in) rewrite text it read as tool calls. The final
* answer's one authority is `TaskResult.result`, and `TaskResult.resultEntryIds` names the committed
* messages it was read from. UNTRUSTED model output for
* display only, same contract as `text_delta`. Emitted only for a segment that holds bytes: an
* empty text block closes silently (a boundary with no segment would render phantom rows).
*
* Additive + ignorable. HONEST ABSENCE: the frame exists only when the serving Brain reports
* block ends (`text_end` on its event stream — all three first-party brains do; a custom brain
* that never emits them yields a wire without this frame). A consumer treats per-segment
* presence as the signal and falls back to its own heuristic only on streams that carry none —
* absence is "unreported", never "the segment did not end".
*/
type: "text_end";
content: string;
} & TaskEventIdentity) | ({
type: "reasoning_delta";
delta: string;
} & TaskEventIdentity) | ({
/** A REASONING SEGMENT is complete — `text_end`'s twin for `reasoning_delta`: the brain closed the thinking block (OpenAI:
* when answer text starts/resumes or at attempt exit; Anthropic/Open-Responses: on provider block/item close or attempt exit;
* reasoning after text began is its own segment). `content` = full segment text, untrusted, non-empty only; absent if a custom brain
* emits none or the Runner's call guardrail / loop relay timer cuts first (terminal follows). Live `contentIndex` is arrival order, not saved index. */
type: "reasoning_end";
content: string;
} & TaskEventIdentity) | ({
type: "tool_start";
toolCallId: string;
toolName: string;
/** {@link ToolSpec.label} when distinct from `toolName`; omitted otherwise. */
label?: string;
args: unknown;
/**
* @contract tool_start.recovered — `true` on a start frame the engine minted at the moment it CLOSED a call
* whose start never went out on this stream: an interrupted run's reconcile closing a call the loop never
* reached, or a resumed process closing a call a dead process had announced. Every `tool_end` is preceded by
* a `tool_start` with the same id on the same stream — this frame is how that holds for those closes. `args`
* is the call's input as the transcript recorded it. It asserts NOTHING about execution (whether the call
* ran is the paired `tool_end.notExecuted`); absent on every start the loop announced itself.
*/
recovered?: true;
/** An extension's own call (`$.tool.call`): who asked for it. Absent on every call a model message carried. The call is
* not part of the conversation — no tool-result message follows it into the transcript. */
requestedBy?: ExtensionRequester;
/**
* @contract tool_start.resumesCheckpoint — on the held call a resumed leg runs: the id of the checkpoint row the leg
* was opened from, the id the parking leg's paused terminal (`terminal.checkpointId`) and the row itself carry. It is the one join between the parking
* leg's frames for the call and the resumed leg's, minted once where the resumed leg opens the held call, and the
* paired `tool_end` carries the same id. Absent on every other call (a live leg's calls, the resumed leg's later calls,
* an interrupted run's reconcile closing a call at a later process start), and on a held call whose row carries no id.
*/
resumesCheckpoint?: string;
} & TaskEventIdentity) | ({
/**
* A LIVENESS TICK for a tool call that is still running. Emitted on the run's own queue between this
* call's `tool_start` and `tool_end`, under the same ordering law as every other content frame, and
* forwarded to a parent's display sink under the SAME opt-in as those two
* (`TaskSpec.forwardSubagentEvents`).
*
* ONE FRAME, not two: the reference splits this into a per-tool `tool_heartbeat` plus Bash's own
* `bash_progress`; this engine mints the single shape and lets the OUTPUT KEYS be what is conditional.
* Registered divergence.
*
* @contract tool_progress.cadence — AT MOST one frame per second per tool call, enforced at the mint over
* ALL producers rather than inside each one (a producer's own timer is a sampling clock, not the contract),
* and a call's first frame is never earlier than one interval after that call was first announced to the lane (its gate
* entry or its first frame). A call that finishes inside one interval emits NO frame at all — this frame's absence is never
* evidence that a call did not run, and a consumer must not expect one per `tool_start`.
*
* @contract tool_progress.ephemeral — LIVE ONLY, like `task_progress`/`status`: core never persists this
* frame (no session-tree entry, no checkpoint state, no resume replay), and a resumed leg re-ticks from
* its own clock. A consumer wanting a DURABLE record of a long call keeps {@link elapsedTimeSeconds} —
* never {@link output}, untrusted process bytes bounded for a pane (the tool's result is the kept face).
*
* Additive and ignorable: a consumer switching on event type and dropping unknown members is unchanged,
* and no gate, policy, memory or model-context path reads this frame.
*/
type: "tool_progress";
/** The still-running call's id — the join key to its own `tool_start`/`tool_end`. */
toolCallId: string;
/** The running tool's name (the `tool_start` value verbatim). */
toolName: string;
/** Whole seconds since the engine released the call into execution, floored and MONOTONIC across its frames;
* 0 while it waits at its gate. ONE ORIGIN per call, stamped by the mint rather than by whichever producer
* emitted — the release, earlier than a shell command's spawn. It does NOT equal the `tool_end` duration. */
elapsedTimeSeconds: number;
/**
* The TAIL of what the command has written so far (stdout and stderr interleaved in arrival order),
* bounded by the mint to a small number of trailing lines — a live pane, never a log.
*
* UNTRUSTED RAW, exactly as `tool_end.output`: process output that may carry secrets, paths or PII;
* core bounds only its SIZE, and a consumer MUST redact before persisting or displaying it. Never
* re-feed it to a model — it is a moving, truncated window.
*
* ABSENT, together with {@link totalLines} and {@link totalBytes}, exactly when the call has produced
* NO output through this environment — it printed nothing (`sleep 3`), or the environment does not
* stream (a buffered remote `exec` never invokes the output callbacks). The three ride or stay away
* together: present = "output has been observed", absent = "none has been observed", never
* "unchanged since the last frame".
*/
output?: string;
/** Newlines observed in the command's output so far (≥ the line count of {@link output}, which is
* only its tail). Rides iff {@link output} does — see its absence law. */
totalLines?: number;
/** Bytes observed in the command's output so far, counted BEFORE the tail bound, so it keeps
* growing after {@link output} stops being able to. Rides iff {@link output} does. */
totalBytes?: number;
/**
* @contract tool_progress.gate — WHO holds the call at its gate when the frame is minted ({@link ToolGatePhase}):
* `classifier` while an auto-mode classification of the call is in flight (the leg's own classifier, or an ancestor's
* frozen one judging it), `approval` while a question about it is put to a person, `hook` while a `classic.PreToolUse`
* screening of it is in flight. The innermost open hold is named (a screening can settle an inherited installation's
* question inside it: `classifier` over `approval` over `hook`). Absent when nothing holds it at the
* gate — before the gate, between two gate rounds, after its release to the executor. Read off the call's one
* occurrence record at the mint, so a heartbeat and a producer's tick say the same. Two absences follow from the
* laws above and say nothing: a classification that answers inside one interval leaves no frame naming it (the call's
* `tool_end.gate` is the record that it ran), and while EVERY call in flight waits on the person nothing is beaten, so
* `approval` rides only a frame minted while some other call is working. The classification's own model-call
* liveness is the `status` frame naming this call (`status.toolCallId`).
*/
gate?: ToolGatePhase;
} & TaskEventIdentity) | ({
type: "tool_end";
toolCallId: string;
toolName: string;
/** {@link ToolSpec.label} when distinct from `toolName` (design/71 liveness); omitted otherwise. */
label?: string;
isError: boolean;
/**
* design/99 §E1 — the tool's MODEL-FACING result content, surfaced for a live UI
* that renders tool output. It is the harness `AgentToolResult.content` the mapper already produced
* (previously dropped here); the internal `details` payload is NOT exposed (e.g. a sub-agent tool's
* `details` is the entire child `TaskResult`).
*
* **Type is `unknown` and intentionally non-uniform** — a `string` result stays a string (over the core text cap it is
* cut, never inside a surrogate pair, and ends with the `…[+N chars truncated]` marker: the cap is in UTF-16 units, `N` counts Unicode characters); a `(TextContent|ImageContent|DocumentContent)[]` result stays
* an array whose blocks keep their slots. One rule for the array (see {@link truncated}): its text blocks (each at its
* text plus whatever else it carries) — with any block that is neither text nor an admitted image/document, at its
* serialization — are one character stream under the text cap, cut IN
* PLACE where the cap runs out (that block ends with the marker, the stream's later blocks leave); MEDIA blocks are not
* measured against the text cap and ride AS-IS while the leg's media budget lasts (`RunnerDeps.mediaBudgetBase64Chars`,
* default `IMAGE_ADMISSION.request.budgetBase64Chars`: base64 characters, spent as wire bytes after the text's
* serialized size), past which a block becomes `{ type, mimeType?, bytes, truncated: true }` in its slot (never a
* string; a media type over 255 characters is not echoed), and when not even a descriptor fits, it and every later
* media block fold into ONE `{ type: "omitted", blocks, bytes, truncated: true }` in its slot, so the media in an event
* is bounded at any block count. A consumer must handle both shapes.
*
* **UNTRUSTED RAW + for OBSERVABILITY ONLY**: it is external tool output (file reads, shell stderr, API
* bodies) and may carry secrets/paths/PII — core bounds only its SIZE; a consumer MUST redact and MAY
* further bound before it persists or displays it (same contract as `tool_start.args`). It is for a live
* UI / trace, NOT for re-feeding to a model: a truncated body would mislead an LLM, and the model already
* has the full, untruncated result in its own context — build model prompts from the session, never by
* replaying this field. The engine's two model-facing readers of it, the observer digest and the sub-agent step
* outcome, render a block through the one block rendering (text as text, any other block as its `[type: mimeType]`
* marker, never its payload).
* Absent when the tool produced no content body.
*/
output?: unknown;
/**
* design/116 (b) — the tool's CC-shaped `toolUseResult` facts: `details.type` ∈ the engine's card set (`engineCardTypes()`,
* derived from the tool catalog) ∪ the leg's caller-declared `renderHints.resultCards`, surfaced on the live wire so a
* CC-faithful shell renders rich cards (red/green diff, stdout panes, file cards) without re-parsing the model-facing
* string. Absent when the tool carries no card shape or when the serialized card exceeds the size bound (omitted whole;
* its skeleton — facts, not a card to render — may ride {@link structuredSkeleton}; the display falls back to `output`).
* UNTRUSTED RAW like {@link output}: a consumer MUST redact before persisting or forwarding.
*
* **The card set is a two-way contract**: every entry has a tool that mints it and every minted card is registered — a
* consumer switching on `details.type` meets no promise nothing keeps and no card it was never told about.
*
* The four **file** cards (`create` / `update` / `edit` / `notebook-edit`) carry `contentSha256` — **NOT a digest of the bytes
* on disk** (`sha256sum` of the file differs whenever it has a BOM or CRLF endings): the hex sha-256 of the file's TEXT as the
* engine reads it back after this write (decoded, BOM dropped, CRLF as LF), the value its read-before-write check holds.
*
* The **advisor** card (`type:"advisor"`, the advisor tool's every call) carries closed words, numbers and catalog ids
* only — `outcome` (`reviewed` / `declined` / `unavailable`, and `isError` ⇔ `unavailable`), `model`, `servedModel?`,
* `stopReason?`, `code?` / `errorKind?` (the failure's own words), `hold?: true` (this failure's cause switches the
* advisor off for the conversation until it is compacted — a classification, not a promise: the transcript says so once
* the result is recorded) and `usage?`. The guidance, a refusal's reason and an error's message ride {@link output}.
*
* **Leak boundary**: the allowlist gates by `type`, so what rides is whatever the minting tool put
* in the object — which makes each mint site responsible for its own field set. The Agent family's
* completed card is therefore built from an EXPLICIT whitelist rather than a child-`TaskResult`
* spread: a `TaskResult` can carry `checkpointToken` (the resume CAPABILITY) on the
* `unexpected.suspended` terminal, and that field, with `checkpointGate`, never leaves the process.
*
* **双面契约(`tool_use_result` describe;P2-3)** — a tool
* result has TWO faces that never substitute for each other:
* - **模型面** = {@link output} / the tool_result text: the string the MODEL reads. It may carry
* model-directed framing — e.g. a delegation tool's trailer (agentId / usage lines the model uses to
* address SendMessage or budget itself). That framing is FOR THE MODEL; it is not a host data format.
* - **宿主面** = this field: the tool's structured Output object, per-tool shaped, keyed by the matching
* tool call's name. For a delegation/Agent-family tool the completed shape is the subagent's final
* report WITHOUT the model-directed trailer, plus run totals (CC names it `AgentToolCompletedOutput`).
* Both Agent shapes ride `type:"agent"` and are told apart by `status`: `"async_launched"` is the
* background launch RECEIPT (task_id / description / prompt), any other value is the completed
* landing report (`result` / `stats` / `resolvedModel` / `toolStats` / kept `worktreePath` /
* failure attribution). Branch on `status`, never on which keys happen to be present.
* A host/shell MUST render from `structured` and MUST NOT parse the model-facing text back into data
* (trailer wording is model-audience prose and may change without notice); symmetrically, core never
* strips the trailer from the model face just because the structured face exists — the model still needs
* it in-context. When `structured` is absent, the honest fallback is to display `output` as opaque text,
* not to scrape it.
*/
structured?: unknown;
/**
* The SKELETON of a card left off {@link structured} by the size measure (a card with no JSON measures infinite) — never
* beside it: which of the two is present says whether the card is whole. `type` plus the members its kind declares
* fixed-length (`CARD_SKELETONS`), as the tool wrote them: a file card keeps its path and `contentSha256`, a caller-declared
* card `type` alone. Absent when not even that fits or a declared member cannot be read. UNTRUSTED RAW like `structured`.
*/
structuredSkeleton?: {
type: string;
} & Record<string, unknown>;
/**
* Present iff {@link isError} is true AND the harness result's `details` carried a string
* discriminator — or on the frame of the call a durable park HOLDS ({@link park} present: `"gate.parked"`, kept there while
* hosts move to `park`, #4317) — read as `details.code` first, falling back to `details.errorKind` (each must be
* a string; `code` wins when both are present, as the deliberate tool-chosen spelling). The
* `errorKind` leg is what makes a LOOP-THROWN error's frame classifiable: the loop's thrown-error
* fold and the resume legs write the discriminator under that name. Lifted so a consumer never
* has to parse the (contract-stable) result text. Engine-minted vocabulary today includes
* `"tool.not_found"` (unknown tool name, retired name, or unmounted shell tool), `"gate.parked"`
* (an abort short-circuit contaminated this call because a durable gate parked the batch — the "Operation aborted" family), and, for a
* failed MCP tool call, the MCP failure class — see {@link import("./mcp-failure.js").McpFailure.kind}
* for the words (the same closed set the per-server status and the wiring manifest's `mcp[]` carry;
* this frame only transports it), and the `config.*` refusal an engine seat throws out of a tool body (the parent-seat,
* retired-member, registry-seat, checkpoint-store, skill-activation and host-floor refusals, minted by `codedRefusal` — a
* platform error's own code is never lifted). A delegation tool's failure (the Agent family, spawn and fork): the child's
* failure code, when it is an engine word, else the kind its thrower declared. Additive: absent on error frames minted before this field
* existed, and on error results whose details carry no string discriminator under either name.
*/
errorCode?: string;
/**
* @contract tool_end.delivered — WHETHER THE REQUEST REACHED ITS SERVER, when this frame closes a
* failed call whose result carried the MCP failure record: the closed
* {@link import("./mcp-failure.js").McpDelivered} (`"yes"` / `"no"` / `"unknown"`), lifted from
* `details.delivered` beside {@link errorCode} and read TOGETHER with it — the same `errorCode`
* (`connection_closed`) is safe to retry at `"no"` (nothing was sent) and must be verified first at
* `"unknown"` (the request may have executed). The meaning of each word is owned by
* {@link import("./mcp-failure.js").McpFailure.delivered}; this frame only transports it. Screened
* against the closed set (an out-of-vocabulary value is not lifted) and never derived from the
* code or the text. The same verdict rides a protocol call the revocation ledger stopped (MCP or A2A) and an A2A
* skill call whose answer refused it with a class (#4523). ABSENT on every frame whose result carried no such verdict —
* every executed call and every other failure — and a consumer must not read a semantic out of the absence.
*/
delivered?: import("./mcp-failure.js").McpDelivered;
/**
* WHICH call the gate was holding, when this frame is a park-contamination frame — the tool call
* id of the gated call. Three conditions, ALL required: `errorCode === "gate.parked"`, the run is
* tearing down behind a committed park, and that park binds a tool call at all.
*
* **WHERE IT COMES FROM — never lifted from the result**, and deliberately unlike its neighbour
* {@link errorCode}: that one IS the result's own `details.code`, i.e. tool-authored, because a
* tool classifying its own failure is bounded self-description. This field is an assertion about a
* DIFFERENT call, so a tool able to author it could point an approval UI at a call nobody is
* holding. It is therefore engine-minted — read from the run's committed park holder and handed to
* the frame projection as a parameter, the same posture (and the same reason) as {@link settledBy}.
* `errorCode` only participates in selecting WHETHER the id is placed; it never supplies the
* value, and on its own it is not enough — the run must also be aborting behind a real park, which
* is why a tool declaring `gate.parked` on its own failure cannot conjure this field.
*
* Why it is on the frame: a durable gate parks ONE call and the loop then short-circuits every
* sibling in the batch with an identical "Operation aborted" body, so `gate.parked` alone says
* "something parked this batch" without saying WHAT. A consumer wanting to render "waiting on
* <the gated call>" beside the collateral frames otherwise has to re-derive the pair from batch
* adjacency and timing — an inference that is wrong exactly when it matters (a batch with more
* than one ask candidate, a reordered stream).
*
* ONLY EVER STRUCTURALLY PROVEN, never guessed: the id is read off the committed checkpoint's
* pending tool call, so it is the same value the checkpoint parks on and the same value the
* decide/resume lane answers about. It is therefore ABSENT — not approximated — for the park
* kinds that hold no call (a resource-limit slice, a plan review), and absent for every abort
* that is not a gate park at all (user interrupt, timeout, walltime): those frames are
* byte-unchanged. Absence means "core cannot prove a causal call", never "there wasn't one".
* The held call's OWN frame (`gatedCallId === toolCallId`) is not a contamination frame since 7.70.0 (#4317): it reads
* `isError: false` and carries {@link park}; the id stays on it beside `errorCode` `"gate.parked"` for hosts that keyed on them.
*/
gatedCallId?: string;
/**
* The call a durable park is HOLDING (#4317): the gate parked the batch on THIS call, which has not run
* and waits for its decision. The frame reads `isError: false` and `notExecuted: true`, its `output` says the call waits (an
* approval's card, or a question's), and this member states the park in the poll faces' shape
* ({@link import("./agent-state.js").AgentPark}): `state` `"pending"`, the card's `gate`, its `checkpointId` (or
* `checkpointIdMissing`). Engine-minted off the run's committed pause, never read from the result. PRESENT only on that one
* frame of a run that parked on a call; ABSENT on every other frame — the batch's other calls still close aborted
* (`errorCode` `"gate.parked"`, `gatedCallId` naming the held call). When the park is resumed, the call's real end follows
* on the resumed leg (`resumesCheckpoint`), and the held result is not in the transcript the resumed model reads.
*/
park?: import("./agent-state.js").AgentPark;
/**
* The gate's record of the pass that admitted or refused this call, when the call went through the
* tool gate at all ({@link import("./gate-outcome.js").GateOutcome}): `disposition` (allowed, or
* denied by which LAYER), `settlement` (how the ask this pass consumed ENDED — a person's yes or
* no with the channel's attribution and, on a bare "no", no note; a window that elapsed and whose;
* nobody reachable; the wait aborted…) and `origin` (who ASKED). It is the SAME object the
* `permissionDenied` observer received and the call's occurrence record holds — one mint, three
* faces — so a renderer never branches on prose to tell "a person refused" from "the window closed".
*
* WHERE IT COMES FROM — never inferred here: the gate mints it at its exit, the decide lane mints it
* from the host's decision facts joined with the row's persisted origin.
*
* THE LATEST RECORD: a station that refuses the call AFTER its gate exit (the shell read admission that
* re-establishes what the gate judged and finds it moved, a resumed leg's re-checks) adds one more
* record, minted as a veto — the refusing layer is the disposition, an approval already given stays on
* the settlement — and this member is that record. A call refused after its gate allowed it therefore
* reads `denied`, never `allowed` beside an error, and {@link isError} is `true` whatever the tool's own
* result said.
*
* ABSENT on every frame of a call no gate exit on this stream saw (a tool call on an unarmed gate, a
* deferred re-issue, a call a reconcile closed that never reached a gate here). A gated call's frame
* ALWAYS carries it — an absence is not a fact about the call, and a consumer must not read one out of it.
*/
gate?: import("./gate-outcome.js").GateOutcome;
/**
* @contract tool_end.wireName — on a REFUSED call's frame only (`gate.disposition.kind === "denied"`): the name of
* the tool the call dispatched to on the live roster — the name the gate judged and the deny observer's `toolName`
* — where {@link toolName} is the model's spelling (an alias, a retired name the roster still answers to). A
* refusals list keyed on the tool reads this member; absent on every other frame, and on a refused frame whose
* station did not know the roster name.
*/
wireName?: string;
/**
* @contract tool_end.refusedInput — on a REFUSED call's frame only (`gate.disposition.kind === "denied"`): the
* arguments the refusal was ruled over, as the call's latest gate exit recorded them (after any rewrite the call
* took on its way in) — the frozen record a deny exit hands the deny observer its copy of, and, on a call refused
* after its gate let it go with a rewrite, the very record that frame's `rewrite.input` carries; never a second
* capture. So a refusals list shows what was refused without joining it back to the start frame, whose `args` are
* the model's bytes before any rewrite. UNTRUSTED RAW like `tool_start.args`: a consumer MUST redact before
* persisting or forwarding. Absent on every other frame, and on a refused frame no gate exit recorded an input for.
*/
refusedInput?: unknown;
/**
* @contract tool_end.notExecuted — `true` when the engine has POSITIVE evidence this call never executed:
* the loop closed it without running it (a sibling settled by a halted batch, a call a turn interrupt
* reached before it started), an interrupted run's reconcile closed a call this run never started, or the
* engine's own judgment REFUSED the call and never let it go to its executor (a person's refusal, the host's
* SLA sweep, a policy or hook or plan-mode deny, a post-approval veto before the run — read off the call's
* occurrence: the latest {@link gate} record is `denied` and the life never reached the release). A refusal
* recorded AFTER the release (a station inside the execution, such as the shell read admission) is not
* evidence. The persisted `toolResult` row repeats the frame's mark as `details.notExecuted: true` (a live
* leg's rows, the resumed leg's and the reconcile's appended close) — the engine's key alone: a tool's own
* value under that name is dropped from the row.
* It is also set on a call whose gate LET IT GO and which the loop itself then refused before the body started:
* the arguments the gate cleared failed the loop's own re-validation or re-reading (a rewrite the tool's input
* check refuses, a form the tool would read as other bytes), or the run was aborted in that gap. Such a frame
* reads `gate.disposition` allowed, `isError` (with an `errorCode` when the refusal carries one), this mark — and, when the gate replaced the
* arguments, {@link rewrite} beside them. A call refused before any gate saw it (an unknown tool, arguments the
* model's own call got wrong) carries no mark: nothing there says whether the loop got that far.
* ABSENT means only that no such evidence exists — never "it ran": a call closed with its outcome unknown
* (a reconcile at the next process start, a call interrupted mid-execution) carries no mark, because
* telling a consumer it did not run could invite a replay of a write that already took effect.
* One more source of that evidence: an extension at `tool.call` answered for the call in place of its body (its own
* result, or its refusal) — the body was never called; {@link answeredBy} names it.
*/
notExecuted?: true;
/**
* The extension (its registration name) that answered for this call at `tool.call` in place of the tool's body — a
* result of its own, or a refusal — so the body never ran (`notExecuted` is set beside it). Absent on every call
* whose body ran or that no extension answered.
*/
answeredBy?: string;
/**
* @contract tool_end.rewrite — the gate let the call go with arguments other than the ones it took: `input` is what it
* let the call go with, `by` who replaced them. Whether the body then ran is the frame's other members' to say (`isError`
* with `errorCode`, as for a tool's refusal of those arguments; {@link notExecuted}) — this member is never evidence that
* it did. Present exactly when the gate's allow exit let the call go, no extension answered for the call in place of its
* body, and the arguments it let the call go with differ from those it took at its entry (both as the tool reads them —
* the loop's argument preparation and schema coercion are no rewrite, so the comparison is never against `tool_start.args`,
* which stays the model's own). Absent on a call refused before it was let go, on a parked or answered-in-place call, and
* on one whose arguments were replaced and then set back; a refusal recorded after the call was let go (the shell read
* admission inside the execution, the loop's own refusal of the arguments the gate cleared) leaves it beside that refusal
* — the call was let go with them. On the frame only: the persisted `toolResult` row does not repeat it. A resumed leg's
* frames do not carry it.
*/
rewrite?: ToolInputRewrite;
/** The same member as the paired `tool_start`'s: an extension's own call, and who asked for it. */
requestedBy?: ExtensionRequester;
/** The same member as the paired `tool_start`'s: `tool_start.resumesCheckpoint`. */
resumesCheckpoint?: string;
/**
* design/99 §E1 — `true` exactly when {@link output} is not the content the tool returned: text was cut at the cap
* (the string, or the block at the cut, carries the marker; the stream's later blocks left), a media block was
* replaced by its descriptor, media folded into the summary, or content that could not be read was replaced by the
* one `[unserializable tool output]` string. Lets a consumer detect truncation programmatically
* instead of parsing the marker out of the text; a media block carries `truncated: true` on its own descriptor.
* Absent/false = `output` IS the returned content, every block in its slot. (The full untruncated result still
* lives in the model's context / `ToolResultStore`.)
*/
truncated?: boolean;
/**
* Present iff {@link truncated} and the content could be read: the TRUE original size (characters) of
* the value this event's {@link output} was bounded from — for a string result, the string's own
* length; for a non-string result (a blocks array), the SUM of each block's own true size (a text
* block's `.text.length` plus whatever else it carries at its serialized length; an image/document block's
* `.data.length`, i.e. its base64 payload, whether the
* block rode as-is or was replaced by its descriptor; any other block, outside the tool contract, its serialized
* length) — never `JSON.stringify(content).length`, which is
* polluted by two different kinds of noise: structural overhead (field-name/punctuation bytes that aren't
* content at all) AND, for text containing quotes/backslashes/control characters, escape inflation (a
* real result: 17298 reported vs 13696 true content characters).
*
* **Not arithmetically tied to the marker's own `N`**: the marker counts, in Unicode characters, how much MORE of the shown text
* exists beyond the cut point; `totalChars` counts, in UTF-16 units, the whole ORIGINAL value, media blocks included, so it
* can run far ahead of the cap plus `N`. Read what was cut from the marker (text) and from the
* descriptors' own `bytes` (media), not from the gap.
*/
totalChars?: number;
} & TaskEventIdentity) | ({
/**
* Context occupancy at a compaction boundary, emitted on EVERY
* boundary (not only when a compaction fires). The three numbers are the engine's own trigger
* inputs, verbatim: `usedTokens > compactAtTokens` IS the predicate `shouldCompact` evaluates, so a
* consumer's "context is N% full" indicator and the moment compaction actually fires can never
* disagree. Re-deriving the numerator downstream is precisely what this exists to prevent.
*
* Deliberately NOT a field on `turn_end`: the boundary check runs AFTER that event, over the
* post-flush message set, so a value attached there would be a different (earlier) measurement
* wearing the same name. `windowTokens` is the AUTOCOMPACT window — a model declaring
* `autoCompactTokens` keeps a LARGER physical request window — so do not present it as "the
* model's context size".
*/
type: "context_usage";
usedTokens: number;
windowTokens: number;
compactAtTokens: number;
/**
* Additive — the leg's system prompt broken down by pack SECTION. Meaning, and the readings it
* forbids, are owned by `contextUsageSections` (`prompt-assembly/section-usage.ts`, `@contract
* context_usage.sections`): PREPARE-TIME estimates in a different coordinate from {@link usedTokens},
* never compared to {@link compactAtTokens}. Absent when the leg assembled no section IR — "no section
* view", never "the sections weigh nothing".
*/
sections?: readonly import("../prompt-assembly/section-usage.js").ContextUsageSection[];
} & TaskEventIdentity) | ({
type: "turn_end";
/**
* Per-turn token usage + cost (the turn that just ended), for live per-turn accounting / a trace UI
* (service [41]). Re-priced in core from injected pricing (authoritative, like `TaskResult.stats`).
* ALWAYS present: a turn that produced no provider usage frame carries the counted ZEROS beside
* `usageMissing: true` — zero is unknown, not free, the one law `TaskResult.stats` states (numbers
* always present, the flag says they under-count), so a consumer handles ONE frame shape.
*
* `inputTokens` is the cache-MISS count (Anthropic-protocol shape, matches
* `stats.promptTokens` / the tracer's `brain.call.promptTokens`); `totalInputTokens` is the
* cache-INCLUSIVE total (`inputTokens + cacheReadTokens + cacheWriteTokens`) that cost is computed
* from. Sum `totalInputTokens` for context/window/spend views; read `inputTokens` only where the
* protocol's `input_tokens` is meant. Up to 2.13.x `inputTokens` carried the total.
*/
usage: {
/** Cache-MISS input tokens for this turn (the Anthropic protocol's `input_tokens` meaning;
* matches `stats.promptTokens` / `brain.call.promptTokens`). **Up to 2.13.x this field
* carried the cache-INCLUSIVE total** (RB-457-a, BREAKING at 3.0.0) — that value now lives
* in `totalInputTokens`. Read this only where the protocol's `input_tokens` is meant. */
inputTokens: number;
/** Cache-INCLUSIVE input total for this turn (`inputTokens + cacheReadTokens +
* cacheWriteTokens`) — what cost is computed from. Sum THIS for context/window/spend
* views; it equals what `inputTokens` carried up to 2.13.x. */
totalInputTokens: number;
outputTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
costMicroUsd: number;
/** Wall time, in milliseconds, of this turn's model calls, summed — each call from the moment the engine hands the request to
* the brain to its final message (the `brain.call` row's `ts − callStartedAt`; a failover walk is one call, its abandoned hops'
* time inside it). A request the loop re-sends in the turn and shows (a refused image sent again without it) counts; one it
* withholds and retries (a prompt-too-long recovery) is not seen. A call with no stamp adds 0 (a hop a fallback walk left
* behind, a turn no model answered). Present on every `turn_end` this engine mints. The leg's total, one run's not a
* session's, is `TaskResult.stats.apiDurationMs` (the reference result's `duration_api_ms`; this per-turn member is ours). */
apiDurationMs?: number;
/** `"fast"` when the provider served every model call of this turn at fast speed (each call's `Usage.speed`); else absent (a
* call at standard speed, or silent). Count: `TaskResult.stats.fastSpeedCalls`. Such a call's share of `costMicroUsd` is at its
* table's fast tier; with none, or with one the table judge refuses (an empty or partial `fast`), an unmarked standard-rate
* lower bound (the run's total is then absent; a $ ceiling stops it). */
speed?: "fast";
};
/** TB 尸检 T1-5: set when the turn ended WITHOUT a provider usage frame (e.g. a degenerate-repetition
* cutoff cancelled the stream before usage arrived) or the brain flagged its frame unknown. Consumers
* must treat `usage` as UNKNOWN — its zeros are not a measured 0 (the provider still served the
* request; `stats` under-counts it honestly rather than polluting the single-source accounting
* with an estimate). Absent on a measured turn (never `false`). */
usageMissing?: true;
/** Present (`true`) when some model call of this turn did not report its cache reads: `usage.cacheReadTokens` is then the
* counted sum (an unreported count adds nothing), not a measurement — UNKNOWN, never a 0% hit. Where the provider's
* input excludes the cached parts the turn's total is then a lower bound too, and `usageMissing` rides beside it. Absent
* ⇔ every call of the turn reported its cache reads. */
cacheReadUnreported?: true;
/** Present (`true`) when some model call of this turn did not report its cache writes (the OpenAI-shaped wires never do):
* `usage.cacheWriteTokens` is then the counted sum, not a measurement. Same law as {@link cacheReadUnreported}. */
cacheWriteUnreported?: true;
/** TB telemetry B1: the NORMALIZED finish reason of the turn's LAST model call —
* the engine's `AssistantMessage.stopReason` (`StopReason`: `"stop"`/`"length"`/`"toolUse"`/
* `"error"`/`"aborted"`). This is post-normalization: e.g. Anthropic `end_turn`/`stop_sequence`
* both fold to `"stop"`, `max_tokens`→`"length"`; the raw provider reason is NOT preserved here.
* The machine signal for "was this turn cut by max_tokens" (`"length"`) — previously stream+trace
* double-blind, which made P1 cap-binding unjudgeable from artifacts. Absent when the turn produced
* no assistant message. Typed `string` (not the internal `StopReason`) to keep the engine's union
* private, but the value set is exactly those five tokens. */
stopReason?: string;
/** The PROVIDER'S OWN name for the model that answered this turn, when it DIFFERS from the id the
* request was sent with — a SECOND fact beside `TaskResult.model` / the trace's `brain.call.model`,
* which stay the ENGINE-SELECTED pool id a resume re-seeds and a catalog resolves, never an
* overwrite of either. PRESENCE: the turn's LAST assistant message carried one
* (`AssistantMessage.responseModel`). ABSENT ⇒ the provider named the requested id or named nothing —
* ONE reading, not two, as on the reference mismatch latch, also written only for a disagreeing pair.
* A mismatch is additionally announced once per leg per pair as `route.response_model_mismatch`. */
responseModel?: string;
/** The extension (its registration name) whose `prompt.submit` handler answered this turn with `{ reply }`, so
* no model request was made: `usage` is a known zero (no `usageMissing` beside it — nothing was served), the
* reply is the turn's assistant text, and the session row carries the same name (`AssistantMessage.answeredBy`).
* Absent on every turn a model answered. */
answeredBy?: string;
} & TaskEventIdentity) | ({
/** design/99 MF-18: a compaction boundary (or, since design/119 #1, mid-turn when the prompt-too-long recovery force-compacts between a failed request and its retry). `trigger` = what caused it: `"auto"` (the context-threshold
* auto-compaction), `"manual"` (the `TaskStream.compact` / `/compact` path), or `"forced"` (RB-398-b
* the prompt-too-long recovery and trim-pressure lanes — compaction was not optional; the
* hook layer's `PreCompactContext.trigger` always had this third state and the wire now carries the
* SAME value the hooks saw instead of flattening it to `"auto"`. Additive value space — a consumer
* switching on auto/manual keeps its exact old behavior). `tokensBefore` = the
* pre-compaction size of the HISTORY the summary replaced (the cut planner's estimate over the branch's
* messages, usage-anchored when the branch carries a fresh anchor; no fixed-prompt term) — DIAGNOSTIC, NOT
* paired with {@link tokensAfter} (that one is structural + the fixed prompt overhead, so `tokensBefore 344`
* beside `tokensAfter 30600` is two coordinates, not a pass that grew the context); read {@link freedTokens}.
* CC parity = `SDKCompactBoundary{trigger, pre_tokens, preserved_segment}`. */
type: "compacted";
trigger: "auto" | "manual" | "forced";
/** The pass this frame CONCLUDES — the value the pass's `compaction_started` frame carried. A landing is
* always preceded by its start, so the engine sets it on every `compacted` frame; it is optional in the
* type only so a literal a host builds by hand stays valid. */
pass?: string;
tokensBefore: number;
/** How much context this compaction FREED, as the engine measured it: one structural sum over
* the pre-messages minus the same sum over the post-messages, inside the pass. **The only
* subtractable number on this event**, and what a context meter should render. Clamped ≥ 0 at
* the mint, so `0` means "freed nothing", never "could not tell". Absent ⇒ the post
* measurement failed and no delta exists — never a stand-in. */
freedTokens?: number;
/** DIAGNOSTIC, NOT subtractable. Post-compaction size in the TRIGGER-GATE coordinate
* (structural estimate + the fixed prompt overhead). {@link triggerTokensBefore} is not its
* matching pre-value: the gate reads a usage-ANCHORED figure whenever the provider's last
* usage is fresh, while this is always structural + overhead, so the difference mixes
* coordinates and goes NEGATIVE on ordinary auto passes (3037 − 4591 = −1554, measured on a
* 4k window). Use {@link freedTokens}. Absent when the post measurement failed. */
tokensAfter?: number;
/** DIAGNOSTIC, NOT subtractable. The quantity the gate compared against its threshold —
* usage-anchored when the anchor is fresh, structural + overhead when it is not. It answers
* WHAT tripped the trigger, a different question from how much was freed; left un-clamped and
* un-paired rather than made to look subtractable. Absent on the legacy emitter. */
triggerTokensBefore?: number;
/** TB telemetry B4: wall time of the whole compaction pass (summary call included) — what the
* boundary pause actually cost. Absent on legacy emitters. */
durationMs?: number;
/** CC `SDKCompactBoundary.preserved_segment` parity: `firstKeptEntryId` is the session-tree entry id where
* the surviving KEPT TAIL begins after this compaction. A consumer maps it to a wire message via the
* `entryId` carried on `message_committed` (message-identity Phase 1) — render the compaction divider just
* before that message + relink the preserved tail. (The eventId↔entryId side map service keeps for resumeAt
* also resolves it, but is no longer required.) Absent on a compaction that reported no kept-tail floor. */
preserved_segment?: {
firstKeptEntryId: string;
};
/** Cross-session message frames that sat in the SUMMARIZED prefix of this pass — delivered
* earlier and visible to the model for the turns since. A record still in the session's box is
* handed over again by the engine (once; a second loss is disclosed `resupply_exhausted`), so
* this counts what the summary swallowed, not what is gone. Present iff at least one. */
summarizedCrossSessionMessages?: number;
/** CC post-compact file-restore parity: the files this compaction's restore delivered (attachWorkingFiles) —
* projected from the restore frames' delivery records, frame order. A shell renders CC's `Read {path} (…)`
* cards under the compaction divider from this. `chars` = the characters of the file's data the frame
* delivered (the line-numbered contents — the share itself counts the file's own text); `truncated` = the frame
* holds a partial view. A file the restore named but did not send (too large, refused, gone, a PDF reference)
* is not listed here — {@link restoreOutcomes} records it. Absent when the feature is off or nothing was delivered. */
attachedFiles?: Array<{
path: string;
chars: number;
truncated: boolean;
}>;
/** What became of each file this compaction's restore re-read: one record per restore frame, frame order — the same
* record, by the same projection, as {@link HumanInputAttachment} on `human_input.attachments` (`label` = the path;
* `outcome` one of `USER_ATTACHMENT_OUTCOMES`; `reason` one of the refusal words, `too_large` among them for a file
* over its share, and `read_failed` for a file whose read threw). Unlike `human_input`'s it is a delivery result: a frame the transcript did not take is
* `not_attached`. A PDF is a reference (`kind: "pdf"`, `attached`, as on `human_input`: its size and page count, no
* contents — which is why `attachedFiles` does not list it). A file the context the summary leaves still shows gets
* no frame and no record. Absent when the
* restore is off, minted no frame, or failed outright (an operator line, `onError` phase `degraded`, says why). */
restoreOutcomes?: HumanInputAttachment[];
/** 压缩子阶段遥测 (1.283 批 G / design/145 §6 正交后续批, additive): sub-phase wall-time split
* of THIS pass, mirrored 1:1 from `maybeCompact().phaseDurations` (single source: the
* `compaction.phase_timings` trace frame minus its envelope). Invariant: prepareMs +
* (summaryMs ?? 0) + persistMs === {@link durationMs} (exact tiling; `summaryMs` absent on a
* provider-reuse pass — no summary LLM call happened). Absent on legacy emitters. */
phaseDurations?: import("./auto-compaction.js").CompactionPhaseDurations;
/** Who asked for this pass when an extension did: present when the pass served a manual request an extension made
* (`$.session.compact`, by its registration name — the last such caller when several requests coalesced onto the
* pass); absent on every other pass, a `compact()` request of the host's included. A display and audit fact only. */
requestedBy?: ExtensionRequester;
} & TaskEventIdentity) | ({
/**
* RB-398-b④: a compaction pass concluded WITHOUT landing — the non-landing outcomes
* used to exist only as `compaction.*` trace frames, so a stream-only consumer watched a
* context quietly stop being managed (breaker opens, rapid-refill disable, hook blocks —
* all invisible). One lightweight additive event, emitted at the same sites as the trace
* frames; the SUCCESS outcome stays on the `compacted` event (this event never carries it,
* so a consumer treating `compacted` as the only success signal is unchanged).
* `outcome` reuses the {@link CompactOutcome} vocabulary plus `"suppressed"` (over-threshold
* pass suppressed by the anti-thrash floor — a state manual compact can never reach, hence
* outside `CompactOutcome`):
* - `"failed"` — a burned summary attempt failed, or the open breaker drained a manual
* request without an attempt (`reason` says which).
* - `"blocked"` — a `preCompact` hook deliberately blocked the pass.
* - `"suppressed"` — wanted to fire, held under the §25.2 anti-thrash floor.
* - `"noop"` — the pass ran but found nothing to compact (no valid cut point/empty history).
* - `"disabled"` — a requested pass (`trigger:"manual"`) was refused because the `manualCompact`
* seat is off, or the rapid-refill breaker disabled compaction mid-task (`reason` says so; the
* trigger is the landing pass's), or a pass the engine would start was not attempted because the fixed
* request prefix alone is at or past its line — `reason` starts `window_below_overhead:` and carries the
* prefix, the threshold, the window, the reserve and the smallest usable window (prefix + reserve); ONCE
* PER TASK, on the trigger of the first pass that met it, and every later non-`force` pass of the task
* (and of later tasks, while the prefix stays that large) is judged the same and not attempted. The `trigger` names the seat: a `"manual"` frame is the
* `manualCompact` seat's, never the `autoCompact` seat's. A seat that is statically off does NOT
* produce one of these per boundary for the passes the engine would start (that would be
* per-boundary noise about a static configuration, not a state change).
* - `"mooted"` — the pass did not run to its end: a manual request no boundary could serve
* (`trigger:"manual"`, `reason:"task_ending"`), or a request withdrawn / a pass cut in flight by its
* caller — a `compact({ signal })` withdrawal, `halt()`, `interrupt()`, `destroy()` or the task's own
* `signal` (`reason:"cancelled"`), on any trigger: `"auto"`, `"manual"` or `"forced"`, or a turn-boundary
* pass in flight that the task's own end cut — a limit, a timeout (`reason:"task_ending"`, with the
* `pass` the start announced). Read `"mooted"` with its `trigger` — it is not a manual-only outcome.
*/
type: "compaction_outcome";
outcome: Exclude<CompactOutcome, "compacted"> | "suppressed";
/** Same three-state vocabulary (and the same value) the pass handed the `preCompact` hook. */
trigger: "auto" | "manual" | "forced";
/** Optional human-readable detail (mirrors the trace frame's reason where one exists). */
reason?: string;
/** A `failed` frame's machine cause, a word of `COMPACTION_FAILURE_CAUSES` (`leaf_moved`: another writer moved the session's
* leaf while the pass ran and the summary landed nowhere), present when the failure has one — on every lane that fails a pass.
* Absent on every other outcome and on a failure the set has no word for; read the word, never the `reason`'s text. */
cause?: import("./auto-compaction.js").CompactionFailureCause;
/** The pass this frame CONCLUDES — the value its `compaction_started` frame carried. Present exactly when a
* start was announced for the pass this frame ends, which makes it `failed` or `mooted` (a pass that ran its
* summary call and did not land, or was cut while it ran). Absent on every outcome of a pass that never
* started — `blocked`, `suppressed`, `disabled`, `noop`, a `mooted` request no boundary served — and on the
* rapid-refill `disabled` frame, which reports a state the landing before it caused, not that pass's end. */
pass?: string;
/** Who asked for this pass when an extension did — the `compacted` frame's member of the same name, on the same
* condition: present when the outcome is a manual request's an extension made (`$.session.compact`). */
requestedBy?: ExtensionRequester;
} & TaskEventIdentity) | ({
/**
* A compaction pass is under way: the engine has committed to it and is about to produce its summary.
* Until now compaction was announced only when it ended (`compacted`, or `compaction_outcome` for a pass
* that did not land), so a consumer watching a summary call wait out a provider's retries had nothing to
* show for the minutes in between.
*
* Minted at the one place a pass commits — after the trigger gate, a valid cut point and the
* `preCompact` hook (a blocking hook ends the pass before it starts), before the summary provider is
* consulted or the model is called — by every lane that compacts: the turn boundary (`"auto"`, `"manual"`,
* and `"forced"` under trim pressure), the prompt-too-long recovery and guard-chain arm B (`"forced"`), and
* the end-of-task summary (`"auto"`). Retries inside the pass's model call never mint a second one.
*
* Pairing: exactly one frame concludes each started pass, carrying the same `pass` — `compacted` when it
* lands, `compaction_outcome{failed | mooted}` when it does not. A pass that never reaches this point
* (`blocked`, `suppressed`, `disabled`, `noop`) announces nothing here and its outcome carries no `pass`.
* `pass` is unique across runs, so a consumer multiplexing several tasks on one stream pairs on `pass` alone.
*/
type: "compaction_started";
/** Same three-state vocabulary (and the same value) the pass hands the `preCompact` hook and its concluding frame. */
trigger: "auto" | "manual" | "forced";
/** The pass's identity: an opaque engine-minted id (uuidv7), carried by the frame that concludes the pass. */
pass: string;
/** The engine clock (epoch ms) at the moment the pass committed. */
startedAt: number;
} & TaskEventIdentity) | ({
/**
* TB telemetry B3: the engine injected a SYSTEM steering message (a deadline nudge
* or the design/130 P2 graceful-finalize instruction) into the model's next turn. Previously these
* went through `harness.steer()` with no stream echo — a consumer literally could not tell whether
* the finalize fired (the refute-130 attribution blind spot). Echo only; the model-facing message
* is unchanged. `preview` is the injected text clipped to a display bound (220 characters; the post-compaction
* `background_tasks` table, a list its renderer already bounds, is echoed whole up to the per-boundary attachment cap).
*
* design/133 (LOW-11/F11): the turn-boundary attachment producers ride the same echo — sources
* `todo_reminder` / `task_reminder` / `changed_files` and the G1/续批 members
* `background_tasks` / `tools_delta` / `agent_listing` / `skills_listing` / `mcp_instructions`
* (one event per attachment; a multi-attachment boundary still coalesces into ONE steer message
* on the model lane). [c209-C]: the listing family's FIRST-FRAME deliveries (initial roster /
* `<skills>` block riding the first user message, not a steer) emit the same echo frames.
*
* `mcp_unavailable`: the declared MCP servers that did not connect for this message — echoed where the notice rides
* (a fresh leg's first user message; a resumed leg's continuation). It used to ride `tools_delta`.
*
* `git_status` (env-tail migration, additive member): the git-status frame — the turn-dynamic
* git facts' carrier since they left the system prompt. Emitted at the frame's append RECEIPT
* (first-frame / resume-continuation / compaction re-assert deliveries alike). Its `preview`
* is a CONSTANT wording on purpose (never frame bytes): branch names and status text are
* repo-controlled and must not enter the event telemetry plane through this echo.
*
* `output_style` (additive member): the frame stating the deployment-declared `TaskSpec.outputStyle`, echoed
* at every delivery (a leg's first turn, a resumed leg's continuation, each continuing boundary).
* The permission-posture frames (planning / bypass / auto, and their exits) are model-lane only and have no
* echo; the retired `plan_mode` member was the echo of the opt-in planning reminder they replaced.
*
* `nested_memory` (additive member): an instruction file of a directory the run accessed (or a rule the deployment
* supplied for an accessed path; the family `NESTED_MEMORY_LANE.declaration` names) reached the model — one event per file, at
* the receipt of the frame that carried it; `preview` is the file's path (the rule's name), never its contents.
* `project_instructions` (additive member): the same for an instruction file of a root's own level — the task root's, or an
* additional working directory's under the family's opt-in (the session's instructions, read by the same lane). Either word, a frame that WITHDREW a file delivered earlier (removed since, or
* holding nothing now) echoes with its path and the words `(withdrawn: it no longer applies)`. The retired
* `instructions_change` member was the echo of a deployment-probed hash notice about the session's instruction file;
* the lane now sends the whole changed file, or its withdrawal. `skill_mention` (additive member): a fresh leg's first request carried, for each
* listed skill the person's opening words named as `/<name>`, the sentence saying it is a skill to run through the Skill tool; `preview` is those sentences.
*/
type: "steering_injected";
source: AttachmentSource | "limit_approach" | "final_verification" | "git_status" | "nested_memory" | "project_instructions";
preview: string;
} & TaskEventIdentity) | ({
/**
* design/121 (`<new-diagnostics>`): NEW LSP diagnostics that appeared after the
* agent's edits, drained at a turn boundary. The SAME data was injected into the model as a
* `<new-diagnostics>` context message; this frame is the shell's render source (CC's collapsed
* `Found N new diagnostic issues in M files (ctrl+o to expand)` row). UNTRUSTED RAW (language-
* server output over workspace files) — a consumer redacts/bounds before persisting (§E1).
*/
type: "diagnostics";
files: Array<{
uri: string;
diagnostics: Array<{
message: string;
/** LSP severity: 1=Error 2=Warning 3=Information 4=Hint. */
severity?: number;
range?: {
start: {
line: number;
character: number;
};
end?: {
line: number;
character: number;
};
};
code?: string | number;
source?: string;
}>;
}>;
isNew: true;
} & TaskEventIdentity) | ({
/**
* message-identity Phase 1 (the CC `SDKCompactBoundary` parity enabler): a persisted session-tree entry was
* just COMMITTED for a RENDERABLE message the consumer has already streamed. `entryId` = `SessionTreeEntry.id`
* (uuidv7, persisted, replica-stable) — the SAME id space as `compacted.preserved_segment.firstKeptEntryId`,
* E18 `resumeAt`, and the design/381 `rewindFilesTo`. `role` + (for a tool result) `toolCallId` let a consumer bind it to
* the message it rendered: a tool result by its `toolCallId`; an assistant/user message by stream order (this
* is the terminal boundary for the content just streamed, after its deltas and before its tool results). A
* consumer builds its own `entryId → message` map from these to resolve `preserved_segment` WITHOUT the
* eventId↔entryId side map. Terminal per-message boundary; additive + ignorable. ABSENT for a message that did
* not persist (an empty-failure assistant) and for non-message entries (a compaction summary / model_change —
* never a `message_committed`). The engine still holds no eventId→entryId map (the deployment owns it); this
* only pushes the persisted id onto the wire, the constitution's primitive/profile split (cf. §E2 `eventId`).
*/
type: "message_committed";
entryId: string;
role: "user" | "assistant" | "toolResult";
/** Present iff `role === "toolResult"`: the exact join key to the `tool_start`/`tool_end` already rendered. */
toolCallId?: string;
/** Present iff `role === "user"`: what this row is — `"human_input"` (a person's or a relay's input, accounted for by a
* `human_input` frame), `"attachment"` (a frame for one of that input's declared attachments, trailing its message),
* `"interruption_marker"` (the engine's own line that the run was interrupted) or `"queued_note"` (any other engine-minted
* user-lane row: a task notification, a boundary steer, the git frame). A consumer anchors on it and on `inputId`, never on
* stream order. */
origin?: import("./user-row-origin.js").UserRowOrigin;
/** Present only with `origin === "human_input"` or `"attachment"`: the `human_input.inputId` of the input this row IS (or, for
* an attachment frame, belongs to) — the same key, so the frame and its row join by key. A `human_input` row is one per key;
* the objective's attachment frames carry the objective's key under `origin: "attachment"`, which tells them apart.
*
* A resume's continuation is ONE message merging every parked steer with the wake message. No `continuation` carrier exists
* (a `human_input` frame's carrier is `steer` or `wake`), so that row is `origin: "human_input"` carrying the WAKE message's
* key — the wake carrier's own, never a merged steer's — and has no key when the resume has no wake message (a continuation of
* parked steers alone). The merged steers have no row of their own: each joins only through its own `delivery: "applied"` frame. A
* continuation that carries neither a parked steer nor a wake message — only the approving person's words, which no `human_input`
* frame accounts for — is a `queued_note`. */
inputId?: string;
/** Present only with `origin === "queued_note"`, on the row of a task notification: the frame's durable key — the one key
* the frame was handed to the model under, whichever road it took (the live lane, or the redelivery at a run's turn open of
* a frame parked while the session sat idle). It is the key the row's transcript entry carries and the one
* `taskNotificationDedupKey` (root export) reads off the `task_notification` frame's payload and the frame states as its own
* `noteKey`, so a consumer joins the frame to the row that brought it to the model by this key, never by stream order. A boundary steer, the
* git frame and every other queued note carry none. */
noteKey?: string;
} & TaskEventIdentity) | ({
/**
* design/171 §5.5/§6.2 — the human-input LIFECYCLE arm: one frame per human input this run
* accepts (WHO fed the run WHAT, per carrier). Additive + ignorable like its siblings.
* Deliberately NOT folded into `message_committed`: that event only fires for messages that
* PERSISTED, while a human input's lifecycle (queued / parked) exists before — and sometimes
* without — a committed message. Constructed via `buildHumanInputEvent` (mints the inputId,
* materializes no absent optional keys); `HumanInputEvent` is the Extract-derived alias.
*
* Attribution semantics are THREE-VALUED, never collapsed:
* - `actor` ABSENT ⇒ the caller supplied none (anonymous — every pre-171 caller);
* - `actor.hostAsserted === false` ⇒ an UNVERIFIED self-claim the host chose to carry;
* - an OLD event stream that predates this arm simply has no `human_input` frames at all —
* a consumer distinguishes "attribution unknowable (pre-arm producer)" by the emitting
* core's version, never by guessing from field absence on some other event.
*/
type: "human_input";
/** Correlation/idempotency key. Caller-supplied when the ingress already minted a message id
* (the parked-steer queue's `inputId` is THE same key); a uuidv7 otherwise. */
inputId: string;
/** Ordinal of this input among the run leg's accepted human inputs (1-based, drain order for
* parked entries). Leg-scoped: a resumed leg restarts at 1 — `inputId` is the global key and
* stream order the global order; a serving layer needing a session-global ordinal mints its
* own. */
sessionSeq: number;
/** Which concrete carrier accepted the input. OPEN set — a serving layer self-reports its own
* carriers (question note / elicitation / decide reason / …) through the same arm; the
* core's five report their {@link HumanInputSource} name. */
carrier: string;
source: HumanInputSource;
/** Who asserted the actor's identity (Slack app id, SSO IdP …) — mirrored from `actor.issuer`
* or supplied alone when the host can name its ingress but not the subject. */
issuer?: string;
actor?: ActorAssertion;
delivery: HumanInputDelivery;
/** Plaintext principal correlation key (deliberately not hashed — the audit consumer joins
* on it). */
principal?: string;
/** The persisted session-tree entry the input landed as, WHEN the emitter knows it (a
* serving layer replaying the ledger); the core's live emissions precede the commit and
* omit it — consumers there join by key: the `message_committed` row with `origin: "human_input"` and this `inputId`. */
entryId?: string;
/** Present only on the `"applied"` frame of an objective that declared attachments: per attachment, in order, what
* the engine read for it and will send (`outcome`) — an admission result, not a delivery (a `path` attachment that did not
* fit the first request: `not_attached`, `reason: "too_large"`); each is its own message after the objective, its `message_committed` the delivery. */
attachments?: readonly HumanInputAttachment[];
/** What brought THIS input, when its host said so on its carrier (`"scheduled"`: the deployment's scheduler handed it —
* render it as the scheduler's, not as someone typing): the objective's `TaskSpec.runOrigin`, a parked or waking
* message's `runOrigin`. Absent ⇒ the host said nothing (never "a person sent it"). Attribution only. */
runOrigin?: import("./run-origin.js").RunOrigin;
/** Present when the leg's prompt screen (`prompt.submit`) rewrote THIS input's text before it was delivered: the extensions
* that changed it, in the order they did. The model saw the rewritten text (the caller's own words are not delivered); rides
* only the frame that delivers it — the `"applied"` frame of an objective, a live or parked steer, a wake's message. Absent ⇒
* the text went as it came (save a `later` steer an extension answered with `{ reply }` and a durable park carried across). */
rewrittenBy?: readonly string[];
/** Who wrote THIS input, when it is not the operator ({@link import("./input-author.js").InputAuthor}): `"extension"` for an
* extension's prompt (`$.prompt.submit`), `"observer"` for an observer's report relayed to the child it watches. Rides
* both frames of a live steer's account (`"queued"`, `"applied"`). Absent ⇒ the operator (a person, or the host relaying
* one) — every input of the public verbs. Render a non-operator input as its author's, never as the person's. */
author?: Exclude<import("./input-author.js").InputAuthor, "operator">;
/** The calling registration's name, beside `author: "extension"` (and only there). */
extension?: string;
} & TaskEventIdentity) | ({
/**
* design/99 §E3/§E10 — a live BRAIN-LAYER status the brain would otherwise absorb
* silently (a 429 rate-limit / a 5xx or network retry / a reconnect / an open circuit breaker). Emitted
* the moment the brain decides to wait/retry, carrying the graduated {@link BrainStatusPhase} + an
* optional `retryInSec` so a UI can show "rate limited, retrying in Ns". EPHEMERAL — a pure liveness
* signal, never persisted or replayed on resume. The phase and the hint are provider-neutral (no
* provider taxonomy, no `stop_reason`); the failing attempt's HTTP status rides its own seat in the
* retry context only — see {@link BrainStatus.errorStatus}.
* SCOPE: reflects THIS task's own (top-level) brain calls. A delegated sub-agent's brain liveness routes
* to the SUB-AGENT's own stream (isolated, like every child event — §E2); a background internal brain
* call (memory recall/consolidation) is intentionally not surfaced.
*/
type: "status";
} & BrainStatus & TaskEventIdentity) | ({
/**
* @contract hook_progress — A HOOK HOLDS a tool call or an input: one of the leg's two decision screens is in flight —
* a tool call's `classic.PreToolUse` screening (phase 1 at the gate, the re-screen of a person's edit, the resumed leg's
* re-screen of an approved call), or a prompt's screen (`prompt.submit`, and `classic.UserPromptSubmit` at its bottom)
* at the objective, a live steer or a parked steer's redelivery. Two frames per screen, paired on {@link screen}:
* `phase: "start"` once the screen has lasted one progress interval (the `tool_progress.cadence` floor, one second),
* `phase: "end"` when it settles — answered, refused, failed (a handler that threw or ran out of its budget), cancelled,
* or cut by the leg's own end. A screen that settles inside the interval leaves NO frame at all (a handler whose matcher
* passes the call over answers in microseconds, and the engine cannot see the matcher); every `start` is followed by
* exactly one `end`, and no `end` comes without a `start`. A steer taken while its leg is still starting can be screened
* before the leg's stream carries content frames: its `start` goes out when they begin, if the screen is still running
* then (so a `start` is never earlier than one interval into its screen, and may be later).
*
* ONE PAIR PER SCREEN, whatever runs inside it: every registration in the chain, an inherited installation judging
* the call, the re-judge of a rewrite — and several of a host's hooks run in parallel inside ONE registration (the
* engine sees the registration, never the hooks it runs), so a screen is one pair, never one per hook. It names no
* hook, no budget and no elapsed time; it says nothing of the verdict (the call's `tool_end.gate`, the input's own
* frames and notices are that record). While a screen holds a call, that call's `tool_progress` beats say
* `gate: "hook"` (the state; this frame is the transition).
*
* Absent: a wake's message is screened before its resumed leg's stream exists (the resume verb itself is what the
* caller is waiting on), so its screen has no frame. Ordering: on the run's own queue, as a content frame — a call's
* `start` follows its `tool_start`, its `end` precedes the call's release or its refusal's `tool_end`; forwarded to a
* parent's display sink under the same opt-in as `tool_progress` (`TaskSpec.forwardSubagentEvents`).
*
* EPHEMERAL, the `tool_progress` law: LIVE ONLY — never persisted (no session-tree entry, no checkpoint state), never
* replayed on resume; a resumed leg's screens mint their own. Additive and ignorable: no gate, policy, memory or
* model-context path reads it.
*/
type: "hook_progress";
/** `start` — the screen has held its subject for one interval; `end` — the screen settled (only after a `start`). */
phase: "start" | "end";
/** The screening's identity: an opaque engine-minted id (uuidv7), carried by both frames of one screen — pair on it alone. */
screen: string;
} & HookProgressSubject & TaskEventIdentity) | ({
/**
* design/115 P2 core slice — SDK-side projection of a background task terminal notification. The model-facing
* projection is the sibling `<task-notification>` XML injected through the runner's system-injection lane when
* the originating harness is still running; durable idle wake/resume is a deployment transport concern.
*/
type: "task_notification";
notification: TaskNotificationPayload;
/** The frame's delivery key: equal to the `noteKey` of the `message_committed` row that hands this same notification to the model
* (`taskNotificationDedupKey(notification)`, a root export), so a consumer joins the frame to its row by equality and never computes
* the key itself. Stated on every frame an engine carrying `task_notification.note_key` pushes (the word's entry says so); without the word, absence says nothing. */
noteKey?: string;
/** design/373 §3.6 — the frame's injection tier as DELIVERED (additive; consumers tolerate
* absence): on the live lane, the tier the routing used (`next`/`now` → steer lane, `later`
* → followUp lane); on the turn-open redelivery lane, the tier the park CARRIED. ABSENT is a
* fact, not a default: a pre-373 producer event, or a parked record whose frame was queued
* with no tier — never read absence as `"later"`. The end-of-run sweep parks a frame under the tier it was queued with. */
priority?: import("./task-notification.js").SystemInjectionPriority;
} & TaskEventIdentity) | ({
/**
* A DELEGATED CHILD STARTED: the one frame that says who the child is, at the beat it starts —
* before its first model request, so a consumer opens the child's row (a foreground child's panel
* line, a background child's fleet entry) without waiting a model turn for the first
* `task_progress`. Mirrors CC's `system/task_started`.
*
* ONE MINT PER CYCLE, at the spawn station of the leg that OPENS the cycle, for every delegation
* lane alike (foreground, background, fork, workflow agent, named teammate) — every cycle starts
* with exactly one: a first spawn mints it, and so does every revival or wake of a child (a new
* cycle — `seq` moves on, the `taskId`/`sessionId` of the revived run say which), and so does a
* durable RESUME whose claim opened the next cycle (a background agent's park resumed with a
* decision — approve or deny: its claim writes the next number, the leg runs as it and starts it — a consumer
* reads it as any revival: same `taskId`, higher `seq`). A resume whose claim opened none (a
* workflow member's parked call driven again, a host redeeming a delegated child's checkpoint
* itself) continues the cycle that parked and mints NOTHING; a child whose prepare throws never
* reaches the station and mints nothing either (its terminal still arrives on the lane that
* spawned it). Ordered strictly after the leg's `wiring_manifest` and strictly before anything its
* first turn produces, so on the forward channel it is the child's first frame. Rides the same door
* as `task_progress` (the child's own stream, and the forward channel to the deployment); the
* process-level delegation-lifecycle `spawn` frame is this mint's projection, same instant, same gate.
*
* Live and ephemeral like `task_progress`: never persisted, never replayed on resume, absent from
* checkpoints. Every member below is a value the run already speaks elsewhere — this frame
* introduces no new reading of any of them.
*
* CC mapping: `task_id` → {@link taskId} (run domain; a background child's registry handle rides
* {@link TaskEventIdentity.bgAgentId}), `tool_use_id` → `parentToolCallId`, `description` →
* {@link name}, `subagent_type` → {@link agentType}, `task_type`/`is_backgrounded` → {@link taskType}
* (absent = a foreground child), `run_id` → {@link seq} (the cycle), `parent_task_id` →
* {@link parentTaskId}, `session_id` → {@link sessionId}. Not carried: `prompt` (a delegated
* objective can hold a secret — the same reason {@link name} never falls back to it), `awaited`,
* `spawn_depth` (the nesting is the `parentTaskId` chain), and the shell/monitor-only members.
*/
type: "task_started";
/** The child leg's task id (a background sub-agent's registry task id, else its session id) — the
* key its `task_progress` frames carry. */
taskId: string;
/** The child run's session id — the handle its transcript is read by. */
sessionId: string;
/** The fleet-task kind, exactly as the child's `task_progress.taskType`: ABSENT for a foreground
* (synchronous) child, which has no fleet row. */
taskType?: DelegationTaskType;
/** The cycle this start opens, exactly as the same leg's `task_progress.seq`: a leg's start and its ticks
* carry one number or none, read the same way (absence is never "cycle 1"). */
seq?: number;
/** Workflow-lane self-identification, as on `task_progress` (stamped where the workflow forwards). */
workflowRunId?: string;
/** The workflow agent's label, riding with {@link workflowRunId}. */
workflowAgentLabel?: string;
/** With {@link workflowRunId} only, as on `task_progress`. */
workflowStepAskedAgain?: true;
/** The spawning run's task id, exactly as `task_progress.parentTaskId`. */
parentTaskId?: string;
/** The spawning run's session id (the always-on parent linkage). */
parentSessionId?: string;
/** The delegation tree's root host session. */
rootSessionId?: string;
/** The child's display label, the same bounded single-line value its `task_progress.name` and its
* hook identity's `agentName` carry. UNTRUSTED display text. */
name?: string;
/** The explicit `Agent({name})` spawn identity (the teammate key), when the spawn carried one. */
spawnName?: string;
/** The resolved subagent type the child was spawned as (absent on a workflow-lane agent). */
agentType?: string;
/** The model the child leg was PREPARED with — the value its `task_progress.model` and
* `TaskResult.model` carry. */
model: string;
/** Epoch ms at the mint. */
startedAt: number;
} & TaskEventIdentity) | ({
/**
* design/99 MF-10 — a SUBAGENT PROGRESS TICK: the delegated sub-run's usage ACCRUING
* over time, emitted at each turn boundary WHILE it runs, so a parent UI animates the Task card's rollup
* (tokens/tool-uses climbing). Emitted ONLY for a delegated leg (the same eligibility as `task_started`); a top-level
* run's own usage is the consumer's own. `status:"running"` mid-run; the terminal usage is the `done` result.
* Live/ephemeral — NOT persisted (a resumable trace re-derives usage from the result), like `status`.
* Maps to CC `SDKTaskProgress` (camelCase here → snake_case `task_id`/`total_tokens`/`tool_uses`/`duration_ms`
* at the SDK/service projection, the same convention as `toolCallId`→`tool_use_id`).
* `taskId` is the child leg's task id, minted once by the child's prepare: a background
* sub-agent's is its registry task id (the `a…` handle TaskStop / TaskOutput / SendMessage take),
* a foreground child's is its session id. One child, one id — `docs/INTEGRATION-CORE.md` §1.6a.
*/
type: "task_progress";
taskId: string;
/**
* The FLEET-task kind of the run this tick reports on — the type discriminator a consumer needs
* when it folds progress ticks and task notifications into one ledger. Without it the only
* available test is "it appeared on the fleet stream, therefore it is an agent", and that
* inference has already minted an agent-shaped row for a task that was a background shell
* command. Drawn from {@link TaskNotificationPayload}'s `task_type` vocabulary (no second
* spelling of one axis) and narrowed to the members a progress tick can honestly claim.
*
* Present on every tick from a run that HAS a fleet row: `"background_agent"` for a background
* delegation child (its registry `a*` row) and `"workflow"` for a workflow-spawned agent (its
* `wa*` read-face row, framed only to a wired child-event sink) — the latter alongside, not in place of, {@link workflowRunId}, which
* names the owning RUN while this names the KIND. ABSENT is a fact, not missing data: a
* SYNCHRONOUS delegated child has no registry identity (INTEGRATION-CORE §1.6a) — the one gap is a delegated child's
* checkpoint a host redeems without the lane's internals (KL-3824-a). Additive — tolerate absence, never read it as "not an agent".
*/
taskType?: DelegationTaskType;
/**
* The STOP-CYCLE number this tick reports from, the same counter `TaskNotificationPayload.seq`
* and `BackgroundChildEvent.seq` already speak — one axis, not a third spelling. It answers
* the one question a fleet consumer cannot otherwise decide when a frame arrives late: "late
* first frame of the cycle I know (same value), or a revived run I have not folded yet
* (higher value)?" Two counters feed it: a background child's is its `a*` registry row's
* generation (fresh spawn = 1; every revival and every decided resume of a park opens the next,
* written by the claim that opens it); a SYNCHRONOUSLY born child's is the count its one wake
* face keeps (the spawn = 1, so its first cycle's ticks carry none and each wake through its
* steer handle reads 2, 3, …) — a cycle count, not a row generation. Advisory observation,
* stamped when the cycle opens; the settle-time ledger stays the authority. ABSENT is a fact,
* not a gap: a synchronous child's first cycle, a workflow `wa*` agent, a top-level run, and a
* delegated child's checkpoint a host redeems without the lane's internals carry none unless the
* host hands a number (`RunInternals.cycleSeq`, or a consume hook that states one) — presence is
* per leg, so one cycle's legs can differ —
* and absence must never be read as "cycle 1".
*/
seq?: number;
/** Workflow-lane self-identification (field-proven: the SSE-forwarded tick of a
* WORKFLOW child previously carried a bare uuid with no workflow identity — indistinguishable
* from an unknown nested subagent; the fleet lane had `wa*`+workflowRunId but this lane had
* nothing). Present iff the tick bubbled out of a workflow-spawned agent. Additive. */
workflowRunId?: string;
/** the workflow agent's display label (opts.label / auto `agent-N`), riding with
* {@link workflowRunId} for the same self-identification. Additive. */
workflowAgentLabel?: string;
/** With {@link workflowRunId} only, present only as `true`: the call runs again a step the run it resumes took up (its card stopped waiting
* undecided, or the same call completed there and the replay stopped before it) — the bit the member's asks and pending rows carry
* (`AskRequest.workflowStepAskedAgain`). No cause; a step approved and not executed is not it. Additive. */
workflowStepAskedAgain?: true;
/** design/99 (nested-subagent live tree): the spawning run's taskId — present on a DEEPER-than-1 subagent tick
* (a subagent spawned by another subagent), forwarded via `RunInternals.onForwardEvent` so a UI nests the
* node directly (this.taskId under parentTaskId) without mapping `parentToolCallId` → owner. The top-level
* run is known to the consumer; its direct children carry the top's taskId here. Absent on a top-level tick. */
parentTaskId?: string;
/** design/99 BC-2 (Service AI [§I]): a short, single-line HUMAN display name for the subagent — its explicit
* `taskName` or the selected agent-type. So a Fleet child row shows a readable label instead of the raw
* `taskId` (the stable row identity stays the taskId). ABSENT when the subagent carries neither a taskName
* nor an agent-type — the child then keeps its taskId (NOT the raw objective, which could leak a delegated
* secret to a progress-scoped consumer — dual-review Q2). Sanitized (control-char-stripped, length-capped). */
name?: string;
/** The EXPLICIT `Agent({name})` spawn identity of the sub-run, when the spawn carried one — the
* teammate KEY, as opposed to {@link name} (the display label): the same string the fleet row's
* spawn frame (`BackgroundChildEvent.spawnName`), the roster row and the child's uplink `from`
* carry, so a consumer binds "@name → row" by string equality. Validated at spawn
* (`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`). ABSENT = an unnamed delegation, never a missing value. */
spawnName?: string;
/**
* The model this sub-run was PREPARED with — the resolved id, read off the leg's prepared model
* at the mint, so it is the same value `TaskResult.model` and the `task.start` trace frame carry.
* (`task.end` reports the run's totals and has never named a model; there is nothing to join to
* there.)
*
* Why it rides the live lane at all: a delegation may name a tier word (`"sonnet"`), an agent
* definition's model, or NOTHING (inherit the caller's current model, or fall to the `subagent`
* role) — every one of those resolves somewhere the consumer cannot see, so a shell badging a
* running child previously had only the REQUESTED word (or nothing) to render, which is a
* different claim from what the child runs on. This is the resolved answer, not the request.
*
* PREPARED, deliberately, and NOT "whatever is serving this turn" — stated in the first sentence
* because the difference is observable. A mid-run DEGRADE switch (`spec.limits.degrade`) or a
* gateway re-route moves the serving model without rewriting this field, exactly as
* `TaskResult.model` behaves; the switch is announced on its own channel (`TaskResult.degraded`),
* and the per-call served id lives on the brain-call telemetry. One name, one meaning, across the
* three faces that use it — at the cost of being the leg's declared model rather than a live one.
*
* Present on every tick this build mints (the frame family is subagent-only by construction, so
* there is no lane where a leg has no prepared model). Declared optional for the ordinary reason:
* a consumer folding frames from a pre-key producer must keep compiling, and absence there means
* "this producer did not state it", never "no model".
*/
model?: string;
/** The child's most recent tool intent as one human line ("Bash npm test",
* "Edit src/x.ts") — the SAME source/value as the registry sink tick's `currentAction` (residual
* observability, lane B), attached to the FORWARDED frame because every client wire projects this
* TaskEvent, not the sink (a deployment's projection legs otherwise see a permanently-absent field).
* UNTRUSTED display hint — redact at the projection boundary. Absent until the child runs a tool. */
currentAction?: string;
usage: {
totalTokens: number;
toolUses: number;
durationMs: number;
};
/** Per-turn ticks are `"running"`. ONE final tick fires at the sub-run's settle with the
* terminal face (`"completed"` | `"failed"` — timeout/blocked fold to failed; a suspended durable
* pause emits no terminal tick), so a uuid-lane consumer sees the row finish instead of a bare
* removal after the last running beat. Additive value space — a consumer switching on "running"
* keeps its exact old behavior. */
status: "running" | "completed" | "failed";
} & TaskEventIdentity) | ({
/**
* WHERE THIS LEG STANDS, one WHOLE snapshot (minted only by `workspaceSnapshotOf`). EVERY prepared
* leg — fresh, resumed, continued, child; a read-only leg and a leg with no shell included — sends ONE leg-start frame
* after `wiring_manifest` and the leg-start `tool_disclosure` census (when the leg has one), before its first model or
* tool interaction, then one more each time the snapshot CHANGES (a `bash` `cd`, EnterWorktree /
* ExitWorktree; observed after the tool that moved it, a resumed leg's approved call included). A frame equal to the
* last one this leg sent is never sent. Replace your copy with each frame (last frame wins): the leg-start frame is
* a snapshot, not a report that something moved — a consumer already holding the same values renders nothing for it.
* A host keeping a session row keeps the LAST frame; nothing else needs re-deriving (the next leg re-sends its own).
*/
type: "workspace_changed";
/** The tracked logical cwd — the RAW path the shell navigated (a `cd` through a symlink reports the path walked,
* not its target). A resumed or continuing leg starts where it restored to; a leg with no shell reports `root`. */
cwd: string;
/** This leg's task root as the leg's root receiving point settled it — the spelling its file fences and path rules are
* anchored at, and where `cwd` starts. */
root: string;
/** The model's EnterWorktree switch active on this leg (`byPath`: entered via `path`, not created by this session);
* ABSENT = no switch is active on this leg. */
entered?: {
dir: string;
byPath?: true;
};
/** The session's checkout (`TaskSpec.workspace`), one entry per repository, fixed by the session's first leg:
* `repository` = the repository's root; `root` = the declared root the entry was made for; `baseSha` = the commit the
* session's code starts from. `dir` / `name` / `branch` / `baseRef` (present together) = the session's own tree of that
* repository, where every declared root in it works (`root` above, `directories` below). `source` = the declared code
* source for that repository. ABSENT = the session declared no workspace, or this leg sent `workspace: null`. */
session?: ReadonlyArray<{
repository: string;
root: "taskRoot" | {
directory: string;
};
baseSha: string;
dir?: string;
name?: string;
branch?: string;
baseRef?: "fresh" | "head" | "source";
source?: {
remote: string;
sha: string;
ref?: string;
};
}>;
/** The declaration the session's checkout was opened under, normalized (present with `session`): the value every later leg
* sends as `TaskSpec.workspace` — it screens to itself. The record judges each leg; this is what to send, not a verdict. */
declaration?: {
isolation?: "worktree";
baseRef?: "fresh" | "head";
name?: string;
roots?: ReadonlyArray<"taskRoot" | {
directory: string;
}>;
sources?: ReadonlyArray<{
root: "taskRoot" | {
directory: string;
};
remote: string;
sha: string;
ref?: string;
}>;
};
/** This leg's additional roots (`additionalDirectories` as `write`, `additionalReadDirectories` as `read`) where each stands:
* `at` (canonical) = its place in its repository's session tree, `tree` = that tree's `dir` (present iff so), else where
* declared. An entry that cannot be resolved is no root and is not listed. ABSENT = the leg has no additional root. */
directories?: ReadonlyArray<{
declared: string;
at: string;
access: "write" | "read";
tree?: string;
}>;
/** This leg's project identity, decided ONCE at leg start and fixed for the leg: `marker` = the checkout's
* `.sema/project` (a `TaskSpec.project.id`, when given, equals it); `declared` = the number this leg was given —
* by its host's `TaskSpec.project.id`, or, for a delegated child that declared nothing and whose own workspace
* has no marker, the project seat of the leg that spawned it (a woken agent: the leg that woke it). ABSENT = none of the three, or the marker could not be
* read (the deployment's `onError` was told which file and why). */
project?: {
id: string;
source: "marker" | "declared";
};
/** True ⇔ the leg's execution env does not declare its paths the host's (`capabilities.hostLocalPaths`), so the
* paths name locations inside that env, not host paths — whatever interface drives it: a host lane driven
* through the remote seam reads `false` (the reading `ResolvedWorkspace.remote` carries). */
remote: boolean;
} & TaskEventIdentity) | ({
/**
* design/173 §2.4/§8.1 — this leg's EFFECTIVE wiring manifest: the machine-readable
* disclosure of how the run is assembled around the optional human-interaction seams
* (ask/question/elicit/park/durability/fleet/governance). Emitted ONCE PER PREPARED LEG
* (root/child/resume each get their own — per-leg assembly genuinely differs, e.g. the
* engine-stripped background lanes), after prepare and BEFORE the leg's first model/tool
* interaction; leg identity rides {@link TaskEventIdentity} plus `manifest.leg.kind`.
*
* DISCLOSURE, not verification (§0 guarantee boundary): seam presence/shape as facts —
* liveness (does the callback actually reach a human) is a round-trip probe's job.
* HOST/OPERATOR plane: the manifest never enters model context, and the `governance`
* section carries `audience: "operator"` — a serving layer forwarding this stream to a
* multi-tenant/shared consumer MUST project that section for operators only (its default,
* when it does no projection, is to not disclose the section). Additive: a consumer that
* ignores unknown event types is unchanged; consumers of the manifest itself must ignore
* unknown FIELDS (`schemaVersion` bumps only on a semantic break).
*/
type: "wiring_manifest";
manifest: import("./wiring-manifest.js").WiringManifest;
} & TaskEventIdentity) | ({
/**
* design/388 §2.5 — a RUN-TIME change to this leg's mounted tool set (today: the RefreshMcpTools
* seam re-inserting a server's tools in place). Carries the WHOLE post-change roster (positions
* come from it; a consumer replaces its copy) plus a summary usable only when the consumer holds
* `fromDigest` — otherwise it adopts the snapshot and records a skew (never rejects). The prepared
* roster itself rides `wiring_manifest.manifest.tools`; this frame never precedes that one.
*/
type: "tool_roster_delta";
delta: import("./tool-roster.js").ToolRosterDelta;
} & TaskEventIdentity) | ({
/**
* A main-line request that does NOT extend the session's previous main request of the same serving model is about to go
* out (the provider must re-read everything after `at`: on a long session, minutes before the first token). Minted BEFORE
* the request is handed to the Brain seat, judged from the request bytes by the session's prefix ledger
* (`core/runner/prefix-ledger.ts`: thinking controls, system text, tool block, messages, in one canonical rendering) —
* never from a cache-read count (zero cached tokens does not mean the head changed). Not a prefix change: a side request, an append,
* or a request on a model this process holds no earlier main request of (`no-baseline`) — unless it opens a leg whose anchor moved.
*/
type: "prefix_changed";
/** Where the first difference falls: the thinking controls, the system text, the tool block, or the messages. */
region: "params" | "system" | "tools" | "messages";
/** Where the request stops repeating the previous one (canonical rendering, UTF-16 units): in params / system / tools the first differing unit, in `messages` the first changed message's start.
* Absent — with `of` — exactly when this process holds no earlier main request of this model for the session (a restart, a switch to a model not served here, a rewrite-voided baseline): `segments` found it. */
at?: number;
/** The previous main request's length in the same rendering (absent with `at`). */
of?: number;
/** Present with `region: "messages"`: which message, by index, first differs from the previous request's or is gone. */
message?: number;
/** The head segments the leg start found moved against the session's anchor (prompt block ids, `tools`); only then. */
segments?: string[];
/** Every word declared since the previous main request (`PrefixChangeCause`), in declaration order; empty when none was. */
causes: import("./prefix-declaration.js").PrefixChangeCause[];
/** A declared word covers the region that changed (`REGION_CAUSES` in the ledger); `false` = no seat declared the move. */
declared: boolean;
} & TaskEventIdentity) | ({
/**
* This leg's DEFERRAL CENSUS: which mounted tools ship as name-only placeholders, which the model has activated, and the policy
* (`RunnerDeps.toolSearch`) that decided it — meaning owned by `ToolDisclosureSnapshot` (`runner/tool-disclosure.ts`). EXISTS ONLY ON A LEG THAT
* DEFERS SOMETHING: an empty deferred set emits no frame, and that absence reads as "nothing was deferred here", never "no disclosure in this build"
* and never "unknown". First frame = the leg-start census, right after `wiring_manifest` — `activated` is EMPTY on a fresh leg and, on a RESUMED one,
* whatever the engine reseeded (never read a non-empty first census as "this leg activated them"); every later frame = a census that CHANGED, i.e. an
* activation landed (either lane — one section, one census). WHOLE SNAPSHOT: replace your copy. `deferred` is frozen at prepare; lists sorted.
*/
type: "tool_disclosure";
policy: import("./tool-search-setting.js").ToolSearchPolicy;
/** Meaning owned by `ToolDisclosureSnapshot.thresholdPercent`: absent under `always` / `never`, where
* no threshold was consulted, and an absence must not be read as "the default percent". */
thresholdPercent?: number;
deferred: readonly string[];
activated: readonly string[];
} & TaskEventIdentity) | {
type: "done";
result: TaskResult;
};
/** design/171 §6.2 — the `human_input` arm as a named type (Extract-derived: ONE source, the union
* above — never a hand-copied second shape). What `buildHumanInputEvent` returns. */
export type HumanInputEvent = Extract<TaskEvent, {
type: "human_input";
}>;
/** One attachment frame's record: its position, the kind the engine found (absent when the read was refused before the
* kind was known), what reached the model of its contents, and the path or name it was declared with (a restored file's
* path). The record of a person's attachment on `human_input.attachments`, and of a compaction restore's frame on
* `compacted.restoreOutcomes`. */
export interface HumanInputAttachment {
readonly ordinal: number;
readonly kind?: UserAttachmentKind;
readonly outcome: UserAttachmentOutcome;
readonly label: string;
/** Why the contents were not attached, when the engine's own frame says so: one word of the table the frame's notes read
* (`import("./user-attachment.js").ATTACHMENT_REFUSAL_REASONS` — `cannot_bind`, `rule_denied`, `approval_required`,
* `admission_unknown`, `target_moved`, `read_failed` — the file or directory could not be opened, listed or read —, and `too_large`: the contents did not fit their share — a person's `path` entry past the first request's room, a restore's file over its share).
* Present only on a `not_attached` attachment whose frame carries one of those notes;
* absent on every attachment that reached the model, and on a refusal that says nothing of the kind (a read refusal given as
* data that no rule made, an extension's decline — see {@link declinedBy} —, a host image that did not admit). A display and audit fact; it decides nothing. */
readonly reason?: import("./user-attachment.js").AttachmentRefusalReason;
/** The extension of the leg that refused this attachment at its `prompt.mention` station, by its registration name — the same author
* type {@link ExtensionRequester} and {@link RewriteAuthor} record elsewhere. Present only on a `not_attached` attachment whose refusal
* the dispatch names: an extension's `{ deny }` / `{ type: null }` answer, or an extension whose handler failed (threw, ran past its
* budget, answered what the station refuses). Absent on every attachment that reached the model, and when no extension is to be named:
* a read rule's refusal, the run's cancel, the engine's own fault, and a bad spelling handed down the chain (which handler handed it
* is not said). A display and audit fact; it decides nothing. */
readonly declinedBy?: ExtensionRequester;
}
/**
* Outcome of a manual {@link TaskStream.compact} request (the enum names align with
* the diagnosis decision tree's drain exits, so a consumer can tell "202 processed" states apart):
* - `"compacted"` — a compaction landed at the boundary (the `compacted{trigger:"manual"}` event fired).
* - `"failed"` — the attempt ran and threw (summarizer failure / empty summary / oversized summary;
* `compaction.failed` trace frame + `Runner.onError(phase:"compaction")`), or the §17.4 breaker was
* already open so the request was drained without an attempt (`compaction.failed` frame, no attempt).
* - `"mooted"` — taken but never served: its caller withdrew it, the run could no longer compact (dying loop: abort / durable suspend /
* plan review in flight), or the task settled before any boundary arrived. A request made at {@link TaskStream.inputWindow} `"over"` is refused, not taken.
* - `"noop"` — the attempt ran but there was nothing to compact (no valid cut point / empty history).
* - `"blocked"` — a `preCompact` hook deliberately blocked this compaction (not a failure).
* - `"disabled"` — requested compaction is switched off: the `manualCompact` seat is `false` (the task's
* `compaction.manualCompact`, else the deployment's `contextSettings[word].manualCompact`). No pass ran. The
* `autoCompact` seat never answers a request: with it off a requested pass still runs.
*/
export type CompactOutcome = "compacted" | "failed" | "mooted" | "noop" | "blocked" | "disabled";