> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nika.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Run events

> Follow a run through one lifecycle vocabulary on both transports, without replacing the result as the source of truth.

`run.events()` yields `NikaRunEvent`s: a lifecycle `kind` that means the same
on both transports, the task a `task.*` event names, the engine's own status
word, and the exact engine frame on `event.raw`.

```ts events.mts theme={"system"}
import { Nika } from '@supernovae-st/nika'

const nika = new Nika({ cwd: process.cwd() })
const run = await nika.run('hello.nika')

for await (const event of run.events()) {
  switch (event.kind) {
    case 'run.started': console.log('started'); break
    case 'task.completed': console.log('done:', event.task); break
    case 'task.failed': console.error('failed:', event.task, event.error?.code); break
    case 'run.waiting': console.log('a human gate holds the run'); break
    case 'run.settled': console.log('ended:', event.status); break
    case 'run.interrupted': console.warn('the engine lost this execution'); break
    default: break // engine.event and future kinds: event.raw.kind names the frame
  }
}
console.log((await run.result()).status)
```

```text theme={"system"}
started
done: greeting
ended: succeeded
succeeded
```

## How many events, on which door

The vocabulary is one; the number of events is not. For the quickstart's
one-task `hello.nika`, measured on 0.123.0:

| Door | Events |
| - | - |
| Local engine | six: `run.started` → `task.scheduled` → `task.started` → `task.completed` → `engine.event` (the engine's `workflow_completed`) → `run.settled` (`succeeded`) |
| `nika serve` | two: `run.started` → `run.settled` (`succeeded`). The server streams no per-task frame, and the SDK never invents one |

A server job admitted with a non-empty `inputs` map opens with one more, an
`engine.event` for the server's `execution.queued` frame (sequence 1, with no
`status`; the frame's `queued` stays on `event.raw.status`). A failing task
adds `task.failed` locally (with `event.error`), and the settlement reads
`failed`. Locally, a skipped task adds `task.skipped` (one skipped by
`on_error: { skip: true }` keeps the error that made it skip on `event.raw`),
a cancelled task adds `task.cancelled`, and a task that a resumed run
(`nika run --resume`) reused adds `task.cache_hit`, with no `task.started`
before it. These three carry `task`, never `error` or `status`; the package
itself never passes `--resume`. A human gate ends the stream with `run.waiting`
(`paused`) on both doors. Longer workflows emit more: never assert a fixed
count, and build a server-side progress view from `run.started`, the final
event and `run.status()`.

<video controls muted playsInline preload="none" poster="/images/posters/sdk-events.png" aria-label="nika check plans brief.nika in three waves, with a nika:wait task named review in the second; watch.mts then prints sixteen run.events() with the second each arrived, from run.started at 0.0 s through a two-second gap to run.settled succeeded at 2.1 s, and the result succeeded · cause normal · 4/4 tasks ok" alt="nika check plans brief.nika in three waves, with a nika:wait task named review in the second; watch.mts then prints sixteen run.events() with the second each arrived, from run.started at 0.0 s through a two-second gap to run.settled succeeded at 2.1 s, and the result succeeded · cause normal · 4/4 tasks ok">
  <source src="https://mintcdn.com/supernovae-acdf3706/BQMaEHUNhf9JYml1/videos/sdk-events.mp4?fit=max&auto=format&n=BQMaEHUNhf9JYml1&q=85&s=59dcc2408cc1cddd1211fa63471d9d67" type="video/mp4" />
</video>

**Sixteen events for a four-task run.** `nika check` first plans `brief.nika` in three waves, with a `nika:wait` task, `review`, in the second. `watch.mts` then prints each event of `run.events()` with the second it arrived: `run.started`, four `task.scheduled`, a `task.started` and a `task.completed` per task, two `engine.event`s whose frame (`permit_checked`, `workflow_completed`) is on `event.raw.kind`, and `run.settled`; then `result()` reads `succeeded · cause normal · 4/4 tasks ok`. The two-second gap is `review` waiting: engine 0.123.0 streams its start only when it completes. *Recorded in a terminal from `@supernovae-st/nika` 0.123.0 and its bundled engine `nika 0.123.0 (0bfde3765)`; every model call is `mock/echo`, the engine's offline rehearsal model, with no provider key and no network.*

> [accordion] Transcript: every screen of the recording, in order
>
> ```text theme={"system"}
> $ ./node_modules/.bin/nika check brief.nika | head -n 5
> nika check · brief.nika
>  ✔ PLAN     3 waves · 4 tasks · max parallelism 2
>       wave 1 audience (infer · mock/echo) · risks (infer · mock/echo)
>       wave 2 review (invoke · nika:wait)
>       wave 3 brief (infer · mock/echo)
> $
>
> ── screen cleared ──
>
> $ cat watch.mts
> import { Nika } from '@supernovae-st/nika';
>
> const nika = new Nika({ cwd: process.cwd() });
> const run = await nika.run<{ brief: string }>('brief.nika', { maxCostUsd: 0 });
>
> // One lifecycle vocabulary; the engine's own frame stays on event.raw.
> const t0 = performance.now();
> for await (const event of run.events()) {
>   const at = ((performance.now() - t0) / 1000).toFixed(1).padStart(4);
>   const frame = event.kind === 'engine.event' ? `(${event.raw.kind})` : '';
>   console.log(`${at}s  ${event.kind.padEnd(15)} ${event.task ?? ''}${event.status ?? ''}${frame}`);
> }
>
> // Events are observation; result() is the terminal truth.
> const { status, settlement } = await run.result();
> const tasks = settlement?.tasks;
> console.log(`\nresult  ${status} · cause ${settlement?.cause} · ${tasks?.ok}/${tasks?.total} tasks ok`);
> $
>
> ── screen cleared ──
>
> $ node watch.mts
>  0.0s  run.started
>  0.0s  task.scheduled  audience
>  0.0s  task.scheduled  risks
>  0.0s  task.scheduled  review
>  0.0s  task.scheduled  brief
>  0.0s  task.started    audience
>  0.0s  task.completed  audience
>  0.0s  task.started    risks
>  0.0s  task.completed  risks
>  2.0s  task.started    review
>  2.0s  engine.event    (permit_checked)
>  2.0s  task.completed  review
>  2.0s  task.started    brief
>  2.0s  task.completed  brief
>  2.0s  engine.event    (workflow_completed)
>  2.1s  run.settled     succeeded
>
> result  succeeded · cause normal · 4/4 tasks ok
> $
> ```

| `event.kind` | Local frame (`event.raw.kind`) | Server frame (`event.raw.kind`) |
| - | - | - |
| `run.started` | `workflow_started` | `execution.started` |
| `task.scheduled` · `task.started` · `task.completed` · `task.failed` | `task_scheduled` · `task_started` · `task_completed` · `task_failed` | none |
| `task.skipped` · `task.cancelled` · `task.cache_hit` | `task_skipped` · `task_cancelled` · `task_cache_hit` | none |
| `run.waiting` | `run_settled` carrying `paused` | `execution.settled` carrying `paused` |
| `run.settled` | `run_settled` carrying `succeeded`, `failed` or `cancelled` | `execution.settled` (or `execution.cancelled`, `execution.refused`) carrying the final status |
| `run.interrupted` | `workflow_interrupted` | `execution.interrupted` |
| `run.sealed` | a `run_sealed` frame, if an engine streams one | none |
| `engine.event` | every other frame (`workflow_completed`, `permit_checked`…) | every other frame: `execution.queued` (a job admitted with inputs), a future kind |

`run.sealed` names a frame engine 0.124.3 does not stream: it writes the seal
to the run's record only. Read `result.receipt.sealed` locally, or
[`traceVerify(receipt)`](https://docs.nika.sh/sdk/runtime/receipts), to know whether a run is sealed.

## Read the access contract and its receipt

A workflow file can declare how its model calls must travel: `run.access`
(`via`, `protocol`, `fallback`, and from engine 0.124.2 `service_tier`) and
`run.reasoning.effort`. On a local run, the terminal frame of each `infer:` or
`agent:` task carries two rows about it, and from 0.124.2 two functions parse
them:

```ts theme={"system"}
import { readNikaAccessRequirement, readNikaAccessSelection } from '@supernovae-st/nika';

for await (const event of run.events()) {
  if (event.kind !== 'task.completed') continue;
  const asked = readNikaAccessRequirement(event);   // { via, protocol, fallback, service_tier, effort }
  const selection = readNikaAccessSelection(event); // nika/access-selection@1
  if (!selection) continue;
  console.log(event.task, selection.model.requested, selection.model.configured, selection.effort.configured);
  const tier = selection.service_tier;
  if (tier) console.log(tier.requested, tier.transmitted, tier.configured, tier.effective.evidence);
}
```

* `readNikaAccessRequirement(event)` returns what the file asked, in the
  file's words. A key the file leaves out is absent, never a default.
* `readNikaAccessSelection(event)` returns what the route did with it. For
  the model and for the effort it keeps four facts apart: `requested` (what
  the file asked), `option` (the session option or request field it travelled
  through), `transmitted` (the exact value sent) and `configured` (what the
  route reported after the selection, with how it was learned in
  `configured_source`). `responder` is the model the provider named in its
  answer, when it names one.
* `service_tier` is present only when the file declares a tier. Its
  `requested` is the file's word (`standard` or `fast`); `offered`,
  `transmitted` and `configured` are the route's own values (`off` and `on`
  on codex-acp); `turn` and `effective` read
  `{ value: null, evidence: 'unknown' }` on an ACP session, because no ACP
  answer names the tier a turn carried or the tier that served it. An absent
  block means the file asked for none, never `standard`.

Both functions accept a `NikaRunEvent` or the engine frame it wraps. They
return `undefined` when the frame carries no such row: a task that called no
model, a file that declares no contract, or any frame from `nika serve`,
which keeps these rows in the job's sealed journal and sends neither over
HTTP. They throw `NikaProtocolError` on a row that is present and malformed.

Before you run a file that declares `run.access.service_tier`, require the
capability on the door you use: `accessServiceTier` in
`supportedCapabilities` (`nika --sdk-identity` locally, `/health` on a
server). An engine older than 0.124.2 refuses the key when it parses the
file, and a server without the token answers 422 for it.
[Ask a seat for its fast tier](https://docs.nika.sh/guides/harness-access.md#ask-a-seat-for-its-fast-tier)
has the language side and what each refusal says.

## Rules for a reducer

* **The result is the truth.** Never infer completion from the last event you
  recognized; await `run.result()`.
* **Keep a default branch.** The set is additive: `engine.event` and future
  kinds stay visible through `event.raw` without crashing an older interface.
* **Guard `event.task`.** It is present only on events that named a task.
* **`event.status` is the engine's word**, never renamed: a waiting run reads
  `paused`.
* **`event.sequence` exists only over HTTP.** It is the server's replay
  cursor: persist it for [`attachRun()`](https://docs.nika.sh/sdk/remote/jobs#recover-after-a-process-restart).

## Read events late

A run keeps its most recent events, so a view opened after the result
replays them:

```ts theme={"system"}
const run = await nika.run('hello.nika')
const result = await run.result()            // first the result,
for await (const event of run.events()) {}   // then every event the run kept
```

The bound is `eventBufferSize`, 4096 by default. Past it, the run still runs
and `run.result()` still resolves; only a late view is refused, with
`NikaEventBufferOverflowError` (`reason: 'replay_truncated'`, and
`error.observed` says how many events there were). A live view that falls more
than its `bufferSize` behind fails with `reason: 'live_backpressure'`. Neither
refusal skips an event, and neither is about the run.

## Stop a view, not the run

```ts theme={"system"}
const observer = new AbortController()
setTimeout(() => observer.abort(), 1000)

for await (const event of run.events({ signal: observer.signal, bufferSize: 64 })) {
  console.log(event.kind)
}
```

An `AbortSignal` stops only its own view: a live loop simply ends at the
abort, without an error, while the run keeps running. It never cancels engine
work: call `run.cancel()` for that.

> [accordion] Which version is this?
>
> > [!NOTE]
> >
> > These pages describe the published `@supernovae-st/nika@0.124.4`
> > [SDK release](https://github.com/supernovae-st/nika-client/tree/v0.124.4) and its matching
> > [bundled engine](https://github.com/supernovae-st/nika/releases/tag/v0.124.4). A newer engine
> > release or SDK main commit does not change an installed package. Use Node.js
> > 22 or newer, on macOS (arm64, x64) or Linux with glibc (x64, arm64); no
> > global Nika installation is required for local mode. Versioned transcripts,
> > recordings and measurements keep the release they were captured on;
> > selecting this package release does not re-run those examples.

> [card] [Results](https://docs.nika.sh/sdk/runtime/results.md)
>
> The settlement every event stream ends on.

> [card] [SSE streaming](https://docs.nika.sh/sdk/remote/streaming.md)
>
> Server events, sequence cursors and recovery.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.