# Stream events (/docs/stream-events)



`runtime.executeMessage()` is an async generator. Every yielded
value is a `StreamEvent` — a discriminated union keyed on `type`.
Browser UIs render from these; server consumers forward them over
SSE. See [SessionRuntime](/docs/session-runtime) for the
generator's signature. A **subset** of these shapes also persists
as durable [event-log](/docs/event-log) rows — the stream is the
real-time surface, the log is the durable one, and they are not
the same catalog: high-frequency stream events (deltas, progress
ticks) are deliberately stream-only, while the log's registered
event types are the durable contract. When you need a record to
survive the session, check the event-log type union, not this
catalog.

```typescript
import type { StreamEvent } from "@pleach/core";

for await (const event of runtime.executeMessage(sessionId, prompt)) {
  // event is a StreamEvent — switch on event.type
}
```

Every event also carries an optional `namespace: string[]` field —
empty for the root orchestrator, populated for events emitted from
inside a subagent. Use it to route subagent output into its own
UI surface.

Every event also carries an optional `stageId`: the graph stage
(`anchor-plan`, `tool-loop`, `synthesize` or `post-turn`) whose
provider stream produced it. The seam stamps it on every
`message.delta` and `message.complete` it tees, next to `callClass`.
Events no seam produced, such as local runtime emits, omit it, and a
producer's own `stageId` is never overwritten.

<Callout type="info" title="Coming from LangGraph?">
  LangGraph's `graph.stream(input, { streamMode: "updates" | "messages" | "values" | "custom" | "tools" | "debug" | "checkpoints" | "tasks" })` returns different shapes per mode. Pleach has a single discriminated union — `StreamEvent` — where every shape ships in every stream and consumers filter on `event.type`. The rough mapping:

  | LangGraph `streamMode` | Pleach equivalent                                                                                                            |
  | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
  | `"updates"`            | `session.updated` events                                                                                                     |
  | `"messages"`           | `message.delta` + `message.complete`                                                                                         |
  | `"values"`             | Re-read the session via `runtime.sessions.resume(sessionId)` after `session.updated`                                         |
  | `"custom"`             | Emit a `custom.event` via `runtime.events.emit()` from inside a node (see [Custom and task events](#custom-and-task-events)) |
  | `"tools"`              | `tool.delta` / `tool.input.discarded` / `tool.awaiting_approval` / `tool.started` / `tool.completed` / `tool.failed`         |
  | `"debug"`              | The full untouched stream; pleach has no filter                                                                              |
  | `"checkpoints"`        | `checkpoint.created`                                                                                                         |
  | `"tasks"`              | `task.scheduled` / `task.completed` (superstep node scheduling; see [Custom and task events](#custom-and-task-events))       |

  LangGraph's `streamMode: ["updates", "custom"]` tuple-yielding form has no pleach analog — the discriminated union plays the same role with one `switch (event.type)`. The array-tuple form trades one extra type-narrow step for the convenience of multi-mode iteration; we picked the discriminated-union shape because it composes better with downstream `flatMap` / `filter` / `tap` pipelines.
</Callout>



## Session lifecycle [#session-lifecycle]

<TypeTable
  type="{
  'session.created': { type: '{ session: SessionState }', description: 'New session minted at turn start.' },
  'session.resumed': { type: '{ session: SessionState }', description: 'Existing session loaded for the turn.' },
  'session.updated': { type: '{ session: SessionState }', description: 'State mutation propagated to subscribers.' },
}"
/>

## Message stream [#message-stream]

The main user-facing surface — what gets rendered into the chat
viewport.

| Type                | Payload                                                                                                                              | When                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message.added`     | `{ message: Message }`                                                                                                               | Full message appended (user or assistant)                                                                                                                                                                                                                                                                                                                                                                        |
| `message.delta`     | `{ delta: string; callClass?: CallClass; stageId?: StageId; partId?: string }`                                                       | Streaming chunk. `callClass` and `stageId` are optional; read them through the lane helpers (see [Delta lanes](#delta-lanes)). `partId` names the text part the chunk belongs to (see [Part ids](#part-ids))                                                                                                                                                                                                     |
| `message.complete`  | `{ message: Message; messageId?: string; usage?: { inputTokens?; outputTokens?; cachedInputTokens? }; contextInputTokens?: number }` | Final assembled assistant message. `messageId` is the id of the turn's assistant message (see [Which message a correction names](#which-message-a-correction-names)). `usage.inputTokens` is the billed sum across every provider request in the call. `contextInputTokens` is the input size of the last request, which is how full the context was. It's omitted when the last request reported no input count |
| `message.citations` | `{ citations: MessageCitation[]; section: string }`                                                                                  | Citation set attached to a message section                                                                                                                                                                                                                                                                                                                                                                       |
| `message.entities`  | `{ toolCallId, toolName, entities: Entity[] }`                                                                                       | Structured entities extracted from a tool result                                                                                                                                                                                                                                                                                                                                                                 |
| `reasoning.delta`   | `{ delta: string; partId?: string }`                                                                                                 | A chunk of the model's reasoning (chain-of-thought), surfaced from the provider as it arrives — **never answer content**                                                                                                                                                                                                                                                                                         |
| `thinking.delta`    | `{ delta: string; partId?: string }`                                                                                                 | Streaming reasoning trace (when the model emits one)                                                                                                                                                                                                                                                                                                                                                             |
| `thinking.complete` | `{ thinking: string }`                                                                                                               | Full reasoning trace assembled                                                                                                                                                                                                                                                                                                                                                                                   |

Render `message.delta` and `thinking.delta` as they arrive;
treat `message.complete` as the authoritative final text.

`message.delta.callClass` names the [call class](/docs/call-classes)
of the provider stream that produced the chunk: `"utility"` for the
tool-loop decision step, `"synthesize"` for the answer step. It is
optional and additive. A producer that does not tag a chunk omits the
field, so treat a missing `callClass` as unlabelled rather than as any
particular class. A renderer that wants only the answer in its answer
bubble can use it to tell the answer stream from the decision step's
prose.

### Delta lanes [#delta-lanes]

`callClass` and `stageId` together place a `message.delta` (and a
seam-teed `message.complete`) in one of three lanes. `@pleach/core`
exports the predicates, so a client does not re-derive the mapping:

| Lane          | Which deltas                                                                   | What a client does                                                                            |
| ------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `answer`      | `synthesize` and `converse` calls, and any delta with no `callClass`           | Append to the answer. This is what the user reads as the reply                                |
| `provisional` | The tool-loop's own draft: `callClass: "utility"` with `stageId: "tool-loop"`  | Show it live as a replaceable draft, styled as a draft, only while no answer text has arrived |
| `narration`   | Other `utility` output (the anchor-plan intent detector) and `reasoning` calls | Never the answer. Do not append it to the answer buffer                                       |

* `laneOfDelta(event)` returns `"answer" | "provisional" | "narration"`.
* `isAnswerDelta(event)` is `true` for a `message.delta` in the
  answer lane.
* `isProvisionalDelta(event)` is `true` for a `message.delta` in the
  provisional lane. It is never also an answer delta.

An untagged delta, or one with a class the helper does not know, reads
as `answer`, so an untagged answer is never blanked.

The provisional draft exists because, on a turn that calls no tools,
the tool loop's draft is the answer and the synthesizer passes it
through without streaming it again. The draft is replaced or cleared
by answer-lane text, by the turn's terminal `message.complete`, by a
`content.reset`, or by a `tool.started` or `tool.awaiting_approval`. A draft-lane `content.reset`
touches only the draft, and a narration-lane reset touches neither.
Buffered consumers (`collectStream`, `HeadlessRuntime`, `pleach tui --print`) never paint the draft; they keep it only as the fallback for
a turn that produced no answer.

`runtime/liveAnswer` exports the fold the shipped live clients
(`useChat`, `useHarness`, `useSessionMessageStream`) share:
`foldLiveAnswer(state, event)` keeps `answer` and `provisional`
buffers, and `liveAnswerView(state)` returns the text to paint with a
`provisional` flag. `useChat` and `useHarness` surface it as
`isProvisional`; see [React](/docs/react#usechat).

### Interim, withheld and narration prose [#interim-withheld-and-narration-prose]

Three events carry prose that is not the answer. None of them is a
terminal: do not end a stream on one, do not commit one as answer
content, and do not let one replace or merge into an accumulated
answer. A client that does not handle the type can ignore it.

| Type                 | Payload                                                                                                               | When                                                                                                                                                                                                                                                                                                 |
| -------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `narration.segment`  | `{ content, reason: "tool-calls" \| "stop-with-buffered-tools", stepIndex, toolCallCount, messageId?, fingerprint? }` | A tool-loop step that ended with tool calls had buffered prose ("Let me look up…"). `content` is that step's full text; `stepIndex` is its 0-based position among the round's tool-ending steps; `toolCallCount` is how many calls closed it. The round's final, no-tools step is never emitted here |
| `content.suppressed` | `{ content, reason: "stop-with-buffered-tools", messageId?, turnKey?, fingerprint?, toolCalls? }`                     | The runtime withheld decision-turn prose from delivery and carries it out in full so a host can archive it. `toolCalls` is the `{ id, name, parameters }` list the same round dispatched; their results are not known yet                                                                            |
| `content.preview`    | `{ reason, contentLen? }`                                                                                             | The body already painted is interstitial and a later stream is expected to supersede it. It carries no body; dim it or label it preliminary                                                                                                                                                          |

`fingerprint` is a `<len>:<hash>` digest, shared across
`narration.segment` and `content.suppressed`, so an archived body can
be joined to its own withheld-prose record by string equality. It is
omitted when it cannot be computed. `content.preview.reason` is one of
`"decision-interim-body-garble"`, `"decision-interim-observer-halt"`,
`"synthesizer-interim-observer-halt"` or
`"synthesizer-plan-backstop-reentry"`; `contentLen` is the interstitial
body's length at emit time, for observability only.

### Reasoning traces (`reasoning.delta`) [#reasoning-traces-reasoningdelta]

Reasoning models (DeepSeek-R1, etc.) stream a chain-of-thought
*before* the answer. Pleach surfaces that as `reasoning.delta`
events — a provider-agnostic side-channel that is **never**
concatenated into the answer text. Two reasons it exists:

1. **Liveness.** A long reasoning phase (tens of seconds with no
   answer token) would otherwise look like a stalled stream.
   `reasoning.delta` keeps the no-content watchdog from
   false-firing while the model thinks.
2. **UX.** Render a "Thinking…" indicator, or accumulate the
   deltas into a collapsible trace next to the final answer.

This is **distinct from the `reasoning` call class** (a
type-level routing invariant on the seam — see
[Seams](/docs/seams)). `reasoning.delta` is *runtime trace
content*; the `reasoning` call class is *which seam a node
consumes*. The `@pleach/react` `useSessionMessageStream` hook
exposes `isReasoning` + `reasoningText` so you don't have to
accumulate the deltas yourself — see [React](/docs/react).

### Part ids [#part-ids]

`message.delta`, `reasoning.delta` and `thinking.delta` carry an
optional `partId`. The runtime mints one text id and one reasoning id
for each provider stream, so a client can key the parts it builds the
way the AI SDK keys its text parts. A stream that is served again gets
fresh ids. Ids are opaque strings: compare them, never parse them. A
`content.reset` or `content.correction` carries no id; the part it
trims or rewrites keeps its own.

`applyStreamEvent` puts the id on the part it builds. `StreamTextPart`
and `StreamReasoningPart` gain an optional `id`:

* A delta whose `partId` differs from the open part's opens a new part.
  Two consecutive streams on one lane give two text parts, even when
  their joined text is the same.
* A delta with no `partId` appends to the open part, as before. A
  consumer that ignores the field, or folds events that carry none,
  reads the same text, and its parts have no `id`.
* Ids are unique within a message. When one stream's text resumes
  after another part (a tool call between two runs of narration), the
  new part's id is `<partId>#<n>`. A live message and the settled one
  before it can share a bare id.
* A tail trim keeps the surviving part's id. A correction or collapse
  keeps the id of the first part it replaces. `thinking.complete` keeps
  the reasoning part's id.

A fold rebuilt from persisted rows that carry no id has parts without
ids.

## Tool calls [#tool-calls]

| Type                     | Payload                                                                                                  | When                                                                                                                                                                                                                                                                                                     |
| ------------------------ | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tool.delta`             | `{ toolCallId: string; delta: string; toolName?: string }`                                               | Streaming argument assembly (e.g. partial JSON) while the model emits the tool call. Precedes `tool.started`                                                                                                                                                                                             |
| `tool.awaiting_approval` | `{ toolCall: ToolCall; interruptId: string }`                                                            | A call held at an approval gate. It comes instead of `tool.started` while the decision is owed                                                                                                                                                                                                           |
| `tool.started`           | `{ toolCall: ToolCall }`                                                                                 | The arguments are complete and the tool is dispatched. A gated call gets it only after a decision approves it; a refused or expired call never does                                                                                                                                                      |
| `tool.input.discarded`   | `{ toolCallId: string; reason: ToolInputDiscardReason; toolName?: string }`                              | A call whose arguments streamed will never start. Drop its streaming input now                                                                                                                                                                                                                           |
| `tool.completed`         | `{ toolCall: ToolCall; result: unknown }`                                                                | The call finished. A dispatched call that failed reports here too, with `toolCall.status` `"failed"` or `"error"` and the error on `toolCall.error` or `result.error`. A failed call whose result told the model not to retry also carries `result.doNotRetry: true`, so a UI can drop its retry control |
| `tool.failed`            | `{ toolCall: ToolCall; error: string }`                                                                  | Tool threw or rejected                                                                                                                                                                                                                                                                                   |
| `tool.progress`          | `{ toolCallId: string; stream: string; data: string }`                                                   | Incremental output of a running tool. `stream` names the output stream, canonically `"stdout"` or `"stderr"`                                                                                                                                                                                             |
| `tool.batch_progress`    | `{ currentBatch, totalBatches, toolsCompleted, totalTools, currentBatchTools: string[], maxConcurrent }` | A tool batch exceeds the concurrency cap and runs in several batches                                                                                                                                                                                                                                     |

Pair `tool.started` with `tool.completed` / `tool.failed` on
`toolCall.id` to render per-tool spinners and result cards. A gated
call opens with `tool.awaiting_approval`, so key the card on whichever
of the two arrives first. The runtime predicts the gate from its own approval settings: `interruptBefore` and tools that require approval. That holds on the graph's dispatch and on the client's own tool loop, which can announce a call before or after its gate is raised. If your own tool executor raises the gate, return `true` from `expectsApproval(toolCall)` in the interrupt config for that call, and its start is held too. A throw counts as `true`. Without it, that call still emits `tool.started` before its `interrupt.requested`. Read
`toolCall.status` on `tool.completed` before you render a result:
`"failed"` and `"error"` are failures.

A **flat terminal** is a `tool.completed` or `tool.failed` that names
its call by `toolCallId` and carries `hasError`, with no `toolCall`.
The runtime emits one for a call it resolves without running it, such
as a call the executor denied before running it. It settles that
call: an error when `hasError` is `true`, `status` is `"failed"` or
`"error"`, or the type is `tool.failed`, otherwise a success.

`collectStream` adds nothing to `toolCalls` for a flat terminal, since
the call's `tool.started` already listed it. `HeadlessRuntime`'s text
transcript prints `failed: <error>` for a `tool.completed` whose
`toolCall.status` is `"failed"` or `"error"`, and for a flat terminal
with `hasError`; a flat terminal's tool name comes from `toolName`.

### Discarded tool input [#discarded-tool-input]

`tool.input.discarded` says a call whose argument text streamed
(`tool.delta`) will never start, so a UI can drop its streaming input
at once instead of keeping it until the message settles. The runtime
emits it once per dropped call id. It is
transient: not a tool outcome, not persisted, and not tool work for a
resume. No `tool.started` or `tool.completed` follows for that id.
The one terminal that may follow is a flat, ledger-only `tool.failed`
whose `error` starts `SUPPRESSED:`, which settles a call that had
already been announced as never executed.

| `reason`     | Meaning                                                                                                                                     |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `retried`    | A mid-stream provider retry abandoned the attempt that streamed it                                                                          |
| `duplicate`  | An identical call (same tool, same arguments) in the same response is kept instead                                                          |
| `incomplete` | The call never finished streaming: no tool name, or the stream ended or failed first                                                        |
| `refused`    | The runtime declined to run it, such as a repeat of a call already run this turn, a batch or budget cap, a deferral or a pre-dispatch block |

The set may grow, so keep a default arm; every reason means the same
thing to a UI. A consumer that misses the event loses nothing durable,
because a settled message drops any input still streaming. A producer
that streams tool arguments itself can emit
the event with `createStreamedToolInputs(emit)` from `@pleach/core`:
note each streamed id with `noteStreamed`, each started one with
`noteStarted`, and call `reconcile(returnedIds)` or
`discardAll(reason)` when the attempt ends.

A host can announce a call in-stream, so it may already have started
the call when the decision step drops it. For such a call, and only
when its stream finished normally, the flat `tool.failed` follows the
discard:

```typescript
{ type: "tool.failed", toolCallId, toolName, hasError: true,
  error: `SUPPRESSED: ${arm} — tool "${toolName}" skipped`, ledgerOnly: true }
```

The `SUPPRESSED:` prefix says the call never executed, so it settles
the call's part as failed and pairs the host's start with one terminal.
A call from a stream that was cut (errored, aborted, exhausted, or
broken by the runtime) gets the discard only: it may already have run,
so it is never labelled skipped.

### Tool parts [#tool-parts]

`applyStreamEvent` (which `useChat`, `useHarness`,
`useSessionMessageStream` and `collectStream` share) keeps one tool
part per call:

* `tool.delta` opens an `input-streaming` part; `tool.started` moves
  it to `input-available` with the parsed input;
  `tool.input.discarded` removes a part still `input-streaming`, and a
  call that started is left alone.
* `tool.awaiting_approval` moves the call's part to
  `approval-requested`, with the interrupt id on `approval.id`. A later
  `tool.started` for that call leaves the approval state in place.
* `interrupt.requested` moves the call's part to
  `approval-requested`, with the interrupt's arguments as its input;
  `interrupt.resolved` moves it to `approval-responded` (approved) or
  `output-denied` (denied).
* `tool.failed`, and a `tool.completed` whose `toolCall.status` is
  `"failed"` or `"error"`, end the part in `output-error`. Any other
  `tool.completed` ends it in `output-available`.
* A flat terminal settles only a part that hasn't settled yet. It
  never creates a part and never overwrites a settled one.
* When the turn settles, any part still `input-streaming` is dropped.
  `withoutUnstartedToolInput(parts)` applies the same drop for a host
  that folds only the tool events and settles the turn itself.

See [React § Tool parts](/docs/react#tool-parts) for how `useChat`
exposes them.

`useChat` folds `tool.progress` into `toolOutput` (the last 64 KB per
`toolCallId`) and keeps the latest `tool.batch_progress` as
`batchProgress`.

A worked sequence for a single `search_corpus` call in a
knowledge-base assistant:

1. `tool.delta` × N — streaming arg assembly while the model emits JSON; concatenate into a per-`toolCallId` buffer
2. `tool.started` — the arguments are complete and the tool is dispatched: `{ toolCall: { id: "tc-018f-7a-1", name: "search_corpus", args: { query: "indexing strategies" } } }`
3. `tool.completed` — `{ toolCall: { id: "tc-018f-7a-1", … }, result: [{ id: "doc-abc123", score: 0.91 }, …] }`
4. `message.entities` — `{ toolCallId: "tc-018f-7a-1", toolName: "search_corpus", entities: [{ kind: "document", id: "doc-abc123" }] }`
5. `message.citations` — citations attached to the synthesized answer's body section once the LLM references the hits

Steps 2 and 3 are the spinner bracket; step 4 is what hydrates a
"sources" sidebar; step 5 is what underlines the cited sentence in
the rendered transcript.

## Custom and task events [#custom-and-task-events]

| Type             | Payload                                                                                                               | When                                                                                  |
| ---------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `custom.event`   | `{ name: string; data?: unknown }`                                                                                    | Your code called `runtime.events.emit(name, data?)` during a turn                     |
| `task.scheduled` | `{ taskId: string; node: string; step: number; messageId?: string }`                                                  | The superstep runner dispatched a graph node. `step` is the 0-based superstep ordinal |
| `task.completed` | `{ taskId: string; node: string; step: number; ok: boolean; durationMs: number; error?: string; messageId?: string }` | The node settled, after retries                                                       |

### `runtime.events.emit` [#runtimeeventsemit]

```typescript
runtime.events.emit(name: string, data?: unknown, options?: { sessionId?: string }): void
```

`emit` publishes a user-defined event, the analogue of LangGraph's
`custom` stream mode. It delivers twice, both synchronously: to
`runtime.events.on("custom.event", handler)` handlers on the live bus,
and, when the target session has a turn in flight, as a `custom.event`
on that turn's `executeMessage` stream.

```typescript
runtime.events.emit("indexing.progress", { done: 40, total: 100 });

for await (const e of runtime.executeMessage(sessionId, text)) {
  if (e.type === "custom.event" && e.name === "indexing.progress") render(e.data);
}
```

The target session is `options.sessionId`, or else the session of the
turn the call runs inside (a node, tool, provider stream or plugin
hook during a turn). `emit` is fail-closed:

* With neither, the event reaches the live bus only, and that bus
  event carries no `sessionId`. It is never delivered to an in-flight
  turn stream, because those can belong to other users' sessions.
  There is no broadcast option.
* A runtime without `AsyncLocalStorage` cannot infer the turn, so
  pass `sessionId` explicitly there.
* Emitting while the target session has no turn in flight also
  reaches the bus only.
* `data` must serialize with `JSON.stringify` (no BigInt, cycles or
  functions) to at most 64 KB (65,536 UTF-8 bytes). Otherwise the
  whole event is dropped, on the bus and the stream, with a
  `[RuntimeEvents] custom.event dropped` warning that names the
  reason.

### Task events [#task-events]

`task.scheduled` and `task.completed` describe the superstep runner
scheduling graph nodes, the analogue of LangGraph's `tasks` stream
mode. They are not subagent or async-job lifecycle events; for those,
see `subagent.*` and `job.*`. `taskId` pairs the two events, and ids
are engine node names, never channel values. They are transient: never
persisted to an event log, and sheddable under channel backpressure,
so a consumer may see one half of a pair. `task.completed.error` is a
truncated error message, present only on turns that run with
diagnostics enabled, and only when `ok` is `false`.

## Async jobs [#async-jobs]

For tools that dispatch work to a queue and return later.

| Type             | Payload                                                                              | When                                   |
| ---------------- | ------------------------------------------------------------------------------------ | -------------------------------------- |
| `job.dispatched` | `{ job: PendingJob }`                                                                | Job submitted to the dispatch endpoint |
| `job.progress`   | `{ jobId, progress, phase?, phaseProgress?, statusMessage?, estimatedRemainingMs? }` | Worker progress update                 |
| `job.completed`  | `{ job: CompletedJob }`                                                              | Worker finished successfully           |
| `job.failed`     | `{ jobId: string; error: string }`                                                   | Worker errored                         |
| `jobs.pending`   | `{ jobs: PendingJob[] }`                                                             | Snapshot of all currently-pending jobs |

`progress` is 0–1. Use `phaseProgress` for multi-phase jobs (e.g.
`download` then `process` then `upload`).

## Interrupts (human-in-the-loop) [#interrupts-human-in-the-loop]

| Type                  | Payload                                               | When                                                                    |
| --------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------- |
| `interrupt.requested` | `{ interrupt: PendingInterrupt }`                     | A gated call is waiting on a decision                                   |
| `interrupt.resolved`  | `{ interruptId: string; decision: ApprovalDecision }` | Decision submitted; turn resumes                                        |
| `interrupt.timeout`   | `{ interruptId: string }`                             | The interrupt manager's own `defaultTimeoutMs` elapsed with no decision |

The `interrupt.requested` event is when you'd surface an approval
modal in your UI; the gated call waits until `decision` lands.
`runtime.executeMessage` yields all three for approvals raised in the
turn's own session, each interrupt once, and never another session's.
A turn started with an `actorId` sees only unbound interrupts and
those bound to its own actor. See [Interrupts](/docs/interrupts).

`runtime.executeMessage` yields all three itself. A tool waiting on an
approval blocks inside the turn, so the runtime merges the session's
interrupt events from its event bus into the turn's stream, once per
interrupt id. A turn started with an `actorId` carries only its own
actor's gates and unbound ones. A gate whose decision window expires,
or that a policy releases, arrives as `interrupt.resolved` with
`decision.approved: false`, `decision.decidedBy: "timeout-policy"` and
its `decision.policyCode`. See
[Interrupts](/docs/interrupts#receiving-an-interrupt-in-the-stream).

## Execution lifecycle [#execution-lifecycle]

Agnostic signals an external `@pleach/core` consumer subscribes to via
`useChat({ onEvent })` (or any `StreamEvent` driver) to observe *how* a
turn ran — stage transitions, recovery, retries, stream timing — without
inheriting the host's console-grep idiom. They fire from graph-internal
sites alongside the runtime's own diagnostics; the values reuse the
canonical core unions (`StageId`, `RecoveryDispatchArm`) and carry no
domain concepts.

| Type                      | Payload                                                                                                                                | When                                                                                                                                                                                                                                                                                                                                                                                                           |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `turn.started`            | `{}`                                                                                                                                   | A turn begins (brackets graph + imperative paths uniformly)                                                                                                                                                                                                                                                                                                                                                    |
| `turn.completed`          | `{ outcome: "ok" \| "error" \| "interrupted" \| "deadline" \| "gate-parked"; durationMs: number; turnId?: string; aborted?: boolean }` | The turn ends; `outcome` is the terminal state. `"deadline"`: the run hit its host deadline at a boundary it couldn't save, so the turn ended unfinished. `"gate-parked"`: an approval gate parked and the turn stopped with no further model call; the decision comes back as a re-submit of the same message. `turnId` matches `turn.started`. `aborted` is true when the abort signal fired, for any reason |
| `stage.transition`        | `{ from: StageId \| null; to: StageId }`                                                                                               | The compiled graph moves stage; `from` is `null` on graph entry                                                                                                                                                                                                                                                                                                                                                |
| `stage.lattice_violation` | `{ from: StageId; to: StageId }`                                                                                                       | A runtime transition was NOT in the set of allowed edge patterns — a structural-conformance canary (fail-soft)                                                                                                                                                                                                                                                                                                 |
| `stage.post_turn_fan_out` | `{ writer: string }`                                                                                                                   | A post-turn parallel writer fired (`"sessionMemoryWrite"` / `"costRollup"`); both per turn means the fan-out held                                                                                                                                                                                                                                                                                              |
| `recovery.fired`          | `{ arm: RecoveryDispatchArm }`                                                                                                         | A post-turn recovery filter dispatched; `arm` ∈ `"zeroToolRecovery"` \| `"allToolsFailedMissingParams"` \| `"maxStepsHit"`                                                                                                                                                                                                                                                                                     |
| `retry.attempted`         | `{ reason: string; attempt: number }`                                                                                                  | The turn re-entered the model loop (e.g. tool re-resolution)                                                                                                                                                                                                                                                                                                                                                   |
| `stream.first_chunk`      | `{ ttfbMs: number }`                                                                                                                   | First content delta arrived; `ttfbMs` is time-to-first-byte from invoke                                                                                                                                                                                                                                                                                                                                        |
| `stream.completed`        | `{ chunks: number; durationMs: number }`                                                                                               | The model stream finished                                                                                                                                                                                                                                                                                                                                                                                      |

Use `stage.transition` to reconstruct the per-turn lattice walk
(`anchor-plan → tool-loop → synthesize → post-turn`); a
`stage.lattice_violation` is your signal that execution diverged from the
advertised lattice (see [Architecture](/docs/architecture) for the
nine-pattern lattice that same allowed set defines).
`stream.first_chunk` / `turn.completed` give you TTFB and total latency
without a separate metrics pipeline.

<Callout type="info" title="Per-call cost & latency live on a different surface">
  These nine are *stream* events (`executeMessage` / `useChat`). The
  per-LLM-call cost/latency signal — `model.called`
  (`{ provider, model, callClass, inputTokens, outputTokens, costUSD,
  latencyMs }`) — fires on the durable `runtime.events` bus, not this
  stream, because cost attribution is a long-lived concern. Wire it straight
  into a destination with the observe bridge:

  ```typescript
  import { observeSink } from "@pleach/observe";

  runtime.events.on("model.called", observeSink({ destinations: [store] }));
  ```

  `model.called` maps one-to-one to an `ObserveRow`. See
  [Observe](/docs/observe) for destinations, redaction, and sampling.
</Callout>

## Artifacts [#artifacts]

| Type               | Payload                     | When                                                    |
| ------------------ | --------------------------- | ------------------------------------------------------- |
| `artifact.created` | `{ artifact: ArtifactRef }` | New artifact (file, image, structured doc) materialized |

## Checkpoints and sync [#checkpoints-and-sync]

| Type                 | Payload                                                                              | When                                                                                                                                                                                                                                                                            |
| -------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `checkpoint.created` | `{ checkpoint: Checkpoint }`                                                         | Stage boundary crossed; snapshot written                                                                                                                                                                                                                                        |
| `sync.started`       | `{ sessionId: string }`                                                              | Sync coordinator begins push/pull cycle                                                                                                                                                                                                                                         |
| `sync.completed`     | `{ sessionId: string }`                                                              | Sync cycle landed cleanly                                                                                                                                                                                                                                                       |
| `sync.conflict`      | `{ sessionId, resolution: "local" \| "remote" \| "merged", conflictCount?: number }` | A conflict surfaced: a server-reported conflict at the end of a `sync()` cycle, or a concurrent version-vector conflict found by `SyncCoordinator.reconcile()`. `resolution` reports the side the client holds; `conflictCount` is the number of conflicting entries when known |
| `sync.error`         | `{ sessionId: string; error: string }`                                               | A `sync()` cycle failed (transport error or non-OK status)                                                                                                                                                                                                                      |

The `sync.*` events come from `SyncCoordinator`. Subscribe with
`coordinator.subscribe(sessionId, callback)`; a `sync()` cycle sends
`sync.started` and then exactly one of `sync.completed`,
`sync.conflict` or `sync.error`. They are delivered to those
subscribers, not yielded on the `executeMessage` stream. See
[Sync](/docs/sync).

## Subagents [#subagents]

When `enableSubagentConcurrency: true` and the orchestrator spawns
parallel workers.

| Type                 | Payload                                                | When                                                                                |
| -------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| `subagent.spawned`   | `{ subagentId, task, specName?, context? }`            | New subagent created                                                                |
| `subagent.progress`  | `{ subagentId, progress, message?, activeToolName? }`  | Subagent progress update                                                            |
| `subagent.completed` | `{ subagentId, content, toolsUsed, toolCallDetails? }` | Subagent finished                                                                   |
| `subagent.failed`    | `{ subagentId, error, terminalStatus? }`               | Subagent errored; `terminalStatus` discriminates `cancelled` / `failed` / `timeout` |

Subagent-emitted events carry `namespace` so a UI can route them
into a separate panel.

`subagent.*` rows in the durable [event log](/docs/event-log) take
their chat id only from the spawning turn's session. A sub-agent
spawned outside a chat turn (for example through the `/mcp`
`tools/call` endpoint) is written with no chat id; it is never
attributed to another chat.

## Sandbox [#sandbox]

For tools that allocate a sandboxed execution environment. The
event shapes below are stable contracts in `@pleach/core`.
`@pleach/sandbox@0.1.0` ships the `SandboxProvider` canonical
adapter and `@pleach/coding-agent@0.1.0` consumes these events —
its `start()` / `stop()` / `executeStep()` bodies all land at
the `0.1.0` cut; `executeStep()` throws
a not-started error only when called
before `start()`. Hosts can implement their own sandbox adapter
against the same event surface.

| Type                 | Payload                                                     | When                                                               |
| -------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------ |
| `sandbox.created`    | `{ sandboxId, tunnelUrl }`                                  | Sandbox booted; `tunnelUrl` is reachable for preview               |
| `sandbox.terminated` | `{ sandboxId, exportedFiles }`                              | Sandbox torn down; `exportedFiles` is the count of files saved     |
| `result.offloaded`   | `{ toolName, filename, sandboxPath, sizeBytes, rowCount? }` | Large tool result written to sandbox filesystem instead of inlined |

## Stream control [#stream-control]

| Type                  | Payload                                                                                                                       | When                                                                                                                              |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `stream.truncated`    | `{ reason; partialLength }`                                                                                                   | Output was truncated; `reason` is one of the six values below, `partialLength` is the characters of answer text before the marker |
| `stream.reconnecting` | `{ attempt, maxRetries, disconnectedAt, delayMs?, phase?: "connect" }`                                                        | Client-produced: `useChat` is about to re-send a request that failed to connect                                                   |
| `stream.disconnected` | `{ maxRetries, phase?: "connect" \| "stream", error? }`                                                                       | Client-produced: the re-send budget is spent, or an established stream dropped                                                    |
| `context.summarized`  | `{ originalMessageCount, compressedTokens, historyPath? }`                                                                    | History was compacted into a summary before the next call                                                                         |
| `content.correction`  | `{ correctedContent, reason, materializerPreviousLen?, contentClass?, sourceMessageId?, producingTurnVerified?, messageId? }` | Post-stream fabrication / leakage guard replaced already-streamed content                                                         |
| `content.reset`       | `{ reason, failedModel?, clearedDeltaLength?, supersedeMessageId?, callClass?, messageId? }`                                  | Drop streamed-so-far content; `clearedDeltaLength` tail-slices instead of full-clears when present                                |

`stream.truncated.reason` is one of six values. The first five name the
degeneration guard that halted the stream; the sixth comes from the
provider's finish reason:

| Reason                 | Meaning                                                             |
| ---------------------- | ------------------------------------------------------------------- |
| `entropy_collapse`     | The output lost coherence                                           |
| `phrase_loop`          | The model got stuck repeating a phrase                              |
| `substring_repetition` | A substring repeated past the guard's limit                         |
| `body_garble`          | The body of the answer turned to garbled text                       |
| `prefix_garble`        | The opening of the answer turned to garbled text                    |
| `length_truncation`    | The provider stopped on its length limit (`finishReason: "length"`) |

The runtime yields one `stream.truncated` per truncation on every
`executeMessage` and `resumeStream` stream, right after the event that
completed the truncation marker, so you handle it once, not per delta.

`stream.reconnecting` and `stream.disconnected` are produced by the
fetch client, never sent by the server. See
[`useChat`](/docs/react#usechat) for when each fires.

`content.reset.reason` is one of twelve values:

| Reason                                | Meaning                                                                                                                            | `clearedDeltaLength` |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `providerError`                       | A provider error mid-stream; clear what streamed before the retry                                                                  | may be set           |
| `garbledNarration`                    | The garble guard fired; clear the garbled fragment                                                                                 | may be set           |
| `synthesisReplacementRetry`           | The synthesizer's replacement retry replaces the prior draft rather than extending it                                              | not set              |
| `synthesisHeaderOverlap`              | The synthesizer re-emitted a section header already in the prior draft; rebuild from the synthesizer's stream alone                | not set              |
| `hallucinationRetrySupersede`         | A recursive retry's answer supersedes narration already accumulated; `supersedeMessageId` names the turn that authorized the reset | not set              |
| `divergentDoubleAnswer`               | A grounded draft prefix stapled in front of a fresh terminal answer covering the same ground is dropped                            | not set              |
| `noHeaderRedelivery`                  | The synthesizer near-verbatim re-delivered a draft with no shared header; the draft prefix is dropped                              | not set              |
| `abandonedPreambleShellDrop`          | A payload-free forward-action preamble shell stapled before a delivered answer is dropped                                          | not set              |
| `agentLoopFallbackAfterPartialStream` | The graph path streamed content, then threw; the fallback loop starts clean                                                        | not set              |
| `duplicateDrainHonestFallback`        | A draft that would re-persist a byte-identical earlier answer is replaced by a short honest fallback                               | not set              |
| `duplicateTerminalHonestFallback`     | The terminal-time sibling: the resolved final content duplicates a prior committed answer                                          | not set              |
| `midStreamRetry`                      | A provider stream died part-way and the retry ladder re-dispatched; the dead attempt's fragment is discarded                       | not set              |

Only `providerError` and `garbledNarration` take the tail-slice
path. Every other reason is a whole clear.

For `content.correction`, the renderer should treat
`correctedContent` as the authoritative final text — replace the
last assistant message wholesale. A common case: the model streamed
a sentence claiming it had called `fetch_document` when no such
tool call landed in the turn; the fabrication guard fires
`content.correction` with `reason: "phantom_tool_reference"` and a
`correctedContent` payload that drops the false claim. The UI's
message buffer for that `messageId` is replaced wholesale, not
appended to.

`content.correction` carries these optional fields beyond
`correctedContent` and `reason`:

* `contentClass`: `"COMMIT"` or `"PREVIEW"`. `"PREVIEW"` means the
  emitting site also stamped the content as interstitial in the content
  ledger. A `"PREVIEW"` correction may grow a visible body but should
  not shrink it.
* `sourceMessageId`: the id of the turn the corrected content was
  produced for. When present, a client should reject or defer the
  correction if it no longer matches the active turn, so a stale
  correction cannot shrink a newer turn's live body. It is the user
  turn's message id, not a per-graph-turn assistant id.
* `producingTurnVerified`: `true` when the runtime proved, by exact
  match on the stable turn key, that the current user turn produced
  the corrected content. A client that would otherwise derive turn
  ownership from a weaker key can treat `true` as authoritative.
  Absent or `false` means no claim, and only the graph-state
  divergence correction sets it today.
* `messageId`: the id of the turn's assistant message, the message
  whose stream carried the correction.

### Which message a correction names [#which-message-a-correction-names]

`content.correction`, `content.reset` and the terminal
`message.complete` carry `messageId`, the id of the turn's
**assistant** message, so a client can replace text for that message.
The runtime mints it when the turn starts, right after the user
message, and stamps it on each correction and reset as it leaves the
turn.

* When the runtime stores the answer itself, it stores it under that
  id, so a correction's `messageId` equals the stored message's `id`
  and the terminal's `messageId`. A host that persists the body itself
  mints its own row id, and an id already taken in the session is
  replaced by a fresh one, so the match isn't guaranteed there.
* `message.complete.messageId` is the stored message's own `id` when
  the runtime stored it, and the turn's assistant id otherwise.
* `sourceMessageId` is unchanged: it names the **user** message of
  the turn that produced the body. `messageId` names the stream;
  `sourceMessageId` names the producer.
* A seam-teed `message.complete` (one that carries a `callClass`) is
  forwarded as the provider emitted it and is not stamped.

All of these fields are optional. A consumer that ignores them
behaves as before.

`reason` is a member of `CONTENT_CORRECTION_REASONS`, with the
`ContentCorrectionReason` type, both exported from `@pleach/core/types`.

### How the core clients apply corrections and resets [#how-the-core-clients-apply-corrections-and-resets]

The core clients (`useChat`, `useHarness`, `useSessionMessageStream`
and `collectStream`) apply these events themselves, through shared
helpers, so they behave the same way:

* **`content.correction`** is applied mid-stream, by the reason's mode.
  `contentCorrectionModeOf(reason)` returns `"replace"` or `"append"`.
  Every reason in `CONTENT_CORRECTION_REASONS` is a `replace` today,
  and a reason outside the list reads as `replace`, so
  `correctedContent` becomes the whole body. A correction that
  arrives after the turn's terminal `message.complete` rewrites the
  settled message. A `"PREVIEW"` correction, or one that lands while
  only the provisional draft exists, rewrites the draft and is never
  promoted to the answer.
* **A stale correction is ignored.** Two checks run, and both must
  pass. Once the client knows the turn's assistant id, a correction
  naming another `messageId` is dropped. Separately, when
  `sourceMessageId` does not match the active turn's user message id
  and `producingTurnVerified` is not `true`, it is dropped too, so a
  late correction from an earlier turn cannot rewrite the current one.
  A matching `messageId` never overrides a stale `sourceMessageId`.
  The assistant id is learned from the first `messageId` on an applied
  correction or on the terminal `message.complete`, and forgotten at
  `turn.started` and at a new user turn. Fold one turn sequence per
  reducer: a stream that merges several turns without those
  boundaries is not supported.
* **`content.reset`** is routed by its own lane. An answer-lane reset
  slices the buffered tail by `clearedDeltaLength`. An untagged reset
  slices when `0 < clearedDeltaLength < length` and otherwise clears. A
  reset tagged with a `callClass` slices when
  `0 < clearedDeltaLength <= length`, so equality empties the buffer;
  zero and an overrun are ignored.
* **`collectStream`** returns the corrected text: `text` has the
  resets and corrections applied, including a correction that lands
  after the final `message.complete`.

## Provider cascade and LLM turn [#provider-cascade-and-llm-turn]

Emitted by the fallback executor and the graph LLM node — surface
per-model progress, model transitions, and token usage.

| Type                     | Payload                                                                                                              | When                                                        |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| `provider.cascade`       | `{ model?, provider?, error?, failedModels?, attempt?, isForceSynthesis? }`                                          | A model in the cascade failed; UI shows "(N failed)"        |
| `provider.cascade.reset` | –                                                                                                                    | New graph turn started; cascade counter resets              |
| `llm.turn`               | `{ model, provider?, input_tokens?, output_tokens?, tool_call_count?, depth?, modelSwitchReason?, requestedModel? }` | LLM turn completed; carries per-turn model + token metadata |

`modelSwitchReason` discriminates `"provider_fallback"`,
`"zero_tool_recovery"`, `"forceSynthesis_escalation"`,
`"forceSynthesis_garble_cascade"`. Use `llm.turn.depth` to attribute
spend across subagent depth levels — `depth: 0` is the root turn,
`depth: 1` is a direct subagent, `depth: 2` is a grandchild, and the
hard ceiling is `SUBAGENT_LIMITS.maxDepth = 3` (see
[Subagents](/docs/subagents#subagent-limits-and-depth-tracking)). A
`GROUP BY depth` on the per-call ledger gives you "how much did
fan-out cost relative to the root turn."

## Domain events [#domain-events]

| Type           | Payload                                 | When                                            |
| -------------- | --------------------------------------- | ----------------------------------------------- |
| `domain.event` | `{ domainType, domain, kind, payload }` | Plugin-namespaced event yielded onto the stream |

Plugins emit `domain.event` to surface arbitrary structured
events to the consumer without inventing a new variant per
plugin. The `domain` namespaces the plugin (e.g.
`compliance.audit`, `gateway.cost`), `kind` is the event kind,
`payload` carries the data.

## Step lifecycle [#step-lifecycle]

| Type         | Payload            | When                                                      |
| ------------ | ------------------ | --------------------------------------------------------- |
| `step.start` | `{ step: string }` | Named step (`anchor-plan`, `tool-loop-iter`, etc.) begins |
| `step.end`   | `{ step: string }` | Step completes                                            |

## Errors [#errors]

| Type    | Payload                                                                    | When                                        |
| ------- | -------------------------------------------------------------------------- | ------------------------------------------- |
| `error` | `{ error: string; code?: string; codeNum?: number; failureCode?: string }` | Recoverable or terminal error in the stream |

The `error` text is scrubbed of secrets and internal infrastructure detail before it's emitted. See [Redaction](/docs/redaction). `failureCode` is one of the closed [failure codes](/docs/error-codes#failure-codes), derived from the raw error before scrubbing. Branch on it, not on the text.

A `graph.exit_meta` event lists crashed nodes in `node_errors`. Each entry names the node and carries a fixed line, `Node failed; the error detail is withheld.`, in place of the exception text. Optional `code`, `error_class` and `message_length` describe the original failure.

The `code` field is a behavioural string such as `PROVIDER_ERROR`.
The numeric code from the catalog rides on `codeNum` — see
[Error codes](/docs/error-codes).

## Forwarding over SSE [#forwarding-over-sse]

The stream maps directly onto Server-Sent Events. The reference
Next.js route in the package looks roughly like:

```typescript
export async function POST(req: Request) {
  const { sessionId, content } = await req.json();
  const stream = new ReadableStream({
    async start(controller) {
      for await (const event of runtime.executeMessage(sessionId, content)) {
        controller.enqueue(`data: ${JSON.stringify(event)}\n\n`);
      }
      controller.close();
    },
  });
  return new Response(stream, {
    headers: { "Content-Type": "text/event-stream" },
  });
}
```

Each event becomes one SSE `data:` line. Clients re-hydrate the
union by parsing `JSON.parse(line)` and switching on `type`.

## Mode-filtered subscription [#mode-filtered-subscription]

`SessionRuntime` also exposes a non-iterator subscription that
filters by `StreamMode`. Use this for cross-cutting subscribers
that don't own the turn loop.

```typescript
const unsubscribe = runtime.subscribeToStream("messages", (event) => {
  // only message.delta / message.complete / thinking.* land here
});
```

`"values"`, `"updates"`, `"messages"`, `"custom"`, `"debug"`, and
`"all"` are the legal modes — see [SessionRuntime → Stream
subscription](/docs/session-runtime#stream-subscription) for the
per-mode event sets.

## `content.delta` [#contentdelta]

`content.delta` is the canonical streaming-chunk event type. The
substrate emits one per token-or-chunk during model output for a
turn.

It pairs with the chunk-loop that folds deltas into a terminal
message at end-of-turn. See [Event log](/docs/event-log) §
`content.delta streaming chunks` for the persisted row shape, and
[Event log projections](/docs/event-log-projections) for the fold
that reconstructs the final message.

Consumers subscribing to `content.delta` should treat each chunk
as forward-only. Don't try to "undo" a delta — the terminal
message is the canonical reconstructed state.

## tool.execution span emit [#toolexecution-span-emit]

The substrate emits a `tool.execution` OTel span per tool
dispatch. The span brackets the same lifecycle moment as the
`tool.completed` stream event above.

The two are paired surfaces for the same dispatch: the span feeds
traces and observability backends; the stream event feeds
in-process subscribers rendering the turn.

See [OTel observability](/docs/otel-observability) for the full
span surface and attribute catalog.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="SessionRuntime" href="/docs/session-runtime" description="The executeMessage signature and abort handling." />

  <Card title="Async tasks" href="/docs/async-tasks" description="Long-running tool calls fire `job.*` events on the same stream." />

  <Card title="Interrupts" href="/docs/interrupts" description="`interrupt.requested` / `interrupt.resolved` — the human-in-the-loop pause surface." />

  <Card title="Checkpointing" href="/docs/checkpointing" description="What `checkpoint.created` events bracket — stage-boundary snapshots." />

  <Card title="Sync" href="/docs/sync" description="The sync coordinator behind `sync.started` / `sync.completed` / `sync.conflict`." />
</Cards>
