@orkestrel/scaffold 0.0.124 → 0.0.125

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.
Files changed (46) hide show
  1. package/dist/agents/skills/orkestrel-publish/scripts/steps.js +523 -0
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +70 -11
  3. package/dist/bin/main.js +5 -5
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/agents/orchestration.md +5 -1
  6. package/dist/host/agents/platforms/windows.md +9 -1
  7. package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +1 -0
  9. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +30 -2
  10. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
  11. package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
  12. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
  13. package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
  14. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
  15. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
  16. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
  17. package/dist/host/claude/agents/orkestrel.md +21 -21
  18. package/dist/host/claude/rules/patterns.md +1 -1
  19. package/dist/host/claude/rules/portability.md +2 -0
  20. package/dist/host/claude/rules/quality.md +3 -1
  21. package/dist/host/claude/rules/tests.md +3 -1
  22. package/dist/host/guides/agent.md +349 -244
  23. package/dist/host/guides/brief.md +52 -48
  24. package/dist/host/guides/browser.md +2 -2
  25. package/dist/host/guides/interpret.md +531 -155
  26. package/dist/host/guides/mcp.md +183 -61
  27. package/dist/host/guides/ollama.md +123 -66
  28. package/dist/host/guides/program.md +117 -39
  29. package/dist/host/guides/qualifier.md +110 -59
  30. package/dist/host/guides/rater.md +85 -32
  31. package/dist/host/guides/scaffold.md +13 -5
  32. package/dist/host/guides/study.md +580 -483
  33. package/dist/host/guides/toolbox.md +159 -80
  34. package/dist/host/guides/workflow.md +44 -25
  35. package/dist/host/manifest.json +36 -30
  36. package/dist/src/core/index.cjs +4 -4
  37. package/dist/src/core/index.cjs.map +1 -1
  38. package/dist/src/core/index.js +4 -4
  39. package/dist/src/core/index.js.map +1 -1
  40. package/dist/src/server/index.cjs +23 -11
  41. package/dist/src/server/index.cjs.map +1 -1
  42. package/dist/src/server/index.d.cts +10 -6
  43. package/dist/src/server/index.d.ts +10 -6
  44. package/dist/src/server/index.js +23 -11
  45. package/dist/src/server/index.js.map +1 -1
  46. package/package.json +4 -4
@@ -18,6 +18,12 @@ The loop and its tool handlers execute in the host that constructs them. See [Pl
18
18
 
19
19
  ## Surface
20
20
 
21
+ `Conversation.add` stores each tool call with only its `id`, `name`, and `arguments`. It refuses
22
+ non-JSON arguments with `ConversationError` code `'MESSAGE'` before storing any member of a batch.
23
+ Hydration still admits non-JSON call arguments in an in-memory snapshot; a durable snapshot must
24
+ satisfy its JSON contract. A stored noul answer outside `[0, 1]` refuses a database read with
25
+ `ConversationError` code `'SNAPSHOT'`; the row remains available for explicit repair or deletion.
26
+
21
27
  The agent-owned surface: the inference boundary and the HTTP engine behind it, the relay that carries that boundary to a browser, the judge boundary with its HTTP engine and the System One wire, the conversation layer, the context and its managers, the loop, the authority gate, the durable-job bridge, and the ledger that serves a conversation through a judge's filing. Tool and workspace entities belong to their originating packages and are consumed directly — never re-exported here — and one vendor's wire belongs to the concrete provider that extends `AgentProvider`.
22
28
 
23
29
  A provider turns a conversation (plus optional tools) into a turn: `generate` resolves the assembled `ProviderResult` (content + any tool calls + any usage); `stream` yields channel-tagged `ProviderDelta` values as they arrive (`content` for answer text, `thinking` for live reasoning) and returns the same assembled result when the stream completes, so a caller can render tokens / reasoning live and still get the full outcome. Both bound the call with an `AbortSignal`:
@@ -103,17 +109,25 @@ Drive the whole turn with an `Agent` (`createAgent`) — it composes the provide
103
109
 
104
110
  ```ts
105
111
  import type { ProviderInterface } from '@orkestrel/agent'
106
- import { createAgent } from '@orkestrel/agent'
112
+ import { createAgent, createAuthority } from '@orkestrel/agent'
107
113
  import { createTokenBudget } from '@orkestrel/budget'
114
+ import { numberShape, objectShape } from '@orkestrel/contract'
108
115
  import { createTool, createToolManager } from '@orkestrel/tool'
109
116
 
110
117
  declare const provider: ProviderInterface
111
118
  const tools = createToolManager()
112
- tools.add(createTool({ name: 'add', execute: (args) => Number(args.a) + Number(args.b) }))
119
+ tools.add(
120
+ createTool({
121
+ name: 'add',
122
+ contract: objectShape({ a: numberShape(), b: numberShape() }),
123
+ execute: (args) => Number(args.a) + Number(args.b),
124
+ }),
125
+ )
113
126
 
114
127
  const agent = createAgent(provider, {
115
128
  system: 'You are concise.',
116
129
  tools,
130
+ authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }), // tools need an authority
117
131
  limit: 4, // cap tool iterations
118
132
  timeout: 30_000, // wall-clock deadline for the whole turn
119
133
  budget: createTokenBudget({ max: 50_000, scope: 'total' }), // cost ceiling
@@ -132,7 +146,7 @@ const result = await stream.result // { content, usage?, partial } — usage sum
132
146
  Both `generate` and `stream` accept optional per-run `AgentRunOptions` — `think` and `schema` (forwarded to the provider as `ProviderStreamOptions`) plus `limit` / `timeout` / `budget` / `allowance` / `signal`, each overriding its `AgentOptions` construction default for this run only. Omitting one keeps the constructed default, so a caller that passes no options gets the agent it configured. The same options carry `conversation`, which binds the run, and `prompt`, which the run appends as a `user` turn after its guards; a run with no `prompt` reads its request from the conversation's tail. A per-run `signal` composes with (never replaces) a constructed `signal` — either aborting cancels the run; the loop calls `start()` on a per-run `budget` or `allowance` for that run and charges it, leaving a constructed one untouched:
133
147
 
134
148
  ```ts
135
- const agent = createAgent(provider, { tools, limit: 10, timeout: 60_000 }) // construction defaults
149
+ const agent = createAgent(provider, { tools, authority, limit: 10, timeout: 60_000 }) // construction defaults
136
150
  agent.context.messages.add({ role: 'user', content: 'Summarize this doc.' })
137
151
 
138
152
  // A tighter, structured-output run -- overrides limit + timeout, adds a schema, for THIS call only.
@@ -145,23 +159,34 @@ const result = await agent.generate({
145
159
 
146
160
  `schema`, like `think`, rides into `provider.stream` as a `ProviderStreamOptions`: the loop composes both into one options object, omitting whichever key is unset, and passes no options object at all when neither is present — a provider that never received one still never does.
147
161
 
148
- The turn is bounded by one cancel folded from the external `signal` + the `timeout` deadline + the `budget` and `allowance` signals through `AbortSignal.any`; `agent.abort(reason)` (or `stream.abort(reason)`) fires it. A cancel — external, deadline, budget, allowance, or `abort()` — commits a partial result: the `result` promise resolves with `{ partial: true, content: <what accumulated> }`, never rejects (a cancel isn't an error); only a genuine provider / tool error rejects. A genuine provider error after streaming still charges the `budget` the failed call's streamed-answer estimate, once, before the run rejects. The loop yields to an optional `scheduler` between turns; tool iteration is capped at `limit` (default `DEFAULT_AGENT_LIMIT`). Exhausting `limit` while the model still holds unresolved tool intent (it requested tools on the very last allowed turn) is a distinct, non-cancel cause of `partial: true` — it fires an `exhaust` event (the turns reached) instead of `abort`. A natural finish on the last allowed turn, or `limit: 0` (which never enters the loop), stays `partial: false`. `agent.status` transitions `idle` → `running` → `done` / `error`.
162
+ The loop also enforces `schema`: the final answer must parse as JSON and satisfy the schema, read through the lenient `schemaToShape`, which widens every keyword it can't express and never narrows. A miss settles the run `error` with `AgentError` `'SCHEMA'`, whose `context.faults` names what missed, and stores no answer. A `truncated` answer skips the check and keeps its `model` stop. Pass `strict: false` to `createAgent` for a provider that ignores schemas: a miss then emits `fault` with that error and settles with the raw content.
149
163
 
150
- Gate the model's tool calls with an optional `Authority` (`createAuthority`) — a synchronous policy gate the loop consults after scope admits a call, passed through `AgentOptions.authority`. It walks ordered `rules` first-match-wins (a matched rule allows unless its `verdict` is `ask` or `deny`), falling back to a configurable default when none match — allow-unmatched by default (a denylist), or deny-by-default when its `fallback` denies (an allowlist). A denied call is never executed: the loop synthesizes the failure arm of `ToolResult` (`error: '"<name>" did not run: <reason>'`) and feeds it back as a `tool` chunk and a tool message, so no handler runs, no budget is spent, and the model still receives the denial and can request another call. An allowed call dispatches normally. An asked call dispatches only when the authority's `ask` approver resolves `true`; a refusal, a rejection, or no approver denies it. The loop raises an `allow` to an `ask` for a tool whose advertised definition is annotated `consequential`, and with no `authority` set it uses a default `Authority`, so every other scope-admitted call dispatches:
164
+ The turn is bounded by one cancel folded from the external `signal` + the `timeout` deadline + the `budget` and `allowance` signals through `AbortSignal.any`; `agent.abort(reason)` (or `stream.abort(reason)`) fires it. A cancel — external, deadline, budget, allowance, or `abort()` — commits a partial result: the `result` promise resolves with `{ partial: true, content: <what accumulated> }`, never rejects (a cancel isn't an error); only a genuine provider / tool error rejects. A genuine provider error after streaming still charges the `budget` the failed call's streamed-answer estimate, once, before the run rejects. The loop yields to an optional `scheduler` between turns; tool iteration is capped at `limit` (default `DEFAULT_AGENT_LIMIT`). Exhausting `limit` while the model still holds unresolved tool intent (it requested tools on the very last allowed turn) is a distinct, non-cancel cause of `partial: true` — it fires an `exhaust` event (the turns reached) instead of `abort`. A natural finish on the last allowed turn stays `partial: false`. A `limit` that is not a positive safe integer throws `AgentError` coded `'LIMIT'`, `0` included, because a run of no turns answers nothing. `agent.status` transitions `idle` → `running` → `done` / `error`.
165
+
166
+ Gate the model's tool calls with an `Authority` (`createAuthority`) — a synchronous policy gate the loop consults after scope admits a call, passed through `AgentOptions.authority`. An agent built with `tools` and no `authority` throws `AgentError` coded `'AUTHORITY'` at construction, so a host decides what the model may call before the model can call anything. The gate walks ordered `rules` first-match-wins, each naming its `verdict`, and the required `fallback` decides when none match: an `allow` fallback makes a denylist, and a `deny` fallback makes an allowlist. A missing `fallback` or a rule with no `verdict` throws `AgentError` coded `'AUTHORITY'` from `createAuthority`. To allow every call, pass `createAuthority({ fallback: { zone: 'default', verdict: 'allow' } })`. A denied call is never executed: the loop synthesizes the failure arm of `ToolResult` (`error: '"<name>" did not run: <reason>'`) and feeds it back as a `tool` chunk and a tool message, so no handler runs, no budget is spent, and the model still receives the denial and can request another call. An allowed call dispatches normally. An asked call dispatches only when the authority's `ask` approver resolves `true`; a refusal, a rejection, or no approver denies it. The loop raises an `allow` to an `ask` for a tool whose advertised definition is annotated `consequential`. An agent built with no `tools` holds no authority, and it denies a tool a host adds later through `context.tools`:
151
167
 
152
168
  ```ts
153
169
  import { createAgent, createAuthority } from '@orkestrel/agent'
170
+ import { numberShape, objectShape } from '@orkestrel/contract'
154
171
  import { createTool, createToolManager } from '@orkestrel/tool'
155
172
 
156
173
  // `provider`, `drop`, and `confirm` come from the host application.
157
174
  const tools = createToolManager()
158
175
  tools.add([
159
- createTool({ name: 'add', execute: (args) => Number(args.a) + Number(args.b) }),
160
- createTool({ name: 'delete', execute: (args) => drop(args.id) }),
176
+ createTool({
177
+ name: 'add',
178
+ contract: objectShape({ a: numberShape(), b: numberShape() }),
179
+ execute: (args) => Number(args.a) + Number(args.b),
180
+ }),
181
+ createTool({
182
+ name: 'delete',
183
+ contract: objectShape({ id: numberShape() }),
184
+ execute: (args) => drop(args.id),
185
+ }),
161
186
  ])
162
187
 
163
- // A denylist: deny `delete`, allow everything else (the default allow fallback), and answer an
164
- // asked call through the host's `confirm`.
188
+ // A denylist: deny `delete`, allow everything else, and answer an asked call through the host's
189
+ // `confirm`.
165
190
  const authority = createAuthority({
166
191
  rules: [
167
192
  {
@@ -171,6 +196,7 @@ const authority = createAuthority({
171
196
  reason: 'read-only mode',
172
197
  },
173
198
  ],
199
+ fallback: { zone: 'default', verdict: 'allow' },
174
200
  ask: (context) => confirm(`Run ${context.call.name}?`),
175
201
  })
176
202
  const agent = createAgent(provider, { tools, authority })
@@ -191,7 +217,7 @@ import { createAgent, createAuthority } from '@orkestrel/agent'
191
217
  // `provider` comes from the host application.
192
218
  declare const tools: ToolManagerInterface // holds `search` and `delete_order`
193
219
  const authority = createAuthority({
194
- rules: [{ match: (context) => context.call.name === 'search', zone: 'read' }],
220
+ rules: [{ match: (context) => context.call.name === 'search', zone: 'read', verdict: 'allow' }],
195
221
  fallback: { zone: 'blocked', verdict: 'deny', reason: 'that tool is not on the list' },
196
222
  })
197
223
  const agent = createAgent(provider, { tools, authority })
@@ -350,6 +376,8 @@ Register a conversation in a `ConversationManager` and pass that registry throug
350
376
 
351
377
  Pass that registry through `AgentOptions.conversations` together with an `AgentOptions.window` context [`Budget`](budget.md) to enable automatic compaction. Before the first provider request and between turns, the loop measures each request it will send, with its messages after the `replay` policy, its advertised tools, and its per-call `options`, against the window and, when that request reaches the ceiling, compacts the run's conversation, when it is summarizable, before continuing on the rebuilt view. Omit `window` and the loop doesn't auto-compact. See the [Contract](#contract) (the automatic-compaction clause) for the exact trigger and the compaction floor.
352
378
 
379
+ Set the window well under the provider's context size, because `estimateTokens` under-measures and an over-window request refuses. Read on Ollama 0.40.14 with `qwen3.5:2b` on 2026-11-04, real prompt tokens over the estimate ran 1.23 to 1.78: 1.5 for ordinary English with figures, 1.23 for JSON tool arguments, and 1.47 to 1.78 for repeated filler words. A window of half of `num_ctx` covers that range.
380
+
353
381
  ```ts
354
382
  import { createAgent, createConversationManager, estimateRequest } from '@orkestrel/agent'
355
383
  import { createBudget } from '@orkestrel/budget'
@@ -361,7 +389,7 @@ const agent = createAgent(provider, {
361
389
  conversations,
362
390
  // A context Budget: consumer = a token estimator, max = the context window. The loop measures
363
391
  // each request against it. A request that reaches the window folds once and continues on the
364
- // rebuilt (smaller) view; only `strict` refuses a request still over the window.
392
+ // rebuilt (smaller) view; `strict`, the default, refuses a request still over the window.
365
393
  window: createBudget({ max: 8_000, consumer: estimateRequest }),
366
394
  })
367
395
  agent.context.messages.add({ role: 'user', content: 'Hi' })
@@ -424,8 +452,8 @@ Auto-compaction (the `window` budget) is hardened for a long-running app:
424
452
  - **Pre-first-turn + run-entry reset.** The budget check runs before the first provider request and between turns — so a resumed or already-long conversation whose initial prompt already exceeds the window compacts immediately (not only after a tool turn). The `window` budget is reset at run entry, so no stale measurement carries across runs or a conversation switch.
425
453
  - **No fold after a cancel.** When the run's signal has aborted by the time tool dispatch ends, the loop records the tool messages and folds nothing, so a cancel never waits on the summarizer. The next run's pre-first-turn check folds the earlier exchanges, call groups whole.
426
454
  - **What a cancel waits for.** The loop races a scheduler's yield, the approver's answer, and the summarizer against the run signal, so one that ignores its signal still ends on a cancel; a provider stream, a judge, a tool handler, and a selection handler are awaited until they settle, because each can carry usage or finished work, so one that ignores its signal holds the run past a cancel or a timeout, and on a ledger its held scan, until it returns.
427
- - **Observable summarizer failure, non-fatal unless strict.** If the summarizer throws during automatic compaction, the loop emits the error as a `fault` event, so the failure is never silently lost. Without `AgentOptions.strict`, the run doesn't crash: the loop skips compaction that turn and continues, and the over-window prompt proceeds to the provider. With `strict` set, the run settles `error` after the `fault` event (see the `strict` clause under [Contract](#contract)). A manual `conversation.compact()` call you make yourself always propagates its error.
428
- - **Futile-compaction guard.** If `compact()` folds nothing (returns `undefined`) between turns while the prompt is still over the window — that is, the section summaries, the run's request, and the run's own turns, which that fold never takes, already exceed it — the loop stops auto-compacting for the rest of that run (a per-run latch), avoiding per-turn churn. The over-window prompt then proceeds to the provider, and the provider decides what happens past its window. A plain fold takes the live tail and leaves the existing sections; a `sections` cap and `cumulative` fold existing sections too, each on a fold that has an eligible slice, as the `cumulative` folds and compaction floor clauses under [Contract](#contract) state.
455
+ - **Observable summarizer failure, non-fatal unless strict.** If the summarizer throws during automatic compaction, the loop emits the error as a `fault` event, so the failure is never silently lost. With `strict: false`, the run doesn't crash: the loop skips compaction that turn and continues, and the over-window prompt proceeds to the provider. Under `strict`, the default, the run settles `error` after the `fault` event (see the `strict` clause under [Contract](#contract)). A manual `conversation.compact()` call you make yourself always propagates its error.
456
+ - **Futile-compaction guard.** If `compact()` folds nothing (returns `undefined`) between turns while the prompt is still over the window — that is, the section summaries, the run's request, and the run's own turns, which that fold never takes, already exceed it — the loop stops auto-compacting for the rest of that run (a per-run latch), avoiding per-turn churn. Under the default `strict`, the over-window request then throws `AgentError` `'WINDOW'` before it reaches the provider. With `strict: false`, it proceeds to the provider, and the provider decides what happens past its window. A plain fold takes the live tail and leaves the existing sections; a `sections` cap and `cumulative` fold existing sections too, each on a fold that has an eligible slice, as the `cumulative` folds and compaction floor clauses under [Contract](#contract) state.
429
457
 
430
458
  The following listener observes an automatic-compaction summarizer failure:
431
459
 
@@ -443,7 +471,7 @@ A `Scope` (`createScope` / a `ScopeManager`) is a named allow-list filter the co
443
471
  ```ts
444
472
  import { createAgent, createScope } from '@orkestrel/agent'
445
473
 
446
- const agent = createAgent(provider, { tools }) // tools holds `search` + `delete`
474
+ const agent = createAgent(provider, { tools, authority }) // tools holds `search` + `delete`
447
475
  agent.context.instructions.add([
448
476
  { name: 'safety', content: 'Refuse unsafe requests.' },
449
477
  { name: 'verbose', content: 'Explain every step.' },
@@ -463,7 +491,7 @@ A scoped-out tool is neither described nor callable. The loop snapshots the scop
463
491
 
464
492
  A scope change through the `context.apply` method applies at each later site that reads the scope. The tool half applies at the next turn's snapshot: a `tool` or `usage` listener changes the next turn's advertising, and a `turn` listener reaches the same turn, because `turn` fires before the snapshot. The prompt half (instructions, skills, memos, files, and `select`) applies at the next build or select site: run entry, the pre-first-turn compaction fold, or a compaction rebuild.
465
493
 
466
- When no tool is advertised, including an empty registry, the provider's `content` field ends the run as the answer with a `partial: false` result. The assistant message is recorded without calls. Each dropped call emits a `deny` event with the `no tool is advertised in the active scope` reason, without a tool result or tool message.
494
+ When no tool is advertised, including an empty registry, a reply with no calls ends the run as the answer, and a call the reply still carries is denied like any other scoped-out call: it emits a `deny` event with the `<tool name> is not in the active scope` reason, gets a denial tool result and tool message, and the loop runs another turn, up to `limit`, so a call is never read as a final answer.
467
495
 
468
496
  When at least one tool is advertised, a call excluded by the tool allow-list or naming no advertised tool emits a `deny` event with the `TOOL is not in the active scope` reason, where the `TOOL` placeholder is the requested name. Its denial `ToolResult` value carries the `"TOOL" did not run: it is not one of the listed tools. Use a listed tool or answer with what you have.` error and is fed back as a tool message. Admitted calls pass through authority and dispatch normally. The loop continues with results in the reply's call order, including when calls share an ID.
469
497
 
@@ -515,7 +543,7 @@ const request = plain.context.messages.add({ role: 'user', content: 'Invoice 42.
515
543
  plain.context.select(plain.context.messages, request, new AbortController().signal) // undefined — no handler in either home
516
544
  ```
517
545
 
518
- A selection fails four ways. A handler throw emits `fault`, and the loop builds from `view()` with no `select` event. A returned `fault` charges its usage first, then emits `fault`, and the loop builds from the returned `messages` and emits `select`. A conversation changed under the handler is a fault as well: `context.select` returns the current `view()` with a `fault` that names the change. A `system` message in a handler's selection is a fault over `view()` carrying `ConversationError` `'ROLE'`. With `AgentOptions.strict` set, all four settle the run `error`. A cancel at a select site wins over all of them, and the run commits partial with no provider call.
546
+ A selection fails four ways. A handler throw emits `fault`, and the loop builds from `view()` with no `select` event. A returned `fault` charges its usage first, then emits `fault`, and the loop builds from the returned `messages` and emits `select`. A conversation changed under the handler is a fault as well: `context.select` returns the current `view()` with a `fault` that names the change. A `system` message in a handler's selection is a fault over `view()` carrying `ConversationError` `'ROLE'`. Under `AgentOptions.strict`, the default, all four settle the run `error`; with `strict: false`, the run continues. A cancel at a select site wins over all of them, and the run commits partial with no provider call.
519
547
 
520
548
  Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`. No `usage` chunk or `usage` event carries it, so that chunk keeps its one-provider-call meaning.
521
549
 
@@ -573,13 +601,13 @@ Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https
573
601
 
574
602
  ### Serving a conversation through a ledger
575
603
 
576
- A ledger serves one conversation as event-sourced records with one record per owner. The `createLedger(provider, options)` factory returns a `LedgerInterface` value that owns the conversation, the agent that answers it, and that agent's tools, and its `respond` method appends a request as a user message and serves it through to the reply. The conversation is the event log. Each request reads the system message, which holds the `system` option and whatever instructions and skills the `agent` option supplies, then the context message when the `agent` option supplies memos or an active workspace, then a tail of the seed history (the messages added before the first request), then a copy of the request turn: the records the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. An earlier request and its reply don't re-enter a planned prompt; what its lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the agent builds the prompt from the whole conversation view instead, earlier requests and replies included, with no records.
604
+ A ledger serves one conversation as event-sourced records with one record per owner. The `createLedger(provider, options)` factory returns a `LedgerInterface` value that owns the conversation, the agent that answers it, and that agent's tools, and its `respond` method appends a request as a user message and serves it through to the reply. The conversation is the event log. Each request reads the system message, which holds the `system` option and whatever instructions and skills the `agent` option supplies, then the context message when the `agent` option supplies memos or an active workspace, then a tail of the seed history (the messages added before the first request), then a copy of the request turn: the records the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. An earlier request and its reply don't re-enter a planned prompt; what its lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the run rejects under the default `strict`, and under `strict: false` the agent builds the prompt from the whole conversation view instead, earlier requests and replies included, with no records.
577
605
 
578
- Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. An active `respond` call owns a run on that conversation whose request, the newest message, is that call's request or one of the ledger's notes. A run that no active `respond` call owns, such as a direct call to the agent's `generate` method or a run on another conversation, gets a faulted selection when its newest message is a user message: the selection's `fault` is a `LedgerError` with code `'REQUEST'`, so the agent emits `fault` and builds the prompt from the whole view of the run's conversation with no records, and the ledger asks its judge nothing for that run. When its newest message isn't a user message, the run gets no selection and builds from the whole view. Calibration admits no run, so a run during the `calibrate` method, or during the calibration that opens a `respond` call, is one that no active `respond` call owns.
606
+ Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. An active `respond` call owns a run on that conversation whose request, the newest message, is that call's request or one of the ledger's notes. A run that no active `respond` call owns, such as a direct call to the agent's `generate` method or a run on another conversation, gets a faulted selection when its newest message is a user message: the selection's `fault` is a `LedgerError` with code `'REQUEST'`, so under the default `strict` the run rejects with that error before it reaches the provider, and under `strict: false` the agent emits `fault` and builds the prompt from the whole view of the run's conversation with no records. Either way the ledger asks its judge nothing for that run. When its newest message isn't a user message, the run gets no selection and builds from the whole view. Calibration admits no run, so a run during the `calibrate` method, or during the calibration that opens a `respond` call, is one that no active `respond` call owns.
579
607
 
580
608
  The method has the following pieces, each named by its export:
581
609
 
582
- - **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. The `narrow` member of the `correction` option keeps only the eligible earlier messages that also share a registry entity with the correction or an id or a number in their content, so a desk topic alone admits no pair, and a correction with no id, owner, or desk topic still asks no pair. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, `narrow` took 24 judge calls and 45 s against 68 and 136 s at a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059), and 26 judge calls and 45 s against 109 and 196 s at a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883). Those calls include the category and topic questions `narrow` leaves in place. Filings were equal at those two corrections, on 5 pairs and 1 supersession. A third correction, forecast from recorded answers and not run, lost 0 of 8 pairs. The 173 pairs `narrow` drops across the three, 196 questions, filed 0 on recorded answers, on text whose corrections repeat a literal by construction, and the registry-entity path admitted no pair on this recording. A true supersession outside that set is never asked, and no run on any model measures how often one occurs. Set `narrow` when a correction's wait costs more than a missed supersession and your corrections repeat the id, number, or looked-up entity they correct. Leave it off for a host with no lookups or with free-text values. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. A judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value reads the filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `ClassifierAttempt` value per logical filing question it attempted, in asking order, and observes the filing without changing it. An attempt names the question's key and its `ClassifierPhase` value, and its `ClassifierOutcome` value says whether the conversation already held the judgment (`cached`), the classifier held the question after a deterministic failure or because a message it names left the conversation (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal (`failed`), or was cut short by an abort (`aborted`). A `resolved`, `failed`, or `aborted` attempt carries the monotonic milliseconds the classifier waited on that call as `duration`, and a `cached` or `skipped` attempt carries none. A question that a caller abort preceded has no attempt, because it never began. The attempts count logical questions and resolve requests, never the physical wire calls a judge makes for them, and they record no join of pending requests. The `attempts` member of the `LedgerResult` value holds the attempts of the filing selections of that `respond` call alone; the `Selection` values the ledger emits carry none. A page passes `agent: { scheduler: createBrowserScheduler() }` from `@orkestrel/workflow/browser`, so the classifier hands the host a turn each time the `LEDGER_SLICE` constant's milliseconds have run while it files, and the plan after the filing still runs as one task; a page that omits the option also runs each stretch of cached filing as one task, and the host gets a turn only while the classifier waits on the judge. A direct `agent.context.select` for the same request during a paced filing's yield rejects with `AgentError` `'CONCURRENCY'`, and one for a message the call does not own returns a selection whose `fault` is `LedgerError` `'REQUEST'`. A `classify` call reads each message's quiet flag and near set at most once while it pairs corrections, so a judgment or message written during a pair-phase await reads at the next `classify` call, and `LedgerLookup.read` runs one time per tool message for each plan, each `recall` call, and each filing pass. The **What a cancel waits for.** bullet under [Production behaviors of automatic compaction](#production-behaviors-of-automatic-compaction) applies to this filing: what it names holds the run, and on a ledger its held scan, until it returns.
610
+ - **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. The `narrow` member of the `correction` option keeps only the eligible earlier messages that also share a registry entity with the correction or an id or a number in their content, so a desk topic alone admits no pair, and a correction with no id, owner, or desk topic still asks no pair. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, `narrow` took 24 judge calls and 45 s against 68 and 136 s at a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059), and 26 judge calls and 45 s against 109 and 196 s at a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883). Those calls include the category and topic questions `narrow` leaves in place. Filings were equal at those two corrections, on 5 pairs and 1 supersession. A third correction, forecast from recorded answers and not run, lost 0 of 8 pairs. The 173 pairs `narrow` drops across the three, 196 questions, filed 0 on recorded answers, on text whose corrections repeat a literal by construction, and the registry-entity path admitted no pair on this recording. A true supersession outside that set is never asked, and no run on any model measures how often one occurs. Set `narrow` when a correction's wait costs more than a missed supersession and your corrections repeat the id, number, or looked-up entity they correct. Leave it off for a host with no lookups or with free-text values. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. Under the default `strict`, a judge failure rejects the `respond` call it belongs to, after the `fault` event, and holds nothing, so the next request asks the judge again about every question still unanswered. A failure that repeats rejects that request too, so a question the judge always refuses stops each request until you remove its message or set `strict: false`. Under `strict: false`, a judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value reads the filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `ClassifierAttempt` value per logical filing question it attempted, in asking order, and observes the filing without changing it. An attempt names the question's key and its `ClassifierPhase` value, and its `ClassifierOutcome` value says whether the conversation already held the judgment (`cached`), the classifier held the question after a deterministic failure or because a message it names left the conversation (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal (`failed`), or was cut short by an abort (`aborted`). A `resolved`, `failed`, or `aborted` attempt carries the monotonic milliseconds the classifier waited on that call as `duration`, and a `cached` or `skipped` attempt carries none. A question that a caller abort preceded has no attempt, because it never began. The attempts count logical questions and resolve requests, never the physical wire calls a judge makes for them, and they record no join of pending requests. The `attempts` member of the `LedgerResult` value holds the attempts of the filing selections of that `respond` call alone; the `Selection` values the ledger emits carry none. A page passes `agent: { scheduler: createBrowserScheduler() }` from `@orkestrel/workflow/browser`, so the classifier hands the host a turn each time the `LEDGER_SLICE` constant's milliseconds have run while it files, and the plan after the filing still runs as one task; a page that omits the option also runs each stretch of cached filing as one task, and the host gets a turn only while the classifier waits on the judge. A direct `agent.context.select` for the same request during a paced filing's yield rejects with `AgentError` `'CONCURRENCY'`, and one for a message the call does not own returns a selection whose `fault` is `LedgerError` `'REQUEST'`. A `classify` call reads each message's quiet flag and near set at most once while it pairs corrections, so a judgment or message written during a pair-phase await reads at the next `classify` call, and `LedgerLookup.read` runs one time per tool message for each plan, each `recall` call, and each filing pass. The **What a cancel waits for.** bullet under [Production behaviors of automatic compaction](#production-behaviors-of-automatic-compaction) applies to this filing: what it names holds the run, and on a ledger its held scan, until it returns.
583
611
  - **The records.** The `buildRecords` helper projects the filing into one `LedgerRecord` value per owner a lookup result names, plus one rules record for the rules and corrections no owner claims. Each line is a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. A message filed quiet or superseded isn't live. Accepted message-level amendments preserve every original indexed sentence of live earlier sources; the projection lists distinct direct edges in its `amendments` member. Sentence scope remains unresolved. The `recall` tool and the answer note keep the stored content of each message they carry. The seed tail keeps stored content except for lookup results, which the plan replaces with stubs.
584
612
  - **Amendment scope.** The first retained occurrence of an amended source opens with its `[N]` reference and a note on its later changes. Distinct retained sources receive decimal references starting at 1 in first-occurrence emission order, after deduplication. References are local to one rendering of the records and are recomputed after each trim; omitted sources do not shift them. Repeated occurrences share one reference. Recall and storage retain original source IDs. Authored content is unchanged. A fully included later source opens with its own [M] reference, and the earlier source's note reads “Changed later by [M].” If any effective correction is absent, partial, or superseded, the note reads “A later change is not shown.” The omission note exposes no omitted identity, text, owner, or count. Completeness uses every original sentence identity after source deduplication and each trim; annotations count against the existing room. Effective superseded amenders retain provenance without restoring their text. No transitive amendment edge is inferred. Earlier text can conflict with its correction; downstream correction application and semantic sentence withdrawal remain unproved.
585
613
  - **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the built head (the system message and the context message), the tail, and the copy of the request turn that carries the records inside a token budget: the `capacity` option less the `predict` option, times the `prompt` share, less the overhead cost of the gauge and held back by the `LEDGER_SCALE_DRIFT` constant, of which the tail takes at most the `tail` share. Owner records with the same member ids in the same order render once, under their titles joined with `; `; before trimming, the view keeps the first requested record's key, members, and lines. The projection, held sources, and recall stay unchanged. The budget bounds only the records and the tail of a request's first call: the plan prices the built head, the tail, and the copy of the request turn with the records and images it carries. The request, each lookup result, the pass's own assistant turns with their calls and replayed thinking, the answer note and the `cue` note, and the whole view a faulted selection builds from enter the prompt unbounded, so any of them can carry a prompt past the budget. The plan prices each lookup stub in the tail at the longer of its `shown` and `hidden` forms, so a tail that fits the plan still fits after the records decide which results they show. The `share` option sets both shares, and the `DEFAULT_LEDGER_SHARE` constant holds the defaults. Until the records fit, the ledger drops the rules off the request's topics, then the sources outside the selected records, then the rules on its topics, then the owner lines. Inside an owner record, it drops the lines whose source isn't a rule or a correction first, oldest first, then the lines of rules and corrections, oldest first. The `Gauge` class prices the prompt; without the `gauge` option, the ledger calibrates before its first pass, and the `calibrate` method measures the price on demand. A lookup in the tail reaches the model as the stub the `renderStub` helper writes, which says whether the records show its result. The plan reaches the agent as a `Selection` value whose `messages` member is the tail, then the copy of the request turn that the `buildRequestMessage` helper writes: the records, a blank line, a `## Request` heading, and the request. When no records render, the copy is the request itself. The answer pass carries the same copy, and the stored request keeps its own content.
@@ -622,20 +650,21 @@ The method has the following documented limits:
622
650
  - **The person prefix trusts capital letters.** A sentence that opens with a pronoun takes the last capitalized name of the sentence before it as its party, so a capitalized word that names no person, such as a carrier named mid-sentence, is read as the party.
623
651
  - **A desk-wide correction stays in one owner's record.** A message that names an owner joins that owner's record and not the rules record, so a correction to a desk-wide rule stated inside one owner's message isn't among the rules a request about another owner reads.
624
652
  - **Recall identity is the topic alone.** The repeat stop compares two `recall` calls by their trimmed `topic` argument, so a second call with the same topic is a repeat whatever other arguments it carries.
625
- - **A direct run beside a request is refused or unowned.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`; during the calibration that opens the call it is a run no active `respond` call owns. A run on another conversation started during a `respond` call gets no ledger selection, yet adds its turns and usage to that call's gauge readings and shares its repeat stop. A run on another conversation can still reach the `recall` and lookup tools, which the ledger's agent advertises to every run and which read the ledger's `conversation`.
653
+ - **A change during a selection rejects the request.** A selection reads the conversation it was asked about, so a host append or removal while a `respond` call's selection runs faults it with a `changed during selection` error. Under the default `strict`, `respond` rejects with that error before it reaches the provider, and the ledger stays free for a later call. Under `strict: false`, the agent emits `fault` and builds the prompt from the whole view.
654
+ - **A direct run beside a request is refused.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`. Under the default `strict`, any other run no active `respond` call owns whose newest message is a user message rejects with `LedgerError` `'REQUEST'` before it reaches the provider: a direct run between requests, one during the calibration that opens a call, and a run on another conversation during a call. Under `strict: false` that run emits `fault` and goes on over the whole view with no ledger selection; a run on another conversation then adds its turns and usage to that call's gauge readings, shares its repeat stop, and can reach the `recall` and lookup tools, which the ledger's agent advertises to every run and which read the ledger's `conversation`.
626
655
  - **A run no call owns keeps no request state.** The ledger holds a request's state in a `LedgerRequest` value from the start of its `respond` call until the call settles. A run that no `respond` call owns, including a run during calibration, reads no request's state: its lookup and `recall` calls run with no repeat stop, recall limit, or close rule, and none of its turns reach a gauge reading.
627
656
  - **A seed tool message counts as successful.** A tool message the application adds to the conversation has no recorded result, so the ledger reads it as a successful lookup and files it as a fact, and its reading handler decides what the result names.
628
657
  - **An abort during calibration rejects.** When the caller's signal aborts while the ledger calibrates, the `respond` method rejects with the abort reason instead of resolving a partial result; after calibration, an abort ends the request partial and skips the answer pass.
629
658
  - **A foreign signal rejects before anything is appended.** A `signal` that isn't a native `AbortSignal` rejects the `respond` method with a `ContractError` before the request is appended, and the ledger stays free for a later request.
630
659
  - **Only the seed forms the tail.** Only the messages added before the first request form the seed tail, so an application message added after the first request reaches a planned prompt only through the records or the `recall` tool.
631
660
  - **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup replaces it, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows.
632
- - **The ledger refuses no over-window prompt.** A request, a lookup result, the pass's own turns, the answer note, or the whole view a faulted selection builds from reaches the provider whole when it's larger than the room the `capacity` option leaves, and the provider's own context limit decides what happens to it.
661
+ - **The ledger refuses no over-window prompt.** A request, a lookup result, the pass's own turns, the answer note, or the whole view a faulted selection builds from reaches the provider whole when it's larger than the room the `capacity` option leaves, and the provider's own context limit decides what happens to it. A provider that refuses an over-long prompt fails the pass, so lower `capacity`, or set `AgentOptions.window` on an agent you drive yourself, to fold the conversation first.
633
662
  - **A memo written between passes enters unpriced.** A memo written during a request's first pass, by a lookup or a host tool, enters the answer pass's context message unpriced: the plan prices the head the first pass sends, and the answer pass rebuilds the context message from the managers as they read then, so the system, tail, and request positions stay byte-identical and the context message can change.
634
663
  - **A heading inside a record line reads as one.** A record line and the request copy render a message's or a lookup's text verbatim, so text holding a `## Rules` or `## Request` heading reads as one inside the user turn's copy; it changes no filing and never reaches `system`, and no delimiter marks such text.
635
- - **A lookup is a read.** A ledger lookup is a read; a tool whose call has a consequence is not a lookup, and a ledger refuses a `consequential` lookup at every call. `LedgerAgentOptions` carries no `authority`, so such a lookup meets the default `Authority` floor with no approver and is denied as unanswered.
664
+ - **A lookup is a read.** A ledger lookup is a read; a tool whose call has a consequence is not a lookup, and a ledger refuses a `consequential` lookup at every call. `LedgerAgentOptions` carries no `authority`: the ledger passes its own, which allows the names it advertises (`recall` and each lookup) and denies every other name, so a `consequential` lookup meets the floor with no approver and is denied as unanswered, and a tool a host adds later reads `the ledger advertises no such tool`.
636
665
  - **A snapshot's judgments are frozen records.** `LedgerInterface.snapshot().conversation` carries the stored deep-frozen judgments, so a write to one throws `TypeError` in strict-mode code, and a host copies a record through `copyJSON` before it migrates or redacts it.
637
666
  - **A snapshot carries no gauge observations.** The `gauge` member of a snapshot holds the scale and the overhead cost alone. A hydrated ledger has observed no reply and no earlier request, so until it completes a request of its own, the `recall` tool sizes its room and applies its close rule as a ledger that has served nothing does, and a `recall` call can list a different number of items than the same call on the ledger that took the snapshot.
638
- - **A hydrated ledger asks a held question again.** A snapshot doesn't carry the questions the classifier held after a refused question or a deterministic judge failure, so a ledger hydrated from it asks each of them again in its next request.
667
+ - **A hydrated ledger asks a held question again.** A snapshot doesn't carry the questions a `strict: false` classifier held after a refused question or a deterministic judge failure, so a ledger hydrated from it asks each of them again in its next request.
639
668
  - **A snapshot survives a store that sorts keys.** A judgment matches by JSON value, so a `DatabaseConversationStore` column that returns keys in another order, a binary JSON column included, keeps every memoized judgment. A structured `state` compares by its JSON text, key order included, so pass the same key order on each resolve or render it to a string first. A restored answer keeps the probability order its store returned, so `measureAnswer` can name another winner on an exact tie; the `category` method of the `Classifier` class walks `LEDGER_CATEGORIES`, so a ledger's filing doesn't depend on that order. A restored lookup call's arguments render in the order the column returns them, so a records line, an item the `recall` tool lists, a lookup stub in the tail, and the provider request can differ in bytes from the ones the original run sent, and a stub's `hidden` form can tell the model to recall with another string argument, because it names the first string in that order. A restored message object keeps the member order its column returned, so a provider whose encode passes `request.messages` through by spread sends those members in that order; the relay projection and the judge requests fix their member order. `matchesJSON` is bounded to JSON data and promises nothing for a cycle, a `toJSON` object, `NaN`, an infinity, or an `undefined`, function, symbol, or hole inside a list.
640
669
  - **The `narrow` member can hide a supersession.** The ledger never compares an earlier message that shares only a desk topic with the correction, so a supersession on a pair sharing no registry entity and no id or number is never filed. For example, "the refund limit is 500" then "no, the refund limit is 600" shares no literal, so with no shared registry entity `narrow` never asks about that pair, where the unset rule does.
641
670
  - **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction of the recording under **The filing.**, one correction asked 98 pair questions over 93 earlier messages, inside 109 judge calls and 196 s on the Mica v0.1 4B judge. The `narrow` member lowers them, and the caller's abort signal ends them.
@@ -681,7 +710,7 @@ When a provider's model has a framing preference, such as XML tags, install that
681
710
 
682
711
  A provider decides how message text reaches its model. Agent neutralizes no model control token in any message, so a provider that renders messages into one prompt owes that escape, and a host that loads text into `system` must author that text. The `@orkestrel/ollama` provider through 0.0.28 escapes none, so a listed token inside any message reaches Ollama's renderer as the real token. From 0.0.29 it escapes a listed token in message content, a replayed call's name, and each top-level argument key and string value, and `guides/ollama.md` states that reach and its limits.
683
712
 
684
- `ProviderInterface` is the boundary; `AgentProvider` is the engine behind it. Every HTTP-backed provider needs the same machinery — a deadline, a transport, an authorization hook, a bounded error read, a chunk decoder, reasoning separation, and result assembly — and rewriting that per vendor is how a fleet of providers drifts apart. `AgentProvider` owns all of it and leaves exactly one thing open: the wire. A subclass supplies `name` and the wire seams — `frame()` returns fresh framing state for the call, `encode(request)` projects a `ProviderRequest` onto the vendor's request shape, `read(record)` decodes one framed record into a `ProviderIncrement`, and `finish(parser)` returns whatever the parser still held at end of input. The engine is generic over `TRecord`: the record type a call's `frame()` parser emits and `read` consumes, defaulting to `Readonly<Record<string, unknown>>` for a wire whose records are JSON objects. The constructor switches decide the rest: `split` separates in-content `<think>` reasoning from the answer (default `true`), and `strict` requires the wire to carry a settled `result` record rather than assembling one at end of input (default `false`).
713
+ `ProviderInterface` is the boundary; `AgentProvider` is the engine behind it. Every HTTP-backed provider needs the same machinery — a deadline, a transport, an authorization hook, a bounded error read, a chunk decoder, reasoning separation, and result assembly — and rewriting that per vendor is how a fleet of providers drifts apart. `AgentProvider` owns all of it and leaves exactly one thing open: the wire. A subclass supplies `name` and the wire seams — `frame()` returns fresh framing state for the call, `encode(request)` projects a `ProviderRequest` onto the vendor's request shape, `read(record)` decodes one framed record into a `ProviderIncrement`, and `finish(parser)` returns whatever the parser still held at end of input. The engine is generic over `TRecord`: the record type a call's `frame()` parser emits and `read` consumes, defaulting to `Readonly<Record<string, unknown>>` for a wire whose records are JSON objects. The constructor switches decide the rest: `split` separates in-content `<think>` reasoning from the answer (default `true`), and `strict` refuses a stream that ends with neither a settled `result` nor a `done` record, because it was cut (default `true`); a wire with no terminal record passes `strict: false` to assemble at end of input.
685
714
 
686
715
  ```ts
687
716
  import type { AgentProviderInput, ProviderInterface } from '@orkestrel/agent'
@@ -698,7 +727,7 @@ const provider = createTextProvider({
698
727
  timeout: 30_000, // the base's own deadline; DEFAULT_PROVIDER_TIMEOUT when omitted
699
728
  headers: async (signal) => ({ authorization: await token(signal) }), // awaited inside that deadline
700
729
  split: true, // route <think> spans to `thinking`, yield the clean answer
701
- strict: false, // assemble at end of input instead of requiring a settled record
730
+ strict: false, // this wire has no terminal record: assemble at end of input instead of refusing
702
731
  })
703
732
  const result = await provider.generate(messages, abort.signal)
704
733
  result.content // the assembled answer, with any <think> span routed to result.thinking
@@ -709,7 +738,7 @@ result.content // the assembled answer, with any <think> span routed to result.t
709
738
  The engine's failures arrive as one error class. A `ProviderError` carries a machine-readable `code` and, for an HTTP failure alone, the response `status`; `isProviderError` narrows a caught value so a caller can branch on the code:
710
739
 
711
740
  - `'HTTP'` — a non-OK response. The message is `provider error: <status>`, with ` - <excerpt>` appended only when the response body carried text. The excerpt is read to at most `MAX_ERROR_BODY_LENGTH` bytes and the remainder of the body is cancelled, so a stalled error body can't hold the call open past its deadline.
712
- - `'PROTOCOL'` — a successful response with no body, a line the provider's framing refuses, a wire record the concrete provider refuses, or a `strict` stream that ended without a settled result. A throw from a provider's framing seam (its parser's `parse` or the provider's `finish`) that races no cancel and is not already a `ProviderError` or `ProviderAbortError` rejects with this code and carries that throw as its `cause`.
741
+ - `'PROTOCOL'` — a successful response with no body, a line the provider's framing refuses, a wire record the concrete provider refuses, a stream that ended with no settled result and no terminal record, or a result or delta that breaks the published contract at the agent's door. A throw from a provider's framing seam (its parser's `parse` or the provider's `finish`) that races no cancel and is not already a `ProviderError` or `ProviderAbortError` rejects with this code and carries that throw as its `cause`.
713
742
  - `'PROVIDER'` — an upstream failure a relay reported in an `error` frame.
714
743
 
715
744
  A cancel isn't in that taxonomy: the call's own deadline and the caller's signal are folded into one bound, and a cancel throws `ProviderAbortError` carrying the partial assembled so far.
@@ -763,7 +792,7 @@ turn.filter((message) => 'thinking' in message).map(({ id }) => id) // ['4'] —
763
792
 
764
793
  ### The judge engine
765
794
 
766
- The `JudgeInterface` contract is the decision boundary beside `ProviderInterface`, and it is never a provider. Its `ask(request, signal)` method answers typed questions about one state with a probability distribution per question. A `JudgeRequest` carries the `state` and the `questions` keyed by your own ids, which the prompt never carries; each question is a `ChoiceQuestion`, a `ScoreQuestion`, or a `NoulQuestion`, named by its `form` member. A `JudgeResult` carries the answering model in its `model` member, the `answers` map keyed by the same ids, the `refusals` map of the questions a wire refused, and the `usage` member with the tokens the calls spent. An answer stores only the distribution the server returned: `probabilities` for a choice or a score, and `noul`, the probability of yes, for a noul question. The `measureAnswer` function derives every measure from that distribution, so every server reads on one scale and no stored measure can drift from its distribution (the derived-measure clause).
795
+ The `JudgeInterface` contract is the decision boundary beside `ProviderInterface`, and it is never a provider. Its `ask(request, signal)` method answers typed questions about one state with a probability distribution per question. A `JudgeRequest` carries the `state` and the `questions` keyed by your own ids, which the prompt never carries; each question is a `ChoiceQuestion`, a `ScoreQuestion`, or a `NoulQuestion`, named by its `form` member. A `JudgeResult` carries the answering model in its `model` member, the `answers` map keyed by the same ids, the `refusals` map of the questions a wire refused, and the `usage` member with the tokens the calls spent; a call whose response reports no complete usage bills the estimate of its response text, as a provider call does. An answer stores only the distribution the server returned: `probabilities` for a choice or a score, and `noul`, the probability of yes, for a noul question. A choice answer names every criterion of its question, a score is as long as its levels, and each probability is in `[0, 1]`: `AgentJudge` refuses any other answer with `JudgeError` `'PROTOCOL'`, and a judgment write with `ConversationError` `'JUDGMENT'`. The `measureAnswer` function derives every measure from that distribution, so every server reads on one scale and no stored measure can drift from its distribution (the derived-measure clause).
767
796
 
768
797
  The `AgentJudge` class is the engine behind that boundary, as the `AgentProvider` class is the engine behind `ProviderInterface`. It owns each call's deadline, the transport, the `headers` hook, the validation before inference, the bounded error read, and the merge of every call's result, and it leaves the wire open: a subclass supplies `name`, `encode(request)`, which projects one call's `JudgeRequest` onto the protocol's request shape, and `read(value, request)`, which decodes one call's parsed response into a `JudgeResult`. A one-shot JSON response has no framing state and no buffered tail, so the engine has no `frame` or `finish` seam. In place of the `split` and `strict` switches it takes one `batch` switch: `true`, the default, sends every question in one call, and `false` sends one call per question in key order.
769
798
 
@@ -867,12 +896,19 @@ The following table lists the errors the root declares and the guards that narro
867
896
 
868
897
  The following table lists the root wire shapes and the contract compiled from them:
869
898
 
870
- | Name | Kind | Signature | Summary |
871
- | ----------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
872
- | `toolCallShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>` | Describes a tool call's JSON wire projection. |
873
- | `messageShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a conversation message's JSON wire projection. |
874
- | `tokenUsageShape` | const | `import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>` | Describes a token usage record's JSON wire projection — its `prompt`, `completion`, and `total` counts, shared by the provider result and the agent frame wires. |
875
- | `messageContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>>` | Validates and projects conversation messages at a JSON wire boundary. |
899
+ | Name | Kind | Signature | Summary |
900
+ | ----------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
901
+ | `toolCallShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>` | Describes a tool call's JSON wire projection. |
902
+ | `messageShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a conversation message's JSON wire projection. |
903
+ | `messageInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a message input's JSON projection: a `messageShape` with no `id`, which the storing conversation mints. |
904
+ | `judgeEntryShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>` | Describes the text or JSON a judge reads: a non-empty string, a non-empty JSON array, or a JSON record. |
905
+ | `judgeQuestionShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>` | Describes a judge question: one exact object per form, the schema an LLM-facing wire can publish. |
906
+ | `judgeAnswerShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>` | Describes a judge answer: one exact object per form, each probability in `[0, 1]`. |
907
+ | `tokenUsageShape` | const | `import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>` | Describes a token usage record's JSON wire projection — its `prompt`, `completion`, and `total` counts, shared by the provider result and the agent frame wires. |
908
+ | `messageContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>>` | Validates and projects conversation messages at a JSON wire boundary. |
909
+ | `messageInputContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>>` | Reads the faults of a refused message input and validates a job's seed messages. |
910
+ | `judgeQuestionContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>>` | Reads the faults of a refused judge question. |
911
+ | `judgeAnswerContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>>` | Reads the faults of a refused judge answer. |
876
912
 
877
913
  #### Cloners
878
914
 
@@ -887,32 +923,37 @@ The following table lists the cloners the root declares:
887
923
 
888
924
  The following table lists the helpers the root declares:
889
925
 
890
- | Name | Kind | Signature | Summary |
891
- | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
892
- | `filterAllowList` | function | `<T>(allow: readonly string[] \| undefined, members: readonly T[], key: (member: T) => string) => readonly T[]` | Filters a list of members by a `ScopeInterface` allow-list of keys — `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys alone, order preserved. The pure, total set-membership primitive the context's build step and the agent loop's tool-advertise step apply a scope through. |
893
- | `sanitizeToken` | function | `(value: number) => number` | Sanitizes one reported token count into a non-negative integer — a non-finite or non-positive value becomes `0`, and a positive fractional value floors down. |
894
- | `sanitizeUsage` | function | `(usage: TokenUsage) => TokenUsage` | Sanitizes a `TokenUsage` into non-negative integers — the guard an agent's abort-usage path applies to a provider's partial usage before it is charged against a budget or folded into the run total. |
895
- | `joinThinking` | function | `(prior: string \| undefined, next: string) => string` | Joins the reasoning a run's provider calls separated from the answer — the first call seeds the accumulation, a later call appends blank-line separated so each turn's reasoning stays readable. |
896
- | `stripThinking` | function | `(messages: readonly Message[], replay: ThinkingReplay) => readonly Message[]` | Applies a `ThinkingReplay` policy to a conversation, returning the messages a provider sends with only the assistant thinking the policy allows. |
897
- | `sumUsage` | function | `(prior: TokenUsage \| undefined, next: TokenUsage) => TokenUsage` | Adds two `TokenUsage` values field by field — the running total an agent run keeps across its provider calls. |
898
- | `removeEntries` | function | `<K>(keys: readonly K[], remove: (key: K) => boolean) => boolean` | Removes each key through a single-key remover and folds the outcomes, so a batch `remove` reports whether the whole batch applied. |
899
- | `collectExchanges` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects whole exchanges, joining every exchange spanned by a tool group. |
900
- | `collectToolGroups` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects each assistant message that carries calls together with the tool messages that answer it, then each run of tool messages that no assistant message owns. |
901
- | `hasCalls` | function | `(message: Pick<Message, 'calls'>) => boolean` | Checks whether a message carries at least one tool call. |
902
- | `renderJSON` | function | `(value: unknown) => string \| undefined` | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
903
- | `matchesJSON` | function | `(left: unknown, right: unknown) => boolean` | Matches two values of JSON data by JSON value, whatever their key order, and reads a value with no JSON text as no match. |
904
- | `matchesJudgment` | function | `(judgment: Judgment, question: JudgeQuestion, sources: readonly string[], state: string, model: string) => boolean` | Matches a recorded question by JSON value, the ordered sources, the rendered state, and the judge identity. |
905
- | `extractLiterals` | function | `(text: string) => LiteralSet` | Reads the ids and the numbers of a text. |
926
+ | Name | Kind | Signature | Summary |
927
+ | ------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
928
+ | `filterAllowList` | function | `<T>(allow: readonly string[] \| undefined, members: readonly T[], key: (member: T) => string) => readonly T[]` | Filters a list of members by a `ScopeInterface` allow-list of keys — `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys alone, order preserved. The pure, total set-membership primitive the context's build step and the agent loop's tool-advertise step apply a scope through. |
929
+ | `sanitizeToken` | function | `(value: number) => number` | Sanitizes one reported token count into a non-negative integer — a non-finite or non-positive value becomes `0`, and a positive fractional value floors down. |
930
+ | `sanitizeUsage` | function | `(usage: TokenUsage) => TokenUsage` | Sanitizes a `TokenUsage` into non-negative integers — the guard an agent's abort-usage path applies to a provider's partial usage before it is charged against a budget or folded into the run total, because a cancelled stream has no settled result to refuse; a settled result's usage crosses the provider-result door instead. |
931
+ | `joinThinking` | function | `(prior: string \| undefined, next: string) => string` | Joins the reasoning a run's provider calls separated from the answer — the first call seeds the accumulation, a later call appends blank-line separated so each turn's reasoning stays readable. |
932
+ | `stripThinking` | function | `(messages: readonly Message[], replay: ThinkingReplay) => readonly Message[]` | Applies a `ThinkingReplay` policy to a conversation, returning the messages a provider sends with only the assistant thinking the policy allows. |
933
+ | `sumUsage` | function | `(prior: TokenUsage \| undefined, next: TokenUsage) => TokenUsage` | Adds two `TokenUsage` values field by field — the running total an agent run keeps across its provider calls. |
934
+ | `describeSnapshotRefusal` | function | `(noun: string, id: unknown, faults: readonly AuditFault[]) => string` | Describes a snapshot a store refuses, naming its id, the first fault, and what a host does about it. |
935
+ | `describeQuestionRefusal` | function | `(id: string, faults: readonly AuditFault[], schema: JSONSchema) => string` | Describes why a judge question refuses, in the text both of its doors throw. |
936
+ | `scanJudgmentTies` | function | `(question: JudgeQuestion, answer: JudgeAnswer) => readonly AuditFault[]` | Scans what a judge's answer must hold to its question: the same form, every probability in `[0, 1]`, a choice's keys equal to the criteria keys, and a score as long as its levels. |
937
+ | `scanProbability` | function | `(value: number \| undefined, path: readonly string[]) => readonly AuditFault[]` | Scans one probability against `[0, 1]`. |
938
+ | `removeEntries` | function | `<K>(keys: readonly K[], remove: (key: K) => boolean) => boolean` | Removes each key through a single-key remover and folds the outcomes, so a batch `remove` reports whether the whole batch applied. |
939
+ | `collectExchanges` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects whole exchanges, joining every exchange spanned by a tool group. |
940
+ | `collectToolGroups` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects each assistant message that carries calls together with the tool messages that answer it, then each run of tool messages that no assistant message owns. |
941
+ | `hasCalls` | function | `(message: Pick<Message, 'calls'>) => boolean` | Checks whether a message carries at least one tool call. |
942
+ | `renderJSON` | function | `(value: unknown) => string \| undefined` | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
943
+ | `matchesJSON` | function | `(left: unknown, right: unknown) => boolean` | Matches two values of JSON data by JSON value, whatever their key order, and reads a value with no JSON text as no match. |
944
+ | `matchesJudgment` | function | `(judgment: Judgment, question: JudgeQuestion, sources: readonly string[], state: string, model: string) => boolean` | Matches a recorded question by JSON value, the ordered sources, the rendered state, and the judge identity. |
945
+ | `extractLiterals` | function | `(text: string) => LiteralSet` | Reads the ids and the numbers of a text. |
906
946
 
907
947
  #### Validators
908
948
 
909
949
  The following table lists the guards the root declares:
910
950
 
911
- | Name | Kind | Signature | Summary |
912
- | -------------------------- | -------- | -------------------------------------------- | ------------------------------------------------------------------------------------------ |
913
- | `isJudgeEntry` | function | `(value: unknown) => value is JudgeEntry` | Checks whether a value is a judge entry: a string, a JSON record, or a JSON array. |
914
- | `isJudgeQuestion` | function | `(value: unknown) => value is JudgeQuestion` | Checks whether a value is a well-formed judge question of the choice, score, or noul form. |
915
- | `isNonNegativeSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a non-negative safe integer, `-0` included. |
951
+ | Name | Kind | Signature | Summary |
952
+ | -------------------------- | -------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
953
+ | `isJudgeEntry` | function | `(value: unknown) => value is JudgeEntry` | Checks whether a value is a judge entry: a non-empty string, a non-empty JSON record, or a non-empty JSON array. |
954
+ | `isJudgeAnswer` | function | `(value: unknown) => value is JudgeAnswer` | Checks whether a value is a stored judge answer of the choice, score, or noul form. |
955
+ | `isJudgeQuestion` | function | `(value: unknown) => value is JudgeQuestion` | Checks whether a value is a well-formed judge question of the choice, score, or noul form. |
956
+ | `isNonNegativeSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a non-negative safe integer, `-0` included. |
916
957
 
917
958
  ### Providers module
918
959
 
@@ -930,12 +971,12 @@ The following table lists the types the providers module declares:
930
971
  | `ProviderInterface` | interface | `{ id, name, replay?, generate(), stream() }` | Defines the pluggable LLM inference boundary — the one contract every agent chunk depends on. A provider turns a conversation (plus optional tools) into either a single assembled `ProviderResult` (`generate`) or a stream of `ProviderDelta` values that returns the assembled result (`stream`). The agent loop, a relay server, and a ledger apply its `replay` policy before calling it. A direct `generate` or `stream` call sends messages as given. |
931
972
  | `ProviderParserInterface` | interface | `{ parse(), clear() }` | Defines the structural framing seam supplied by a concrete provider. |
932
973
  | `ProviderRequest` | interface | `{ messages, tools?, options? }` | Carries the conversation and per-call configuration sent to a provider. |
933
- | `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result? }` | Holds the decoded contribution of a wire record to a provider turn. |
974
+ | `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result?, done? }` | Holds the decoded contribution of a wire record to a provider turn. |
934
975
  | `ProviderOptions` | interface | `{ timeout?, replay?, fetch?, headers? }` | Configures a provider's deadline, transport, and headers. |
935
976
  | `AgentProviderInput` | interface | `{ url, path?, split?, strict? }` | Configures the HTTP destination and stream assembly of a provider base. |
936
977
  | `AgentProviderInterface` | interface | `{ frame(), encode(), read(), finish() }` | Defines the wire-specific seams of the shared HTTP provider engine. |
937
978
  | `ProviderErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'PROVIDER'` | Names the machine-readable provider failure conditions. |
938
- | `ProviderErrorOptions` | interface | `{ status?, cause? }` | Carries a provider failure's HTTP status and underlying cause. |
979
+ | `ProviderErrorOptions` | interface | `{ status?, cause?, context? }` | Carries a provider failure's HTTP status and underlying cause. |
939
980
  | `FailureRead` | interface | `{ message, status, cause? }` | Carries an HTTP failure message, the response status, and the underlying body-read cause when available. |
940
981
  | `TextRead` | interface | `{ text, complete }` | Carries a decoded stream prefix and whether the stream ended within its byte budget. |
941
982
  | `RelayFrame` | type | `ProviderDelta \| { readonly channel: 'result'; readonly result: ProviderResult; } \| { readonly channel: 'abort'; readonly partial: ProviderResult; } \| { readonly channel: 'error'; readonly message: string; }` | Carries a relay delta, settled result, remote abort, or remote failure. |
@@ -1059,32 +1100,35 @@ The following table lists the classes the providers module declares:
1059
1100
 
1060
1101
  The following table lists the helpers the providers module declares:
1061
1102
 
1062
- | Name | Kind | Signature | Summary |
1063
- | ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
1064
- | `buildProviderResult` | function | `(content: string, thinking: string, tools: readonly ToolCall[], usage: TokenUsage \| undefined, truncated: boolean \| undefined) => ProviderResult` | Assembles a provider result with only populated optional fields. |
1065
- | `armReaderAbort` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>, signal: AbortSignal \| undefined) => Promise<AbortController>` | Arms signal propagation to a byte reader and returns the controller that removes the listener. |
1066
- | `readFailure` | function | `(response: Response, prefix: string, signal: AbortSignal) => Promise<FailureRead>` | Reads a bounded HTTP failure excerpt and preserves an unreadable body's cause. |
1067
- | `readBodyText` | function | `(body: ReadableStream<Uint8Array>, limit?: number, signal?: AbortSignal) => Promise<TextRead>` | Reads a UTF-8 prefix of a byte stream and cancels its remainder. |
1068
- | `readChunks` | function | `(body: ReadableStream<Uint8Array>, signal?: AbortSignal) => AsyncGenerator<string>` | Decodes UTF-8 chunks with a final flush and releases the stream on every exit. |
1069
- | `releaseReader` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>) => Promise<void>` | Cancels a stream reader and releases its lock, swallowing a cancellation failure so the caller's own outcome stands. |
1070
- | `measureAnswer` | function | `(answer: JudgeAnswer) => AnswerMeasure` | Derives the winner, its probability, the published confidence, and a score answer's expected level from a judge answer's distribution. |
1071
- | `buildJudgeResult` | function | `(model: string, results: readonly JudgeResult[]) => JudgeResult` | Merges the results of a judge request's calls into one result. |
1072
- | `buildProviderHeaders` | function | `(hook: ProviderOptions['headers'], signal: AbortSignal) => Promise<Headers>` | Builds a request's JSON headers, awaiting the caller's header hook inside the call's cancellation bound. |
1073
- | `requestToRelay` | function | `(request: ProviderRequest) => ProviderRequest` | Projects a provider request onto the declared members the relay wire carries. |
1074
- | `buildRelayRequest` | function | `(request: ProviderRequest, policy: Pick<RelayOptions, 'system' \| 'tools'>) => Result<ProviderRequest, readonly RelayRefusal[]>` | Builds the request a relay forwards under its system turn and tool definition policy, or every refusal that policy finds. |
1075
- | `describeRelayRefusal` | function | `(refusal: RelayRefusal) => string` | Describes one relay refusal as the line its `422` response body carries. |
1076
- | `questionToSystemOne` | function | `(question: JudgeQuestion) => SystemOneQuestion` | Projects a judge question onto the System One wire while preserving omitted members. |
1077
- | `extractSystemOneAnswer` | function | `(answer: SystemOneAnswer, question: JudgeQuestion) => JudgeAnswer \| undefined` | Extracts a System One distribution in question criteria order and drops server measures. |
1078
- | `extractSystemOneUsage` | function | `(usage: SystemOneUsage \| undefined) => TokenUsage \| undefined` | Maps complete System One token counts onto validated token usage. |
1103
+ | Name | Kind | Signature | Summary |
1104
+ | ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1105
+ | `readProviderDelta` | function | `(value: unknown) => ProviderDelta \| undefined` | Reads a foreign delta's two members once into an owned copy, the value a run checks and consumes. |
1106
+ | `requireProviderResult` | function | `(value: unknown) => ProviderResult` | Owns a provider's settled result: reads each published member of the foreign value once into a fresh record, checks that copy, and returns it, or throws a coded error the run rejects with. |
1107
+ | `buildProviderResult` | function | `(content: string, thinking: string, tools: readonly ToolCall[], usage: TokenUsage \| undefined, truncated: boolean \| undefined) => ProviderResult` | Assembles a provider result with only populated optional fields. |
1108
+ | `armReaderAbort` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>, signal: AbortSignal \| undefined) => Promise<AbortController>` | Arms signal propagation to a byte reader and returns the controller that removes the listener. |
1109
+ | `readFailure` | function | `(response: Response, prefix: string, signal: AbortSignal) => Promise<FailureRead>` | Reads a bounded HTTP failure excerpt and preserves an unreadable body's cause. |
1110
+ | `readBodyText` | function | `(body: ReadableStream<Uint8Array>, limit?: number, signal?: AbortSignal) => Promise<TextRead>` | Reads a UTF-8 prefix of a byte stream and cancels its remainder. |
1111
+ | `readChunks` | function | `(body: ReadableStream<Uint8Array>, signal?: AbortSignal) => AsyncGenerator<string>` | Decodes UTF-8 chunks with a final flush and releases the stream on every exit. |
1112
+ | `releaseReader` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>) => Promise<void>` | Cancels a stream reader and releases its lock, swallowing a cancellation failure so the caller's own outcome stands. |
1113
+ | `measureAnswer` | function | `(answer: JudgeAnswer) => AnswerMeasure` | Derives the winner, its probability, the published confidence, and a score answer's expected level from a judge answer's distribution. |
1114
+ | `buildJudgeResult` | function | `(model: string, results: readonly JudgeResult[]) => JudgeResult` | Merges the results of a judge request's calls into one result. |
1115
+ | `buildProviderHeaders` | function | `(hook: ProviderOptions['headers'], signal: AbortSignal) => Promise<Headers>` | Builds a request's JSON headers, awaiting the caller's header hook inside the call's cancellation bound. |
1116
+ | `requestToRelay` | function | `(request: ProviderRequest) => ProviderRequest` | Projects a provider request onto the declared members the relay wire carries. |
1117
+ | `buildRelayRequest` | function | `(request: ProviderRequest, policy: Pick<RelayOptions, 'system' \| 'tools'>) => Result<ProviderRequest, readonly RelayRefusal[]>` | Builds the request a relay forwards under its system turn and tool definition policy, or every refusal that policy finds. |
1118
+ | `describeRelayRefusal` | function | `(refusal: RelayRefusal) => string` | Describes one relay refusal as the line its `422` response body carries. |
1119
+ | `questionToSystemOne` | function | `(question: JudgeQuestion) => SystemOneQuestion` | Projects a judge question onto the System One wire while preserving omitted members. |
1120
+ | `extractSystemOneAnswer` | function | `(answer: SystemOneAnswer, question: JudgeQuestion) => JudgeAnswer \| undefined` | Extracts a System One distribution in question criteria order and drops server measures. |
1121
+ | `extractSystemOneUsage` | function | `(usage: SystemOneUsage \| undefined) => TokenUsage \| undefined` | Maps complete System One token counts onto validated token usage. |
1079
1122
 
1080
1123
  #### Validators
1081
1124
 
1082
1125
  The following table lists the guards the providers module declares:
1083
1126
 
1084
- | Name | Kind | Signature | Summary |
1085
- | --------------------- | -------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------- |
1086
- | `isSystemOneResponse` | function | `(value: unknown) => value is SystemOneResponse` | Checks whether a value is a System One response envelope with optional model and usage. |
1087
- | `isSystemOneAnswer` | function | `(value: unknown) => value is SystemOneAnswer` | Checks whether a value is a System One answer whose type and distribution the wire can read. |
1127
+ | Name | Kind | Signature | Summary |
1128
+ | --------------------- | -------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1129
+ | `isSystemOneResponse` | function | `(value: unknown) => value is SystemOneResponse` | Checks whether a value is a System One response envelope with optional model and usage. |
1130
+ | `isProviderResult` | const | `Guard<ProviderResult>` | Checks whether a value carries the members `ProviderResult` publishes: a string `content`, and `thinking`, `tools`, `usage`, and `truncated` absent or of their published types. |
1131
+ | `isSystemOneAnswer` | function | `(value: unknown) => value is SystemOneAnswer` | Checks whether a value is a System One answer whose type and distribution the wire can read. |
1088
1132
 
1089
1133
  ### Conversations module
1090
1134
 
@@ -1110,7 +1154,7 @@ The following table lists the types the conversations module declares:
1110
1154
  | `ConversationSnapshot` | interface | `{ id, judgments?, sections, messages }` | Holds a JSON-serializable snapshot of the state of a conversation — its `id`, the compacted `sections`, and the live tail `messages` — the durable payload the `ConversationStoreInterface` persists. The exact analogue of `WorkspaceSnapshot`. |
1111
1155
  | `ConversationStoreInterface` | interface | `{ get(), set(), delete() }` | Persists a `ConversationSnapshot` durably — the async `get` / `set` / `delete` primitives, keyed by a conversation id and holding no expiry, the exact analogue of `WorkspaceStoreInterface`. |
1112
1156
  | `ConversationSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseConversationStore` persists — a conversation `id` plus its `ConversationSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. The exact analogue of `WorkspaceSnapshotRow`. |
1113
- | `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'SNAPSHOT'` | Names the machine-readable condition a `ConversationError` reports. |
1157
+ | `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID'` | Names the machine-readable condition a `ConversationError` reports. |
1114
1158
  | `JudgmentManagerInterface` | interface | `{ count, add(), judgment(), judgments(), remove(), clear(), resolve() }` | Stores judgments by caller key and resolves requests by reusing matching records. |
1115
1159
 
1116
1160
  #### Constants
@@ -1126,10 +1170,10 @@ The following table lists the constants the conversations module declares:
1126
1170
 
1127
1171
  The following table lists the errors the conversations module declares and the guards that narrow them:
1128
1172
 
1129
- | Name | Kind | Signature | Summary |
1130
- | --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1131
- | `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap below `1`, a `keep` that is not a nonnegative safe integer, a summarizer digest whose trimmed text is empty, a judgment or judge request that JSON cannot carry, a stored or selected message whose role is not a conversation role, or a malformed snapshot — thrown by the `compact()` and `add` methods of a `ConversationInterface`, its construction, or its judgment store, or returned as the `fault` of an agent selection, carrying the machine-readable `code` `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'SNAPSHOT'`. |
1132
- | `isConversationError` | function | `(value: unknown) => value is ConversationError` | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1173
+ | Name | Kind | Signature | Summary |
1174
+ | --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1175
+ | `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap that is not a positive safe integer, a `keep` that is not a nonnegative safe integer, a summarizer digest whose trimmed text is empty, a judgment or judge request that JSON cannot carry, a stored or selected message whose role is not a conversation role, or a malformed snapshot — thrown by the `compact()` and `add` methods of a `ConversationInterface`, its construction, or its judgment store, or returned as the `fault` of an agent selection, carrying the machine-readable `code` `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID'`. |
1176
+ | `isConversationError` | function | `(value: unknown) => value is ConversationError` | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1133
1177
 
1134
1178
  #### Factories
1135
1179
 
@@ -1164,10 +1208,13 @@ The following table lists the helpers the conversations module declares:
1164
1208
  | `buildRecapMessage` | function | `(section: Section) => Message` | Builds the framed recap message for one compacted section — the same role and stable `id` as `buildSummaryMessage`, with the content prefixed by `CONVERSATION_RECAP_PREFIX`. |
1165
1209
  | `requireJudgment` | function | `(value: unknown) => Judgment` | Returns a stored judgment record after checking it, or throws a coded error. |
1166
1210
  | `requireRole` | function | `(role: unknown) => ConversationRole` | Returns a stored message role after checking it is a conversation role, or throws a coded error. |
1167
- | `requireConversationSnapshot` | function | `(value: unknown) => ConversationSnapshot` | Returns a conversation snapshot after checking its shape, its stored roles, and its ids, or throws a coded error. |
1168
- | `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking its lower bound, or throws a coded error. |
1211
+ | `requireConversationSnapshot` | function | `(value: unknown, contract: Pick<ContractInterface<unknown>, 'audit' \| 'schema'>) => ConversationSnapshot` | Returns a conversation snapshot after checking its shape, its stored roles, and its ids, or throws a coded error. |
1212
+ | `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking it is a positive safe integer, or throws a coded error. |
1169
1213
  | `requireCumulative` | function | `(cumulative: boolean, cap: number \| undefined) => boolean` | Returns the cumulative switch after checking it does not combine with a `sections` cap, or throws a coded error. |
1170
1214
  | `requireKeep` | function | `(keep: number) => number` | Returns a retained-tail size after checking it is a nonnegative safe integer, or throws a coded error. |
1215
+ | `requireMessageInput` | function | `(input: unknown, contract: Pick<ContractInterface<unknown>, 'audit' \| 'schema'>) => MessageInput` | Returns a message input after checking its role and its members, or throws a coded error. |
1216
+ | `readJudgeOutcome` | function | `(result: JudgeResult, id: string) => { readonly answer: JudgeAnswer \| undefined; readonly refusal: Refusal \| undefined; }` | Reads what a judge result holds for one question, from its own keys alone. |
1217
+ | `requireJudgeResult` | function | `(request: JudgeRequest, result: JudgeResult) => void` | Returns after checking a complete judge result answered or refused every question it was asked, or throws a coded error naming those it left out. |
1171
1218
  | `requireSummary` | function | `(summary: string) => string` | Returns a summarizer digest after checking it carries non-whitespace text, or throws a coded error. |
1172
1219
  | `raceSignal` | function | `<T>(promise: Promise<T>, signal: AbortSignal \| undefined) => Promise<T>` | Settles with a promise, or rejects with the reason of a signal that aborts first, so a caller is released at once even when the work behind the promise ignores the signal. |
1173
1220
  | `buildJudgments` | function | `(request: JudgeRequest, result: JudgeResult, sources: readonly string[], state: string, model: string) => readonly JudgmentInput[]` | Builds records for answered or refused request keys, attaching usage only for a single question. |
@@ -1176,15 +1223,22 @@ The following table lists the helpers the conversations module declares:
1176
1223
 
1177
1224
  The following table lists the guards the conversations module declares:
1178
1225
 
1179
- | Name | Kind | Signature | Summary |
1180
- | ------------------------ | -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1181
- | `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
1182
- | `isSection` | function | `(value: unknown) => value is Section` | Checks whether an `unknown` is structurally a `Section` record — a `string` `id` and `summary` beside a `messages` array of valid `Message` records, the per-section step of the `isConversationSnapshot` read-boundary narrow. Total, never throwing, and never an assertion. |
1183
- | `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id` and valid `sections` and `messages` arrays; the total boundary guard for an untrusted snapshot read (a storage row a `DatabaseConversationStore` reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact analogue of `isWorkspaceSnapshot`. |
1184
- | `isConversation` | function | `(value: unknown) => value is ConversationInterface` | Checks whether a value carries the `ConversationInterface` members a run reads: a string `id`, a boolean `summarizable`, and `view`, `add`, `compact`, and `messages` methods. |
1185
- | `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
1186
-
1187
- A `DatabaseConversationStore` reads its snapshot column back as `unknown` and narrows it through `isConversationSnapshot`, so a malformed blob resolves `undefined` rather than a broken conversation:
1226
+ | Name | Kind | Signature | Summary |
1227
+ | ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1228
+ | `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
1229
+ | `isSection` | function | `(value: unknown) => value is Section` | Checks whether an `unknown` is structurally a `Section` record — a `string` `id` and `summary` beside a `messages` array of valid `Message` records, the per-section step of the `isConversationSnapshot` read-boundary narrow. Total, never throwing, and never an assertion. |
1230
+ | `isMessageInput` | function | `(value: unknown) => value is MessageInput` | Checks whether a value is a message input a conversation can store: a string `content`, and `calls`, `call`, `images`, and `thinking` absent or of their declared types. |
1231
+ | `judgmentShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>` | Describes a stored judgment: exactly one of an answer or a refusal, with its question, sources, state, model, and storage time. |
1232
+ | `sectionShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a compacted section: its id, its summary, and the originals it folded. |
1233
+ | `conversationSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; sections: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; judgments: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>>>; }, boolean \| ContractShape>` | Describes a conversation snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
1234
+ | `judgmentContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>>` | Reads the faults of a refused judgment. |
1235
+ | `sectionContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>>` | Reads the faults of a refused section. |
1236
+ | `conversationSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; sections: readonly Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>[]; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { judgments?: readonly (Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>)[]; }>>` | Reads the faults of a refused conversation snapshot. |
1237
+ | `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id` and valid `sections` and `messages` arrays; the total boundary guard for an untrusted snapshot read (a storage row a `DatabaseConversationStore` reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact analogue of `isWorkspaceSnapshot`. |
1238
+ | `isConversation` | function | `(value: unknown) => value is ConversationInterface` | Checks whether a value carries the `ConversationInterface` members a run reads: a string `id`, a boolean `summarizable`, and `view`, `add`, `compact`, and `messages` methods. |
1239
+ | `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
1240
+
1241
+ A `DatabaseConversationStore` reads its snapshot column back as `unknown` and narrows it through `isConversationSnapshot`. Only a missing row resolves `undefined`: a present row that fails the guard or names another id throws `ConversationError` `'SNAPSHOT'`, naming the id, carrying the faults, and saying to read the row through your own table and rewrite it, or to delete it with `store.delete`, and `set` refuses what `get` would. The same narrow, written by hand, reads:
1188
1242
 
1189
1243
  ```ts
1190
1244
  import { isConversationSnapshot } from '@orkestrel/agent'
@@ -1203,7 +1257,7 @@ The following table lists the types the contexts module declares:
1203
1257
 
1204
1258
  | Name | Kind | Signature | Summary |
1205
1259
  | ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1206
- | `ContextErrorCode` | type | `'SNAPSHOT'` | Names the machine-readable condition a `ContextError` reports. |
1260
+ | `ContextErrorCode` | type | `'SNAPSHOT' \| 'IMAGES'` | Names the machine-readable condition a `ContextError` reports. |
1207
1261
  | `ContextSectionFormat` | interface | `{ open?, render?, close? }` | Overrides one context section's format — an `open` / `render` / `close` trio that frames a section in the `AgentContext` build cascade: a top line rendered once before the items, a per-item rendering, and a bottom line rendered once after the items. |
1208
1262
  | `InstructionInterface` | interface | `{ id, name, content, priority, override? }` | Represents an immutable instruction — a named directive a richer context places between the system prompt and the conversation, ordered by descending `priority`. |
1209
1263
  | `InstructionInput` | interface | `{ name, content, priority?, override? }` | Carries the minimal data to author an `InstructionInterface` — the `id` is minted by the `InstructionManagerInterface` that stores it, so a caller supplies only `name` / `content` and an optional `priority`. Default: `0`. |
@@ -1249,10 +1303,10 @@ The following table lists the constants the contexts module declares:
1249
1303
 
1250
1304
  The following table lists the errors the contexts module declares and the guards that narrow them:
1251
1305
 
1252
- | Name | Kind | Signature | Summary |
1253
- | ---------------- | -------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1254
- | `ContextError` | class | `new (code: ContextErrorCode, message: string, options?: CodedErrorOptions) => ContextError` | Reports a context snapshot that `isMemoSnapshot` refuses, thrown by the construction of a `MemoManager` before it seats any state, carrying the machine-readable `code` `'SNAPSHOT'`. |
1255
- | `isContextError` | function | `(value: unknown) => value is ContextError` | Narrows an unknown caught value to a `ContextError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1306
+ | Name | Kind | Signature | Summary |
1307
+ | ---------------- | -------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1308
+ | `ContextError` | class | `new (code: ContextErrorCode, message: string, options?: CodedErrorOptions) => ContextError` | Reports a context snapshot that `isMemoSnapshot` refuses, thrown by the construction of a `MemoManager` before it seats any state or by a memo store, or image files a build has no user turn to carry, carrying the machine-readable `code` `'SNAPSHOT' \| 'IMAGES'`. |
1309
+ | `isContextError` | function | `(value: unknown) => value is ContextError` | Narrows an unknown caught value to a `ContextError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1256
1310
 
1257
1311
  #### Factories
1258
1312
 
@@ -1304,10 +1358,15 @@ The following table lists the helpers the contexts module declares:
1304
1358
 
1305
1359
  The following table lists the guards the contexts module declares:
1306
1360
 
1307
- | Name | Kind | Signature | Summary |
1308
- | ---------------- | -------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1309
- | `isMemo` | const | `Guard<Memo>` | Checks whether a value is a stored memo revision: a record with a string `id`, `name`, `description`, and `content`, a finite `time`, and an optional `origin`. |
1310
- | `isMemoSnapshot` | function | `(value: unknown) => value is MemoSnapshot` | Checks whether a value is a stored memo set: a record with a string `id` and a dense `memos` array of `isMemo` values. |
1361
+ | Name | Kind | Signature | Summary |
1362
+ | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1363
+ | `isMemo` | function | `(value: unknown) => value is Memo` | Checks whether a value is a stored memo revision: a record with a string `id`, `name`, `description`, and `content`, a finite `time`, and an optional `origin`. |
1364
+ | `memoShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo revision exactly. |
1365
+ | `memoSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; memos: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo set exactly: an unknown key refuses. |
1366
+ | `memoContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>>` | Reads the faults of a refused memo revision. |
1367
+ | `memoSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; memos: readonly Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>[]; } & {}>>` | Reads the faults of a refused memo snapshot. |
1368
+ | `isMemoOrigin` | function | `(value: unknown) => value is MemoOrigin` | Checks whether a value is a memo's origin: a record with a string `conversation` and an optional string `message`. |
1369
+ | `isMemoSnapshot` | function | `(value: unknown) => value is MemoSnapshot` | Checks whether a value is a stored memo set: a record with a string `id` and a dense `memos` array of `isMemo` values. |
1311
1370
 
1312
1371
  ### Agents module
1313
1372
 
@@ -1326,7 +1385,7 @@ The following table lists the types the agents module declares:
1326
1385
  | `AgentRunResult` | interface | `{ content, thinking, usage, partial, exhausted, stop }` | Holds the immutable outcome of one agent loop, assembled into the `AgentResult` resolved by the stream handle. |
1327
1386
  | `AgentTurn` | interface | `{ content, thinking, usage, spent, messages, outcome, partial, futile, estimate, interrupted, truncated }` | Holds what one agent loop turn contributed to its run and how the turn ended — the readonly record the loop appends for each turn, from which the run derives its `AgentRunResult`. |
1328
1387
  | `AgentStop` | type | `{ readonly layer: 'meter' \| 'budget'; readonly id: string; readonly max: number; readonly consumed: number; readonly estimate?: number; readonly usage?: TokenUsage; } \| { readonly layer: 'model'; readonly id: string; readonly estimate?: number; readonly usage?: TokenUsage; }` | Represents why one of a run's three allowed failure layers stopped it — the meter's estimate allowance, the cost budget, or the model's own token limit — with the readings that layer crossed. |
1329
- | `AgentErrorCode` | type | `'APPROVER' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'WINDOW'` | Names the machine-readable agent approver, concurrency, limit, registry, and window failures. |
1388
+ | `AgentErrorCode` | type | `'APPROVER' \| 'AUTHORITY' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'SCHEMA' \| 'WINDOW'` | Names the machine-readable agent approver, authority, concurrency, limit, registry, schema, and window failures. |
1330
1389
  | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1331
1390
  | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1332
1391
  | `ChannelInterface` | interface | `{ push(), close(), fail(), drain() }` | Buffers values in an unbounded async channel — a producer writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
@@ -1342,12 +1401,12 @@ The following table lists the types the agents module declares:
1342
1401
  | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1343
1402
  | `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
1344
1403
  | `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
1345
- | `AuthorityRule` | interface | `{ match, zone, verdict?, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1404
+ | `AuthorityRule` | interface | `{ match, zone, verdict, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1346
1405
  | `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
1347
- | `AuthorityOptions` | interface | `{ rules?, fallback?, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
1406
+ | `AuthorityOptions` | interface | `{ rules?, fallback, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
1348
1407
  | `AuthorityInterface` | interface | `{ evaluate(), ask?() }` | Gates each tool call before it runs — the synchronous policy that turns one `AuthorityContext` into an `AuthorityDecision`, and the optional approver that answers an `ask` verdict. |
1349
1408
  | `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
1350
- | `AgentJobInput` | interface | `{ provider, messages, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, children? }` | Represents a JSON-serializable agent job — the descriptor a durable queue or runner runs. Its non-serializable pieces (the provider, tools, authority, scheduler) are referenced by name and resolved to live objects through an `AgentRegistryInterface` at handler time, while its data fields (the seed `messages`, `system`, `limit`, `timeout`, and a token `budget` ceiling) carry directly. |
1409
+ | `AgentJobInput` | interface | `{ provider, messages?, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, children? }` | Represents a JSON-serializable agent job — the descriptor a durable queue or runner runs. Its non-serializable pieces (the provider, tools, authority, scheduler) are referenced by name and resolved to live objects through an `AgentRegistryInterface` at handler time, while its data fields (the seed `messages`, `system`, `limit`, `timeout`, and a token `budget` ceiling) carry directly. |
1351
1410
  | `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1352
1411
  | `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
1353
1412
  | `AgentQueueOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout?, store? }` | Configures `createAgentQueue` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createQueue`. |
@@ -1360,7 +1419,6 @@ The following table lists the constants the agents module declares:
1360
1419
  | Name | Kind | Signature | Summary |
1361
1420
  | ------------------------ | ----- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1362
1421
  | `DEFAULT_AGENT_LIMIT` | const | `10` | Caps an `AgentInterface` turn's tool iterations by default — `10` context → provider → tools cycles before the loop stops, so a model that keeps requesting tools can never loop forever. Overridable per agent through `AgentOptions.limit`. |
1363
- | `DEFAULT_AUTHORITY_ZONE` | const | `"default"` | Names the default zone for an unmatched tool call allowed by an authority. |
1364
1422
  | `AUTHORITY_NOTES` | const | `AuthorityNote` | Holds the model-facing texts the loop writes after a tool name in a denial result — the `denied` note for a deny with no reason, an evaluate throw, an invalid decision, or a tool changed after its decision; the `refused` note for an ask the approver refused; and the `unanswered` note for an ask no approver answered, frozen. |
1365
1423
  | `SCOPE_NOTE` | const | `"it is not one of the listed tools. Use a listed tool or answer with what you have."` | Holds the model-facing text the loop writes after a tool name in the denial result of a call outside the active scope's tool allow-list or whose name no definition advertises this turn. |
1366
1424
  | `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
@@ -1370,12 +1428,12 @@ The following table lists the constants the agents module declares:
1370
1428
 
1371
1429
  The following table lists the errors the agents module declares and the guards that narrow them:
1372
1430
 
1373
- | Name | Kind | Signature | Summary |
1374
- | ----------------- | -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1375
- | `AgentJobError` | class | `new (message: string, partial: AgentResult) => AgentJobError` | Reports an `AgentInterface` run that ended `AgentResult.partial` under a `partial` policy of `false` (the default) — thrown by an agent-job handler (a `createAgentQueue` / `createAgentRunner` job), carrying the partial `AgentResult` so the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`. |
1376
- | `isAgentJobError` | function | `(value: unknown) => value is AgentJobError` | Narrows an unknown caught value to an `AgentJobError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
1377
- | `AgentError` | class | `new (code: AgentErrorCode, message: string, options?: CodedErrorOptions) => AgentError` | Reports an `ask` on an authority that has no approver or that its approver refuses, a run sharing accounting or a conversation with a live run, a `limit` that is not a nonnegative safe integer, a name absent from a registry pool, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead, and an `'APPROVER'` refusal rejects the promise the `ask` method of an `Authority` or the `ask` handler of an `Approver` returns. Await the call inside `try`/`catch` to catch it. |
1378
- | `isAgentError` | function | `(value: unknown) => value is AgentError` | Narrows an unknown caught value to an `AgentError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1431
+ | Name | Kind | Signature | Summary |
1432
+ | ----------------- | -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1433
+ | `AgentJobError` | class | `new (message: string, partial: AgentResult) => AgentJobError` | Reports an `AgentInterface` run that ended `AgentResult.partial` under a `partial` policy of `false` (the default) — thrown by an agent-job handler (a `createAgentQueue` / `createAgentRunner` job), carrying the partial `AgentResult` so the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`. |
1434
+ | `isAgentJobError` | function | `(value: unknown) => value is AgentJobError` | Narrows an unknown caught value to an `AgentJobError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
1435
+ | `AgentError` | class | `new (code: AgentErrorCode, message: string, options?: CodedErrorOptions) => AgentError` | Reports an `ask` on an authority that has no approver or that its approver refuses, an authority missing its fallback or a rule's verdict, tools set with no authority, a run sharing accounting or a conversation with a live run, a `limit` that is not a positive safe integer, a name absent from a registry pool, a strict run's answer that fails its schema, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead, and an `'APPROVER'` refusal rejects the promise the `ask` method of an `Authority` or the `ask` handler of an `Approver` returns. Await the call inside `try`/`catch` to catch it. |
1436
+ | `isAgentError` | function | `(value: unknown) => value is AgentError` | Narrows an unknown caught value to an `AgentError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1379
1437
 
1380
1438
  #### Shapes and contracts
1381
1439
 
@@ -1385,9 +1443,11 @@ The following table lists the agent wire shapes and the contracts compiled from
1385
1443
  | --------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
1386
1444
  | `agentFrameShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["token"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["think"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [true]>; name: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [false]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["usage"]>; usage: import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>; estimate: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["ask"]>; id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; zone: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["finish"]>; content: import("@orkestrel/contract").StringShape; partial: import("@orkestrel/contract").BooleanShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; layer: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").LiteralShape<readonly ["meter", "budget", "model"]>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["error"]>; }, boolean \| ContractShape>]>` | Describes the agent frame wire — one exact object per `AgentFrame` arm, discriminated by `category`. |
1387
1445
  | `agentPromptShape` | const | `import("@orkestrel/contract").ObjectShape<{ content: import("@orkestrel/contract").StringShape; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; }, boolean \| ContractShape>` | Describes the agent prompt wire — the `content` and optional `images` of one user turn, read by the run's `prompt` option and by a page's request body. |
1446
+ | `agentJobShape` | const | `import("@orkestrel/contract").ObjectShape<{ provider: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>>; system: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; authority: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; scheduler: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; limit: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; timeout: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; budget: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; children: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>>; }, boolean \| ContractShape>` | Describes a durable agent job — the record `AgentRegistry.build` checks exactly, so a misspelled key refuses instead of running an agent without it. |
1388
1447
  | `agentAnswerShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; approved: import("@orkestrel/contract").BooleanShape; }, boolean \| ContractShape>` | Describes the agent answer wire — the `id` of one `ask` frame and a boolean `approved`. |
1389
1448
  | `agentFrameContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ category: "token"; content: string; } & {}> \| Readonly<{ category: "think"; content: string; } & {}> \| Readonly<{ category: "tool"; success: true; name: string; } & {}> \| Readonly<{ category: "tool"; success: false; } & {}> \| Readonly<{ category: "usage"; usage: Readonly<{ prompt: number; completion: number; total: number; } & {}>; estimate: number; } & {}> \| Readonly<{ category: "ask"; id: string; name: string; zone: string; arguments: string; } & {}> \| Readonly<{ category: "finish"; content: string; partial: boolean; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; layer?: "budget" \| "meter" \| "model"; }> \| Readonly<{ category: "error"; } & {}>>` | Validates and projects agent frames at a JSON wire boundary. |
1390
1449
  | `agentPromptContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ content: string; } & { images?: readonly string[]; }>>` | Validates and projects agent prompts at the run's `prompt` option and a page's request body. |
1450
+ | `agentJobContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ provider: string; } & { messages?: readonly Readonly<{ role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; system?: string; tools?: readonly string[]; authority?: string; scheduler?: string; limit?: number; timeout?: number; budget?: number; children?: readonly { readonly [k: string]: import("@orkestrel/contract").JSONValue; }[]; }>>` | Checks a durable agent job exactly at `AgentRegistry.build`. |
1391
1451
  | `agentAnswerContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; approved: boolean; } & {}>>` | Validates and projects a page's answers to `ask` frames at a JSON wire boundary. |
1392
1452
 
1393
1453
  #### Factories
@@ -1397,7 +1457,7 @@ The following table lists the factories the agents module declares:
1397
1457
  | Name | Kind | Signature | Summary |
1398
1458
  | --------------------- | -------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1399
1459
  | `createAgent` | function | `(provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Creates an agent loop — an `AgentInterface` composing a `ProviderInterface`, its `AgentContextInterface`, and a tool registry into a bounded context → provider → tools → repeat turn, exposed as a one-shot `generate` and a live `stream`. |
1400
- | `createAuthority` | function | `(options?: AuthorityOptions) => AuthorityInterface` | Creates a policy gate — an `AuthorityInterface` the agent loop consults before each tool call runs, evaluating the ordered rules first-match-wins and falling back to the configured default when none match. |
1460
+ | `createAuthority` | function | `(options: AuthorityOptions) => AuthorityInterface` | Creates a policy gate — an `AuthorityInterface` the agent loop consults before each tool call runs, evaluating the ordered rules first-match-wins and falling back to the required `fallback` when none match. |
1401
1461
  | `createApprover` | function | `() => ApproverInterface` | Creates an approver — an `ApproverInterface` that holds a server's waiting asks between the run that asked them and the page that answers them. |
1402
1462
  | `createChannel` | function | `<T>() => ChannelInterface<T>` | Creates an empty unbounded async channel — a `ChannelInterface` a producer writes values into (`push`) and ends (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
1403
1463
  | `createAgentRegistry` | function | `(options: AgentRegistryOptions) => AgentRegistryInterface` | Creates a registry of live providers, tools, authorities, and schedulers whose `build` method returns a seeded, signal-wired `AgentInterface` from a serializable job. |
@@ -1412,7 +1472,7 @@ The following table lists the classes the agents module declares:
1412
1472
  | --------------- | ----- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1413
1473
  | `Agent` | class | `new (provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Composes a `ProviderInterface`, an `AgentContext`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn, exposed as both a one-shot `generate` and a live `stream` that share one private run — bounded by the run `signal`, the `timeout`, and the `budget` folded through `AbortSignal.any`, paced by `scheduler`, with tool iteration capped at `limit`. |
1414
1474
  | `AgentFanout` | class | `new (registry: AgentRegistryInterface, partial: boolean) => AgentFanout` | Executes one runner's agent jobs — spawning each unit's declared children on its first attempt only, then rehydrating the unit through a registry with the controller signal and settling it under the shared partial-result policy. |
1415
- | `Authority` | class | `new (options?: AuthorityOptions) => AuthorityInterface` | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to a configurable default, which allows an unmatched call unless its `fallback` decides otherwise, and the approver that answers an `ask` verdict. |
1475
+ | `Authority` | class | `new (options: AuthorityOptions) => AuthorityInterface` | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to the required `fallback`, and the approver that answers an `ask` verdict. |
1416
1476
  | `Approver` | class | `new () => ApproverInterface` | Holds a server's waiting asks between the run that asked them and the page that answers them — an `ApproverInterface` whose `ask` is the authority's handler, keyed by the asked call object. |
1417
1477
  | `AgentRegistry` | class | `new (options: AgentRegistryOptions) => AgentRegistryInterface` | Makes a durable, JSON-serializable `AgentJobInput` runnable — holds the named pools of live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name absent from its pool, and its `build` method returns a seeded, signal-wired `Agent` from a job's names and data. |
1418
1478
  | `Channel` | class | `new <T>() => ChannelInterface<T>` | Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through the `drain` async-iterator. Decoupling write from read is what lets a producer make progress without a consumer pulling, and it is why an agent's `result` settles whether or not its `events` are drained. |
@@ -1421,32 +1481,36 @@ The following table lists the classes the agents module declares:
1421
1481
 
1422
1482
  The following table lists the helpers the agents module declares:
1423
1483
 
1424
- | Name | Kind | Signature | Summary |
1425
- | --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1426
- | `agentResultToJSON` | function | `(value: unknown) => JSONValue \| undefined` | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving finite negative and fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a non-finite usage number, a throwing getter, or a malformed or revoked proxy. |
1427
- | `tokenUsageToJSON` | function | `(value: unknown) => TokenUsage \| undefined` | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving finite negative and fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing or non-finite count, a throwing getter, or a malformed or revoked proxy. |
1428
- | `agentChunkToFrame` | function | `(chunk: AgentChunk) => AgentFrame \| undefined` | Projects one `AgentChunk` onto the `AgentFrame` a page receives, member by member, or returns `undefined` for an `ask` chunk. |
1429
- | `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
1430
- | `agentStreamToFrames` | function | `(stream: AgentStreamInterface, approver: ApproverInterface \| undefined) => AsyncGenerator<AgentFrame, void, undefined>` | Projects a run's live handle onto the frames a page receives — one frame per projected chunk, in order, then exactly one terminal `finish` or `error`, last. |
1431
- | `inferStop` | function | `(reason: unknown, allowance: BudgetInterface<TokenUsage> \| undefined, budget: BudgetInterface<TokenUsage> \| undefined, provider: string, turn: AgentTurn \| undefined) => AgentStop \| undefined` | Infers which of a run's three failure layers stopped it — the meter allowance, a cost budget, or the model's own token limit — and returns the stop record with the final call's readings, or `undefined` when no layer stopped the run. |
1432
- | `estimateTokens` | function | `(text: string) => number` | Estimates the context-token footprint of a string — the deterministic `ceil(length / 4)` character heuristic `estimateMessages` sums over a conversation's messages (the default context-budget estimator). |
1433
- | `estimateMessages` | function | `(messages: readonly Message[]) => number` | Estimates the context-token footprint of a batch of messages — each message's content plus `MESSAGE_TOKEN_OVERHEAD`, a tool-call JSON estimate, a thinking estimate, and `IMAGE_TOKEN_ESTIMATE` for each attached image. The `estimateRequest` message term for an agent's context budget (the `AgentOptions` `window`), a provider-independent approximation for conforming messages rather than an exact tokenizer count. |
1434
- | `estimateRequest` | function | `(request: ProviderRequest) => number` | Estimates the context-token footprint of a complete provider request — its messages through `estimateMessages`, plus the rendered advertised `tools`, plus the rendered `options.schema`. The `consumer` estimator an agent's `window` budget measures every request through, a provider-independent heuristic rather than an exact tokenizer count. |
1435
- | `measureMessage` | function | `(message: Message) => MessageMeasure` | Measures the disjoint estimate components of one message — its content, framing, rendered calls, thinking, and attached images — as the same heuristic units `estimateMessages` sums. |
1436
- | `measureRequest` | function | `(request: ProviderRequest) => RequestMeasure` | Measures the disjoint estimate components of a complete provider request — each message through `measureMessage`, plus the rendered advertised `tools` and `options.schema` — as the same heuristic units `estimateRequest` sums. |
1437
- | `settleAgentJob` | function | `(agent: AgentInterface, partial: boolean) => Promise<AgentResult>` | Runs one rehydrated agent and applies the partial-as-configurable-failure policy — a partial run throws an `AgentJobError` unless the `partial` policy allows it, and a natural finish resolves. The shared job-handler step `createAgentQueue` and `createAgentRunner` both settle each job through, so the policy can never diverge between them. |
1438
- | `handleAgentQueueJob` | function | `(registry: AgentRegistryInterface, partial: boolean, input: AgentJobInput, context: QueueContext) => Promise<AgentResult>` | Handles one queued agent job by rehydrating it through a registry with the queue attempt's signal, then applying the shared partial-result policy. |
1439
- | `assembleResult` | function | `(outcome: AgentRunResult) => AgentResult` | Assembles the settled `AgentResult` from a run's `AgentRunResult` — `thinking`, `usage`, and `stop` are carried only when the run surfaced them, and the loop-internal `exhausted` flag is left out. |
1440
- | `denyCall` | function | `(call: ToolCall, reason: string \| undefined) => ToolResult` | Synthesizes the denial `ToolResult` a blocked call is fed back with — the call's `id` / `name` keyed back, carrying a denial `error` instead of a value. |
1441
- | `renderArguments` | function | `(value: Readonly<Record<string, unknown>>) => string \| undefined` | Renders a tool call's arguments as escaped canonical JSON text — sorted keys, with every control, format, line-separator, and paragraph-separator code point written as `\uXXXX` — or returns `undefined` when they cannot be rendered. |
1442
- | `resolveDecision` | function | `(decision: AuthorityDecision, definition: ToolDefinition \| undefined) => AuthorityDecision` | Applies the `consequential` floor to one `AuthorityDecision` — an `allow` for a tool whose advertised definition is annotated `consequential` becomes an `ask`. |
1443
- | `chargeUsage` | function | `(budget: BudgetInterface<TokenUsage> \| undefined, usage: TokenUsage, charged: number) => void` | Consumes a reported usage against a budget over what was already charged, so a turn's total draw is never less than the report and nothing is charged twice. |
1444
- | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a nonnegative safe integer, or throws a coded error. |
1445
- | `requireBudget` | function | `(value: BudgetInterface<TokenUsage> \| undefined, key: 'budget' \| 'allowance') => BudgetInterface<TokenUsage> \| undefined` | Returns a run's budget or allowance after checking it implements `BudgetInterface`, or throws a coded error before the run starts it. |
1446
- | `requireConversation` | function | `(value: unknown) => ConversationInterface \| undefined` | Returns a run's `conversation` option after checking it implements `ConversationInterface`, or throws a coded error before the run starts. |
1447
- | `renderToolValue` | function | `(value: unknown) => string` | Renders a tool's output as the string content of its tool message. |
1448
- | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1449
- | `extractQueueOptions` | function | `(options: Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>) => Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>` | Extracts the present concurrency, retry, and deadline options for an agent job queue. |
1484
+ | Name | Kind | Signature | Summary |
1485
+ | --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1486
+ | `agentResultToJSON` | function | `(value: unknown) => JSONValue \| undefined` | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a negative or non-finite usage number, a throwing getter, or a malformed or revoked proxy. |
1487
+ | `tokenUsageToJSON` | function | `(value: unknown) => TokenUsage \| undefined` | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing, negative, or non-finite count, a throwing getter, or a malformed or revoked proxy. |
1488
+ | `agentChunkToFrame` | function | `(chunk: AgentChunk) => AgentFrame \| undefined` | Projects one `AgentChunk` onto the `AgentFrame` a page receives, member by member, or returns `undefined` for an `ask` chunk. |
1489
+ | `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
1490
+ | `agentStreamToFrames` | function | `(stream: AgentStreamInterface, approver: ApproverInterface \| undefined) => AsyncGenerator<AgentFrame, void, undefined>` | Projects a run's live handle onto the frames a page receives — one frame per projected chunk, in order, then exactly one terminal `finish` or `error`, last. |
1491
+ | `inferStop` | function | `(reason: unknown, allowance: BudgetInterface<TokenUsage> \| undefined, budget: BudgetInterface<TokenUsage> \| undefined, provider: string, turn: AgentTurn \| undefined) => AgentStop \| undefined` | Infers which of a run's three failure layers stopped it — the meter allowance, a cost budget, or the model's own token limit — and returns the stop record with the final call's readings, or `undefined` when no layer stopped the run. |
1492
+ | `estimateTokens` | function | `(text: string) => number` | Estimates the context-token footprint of a string — the deterministic `ceil(length / 4)` character heuristic `estimateMessages` sums over a conversation's messages (the default context-budget estimator). |
1493
+ | `estimateMessages` | function | `(messages: readonly Message[]) => number` | Estimates the context-token footprint of a batch of messages — each message's content plus `MESSAGE_TOKEN_OVERHEAD`, a tool-call JSON estimate, a thinking estimate, and `IMAGE_TOKEN_ESTIMATE` for each attached image. The `estimateRequest` message term for an agent's context budget (the `AgentOptions` `window`), a provider-independent approximation for conforming messages rather than an exact tokenizer count. |
1494
+ | `estimateRequest` | function | `(request: ProviderRequest) => number` | Estimates the context-token footprint of a complete provider request — its messages through `estimateMessages`, plus the rendered advertised `tools`, plus the rendered `options.schema`. The `consumer` estimator an agent's `window` budget measures every request through, a provider-independent heuristic rather than an exact tokenizer count. |
1495
+ | `measureMessage` | function | `(message: Message) => MessageMeasure` | Measures the disjoint estimate components of one message — its content, framing, rendered calls, thinking, and attached images — as the same heuristic units `estimateMessages` sums. |
1496
+ | `measureRequest` | function | `(request: ProviderRequest) => RequestMeasure` | Measures the disjoint estimate components of a complete provider request — each message through `measureMessage`, plus the rendered advertised `tools` and `options.schema` — as the same heuristic units `estimateRequest` sums. |
1497
+ | `settleAgentJob` | function | `(agent: AgentInterface, partial: boolean) => Promise<AgentResult>` | Runs one rehydrated agent and applies the partial-as-configurable-failure policy — a partial run throws an `AgentJobError` unless the `partial` policy allows it, and a natural finish resolves. The shared job-handler step `createAgentQueue` and `createAgentRunner` both settle each job through, so the policy can never diverge between them. |
1498
+ | `handleAgentQueueJob` | function | `(registry: AgentRegistryInterface, partial: boolean, input: AgentJobInput, context: QueueContext) => Promise<AgentResult>` | Handles one queued agent job by rehydrating it through a registry with the queue attempt's signal, then applying the shared partial-result policy. |
1499
+ | `assembleResult` | function | `(outcome: AgentRunResult) => AgentResult` | Assembles the settled `AgentResult` from a run's `AgentRunResult` — `thinking`, `usage`, and `stop` are carried only when the run surfaced them, and the loop-internal `exhausted` flag is left out. |
1500
+ | `denyCall` | function | `(call: ToolCall, reason: string \| undefined) => ToolResult` | Synthesizes the denial `ToolResult` a blocked call is fed back with — the call's `id` / `name` keyed back, carrying a denial `error` instead of a value. |
1501
+ | `renderArguments` | function | `(value: Readonly<Record<string, unknown>>) => string \| undefined` | Renders a tool call's arguments as escaped canonical JSON text — sorted keys, with every control, format, line-separator, and paragraph-separator code point written as `\uXXXX` — or returns `undefined` when they cannot be rendered. |
1502
+ | `resolveDecision` | function | `(decision: AuthorityDecision, definition: ToolDefinition \| undefined) => AuthorityDecision` | Applies the `consequential` floor to one `AuthorityDecision` — an `allow` for a tool whose advertised definition is annotated `consequential` becomes an `ask`. |
1503
+ | `chargeUsage` | function | `(budget: BudgetInterface<TokenUsage> \| undefined, usage: TokenUsage, charged: number) => void` | Consumes a reported usage against a budget over what was already charged, so a turn's total draw is never less than the report and nothing is charged twice. |
1504
+ | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a positive safe integer, or throws a coded error. |
1505
+ | `requireAnswer` | function | `(content: string, schema: Readonly<Record<string, unknown>>) => void` | Checks a run's final answer against its schema: the content must parse as JSON and satisfy the schema, or the call throws a coded error carrying the faults. |
1506
+ | `settleToolResult` | function | `(result: ToolResult) => { readonly outcome: ToolResult; readonly content: string; }` | Settles one dispatched result into the result the loop reports and the content of its tool message, turning a success whose value JSON cannot carry into a tool failure the model reads. |
1507
+ | `requireFallback` | function | `(options: AuthorityOptions) => AuthorityDecision` | Returns an authority's no-match decision after checking the options carry one, or throws a coded error naming the two fallbacks a host chooses between. |
1508
+ | `requireRules` | function | `(rules: readonly AuthorityRule[] \| undefined) => readonly AuthorityRule[]` | Returns an authority's rules after checking each one names a verdict, or throws a coded error naming the first rule that does not. |
1509
+ | `requireBudget` | function | `(value: BudgetInterface<TokenUsage> \| undefined, key: 'budget' \| 'allowance') => BudgetInterface<TokenUsage> \| undefined` | Returns a run's budget or allowance after checking it implements `BudgetInterface`, or throws a coded error before the run starts it. |
1510
+ | `requireConversation` | function | `(value: unknown) => ConversationInterface \| undefined` | Returns a run's `conversation` option after checking it implements `ConversationInterface`, or throws a coded error before the run starts. |
1511
+ | `renderToolValue` | function | `(value: unknown) => string \| undefined` | Renders a tool's output as the string content of its tool message, or returns `undefined` when JSON cannot carry it. |
1512
+ | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1513
+ | `extractQueueOptions` | function | `(options: Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>) => Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>` | Extracts the present concurrency, retry, and deadline options for an agent job queue. |
1450
1514
 
1451
1515
  The measures are structural estimates, not tokenizer allocations. A message's `id` and `role` join a measure back to its message and are not token components, and a provider's template effects and the estimation error are not individually attributed.
1452
1516
 
@@ -1490,6 +1554,7 @@ The following table lists the guards the agents module declares:
1490
1554
 
1491
1555
  | Name | Kind | Signature | Summary |
1492
1556
  | --------------------- | -------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1557
+ | `isAuthorityVerdict` | function | `(value: unknown) => value is AuthorityVerdict` | Checks whether a value is an authority verdict: `allow`, `ask`, or `deny`. |
1493
1558
  | `isAuthorityDecision` | function | `(value: unknown) => value is AuthorityDecision` | Checks whether a value is an authority decision: an object whose `zone` is a string, whose `verdict` is `allow`, `ask`, or `deny`, and whose `reason` is absent or a string. |
1494
1559
 
1495
1560
  ### Ledgers module
@@ -1500,53 +1565,53 @@ The `ledgers` module serves a conversation through event-sourced records: the `L
1500
1565
 
1501
1566
  The following table lists the types the ledger declares, each with its shape:
1502
1567
 
1503
- | Name | Kind | Signature | Summary |
1504
- | ------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1505
- | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1506
- | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1507
- | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1508
- | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1509
- | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1510
- | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1511
- | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1512
- | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1513
- | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1514
- | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1515
- | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1516
- | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1517
- | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
1518
- | `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
1519
- | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1520
- | `LedgerIndex` | interface | `{ ids, aliases, carriers, names, words, keys, ranks }` | Carries a registry prepared for matching: its ids, each owner name's owners, and the compiled needles. |
1521
- | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1522
- | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1523
- | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, correction?, agent?, snapshot? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, snapshot, recall limit, correction filter, and agent options. |
1524
- | `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
1525
- | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1526
- | `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), calibrate(), snapshot() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1527
- | `LedgerRequestInterface` | interface | `{ message, plan, selection, boundary, usage, calls, attempts, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), lines() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing attempts and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
1528
- | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1529
- | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1530
- | `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
1531
- | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1532
- | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1533
- | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1534
- | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1535
- | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1536
- | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1537
- | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1538
- | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1539
- | `ClassifierOptions` | interface | `{ conversation, judge, questions, topics, thresholds, assign, entities, correction?, scheduler? }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, the ledger's handlers, and the optional correction filter and scheduler. |
1540
- | `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
1541
- | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1542
- | `ClassifierAttempt` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
1543
- | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1544
- | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1545
- | `GaugeCall` | interface | `{ estimate, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1546
- | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1547
- | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1548
- | `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names the planning group of a source the records render: a topic match, an off-topic rule or correction, or a name match. |
1549
- | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT'` | Names the machine-readable conditions a `LedgerError` error reports. |
1568
+ | Name | Kind | Signature | Summary |
1569
+ | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1570
+ | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1571
+ | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1572
+ | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1573
+ | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1574
+ | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1575
+ | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1576
+ | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1577
+ | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1578
+ | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1579
+ | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1580
+ | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1581
+ | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1582
+ | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
1583
+ | `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
1584
+ | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1585
+ | `LedgerIndex` | interface | `{ ids, aliases, carriers, names, words, keys, ranks }` | Carries a registry prepared for matching: its ids, each owner name's owners, and the compiled needles. |
1586
+ | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1587
+ | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'strict'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1588
+ | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, correction?, agent?, snapshot? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, snapshot, recall limit, correction filter, and agent options. |
1589
+ | `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
1590
+ | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1591
+ | `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), calibrate(), snapshot() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1592
+ | `LedgerRequestInterface` | interface | `{ fault(), faulted(), message, plan, selection, boundary, usage, calls, attempts, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), lines() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing attempts and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
1593
+ | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1594
+ | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1595
+ | `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
1596
+ | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1597
+ | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1598
+ | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1599
+ | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1600
+ | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1601
+ | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1602
+ | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1603
+ | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1604
+ | `ClassifierOptions` | interface | `{ strict?, conversation, judge, questions, topics, thresholds, assign, entities, correction?, scheduler? }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, the ledger's handlers, and the optional correction filter and scheduler. |
1605
+ | `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
1606
+ | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1607
+ | `ClassifierAttempt` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
1608
+ | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1609
+ | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1610
+ | `GaugeCall` | interface | `{ estimate, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1611
+ | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1612
+ | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1613
+ | `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names the planning group of a source the records render: a topic match, an off-topic rule or correction, or a name match. |
1614
+ | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION'` | Names the machine-readable conditions a `LedgerError` error reports. |
1550
1615
 
1551
1616
  #### Constants
1552
1617
 
@@ -1574,10 +1639,10 @@ The following table lists the constants that hold the ledger's categories, recor
1574
1639
 
1575
1640
  The following table lists the error the ledger raises and the guard that narrows it:
1576
1641
 
1577
- | Name | Kind | Signature | Summary |
1578
- | --------------- | -------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
1579
- | `LedgerError` | class | `new (code: LedgerErrorCode, message: string) => LedgerError` | Reports an invalid ledger configuration, failed calibration, or unowned request selection, carrying the machine-readable `code`. |
1580
- | `isLedgerError` | function | `(value: unknown) => value is LedgerError` | Narrows an unknown caught value to a `LedgerError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1642
+ | Name | Kind | Signature | Summary |
1643
+ | --------------- | -------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
1644
+ | `LedgerError` | class | `new (code: LedgerErrorCode, message: string, options?: CodedErrorOptions) => LedgerError` | Reports an invalid ledger configuration, failed calibration, or unowned request selection, carrying the machine-readable `code`. |
1645
+ | `isLedgerError` | function | `(value: unknown) => value is LedgerError` | Narrows an unknown caught value to a `LedgerError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1581
1646
 
1582
1647
  #### Factories
1583
1648
 
@@ -1602,11 +1667,14 @@ The following table lists the classes that serve, file, and price a conversation
1602
1667
 
1603
1668
  The following guards validate ledger fractions, capacity, and snapshots:
1604
1669
 
1605
- | Name | Kind | Signature | Summary |
1606
- | ----------------------- | -------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------- |
1607
- | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1608
- | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1609
- | `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
1670
+ | Name | Kind | Signature | Summary |
1671
+ | ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1672
+ | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1673
+ | `isLedgerQuestion` | function | `(value: unknown) => value is LedgerQuestion` | Checks whether a value holds the wording a ledger files with: a choice `category` question whose criteria describe every category, a non-empty `topic` string, and noul `amends` and `supersedes` questions. |
1674
+ | `ledgerSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; sections: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; judgments: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>>>; }, boolean \| ContractShape>; requests: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; notes: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; failures: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; gauge: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ scale: import("@orkestrel/contract").NumberShape; overhead: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a ledger snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
1675
+ | `ledgerSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ conversation: Readonly<{ id: string; sections: readonly Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>[]; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { judgments?: readonly (Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>)[]; }>; requests: readonly string[]; notes: readonly string[]; failures: readonly string[]; } & { gauge?: Readonly<{ scale: number; overhead: number; } & {}>; }>>` | Reads the faults of a refused ledger snapshot. |
1676
+ | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1677
+ | `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
1610
1678
 
1611
1679
  #### Helpers
1612
1680
 
@@ -1957,14 +2025,14 @@ failed.fail(new Error('upstream died')) // the 2 is delivered, then the drain th
1957
2025
 
1958
2026
  The policy gate the agent loop consults before each tool call. `evaluate` is synchronous; the optional `ask` answers an `ask` verdict asynchronously. It has no data members.
1959
2027
 
1960
- | Method | Returns | Summary |
1961
- | ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1962
- | `evaluate` | `AuthorityDecision` | Evaluates one tool call against the ordered rules — returns the first matching rule's verdict, which allows when the rule names none, or the fallback when none match. |
1963
- | `ask` | `Promise<boolean>` | Resolves `true` to approve one asked call; absent, every ask reads as unanswered. |
2028
+ | Method | Returns | Summary |
2029
+ | ---------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
2030
+ | `evaluate` | `AuthorityDecision` | Evaluates one tool call against the ordered rules — returns the first matching rule's verdict, or the fallback when none match. |
2031
+ | `ask` | `Promise<boolean>` | Resolves `true` to approve one asked call; absent, every ask reads as unanswered. |
1964
2032
 
1965
2033
  #### `ApproverInterface`
1966
2034
 
1967
- The server half of a page's approval. Its `ask` is a readonly data member that holds the bound `AuthorityHandler`, so `createAuthority({ rules, ask: approver.ask })` wires it; `frame` reads a waiting ask's `ask` frame for the page, and `answer` settles that ask from the page's `AgentAnswer`.
2035
+ The server half of a page's approval. Its `ask` is a readonly data member that holds the bound `AuthorityHandler`, so `createAuthority({ rules, fallback, ask: approver.ask })` wires it; `frame` reads a waiting ask's `ask` frame for the page, and `answer` settles that ask from the page's `AgentAnswer`.
1968
2036
 
1969
2037
  | Method | Returns | Summary |
1970
2038
  | -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -2028,22 +2096,22 @@ A conversation that owns its live message tail directly (the flat store verbs fo
2028
2096
  | `reference` | `string` | Renders this conversation as a self-labeled, fenced provenance block to pull into another conversation — a pure string with no model call: a leading `[Reference — conversation "<label>" — NOT part of this conversation]` marker, then the cherry-picked excerpts (`- role: content`) when `messages` is supplied. The `label` option names the source. Default: the `id`. |
2029
2097
  | `snapshot` | `ConversationSnapshot` | Serializes this conversation to a plain, JSON-serializable `ConversationSnapshot` — its `id`, the compacted `sections`, and the live tail; the live `summarize` / `keep` are configuration re-supplied on hydrate rather than serialized. |
2030
2098
 
2031
- A supplied `sections` cap must satisfy `>= 1`; `NaN` throws `ConversationError` with code `SECTIONS` before a fold starts. A successful capped merge retains at most `Math.ceil(sections)` entries. An absent cap, fractional caps `>= 1`, and positive infinity retain their existing behavior. A supplied `keep` must be a nonnegative safe integer; any other value throws `ConversationError` with code `KEEP`, carrying the value as `context.keep`, before a fold starts. `compact()` calls run one at a time. A `remove` or `clear` during the initial summarizer leaves no section. `CompactOptions.signal` rejects a call with its reason at once and commits nothing after the abort; a fold committed before an aborted overflow merge stays. A summarizer digest whose trimmed text is empty rejects with `ConversationError` code `SUMMARY`: a fold commits nothing, and a refused overflow merge leaves the appended section.
2099
+ A supplied `sections` cap must be a positive safe integer; any other value throws `ConversationError` with code `SECTIONS` before a fold starts. A successful capped merge retains at most `sections` entries. An absent cap leaves the sections unbounded. A supplied `keep` must be a nonnegative safe integer; any other value throws `ConversationError` with code `KEEP`, carrying the value as `context.keep`, before a fold starts. `compact()` calls run one at a time. A `remove` or `clear` during the initial summarizer leaves no section. `CompactOptions.signal` rejects a call with its reason at once and commits nothing after the abort; a fold committed before an aborted overflow merge stays. A summarizer digest whose trimmed text is empty rejects with `ConversationError` code `SUMMARY`: a fold commits nothing, and a refused overflow merge leaves the appended section.
2032
2100
 
2033
2101
  #### `ConversationManagerInterface`
2034
2102
 
2035
- The id-keyed registry of `Conversation` instances with an active pointer. `add(input?)` mints a conversation (flowing the manager's default `summarize` / `keep` in unless the input overrides them) and auto-activates the first one; a later `add` leaves `active` unchanged. `add` forwards the input's `on` hooks and `error` handler to the conversation's emitter, so a throwing listener reports to that handler. `open(id)` returns the conversation registered under `id` while its store read was pending rather than overwriting it, and resolves `undefined` for a stored snapshot whose `id` is not `id`. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, and the registry and `active` stay unchanged. `switch(id)` re-points `active` (an unknown `id` returns `undefined`, leaving `active` unchanged — lenient, never throws); `remove` carries batch overloads and clears `active` when the removed conversation was active. The `count` and `active` data members stay Surface rows (`active` is a `readonly` accessor — a property, not a method); the manager is event-free (each conversation owns its `emitter`).
2103
+ The id-keyed registry of `Conversation` instances with an active pointer. `add(input?)` mints a conversation (flowing the manager's default `summarize` / `keep` in unless the input overrides them) and auto-activates the first one; a later `add` leaves `active` unchanged, and `add` of an `id` already live throws `ConversationError` `'ID'`, so a live conversation is never replaced. `add` forwards the input's `on` hooks and `error` handler to the conversation's emitter, so a throwing listener reports to that handler. `open(id)` returns the conversation registered under `id` while its store read was pending rather than overwriting it, and rejects with `ConversationError` `'SNAPSHOT'` for a stored snapshot whose `id` is not `id`. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, and the registry and `active` stay unchanged. `switch(id)` re-points `active` (an unknown `id` returns `undefined`, leaving `active` unchanged — lenient, never throws); `remove` carries batch overloads and clears `active` when the removed conversation was active. The `count` and `active` data members stay Surface rows (`active` is a `readonly` accessor — a property, not a method); the manager is event-free (each conversation owns its `emitter`).
2036
2104
 
2037
- | Method | Returns | Summary |
2038
- | --------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2039
- | `conversation` | `ConversationInterface \| undefined` | Looks up one conversation by id (`undefined` when absent). |
2040
- | `conversations` | `readonly ConversationInterface[]` | Lists every conversation, in insertion order. |
2041
- | `add` | `ConversationInterface` | Mints a conversation, taking its `id` from the input or a fresh UUID and flowing the default `summarize` / `keep` of the manager in unless the input overrides them — auto-activates the first, and an already-present `id` overwrites, last write wins. |
2042
- | `switch` | `ConversationInterface \| undefined` | Re-points `active` at the conversation with `id` and returns it; an unknown `id` returns `undefined` and leaves `active` unchanged, never throwing. |
2043
- | `open` | `Promise<ConversationInterface \| undefined>` | Resolves a conversation by id and activates it — from the registry when present, else hydrated from the optional `ConversationStoreInterface` (`store`); `undefined` when it is neither registered nor stored. |
2044
- | `save` | `Promise<boolean>` | Persists a registered conversation's `ConversationInterface.snapshot` to the optional `ConversationStoreInterface` (`store`) — `true` when persisted, `false` when there is no store or the id is unknown; a store failure propagates. |
2045
- | `remove` | `boolean` | Removes one conversation by id, or a batch — `true` only when every supplied id was removed; clears `active` when a removed conversation was the active one. |
2046
- | `clear` | `void` | Removes every conversation and clears `active`. |
2105
+ | Method | Returns | Summary |
2106
+ | --------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2107
+ | `conversation` | `ConversationInterface \| undefined` | Looks up one conversation by id (`undefined` when absent). |
2108
+ | `conversations` | `readonly ConversationInterface[]` | Lists every conversation, in insertion order. |
2109
+ | `add` | `ConversationInterface` | Mints a conversation, taking its `id` from the input or a fresh UUID and flowing the default `summarize` / `keep` of the manager in unless the input overrides them — auto-activates the first, and an already-present `id` throws. |
2110
+ | `switch` | `ConversationInterface \| undefined` | Re-points `active` at the conversation with `id` and returns it; an unknown `id` returns `undefined` and leaves `active` unchanged, never throwing. |
2111
+ | `open` | `Promise<ConversationInterface \| undefined>` | Resolves a conversation by id and activates it — from the registry when present, else hydrated from the optional `ConversationStoreInterface` (`store`); `undefined` when it is neither registered nor stored. |
2112
+ | `save` | `Promise<boolean>` | Persists a registered conversation's `ConversationInterface.snapshot` to the optional `ConversationStoreInterface` (`store`) — `true` when persisted, `false` when there is no store or the id is unknown; a store failure propagates. |
2113
+ | `remove` | `boolean` | Removes one conversation by id, or a batch — `true` only when every supplied id was removed; clears `active` when a removed conversation was the active one. |
2114
+ | `clear` | `void` | Removes every conversation and clears `active`. |
2047
2115
 
2048
2116
  #### `ConversationStoreInterface`
2049
2117
 
@@ -2093,6 +2161,8 @@ The state of one `respond` call. The ledger creates one request per call and dro
2093
2161
  | --------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
2094
2162
  | `enter` | `Message` | Appends the request's content to a conversation as a user message, once, and holds it as `message`. |
2095
2163
  | `open` | `void` | Opens a pass, which becomes the current pass. |
2164
+ | `fault` | `void` | Records an error the request's run reported through its `fault` event. |
2165
+ | `faulted` | `boolean` | Reports whether the request's run reported this error through its `fault` event. |
2096
2166
  | `adopt` | `void` | Records the selection the current pass's run adopted and adds the usage it spent. |
2097
2167
  | `observe` | `void` | Starts a gauge call in the current pass, making that pass's call in flight final. |
2098
2168
  | `spend` | `void` | Adds one call's reported usage to the current pass and records it on the call in flight. |
@@ -2124,6 +2194,9 @@ const selection: Selection = {
2124
2194
  }
2125
2195
  request.adopt(selection, conversation.count)
2126
2196
  request.observe({ estimate: 40, tools: 2 }, conversation.count)
2197
+ const failure = new Error('the judge is unreachable')
2198
+ request.fault(failure)
2199
+ request.faulted(failure) // true — the request's run reported this error through its `fault` event
2127
2200
  request.spend({ prompt: 52, completion: 8, total: 60 })
2128
2201
  request.usage // { prompt: 82, completion: 10, total: 92 } — the selection's usage and the call's
2129
2202
  request.calls // [{ estimate: 40, tools: 2, prompt: 52, completion: 8 }] — the call in flight took its usage
@@ -2177,15 +2250,15 @@ These invariants hold across `src/core` ↔ `agent.md`:
2177
2250
  - **The message-store contract (`MessageManagerInterface`).** Every `ConversationInterface`, the `context.messages` conversation included, satisfies `MessageManagerInterface` structurally. `add` mints each message's `id`, carries `calls` only when supplied, and returns the stored immutable message that `message(id)` later resolves; `remove` reports `true` only when every supplied id was removed.
2178
2251
  - **The richer turn context (`AgentContext`).** `AgentContext` composes the optional `system` prompt, the `instructions`, `skills`, `memos`, `workspaces`, and `conversations` managers, `messages`, the `tools` registry, and a readonly active `scope`, creating each omitted manager fresh. `build()` folds the system prompt, the scope-filtered instructions, and the scope-filtered skills index into one leading `system` message, renders the scope-filtered memos index and the active workspace's scope-filtered text files into one `user` context message after it, then appends the active conversation's `view()`, or a passed selection's `messages`. The `system` message holds host-authored text alone. It never reads `tools`, never mutates a manager or a stored message, and builds fresh on each call.
2179
2252
  - **Scope filtering.** A scope holds one three-way allow-list per category (`instructions` by `name`, `skills` by `name`, `memos` by `name`, `tools` by `name`, `files` by `path`), applied through `filterAllowList`, and `narrow` intersects each list, so narrowing only tightens. The scope's filters never touch messages; message inclusion is the conversation's through compaction and, when a handler is set, the selection's. The loop filters the advertised definitions by `scope.tools`, so a scoped-out tool is neither described nor callable, and `build()` never contains a tool's name or schema.
2180
- - **The agent loop (`Agent` / `createAgent`).** `Agent` builds the provider input, then iterates up to `limit`: stream a turn, fold its usage, append any assistant tool calls, and dispatch them. Each `ToolResult` becomes a tool message whose `call` names the paired call, in the reply's call order, because ids can repeat; a string value is the content unchanged, `undefined` is `''`, another value is its `JSON.stringify` text, or `String(value)` when JSON can't carry it, and a failure's content is its `error`. A reply with no tool calls ends the loop.
2253
+ - **The agent loop (`Agent` / `createAgent`).** `Agent` builds the provider input, then iterates up to `limit`: stream a turn, fold its usage, append any assistant tool calls, and dispatch them. Each `ToolResult` becomes a tool message whose `call` names the paired call, in the reply's call order, because ids can repeat; a string value is the content unchanged, `undefined` is `''`, another value is its `JSON.stringify` text, a value JSON can't carry becomes a tool failure the model reads, and a failure's content is its `error`. A reply with no tool calls ends the loop.
2181
2254
  - **One run shared by `generate` and `stream`.** `generate` drains the private run `stream` exposes, so a `generate` result deep-equals a drained `stream` on the same input.
2182
2255
  - **The `AgentChunk` stream.** `stream().events` yields, per turn, each answer delta as `token`, each reasoning delta as `think`, then optional `usage`, then one `ask` chunk per asked call, then one `tool` chunk per dispatched call. `result` resolves the settled `AgentResult`: the content, the joined thinking, the summed optional usage, `partial`, and the optional `stop`. A `usage` chunk carries the call's streamed-answer `estimate` beside its usage.
2183
2256
  - **Bounded, paced, capped.** Each run folds the external `signal`, the `timeout`, and the `budget` and `allowance` signals into one cancel; a cancel resolves `{ partial: true, content }` with what streamed, while a genuine provider or tool error rejects `result` and sets `status` to `error`. `scheduler.yield` runs between turns and never after the last, and `limit` caps tool iteration.
2184
2257
  - **Pull and push observation on the `Agent`; the rest event-free.** The provider contract, the conversation registry, and the context carry no emitter, while the instruction and scope managers and each conversation own one. The `Agent` pairs the `AgentChunk` stream with an `emitter` over `AgentEventMap` (`start`, `turn`, `tool`, `usage`, `allow`, `ask`, `deny`, `finish`, `error`, `abort`, `exhaust`, `fault`, `select`) and has no `token` or `think` event. The emitter routes a listener throw to the `error` option, and a cancelled run emits `abort` then `finish`.
2185
2258
  - **Doc ↔ source method bijection.** The `## Methods` tables list exactly the call-signature members of every interface named there, and each implementing class exposes exactly its interface's methods.
2186
- - **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins, a matched rule allowing unless its `verdict` is `ask` or `deny`, and returns the `fallback` when none match, which defaults to `{ zone: DEFAULT_AUTHORITY_ZONE, verdict: 'allow' }`. `evaluate` is synchronous. `ask(context, decision, signal)` resolves the `ask` option's answer and rejects with an `AgentError` coded `'APPROVER'` when no handler is set. The gate is event-free.
2187
- - **A denied call is fed back, never executed.** The loop consults `authority`, or a default `Authority` when none is set, after scope admits a call. A call no definition advertises is denied with the scope note before the authority evaluates it, under every verdict, and its `deny` event carries no decision. A `deny` verdict, and an `ask` the approver refuses or leaves unanswered, become the failure arm `{ success: false, id, name, error }` without running the tool. A call that `allow` cleared whose tool is replaced or removed before dispatch is denied too: the model reads the `denied` note of `AUTHORITY_NOTES`, and its `deny` event carries the reason `<name> changed after its decision` and no decision. Executed results and denials merge in the reply's call order, each producing a `tool` chunk and a tool message.
2188
- - **Durable, serializable agent jobs (`AgentJobInput` + `AgentRegistry`).** An `AgentJobInput` names its `provider`, `tools`, `authority`, and `scheduler` and carries its data directly, and `AgentRegistry.build(input, signal?)` rehydrates a seeded, signal-wired `Agent` from the named pools. An unknown name throws `AgentError` with code `REGISTRY` and the message `unknown <category>: <name>`.
2259
+ - **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins, returning the matched rule's `verdict`, and returns the required `fallback` when none match. A missing `fallback` or a rule with no `verdict` throws `AgentError` coded `'AUTHORITY'` at construction. `evaluate` is synchronous. `ask(context, decision, signal)` resolves the `ask` option's answer and rejects with an `AgentError` coded `'APPROVER'` when no handler is set. The gate is event-free.
2260
+ - **A denied call is fed back, never executed.** The loop consults `authority` after scope admits a call, and denies the call when the agent holds none, which only a tool added later to an agent built with no `tools` can reach. A call no definition advertises is denied with the scope note before the authority evaluates it, under every verdict, and its `deny` event carries no decision. A `deny` verdict, and an `ask` the approver refuses or leaves unanswered, become the failure arm `{ success: false, id, name, error }` without running the tool. A call that `allow` cleared whose tool is replaced or removed before dispatch is denied too: the model reads the `denied` note of `AUTHORITY_NOTES`, and its `deny` event carries the reason `<name> changed after its decision` and no decision. Executed results and denials merge in the reply's call order, each producing a `tool` chunk and a tool message.
2261
+ - **Durable, serializable agent jobs (`AgentJobInput` + `AgentRegistry`).** An `AgentJobInput` names its `provider`, `tools`, `authority`, and `scheduler` and carries its data directly, and `AgentRegistry.build(input, signal?)` checks it exactly against `agentJobContract`, throwing `AgentError` with code `REGISTRY` and the faults on a misspelled key, then rehydrates a seeded, signal-wired `Agent` from the named pools. An unknown name throws `AgentError` with code `REGISTRY` and the message `unknown <category>: <name>`, and a job that names `tools` and no `authority` throws the same code at `build`.
2189
2262
  - **Partial is a configurable failure (`partial`).** A durable job's handler throws `AgentJobError` carrying the partial `AgentResult` unless `partial: true`, which resolves the partial as success. `isAgentJobError` narrows a caught value.
2190
2263
  - **Concurrency, retries, and persistence come from the substrate.** `createAgentQueue` composes `createQueue` and `createAgentRunner` composes `createRunner`, adding only rehydration through the registry and the partial policy.
2191
2264
  - **Sub-agent fan-out through `controller.spawn`.** A runner job's handler spawns each declared child through `controller.spawn`, and the child runs as a sub-agent beside the parent. Both pass their signal into `registry.build`, so a queue or runner cancel commits the rehydrated agent's partial. A unit spawns its declared children on its first attempt only, so a retried parent never runs a child twice: the runner's handler is the `execute` method of one `AgentFanout`, which records each unit it fanned out.
@@ -2193,15 +2266,15 @@ These invariants hold across `src/core` ↔ `agent.md`:
2193
2266
  - **The context's default conversation and a run's conversation.** `context.messages` is the `conversations` registry's active conversation, always defined and read on each access, so it follows `conversations.switch(id)`. A run binds its conversation once, at its `stream()` or `generate()` call: `AgentRunOptions.conversation`, else the active one. The run appends `AgentRunOptions.prompt` to that conversation as a `user` turn after its guards, or reads its request from the conversation's tail when it has no `prompt`, then selects and builds over its `view()`, appends every assistant and tool message to it, and folds it under `window`, so a later `switch`, `open`, `remove`, `clear`, or same-id `add` never moves a live run, and the conversation needs no registration.
2194
2267
  - **Automatic compaction (the context `window` budget).** With `AgentOptions.window` set and a summarizable run conversation, the loop measures each request it will send, with its messages after the `replay` policy, its advertised tools, and its per-call `options`, against the window before the first provider request and between turns, and compacts and rebuilds when the window is exhausted. A summarizer throw emits `fault` and the run continues over-window unless `strict` is set, and a fold that compacts nothing between turns while over the window stops auto-compaction for the rest of the run. A run whose signal aborted by the end of tool dispatch folds nothing before it settles. When no selection handler runs, and either `window` is absent or the run's conversation has no summarizer, the loop adds no `await` before the first provider request.
2195
2268
  - **Active workspace rendering by carrier.** `build()` reads only the active workspace, filters its files through `scope.files`, renders text files under `WORKSPACE_SECTION_HEADER` through `renderFencedFile` into one `user` context message with a minted id, which is never stored, and attaches the base64 data of binary `image/` files to a copy of the last user message of the conversation. With no active workspace, or no text file, the context message holds the memos index alone, and with no memos index either, no context message renders.
2196
- - **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, sections, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events. `MemoryConversationStore` keeps snapshots in a map and `DatabaseConversationStore` in one opaque JSON column narrowed by `isConversationSnapshot`, both through `get`, `set`, and `delete`. `open(id)` activates a registry hit or hydrates a store hit, keeps a conversation registered under `id` during the store read, and refuses a snapshot whose `id` is not `id`; `DatabaseConversationStore.get` refuses such a row too. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, the registry and `active` unchanged. `save(id)` returns `false` when no store or conversation exists. `MemoStoreInterface` is the memo twin: `MemoryMemoStore` and `DatabaseMemoStore` persist a `MemoSnapshot` by its memo set id through `get`, `set`, and `delete`, and the host authors what it stores, because a memo can be model-written and a stored memo set hydrates as written after `isMemoSnapshot` accepts it.
2269
+ - **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, sections, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events. `MemoryConversationStore` keeps snapshots in a map and `DatabaseConversationStore` in one opaque JSON column narrowed by `isConversationSnapshot`, both through `get`, `set`, and `delete`. `open(id)` activates a registry hit or hydrates a store hit, keeps a conversation registered under `id` during the store read, and throws `ConversationError` `'SNAPSHOT'` on a snapshot whose `id` is not `id`; `DatabaseConversationStore.get` throws the same code on such a row and on a row that fails the guard, and `set` refuses what `get` would. `add` throws `ConversationError` `'ID'` on an id already live. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, the registry and `active` unchanged. `save(id)` returns `false` when no store or conversation exists. `MemoStoreInterface` is the memo twin: `MemoryMemoStore` and `DatabaseMemoStore` persist a `MemoSnapshot` by its memo set id through `get`, `set`, and `delete`, and the host authors what it stores, because a memo can be model-written and a stored memo set hydrates as written after `isMemoSnapshot` accepts it.
2197
2270
  - **Limit exhaustion, the three failure layers, and per-run options.** A run that exhausts `limit` while its last turn still requested tools settles `partial: true` and emits `exhaust` instead of `abort`. The loop charges the `allowance` mid-stream from the `estimateTokens` estimate of each turn's content, and charges the cost `budget` the reported usage after each call, net of the estimate only when the `allowance` is the `budget`, or the estimate when the call reported none, a call that failed with a genuine provider error included; it never charges twice. `AgentResult.stop` names the one layer, `meter`, `budget`, or `model`, that stopped the final provider call first. `AgentRunOptions` members override their construction defaults for one run, `conversation` and `prompt` have no construction default, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a nonnegative safe integer throws `AgentError` with code `LIMIT`.
2198
2271
  - **Construction-time context wiring.** `AgentOptions.instructions`, `skills`, `memos`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
2199
- - **`strict` — fault escalation.** With `AgentOptions.strict` set, an automatic-compaction summarizer failure and each selection fault emit `fault` and then settle the run `error`; without it, the run continues. A strict run also refuses a request still over the window with `AgentError` `'WINDOW'`, whose message reads `the request measures <consumed> against a window of <max> and this run folds no further`. A cancel at a select site wins over `strict`, and a manual `conversation.compact()` always propagates its own error.
2200
- - **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `Math.ceil(sections)` entries after a successful merge; when a fold exceeds it, the oldest sections merge into one through a summarizer call and `collapse` fires. A cap below 1 throws `ConversationError` with code `SECTIONS`, and a `keep` that is not a nonnegative safe integer throws it with code `KEEP`. A digest that is not a string or whose trimmed text is empty refuses the fold it would commit with `'SUMMARY'`; such a digest for a capped merge refuses the merge and keeps the fold already committed, one section over the cap, which the next sound merge collapses.
2272
+ - **`strict` — fault escalation.** `AgentOptions.strict` defaults to `true`: an automatic-compaction summarizer failure and each selection fault emit `fault` and then settle the run `error`, and with `strict: false` the run continues. A strict run also refuses a final answer that misses the run's `schema` with `AgentError` `'SCHEMA'`, and a request still over the window with `AgentError` `'WINDOW'`, whose message reads `the request measures <consumed> against a window of <max> and this run folds no further`. A cancel at a select site wins over `strict`, and a manual `conversation.compact()` always propagates its own error.
2273
+ - **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `sections` entries after a successful merge; when a fold exceeds it, the oldest sections merge into one through a summarizer call and `collapse` fires. A cap that is not a positive safe integer throws `ConversationError` with code `SECTIONS`, and a `keep` that is not a nonnegative safe integer throws it with code `KEEP`. A digest that is not a string or whose trimmed text is empty refuses the fold it would commit with `'SUMMARY'`; such a digest for a capped merge refuses the merge and keeps the fold already committed, one section over the cap, which the next sound merge collapses.
2201
2274
  - **`cumulative` folds.** `ConversationOptions.cumulative` and `ConversationInput.cumulative` are booleans that default to `false`; the manager holds no default and `CompactOptions` has no member. A cumulative `compact()` makes one summarizer call over the framed recaps of every prior section followed by the eligible live slice with thinking stripped, using the same cut rules and protecting the newest user exchange. After the call settles and the abort check passes, it verifies the slice and the prior sections are unchanged, then replaces all prior sections with one section holding their original messages in order followed by the slice, removes only the slice from the live tail, and emits `compact` once with no `collapse`. A throw, an abort, or a changed input commits nothing, and a fold with no eligible slice makes no call. The originals behind the recaps are never sent to the summarizer, and a hydrated snapshot with several sections folds them all at the next fold that has an eligible slice. Combining `cumulative` with a `sections` cap, whether configured, inherited from a manager, or passed to `compact()`, throws `ConversationError` with code `SECTIONS`.
2202
2275
  - **The compaction floor on one recording.** The smallest request a fold can leave holds every recap, the exchange that `keep` retains, and the new request. One recorded run reads it: a scripted support-desk conversation, one desk request per goal, on Qwen 3.5 2B `q4_K_M` on Ollama 0.40.13 on 2026-11-02 and 2026-11-03, under `keep: 2`, `strict`, and a window of 11776 tokens with 8192 tokens reserved for output, measured by a study gauge that adds 354 tokens to the estimate. That is the study's configuration and not Agent's defaults. At goal 35 the conversation held 118 folded messages of 182898 characters (median 580, 95th percentile 4913, maximum 5030), 7 recaps of 33822 characters, and 4 live messages of 17925 characters. After eight folds, with recaps of 567 to 1882 tokens summing to 8993, the rebuilt request at goal 36 measured 11940 against 11776, and the run refused it with `AgentError` `'WINDOW'` before any dispatch.
2203
2276
 
2204
- With `strict` false, the default, no error and no agent event marks that point: the loop sends the over-window request, and no reading covers the provider's behavior past its window. The `consumed` and `exhausted` members of your `window` `Budget` read the last request the loop measured, so read them after a run, or set `strict`.
2277
+ With `strict`, the default, that request throws `AgentError` `'WINDOW'`. With `strict: false`, no error and no agent event marks that point: the loop sends the over-window request, and no reading covers the provider's behavior past its window, so read the `consumed` and `exhausted` members of your `window` `Budget`, which hold the last request the loop measured, after a run.
2205
2278
 
2206
2279
  From that stop, `compact({ keep: 0 })` frees one request: with a scripted summarizer and the same text, under a gauge overhead of 352, the next request measured 10358 tokens with 9 recaps, the new recap being the recorded 2385 characters. A conversation at `keep: 0` from goal 35, whose fold at goal 36 takes 4 messages and leaves 8 recaps, measured 9750 under that recap and 11139 under a recap of 7942 characters. The sections stay, so each later fold adds a recap against the same window. Only a `sections` cap or `cumulative` lowers that smallest request, and each needs a fold with an eligible slice. At that stop under `keep: 2` the live tail is a user, an assistant, and a user message, so `compact()` folds nothing and a strict retry refuses again; the sections merge at `compact({ keep: 0 })` or at the admission of a later run whose new prompt leaves an eligible slice. The two can't combine. `cumulative` has no per-call form, so it needs a conversation rebuilt from `snapshot()` with `ConversationInput.cumulative`. A host that reserves less output can set a larger `max` on the same model.
2207
2280
 
@@ -2210,7 +2283,7 @@ These invariants hold across `src/core` ↔ `agent.md`:
2210
2283
  - **`sanitizeUsage`.** `sanitizeToken` turns a non-finite or non-positive count into `0` and floors a positive fraction, and `sanitizeUsage` applies it to each field. The loop sanitizes a provider's usage and an abort partial's usage before charging or folding it.
2211
2284
  - **`AgentError` — the concurrency guard.** `stream()` throws `AgentError` with code `CONCURRENCY` and `context: { agent }` synchronously when a run is in flight and the agent carries a `window`, or when the run's effective `budget` or `allowance` is an instance a live run holds; after those checks it throws one with `context: { agent, conversation }`, naming the conversation's id, when a live run is bound to the run's conversation. Runs holding distinct instances on distinct conversations with no `window` overlap. The refused run never starts either bound, so the live run stays bound to it. The guard compares conversation instances: two `Conversation` values opened from one stored snapshot are distinct to it and run at once on an agent with no `window` and distinct budgets, so a host opens each thread once and keys its thread registry by principal and thread. A `prompt` that is not an exact `AgentPrompt`, a `budget` or `allowance` that does not implement `BudgetInterface`, or a `conversation` that does not implement `ConversationInterface` throws `ContractError` with code `placement` before either bound starts, and a refused run appends no `prompt`. `isAgentError` narrows a caught value, and a `REGISTRY` error's `context` names the `category` and `name`.
2212
2285
  - **`agentResultToJSON` — the portable `AgentResult` projection.** The helper accepts `unknown`, never throws, reads each structural field once, and returns a fresh exact `{ content, thinking?, usage?, partial, stop? }` `JSONValue`, or `undefined` for invalid input; a malformed `stop` refuses the whole value. Finite negative and fractional usage counts are preserved, and extra fields are dropped.
2213
- - **The provider engine's request and stream.** The engine posts `JSON.stringify(encode(request))` to `url + (path ?? '')` with a JSON content type the `headers` hook can extend, decodes the body through `readChunks`, and feeds every framed record and the `finish` tail through `read`. A record whose `read` returns a `result` ends the call with that result, and with `strict: true` a stream that ends with no settled result throws `ProviderError` with code `PROTOCOL`. A non-OK body is read through `readBodyText` to at most `MAX_ERROR_BODY_LENGTH` bytes and its remainder cancelled, and each reader releases its lock on every exit.
2286
+ - **The provider engine's request and stream.** The engine posts `JSON.stringify(encode(request))` to `url + (path ?? '')` with a JSON content type the `headers` hook can extend, decodes the body through `readChunks`, and feeds every framed record and the `finish` tail through `read`. A record whose `read` returns a `result` ends the call with that result, and under the default `strict` a stream that ends with neither a settled result nor a `done` record throws `ProviderError` with code `PROTOCOL`. A non-OK body is read through `readBodyText` to at most `MAX_ERROR_BODY_LENGTH` bytes and its remainder cancelled, and each reader releases its lock on every exit.
2214
2287
  - **The wire shapes and the compiled contracts.** The shapes declare each JSON projection and the contracts compile them, each strictly narrower than its domain type, so a value JSON can't carry is refused rather than dropped and a `ToolContext` appears in no wire shape. `RelayProvider.encode` projects the request through `requestToRelay`, which reads each declared member as the request presents it: a getter runs, and an inherited declared member crosses. The clone of that projection uses property descriptors and consults no getter, prototype, or `toJSON` serializer; a non-JSON value is refused before fetching.
2215
2288
  - **The relay protocol (`createRelay` / `RelayStream` / `RelayProvider`).** The request is a `POST` of one `providerRequestContract` document, and the response is newline-delimited `RelayFrame` records under `RELAY_CONTENT_TYPE`, written under backpressure, with every upstream failure reduced to `RELAY_PROVIDER_MESSAGE`. `authorize` is mandatory and runs before the body is read; the handler answers `401`, `413` at the byte `limit`, `400`, or `502` with no body, or `422` with one `text/plain` line per page `system` message or tool definition its policy refuses, and the browser receives each as a `ProviderError` with code `HTTP`. An inbound abort, a client disconnecting included, cancels the upstream turn.
2216
2289
  - **`ProviderError` and its codes.** `ProviderError` carries a `code` and, for `HTTP` alone, a `status`: `HTTP` reports a non-OK response as `provider error: <status>` with ` - <excerpt>` only when the error body had text, `PROTOCOL` a missing body, a refused record, or a `strict` stream with no settled result, and `PROVIDER` a relay `error` frame. A cancel throws `ProviderAbortError`, never `ProviderError`.
@@ -2228,7 +2301,7 @@ These invariants hold across `src/core` ↔ `agent.md`:
2228
2301
  - **Selection faults.** A thrown handler, a returned `fault`, a conversation changed under the handler, and a selected `system` message, carrying `ConversationError` `'ROLE'` over `view()`, each emit `fault`; a throw builds from `view()` with no `select` event, and a returned `fault` charges its usage before `fault` fires. With `strict` set, each settles the run `error`. A cancel at a select site wins over every fault, and the run commits partial without a further provider call.
2229
2302
  - **Selection cost.** Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`, with no `usage` chunk or `usage` event.
2230
2303
  - **Judgments.** A conversation's `judgments` store keys each record by the caller's question id, last write wins in place, stamps `time` on `add`, attaches `usage` only for a one-question request, and returns each record deep-frozen. `resolve` reuses each record whose question JSON value, ordered sources, rendered state, and configured judge `model` match, asks once for the rest, and keeps the completed records when a cancel interrupts it.
2231
- - **Judgments in a snapshot.** A snapshot carries `judgments` only while the store holds one, and a snapshot without the member validates and restores. Its judgments are the stored frozen records, so copy one before you edit it, and hydrating takes an owned frozen copy. A judgment whose `usage` member is present with the value `undefined` is refused, so omit the member from an in-memory snapshot. `isJudgment` and `isMemo` are guard constants, so each reads an empty `.name`.
2304
+ - **Judgments in a snapshot.** A snapshot carries `judgments` only while the store holds one, and a snapshot without the member validates and restores. Its judgments are the stored frozen records, so copy one before you edit it, and hydrating takes an owned frozen copy. A judgment whose `usage` member is present with the value `undefined` is refused, so omit the member from an in-memory snapshot. `isJudgment` is a guard constant, so it reads an empty `.name`.
2232
2305
 
2233
2306
  ## Patterns
2234
2307
 
@@ -2282,7 +2355,8 @@ interface TextOptions extends ProviderOptions {
2282
2355
  class TextProvider extends AgentProvider<string> {
2283
2356
  readonly name = 'text'
2284
2357
  constructor(options: TextOptions) {
2285
- super({ ...options, path: '/generate' })
2358
+ // Raw text has no terminal record, so a stream that stops reads as complete.
2359
+ super({ ...options, path: '/generate', strict: false })
2286
2360
  }
2287
2361
  frame(): ProviderParserInterface<string> {
2288
2362
  return new TextFrame()
@@ -2299,7 +2373,7 @@ class TextProvider extends AgentProvider<string> {
2299
2373
  }
2300
2374
  ```
2301
2375
 
2302
- That provider drives the whole runtime unchanged — `createAgent`, the tool loop, the authority gate, and durable jobs all read it through `ProviderInterface`. Take the switches deliberately. Leave `split` at its default when the backend inlines its reasoning as `<think>` spans in the answer, and set `split: false` when the backend already separates reasoning onto its own field, because splitting twice re-classifies text the backend has already ruled on. Set `strict: true` when the protocol always ends with a settled record and a stream that stops short is a protocol failure worth reporting; leave it `false` when the answer is assembled from the deltas themselves.
2376
+ That provider drives the whole runtime unchanged — `createAgent`, the tool loop, the authority gate, and durable jobs all read it through `ProviderInterface`. Take the switches deliberately. Leave `split` at its default when the backend inlines its reasoning as `<think>` spans in the answer, and set `split: false` when the backend already separates reasoning onto its own field, because splitting twice re-classifies text the backend has already ruled on. A `read` that recognizes the wire's terminal record returns `done: true`, and the engine folds every increment into the settled result, so a stream that stops before that record throws `ProviderError` coded `'PROTOCOL'`. Pass `strict: false` only when the wire has no terminal record, as the raw text subclass in the preceding fence does, because then a cut stream reads as complete.
2303
2377
 
2304
2378
  ### Asking a System One server a choice, a noul, and a score
2305
2379
 
@@ -2451,7 +2525,7 @@ The following rules complete the table:
2451
2525
 
2452
2526
  ### Relaying a browser provider through your own server
2453
2527
 
2454
- When you compose `createAgent(browser, { tools })` in the page, the agent dispatches page tools there after the Node provider returns a tool call, for the definitions the relay forwards: those the server declares in `tools.definitions` or `tools.accept` admits. The Node server runs the relay handler and upstream inference. See [Placement proofs](#placement-proofs) for the planned Chromium receipt; the executed transcription described next proves an HTTP hop in Node.
2528
+ When you compose `createAgent(browser, { tools, authority })` in the page, the agent dispatches page tools there after the Node provider returns a tool call, for the definitions the relay forwards: those the server declares in `tools.definitions` or `tools.accept` admits. The Node server runs the relay handler and upstream inference. See [Placement proofs](#placement-proofs) for the planned Chromium receipt; the executed transcription described next proves an HTTP hop in Node.
2455
2529
 
2456
2530
  A browser must never hold a model credential. Mount `createRelay` on your own server, where the credential already lives, and give the browser `createRelayProvider` pointed at that route: the browser drives a `ProviderInterface` like any other, and the credential never leaves the server. The handler is a plain `(request: Request) => Promise<Response>`, so any fetch-standard router mounts it — this composition mounts it on an `@orkestrel/router` dispatcher. Each half that follows runs in its own process: copy the server half into your server and the browser half into your browser bundle.
2457
2531
 
@@ -2541,7 +2615,10 @@ tools.add(
2541
2615
  PAGE_TOOLS.map((definition) => createTool({ ...definition, execute: () => readSelection() })),
2542
2616
  )
2543
2617
  const browser = createRelayProvider({ url: 'https://app.example/relay' })
2544
- const agent = createAgent(browser, { tools })
2618
+ const agent = createAgent(browser, {
2619
+ tools,
2620
+ authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
2621
+ })
2545
2622
  ```
2546
2623
 
2547
2624
  The server mounts the same definitions beside its own text:
@@ -2621,7 +2698,11 @@ for (const principal of ['ada', 'grace']) {
2621
2698
  const agent = createAgent(provider, {
2622
2699
  tools,
2623
2700
  conversations: threads,
2624
- authority: createAuthority({ rules, ask: approver.ask }),
2701
+ authority: createAuthority({
2702
+ rules,
2703
+ fallback: { zone: 'files', verdict: 'deny' },
2704
+ ask: approver.ask,
2705
+ }),
2625
2706
  })
2626
2707
  sessions.set(principal, { agent, threads, approver })
2627
2708
  }
@@ -2758,12 +2839,19 @@ Advertising and dispatch are the halves of one exchange: hand `definitions()` to
2758
2839
 
2759
2840
  ```ts
2760
2841
  import type { ProviderInterface } from '@orkestrel/agent'
2842
+ import { numberShape, objectShape } from '@orkestrel/contract'
2761
2843
  import { createToolManager, createTool } from '@orkestrel/tool'
2762
2844
 
2763
2845
  // `messages` and `signal` come from the host application.
2764
2846
  declare const provider: ProviderInterface
2765
2847
  const tools = createToolManager()
2766
- tools.add(createTool({ name: 'add', execute: (args) => Number(args.a) + Number(args.b) }))
2848
+ tools.add(
2849
+ createTool({
2850
+ name: 'add',
2851
+ contract: objectShape({ a: numberShape(), b: numberShape() }),
2852
+ execute: (args) => Number(args.a) + Number(args.b),
2853
+ }),
2854
+ )
2767
2855
 
2768
2856
  const turn = await provider.generate(messages, signal, tools.definitions())
2769
2857
  if (turn.tools) {
@@ -2825,7 +2913,7 @@ tools.add(
2825
2913
  },
2826
2914
  }),
2827
2915
  )
2828
- const agent = createAgent(provider, { tools })
2916
+ const agent = createAgent(provider, { tools, authority })
2829
2917
  const stream = agent.stream()
2830
2918
  await entered.promise
2831
2919
  agent.abort('request ended')
@@ -2866,7 +2954,7 @@ result.stop?.layer // 'meter' when the estimate ran out first, 'budget' when the
2866
2954
 
2867
2955
  An `Agent` exposes a pull and a push observation surface. Pull — the `AgentChunk` stream (`stream().events`) — is for a live consumer rendering per-token answer deltas and per-think reasoning deltas as they arrive. Push — the `emitter` (`AgentEventMap`) — is for fire-and-forget observers (logging, metrics, tracing) that want the loop's lifecycle moments without draining the stream: `start` (a run begins), `turn` (each iteration), `tool` (a dispatched call + its result), `usage` (a turn's token usage and the `estimate` of the answer it streamed, as `(usage, estimate)`), `allow` (a call cleared for dispatch, with its decision), `ask` (a call handed to the approver, with its decision), `deny` (a denied call; the event is never a chunk, and a call that scope or authority denies still yields a `tool` chunk that carries its denial result, while a call made when the active scope advertises no tools yields no chunk), `finish` (the settled result), `error` (a genuine failure), `abort` (a cancel), and `exhaust` (the limit was reached while the model still held unresolved tool intent — fires instead of `abort`, still followed by `finish`). Per-token / per-thinking deltas stay the stream's job exclusively — there is deliberately no `token` or `think` event on the emitter; reach for the stream when you need live output, the emitter when you need lifecycle.
2868
2956
 
2869
- An allow clears a call for the tool instance the registry held when the turn advertised it; if that instance is replaced or removed before dispatch, a `deny` follows with the reason `<name> changed after its decision` and no decision, so `deny` can follow that call's `allow`, and neither instance runs. A tool handler that replaces a later tool in the same batch before its first await is host code and is not re-checked. A cancel that ends the turn before dispatch emits no such `deny`.
2957
+ An allow clears a call for the tool instance the registry held when the turn advertised it; if that instance is replaced or removed before dispatch, a `deny` follows with the reason `<name> changed after its decision` and no decision, so `deny` can follow that call's `allow`, and neither instance runs. Each call is checked once more right before it starts, so a handler that replaces or removes a later call's tool before its first await, or changes whether that tool is annotated `consequential`, gets the later call the same `deny`. The manager keeps its own policy for each call, and a supplied manager must resolve the tool when `execute` is entered, as `ToolManager` does. A cancel that ends the turn before dispatch emits no such `deny`.
2870
2958
 
2871
2959
  The following observers wire at construction and later:
2872
2960
 
@@ -3032,7 +3120,7 @@ import { createAgent } from '@orkestrel/agent'
3032
3120
  import { createToolManager } from '@orkestrel/tool'
3033
3121
 
3034
3122
  declare const provider: ProviderInterface
3035
- const agent = createAgent(provider, { tools: createToolManager() })
3123
+ const agent = createAgent(provider, { tools: createToolManager(), authority })
3036
3124
 
3037
3125
  // The first add auto-activates — agent.context.workspaces.active is this workspace, so build()
3038
3126
  // renders its text files into the `## Workspace` section on every turn.
@@ -3104,7 +3192,7 @@ const modes = new Map(
3104
3192
  }),
3105
3193
  )
3106
3194
 
3107
- const agent = createAgent(provider, { tools, select: judged })
3195
+ const agent = createAgent(provider, { tools, authority, select: judged })
3108
3196
  async function ask(content: string): Promise<void> {
3109
3197
  agent.context.messages.add({ role: 'user', content })
3110
3198
  await agent.generate()
@@ -3134,7 +3222,7 @@ Overlapping runs on one agent share its scope and its default handler, so an `ap
3134
3222
 
3135
3223
  ### Answering without tools
3136
3224
 
3137
- When the next turn must answer from what it already holds, apply a scope with an empty `tools` list: `createScope({ name: 'answer', tools: [] })`. The package exports no constant for it. The provider's `content` ends the run as the answer with `partial: false`, and each call the reply still carries emits `deny` with the reason `no tool is advertised in the active scope`, as [Scoping a turn](#scoping-a-turn) states. That reason and `TOOL is not in the active scope` are frozen copy, so a harness can match them verbatim.
3225
+ When the next turn must answer from what it already holds, apply a scope with an empty `tools` list: `createScope({ name: 'answer', tools: [] })`. The package exports no constant for it. A reply with no calls ends the run as the answer with `partial: false`, and each call a reply still carries emits `deny` with the reason `TOOL is not in the active scope`, gets a denial the model reads, and costs another turn, as [Scoping a turn](#scoping-a-turn) states. That reason is frozen copy, so a harness can match it verbatim.
3138
3226
 
3139
3227
  The following run ends answer-only:
3140
3228
 
@@ -3143,13 +3231,16 @@ import type { ProviderInterface } from '@orkestrel/agent'
3143
3231
  import { createAgent, createScope } from '@orkestrel/agent'
3144
3232
  import { createTool, createToolManager } from '@orkestrel/tool'
3145
3233
 
3146
- declare const provider: ProviderInterface // replies with text and a stray `refund` call
3234
+ declare const provider: ProviderInterface // replies with a stray `refund` call, then the answer
3147
3235
  declare function log(name: string, reason: string | undefined): void
3148
3236
 
3149
3237
  const tools = createToolManager()
3150
3238
  tools.add(createTool({ name: 'refund', execute: () => 'refunded' }))
3151
- const agent = createAgent(provider, { tools })
3152
- agent.emitter.on('deny', (call, reason) => log(call.name, reason)) // 'refund', 'no tool is advertised in the active scope'
3239
+ const agent = createAgent(provider, {
3240
+ tools,
3241
+ authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
3242
+ })
3243
+ agent.emitter.on('deny', (call, reason) => log(call.name, reason)) // 'refund', 'refund is not in the active scope'
3153
3244
  agent.context.apply(createScope({ name: 'answer', tools: [] }))
3154
3245
  agent.context.messages.add({ role: 'user', content: 'Refund invoice 42.' })
3155
3246
  const result = await agent.generate() // { content: 'Refunds need a manager.', partial: false }
@@ -3212,7 +3303,18 @@ const judge: JudgeInterface = {
3212
3303
  Object.entries(request.questions).map(([id, question]): [string, JudgeAnswer] => [
3213
3304
  id,
3214
3305
  question.form === 'choice'
3215
- ? { form: 'choice', probabilities: { rule: 0.9, fact: 0.1 } }
3306
+ ? {
3307
+ form: 'choice',
3308
+ probabilities: {
3309
+ fact: 0.1,
3310
+ rule: 0.9,
3311
+ correction: 0,
3312
+ request: 0,
3313
+ opinion: 0,
3314
+ chatter: 0,
3315
+ distractor: 0,
3316
+ },
3317
+ }
3216
3318
  : { form: 'noul', noul: 0.1 },
3217
3319
  ]),
3218
3320
  ),
@@ -3288,9 +3390,9 @@ To serve a thinking model, pass its context window as the `capacity` option and
3288
3390
 
3289
3391
  ### Upgrade data written before 0.0.35
3290
3392
 
3291
- Stored data written before 0.0.35 meets the checks of 0.0.35 at its next read. A stored snapshot that holds a `system` row rejects with `ConversationError` `'ROLE'` and the message `a conversation snapshot holds a system message; a snapshot written before 0.0.35 can hold a system row; remove it before loading`. A queued `AgentJobInput` seed that holds a `system` message fails at `AgentRegistry.build` through `add`, with `ConversationError` `'ROLE'` and the message `a stored message role must be one of "user", "assistant", "tool"; received "system"; host text goes in the system option or an instruction`, and the job's `system` member carries that text.
3393
+ Stored data written before 0.0.35 meets the checks of 0.0.35 at its next read. A snapshot that carries a member its shape doesn't declare, the conversation `summary` a 0.0.29 snapshot can hold included, refuses at its next read as well: the stores throw `'SNAPSHOT'` naming the key, because a refused row read as absent would let `open` overwrite it. Read that row through your own table and rewrite it without the key, or delete it with `store.delete`. A stored snapshot that holds a `system` row rejects with `ConversationError` `'ROLE'` and the message `a conversation snapshot holds a system message; a snapshot written before 0.0.35 can hold a system row; remove it before loading`. A queued `AgentJobInput` seed that holds a `system` message fails at `AgentRegistry.build` through `add`, with `ConversationError` `'ROLE'` and the message `a stored message role must be one of "user", "assistant", "tool"; received "system"; host text goes in the system option or an instruction`, and the job's `system` member carries that text.
3292
3394
 
3293
- The following fence removes the row from a snapshot read from a store. It narrows the read through `isConversationSnapshot`, which stays structural, and it filters `messages` and each section's `messages`, because hydrating checks both and a fold can hold the row in a section:
3395
+ The following fence removes the row from a snapshot read from a store. It narrows the read through `isConversationSnapshot`, which is exact on keys and leaves roles and repeated ids to the hydrate, and it filters `messages` and each section's `messages`, because hydrating checks both and a fold can hold the row in a section:
3294
3396
 
3295
3397
  ```ts
3296
3398
  import type { ConversationSnapshot, ConversationStoreInterface } from '@orkestrel/agent'
@@ -3358,7 +3460,10 @@ scopes.remove(scope.id)
3358
3460
  scopes.clear()
3359
3461
 
3360
3462
  // Authority — `evaluate` decides and `ask` approves (both also reached through the agent loop internally).
3361
- const authority = createAuthority({ ask: () => true })
3463
+ const authority = createAuthority({
3464
+ fallback: { zone: 'default', verdict: 'allow' },
3465
+ ask: () => true,
3466
+ })
3362
3467
  const call = { id: '1', name: 'add', arguments: {} }
3363
3468
  const decision = authority.evaluate({ call }) // { zone: 'default', verdict: 'allow' }
3364
3469
  await authority.ask?.({ call }, decision, new AbortController().signal) // true (`ask` is optional on the interface)
@@ -3449,10 +3554,10 @@ The following test files back this guide:
3449
3554
  - [`tests/src/core/contexts/scopes/ScopeManager.test.ts`](../tests/src/core/contexts/scopes/ScopeManager.test.ts) — the scope registry's add, lookup, removal, and emitter.
3450
3555
  - [`tests/src/core/contexts/skills/SkillManager.test.ts`](../tests/src/core/contexts/skills/SkillManager.test.ts) — the skill registry's add, files minted through `createFile`, same-name replace, lookup, removal, format cascade, and emitter.
3451
3556
  - [`tests/src/core/contexts/stores/MemoryMemoStore.test.ts`](../tests/src/core/contexts/stores/MemoryMemoStore.test.ts) — the in-memory memo store's restore into a manager, its JSON parity, and the object its `get` method returns.
3452
- - [`tests/src/core/contexts/stores/DatabaseMemoStore.test.ts`](../tests/src/core/contexts/stores/DatabaseMemoStore.test.ts) — the driver-backed memo store's malformed and foreign-id rows read as absent, its copy on read, and its table kept apart from the conversation store's on one driver.
3557
+ - [`tests/src/core/contexts/stores/DatabaseMemoStore.test.ts`](../tests/src/core/contexts/stores/DatabaseMemoStore.test.ts) — the driver-backed memo store's malformed and foreign-id rows refusing with `SNAPSHOT` while an absent row reads as absent, its copy on read, and its table kept apart from the conversation store's on one driver.
3453
3558
  - [`tests/src/core/agents/Agent.test.ts`](../tests/src/core/agents/Agent.test.ts) — the loop over a scripted provider: the recorded-request control, scope dispatch, tool iteration, authority, `generate` and `stream` parity, chunks, bounds, cancellation timing, the emitter, automatic compaction, recorded thinking and the replay policy, multi-conversation runs and the run-bound conversation under a switch, a fold, and a removal, limit exhaustion, budget reconciliation, per-run options, the concurrency guard with its refusal of a second run on one conversation, usage sanitizing, the selection seam, the turn records, the three failure layers, the stored-ingress canary that refuses a `system` message through `add`, a snapshot, a job seed, and a selection and sends none, the scope denial of a name no definition advertises under every verdict, the `ask` chunk and its order, the approver over a real run with its page answers, timeouts, aborts, and injected arguments, the `prompt` option with its exact check and its append after the run's guards, and the forwarded skills and memos.
3454
3559
  - [`tests/src/core/agents/AgentRegistry.test.ts`](../tests/src/core/agents/AgentRegistry.test.ts) — the registry's accessors, rehydrating `build` and its field wiring, a job seed holding a `system` role refused, isolation, the conversation store seam, and an empty registry.
3455
- - [`tests/src/core/agents/Authority.test.ts`](../tests/src/core/agents/Authority.test.ts) — first-match-wins ordering, a matched rule's default allow, the fallback, the `{ call }` context, and the `ask` approver with its `'APPROVER'` refusal.
3560
+ - [`tests/src/core/agents/Authority.test.ts`](../tests/src/core/agents/Authority.test.ts) — first-match-wins ordering, the refusal of a missing fallback and a missing verdict, the fallback, the `{ call }` context, and the `ask` approver with its `'APPROVER'` refusal.
3456
3561
  - [`tests/src/core/agents/Approver.test.ts`](../tests/src/core/agents/Approver.test.ts) — the bound `ask`, the ask registered before it suspends, the frame's members and minted id, strict approval, identity keying, the missed mark, the second-ask and unrenderable-argument refusals with the call name encoded, and the release of the run signal on an answer and an abort.
3457
3562
  - [`tests/src/core/agents/Channel.test.ts`](../tests/src/core/agents/Channel.test.ts) — the channel's lost-wakeup, `undefined` values, buffer-before-close, `fail`, concurrent readers, push after end, FIFO order, end semantics, the unread rest before an end, and a `return()` while a read is parked.
3458
3563
  - [`tests/src/core/agents/ChannelCell.test.ts`](../tests/src/core/agents/ChannelCell.test.ts) — the internal `ChannelCell` class: a new cell's value with no next cell, and the `link` method's latch, which keeps the first linked cell.