@nika-open/nika 0.0.0-stage → 0.124.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/runs.md ADDED
@@ -0,0 +1,670 @@
1
+ # Runs: results, inputs, events and cancellation
2
+
3
+ A run is one admission of a workflow. `nika.run(workflow, options)` resolves
4
+ with a `NikaRun` once the engine admitted it, and the handle owns everything
5
+ that follows: its events, its result, its status and its cancellation. This
6
+ page covers both doors (the bundled engine and `nika serve`); where they
7
+ differ, it says so. Server specifics live in [server.md](server.md), proof in
8
+ [receipts.md](receipts.md), and every error in [errors.md](errors.md).
9
+
10
+ ```ts
11
+ import { Nika, isNikaRunSucceeded } from '@nika-open/nika';
12
+
13
+ const nika = new Nika();
14
+ const run = await nika.run<{ answer: number }>('flow.nika', { maxCostUsd: 0.05 });
15
+ for await (const event of run.events()) console.log(event.kind, event.status);
16
+ const result = await run.result();
17
+ console.log(isNikaRunSucceeded(result) ? result.outputs?.answer : result.status);
18
+ ```
19
+
20
+ | `NikaRun` member | What it gives you |
21
+ |---|---|
22
+ | `run.id` | The run's id: the server's durable job id over HTTP, a throwaway id on a local engine |
23
+ | `run.events(options?)` | The run's events as they happen, or replayed from the start |
24
+ | `run.result()` | The final result, settled once; a failed run resolves, it does not throw |
25
+ | `run.status()` | The current status without waiting (server runs only) |
26
+ | `run.cancel()` | Asks the engine to stop the run; every call returns the same request |
27
+ | `run.artifacts(options?)` | What the settled job produced, as its sealed journal lists it (server runs only) |
28
+ | `run.downloadArtifact(artifact, options?)` | One artifact's bytes as a stream that closes once they are proven (server runs only) |
29
+ | `run.readArtifact(artifact, options?)` | One artifact's proven bytes, whole, up to `maxBytes` (server runs only) |
30
+ | `run.done` | The same promise as `run.result()`, kept for older code |
31
+
32
+ Every member is bound to its run, so you can pass it around:
33
+ `const { events, result } = run`. The handle observes, settles, reports and
34
+ cancels its run, and on a server reads what its job produced; checking, proof,
35
+ catalogs and authoring stay on `Nika`.
36
+
37
+ ## Check a workflow without running it: `check()`
38
+
39
+ You do not need `check()` before `run()`: the engine checks on every run, and
40
+ a red file never becomes a run. Use `check()` to show the audit without
41
+ running anything, for example in a CI step or an editor.
42
+
43
+ ```ts
44
+ const report = await nika.check('hello.nika', { nativeStrict: true });
45
+ console.log(report.clean, report.exitCode);
46
+ ```
47
+
48
+ - **On a local engine** you get the engine's whole report: `clean`,
49
+ `exitCode`, its `findings[]` and its `verdicts`. Options: `model` (check
50
+ against another model), `nativeStrict` (the engine's `--native-strict`
51
+ audit), `access` (judge the access plan under a pin, see
52
+ [Pin the access path](#pin-the-access-path-access)) and `signal` (stops
53
+ this check only).
54
+ - **On a server, by served name**, you get the server's short answer:
55
+ `clean: true`, or its typed refusal with `clean: false`. The package never
56
+ invents findings or an exit code. An explicit local path (`./hello.nika`)
57
+ is captured locally and returns the engine's findings and exit code.
58
+ `model` and `nativeStrict` are refused over HTTP with a typed error;
59
+ `access` rides a served name only.
60
+
61
+ Each finding keeps the engine's fields (`NikaCheckFinding`): `code`,
62
+ `message`, `severity`, `gate`, `kind`, `task`, `docs_url`, and `span`, the
63
+ byte range of the workflow file it names (`start` inclusive, `end`
64
+ exclusive), so an editor can underline it. From engine 0.124 a parse refusal
65
+ in a local report carries a `span` too, and from 0.124.1 the range indexes
66
+ the file as saved, a leading byte-order mark included (0.124.0 indexed it
67
+ from the byte after the mark, three bytes short). A local check of a
68
+ workflow that calls a child workflow (`invoke: { workflow: ./child.nika }`)
69
+ reads the children,
70
+ and engine 0.124 judges each call as the tasks the child stands for: a
71
+ lethal trifecta (`NIKA-SEC-009`) or a confirm gate that does not stop an
72
+ effect (`NIKA-SEC-014`) is refused through a child as it is inline. The
73
+ report lists those calls in `composed_calls`, which rides untyped. From
74
+ engine 0.124 a local report also lists each paid image or speech call in
75
+ `cost.media`, untyped too: its provider, and its model, its floor, the rate
76
+ that sets it and the price table's date when they are known.
77
+
78
+ `verdicts.access_ready` judges the model routes only. From engine 0.124.1 a
79
+ local report's `verdicts.network_tasks` lists, sorted, the tasks whose own
80
+ effects can still reach the network: a fetch or webhook to a real host, an
81
+ MCP tool, a paid media call. A `mock/echo` rehearsal stubs the model, never
82
+ these tasks, and the report's PERMITS row judges them. For a `mock/echo` file
83
+ whose `grab` task calls `nika:fetch` on `api.github.com`, `network_tasks` is
84
+ `['grab']`; the ACCESS row reads `this model route never dials` and names
85
+ `grab` under it, where engine 0.124.0 printed `never dials · nothing to judge`.
86
+
87
+ The same audit, for humans, is `./node_modules/.bin/nika check hello.nika`.
88
+
89
+ ## Read the result
90
+
91
+ ```ts
92
+ import { Nika, isNikaRunSucceeded } from '@nika-open/nika';
93
+
94
+ const run = await new Nika().run<{ answer: number }>('flow.nika');
95
+ const result = await run.result();
96
+ if (isNikaRunSucceeded(result)) {
97
+ console.log(result.outputs?.answer); // outputs stay typed and optional
98
+ } else {
99
+ console.error(result.status, result.error?.code, result.error?.message);
100
+ process.exitCode = 1;
101
+ }
102
+ ```
103
+
104
+ | `result.status` | What happened |
105
+ |---|---|
106
+ | `succeeded` | The run finished. Its `outputs` are on the result, when the workflow declares any. |
107
+ | `failed` | The engine admitted the run and it failed. `result.error` carries the engine's `code`, `message` and, when one task failed, its `task`. |
108
+ | `paused` | A human gate holds the run. It is neither a failure nor a finished run. |
109
+ | `cancelled` | The run was cancelled. |
110
+ | `interrupted` | The engine lost the execution; how it would have ended is unknown. |
111
+
112
+ > [!WARNING]
113
+ > An admitted failure **resolves**: `run.result()` does not throw for a failed
114
+ > workflow. A `try { await run.result() } catch {}` alone never catches one,
115
+ > so a CI job or an app must read `result.status`, or call
116
+ > `isNikaRunSucceeded(result)`, and treat anything but `succeeded` as its own
117
+ > failure. Otherwise a red run passes silently.
118
+
119
+ `run.result()` rejects only for transport, protocol, configuration and
120
+ compatibility problems, with typed errors (see [errors.md](errors.md)). None
121
+ of those says the run failed: it may still be running.
122
+
123
+ `isNikaRunSucceeded` returns `false` for paused, failed, cancelled and
124
+ interrupted runs. It only reads the engine's status and never fills in
125
+ missing outputs. A paused run arrives as a `run.waiting` event, never as
126
+ `run.settled`, and `result.status` keeps the engine's word, `paused`: show it
127
+ as waiting, and never let a CI job pass it as success.
128
+
129
+ A paused run waits for an answer this package cannot give: `run()` has no
130
+ way to answer a gate. On a local engine the question is on the native
131
+ `workflow_paused` frame, an `engine.event` whose `raw.fields` hold it in the
132
+ `message` row; answer it from a terminal with
133
+ `nika run --resume <trace> --answer <task>=<value>`. From engine 0.124, a
134
+ command a Codex seat asks to run outside its sandbox always pauses, whatever
135
+ `permits.exec` grants, and its question names the command and the reason on
136
+ one line (`Run command: curl -sS https://example.com (reason: …)`). One
137
+ `--answer` decides one ask: an attempt that `retry:` replays asks again. A
138
+ server's frames do not carry the question: the job reads `paused`.
139
+
140
+ `result.settlement` carries the engine's own account of the ending: its
141
+ `cause` (`normal`, `human_gate`, `task_failed`, `budget`, `operator`…), the
142
+ task tally, the elapsed time and the spend with its pricing qualifier. An
143
+ unknown cost is never reported as zero. From engine 0.124 the keyless system
144
+ voice (`nika:tts_generate` with `provider: system`) counts as an unpriced
145
+ call, like a mock or local model: a run whose only spend is that voice
146
+ settles with `spend.qualifier` `unpriced` and `unpriced_calls: 1`, and its
147
+ native task frame names why (`cost_unpriced: local_model`).
148
+
149
+ Paid image and speech calls count from engine 0.124 too. A call the
150
+ engine's dated price table prices adds its bill to `spend.total_cost_usd`,
151
+ under `spend.by_source['nika:image_generate']` or
152
+ `spend.by_source['nika:tts_generate']`, and keeps it when the call fails
153
+ after its provider billed: a local `task_failed` frame then carries it as
154
+ `cost_usd`. A paid call the table cannot price runs only with no cost cap,
155
+ and counts in `unpriced_calls` (`cost_unpriced: missing_catalog_price`), so
156
+ the run settles `unpriced` or `partially_priced`, never `priced`. Under a
157
+ cap, `maxCostUsd` or the server's ceiling, it is refused before any request.
158
+ A call the workflow writes out refuses the run with `NIKA-1709`: `run()`
159
+ rejects on a local engine, and a server job settles `failed` with that code
160
+ and no `settlement`. A call only the run decides fails its task with
161
+ `NIKA-1704` (see [errors.md](errors.md#troubleshooting)).
162
+
163
+ ## Pass your app's data: `inputs`
164
+
165
+ `inputs` fills the workflow's declared `inputs:` by name, with the same
166
+ meaning on both transports:
167
+
168
+ ```ts
169
+ const run = await nika.run('support-triage.nika', {
170
+ inputs: { ticketId: '42' },
171
+ // idempotencyKey: `triage-${ticket.id}`, // HTTP only
172
+ });
173
+ ```
174
+
175
+ **Values are strict JSON and stay literal.** `'42'` stays a string and `42` a
176
+ number. `'@env:HOME'` and `'${{ tasks.x.output }}'` are plain text: never read
177
+ from the environment, never evaluated. Nothing is converted to the declared
178
+ type.
179
+
180
+ **The engine judges them before any run exists.** An undeclared key
181
+ (`unknown_input`), a value that does not fit its declared type
182
+ (`input_type_mismatch`) or a missing required input (`NIKA-1708`) makes
183
+ `run()` reject with a `NikaOperationError` carrying that code, `status: 3` on
184
+ a local engine and `status: 422` over HTTP. The values you pass are recorded
185
+ with `api-caller` provenance; declared defaults keep `file`.
186
+
187
+ **The package refuses what JSON would silently lose**, before it starts or
188
+ sends anything: `undefined`, a function, a symbol, a bigint, `NaN` or
189
+ `Infinity`, a cycle, a class instance (a `Date`, a `Map`), an object whose
190
+ prototype only pretends to be plain, an array hole, an accessor. That is a
191
+ `NikaConfigurationError` naming the path (`inputs.ticketId is undefined`),
192
+ never the value. None of your code runs while the map is judged: no getter is
193
+ called, and a `Proxy` is refused before it is read. The serialized map is
194
+ limited to 1 MiB on both transports. Do not put a secret in `inputs`.
195
+
196
+ **The engine must advertise the channel**, and the package checks before
197
+ admission:
198
+
199
+ - Local: `inputsLiteral` in `nika --sdk-identity`. The values travel on the
200
+ engine's stdin (`nika run --inputs-json -`), so they never appear in a
201
+ process listing.
202
+ - Server: `jobInputs` in `GET /health`, for a workflow run by its served
203
+ name. A snapshot of a local file (`./flow.nika`) freezes its inputs, so an
204
+ HTTP run of a local path refuses `inputs`, even an empty map.
205
+
206
+ Engine 0.123.0 advertises both. An engine without the capability makes `run()`
207
+ reject with `NikaCompatibilityError` (`capability: 'inputsLiteral'` or
208
+ `'jobInputs'`) and nothing runs. The SDK never falls back to `--var`. A server
209
+ that merely answers 202 has agreed to nothing: one older than this channel
210
+ accepts the field and ignores its values.
211
+
212
+ `vars` is deprecated. It remains the local `--var KEY=VALUE` operator
213
+ channel, unchanged: the engine reads `@env:NAME` from its environment and
214
+ converts text to the declared type, so it cannot carry literal values and has
215
+ no HTTP form. Passing `inputs` and `vars` together rejects `run()`; they are
216
+ never merged. From engine 0.124, a `vars` pair the engine refuses carries the
217
+ same code as `inputs` (`unknown_input`, `input_type_mismatch`); engine 0.123
218
+ named none, so the package's `run_refused` stood in its place.
219
+
220
+ ## Pin the access path: `access`
221
+
222
+ A workflow's `model:` picks the intelligence; an access pin picks the path
223
+ the engine takes to it, the value `nika run --access` takes. It is an access
224
+ class (`local`, `mock`, `harness`, `oauth`, `api`) or a harness seat
225
+ (`claude-code`, `codex`, `copilot`, `gemini-cli`, `grok-build`, `kimi-code`,
226
+ `opencode`, `qwen-code`), the words engine 0.123.1 knows. The type,
227
+ `NikaAccessPin`, lists them for completion and still takes any string: the
228
+ engine, never the package, judges a pin.
229
+
230
+ ```ts
231
+ const run = await nika.run('triage.nika', { access: 'codex' });
232
+ const report = await nika.check('triage.nika', { access: 'codex' });
233
+ console.log(report.verdicts?.access_ready, report.verdicts?.blockers);
234
+ ```
235
+
236
+ A pin is a pin: the engine refuses one it does not know or that is retired
237
+ (`NIKA-1802`), or one the workflow's model cannot use (`NIKA-1801`), and it
238
+ never takes another path or model instead. Each door reports that refusal as
239
+ the engine wrote it:
240
+
241
+ | | Local engine | `nika serve` |
242
+ |---|---|---|
243
+ | Sent as | one argv element, `--access=<pin>` (a pin that starts with `-` stays a value) | `access` in the `POST /v1/jobs` or `POST /v1/check` body, beside a served name |
244
+ | A pin the engine takes | the run uses that path; `run_settled` lists it in `access_plan` with `pinned: true` | the job uses that path |
245
+ | An unknown, retired or unusable pin | `run()` resolves and `run.result()` settles `failed`: `error.code` `NIKA-1802` or `NIKA-1801`, `settlement.cause` `refused`, `exitCode` 3; no task ran | the server admits the job (202), its execution refuses the pin, and `run.result()` settles `failed` with `error.code`, no `settlement` |
246
+ | An empty or blank pin | the same, `NIKA-1802` | `run()` rejects with `NikaOperationError`: `code` `NIKA-1802`, `status` 422 |
247
+ | `check({ access })` | the report judges the access plan under the pin: an unusable pin keeps `clean: true` (the file holds), with `verdicts.access_ready: false` and the refusal in `verdicts.blockers` | the server's check is source-only and evaluates no access plan: it acknowledges any other pin, and refuses an empty one with `clean: false`, `error.code` `NIKA-1802` |
248
+ | A local file (`./flow.nika`) | the pin applies | refused before any capture or request: a snapshot carries no pin (`NikaCompatibilityError`, `capability: 'snapshotAccess'`) |
249
+
250
+ The package itself refuses only a value neither door can carry unchanged,
251
+ before anything starts: a non-string, a NUL byte or a lone surrogate
252
+ (`NikaConfigurationError`, `run({ access })` or `check({ access })` in its
253
+ message). Over HTTP the pin is part of the request bytes an idempotency key
254
+ binds: a retry sends the same pin, and another pin under the same key is an
255
+ `idempotency_conflict`. Measured on engine 0.123.1.
256
+
257
+ ## The file's own access contract: `run.access`
258
+
259
+ A workflow file can declare its route itself, under `run.access` and
260
+ `run.reasoning`. The package sends nothing for it: the engine reads the file.
261
+
262
+ ```yaml
263
+ run:
264
+ access:
265
+ via: codex
266
+ protocol: acp
267
+ fallback: none
268
+ service_tier: fast # engine 0.124.2 and later
269
+ reasoning:
270
+ effort: low
271
+ ```
272
+
273
+ `service_tier` takes the words `standard` and `fast`. Leaving it out is not
274
+ `standard`: the engine then sends no speed selection and the route keeps its
275
+ own tier. Only a route with a measured speed control carries it (the codex
276
+ seat over ACP today); every other route refuses the key before any model call
277
+ (`NIKA-1800` at check and before task 1, `NIKA-1805` when the session refuses
278
+ it). An engine older than 0.124.2 refuses the key at parse.
279
+
280
+ Before you run a file that declares a tier, require the capability on the door
281
+ you use: `accessServiceTier` in `supportedCapabilities` (`nika
282
+ --sdk-identity` locally, `/health` on a server).
283
+
284
+ On a local run, each `infer:` or `agent:` task's terminal frame carries what
285
+ the file asked and what the route did. Two readers parse those rows:
286
+
287
+ ```ts
288
+ import { readNikaAccessRequirement, readNikaAccessSelection } from '@nika-open/nika';
289
+
290
+ for await (const event of run.events()) {
291
+ if (event.kind !== 'task.completed') continue;
292
+ const asked = readNikaAccessRequirement(event); // { via, protocol, fallback, service_tier, effort }
293
+ const selection = readNikaAccessSelection(event); // nika/access-selection@1
294
+ const tier = selection?.service_tier;
295
+ if (tier) {
296
+ console.log(event.task, tier.requested, tier.transmitted, tier.configured, tier.effective.evidence);
297
+ // render_image fast on on unknown
298
+ }
299
+ }
300
+ ```
301
+
302
+ The receipt keeps its facts apart, and so should what you show:
303
+
304
+ | Fact | Where | Meaning |
305
+ |---|---|---|
306
+ | Requested | `service_tier.requested` | the file's word (`standard`, `fast`) |
307
+ | Offered | `service_tier.offered` | the values the route listed for its option when the tier was judged |
308
+ | Transmitted | `service_tier.transmitted` | the route's own value the engine sent (codex-acp: `on`, `off`) |
309
+ | Configured | `service_tier.configured` | the value the route reported after the selection |
310
+ | Carried on the turn | `service_tier.turn` | `{ value: null, evidence: 'unknown' }` on an ACP session |
311
+ | Effective | `service_tier.effective` | `{ value: null, evidence: 'unknown' }` unless a provider reports it |
312
+
313
+ A configured `on` is not proof that a turn ran on the fast tier: an ACP
314
+ answer names neither the tier it carried nor the one that served it. Both
315
+ readers return `undefined` when the frame carries no such row (a task that
316
+ called no model, a file that declares no contract, or any frame from `nika
317
+ serve`, which keeps these rows in the sealed journal), and throw
318
+ `NikaProtocolError` on a row that is present and malformed.
319
+
320
+ ## Watch a run: `run.events()`
321
+
322
+ `run.events()` yields `NikaRunEvent`s: a lifecycle `kind` that means the same
323
+ on both transports, plus the exact engine frame on `event.raw`.
324
+
325
+ ```ts
326
+ for await (const event of run.events()) {
327
+ switch (event.kind) {
328
+ case 'run.started': break;
329
+ case 'task.completed': console.log('done:', event.task); break;
330
+ case 'task.failed': console.error(event.task, event.error?.code); break;
331
+ case 'run.waiting': console.log('a human gate holds the run'); break;
332
+ case 'run.settled': console.log('ended:', event.status); break;
333
+ case 'run.interrupted': console.warn('the engine lost this execution'); break;
334
+ default: break; // new kinds may come: event.raw.kind names the frame
335
+ }
336
+ }
337
+ ```
338
+
339
+ For the quick-start file on a local engine you get six events:
340
+ `run.started`; `task.scheduled`, `task.started` and `task.completed` for the
341
+ task `greeting`; one `engine.event` (the engine's `workflow_completed`); then
342
+ `run.settled` with `succeeded`. That holds with or without a signing key
343
+ (measured on engine 0.123.0): a sealed run's seal is the last line of its
344
+ trace (`run_sealed`), and that run streamed no `run_sealed` frame, so read
345
+ `result.receipt.sealed` to know whether a run was sealed. A `nika serve` run
346
+ of the same file yields two events, `run.started` and `run.settled`: the
347
+ server streams no per-task frames, and the package never invents one. A
348
+ server job admitted with `inputs` yields three: the server first records
349
+ `execution.queued` (sequence 1, before `execution.started`), which the
350
+ package names `engine.event`, with no `status` (the frame's `queued` stays on
351
+ `event.raw.status`). Measured on engine 0.123.1; an empty `inputs` map adds
352
+ no such frame.
353
+
354
+ **Watch a four-task run stream its events.**
355
+
356
+ <p align="center">
357
+ <picture>
358
+ <source media="(prefers-reduced-motion: reduce)" srcset="https://raw.githubusercontent.com/nika-open/nika-client/HEAD/media/stills/sdk-events.png">
359
+ <img src="https://raw.githubusercontent.com/nika-open/nika-client/HEAD/media/gifs/sdk-events.gif" alt="nika check brief.nika plans 3 waves and 4 tasks. watch.mts loops over run.events() and prints each event's time and kind. node watch.mts prints 16 events: at 0.0 s run.started, four task.scheduled, audience and risks started and completed; at 2.0 s review started, an engine.event (permit_checked), review completed, brief started and completed, an engine.event (workflow_completed) and run.settled succeeded; then result succeeded · cause normal · 4/4 tasks ok" width="860">
360
+ </picture>
361
+ </p>
362
+ <p align="center"><sub><code>watch.mts</code> prints each event of a four-task workflow with the time it arrived: sixteen events, the engine's <code>permit_checked</code> and <code>workflow_completed</code> frames as <code>engine.event</code> (their kind on <code>event.raw</code>), then <code>result()</code>: <code>succeeded · cause normal · 4/4 tasks ok</code>. The two-second gap is a <code>nika:wait</code> task, whose start engine 0.124.0 streams only when it completes. Recorded from <code>@supernovae-st/nika</code> 0.124.0 and its bundled engine; the run is a <code>mock/echo</code> rehearsal.<br>▶ <a href="https://github.com/nika-open/nika-client/blob/main/media/videos/sdk-events.mp4?raw=true">MP4</a> · <a href="https://github.com/nika-open/nika-client/blob/main/media/transcripts/sdk-events.txt">transcript</a> · <a href="https://github.com/nika-open/nika-client/tree/main/scripts/media/scenes/sdk-events">the workflow and the program</a></sub></p>
363
+
364
+ | `event.kind` | Local engine frame (`event.raw.kind`) | Server frame (`event.raw.kind`) |
365
+ |---|---|---|
366
+ | `run.started` | `workflow_started` | `execution.started` |
367
+ | `task.scheduled` · `task.started` · `task.completed` · `task.failed` · `task.skipped` · `task.cancelled` · `task.cache_hit` | `task_scheduled` · `task_started` · `task_completed` · `task_failed` · `task_skipped` · `task_cancelled` · `task_cache_hit` | none: the server streams no per-task frame |
368
+ | `run.waiting` | `run_settled` carrying `paused` | `execution.settled` carrying `paused` |
369
+ | `run.settled` | `run_settled` carrying `succeeded` · `failed` · `cancelled` | `execution.settled` carrying `succeeded` · `failed` · `cancelled`; `execution.cancelled` carrying `cancelled` only; `execution.refused` carrying `failed` only |
370
+ | `run.interrupted` | `workflow_interrupted` carrying `interrupted` | `execution.interrupted` · `interrupted` carrying `interrupted` |
371
+ | `run.sealed` | `run_sealed`, when an engine streams one | none |
372
+ | `engine.event` | every other frame (`workflow_completed`, `workflow_paused`, `permit_checked`, `task_recovered`…) | every other frame: `execution.queued` (a job admitted with inputs), a `null` or future kind |
373
+
374
+ `event.status` is always the engine's own word (a waiting run reads
375
+ `paused`). `event.task` is the task a `task.*` frame named. A task the engine
376
+ skipped ends on `task.skipped` and a task it cancelled on `task.cancelled`,
377
+ whatever the reason: both name their `task`, never an `error` or a `status`.
378
+ A task skipped by `on_error: { skip: true }` still keeps the error that made
379
+ it skip: the engine leaves it on `event.raw`, in the frame's `outcome` row.
380
+ A recovered task ends on `task.completed`; the engine's `task_recovered` frame
381
+ before it stays an `engine.event`. Measured on engine 0.123.2 with one task
382
+ skipped by `on_error: { skip: true }`, one recovered by
383
+ `on_error: { recover: … }` and one cancelled because its `after:` edge never
384
+ admitted. A task a resumed run reused ends on `task.cache_hit`, which names
385
+ its `task` and has no `task.started` before it: `nika run --resume <trace>`
386
+ skips a task whose identity matches a success the trace records, and the
387
+ frame keeps that identity (`def_hash`, `input_hash`) and the reused `output`
388
+ on `event.raw`, in its rows. The package itself never resumes a run. Measured
389
+ on engine 0.123.2, resuming a run whose second task had failed. `event.error` is
390
+ the failure a `task.failed` frame or a `failed` settlement named; no other
391
+ event carries one. `event.sequence` is the server's replay cursor and exists
392
+ only over HTTP. An `engine.event` carries only its cursor and `raw`, never a
393
+ `status`.
394
+
395
+ The package names a fact only when the engine wrote it, for a (kind, status)
396
+ pair the table lists. The engine's state word decides and is never assumed: an
397
+ absent, null, future or still-running status stays an `engine.event`, and so
398
+ does a frame that contradicts itself (`execution.refused` carrying
399
+ `succeeded`, say). `event.raw` still holds that frame, and `run.result()`
400
+ still reads the state the engine wrote. The projection keeps no state between
401
+ frames, removes no duplicates and never makes up an event: transports differ
402
+ in how many events they send, never in their names.
403
+
404
+ `run.waiting` is not `run.settled`: a human gate holds a run that can resume,
405
+ neither failed nor done. `run.interrupted` is the engine reporting that it
406
+ lost an execution; it has nothing to do with the thrown
407
+ `NikaObservationInterrupted`, which means this client lost its view of a run
408
+ that may still be running.
409
+
410
+ ### A view opened late
411
+
412
+ You can read the result first and the events after:
413
+
414
+ ```ts
415
+ const run = await nika.run('wide.nika');
416
+ const result = await run.result(); // first the result,
417
+ for await (const event of run.events()) {} // then every event the run saw
418
+ ```
419
+
420
+ A late view gets every event the run kept, or it is refused; it is never
421
+ handed a shortened history. A run keeps its most recent `eventBufferSize`
422
+ events, **4096 by default**. For scale, measured on engine 0.123.0: a clean
423
+ run of N independent `mock/echo` tasks wrote `3N + 3` frames (1 task: 6, 10
424
+ tasks: 33, 90 tasks: 273). That is one fixture, not a law: a `nika:wait`
425
+ task adds a `permit_checked` frame, a failed task writes `task_failed`, and
426
+ retries, agents and `for_each` were not measured. Count your own run:
427
+ `error.observed` below gives the number. A `nika serve` job was measured at
428
+ two frames (three with inputs), so the bound matters on a local engine.
429
+
430
+ The bound is finite on purpose. Each frame is capped by `machineBufferBytes`
431
+ (16 MiB by default, see [Large results](#large-results-machinebufferbytes)),
432
+ so a run's kept history holds at most `eventBufferSize × machineBufferBytes`
433
+ of frame text: 64 GiB at the defaults. That is arithmetic over the per-frame
434
+ cap, not a size any run approaches: on engine 0.123.0 the 273 frames of the
435
+ 90-task run totalled 0.19 MiB, and the largest, the run's first frame
436
+ (`workflow_started`, which carries the engine's admission pricing), was about
437
+ 32 KiB. The bound covers the history only: events your code holds, other open
438
+ views and other runs add their own. Nothing here is a claim about heap or
439
+ process memory. If the ceiling matters to you, set `eventBufferSize`
440
+ yourself: an explicit value is kept exactly. Do not lower `machineBufferBytes`
441
+ below that first frame: a run then fails with a `NikaProtocolError`
442
+ (measured: 16 KiB fails, 32 KiB and 64 KiB pass).
443
+
444
+ Past the bound, the run still runs and `run.result()` still resolves. Only a
445
+ view is refused, with `NikaEventBufferOverflowError`, whose `reason` names the
446
+ bound it hit:
447
+
448
+ | `error.reason` | What happened | What to do |
449
+ |---|---|---|
450
+ | `replay_truncated` | The view opened after the run produced more events (`error.observed`) than it can be given (`error.limit`); `error.retained` is how many the run still holds | If `retained === observed`, nothing is lost: open the view with `bufferSize >= observed`. Otherwise the early events are gone from this process: set `eventBufferSize >= observed` for the next run, or watch it live |
451
+ | `live_backpressure` | A live view fell more than `error.limit` events behind | Read faster, or raise that view's `bufferSize`; other views and the result are unaffected |
452
+
453
+ ```ts
454
+ try {
455
+ for await (const event of run.events()) render(event);
456
+ } catch (error) {
457
+ if (error instanceof NikaEventBufferOverflowError && error.reason === 'replay_truncated') {
458
+ // The run is fine. Its history is longer than this view can replay.
459
+ console.warn(`${error.observed} events, ${error.retained} retained; run ${result.status}`);
460
+ } else throw error;
461
+ }
462
+ ```
463
+
464
+ Neither refusal skips an event, and neither is about the run.
465
+ `error.observed` is a count taken when the view opened. The engine's journal
466
+ stays the source of truth for a local trace (`receipt.trace_path`,
467
+ `traceVerify`): a late `run.events()` only replays what this process saw, and
468
+ the package reads no journal to extend it. Over HTTP the server holds the
469
+ job: recover there with `attachRun(id, { lastEventId })` (see
470
+ [server.md](server.md#recovery-after-a-restart)).
471
+
472
+ ### Large results: `machineBufferBytes`
473
+
474
+ `machineBufferBytes` is the most the package holds of one engine frame (a
475
+ local engine's stdout line, a server's SSE event) or one document (a server's
476
+ JSON answer, a captured report). Its default, **16 MiB**, is the bound of a
477
+ `nika serve` job store: the server refuses, rather than truncates, a result
478
+ that would outgrow it, so every result a server settles reaches
479
+ `run.result()` and `attachRun()` under the default. Outputs that carry an
480
+ image are the usual large result, base64 widening the bytes by a third: on
481
+ engine 0.123.1 a 200,049-byte outputs map rode a 200,756-byte frame and a
482
+ 200,815-byte job record. A local engine bounds no frame: `run_settled`
483
+ carries the outputs map whole, whatever its size, and a task's output rides
484
+ its `task_completed` frame, so a local result above 16 MiB needs a larger
485
+ value.
486
+
487
+ Past the bound, the package reads the frame to its end without keeping it,
488
+ then rejects with a `NikaProtocolError` that names the option and the size
489
+ to set:
490
+
491
+ ```text
492
+ SSE event frame of job 51b0db8a-518b-4b3b-83c4-9dec6f47de03 exceeded 65536 bytes (machineBufferBytes): it is 200756 bytes. Set machineBufferBytes to at least 200756, or leave it unset: its 16 MiB default holds any result nika serve settles. The job itself is unaffected: attachRun('51b0db8a-518b-4b3b-83c4-9dec6f47de03') reads it again
493
+ ```
494
+
495
+ That is a 200,000-character output under `machineBufferBytes: 64 * 1024`
496
+ (the former default), measured on engine 0.123.1.
497
+
498
+ The same words name a server's JSON record (`HTTP /v1/jobs/<id> JSON
499
+ exceeded …`, its size read from `Content-Length`), a local line (`Native
500
+ machine line exceeded …`) and a local report (`` `nika check` output
501
+ exceeded … ``). On a server the job keeps its result: a client with a larger
502
+ bound reads it again with `attachRun(jobId)`, which reads the job's record
503
+ first, a few dozen bytes larger than its last frame. Locally, that result
504
+ never reaches your process: set the larger bound before the run.
505
+
506
+ ## Files a server run produced: artifacts
507
+
508
+ An image in `outputs` rides as base64. A server run can hand you the file
509
+ itself instead: the files its builtins saved (`nika:chart`,
510
+ `nika:image_generate`, `nika:tts_generate`, `nika:image_fx`, and
511
+ `nika:image_compose` from engine 0.124) and the images its agents sent,
512
+ listed from the job's sealed journal, each one downloaded with its bytes
513
+ proven against the size and SHA-256 recorded there:
514
+
515
+ ```ts
516
+ await run.result();
517
+ const { artifacts } = await run.artifacts();
518
+ const chart = await run.readArtifact(artifacts[0]!); // Uint8Array, up to 16 MiB by default
519
+ const { stream } = await run.downloadArtifact('file/out/totals.svg'); // streamed, no maxBytes
520
+ ```
521
+
522
+ From engine 0.124, an `agent:` task that declares
523
+ `images: { save: ./out/banner.png }` has the engine write the image its
524
+ harness sent to that path, and the manifest lists that file
525
+ (`file/out/banner.png`) beside the image itself (`agent_image/1.png`),
526
+ the same bytes under two names. From engine 0.124.1 it also lists each file
527
+ a `for_each` fan-out saved, one entry per item, once every item settled ok.
528
+
529
+ Neither `machineBufferBytes` nor `requestTimeout` bounds a download. A local
530
+ run has no artifact manifest: its files are where its workflow wrote them, in
531
+ the client's `cwd`, and the three methods reject with
532
+ `NikaCompatibilityError` (`capability: 'artifacts'`).
533
+ [server.md](server.md#download-what-a-job-produced-artifacts) covers what is
534
+ listed, what a download proves, its retries and its errors.
535
+
536
+ ## Cancel a run
537
+
538
+ ```ts
539
+ const run = await nika.run('slow.nika');
540
+ const cancellation = await run.cancel();
541
+ const result = await run.result();
542
+
543
+ console.log(cancellation.accepted, cancellation.status, result.status);
544
+ ```
545
+
546
+ `run.cancel()` is idempotent: every call returns the same request. An
547
+ `AbortSignal` you pass to `check`, `events` or `traceVerify` stops only that
548
+ request or view; it never cancels the run.
549
+
550
+ - **Local engine.** The package signals the engine process, and the result is
551
+ whatever the engine then records. Work already in flight settles first
552
+ (an MCP call in flight is told to cancel) and tasks not yet started are
553
+ cancelled: the run settles `cancelled` (cause `operator`), `interrupted`
554
+ when the process ended without a settlement, or `succeeded` when its last
555
+ task had completed before the request landed. On engine 0.123.0,
556
+ cancelling a run waiting in a `nika:wait` task printed
557
+ `true cancellation_requested cancelled` once the wait ended, and a cancel
558
+ during the first of two waits settled `cancelled` with the second never
559
+ started. A local engine sets no time limit on that settling.
560
+ - **`nika serve`.** A running job answers 202,
561
+ `{ accepted: true, status: 'cancellation_requested' }`, and the server
562
+ gives the run a **fixed 5-second grace**, which no option changes, to reach
563
+ its next wave boundary and settle. Within it, `run.result()` settles on what
564
+ the run recorded: `cancelled`, or `succeeded` or `failed` when that raced the
565
+ request. Past it, the server drops the execution and records the job
566
+ `interrupted`: the events end with `run.interrupted`, `result.status` is
567
+ `interrupted`, never `cancelled`, and the result carries no `settlement`, so
568
+ that run's task tally and spend are unknown to the client; `run.status()`
569
+ then reads `interrupted`. A task still waiting, calling a model or running
570
+ a command 5 seconds after the request ends the job this way. Measured on
571
+ engine 0.123.1: a job inside a 20-second `nika:wait` settled `interrupted`
572
+ about 5 seconds after its cancel, with the events `run.started` and
573
+ `run.interrupted`. A job cancelled before its execution started settles on
574
+ the reply itself (200, `status: 'cancelled'`). A job that already ended
575
+ replays its result with `accepted: false` and `status: 'already_settled'`.
576
+
577
+ [`examples/watch-and-cancel.ts`](https://github.com/nika-open/nika-client/blob/main/examples/watch-and-cancel.ts) prints each
578
+ event as it arrives and cancels after a delay or on Ctrl+C, on either door.
579
+
580
+ ## Typed engine frames, outputs and ids
581
+
582
+ `event.raw` is a `NikaEvent`: a union over the frames both transports send. A
583
+ local engine sends `workflow_started`, `task_scheduled`, `task_started`,
584
+ `task_completed`, `workflow_completed`, `workflow_failed`,
585
+ `workflow_interrupted` and `run_settled`; the union also types `run_sealed`,
586
+ which the measured 0.123.0 runs kept in their trace instead of streaming it.
587
+ A `nika serve` job streams `execution.started`,
588
+ `execution.settled`, `execution.cancelled`, `execution.refused` and
589
+ `execution.interrupted` (a server that restarts marks an orphaned running job
590
+ `interrupted`). Kinds this version does not know yet stay readable through
591
+ the `NikaUnknownEvent` fallback, so the union is open on purpose and every
592
+ variant keeps room for future fields.
593
+
594
+ `run()` and `attachRun()` take one `Outputs` type argument. It types
595
+ `run.result()` and, on the raw frames, `run_settled`, `execution.settled` and
596
+ `workflow_completed`. It validates nothing at runtime, and defaults to
597
+ `Record<string, unknown>`:
598
+
599
+ ```ts
600
+ const run = await nika.run<{ answer: number }>('flow.nika');
601
+ const result = await run.result(); // result.outputs?: { answer: number }
602
+
603
+ for await (const event of run.events()) {
604
+ if (isNikaRunSettledEvent(event.raw)) {
605
+ // The settlement frame of either transport (`run_settled` locally,
606
+ // `execution.settled` over HTTP): status, outputs and receipt together.
607
+ console.log(event.raw.status, event.raw.outputs?.answer, event.raw.receipt);
608
+ }
609
+ }
610
+ ```
611
+
612
+ A run can also end without settling outputs: cancelled, refused or
613
+ interrupted. `isNikaTerminalEvent(event.raw)` covers those too. It reads the
614
+ status the engine reported (`succeeded`, `failed`, `interrupted`,
615
+ `cancelled`) rather than the kind, so it holds on both transports and on kinds
616
+ this version does not know yet:
617
+
618
+ ```ts
619
+ for await (const event of run.events()) {
620
+ if (isNikaTerminalEvent(event.raw)) {
621
+ console.log('no further frames for this run:', event.raw.status);
622
+ }
623
+ }
624
+ ```
625
+
626
+ `isNikaRunSealedEvent(event.raw)` narrows a `run_sealed` frame when an
627
+ engine streams one.
628
+
629
+ Run, execution and job ids are branded strings (`NikaRunId`,
630
+ `NikaExecutionId`, `NikaJobId`): they are assignable to `string`, but a plain
631
+ `string` does not stand in for one. Four words name three things. A
632
+ **workflow** is the file, or served name, you pass in. A **run** is this
633
+ client's handle on one admission (`run.id`); over HTTP that same string is the
634
+ server's **job** id (`/v1/jobs/{id}`, `attachRun(jobId)`). An **execution** is
635
+ the engine's own id for what actually ran (`execution_id`, the `execution.*`
636
+ kinds), carried by the receipt with the `trace_id`. The
637
+ [glossary](glossary.md) defines the other words.
638
+
639
+ ## Migrating to the Run-owned lifecycle
640
+
641
+ The client-level lifecycle methods are deprecated. They still check
642
+ ownership: a run this client did not create throws `NikaRunOwnershipError`,
643
+ because there is no global run registry.
644
+
645
+ | Deprecated | Use | What changes |
646
+ |---|---|---|
647
+ | `nika.events(run, options?)` | `run.events(options?)` | lifecycle `kind`s; the frame the wrapper yields is now `event.raw` |
648
+ | `nika.cancel(run)` | `run.cancel()` | nothing: the same request |
649
+ | `nika.status(run)` | `run.status()` | nothing |
650
+ | `await run.done` | `await run.result()` | nothing: `done` stays as an alias of the same promise |
651
+
652
+ `nika.events(run)` still yields the engine's frames exactly as before, so
653
+ existing code keeps working while you move:
654
+
655
+ ```ts
656
+ // before
657
+ for await (const e of nika.events(run)) {
658
+ if (e.kind === 'workflow_started' || e.kind === 'execution.started') start();
659
+ }
660
+
661
+ // after
662
+ for await (const e of run.events()) {
663
+ if (e.kind === 'run.started') start();
664
+ }
665
+ ```
666
+
667
+ **How long they stay.** The wrappers shipped unchanged next to the Run-owned
668
+ lifecycle from 0.120.0, the first version published to npm with it, and they
669
+ are still here in 0.124.5. If a later version removes them, its release notes
670
+ say so.