@orkestrel/scaffold 0.0.140 → 0.0.142

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.
@@ -2,11 +2,10 @@
2
2
 
3
3
  > The conversation runtime for the `@orkestrel` line: the `ProviderInterface` inference
4
4
  > boundary with the host-independent HTTP engine and browser relay that implement it, the
5
- > conversation layer that feeds it — messages, compaction, instructions, scopes, and prompt
6
- > assembly — and the bounded context → provider → tools → repeat loop that carries a turn to
7
- > its end.
5
+ > conversation layer that feeds it — messages, instructions, scopes, and prompt assembly — and
6
+ > the bounded context → provider → tools → repeat loop that carries a turn to its end.
8
7
 
9
- An agent is a conversation with a model and the loop that carries it forward. A `Conversation` holds the history — a live tail of immutable messages plus the sections older turns were compacted into. An `AgentContext` assembles that history into the next prompt, folding in the instructions, the skills and memos indexes, the skills a run shows, and one workspace, and applying the active scope. An `Agent` drives that prompt through a provider, dispatches requested tools admitted by scope and authority, feeds the results back, and repeats until the model stops. A `Ledger` composes all three to serve one conversation through records projected from what a judge filed, written into a copy of each request turn. Everything else in this module either configures those nouns or observes them. Source: [`src/core`](../src/core). Published through `@orkestrel/agent`.
8
+ An agent is a conversation with a model and the loop that carries it forward. A `Conversation` holds the history — the owned, immutable messages of the thread and the judgments recorded about them. An `AgentContext` assembles that history into the next prompt, folding in the instructions, the skills and memos indexes, the skills a run shows, and one workspace, and applying the active scope. An `Agent` drives that prompt through a provider, dispatches requested tools admitted by scope and authority, feeds the results back, and repeats until the model stops. A `Ledger` composes all three to serve one conversation through records projected from what a judge filed, written into a copy of each request turn. Everything else in this module either configures those nouns or observes them. Source: [`src/core`](../src/core). Published through `@orkestrel/agent`.
10
9
 
11
10
  Hand a provider a conversation and get back one assembled `ProviderResult` (`generate`), or a live stream of channel-tagged `ProviderDelta` values that returns that same assembled result when it ends (`stream`). Reasoning separation, the authority gate, and durable jobs sit around that boundary. The model itself is the one thing this package doesn't supply. `ProviderInterface` stays the boundary any backend can satisfy, and `AgentProvider` is the host-independent HTTP engine a concrete provider extends rather than rewrites: it owns the deadline, the transport, the bounded error read, the framing loop, reasoning separation, and result assembly, and the subclass fills in one vendor's wire. `RelayProvider` and `createRelay` carry that same boundary across your own server, so a browser drives a model it holds no credential for. There is no hidden global state, a plugin lifecycle, a prompt-template DSL, or an implicit memory store. This is a kit of composable primitives: the loop is the convenient way to use them, not the only one, and a caller that would rather bound and drive a provider by hand can skip it entirely.
12
11
 
@@ -84,7 +83,7 @@ const results = await tools.execute([
84
83
 
85
84
  Contained failure is the registry's contract, not a limitation of it: in-process code that wants a typed error calls the tool itself — `tools.tool(name)` then `tool.execute(args, context)` inside its own `try`/`catch`. For registration, advertising, dispatch, and error containment, see [Tool](tool.md).
86
85
 
87
- Collect a turn's conversation in an `AgentContext`. Add turns through `context.messages` — the active conversation's live tail, always present, satisfying `MessageManagerInterface` by minting each `id` on `add` and keeping stored messages immutable and in insertion order — then call `build()` to produce the provider input: `[systemMessage?, ...messages]`. `context.tools` sits beside them, but it is a different kind of thing: the other managers assemble prompt text, while the tool registry exists so the loop can advertise definitions and dispatch calls. Its contents reach the model as the `tools` argument, never as a message:
86
+ Collect a turn's conversation in an `AgentContext`. Add turns through `context.messages` — the active conversation, always present, satisfying `MessageManagerInterface` by minting each `id` on `add` and keeping stored messages immutable and in insertion order — then call `build()` to produce the provider input: `[systemMessage?, ...messages]`. `context.tools` sits beside them, but it is a different kind of thing: the other managers assemble prompt text, while the tool registry exists so the loop can advertise definitions and dispatch calls. Its contents reach the model as the `tools` argument, never as a message:
88
87
 
89
88
  ```ts
90
89
  import type { ProviderInterface } from '@orkestrel/agent'
@@ -303,7 +302,7 @@ A memo's `origin` is asserted by whoever wrote it and not verified, so read it a
303
302
 
304
303
  The model reads a skill's body only while a run shows that skill. The model shows one through the `load` built-in, as [Enabling the built-in tools](#enabling-the-built-in-tools) states. A shown body renders last in the `system` message, under `## Loaded skills`, and a load belongs to the conversation that stored it: another conversation of the same agent shows the skill only after its own `load`. An instruction a host adds through `context.instructions` reaches every conversation of the agent, so keep the text every thread needs there. A host that adds no skills sees no `## Skills` section. The skills index and a loaded body render in the `system` message, so build each `SkillInput` from text the host authored, never from a user message, a tool result, a stored memo, or a page's request body. The agent reads a loaded body from its skill registry by name, never from the call's arguments. A memo can be model-written, so the memos index renders in the context message and never in the `system` message. A relay refuses a page's `system` message, its skills index included, until `RelaySystemOptions.accept` admits it.
305
304
 
306
- `build({ selection })` adds at most one `system` message of its own and reads the selection's messages as conversation parts without a role check; the select path refuses a selected `system` role as a `'ROLE'` fault over `view()`; a host's direct `build({ selection })` is host-trusted, and a conversation a host implements itself whose `view()` holds a `system` message is read as host-trusted too.
305
+ `build({ selection })` adds at most one `system` message of its own and reads the selection's messages as conversation parts without a role check; the select path refuses a selected `system` role as a `'ROLE'` fault over `messages()`; a host's direct `build({ selection })` is host-trusted, and a conversation a host implements itself whose `messages()` holds a `system` message is read as host-trusted too.
307
306
 
308
307
  Documents reach a turn one way only: through the active workspace. A workspace from the `@orkestrel/workspace` package (see [Workspace](workspace.md)) is a flat map of immutable files, and it takes no position on prompts — deciding how a file becomes part of a turn is this package's job, and the decision is a split by carrier. A text file renders as a fenced reference block in a `## Workspace` section of the user context message that follows the system message, where the model can read it as quoted material. An image file can't be text, so its `base64` payload attaches to the last user message instead, the turn a vision provider reads images from. A message carries that payload on its optional `images` field — `Message` and `MessageInput` both accept `readonly images?: readonly string[]` — and a vision-capable provider forwards it onto the wire (an empty or absent array is never sent). It is input-only; `ProviderResult` is unchanged. In the following example, the `IMAGE_BASE64` placeholder stands for the base64 text of one image.
309
308
 
@@ -335,81 +334,44 @@ const input = context.build()
335
334
  // input[2] = { role: 'user', content: 'Review this.' }
336
335
  ````
337
336
 
338
- ### Conversations & compaction
337
+ ### Conversations
339
338
 
340
- Above the flat `MessageManagerInterface` sits the `Conversation` (`createConversation` / a `ConversationManager`) — it owns its messages directly and compacts older ones into summarized `sections` so a long history fits a turn's context window without discarding the originals. Append turns through the conversation's own `add` (the live uncompacted tail; `message` / `messages` / `remove` / `clear` / `count` round it out); `compact()` folds the older live messages into a summarized `Section` (retaining their originals) and shrinks `view()` — the model input, where each section becomes one summary message followed by the live tail. Compaction is driven by a provider-agnostic `ConversationSummaryHandler` seam (`(messages, signal?) => Promise<string>`) the agent runtime supplies, so a `compact()` without one throws a `ConversationError`. `keep` retains a recent tail (default `DEFAULT_CONVERSATION_KEEP` = `0`, no retained tail); `rehydrate(id)` / `search(query)` read the retained originals. A fold never takes the newest user message or any message after it, because that message is the request a run serves. An exchange is a user message and every message after it up to the next user message. The messages before the first user message form their own exchange, which folds only together with the first user exchange. A fold removes whole exchanges: a cut inside an exchange moves back to its start. A fold never splits an assistant message with calls from the tool messages that answer it, matched by each tool message's `call` member with a positional fallback: a cut inside that group moves before the assistant message. When those rules leave nothing to fold, `compact()` returns `undefined`:
339
+ Above the flat `MessageManagerInterface` sits the `Conversation` (`createConversation` / a `ConversationManager`) — it owns each message it stores, deep-frozen and in insertion order, beside the judgments recorded about them. Append turns through the conversation's own `add`; `message` / `messages` / `remove` / `clear` / `count` round it out, and `messages()` is what a run sends. `add` and a hydrate copy each message through JSON and freeze the copy, so a strategy can hold a message by reference and know its content can't change in process. `remove` of any member of a call group, an assistant message with calls and the tool messages that answer it, removes the whole group, so a provider never receives half of one, and `remove` and `clear` drop every judgment that quotes a removed message. `search(query)` finds messages by case-insensitive substring, and `reference(options)` renders a fenced provenance block. The emitter reports `add`, `remove`, and `clear` after each change, and `destroy()` drops every listener:
341
340
 
342
341
  ```ts
343
- import type { ProviderInterface } from '@orkestrel/agent'
344
342
  import { createConversation } from '@orkestrel/agent'
345
343
 
346
- declare const provider: ProviderInterface // any concrete implementation supplied by the host app
347
- // The summarizer seam — built from the provider by the runtime; core stays provider-agnostic.
348
- // Append the instruction as the FINAL user turn: a chat model emits nothing when the prompt
349
- // ends on an assistant turn, so a leading-system instruction is unreliable.
350
- const conversation = createConversation({
351
- summarize: async (messages, signal) =>
352
- (
353
- await provider.generate(
354
- [
355
- ...messages,
356
- { id: 's', role: 'user', content: 'Summarize the conversation so far concisely.' },
357
- ],
358
- signal ?? AbortSignal.timeout(30_000), // the compact() call's signal, when it passed one
359
- )
360
- ).content,
361
- keep: 2, // retain at least the 2 most recent messages verbatim on each compaction
362
- })
363
- conversation.add([
364
- { role: 'user', content: 'My name is Ada.' },
365
- { role: 'assistant', content: 'Nice to meet you, Ada.' },
366
- { role: 'user', content: 'Book a table for two at 19:00.' },
367
- { role: 'assistant', content: 'Booked for two at 19:00.' },
368
- { role: 'user', content: 'What did I say my name was?' },
344
+ const conversation = createConversation({ id: 'desk' })
345
+ const [, call] = conversation.add([
346
+ { role: 'user', content: 'Is order LH-81660 late?' },
347
+ {
348
+ role: 'assistant',
349
+ content: '',
350
+ calls: [{ id: 'order', name: 'lookup', arguments: { order: 'LH-81660' } }],
351
+ },
352
+ { role: 'tool', content: 'LH-81660 ships on Friday.', call: 'order' },
353
+ { role: 'assistant', content: 'It ships on Friday.' },
369
354
  ])
370
355
 
371
- const section = await conversation.compact() // folds the first exchange → a summarized section
372
- conversation.view() // [<section summary message>, ...the retained recent exchanges] — the model input
373
- conversation.search('ada') // case-insensitive across sections' originals + the live tail
374
- section && conversation.rehydrate(section.id) // the section's full original messages (a pure read)
356
+ conversation.search('friday').length // 2 — case-insensitive over every stored message
357
+ Object.isFrozen(call) // true — every stored message is owned and frozen
358
+ conversation.remove(call?.id ?? '') // true — removes the call and its tool result together
359
+ conversation.count // 2
360
+ conversation.reference({ label: 'orders', messages: conversation.messages() })
361
+ // a block fenced by [Reference — conversation "orders" — …] and [End of reference "orders"]
375
362
  ```
376
363
 
377
- Calls to `compact()` run one at a time: a call made while another is in flight waits for it, then folds from the live tail it finds. A fold commits only when every folded message is still the same live entry after the summarizer settles, so a `remove` or `clear` during the initial summarizer makes `compact()` resolve `undefined` and leaves no section. A summarizer must not call `compact()` on the conversation it serves. When no other fold is in flight, a fold counts as in flight only after its summarizer returns, so the summarizer's own call waits for nothing and summarizes the same slice again; the commit check keeps one section, because the later fold finds its slice already folded and resolves `undefined`. Pass `CompactOptions.signal` to cancel a fold: the summarizer receives the signal as its second argument, and an abort rejects `compact()` with the signal's reason at once, even when the summarizer ignores the signal, and commits nothing after the abort; a fold committed before an aborted overflow merge stays. `keep` must be a nonnegative safe integer: `NaN`, a fraction, a negative, or `Infinity` throws `ConversationError` with code `KEEP` before any summarizer call.
378
-
379
- Register a conversation in a `ConversationManager` and pass that registry through `AgentContextOptions.conversations` to make it the message source. `context.messages` then is the active conversation's live tail, and `build()` folds its `view()`. The scope's filters never touch messages; message inclusion is the conversation's through compaction and, when a handler is set, the selection's. When the registry is omitted, the context creates one with an active default conversation.
380
-
381
- 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.
364
+ A conversation keeps every message it's given and sends them all. Serve one that outgrows a model's context through a ledger, as [Serving a conversation through a ledger](#serving-a-conversation-through-a-ledger) states: the ledger bounds every request it sends.
382
365
 
383
- 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.
384
-
385
- ```ts
386
- import { createAgent, createConversationManager, estimateRequest } from '@orkestrel/agent'
387
- import { createBudget } from '@orkestrel/budget'
388
-
389
- // `provider` and `summarize` come from the host application.
390
- const conversations = createConversationManager({ summarize, keep: 2 })
391
- const conversation = conversations.add()
392
- const agent = createAgent(provider, {
393
- conversations,
394
- // A context Budget: consumer = a token estimator, max = the context window. The loop measures
395
- // each request against it. A request that reaches the window folds once and continues on the
396
- // rebuilt (smaller) view; `strict`, the default, refuses a request still over the window.
397
- window: createBudget({ max: 8_000, consumer: estimateRequest }),
398
- })
399
- agent.context.messages.add({ role: 'user', content: 'Hi' })
400
- await agent.generate() // folds older turns into a section mid-run when the prompt reaches the window, then continues
401
- ```
402
-
403
- Set `max` under a hard ceiling: on 11 agent requests with no tool call, recorded on 2026-11-02 on Qwen 3.5 2B on Ollama 0.40.13, over a scripted support-desk conversation of up to 38 messages and 46713 characters (median 640, 95th percentile 3367, maximum 3506), `estimateRequest` read 147 to 204 tokens under the daemon's prompt count of 1850 to 12283, so leave at least that headroom. No other model and no request holding a tool call has a reading here.
366
+ Register a conversation in a `ConversationManager` and pass that registry through `AgentContextOptions.conversations` to make it the message source. `context.messages` then is the active conversation, and `build()` folds its `messages()`. The scope's filters never touch messages; message inclusion is the conversation's and, when a handler is set, the selection's. When the registry is omitted, the context creates one with an active default conversation.
404
367
 
405
368
  ##### One agent per principal, one conversation per run (binding a run to its thread)
406
369
 
407
- `agent.context.conversations` is the structural registry, supplied at construction and never reassigned, and its active conversation is the default a run binds. `context.messages` is dynamic: it always points at the current active conversation's live tail (the same reference, no duplication) and follows `conversations.switch(id)`. The registry always has an active conversation (a default is added when it has none). A run binds its conversation once, at its `generate` or `stream` call: the `AgentRunOptions.conversation` it names, else the active one. The run reads its request from that conversation, appends every reply to it, and folds it, so a later `switch`, `open`, `remove`, `clear`, or same-id `add` never moves a live run, and a switch sets only the next run's default. Each conversation accumulates its own history and compacts independently (one thread's sections never leak into another). On a server, the application's session table holds one entry per authenticated principal, `{ agent, threads }`: `threads` is a `createConversationManager()` value that principal owns, and `agent` is one `Agent` built once for that principal from shared providers, tools, rules, and immutable host text. Each request names its thread, looked up in the principal's own `threads` and never in a process-global registry, and passes the request's text as the run's `AgentRunOptions.prompt`. The run appends the prompt to the thread as a `user` turn after its guards, so a refused run appends nothing; a run with no `prompt` reads its request from the conversation's tail:
370
+ `agent.context.conversations` is the structural registry, supplied at construction and never reassigned, and its active conversation is the default a run binds. `context.messages` is dynamic: it always points at the current active conversation (the same reference, no duplication) and follows `conversations.switch(id)`. The registry always has an active conversation (a default is added when it has none). A run binds its conversation once, at its `generate` or `stream` call: the `AgentRunOptions.conversation` it names, else the active one. The run reads its request from that conversation and appends every reply to it, so a later `switch`, `open`, `remove`, `clear`, or same-id `add` never moves a live run, and a switch sets only the next run's default. Each conversation accumulates its own history, which never leaks into another. On a server, the application's session table holds one entry per authenticated principal, `{ agent, threads }`: `threads` is a `createConversationManager()` value that principal owns, and `agent` is one `Agent` built once for that principal from shared providers, tools, rules, and immutable host text. Each request names its thread, looked up in the principal's own `threads` and never in a process-global registry, and passes the request's text as the run's `AgentRunOptions.prompt`. The run appends the prompt to the thread as a `user` turn after its guards, so a refused run appends nothing; a run with no `prompt` reads its request from the conversation's tail:
408
371
 
409
372
  ```ts
410
373
  import type { AgentInterface, ConversationManagerInterface } from '@orkestrel/agent'
411
- import { createAgent, createConversationManager, estimateRequest } from '@orkestrel/agent'
412
- import { createBudget } from '@orkestrel/budget'
374
+ import { createAgent, createConversationManager } from '@orkestrel/agent'
413
375
 
414
376
  interface Session {
415
377
  readonly agent: AgentInterface
@@ -423,23 +385,20 @@ async function handle(session: Session, threadId: string, text: string): Promise
423
385
  return (await session.agent.generate({ conversation: thread, prompt: { content: text } })).content
424
386
  }
425
387
 
426
- // `provider` and `summarize` come from the host application.
388
+ // `provider` comes from the host application.
427
389
  // The session table: one entry per authenticated principal, held by the application.
428
390
  const sessions = new Map<string, Session>()
429
391
  for (const principal of ['ada', 'grace']) {
430
- // Each entry owns its threads and its window; neither is shared across principals.
431
- const threads = createConversationManager({ summarize, keep: 2 })
432
- const agent = createAgent(provider, {
433
- conversations: threads,
434
- window: createBudget({ max: 8_000, consumer: estimateRequest }),
435
- })
392
+ // Each entry owns its threads; none is shared across principals.
393
+ const threads = createConversationManager()
394
+ const agent = createAgent(provider, { conversations: threads })
436
395
  sessions.set(principal, { agent, threads })
437
396
  }
438
397
 
439
398
  const ada = sessions.get('ada')
440
399
  const grace = sessions.get('grace')
441
400
  if (ada === undefined || grace === undefined) throw new Error('unknown principal')
442
- // Ada's trip thread accumulates and compacts on its own.
401
+ // Ada's trip thread accumulates on its own.
443
402
  await handle(ada, 'trip', 'Hi, I am Ada.')
444
403
  // Ada's math thread is independent of her trip thread.
445
404
  await handle(ada, 'math', 'What is 2 + 2?')
@@ -449,28 +408,9 @@ await handle(grace, 'trip', 'What did I say my name was?')
449
408
 
450
409
  > **Concurrency caveat.** [Serving one agent per principal](#serving-one-agent-per-principal) holds what this session table shares and refuses. Here a refused overlap rejects the promise `handle` returns, so the caller rethrows or maps `AgentError` `'CONCURRENCY'`.
451
410
 
452
- ##### Production behaviors of automatic compaction
453
-
454
- Auto-compaction (the `window` budget) is hardened for a long-running app:
455
-
456
- - **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.
457
- - **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.
458
- - **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.
459
- - **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.
460
- - **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.
461
-
462
- The following listener observes an automatic-compaction summarizer failure:
463
-
464
- ```ts
465
- // `agent` comes from the preceding example; `log` comes from the host application.
466
- agent.emitter.on('fault', (error) =>
467
- log('auto-compaction summarizer failed (run continues)', error),
468
- )
469
- ```
470
-
471
411
  ### Scoping a turn
472
412
 
473
- A `Scope` (`createScope` / a `ScopeManager`) is a named allow-list filter the context applies at `build()` time and at the loop's tool-advertise step. It carries an optional `instructions` / `skills` / `memos` / `tools` / `files` / `workspaces` list keyed by each category's identity — `instructions` (by `name`), `skills` (by `name`), `memos` (by `name`), `tools` (by `name`), `files` (the rendered workspace's files, by `path`), `workspaces` (by `id`) — each three-way: `undefined` ⇒ no constraint (all pass), `[]` ⇒ none pass, a non-empty list ⇒ only the listed keys. The scope's filters never touch messages; message inclusion is the conversation's through compaction and, when a handler is set, the selection's, so a scope has no `messages` allow-list. A scope also carries an optional `select` handler, covered in [Selecting the messages a turn carries](#selecting-the-messages-a-turn-carries). Apply the active filter through `context.apply(scope)`; call `context.apply(undefined)` to remove filtering. The readonly `context.scope` getter reports the current filter, and `build()` reflects whatever scope is active when it runs (recomputed fresh each call). `narrow(config)` composes a tighter child scope by set-intersection (an `undefined` side imposes no constraint), so narrowing can only tighten — a parent-excluded key never returns:
413
+ A `Scope` (`createScope` / a `ScopeManager`) is a named allow-list filter the context applies at `build()` time and at the loop's tool-advertise step. It carries an optional `instructions` / `skills` / `memos` / `tools` / `files` / `workspaces` list keyed by each category's identity — `instructions` (by `name`), `skills` (by `name`), `memos` (by `name`), `tools` (by `name`), `files` (the rendered workspace's files, by `path`), `workspaces` (by `id`) — each three-way: `undefined` ⇒ no constraint (all pass), `[]` ⇒ none pass, a non-empty list ⇒ only the listed keys. The scope's filters never touch messages; message inclusion is the conversation's and, when a handler is set, the selection's, so a scope has no `messages` allow-list. A scope also carries an optional `select` handler, covered in [Selecting the messages a turn carries](#selecting-the-messages-a-turn-carries). Apply the active filter through `context.apply(scope)`; call `context.apply(undefined)` to remove filtering. The readonly `context.scope` getter reports the current filter, and `build()` reflects whatever scope is active when it runs (recomputed fresh each call). `narrow(config)` composes a tighter child scope by set-intersection (an `undefined` side imposes no constraint), so narrowing can only tighten — a parent-excluded key never returns:
474
414
 
475
415
  ```ts
476
416
  import { createAgent, createScope } from '@orkestrel/agent'
@@ -493,7 +433,7 @@ const result = await agent.generate()
493
433
 
494
434
  A scoped-out tool is neither described nor callable. The loop snapshots each turn's tool ceiling before advertising, the context scope's `tools` list intersected with the run scope's, and checks each returned call against that ceiling before consulting the `AgentOptions.authority` option. A ceiling with no `tools` list on either scope, or with no scope at all, admits every advertised name and refuses a name no advertised definition carries with the scope denial. An empty `tools` list admits none.
495
435
 
496
- A scope change through the `context.apply` method applies at the next turn's snapshot, which decides the tools the turn advertises and the prompt it sends. A `tool` or `usage` listener therefore changes the next turn, and a `turn` listener reaches the same turn, because `turn` fires before the snapshot. A turn rebuilds the head, the `system` message and the context message, when its view differs from the view the head was built with. The view is the ceiling's `instructions`, `skills`, `memos`, `files`, and `workspaces` lists, the shown skills, the shown workspace, the files that workspace renders under the `files` list, compared by identity, and whether `switch` is advertised. An edit to a rendered file, by a tool call or by the host, therefore rebuilds the head at the next turn, and an edit to a file no request renders doesn't. The rebuilt head keeps every message added since, and a turn whose view is unchanged sends the head it already built. A skill replaced under its name changes the view, so its body and its tools change at the same turn. A `select` handler change, and an edit to an instruction's text with no list change, wait for the next build or select site: run entry, the pre-first-turn compaction fold, or a compaction rebuild.
436
+ A scope change through the `context.apply` method applies at the next turn's snapshot, which decides the tools the turn advertises and the prompt it sends. A `tool` or `usage` listener therefore changes the next turn, and a `turn` listener reaches the same turn, because `turn` fires before the snapshot. A turn rebuilds the head, the `system` message and the context message, when its view differs from the view the head was built with. The view is the ceiling's `instructions`, `skills`, `memos`, `files`, and `workspaces` lists, the shown skills, the shown workspace, the files that workspace renders under the `files` list, compared by identity, and whether `switch` is advertised. An edit to a rendered file, by a tool call or by the host, therefore rebuilds the head at the next turn, and an edit to a file no request renders doesn't. The rebuilt head keeps every message added since, and a turn whose view is unchanged sends the head it already built. A skill replaced under its name changes the view, so its body and its tools change at the same turn. A `select` handler change, and an edit to an instruction's text with no list change, wait for the next build or select site, which is the next run's entry.
497
437
 
498
438
  A run narrows its own ceiling through the `scope` member of `AgentRunOptions`. Each turn reads the context scope and the run scope one time and intersects them list by list, so the turn advertises only a tool both scopes admit, and each build site of the run filters instructions, skills, memos, files, and workspaces by the same intersection. The run scope's `select` runs in place of the context scope's, which runs in place of the agent default. A `context.apply` still reaches the run at its next turn, and never past the run scope. An agent never widens its own ceiling: a run scope only narrows the context scope, so a run that needs a wider scope than the context scope needs another agent. A `scope` value that doesn't implement `ScopeInterface` makes the `stream` or `generate` call throw a `ContractError` with code `placement` before the run appends its prompt or starts.
499
439
 
@@ -589,7 +529,7 @@ const plain = createScope({ name: 'plain', workspaces: ['orders'] })
589
529
  await agent.generate({ prompt: { content: 'Check order 9.' }, scope: plain }) // renders orders
590
530
  ```
591
531
 
592
- What a run shows comes from its conversation. Each turn reads the conversation's stored messages for every successful `load`, `unload`, and `switch` call, recognized by the note it returned, and keeps what the registries hold and the ceiling admits. The shown skills are the model's, in load order, and a skill loaded again after its unload goes last. A denied, refused, or failed call shows nothing, and so does a tool message whose text equals a note but answers another tool's call. A record counts only while the run enables its built-in, so a host tool under a built-in's name on a run that doesn't enable it shows nothing. A stored record can't name its writer, so a record such a tool wrote counts after a run enables the built-in, bounded by the registry and the ceiling as every record is. The read repairs each call's arguments through the `repairValue` function of `@orkestrel/contract`, as the tool's door repairs them, so a `{ skill: 1 }` the door repaired to `'1'` shows the skill `'1'`. A fold keeps the record, because the read covers each section's retained originals before the live tail, and a conversation restored from its `ConversationSnapshot` shows what it showed when the snapshot was taken. A skill the ceiling excludes, or the registry no longer holds, shows nothing, and it shows again with no further `load` when it is admitted again. The loop reads no record while `builtins` lists none of `load`, `unload`, and `switch`. In the following runs, the second conversation shows nothing until its own load, and the restored one shows the skill from its first request:
532
+ What a run shows comes from its conversation. Each turn reads the conversation's stored messages for every successful `load`, `unload`, and `switch` call, recognized by the note it returned, and keeps what the registries hold and the ceiling admits. The shown skills are the model's, in load order, and a skill loaded again after its unload goes last. A denied, refused, or failed call shows nothing, and so does a tool message whose text equals a note but answers another tool's call. A record counts only while the run enables its built-in, so a host tool under a built-in's name on a run that doesn't enable it shows nothing. A stored record can't name its writer, so a record such a tool wrote counts after a run enables the built-in, bounded by the registry and the ceiling as every record is. The read repairs each call's arguments through the `repairValue` function of `@orkestrel/contract`, as the tool's door repairs them, so a `{ skill: 1 }` the door repaired to `'1'` shows the skill `'1'`. A host that removes a `load` call removes its call group, so the skill shows no longer, and a conversation restored from its `ConversationSnapshot` shows what it showed when the snapshot was taken. A skill the ceiling excludes, or the registry no longer holds, shows nothing, and it shows again with no further `load` when it is admitted again. The loop reads no record while `builtins` lists none of `load`, `unload`, and `switch`. In the following runs, the second conversation shows nothing until its own load, and the restored one shows the skill from its first request:
593
533
 
594
534
  ```ts
595
535
  import type { ProviderInterface } from '@orkestrel/agent'
@@ -670,7 +610,7 @@ await agent.generate({ prompt: { content: 'Look up the billing rules.' } })
670
610
 
671
611
  A selection handler chooses the conversation messages the next prompt carries for one user request. It has three homes: `AgentOptions.select` is the agent default, forwarded as `AgentContextOptions.select`, the active scope's `select` overrides it while that scope is active, and a run scope's `select` overrides both for that run. The `context.select` method takes the run scope as its fourth argument, resolves `run?.select ?? scope?.select ?? default` once per call, and returns `undefined` when no home holds a handler, so the default path awaits nothing before the first provider request.
672
612
 
673
- The loop calls the handler at each select site (run entry, the pre-first-turn compaction fold, and a compaction rebuild) with the run's conversation, the user message that ends that conversation's view at run entry, and the run's signal; when the view ends on another role, it calls no handler. It folds the result through `build({ selection, scope })`, with the run scope as `scope`. That build carries `selection.messages` in place of `view()` after the unchanged system and context messages, and the loop then emits `select` with the `Selection`. That event fires at each select site, so twice before turn 0 when the pre-first-turn fold runs, and never for a run cancelled during selection.
613
+ The loop calls the handler at the select site, run entry, with the run's conversation, the user message that ends that conversation's messages at run entry, and the run's signal; when the messages end on another role, it calls no handler. It folds the result through `build({ selection, scope })`, with the run scope as `scope`. That build carries `selection.messages` in place of `messages()` after the unchanged system and context messages, and the loop then emits `select` with the `Selection`. That event fires once before turn 0, and never for a run cancelled during selection.
674
614
 
675
615
  A `Selection` carries the `messages`, the `judgments` keys they rest on, the judge `usage` spent, and an optional `fault`. Its `messages` are conversation parts only: a handler that adds text for the model writes it into one of them, as a ledger writes its records into a copy of the request turn, because the system message holds host-authored text alone. It has no tool member: what a turn advertises and dispatches stays the scope's `tools` allow-list.
676
616
 
@@ -684,7 +624,7 @@ declare const provider: ProviderInterface
684
624
 
685
625
  // The agent default keeps the user turns; the focus mode keeps the request alone.
686
626
  const userTurns: SelectionHandler = async (conversation) => ({
687
- messages: conversation.view().filter((message) => message.role === 'user'),
627
+ messages: conversation.messages().filter((message) => message.role === 'user'),
688
628
  judgments: [],
689
629
  })
690
630
  const requestOnly: SelectionHandler = async (_conversation, request) => ({
@@ -712,7 +652,7 @@ const request = plain.context.messages.add({ role: 'user', content: 'Invoice 42.
712
652
  plain.context.select(plain.context.messages, request, new AbortController().signal) // undefined — no handler in either home
713
653
  ```
714
654
 
715
- 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.
655
+ A selection fails four ways. A handler throw emits `fault`, and the loop builds from `messages()` 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 `messages()` with a `fault` that names the change. A `system` message in a handler's selection is a fault over `messages()` 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.
716
656
 
717
657
  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.
718
658
 
@@ -724,9 +664,9 @@ A conversation's `judgments` store records what a judge answered about its messa
724
664
 
725
665
  The `resolve(judge, request, sources, signal)` method reuses every recorded judgment that matches and asks the judge once for the rest, recording what returns. A match compares the question as a JSON value, the sources in order, the rendered state, and the judge's configured `model` rather than the name a server reports, so a question whose keys arrive in another order, from a store that returns keys sorted or a host that builds it in another order, matches, and a changed criterion, a changed state, or a changed source order asks again. Criteria order reaches the prompt and a small model reads options by position, so a reused answer keeps the reading its first order earned; call `remove(id)` to ask again after reordering. A cancel keeps the records of the questions that completed and rethrows the abort.
726
666
 
727
- A question id is a caller key that the prompt never carries, so the whole question lives in `instructions`, and a judgment that needs an earlier answer is a second request. A snapshot carries `judgments` only while the store holds one, so a conversation without judgments serializes as `{ id, sections, messages }`, and a snapshot written without the member still validates and restores.
667
+ A question id is a caller key that the prompt never carries, so the whole question lives in `instructions`, and a judgment that needs an earlier answer is a second request. A snapshot carries `judgments` only while the store holds one, so a conversation without judgments serializes as `{ id, messages }`, and a snapshot written without the member still validates and restores.
728
668
 
729
- The `judgment`, `add`, and `resolve` methods return the stored deep-frozen record, and the `judgments` method returns a fresh array of them. `ConversationInterface.snapshot()` and `LedgerInterface.snapshot().conversation` carry those records. `MemoryConversationStore.get` hands back the stored snapshot object itself: its messages and sections are shared with the store, so an edit to them changes what the next `get` returns, and its judgments are frozen records, so a write to one throws `TypeError` in strict-mode code; copy a judgment through `copyJSON` to migrate or redact it. Hydrating takes an owned frozen copy and never touches its input.
669
+ The `judgment`, `add`, and `resolve` methods return the stored deep-frozen record, and the `judgments` method returns a fresh array of them. `ConversationInterface.snapshot()` and `LedgerInterface.snapshot().conversation` carry those records. `MemoryConversationStore.get` hands back the stored snapshot object itself: its messages and judgments are the conversation's frozen records, so a write to one throws `TypeError` in strict-mode code; copy a message or a judgment through `copyJSON` to migrate or redact it. Hydrating takes an owned frozen copy and never touches its input.
730
670
 
731
671
  The following conversation records one answer and then reuses it:
732
672
 
@@ -772,24 +712,26 @@ Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https
772
712
 
773
713
  ### Serving a conversation through a ledger
774
714
 
775
- 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 each completed exchange in the window as it was sent, then a copy of the request turn: the record lines the window doesn't hold, which the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. The window follows the seed without changing its selection. A request or a reply the window no longer holds re-enters a planned prompt through a labeled word match from the `recall` tool, and what a request's 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.
715
+ 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 each completed exchange in the window as it was sent, then a copy of the request turn: the record lines the window doesn't hold, which the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. The window follows the seed without changing its selection. A request or a reply the window no longer holds re-enters a planned prompt through a labeled word match from the `recall` tool, and what a request's lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the `respond` call rejects after the agent's `fault` event.
716
+
717
+ Run the ledger's agent only through the `respond` and `stream` methods: the ledger's agent serves only the ledger's `conversation`. The `agent` member is a `LedgerAgentInterface` value, a frozen record of the agent's `emitter`, `id`, `status`, `context`, and `abort` members with no `generate` or `stream` method, so every run on that agent is a pass of the active `respond` or `stream` call, on the ledger's `conversation`. Its `status` member reads the agent's live status, and its `abort` method ends the active pass partial with the reason it takes; because the caller didn't abort, the ledger then runs the answer pass. To serve another conversation, build another ledger or another agent for it. A direct call to the `context.select` method for a message no active `respond` or `stream` call owns returns a selection whose `fault` is a `LedgerError` with code `'REQUEST'`, on the ledger's conversation or another one, and asks the judge nothing; over another conversation, that selection carries that conversation's view alone. The calibration that opens a `respond` or `stream` call, and a `calibrate` call, own no message, so a direct selection during either faults the same way.
776
718
 
777
- Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. The `agent` member is a `LedgerAgentInterface` value, a frozen record of the agent's `emitter`, `id`, `status`, `context`, and `abort` members with no `generate` or `stream` method, so every run on that agent is a pass of the active `respond` call, on the ledger's `conversation`. Its `status` member reads the agent's live status, and its `abort` method ends the active pass partial with the reason it takes; because the caller didn't abort, the ledger then runs the answer pass. To serve another conversation, build another ledger or another agent for it. A direct call to the `context.select` method for a message no active `respond` call owns returns a selection whose `fault` is a `LedgerError` with code `'REQUEST'`, on the ledger's conversation or another one, and asks the judge nothing; over another conversation, that selection carries that conversation's view alone. The calibration that opens a `respond` call, and a `calibrate` call, own no message, so a direct selection during either faults the same way.
719
+ The `stream` method serves a request as `respond` serves it and returns a `StreamInterface` handle. Its `events` yield every pass's `AgentChunk` values in pass order, the first pass's and then the answer pass's, and its `result` settles the `LedgerResult` that `respond` settles, a rejection included. A chunk carries no pass boundary, so the tokens of a first pass that the answer pass replaces still reach you, while `result.content` holds the last pass's content alone: render the reply from `result.content`. Breaking out of `events` early aborts the request as a caller abort does, so the pass in flight ends partial and no answer pass runs, and the handle's `abort` method ends it the same way. Every refusal reaches you through `result` and `events`, so the `stream` call itself never throws. The `destroy` method destroys the conversation's emitter and the agent's emitter, which ends every subscription on them, the ledger's own included; after it, and after a host destroys either emitter by hand, the `respond`, `stream`, `calibrate`, and `snapshot` methods refuse with `LedgerError` code `'DESTROYED'`. A `destroy` call while a request is in flight throws `AgentError` with code `'CONCURRENCY'`, so abort the request and await it first. A message removed from the conversation, one by one or by `clear`, takes the ledger's marks of it at the removal, and the exchange window with them when the window held the message or one of its accepted amendment edges named it. A request in flight at the removal commits no window that names the message, and files no tool result onto another message, so neither the next request nor a snapshot carries its state.
778
720
 
779
721
  The method has the following pieces, each named by its export:
780
722
 
781
- - **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. A user message carrying an id or a number, as read by `extractLiterals`, stays non-quiet regardless of its recorded weights. If its winning category is quiet, `category` returns `undefined`; this floor supplies no fact, rule, or correction judgment. Shape assignments keep their categories. Hydrating recorded judgments applies the same floor, and the next filing asks the topic questions those messages previously skipped. 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 ignores amendment and supersession marks whose later message is quiet and reads the remaining 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.
723
+ - **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. A user message carrying an id or a number, as read by `extractLiterals`, stays non-quiet regardless of its recorded weights. If its winning category is quiet, `category` returns `undefined`; this floor supplies no fact, rule, or correction judgment. Shape assignments keep their categories. Hydrating recorded judgments applies the same floor, and the next filing asks the topic questions those messages previously skipped. 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. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059) took 68 judge calls and 136 s, and a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883) took 109 judge calls and 196 s, the category and topic questions included. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. A transient judge failure, such as an HTTP or protocol failure, a timeout, or a network error, rejects the `respond` call it belongs to, after the `fault` event, and stores nothing, so the next request asks the judge again about every question still unanswered. A question the judge refuses before inference, which it reports as a `JudgeError` with code `'QUESTION'`, refuses again under the same wording, message, and judge, so the ledger holds it: it stores a refused `Judgment` under the question's key, whose `missing` list names every candidate, reports a `LedgerError` with code `'HOLD'` through the agent's `fault` event once, in the request that held it, and serves that request with the question undecided. The error's `cause` is the judge's rejection, and its `context` holds the question's `key`, `phase`, and `sources`. Every later request, and a ledger hydrated from the snapshot, reads the held question as `skipped` and asks it no more. A change to the question's wording, to a desk topic, to the message, or to the judge's `model` asks it again, and the answer replaces the refusal under the same key. One key holds one judgment, so a judge that alternates between models A, B, and A asks a held question again on its return to A. Removing the message removes its holds, and `ledger.conversation.judgments.remove(key)`, with the key from the attempt or from the error's `context`, asks the question again at the next request. A question a wire refuses, such as one whose top logprob token repeats on Ollama, arrives as a stored refusal and reads the same way, with no `fault`. A held category question leaves its message live with no category: the message files on the owner record its text names, or as an orphan, never on the rules record, and acts as no correction. A held topic question leaves that topic off its message, and a held `amends` or `supersedes` question files no mark of its own. Treat a `'HOLD'` fault as an operational signal, because a judge that refuses every question holds every question, and requests go on with owner names alone. The `LedgerClassification` value ignores amendment and supersession marks whose later message is quiet and reads the remaining 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 a judgment with an answer (`cached`), held a refusal or lost a message the question names (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal, the rejection that holds a question included (`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.
782
724
  - **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 accepted 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. A write files its result as a finding, as a lookup does, and the finding supersedes every earlier finding whose ids or owner ids meet its `targets`, and every such finding without targets in its own tool group, which the `collectWriteSupersessions` helper reads and the `mergeSupersessions` helper merges into the filing. So the reads a write made stale leave the records, its own lines join their owner record, and a write that names no owner joins the owner record of the read it retired.
783
725
  - **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. A copy that follows a window numbers its sources after the ones the window holds, so one reference names one source across the window and that copy. 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 or partial, 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. An edge whose amender a newer message superseded points at that amender's newest live successor, followed through accepted supersessions alone, so a change fully received by the records is not called not shown. With no live successor, the edge keeps its endpoint, which reads as absent. Neither restores the superseded text. An amendment of an amender infers no edge to the earlier message. Earlier text can conflict with its correction; downstream correction application and semantic sentence withdrawal remain unproved.
784
726
  - **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 definitions the first pass can advertise and held back by the `LEDGER_SCALE_DRIFT` constant, of which the seed tail takes at most the `tail` share. The `tail` share bounds only the seed. The definitions the first pass can advertise are those the scope the request entered with admits, `recall` included, so a scope that hides definitions returns their price to the plan: the plan subtracts the gauge's overhead less the price of the hidden definitions, the lower of the gauge's scale and the calibrated definitions' overhead per estimate unit, times their estimate, so never more than their proportional share of the overhead, and a scope that hides every definition costs the plan no overhead. The calibrated definitions are every definition a turn can advertise but the tools a registered skill holds back while `agent.builtins` enables `load`, so a catalog registered behind skills leaves the plan the price of its ungated core. The plan also prices the skills the thread shows: their bodies in the head, and the definitions they add beyond the calibrated set at the higher of the gauge's scale and that overhead per estimate unit, as the `computeToolPrice` helper prices an addition. While the first pass advertises `load`, the plan holds back the price of the largest skill the ceiling admits and the thread doesn't show, as the `computeSkillPrice` helper prices it, and the price of one result, the longer of the longest stored tool result and the gauge's reply reserve, so a load the model makes has room. 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 and held sources stay unchanged. The plan budget bounds the records, the tail, and the window of a request's first call: it prices the built head, the tail, the window, and the copy with its records and images. Runtime recall and recovery fit their result groups separately. A request, a lookup result, or a faulted selection's whole view can still exceed 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 window and the copy 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 or a snapshot gauge priced on the same calibrated definitions, the ledger calibrates before its first pass, and it calibrates again before any later request that finds other calibrated definitions, and the `calibrate` method measures the price on demand and records the digest of the definitions it priced. Calibration sends the head the agent's context builds for an empty turn, within the scope at entry, with no conversation message. The first call carries the calibrated definitions and no workspace text, and the second carries neither; their difference is the overhead. When the workspace renders text, a third call carries the head and that text with no definitions, cut to a third of the capacity the second call left, in characters, as the `LEDGER_SAMPLE_BYTES` constant sets. The scale is the reported prompt of the head with the workspace over its estimate, with a cut text's tokens scaled to the whole text's estimate, and never under the head's own rate. A long thread moves no call, and no workspace moves one past `capacity`. When the call with the definitions reports a prompt over `capacity`, the head included, the ledger sends no second call, stores no gauge, and rejects `calibrate` and `respond` with `LedgerError` code `'GAUGE'`, whose `context` holds `capacity` and `prompt`; the call without them and the call with the workspace text refuse the same way, and a refused `respond` stores no request. The error's text names the call and its prompt, such as `the calibration call with the tool definitions prices 9000 tokens, the head included, over the capacity 8192`. A scope doesn't change the calibrated set, so the remedy is the one the error names: hold tools behind a skill with the `load` built-in, which takes them out of the calibrated set and still lets a scope that lists them advertise them, register fewer tools, or raise `capacity`. A head over `capacity` on its own clears only through a shorter system prompt or a larger `capacity`, and a workspace call over it through a scope that shows less of the workspace or a larger `capacity`, which its error names. A load, a change to the ceiling, and an edit to a held-back definition leave the calibrated set as it was, so none of them calibrates. A lookup in the tail reaches the model as the stub the `renderStub` helper writes, which reads `shown` when the window and the copy together hold its whole result or the whole result of a finding with the same canonical lookup identity and text. A `hidden` stub names the `recall` call that finds its result only when the window rung the plan admits offers `recall` and the scope admits it; otherwise it reads `result not shown`. The plan reaches the agent as a `Selection` value whose `messages` member is the tail, then each exchange in the window, then the copy of the request turn that the `buildRequestMessage` helper writes: the record lines the window doesn't hold, a blank line, a `## Request` heading, and the request. A copy with no line to add is the request itself. The answer pass carries the same copy, and the stored request keeps its own content.
785
- - **The window.** The ledger holds one `LedgerExchange` value per completed exchange: the request as it was sent, its final reply, and the record lines that copy rendered. Each prompt sends those exchanges in order, so a prompt extends the one before it, within the limits the **A follow-up can read the reply again.** bullet names. A copy holds only the record lines the window doesn't hold, matched by identity and never by text, so identical words under another source render with their own attribution. A titled record's line is held by record, source, and sentence, so a source under another owner's record renders again for its attribution. A line of a source outside the selected records, which renders under no title, is held by source and sentence under any placement, so it doesn't repeat what an earlier copy printed under a title. A line the window holds stays held whether or not a later request selects its record. The seed and the records are planned without the window, so the window spends only the spare room of the plan's total and never displaces a record line or a seed message. The plan prices the following rungs in order and sends the first whose prompt fits the total and, if that rung offers `recall`, leaves an open recall open: the whole window with a copy of the lines it doesn't hold, then the newest exchange with its request plain and a copy of every selected line, then no exchange and a copy of every selected line. When no rung meets both tests, the plan sends no exchange. A recall already closed with no exchange at all doesn't prevent admission. A fall to a lower rung is silent, with no note, and an answered request leaves the window as what it sent plus its own exchange, so the exchanges a fall left out don't return. An admitted window can reduce recall listing room without closing recall. Admission retains its reserve forecast. Runtime recall reads reported usage when available, including completion and replayed thinking, and fits its result without that reserve veto. The window empties when a message it holds changes or leaves the conversation, when a source it holds leaves the records, when the accepted amendments touching a message it holds change, when a request no longer pairs with the reply held for it, or when this request's lines would change an amendment note or reference an earlier copy printed. A source missing from this request's selected records empties nothing. An empty window derives the newest request and its final reply from the conversation, with the request plain, or nothing when the newest request holds no valid reply. A window a change empties keeps its last exchange, with the request plain, when the derive gives nothing because a later request failed and that exchange's reply still stands, so a stopped request doesn't lose the reply a person read. It never carries a removed reply, and it never falls back to an exchange older than that. A derived pair seats before the request is sent. A request that rejects or ends with no reply leaves the window as it stands, a seated derived pair included, so the next prompt holds the last good exchange. A request answered through the whole view under `strict: false` joins with its stored request plain and no lines. Tool calls, tool results, and ledger notes never enter the window, so a request that called a tool joins as its copy and its final reply.
786
- - **The `recall` tool.** The tool requires a nonempty topic string; an empty topic fails argument admission. The ledger registers a `recall` tool beside the application's lookups and offers it only on a request with something to find: a user statement, including a quiet one, a lookup finding with a result, an earlier request, or a nonblank call-free reply that the seed tail, the window, and the copy together don't hold whole. A lookup stub doesn't hold its result, but a fully received finding with the same canonical lookup identity and text holds an identical finding's result too. A partly shown message counts as hidden, and a finding with no result never opens the offer. A retired finding never opens the offer either: one a write superseded through its `targets`, or one a later finding of the same canonical lookup identity replaced with different text or an empty result, as the `collectRetiredFindings` helper reads them. A live hidden finding still opens it. A ledger note and the current request's own turns never open the offer. The `collectRecallMessages` and `hasHiddenRecall` helpers read this per request from the conversation, so a hydrated ledger offers what the uninterrupted one offers. When nothing is hidden, the ledger narrows the agent's scope to the other tools for that request, keeping a host's allow-lists and selector, and the `respond` method restores the host's own scope when it settles, a rejection or an abort included, only while the plan's scope is still active. A scope the host applied in the meantime stays active. The tool's description reads that it finds something said earlier that isn't in the messages the model can see. It lists matching statements and lookup findings first, newest first, each source followed by the amenders the topic doesn't match itself; an amender the topic matches lists as its own newer item. It then lists earlier requests and call-free, non-empty assistant replies, newest first, under `Earlier request:` and `Earlier reply:`. A conversation match contains every word of at least one part of the topic, including when that part also names an owner. This conversation route excludes the current request and its turns, ledger notes, and messages already listed, and neither route lists a retired finding, as its own item or as an amender. It keeps the stored text, with each run of line breaks written as a line break and two spaces so that only a label opens a line, and it admits a partial reply the conversation stored before an abort. A hidden quiet statement can open the offer by itself, and a word match can list it. A cut landing mid-stream stores no reply and carries nothing. On the statement and lookup route, only lines opening with `Earlier request:` or `Earlier reply:` gain the same two-space indent; every other byte, including stored line breaks, stays unchanged. A label names the message's role, so a host-added assistant message in the seed reads as a reply too. These listings do not promote replies or requests into records. A search that finds nothing returns `nothing earlier on "TOPIC"; answer from the messages you can see`, where `TOPIC` is the searched topic, and that result enters no answer note. A blank topic still returns its guidance as a failure. The route reads the conversation and not the prompt, so it can list a request or a reply the window already carries. The tool fits whole items, including each source's amenders, into what the measured request leaves below capacity less predict, and names how many items it left out. An oversized item is omitted, and a later fitting item can still be returned. The result and its omission line share the allowance, with tool-message framing counted. When no item fits, the line reads `N older items didn't fit in this request; answer from the messages you can see`, using `item` for one and `more` for conversation matches. A partial listing keeps `N older items not shown; name a narrower topic to narrow the recall`. A `recall` call a host makes by hand between requests fits its listing to the same allowance when the ledger holds a gauge; with no gauge, the first whole item remains unconditional. The cut line uses `more` when an omitted item precedes a kept one in listing order, or when conversation matches are listed; otherwise it uses `older`. This rule applies to both omission forms. Statements and lookup findings take priority over conversation matches. A request can call it as many times as the `limit` member of the `recall` option allows, the `DEFAULT_RECALL_LIMIT` constant by default; after that it returns the `closure` note. Lack of room never closes recall: a distinct later call is fitted independently. The prefix uses the last call's reported prompt and completion, adjusted for replay by `Gauge.remainder`; missing usage uses an estimate. Additions use the larger of `Gauge.rate` and the last reported call's prompt less known overhead divided by its estimate, with `LEDGER_SCALE_DRIFT` headroom. As in `Gauge.observe`, a partly spared call keeps the marginal rate instead of guessing an overhead share. Calls without reported usage use the marginal rate alone. Sibling recall results share the room. A listing within the `LEDGER_SCALE_DRIFT` margin of the room can be left out, with the omission line stating that it did not fit this request.
727
+ - **The window.** The ledger holds one `LedgerExchange` value per completed exchange: the request as it was sent, its final reply, and the record lines that copy rendered. Each prompt sends those exchanges in order, so a prompt extends the one before it, within the limits the **A follow-up can read the reply again.** bullet names. A copy holds only the record lines the window doesn't hold, matched by identity and never by text, so identical words under another source render with their own attribution. A titled record's line is held by record, source, and sentence, so a source under another owner's record renders again for its attribution. A line of a source outside the selected records, which renders under no title, is held by source and sentence under any placement, so it doesn't repeat what an earlier copy printed under a title. A line the window holds stays held whether or not a later request selects its record. The seed and the records are planned without the window, so the window spends only the spare room of the plan's total and never displaces a record line or a seed message. The plan prices the following rungs in order and sends the first whose prompt fits the total and, if that rung offers `recall`, leaves an open recall open: the whole window with a copy of the lines it doesn't hold, then the newest exchange with its request plain and a copy of every selected line, then no exchange and a copy of every selected line. When no rung meets both tests, the plan sends no exchange. A recall already closed with no exchange at all doesn't prevent admission. A fall to a lower rung is silent, with no note, and an answered request leaves the window as what it sent plus its own exchange, so the exchanges a fall left out don't return. An admitted window can reduce recall listing room without closing recall. Admission retains its reserve forecast. Runtime recall reads reported usage when available, including completion and replayed thinking, and fits its result without that reserve veto. The window empties when a message it holds changes or leaves the conversation, when a source it holds leaves the records, when the accepted amendments touching a message it holds change, when a request no longer pairs with the reply held for it, or when this request's lines would change an amendment note or reference an earlier copy printed. A source missing from this request's selected records empties nothing. An empty window derives the newest request and its final reply from the conversation, with the request plain, or nothing when the newest request holds no valid reply. A window a change empties keeps its last exchange, with the request plain, when the derive gives nothing because a later request failed and that exchange's reply still stands, so a stopped request doesn't lose the reply a person read. It never carries a removed reply, and it never falls back to an exchange older than that. A derived pair seats before the request is sent. A request that rejects or ends with no reply leaves the window as it stands, a seated derived pair included, so the next prompt holds the last good exchange. Tool calls, tool results, and ledger notes never enter the window, so a request that called a tool joins as its copy and its final reply.
728
+ - **The `recall` tool.** The tool requires a nonempty topic string; an empty topic fails argument admission. The ledger registers a `recall` tool beside the application's lookups and offers it only on a request with something to find: a user statement, including a quiet one, a lookup finding with a result, an earlier request, or a nonblank call-free reply that the seed tail, the window, and the copy together don't hold whole. A lookup stub doesn't hold its result, but a fully received finding with the same canonical lookup identity and text holds an identical finding's result too. A partly shown message counts as hidden, and a finding with no result never opens the offer. A retired finding never opens the offer either: one a write superseded through its `targets`, or one a later finding of the same canonical lookup identity replaced with different text or an empty result, as the `collectRetiredFindings` helper reads them. A live hidden finding still opens it. A ledger note and the current request's own turns never open the offer. The `collectRecallMessages` and `hasHiddenRecall` helpers read this per request from the conversation, so a hydrated ledger offers what the uninterrupted one offers. When nothing is hidden, the ledger narrows the agent's scope to the other tools for that request, keeping a host's allow-lists and selector, and the `respond` method restores the host's own scope when it settles, a rejection or an abort included, only while the plan's scope is still active. A scope the host applied in the meantime stays active. The tool's description reads that it finds something said earlier that isn't in the messages the model can see. It lists matching statements and lookup findings first, newest first, each source followed by the amenders the topic doesn't match itself; an amender the topic matches lists as its own newer item. It then lists earlier requests and call-free, non-empty assistant replies, newest first, under `Earlier request:` and `Earlier reply:`. A conversation match contains every word of at least one part of the topic, including when that part also names an owner. This conversation route excludes the current request and its turns, ledger notes, and messages already listed, and neither route lists a retired finding, as its own item or as an amender. It keeps the stored text, with each run of line breaks written as a line break and two spaces so that only a label opens a line, and it admits a partial reply the conversation stored before an abort. A hidden quiet statement can open the offer by itself, and a word match can list it. A cut landing mid-stream stores no reply and carries nothing. On the statement and lookup route, only lines opening with `Earlier request:` or `Earlier reply:` gain the same two-space indent; every other byte, including stored line breaks, stays unchanged. A label names the message's role, so a host-added assistant message in the seed reads as a reply too. These listings do not promote replies or requests into records. A search that finds nothing returns `nothing earlier on "TOPIC"; answer from the messages you can see`, where `TOPIC` is the searched topic, and that result enters no answer note. A blank topic still returns its guidance as a failure. The route reads the conversation and not the prompt, so it can list a request or a reply the window already carries. The tool fits whole items, including each source's amenders, into what the measured request leaves below capacity less predict, and names how many items it left out. An oversized item is omitted, and a later fitting item can still be returned. The result and its omission line share the allowance, with tool-message framing counted. When no item fits, the line reads `N older items didn't fit in this request; answer from the messages you can see`, using `item` for one and `more` for conversation matches. A partial listing keeps `N older items not shown; name a narrower topic to narrow the recall`. A `recall` call a host makes by hand between requests fits its listing to the same allowance when the ledger holds a gauge; with no gauge, the first whole item remains unconditional. The cut line uses `more` when an omitted item precedes a kept one in listing order, or when conversation matches are listed; otherwise it uses `older`. This rule applies to both omission forms. Statements and lookup findings take priority over conversation matches. A request can call it as many times as the `LEDGER_RECALL_LIMIT` constant allows, 2 calls, and a later call in that request returns the `closure` note. Lack of room never closes recall: a distinct later call is fitted independently. The prefix uses the last call's reported prompt and completion, adjusted for replay by `Gauge.remainder`; missing usage uses an estimate. Additions use the larger of `Gauge.rate` and the last reported call's prompt less known overhead divided by its estimate, with `LEDGER_SCALE_DRIFT` headroom. As in `Gauge.observe`, a partly spared call keeps the marginal rate instead of guessing an overhead share. Calls without reported usage use the marginal rate alone. Sibling recall results share the room. A listing within the `LEDGER_SCALE_DRIFT` margin of the room can be left out, with the omission line stating that it did not fit this request.
787
729
  - **The repeat stop.** A lookup, write, or `recall` call that repeats an earlier call of the same request, compared by tool name and canonical arguments, returns the `repeat` note as its failure, and the ledger aborts the pass. For a lookup, the repeat stop's identity compares string arguments as written. The projection's lookup identity, which the `identifyLookup` helper writes, trims and uppercases each top-level string argument and decides which finding replaces an earlier one. So `lookup_order` calls for `bw-5512` and `BW-5512` both run in one request, and the second finding replaces the first in the records when its text differs. A finding with different text or an empty result replaces the earlier one, a finding with the same text replaces nothing, so the first unsuperseded finding of the final same-text run stays live, and a thrown call files no finding, leaving the earlier result live. A write that runs admits again each lookup call whose finding it retired, so a read in a later turn that checks the write runs, and a second identical read with no write between is still a repeat. A lookup or write call its tool refuses for its arguments is never a run: when the tool's `execute` throws, or returns a promise that rejects with, an error `isToolError` admits whose code is `'ARGUMENTS'`, from the tool's own door or its handler, the request releases the call, so the identical call runs again, the model can repair it, and the agent's `limit` bounds a model that keeps sending it. The release lands when the refusal does, so an identical twin in the same batch that starts while a promise's refusal is still pending reads as a repeat. Every other failure of a call that reached its tool counts as a run: another thrown or rejected error, a `ToolError` of another code, and a refusal the host raises inside the handler, such as a declined confirm. A host registry's `execute` answers a refusal as a failure with no code, so a handler that routes through one and rethrows that failure turns an argument refusal into a run; call `tools.tool(name)` and its `execute` to keep the code. A call the agent's scope or authority refuses, or its approver declines or leaves unanswered, never reaches its tool. When the authority's `evaluate` method denies a lookup or write call, or its ask is declined or left unanswered, the request records the call as denied, and its identical retry in a later turn of the same request is denied with the `repeat` note as its reason before the authority's `evaluate` method reads it and with no ask, so the ledger aborts the pass and the person is asked once. Every call of a batch is evaluated before the first ask, so the identical twin in one batch of a call whose ask was declined or left unanswered reaches the ledger's `ask`, which refuses it without entering the host's approver: the agent reports the twin's `ask` event, then its `deny` event, the twin reads the `refused` note, and its pass goes on. The twin of a call the `evaluate` method denied stops as a repeat. A later request asks again, and a call with other arguments is evaluated and asked as before. A denial that the agent's `deny` event reports with no decision records nothing: a scope miss, a throwing `evaluate` method or an invalid decision, and a cleared call whose tool changed before dispatch. An asked call whose tool changed before its approval returned is denied as unanswered with its decision, so the request records it.
788
730
  - **The stray stop.** A call the model makes in a turn that advertises no tools runs nothing, in the first pass and the answer pass alike: the agent refuses it once, as its `deny` and `tool` events and the stream's `tool` chunk report, and the ledger then ends that pass, which the agent's `abort` event reports with the reason `'stray'`. So a pass whose dispatched request advertises no tools makes at most one model generation, whatever the agent's `limit`. The ledger reads each request a turn dispatches through the agent's `request` event, and every run on its agent is a pass on the ledger's `conversation`, so its count of advertised tools is the provider's even when a `turn` listener or a scheduler yield changes the scope after an earlier listener ran. A first pass advertises no tools when the ledger registers no lookup and no write and nothing is hidden, because the plan then leaves `recall` out too, and the guide's example ledger is one. When every call of that turn failed, the ledger stores the reply again without its calls and their refusals, as a call-free turn stores it, so the call files no finding, retires nothing, and leaves the records, the window, the snapshot, and the `recall` tool as a call-free pass leaves them. A reply that carries text beside the call ends the pass with that text and `partial: false`. A reply with no text ends it partial with empty content, so after a first pass the ledger runs the answer pass, as it does after an empty first pass. A turn that advertises any tool keeps the pass running: a call to a name it doesn't advertise is refused and the pass runs on, up to the agent's `limit`.
789
731
  - **The answer pass.** When the first pass ends partial or without final text and the caller didn't abort, the ledger adds an answer note when the pass's lookups or recalls returned anything, carrying what they returned without their call text, then the `cue` note, and runs one answer pass that advertises no tools and always turns thinking off. A call the model makes there anyway ends the pass after its one generation, whatever the agent's `limit`, as **The stray stop.** states, and a reply with no text makes the `respond` method resolve partial with empty content. The answer pass runs under a run scope of its own, the scope the request entered with narrowed to no tools, so it advertises nothing whatever scope a host applies during the request, and it leaves the `context.scope` value as it found it. Both passes bind the scope the request entered with: a scope a host widens during a request adds no tool to either pass, and no instruction, skill, memo, or file to the answer pass, before the next request, while a scope a host narrows during it hides a tool from the next turn. Before that pass, the ledger prices the rebuilt prompt at the same request-local rate. If it exceeds capacity less predict, it leaves a call-free partial assistant reply out of the prompt while keeping it stored, then fits the union of result groups to the remaining room. Source and amendment groups stay whole. Only the omission line the ledger appended is excluded from the digest; a literal line inside an accepted source group is preserved, even when its text matches an omission line; groups already represented by earlier groups enter no second copy. A note that doesn't fit beside the rest of the prompt is left out. When the prompt with that reply and the note left out still exceeds capacity less predict, no answer pass opens, and the `respond` method rejects with `LedgerError` code `'OVERFLOW'`, as **The capacity gate.** states. The answer pass advertises nothing and carries every skill body the thread shows, and its note carries what a `memo` call returned and no other built-in's acknowledgement. The `passes` member of the `LedgerResult` value holds both passes, and its `content` member is the last pass's. A rejected first pass counts as unfinished. When the answer pass rejects as well, the `respond` method rejects with that pass's error, and the ledger stays free for a later request.
790
732
  - **The capacity gate.** A ledger sends no request it prices over the `capacity` option less the `predict` option, and the rule holds for every ledger and every request of a pass. The ledger prices each request as the agent composed it, when the agent's `request` event fires: the definitions it advertises against the calibrated set, and its messages at the rate the request has measured, never under the gauge's scale, with the `LEDGER_SCALE_DRIFT` margin. The plan cuts what the ledger owns: record lines, the seed tail, and the exchange window. It never cuts your system text, instructions, memos, skills, workspace, or definitions, or the request. A first request that doesn't fit after those cuts isn't sent: the agent's `abort` event carries the reason `overflow`, and the answer pass answers without tools. A later turn that doesn't fit, for example after a large lookup result, isn't sent, and the answer pass answers from the results note. An answer pass that doesn't fit isn't sent, and `respond` rejects with `LedgerError` code `'OVERFLOW'`, whose `context` holds `capacity`, `predict`, and `price`. Shorten the request, narrow what the scope shows, or raise `capacity`. To give a large tool set room, hold definitions back behind skills and enable `load`. To give a large workspace room, size it to what the definitions leave. The price carries the `LEDGER_SCALE_DRIFT` margin, so a request within that margin under the limit can be refused. After an `'OVERFLOW'` rejection, the conversation keeps the request message, and the calls the first pass made with their results and the findings they filed, and the window stays as it stood, as after any request that rejects. A rejection the answer pass's fit raises stores no note and no cue. A rejection at the answer pass's request, after a host edit grew it past the limit, keeps the note and the cue that pass stored. A run aborted from a `request` listener sends nothing for that turn, and a listener reads the request and never writes into a message or a definition it shares, because the ledger's price holds only for the request as frozen.
791
733
  - **The built-ins.** The `builtins` member of the `agent` option enables the built-in tools and its `workspace` member names the workspace a request renders in place of the active one, as [Enabling the built-in tools](#enabling-the-built-in-tools) describes, and a ledger with `builtins` requires the `authority` member: construction throws `AgentError` with code `'AUTHORITY'` without it. Each built-in call meets the ledger's tests before the host's authority reads it, and every call they admit reaches the authority's `evaluate` method and, when asked, its `ask` method. `remember` carries the `consequential` annotation, so an `ask` that approves every call approves each `remember` too. In one request, the identical second call of a built-in returns the `repeat` note as its denial before the authority reads it, and the ledger ends the pass. The ledger tests a `load`, a `remember`, and a `switch` for room against the remainder the gauge measured less `predict`, with what the call's batch already committed and the `LEDGER_SCALE_DRIFT` margin, and denies a call that doesn't fit with the `overflow` text of the `LEDGER_NOTES` constant as its reason, changing nothing. A `load` is admitted by its skill's price and one result's price, and by the `skills` share: the skills the thread shows, the loads its batch already admitted, and its own skill take at most that share of the prompt budget. A `remember` is admitted by its index line as the `renderIndexEntry` helper renders it. Neither test prices an acknowledgement, and a host's memo `format.render` isn't priced at admission. A `switch` is admitted by the tokens its workspace adds over the shown one, and a denied `switch` leaves the shown workspace as it was. A workspace the host gives or leaves active meets no admission, and **The capacity gate.** bounds it. A call the room admits commits its price, and a lookup or a write the authority clears commits one result's price, so a `load` later in the same batch counts it. A commitment stands for its turn when the host's authority denies the call or its handler refuses it. The `commit` method of the `LedgerRequestInterface` takes the price and, for a `load`, its skill, and its `loads` member holds the skills of the loads committed after the call in flight started. A denial for room stays out of the repeat stop, and a successful call reopens the calls of its request whose answer it changed: an `unload` reopens the `load` of its skill and every call the room denied, a `load` the `unload` of its skill, a `switch` every other `switch`, and a `remember` the `memo` of its name. So in one request a `memo`, a `remember`, and a `memo` of one name read the revised body, a `load`, an `unload`, and a `load` of one skill load it again, and a `switch` back to the first of two workspaces switches back, while an identical call with no such call between is a repeat. No built-in's tool message files a finding, a record, or a `recall` listing. A ledger hydrated from its snapshot shows the skills and the workspace its thread showed, within the ceiling in force then, and reuses a stored gauge priced on the same calibrated definitions with no calibration call.
792
- - **The thinking budget.** The `predict` option reserves the generation room that thinking and the reply share, taking it out of the plan budget, the runtime recall room, and the answer prompt allowance. The plan's reserve-based admission rule stays unchanged. The gauge counts only the thinking the next request carries: under the provider's default `replay` of `'none'`, it leaves a call's thinking out of the capacity that call used, and the `computeThinking` helper apportions that thinking from the completion by character share. Under every policy, the reply reserve reads the reply without its thinking. The `think` option requests or suppresses thinking for the first pass, and omission leaves the provider's default; the answer pass always runs with thinking off. With replay `'none'`, a ledger at a `capacity` of `W + P` with a `predict` of `P`, where `W` is a context window and `P` a generation cap, budgets like a ledger at `W` without thinking.
734
+ - **The thinking budget.** The `predict` option reserves the generation room that thinking and the reply share, taking it out of the plan budget, the runtime recall room, and the answer prompt allowance. The plan's reserve-based admission rule stays unchanged. The gauge counts only the thinking the next request carries: under the provider's default `replay` of `'none'`, it leaves a call's thinking out of the capacity that call used, and the `computeThinking` helper apportions that thinking from the completion by character share. Under every policy, the reply reserve reads the reply without its thinking. The `think` option requests or suppresses thinking for the first pass, and omission leaves the provider's default; the answer pass always runs with thinking off. With replay `'none'`, a ledger at a `capacity` of `W + P` with a `predict` of `P`, where `W` is a context window and `P` a generation cap, budgets like a ledger at a `capacity` of `W + 1` with a `predict` of 1 that doesn't think.
793
735
 
794
736
  Display references identify sources within the rendered records while the line keeps the stored identity:
795
737
 
@@ -818,7 +760,7 @@ The application supplies the following through `LedgerOptions`:
818
760
  - the writes, through the `writes` option, each a tool annotated `consequential` and a reading handler that names the ids, the owners, and the `targets` in its result, the ids whose state the call changed or removed;
819
761
  - the agent options, through the `agent` option, whose `authority` member gates every lookup and write and is required with writes; the option holds the `LedgerAgentOptions` pick and refuses any other member with a refusal that opens `Ledger agent:`, so set a scope through `ledger.agent.context.apply`, and leave the token budget to the ledger, which derives it from `capacity`, `predict`, and `share`;
820
762
  - the capacity, through the `capacity` option, the model's context window in tokens;
821
- - the generation cap, through the `predict` option, in tokens with thinking included, 0 by default and less than `capacity`;
763
+ - the generation cap, through the required `predict` option, in tokens with thinking included, a positive integer less than `capacity`;
822
764
  - the thinking of the first pass, through the boolean `think` option; the answer pass always runs with thinking off;
823
765
  - the state to hydrate from, through the `snapshot` option, which takes what a ledger's `snapshot` method returned: the conversation with its judgments, the marked request, note, and failed tool result ids, the gauge, which a `gauge` option overrides and which holds only for the tool definitions it priced, and the window while it holds an exchange.
824
766
 
@@ -865,7 +807,7 @@ When a provider's model has a framing preference, such as XML tags, install that
865
807
 
866
808
  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.
867
809
 
868
- `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.
810
+ `ProviderInterface` is the boundary; `AgentProvider` is the engine behind it. Every provider carries `model`, the non-empty name of the model it serves: `createAgent` and `createLedger` refuse a provider whose `model` is missing, not a string, or empty with a `ContractError` coded `'placement'`, and a ledger reuses a stored gauge only under the `model` it was measured on. 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.
869
811
 
870
812
  ```ts
871
813
  import type { AgentProviderInput, ProviderInterface } from '@orkestrel/agent'
@@ -878,6 +820,7 @@ const messages = [{ id: '1', role: 'user', content: 'Say hello.' }] as const
878
820
 
879
821
  const provider = createTextProvider({
880
822
  url: 'https://api.example',
823
+ model: 'qwen3:4b', // the model the provider serves; createAgent and createLedger refuse an empty one
881
824
  path: '/generate', // appended to `url` on every call
882
825
  timeout: 30_000, // the base's own deadline; DEFAULT_PROVIDER_TIMEOUT when omitted
883
826
  headers: async (signal) => ({ authorization: await token(signal) }), // awaited inside that deadline
@@ -910,7 +853,7 @@ The provider's `replay` member decides which recorded thinking goes back to the
910
853
 
911
854
  Choose `'turn'` for a backend that reads thinking inside a tool loop. Some chat formats keep the thinking of the turn in progress and drop older thinking, such as the Qwen3 template (see [the Qwen3 model card](https://huggingface.co/Qwen/Qwen3-235B-A22B)), and some APIs refuse a tool turn that leaves out its thinking, such as DeepSeek's (see [DeepSeek thinking mode](https://api-docs.deepseek.com/guides/thinking_mode)). The `thinking` member is a plain string, so it can't carry a signature that an API requires beside the text, such as Anthropic's (see [Anthropic extended thinking](https://platform.claude.com/docs/en/build-with-claude/thinking)).
912
855
 
913
- The agent loop, a relay server, and a ledger apply the policy before calling the provider. A direct `generate` or `stream` call sends messages as given. The agent applies the policy through `stripThinking` before every provider call and before every compaction estimate, and a provider without a `replay` member counts as `'none'`. `estimateRequest` counts a message's `thinking`, so the `window` budget counts the thinking the request carries and no other. A ledger applies the same policy to the tail and the window it plans and each call it measures, and calibration applies the policy at the next user boundary, as if a user message followed the conversation view. Calibration prices the whole view; a planned request carries only the selected tail, so the retained messages can differ.
856
+ The agent loop, a relay server, and a ledger apply the policy before calling the provider. A direct `generate` or `stream` call sends messages as given. The agent applies the policy through `stripThinking` before every provider call, and a provider without a `replay` member counts as `'none'`. `estimateRequest` counts a message's `thinking`, so a budget it measures counts the thinking the request carries and no other. A ledger applies the same policy to the tail and the window it plans and each call it measures, and calibration applies the policy at the next user boundary, as if a user message followed the conversation view. Calibration prices the whole view; a planned request carries only the selected tail, so the retained messages can differ.
914
857
 
915
858
  A relay applies both policies. The agent in the browser strips the request by the policy of its `RelayProvider`, the request carries each remaining `thinking` member, and `RelayStream` strips it again by the upstream provider's policy, so the upstream call carries only the thinking that both policies keep.
916
859
 
@@ -983,6 +926,7 @@ const handler = createRelay({
983
926
  // In the browser: a provider like any other, reached over that route.
984
927
  const browser = createRelayProvider({
985
928
  url: 'https://app.example/relay',
929
+ model: upstream.model, // the model the server's upstream provider serves
986
930
  headers: () => ({ authorization: 'Bearer session-token' }),
987
931
  })
988
932
  ```
@@ -1099,6 +1043,7 @@ The following table lists the helpers the root declares:
1099
1043
  | `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. |
1100
1044
  | `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. |
1101
1045
  | `extractLiterals` | function | `(text: string) => LiteralSet` | Reads the ids and the numbers of a text. |
1046
+ | `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. |
1102
1047
 
1103
1048
  #### Validators
1104
1049
 
@@ -1124,11 +1069,11 @@ The following table lists the types the providers module declares:
1124
1069
  | `ProviderResult` | interface | `{ content, thinking?, tools?, usage?, truncated? }` | Holds a single inference turn's structured outcome — the assembled assistant content, any reasoning the provider separated from it, any tool calls the model requested, and the token usage it reported. |
1125
1070
  | `ProviderDelta` | type | `{ readonly channel: 'content'; readonly text: string; } \| { readonly channel: 'thinking'; readonly text: string; }` | Represents one streamed delta the `stream` method of a `ProviderInterface` yields — a unit tagged by the channel it belongs to, so the agent loop can forward answer content and live reasoning separately as each delta arrives. |
1126
1071
  | `ProviderStreamOptions` | interface | `{ think?, schema? }` | Carries the per-call options threaded into the `generate` and `stream` methods of a `ProviderInterface` — the bag a caller passes to influence one inference call without reconfiguring the provider instance. |
1127
- | `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. |
1072
+ | `ProviderInterface` | interface | `{ id, name, model, 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. |
1128
1073
  | `ProviderParserInterface` | interface | `{ parse(), clear() }` | Defines the structural framing seam supplied by a concrete provider. |
1129
1074
  | `ProviderRequest` | interface | `{ messages, tools?, options? }` | Carries the conversation and per-call configuration sent to a provider. |
1130
1075
  | `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result?, done? }` | Holds the decoded contribution of a wire record to a provider turn. |
1131
- | `ProviderOptions` | interface | `{ timeout?, replay?, fetch?, headers? }` | Configures a provider's deadline, transport, and headers. |
1076
+ | `ProviderOptions` | interface | `{ model, timeout?, replay?, fetch?, headers? }` | Configures a provider's model, deadline, transport, and headers. |
1132
1077
  | `AgentProviderInput` | interface | `{ url, path?, split?, strict? }` | Configures the HTTP destination and stream assembly of a provider base. |
1133
1078
  | `AgentProviderInterface` | interface | `{ frame(), encode(), read(), finish() }` | Defines the wire-specific seams of the shared HTTP provider engine. |
1134
1079
  | `ProviderErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'PROVIDER'` | Names the machine-readable provider failure conditions. |
@@ -1164,29 +1109,29 @@ The following table lists the types the providers module declares:
1164
1109
 
1165
1110
  The following table lists the constants the providers module declares:
1166
1111
 
1167
- | Name | Kind | Signature | Summary |
1168
- | ---------------------------- | ----- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1169
- | `THINK_OPEN` | const | `"<think>"` | Names the opening tag a `ThinkSplitter` recognizes as the start of an in-content reasoning span — `'<think>'`, the de-facto wire convention thinking models (qwen3, DeepSeek-R1 family) emit their chain-of-thought under when a daemon renders it inline instead of on a separate wire field. Paired with `THINK_CLOSE`. |
1170
- | `THINK_CLOSE` | const | `"</think>"` | Names the closing tag that ends a `THINK_OPEN` reasoning span — `'</think>'`. A span the stream never closes (the model was cut off mid-reasoning) is treated as thinking to its end, and `ThinkSplitterInterface.flush` settles it. |
1171
- | `DEFAULT_PROVIDER_TIMEOUT` | const | `120000` | Holds the default provider deadline in milliseconds — `120_000`, the wall-clock bound a call runs under when `AgentProviderInput.timeout` is omitted, folded with the caller's signal so whichever trips first cancels the call. |
1172
- | `MAX_ERROR_BODY_LENGTH` | const | `2048` | Bounds the decoded error excerpt's input in bytes — `2048`, the leading bytes of a non-OK response body handed to the decoder before the read cancels the remainder, so a `ProviderError` message never carries a longer excerpt. |
1173
- | `DEFAULT_RELAY_LIMIT` | const | `1048576` | Holds the default relay request limit in bytes — `1_048_576`, the byte budget a relay applies to an inbound body when `RelayOptions.limit` is omitted, refusing a body that reaches it. |
1174
- | `RELAY_CONTENT_TYPE` | const | `"application/x-ndjson; charset=utf-8"` | Names the relay's newline-delimited JSON content type — `'application/x-ndjson; charset=utf-8'`, the header a relay response carries beside `cache-control: no-store`. |
1175
- | `RELAY_PROVIDER_MESSAGE` | const | `"relay provider failed"` | Names the public message for an unexpected upstream relay failure — `'relay provider failed'`, the fixed text every `error` frame carries, so an upstream failure's own message never reaches the browser. |
1176
- | `UNAUTHORIZED_RELAY_STATUS` | const | `401` | Names the status a relay answers when the `authorize` callback returns anything but `true` or throws — `401`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
1177
- | `INVALID_RELAY_STATUS` | const | `400` | Names the status a relay answers for a body that is missing, unreadable, or rejected by `providerRequestContract` — `400`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
1178
- | `OVERSIZED_RELAY_STATUS` | const | `413` | Names the status a relay answers for a request body at or above its byte budget — `413`, carried with no body and answered for an aborted inbound read as well. |
1179
- | `REFUSED_RELAY_STATUS` | const | `422` | Names the status a relay answers for a page system message or tool definition its policy refuses — `422`, carrying one `REFUSED_RELAY_CONTENT_TYPE` line per refused member and reaching the browser as a `ProviderError` with the `HTTP` code. |
1180
- | `REFUSED_RELAY_CONTENT_TYPE` | const | `"text/plain; charset=utf-8"` | Names the content type of a relay's `422` refusal body — `'text/plain; charset=utf-8'`, the header a refusal carries beside `cache-control: no-store`. |
1181
- | `UPSTREAM_RELAY_STATUS` | const | `502` | Names the status a relay answers when the upstream provider call cannot be constructed — `502`, carried with no body after `provider.stream` was entered and threw before returning its iterator. |
1182
- | `SYSTEM_ONE_PATH` | const | `"/v1/systemone"` | Names the System One decision endpoint shared by compatible servers. |
1183
- | `RELAY_OPTION_KEYS` | const | `readonly ["provider", "authorize", "limit", "system", "tools"]` | Lists the members `RelayOptions` declares, frozen — the keys `createRelay` admits. |
1184
- | `RELAY_PROVIDER_KEYS` | const | `readonly ["url", "parser", "timeout", "replay", "fetch", "headers"]` | Lists the members `RelayProviderOptions` declares, frozen — the keys the `RelayProvider` constructor admits. |
1185
- | `RELAY_STREAM_KEYS` | const | `readonly ["provider", "request", "signal"]` | Lists the members `RelayStreamOptions` declares, frozen — the keys the `RelayStream` constructor admits. |
1186
- | `PROVIDER_INPUT_KEYS` | const | `readonly ["url", "path", "split", "strict", "timeout", "replay", "fetch", "headers"]` | Lists the members `AgentProviderInput` declares, frozen — the keys the `AgentProvider` constructor admits. |
1187
- | `JUDGE_INPUT_KEYS` | const | `readonly ["url", "path", "model", "batch", "timeout", "fetch", "headers"]` | Lists the members `AgentJudgeInput` declares, frozen — the keys the `AgentJudge` constructor admits. |
1188
- | `SYSTEM_ONE_OPTION_KEYS` | const | `readonly ["url", "model", "timeout", "fetch", "headers"]` | Lists the members `SystemOneJudgeOptions` declares, frozen — the keys the `SystemOneJudge` constructor admits. |
1189
- | `STREAM_OPTION_KEYS` | const | `readonly ["think", "schema"]` | Lists the members `ProviderStreamOptions` declares, frozen — the keys the `generate` and `stream` methods of an `AgentProvider` admits. |
1112
+ | Name | Kind | Signature | Summary |
1113
+ | ---------------------------- | ----- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1114
+ | `THINK_OPEN` | const | `"<think>"` | Names the opening tag a `ThinkSplitter` recognizes as the start of an in-content reasoning span — `'<think>'`, the de-facto wire convention thinking models (qwen3, DeepSeek-R1 family) emit their chain-of-thought under when a daemon renders it inline instead of on a separate wire field. Paired with `THINK_CLOSE`. |
1115
+ | `THINK_CLOSE` | const | `"</think>"` | Names the closing tag that ends a `THINK_OPEN` reasoning span — `'</think>'`. A span the stream never closes (the model was cut off mid-reasoning) is treated as thinking to its end, and `ThinkSplitterInterface.flush` settles it. |
1116
+ | `DEFAULT_PROVIDER_TIMEOUT` | const | `120000` | Holds the default provider deadline in milliseconds — `120_000`, the wall-clock bound a call runs under when `AgentProviderInput.timeout` is omitted, folded with the caller's signal so whichever trips first cancels the call. |
1117
+ | `MAX_ERROR_BODY_LENGTH` | const | `2048` | Bounds the decoded error excerpt's input in bytes — `2048`, the leading bytes of a non-OK response body handed to the decoder before the read cancels the remainder, so a `ProviderError` message never carries a longer excerpt. |
1118
+ | `DEFAULT_RELAY_LIMIT` | const | `1048576` | Holds the default relay request limit in bytes — `1_048_576`, the byte budget a relay applies to an inbound body when `RelayOptions.limit` is omitted, refusing a body that reaches it. |
1119
+ | `RELAY_CONTENT_TYPE` | const | `"application/x-ndjson; charset=utf-8"` | Names the relay's newline-delimited JSON content type — `'application/x-ndjson; charset=utf-8'`, the header a relay response carries beside `cache-control: no-store`. |
1120
+ | `RELAY_PROVIDER_MESSAGE` | const | `"relay provider failed"` | Names the public message for an unexpected upstream relay failure — `'relay provider failed'`, the fixed text every `error` frame carries, so an upstream failure's own message never reaches the browser. |
1121
+ | `UNAUTHORIZED_RELAY_STATUS` | const | `401` | Names the status a relay answers when the `authorize` callback returns anything but `true` or throws — `401`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
1122
+ | `INVALID_RELAY_STATUS` | const | `400` | Names the status a relay answers for a body that is missing, unreadable, or rejected by `providerRequestContract` — `400`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
1123
+ | `OVERSIZED_RELAY_STATUS` | const | `413` | Names the status a relay answers for a request body at or above its byte budget — `413`, carried with no body and answered for an aborted inbound read as well. |
1124
+ | `REFUSED_RELAY_STATUS` | const | `422` | Names the status a relay answers for a page system message or tool definition its policy refuses — `422`, carrying one `REFUSED_RELAY_CONTENT_TYPE` line per refused member and reaching the browser as a `ProviderError` with the `HTTP` code. |
1125
+ | `REFUSED_RELAY_CONTENT_TYPE` | const | `"text/plain; charset=utf-8"` | Names the content type of a relay's `422` refusal body — `'text/plain; charset=utf-8'`, the header a refusal carries beside `cache-control: no-store`. |
1126
+ | `UPSTREAM_RELAY_STATUS` | const | `502` | Names the status a relay answers when the upstream provider call cannot be constructed — `502`, carried with no body after `provider.stream` was entered and threw before returning its iterator. |
1127
+ | `SYSTEM_ONE_PATH` | const | `"/v1/systemone"` | Names the System One decision endpoint shared by compatible servers. |
1128
+ | `RELAY_OPTION_KEYS` | const | `readonly ["provider", "authorize", "limit", "system", "tools"]` | Lists the members `RelayOptions` declares, frozen — the keys `createRelay` admits. |
1129
+ | `RELAY_PROVIDER_KEYS` | const | `readonly ["url", "model", "parser", "timeout", "replay", "fetch", "headers"]` | Lists the members `RelayProviderOptions` declares, frozen — the keys the `RelayProvider` constructor admits. |
1130
+ | `RELAY_STREAM_KEYS` | const | `readonly ["provider", "request", "signal"]` | Lists the members `RelayStreamOptions` declares, frozen — the keys the `RelayStream` constructor admits. |
1131
+ | `PROVIDER_INPUT_KEYS` | const | `readonly ["url", "model", "path", "split", "strict", "timeout", "replay", "fetch", "headers"]` | Lists the members `AgentProviderInput` declares, frozen — the keys the `AgentProvider` constructor admits. |
1132
+ | `JUDGE_INPUT_KEYS` | const | `readonly ["url", "path", "model", "batch", "timeout", "fetch", "headers"]` | Lists the members `AgentJudgeInput` declares, frozen — the keys the `AgentJudge` constructor admits. |
1133
+ | `SYSTEM_ONE_OPTION_KEYS` | const | `readonly ["url", "model", "timeout", "fetch", "headers"]` | Lists the members `SystemOneJudgeOptions` declares, frozen — the keys the `SystemOneJudge` constructor admits. |
1134
+ | `STREAM_OPTION_KEYS` | const | `readonly ["think", "schema"]` | Lists the members `ProviderStreamOptions` declares, frozen — the keys the `generate` and `stream` methods of an `AgentProvider` admits. |
1190
1135
 
1191
1136
  #### Errors
1192
1137
 
@@ -1267,6 +1212,7 @@ The following table lists the helpers the providers module declares:
1267
1212
  | ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1268
1213
  | `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. |
1269
1214
  | `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. |
1215
+ | `requireProviderModel` | function | `(provider: ProviderInterface, owner: 'Agent' \| 'Ledger') => string` | Returns the model a provider serves, read once, or throws a coded error before the agent or ledger that would hold the provider is built. |
1270
1216
  | `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. |
1271
1217
  | `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. |
1272
1218
  | `readFailure` | function | `(response: Response, prefix: string, signal: AbortSignal) => Promise<FailureRead>` | Reads a bounded HTTP failure excerpt and preserves an unreadable body's cause. |
@@ -1301,58 +1247,54 @@ The `conversations` module holds the conversation, its judgment store, the conve
1301
1247
 
1302
1248
  The following table lists the types the conversations module declares:
1303
1249
 
1304
- | Name | Kind | Signature | Summary |
1305
- | ------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1306
- | `MessageManagerInterface` | interface | `{ count, add(), message(), messages(), remove(), clear() }` | Stores immutable `Message` records in insertion order and mints each `id` on `add` — the message-store contract every `ConversationInterface` satisfies structurally, the `AgentContextInterface.messages` conversation included. |
1307
- | `ConversationSummaryHandler` | type | `(messages: readonly Message[], signal?: AbortSignal) => Promise<string>` | Summarizes a conversation, provider-agnostically — the seam the agent runtime supplies so core never imports a provider. Given the folded messages, it resolves their digest, the model-written summary of a compacted `Section` or of the oldest sections a `sections` cap merges. |
1308
- | `Section` | interface | `{ id, summary, messages }` | Holds a slice of folded messages digested into a summary — the unit of compaction a `ConversationInterface` produces when its `compact()` call folds the live tail. |
1309
- | `ConversationEventMap` | type | `{ readonly compact: readonly [section: Section]; readonly rehydrate: readonly [id: string]; readonly collapse: readonly [section: Section]; }` | Maps the push observation surface of a `ConversationInterface` — the compaction moments a fire-and-forget observer subscribes to through `conversation.emitter.on`. |
1310
- | `ConversationOptions` | interface | `{ id?, on?, error?, summarize?, keep?, sections?, cumulative?, snapshot? }` | Configures `createConversation` — the optional `id`, the reserved `on` hooks, the provider-agnostic `summarize` seam, the retained-tail size, an optional cap on the compacted `sections` list, and a `ConversationSnapshot` to hydrate from. |
1311
- | `CompactOptions` | interface | `{ keep?, sections?, signal? }` | Configures one `ConversationInterface.compact` call — the retained-tail size, the `sections` cap, or both, overridden for one fold. |
1312
- | `ConversationReferenceOptions` | interface | `{ label?, messages? }` | Configures `ConversationInterface.reference` — how to render one conversation as a self-labeled, fenced provenance block to pull into another conversation by writing it to the active workspace of the active context: `label` names the source and `messages` lists the cherry-picked excerpts. |
1313
- | `ConversationInterface` | interface | `{ id, judgments, emitter, sections, summarizable, count, add(), message(), messages(), remove(), clear(), view(), compact(), rehydrate(), search(), reference(), snapshot() }` | Groups messages above the flat `MessageManagerInterface` — a live uncompacted tail plus compacted, summarized `Section` records, with on-demand `rehydrate`, substring `search`, a cross-conversation `reference`, and a JSON `snapshot`, driven by a provider-agnostic `ConversationSummaryHandler` seam; `summarizable` reports whether that seam was supplied, and the agent loop gates automatic compaction on it. |
1314
- | `ConversationInput` | interface | `{ id?, summarize?, keep?, sections?, cumulative?, on?, error?, snapshot? }` | Carries the data to author a `ConversationInterface` through a `ConversationManagerInterface` — the optional `id`, a `summarize` override, a `keep` override, a `sections` cap override, the `cumulative` switch, the reserved `on` hooks, and a `ConversationSnapshot` to hydrate from. |
1315
- | `ConversationManagerOptions` | interface | `{ summarize?, keep?, sections?, store? }` | Configures `createConversationManager` — the default `ConversationSummaryHandler`, retained-tail size, and `sections` cap the conversations it creates inherit, plus the optional durable `store` backing `open` / `save`. |
1316
- | `ConversationManagerInterface` | interface | `{ count, active, conversation(), conversations(), add(), switch(), open(), save(), remove(), clear() }` | Registers `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContextInterface` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManagerInterface`); the observability lives on each `ConversationInterface`. |
1317
- | `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`. |
1318
- | `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`. |
1319
- | `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`. |
1320
- | `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID'` | Names the machine-readable condition a `ConversationError` reports. |
1321
- | `JudgmentManagerInterface` | interface | `{ count, add(), judgment(), judgments(), remove(), clear(), resolve() }` | Stores judgments by caller key and resolves requests by reusing matching records. |
1250
+ | Name | Kind | Signature | Summary |
1251
+ | ------------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1252
+ | `MessageManagerInterface` | interface | `{ count, add(), message(), messages(), remove(), clear() }` | Stores immutable `Message` records in insertion order and mints each `id` on `add` — the message-store contract every `ConversationInterface` satisfies structurally, the `AgentContextInterface.messages` conversation included. |
1253
+ | `ConversationEventMap` | type | `{ readonly add: readonly [message: Message]; readonly remove: readonly [id: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `ConversationInterface` — the mutations a fire-and-forget observer subscribes to through `conversation.emitter.on`. |
1254
+ | `ConversationOptions` | interface | `{ id?, on?, error?, snapshot? }` | Configures `createConversation` — the optional `id`, the reserved `on` hooks, the emitter's `error` handler, and a `ConversationSnapshot` to hydrate from. |
1255
+ | `ConversationReferenceOptions` | interface | `{ label?, messages? }` | Configures `ConversationInterface.reference` — how to render one conversation as a self-labeled, fenced provenance block to pull into another conversation by writing it to the active workspace of the active context: `label` names the source and `messages` lists the cherry-picked excerpts. |
1256
+ | `ConversationInterface` | interface | `{ id, judgments, emitter, count, add(), message(), messages(), remove(), clear(), search(), reference(), snapshot(), destroy() }` | Holds one conversation's messages in insertion order, the judgments recorded about them, a substring `search`, a fenced cross-conversation `reference`, and a JSON `snapshot` — the log a memory strategy and a host share, observable through its own emitter. |
1257
+ | `ConversationInput` | interface | `{ id?, on?, error?, snapshot? }` | Carries the data to author a `ConversationInterface` through a `ConversationManagerInterface` — the optional `id`, the reserved `on` hooks, the emitter's `error` handler, and a `ConversationSnapshot` to hydrate from. |
1258
+ | `ConversationManagerOptions` | interface | `{ store? }` | Configures `createConversationManager` — the optional durable `store` backing `open` / `save`. |
1259
+ | `ConversationManagerInterface` | interface | `{ count, active, conversation(), conversations(), add(), switch(), open(), save(), remove(), clear() }` | Registers `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContextInterface` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManagerInterface`); the observability lives on each `ConversationInterface`. |
1260
+ | `ConversationSnapshot` | interface | `{ id, judgments?, messages }` | Holds a JSON-serializable snapshot of the state of a conversation — its `id`, its `messages`, and its judgments — the durable payload the `ConversationStoreInterface` persists. The analogue of `WorkspaceSnapshot`. |
1261
+ | `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 analogue of `WorkspaceStoreInterface`. |
1262
+ | `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 analogue of `WorkspaceSnapshotRow`. |
1263
+ | `ConversationErrorCode` | type | `'JUDGMENT' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID' \| 'LABEL'` | Names the machine-readable condition a `ConversationError` reports. |
1264
+ | `JudgmentManagerInterface` | interface | `{ count, add(), judgment(), judgments(), remove(), clear(), resolve() }` | Stores judgments by caller key and resolves requests by reusing matching records. |
1322
1265
 
1323
1266
  #### Constants
1324
1267
 
1325
1268
  The following table lists the constants the conversations module declares:
1326
1269
 
1327
- | Name | Kind | Signature | Summary |
1328
- | --------------------------- | ----- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1329
- | `CONVERSATION_RECAP_PREFIX` | const | `"[Summary of earlier messages] "` | Names the framing label the `view()` method of a `ConversationInterface` prefixes onto the summary of each compacted section so a small model reads it as a condensed recap of earlier turns — the lean `'[Summary of earlier messages] '` marker, never a literal assistant turn to echo or treat as the live answer. |
1330
- | `DEFAULT_CONVERSATION_KEEP` | const | `0` | Sets the default number of recent live messages the `compact()` method of a `ConversationInterface` retains verbatim — `0`, so a manual `compact()` keeps no recent tail and folds every exchange before the newest user message into one summarized section. A caller retains a recent tail by passing `keep` (on `ConversationOptions`, `ConversationManagerOptions`, or per-fold through `CompactOptions`), folding at most the older `count - keep` messages, cut back to whole exchanges, and leaving at least the most recent `keep` live for the next turn. Overridable everywhere `keep` is accepted. |
1331
- | `CONVERSATION_OPTION_KEYS` | const | `readonly ["id", "on", "error", "summarize", "keep", "sections", "cumulative", "snapshot"]` | Lists the members `ConversationOptions` declares, frozen — the keys the `Conversation` constructor admits. |
1332
- | `CONVERSATION_MANAGER_KEYS` | const | `readonly ["summarize", "keep", "sections", "store"]` | Lists the members `ConversationManagerOptions` declares, frozen — the keys the `ConversationManager` constructor admits. |
1333
- | `CONVERSATION_INPUT_KEYS` | const | `readonly ["id", "summarize", "keep", "sections", "cumulative", "on", "error", "snapshot"]` | Lists the members `ConversationInput` declares, frozen — the keys the `add` method of a `ConversationManager` admits. |
1334
- | `COMPACT_OPTION_KEYS` | const | `readonly ["keep", "sections", "signal"]` | Lists the members `CompactOptions` declares, frozen — the keys the `compact` method of a `Conversation` admits. |
1335
- | `REFERENCE_OPTION_KEYS` | const | `readonly ["label", "messages"]` | Lists the members `ConversationReferenceOptions` declares, frozen — the keys the `reference` method of a `Conversation` admits. |
1270
+ | Name | Kind | Signature | Summary |
1271
+ | --------------------------- | ----- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1272
+ | `CONVERSATION_OPTION_KEYS` | const | `readonly ["id", "on", "error", "snapshot"]` | Lists the members `ConversationOptions` declares, frozen — the keys the `Conversation` constructor admits. |
1273
+ | `CONVERSATION_MANAGER_KEYS` | const | `readonly ["store"]` | Lists the members `ConversationManagerOptions` declares, frozen — the keys the `ConversationManager` constructor admits. |
1274
+ | `CONVERSATION_INPUT_KEYS` | const | `readonly ["id", "on", "error", "snapshot"]` | Lists the members `ConversationInput` declares, frozen — the keys the `add` method of a `ConversationManager` admits. |
1275
+ | `REFERENCE_OPTION_KEYS` | const | `readonly ["label", "messages"]` | Lists the members `ConversationReferenceOptions` declares, frozen — the keys the `reference` method of a `Conversation` admits. |
1276
+ | `REFERENCE_LABEL_PATTERN` | const | `Readonly<RegExp>` | Matches a character a reference label refuses: a double quote, which would close the quoted name in a marker early, or a line break (line feed, vertical tab, form feed, carriage return, next line, line separator, or paragraph separator), which would start a line a marker or an excerpt could claim. Frozen, and neither global nor sticky, so `test` keeps no position. |
1277
+ | `REFERENCE_BREAK_PATTERN` | const | `Readonly<RegExp>` | Matches one line break in an excerpt a reference block renders: a carriage return before a line feed as one break, or any one of line feed, vertical tab, form feed, carriage return, next line, line separator, and paragraph separator. Frozen and not global, so `split` reads it without writing its position. |
1336
1278
 
1337
1279
  #### Errors
1338
1280
 
1339
1281
  The following table lists the errors the conversations module declares and the guards that narrow them:
1340
1282
 
1341
- | Name | Kind | Signature | Summary |
1342
- | --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1343
- | `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'`. |
1344
- | `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`. |
1283
+ | Name | Kind | Signature | Summary |
1284
+ | --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1285
+ | `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a judgment or judge request that JSON cannot carry, a stored or selected message whose role is not a conversation role, a malformed message input, a malformed snapshot, a manager's `add` of an id it already holds, or a reference label that could rewrite its fence — thrown by the `add` and `reference` methods of a `ConversationInterface`, its construction, its judgment store, or its manager, or returned as the `fault` of an agent selection, carrying the machine-readable `code` `'JUDGMENT' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID' \| 'LABEL'`. |
1286
+ | `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`. |
1345
1287
 
1346
1288
  #### Factories
1347
1289
 
1348
1290
  The following table lists the factories the conversations module declares:
1349
1291
 
1350
- | Name | Kind | Signature | Summary |
1351
- | --------------------------------- | -------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1352
- | `createConversation` | function | `(options?: ConversationOptions) => ConversationInterface` | Creates a conversation — a `ConversationInterface` grouping messages above a flat message store it owns directly, with compaction into summarized sections, on-demand `rehydrate`, and substring `search`, driven by a provider-agnostic `ConversationSummaryHandler` seam. |
1353
- | `createConversationManager` | function | `(options?: ConversationManagerOptions) => ConversationManagerInterface` | Creates a conversation registry — a `ConversationManagerInterface` holding `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer: the id-keyed store over the conversation layer plus the `active` / `switch` seam the context renders. `add` auto-activates the first conversation and flows the registry's default `summarize` / `keep` into every conversation it creates. |
1354
- | `createMemoryConversationStore` | function | `() => ConversationStoreInterface` | Creates the in-memory conversation store — a `ConversationStoreInterface` backed by a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default backing for the durable `ConversationManagerInterface.open` / `ConversationManagerInterface.save` seam. The exact twin of `createMemoryWorkspaceStore`. |
1355
- | `createDatabaseConversationStore` | function | `(driver?: DriverInterface) => ConversationStoreInterface` | Creates a `DatabaseConversationStore` over any `DriverInterface` — the durable, driver-pluggable backing for the conversation persistence seam, holding each snapshot as one opaque JSON column and standing as the opt-in twin of `createMemoryConversationStore`. The exact twin of `createDatabaseWorkspaceStore`. |
1292
+ | Name | Kind | Signature | Summary |
1293
+ | --------------------------------- | -------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1294
+ | `createConversation` | function | `(options?: ConversationOptions) => ConversationInterface` | Creates a conversation — a `ConversationInterface` holding owned, frozen messages in insertion order beside the judgments recorded about them, with substring `search`, a fenced `reference`, and a JSON `snapshot`. |
1295
+ | `createConversationManager` | function | `(options?: ConversationManagerOptions) => ConversationManagerInterface` | Creates a conversation registry — a `ConversationManagerInterface` holding `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer: the id-keyed store over the conversation layer plus the `active` / `switch` seam the context renders. `add` auto-activates the first conversation. |
1296
+ | `createMemoryConversationStore` | function | `() => ConversationStoreInterface` | Creates the in-memory conversation store — a `ConversationStoreInterface` backed by a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default backing for the durable `ConversationManagerInterface.open` / `ConversationManagerInterface.save` seam. The exact twin of `createMemoryWorkspaceStore`. |
1297
+ | `createDatabaseConversationStore` | function | `(driver?: DriverInterface) => ConversationStoreInterface` | Creates a `DatabaseConversationStore` over any `DriverInterface` — the durable, driver-pluggable backing for the conversation persistence seam, holding each snapshot as one opaque JSON column and standing as the opt-in twin of `createMemoryConversationStore`. The exact twin of `createDatabaseWorkspaceStore`. |
1356
1298
 
1357
1299
  #### Classes
1358
1300
 
@@ -1360,7 +1302,7 @@ The following table lists the classes the conversations module declares:
1360
1302
 
1361
1303
  | Name | Kind | Signature | Summary |
1362
1304
  | --------------------------- | ----- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1363
- | `Conversation` | class | `new (options?: ConversationOptions) => ConversationInterface` | Represents a conversation — a live uncompacted tail of messages it owns directly above a flat message store, plus compacted, summarized `Section` records and a `summarizable` flag, with on-demand `rehydrate` and substring `search`, driven by a provider-agnostic `ConversationSummaryHandler` seam so `core` never imports a provider. Observable through its own `emitter`. |
1305
+ | `Conversation` | class | `new (options?: ConversationOptions) => ConversationInterface` | Represents a conversation — the messages it owns in insertion order, the judgments recorded about them, a substring `search`, a fenced cross-conversation `reference`, and a JSON `snapshot`, observable through its own `emitter`. |
1364
1306
  | `ConversationManager` | class | `new (options?: ConversationManagerOptions) => ConversationManagerInterface` | Registers `Conversation` instances keyed by `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContext` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManager`); the observability lives on each `Conversation`. |
1365
1307
  | `MemoryConversationStore` | class | `new () => ConversationStoreInterface` | Implements the `ConversationStoreInterface` in memory — a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default store `createMemoryConversationStore` builds and the default backing for `open` / `save`. The exact twin of `MemoryWorkspaceStore`. |
1366
1308
  | `DatabaseConversationStore` | class | `new (table: TableInterface<ConversationSnapshotRow>) => ConversationStoreInterface` | Backs a `ConversationStoreInterface` with one table of the `databases` layer — a conversation's durable state is a row holding the snapshot as one opaque JSON column, narrowed back on `get` by `isConversationSnapshot`, so persistence reduces to keyed point-access (`get` / `set` / `delete`) over a `TableInterface`. The driver-pluggable twin of the plain-`Map` `MemoryConversationStore`, and the exact twin of `DatabaseWorkspaceStore`. |
@@ -1370,41 +1312,35 @@ The following table lists the classes the conversations module declares:
1370
1312
 
1371
1313
  The following table lists the helpers the conversations module declares:
1372
1314
 
1373
- | Name | Kind | Signature | Summary |
1374
- | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1375
- | `buildSummaryMessage` | function | `(section: Section) => Message` | Builds the raw synthetic summary message for one compacted section — role `'assistant'`, the section's stable `id`, and its `summary` verbatim as content. |
1376
- | `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`. |
1377
- | `requireJudgment` | function | `(value: unknown) => Judgment` | Returns a stored judgment record after checking it, or throws a coded error. |
1378
- | `requireRole` | function | `(role: unknown) => ConversationRole` | Returns a stored message role after checking it is a conversation role, or throws a coded error. |
1379
- | `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. |
1380
- | `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking it is a positive safe integer, or throws a coded error. |
1381
- | `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. |
1382
- | `requireKeep` | function | `(keep: number) => number` | Returns a retained-tail size after checking it is a nonnegative safe integer, or throws a coded error. |
1383
- | `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. |
1384
- | `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. |
1385
- | `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. |
1386
- | `requireSummary` | function | `(summary: string) => string` | Returns a summarizer digest after checking it carries non-whitespace text, or throws a coded error. |
1387
- | `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. |
1388
- | `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. |
1315
+ | Name | Kind | Signature | Summary |
1316
+ | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1317
+ | `requireJudgment` | function | `(value: unknown) => Judgment` | Returns a stored judgment record after checking it, or throws a coded error. |
1318
+ | `requireRole` | function | `(role: unknown) => ConversationRole` | Returns a stored message role after checking it is a conversation role, or throws a coded error. |
1319
+ | `requireConversationSnapshot` | function | `(value: unknown, contract: Pick<ContractInterface<unknown>, 'audit' \| 'schema'>) => ConversationSnapshot` | Returns a conversation snapshot after checking its shape, its stored roles, its ids, and its call arguments, or throws a coded error. |
1320
+ | `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. |
1321
+ | `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. |
1322
+ | `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. |
1323
+ | `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. |
1324
+ | `requireStoredMessage` | function | `(value: unknown, code: 'MESSAGE' \| 'SNAPSHOT') => Message` | Returns the owned copy of a stored message after checking it is a message of a conversation role, or throws a coded error. |
1325
+ | `collectRemovals` | function | `(messages: readonly Message[], ids: readonly string[]) => readonly string[]` | Collects the ids a removal takes, in message order: every supplied id a message holds, and every other member of each call group one of them belongs to. |
1326
+ | `requireLabel` | function | `(label: string) => string` | Returns a reference label after checking it holds no double quote and no line break, or throws a coded error. |
1327
+ | `renderReference` | function | `(label: string, messages: readonly Message[]) => string` | Renders a reference block: an opening marker naming the label, the excerpts under a `Relevant messages:` line when there are any, and a closing marker naming the label. |
1389
1328
 
1390
1329
  #### Validators
1391
1330
 
1392
1331
  The following table lists the guards the conversations module declares:
1393
1332
 
1394
- | Name | Kind | Signature | Summary |
1395
- | ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1396
- | `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
1397
- | `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. |
1398
- | `isMessageInput` | const | `Guard<MessageInput>` | Checks whether a value is a message input a conversation can store: a `ConversationRole`, a string `content`, and `calls`, `call`, `images`, and `thinking` absent or of their declared types. |
1399
- | `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. |
1400
- | `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. |
1401
- | `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. |
1402
- | `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. |
1403
- | `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. |
1404
- | `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. |
1405
- | `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`. |
1406
- | `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. |
1407
- | `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
1333
+ | Name | Kind | Signature | Summary |
1334
+ | ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1335
+ | `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
1336
+ | `isMessageInput` | const | `Guard<MessageInput>` | Checks whether a value is a message input a conversation can store: a `ConversationRole`, a string `content`, and `calls`, `call`, `images`, and `thinking` absent or of their declared types. |
1337
+ | `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. |
1338
+ | `conversationSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: 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>>; 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. |
1339
+ | `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. |
1340
+ | `conversationSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: 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. |
1341
+ | `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id`, a valid `messages` array, and valid `judgments` when present; 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 analogue of `isWorkspaceSnapshot`. |
1342
+ | `isConversation` | function | `(value: unknown) => value is ConversationInterface` | Checks whether a value carries the `ConversationInterface` members a run reads: a string `id` and `add` and `messages` methods. |
1343
+ | `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
1408
1344
 
1409
1345
  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:
1410
1346
 
@@ -1434,7 +1370,7 @@ The following table lists the types the contexts module declares:
1434
1370
  | `InstructionManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createInstructionManager` — the reserved `on` hooks plus an optional per-section format override. |
1435
1371
  | `InstructionManagerInterface` | interface | `{ emitter, count, open, close, add(), instruction(), instructions(), render(), remove(), clear() }` | Registers `InstructionInterface` values keyed by `name` — `add` (one or a batch) mints each `id` and overwrites a same-name instruction, last write wins, while `instructions()` lists them sorted by descending `priority` and stable for ties. |
1436
1372
  | `ScopeFilter` | interface | `{ instructions?, skills?, memos?, tools?, files?, workspaces? }` | Lists the per-category allow-lists a `ScopeInterface` carries — an optional `readonly string[]` for `instructions`, for `skills`, for `memos`, for `tools`, for `files`, and for `workspaces`, each keyed by that category's identity (an instruction's, a skill's, a memo's, or a tool's `name`, a workspace file's `path`, a workspace's `id`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. |
1437
- | `Selection` | interface | `{ messages, judgments, usage?, fault? }` | Carries the conversation part of the next prompt and the receipt for it. |
1373
+ | `Selection` | interface | `{ messages, judgments, usage?, fault?, recoveries? }` | Carries the conversation part of the next prompt and the receipt for it. |
1438
1374
  | `SelectionHandler` | type | `(conversation: ConversationInterface, request: Message, signal: AbortSignal) => Promise<Selection>` | Chooses the conversation messages the next prompt carries for one user request. |
1439
1375
  | `ScopeInput` | interface | `{ name, select? }` | Carries the data to author a `ScopeInterface` — a `ScopeFilter` plus the required `name` (a human label; the `id` is minted by the layer that stores it). |
1440
1376
  | `ScopeInterface` | interface | `{ id, name, select?, narrow() }` | Represents a named, immutable filter over a richer context's items — the per-category allow-lists (`ScopeFilter`) plus an `id` / `name`, and a `narrow` that composes a tighter child by set intersection. |
@@ -1568,79 +1504,79 @@ The `agents` module holds the loop, the authority gate, the channel, and the dur
1568
1504
 
1569
1505
  The following table lists the types the agents module declares:
1570
1506
 
1571
- | Name | Kind | Signature | Summary |
1572
- | ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1573
- | `AgentStatus` | type | `'idle' \| 'running' \| 'done' \| 'error'` | Names the lifecycle state of an `AgentInterface` turn — `idle` before a run, `running` while the loop is in flight, then the settled `done` (a normal finish or a cancel) or `error` (a genuine provider / tool failure). |
1574
- | `AgentBuiltin` | type | `'load' \| 'unload' \| 'memo' \| 'remember' \| 'switch'` | Names a tool the agent serves itself: `load` and `unload` show and hide a skill, `memo` reads a memo, `remember` writes one, and `switch` selects a workspace. |
1575
- | `AgentCaller` | interface | `{ workspace, files }` | Carries what an agent run hands each tool call as `ToolContext.caller`: the workspace the run acts on and the paths it reaches there. |
1576
- | `AgentChunk` | type | `{ readonly category: 'token'; readonly content: string; } \| { readonly category: 'think'; readonly content: string; } \| { readonly category: 'tool'; readonly call: ToolCall; readonly result: ToolResult; } \| { readonly category: 'usage'; readonly usage: TokenUsage; readonly estimate: number; } \| { readonly category: 'ask'; readonly call: ToolCall; readonly decision: AuthorityDecision; }` | Represents a streamed step of an agent turn — the union the loop yields as it runs, discriminated by the `category` of step it carries, and the pull surface beside the push `AgentEventMap`. |
1577
- | `AgentEventMap` | type | `{ readonly start: readonly [id: string]; readonly turn: readonly [index: number]; readonly tool: readonly [call: ToolCall, result: ToolResult]; readonly usage: readonly [usage: TokenUsage, estimate: number]; readonly allow: readonly [call: ToolCall, decision: AuthorityDecision]; readonly ask: readonly [call: ToolCall, decision: AuthorityDecision]; readonly deny: readonly [ call: ToolCall, reason: string \| undefined, decision: AuthorityDecision \| undefined ]; readonly finish: readonly [result: AgentResult]; readonly error: readonly [error: unknown]; readonly abort: readonly [reason: unknown]; readonly exhaust: readonly [turns: number]; readonly fault: readonly [error: unknown]; readonly select: readonly [selection: Selection]; readonly request: readonly [ index: number, request: ProviderRequest, conversation: ConversationInterface ]; }` | Maps the push observation surface of an `AgentInterface` — the lifecycle, usage, and tool moments a fire-and-forget observer (logging, metrics, tracing) subscribes to, beside the pull `AgentChunk` stream. |
1578
- | `AgentResult` | interface | `{ content, thinking?, usage?, partial, stop? }` | Holds the settled outcome of an agent turn — the assembled assistant `content`, the `usage` summed across the turn's provider calls, and whether it was committed `partial`. |
1579
- | `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. |
1580
- | `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`. |
1581
- | `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. |
1582
- | `AgentErrorCode` | type | `'APPROVER' \| 'AUTHORITY' \| 'BUILTIN' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'SCHEMA' \| 'WINDOW'` | Names the machine-readable agent approver, authority, built-in, concurrency, limit, registry, schema, and window failures. |
1583
- | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1584
- | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1585
- | `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`. |
1586
- | `StreamInterface` | interface | `{ events, result, abort() }` | Pairs a live event stream with the eventual settled result and a cancel — the generic pull/streaming handle a long-running operation hands back. |
1587
- | `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
1588
- | `AgentFrame` | type | `{ readonly category: 'token'; readonly content: string; } \| { readonly category: 'think'; readonly content: string; } \| { readonly category: 'tool'; readonly success: true; readonly name: string; } \| { readonly category: 'tool'; readonly success: false; } \| { readonly category: 'usage'; readonly usage: TokenUsage; readonly estimate: number; } \| { readonly category: 'ask'; readonly id: string; readonly name: string; readonly zone: string; readonly arguments: string; } \| { readonly category: 'finish'; readonly content: string; readonly partial: boolean; readonly usage?: TokenUsage; readonly layer?: AgentStop['layer']; } \| { readonly category: 'error'; }` | Represents one step of a server-run agent turn as a page receives it — one frame per projected `AgentChunk`, then exactly one terminal `finish` or `error`. |
1589
- | `AgentPrompt` | interface | `{ content, images? }` | Holds the one user turn a run appends to its conversation — passed as `AgentRunOptions.prompt` by a host or sent by a page; the run writes `role: 'user'` itself. |
1590
- | `AgentAnswer` | interface | `{ id, approved }` | Carries a page's answer to one `ask` frame; only `approved: true` approves. |
1591
- | `ApproverInterface` | interface | `{ ask, frame(), answer() }` | Holds a server's waiting asks between the run that asked them and the page that answers them — the authority's `ask` handler, the frame each waiting ask crosses as, and the answer that settles it. |
1592
- | `AgentOptions` | interface | `{ on?, error?, system?, tools?, instructions?, skills?, memos?, workspaces?, scope?, limit?, timeout?, budget?, allowance?, scheduler?, signal?, authority?, conversations?, window?, strict?, select?, builtins?, workspace? }` | Configures `createAgent` — the loop's bounds and pacing, the reserved `on` hooks, the construction-time context wiring (`instructions` / `skills` / `memos` / `workspaces` / `scope`), the `conversations` registry holding every run's default, the context `window` budget that opts into automatic compaction of the run's conversation, the `builtins` each run serves and the `workspace` it renders, and the `strict` switch that settles the run `error` on an automatic-compaction summarizer failure, a selection fault, or a request still over the window, or continues past them when `false`. |
1593
- | `AgentRunOptions` | interface | `{ think?, schema?, limit?, timeout?, budget?, allowance?, signal?, conversation?, prompt?, scope?, workspace? }` | Carries overrides for one call to the `generate` or `stream` method of an `AgentInterface`. Each member overrides the matching `AgentOptions` value, while `signal` composes with the construction signal, `conversation` binds the run to one conversation, `prompt` adds the run's user turn to it, and `scope` narrows the context scope for the run. |
1594
- | `AgentInterface` | interface | `{ emitter, id, status, context, generate(), stream(), abort() }` | Composes a `ProviderInterface`, an `AgentContextInterface`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn. |
1595
- | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1596
- | `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
1597
- | `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
1598
- | `AuthorityRule` | interface | `{ match, zone, verdict, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1599
- | `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
1600
- | `AuthorityOptions` | interface | `{ rules?, fallback, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
1601
- | `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. |
1602
- | `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
1603
- | `BuiltinNote` | interface | `{ loaded, unloaded, remembered, switched }` | Holds the model-facing texts the built-ins return on success. |
1604
- | `AgentJobInput` | interface | `{ provider, messages?, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, scope?, workspace?, builtins?, 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. |
1605
- | `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1606
- | `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store?, skills?, memos?, workspaces? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
1607
- | `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`. |
1608
- | `AgentRunnerOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout? }` | Configures `createAgentRunner` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createRunner`. |
1507
+ | Name | Kind | Signature | Summary |
1508
+ | ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1509
+ | `AgentStatus` | type | `'idle' \| 'running' \| 'done' \| 'error'` | Names the lifecycle state of an `AgentInterface` turn — `idle` before a run, `running` while the loop is in flight, then the settled `done` (a normal finish or a cancel) or `error` (a genuine provider / tool failure). |
1510
+ | `AgentBuiltin` | type | `'load' \| 'unload' \| 'memo' \| 'remember' \| 'switch'` | Names a tool the agent serves itself: `load` and `unload` show and hide a skill, `memo` reads a memo, `remember` writes one, and `switch` selects a workspace. |
1511
+ | `AgentCaller` | interface | `{ workspace, files }` | Carries what an agent run hands each tool call as `ToolContext.caller`: the workspace the run acts on and the paths it reaches there. |
1512
+ | `AgentChunk` | type | `{ readonly category: 'token'; readonly content: string; } \| { readonly category: 'think'; readonly content: string; } \| { readonly category: 'tool'; readonly call: ToolCall; readonly result: ToolResult; } \| { readonly category: 'usage'; readonly usage: TokenUsage; readonly estimate: number; } \| { readonly category: 'ask'; readonly call: ToolCall; readonly decision: AuthorityDecision; }` | Represents a streamed step of an agent turn — the union the loop yields as it runs, discriminated by the `category` of step it carries, and the pull surface beside the push `AgentEventMap`. |
1513
+ | `AgentEventMap` | type | `{ readonly start: readonly [id: string]; readonly turn: readonly [index: number]; readonly tool: readonly [call: ToolCall, result: ToolResult]; readonly usage: readonly [usage: TokenUsage, estimate: number]; readonly allow: readonly [call: ToolCall, decision: AuthorityDecision]; readonly ask: readonly [call: ToolCall, decision: AuthorityDecision]; readonly deny: readonly [ call: ToolCall, reason: string \| undefined, decision: AuthorityDecision \| undefined ]; readonly finish: readonly [result: AgentResult]; readonly error: readonly [error: unknown]; readonly abort: readonly [reason: unknown]; readonly exhaust: readonly [turns: number]; readonly fault: readonly [error: unknown]; readonly select: readonly [selection: Selection]; readonly request: readonly [ index: number, request: ProviderRequest, conversation: ConversationInterface ]; }` | Maps the push observation surface of an `AgentInterface` — the lifecycle, usage, and tool moments a fire-and-forget observer (logging, metrics, tracing) subscribes to, beside the pull `AgentChunk` stream. |
1514
+ | `AgentResult` | interface | `{ content, thinking?, usage?, partial, stop? }` | Holds the settled outcome of an agent turn — the assembled assistant `content`, the `usage` summed across the turn's provider calls, and whether it was committed `partial`. |
1515
+ | `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. |
1516
+ | `AgentTurn` | interface | `{ content, thinking, usage, messages, outcome, partial, 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`. |
1517
+ | `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. |
1518
+ | `AgentErrorCode` | type | `'APPROVER' \| 'AUTHORITY' \| 'BUILTIN' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'SCHEMA'` | Names the machine-readable agent approver, authority, built-in, concurrency, limit, registry, and schema failures. |
1519
+ | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1520
+ | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1521
+ | `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`. |
1522
+ | `StreamInterface` | interface | `{ events, result, abort() }` | Pairs a live event stream with the eventual settled result and a cancel — the generic pull/streaming handle a long-running operation hands back. |
1523
+ | `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
1524
+ | `AgentFrame` | type | `{ readonly category: 'token'; readonly content: string; } \| { readonly category: 'think'; readonly content: string; } \| { readonly category: 'tool'; readonly success: true; readonly name: string; } \| { readonly category: 'tool'; readonly success: false; } \| { readonly category: 'usage'; readonly usage: TokenUsage; readonly estimate: number; } \| { readonly category: 'ask'; readonly id: string; readonly name: string; readonly zone: string; readonly arguments: string; } \| { readonly category: 'finish'; readonly content: string; readonly partial: boolean; readonly usage?: TokenUsage; readonly layer?: AgentStop['layer']; } \| { readonly category: 'error'; }` | Represents one step of a server-run agent turn as a page receives it — one frame per projected `AgentChunk`, then exactly one terminal `finish` or `error`. |
1525
+ | `AgentPrompt` | interface | `{ content, images? }` | Holds the one user turn a run appends to its conversation — passed as `AgentRunOptions.prompt` by a host or sent by a page; the run writes `role: 'user'` itself. |
1526
+ | `AgentAnswer` | interface | `{ id, approved }` | Carries a page's answer to one `ask` frame; only `approved: true` approves. |
1527
+ | `ApproverInterface` | interface | `{ ask, frame(), answer() }` | Holds a server's waiting asks between the run that asked them and the page that answers them — the authority's `ask` handler, the frame each waiting ask crosses as, and the answer that settles it. |
1528
+ | `AgentOptions` | interface | `{ on?, error?, system?, tools?, instructions?, skills?, memos?, workspaces?, scope?, limit?, timeout?, budget?, allowance?, scheduler?, signal?, authority?, conversations?, strict?, select?, builtins?, workspace? }` | Configures `createAgent` — the loop's bounds and pacing, the reserved `on` hooks, the construction-time context wiring (`instructions` / `skills` / `memos` / `workspaces` / `scope`), the `conversations` registry holding every run's default, the `builtins` each run serves and the `workspace` it renders, and the `strict` switch that settles the run `error` on a selection fault or a schema miss, or continues past them when `false`. |
1529
+ | `AgentRunOptions` | interface | `{ think?, schema?, limit?, timeout?, budget?, allowance?, signal?, conversation?, prompt?, scope?, workspace? }` | Carries overrides for one call to the `generate` or `stream` method of an `AgentInterface`. Each member overrides the matching `AgentOptions` value, while `signal` composes with the construction signal, `conversation` binds the run to one conversation, `prompt` adds the run's user turn to it, and `scope` narrows the context scope for the run. |
1530
+ | `AgentInterface` | interface | `{ emitter, id, status, context, generate(), stream(), abort() }` | Composes a `ProviderInterface`, an `AgentContextInterface`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn. |
1531
+ | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1532
+ | `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
1533
+ | `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
1534
+ | `AuthorityRule` | interface | `{ match, zone, verdict, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1535
+ | `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
1536
+ | `AuthorityOptions` | interface | `{ rules?, fallback, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
1537
+ | `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. |
1538
+ | `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
1539
+ | `BuiltinNote` | interface | `{ loaded, unloaded, remembered, switched }` | Holds the model-facing texts the built-ins return on success. |
1540
+ | `AgentJobInput` | interface | `{ provider, messages?, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, scope?, workspace?, builtins?, 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. |
1541
+ | `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1542
+ | `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store?, skills?, memos?, workspaces? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
1543
+ | `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`. |
1544
+ | `AgentRunnerOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout? }` | Configures `createAgentRunner` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createRunner`. |
1609
1545
 
1610
1546
  #### Constants
1611
1547
 
1612
1548
  The following table lists the constants the agents module declares:
1613
1549
 
1614
- | Name | Kind | Signature | Summary |
1615
- | -------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1616
- | `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`. |
1617
- | `JOB_REFUSAL_PREFIX` | const | `"refused "` | Opens a job tree finding that refuses a whole job, which sets it apart from a finding that names an exceeded member. |
1618
- | `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. |
1619
- | `BUILTIN_NOTES` | const | `BuiltinNote` | Holds the texts the built-ins return on success — `loaded`, `unloaded`, `remembered`, and `switched` — frozen. |
1620
- | `BUILTIN_LIMITS` | const | `Readonly<{ name: number; description: number; content: number; candidates: number; }>` | Caps each built-in argument in code points, as the built-in argument shapes count them — a `name` (a skill name, a memo name, or a workspace id), a memo `description`, and a memo `content` — and the `candidates` one refusal lists, frozen. |
1621
- | `BUILTIN_TOOLS` | const | `Readonly<Record<AgentBuiltin, Readonly<{ description: string; annotations?: ToolAnnotations; }>>>` | Declares each built-in tool's model-facing description and annotations, keyed by its `AgentBuiltin` name, frozen. |
1622
- | `ARGUMENT_CONTROL_PATTERN` | const | `Readonly<RegExp>` | Matches one control, format, line-separator, or paragraph-separator code point — the class `renderArguments` encodes and a memo's one-line name and description may not hold, frozen. |
1623
- | `ARGUMENT_BLANK_PATTERN` | const | `Readonly<RegExp>` | Matches a text that is blank: empty after white space and default-ignorable code points, such as U+3164, are removed, frozen. |
1624
- | `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 turn's tool ceiling, the context scope's tool allow-list intersected with the run scope's, or whose name no definition advertises this turn. |
1625
- | `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
1626
- | `IMAGE_TOKEN_ESTIMATE` | const | `512` | Names the coarse, deliberately approximate per-image token cost `estimateMessages` charges for each attached image — `512`, because a base64 payload's length is no reliable token proxy. |
1627
- | `AGENT_OPTION_KEYS` | const | `readonly ["on", "error", "system", "tools", "instructions", "skills", "memos", "workspaces", "scope", "limit", "timeout", "budget", "allowance", "scheduler", "signal", "authority", "conversations", "window", "strict", "select", "builtins", "workspace"]` | Lists the members `AgentOptions` declares, frozen — the keys the `Agent` constructor admits. |
1628
- | `AGENT_RUN_KEYS` | const | `readonly ["think", "schema", "limit", "timeout", "budget", "allowance", "signal", "conversation", "prompt", "scope", "workspace"]` | Lists the members `AgentRunOptions` declares, frozen — the keys the `stream` and `generate` methods admit. |
1629
- | `AUTHORITY_OPTION_KEYS` | const | `readonly ["rules", "fallback", "ask"]` | Lists the members `AuthorityOptions` declares, frozen — the keys the `Authority` constructor admits. |
1630
- | `REGISTRY_OPTION_KEYS` | const | `readonly ["providers", "tools", "authorities", "schedulers", "store", "skills", "memos", "workspaces"]` | Lists the members `AgentRegistryOptions` declares, frozen — the keys the `AgentRegistry` constructor admits. |
1631
- | `QUEUE_OPTION_KEYS` | const | `readonly ["registry", "partial", "concurrency", "retries", "timeout", "store"]` | Lists the members `AgentQueueOptions` declares, frozen — the keys `createAgentQueue` admits. |
1632
- | `RUNNER_OPTION_KEYS` | const | `readonly ["registry", "partial", "concurrency", "retries", "timeout"]` | Lists the members `AgentRunnerOptions` declares, frozen — the keys `createAgentRunner` admits. |
1550
+ | Name | Kind | Signature | Summary |
1551
+ | -------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1552
+ | `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`. |
1553
+ | `JOB_REFUSAL_PREFIX` | const | `"refused "` | Opens a job tree finding that refuses a whole job, which sets it apart from a finding that names an exceeded member. |
1554
+ | `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. |
1555
+ | `BUILTIN_NOTES` | const | `BuiltinNote` | Holds the texts the built-ins return on success — `loaded`, `unloaded`, `remembered`, and `switched` — frozen. |
1556
+ | `BUILTIN_LIMITS` | const | `Readonly<{ name: number; description: number; content: number; candidates: number; }>` | Caps each built-in argument in code points, as the built-in argument shapes count them — a `name` (a skill name, a memo name, or a workspace id), a memo `description`, and a memo `content` — and the `candidates` one refusal lists, frozen. |
1557
+ | `BUILTIN_TOOLS` | const | `Readonly<Record<AgentBuiltin, Readonly<{ description: string; annotations?: ToolAnnotations; }>>>` | Declares each built-in tool's model-facing description and annotations, keyed by its `AgentBuiltin` name, frozen. |
1558
+ | `ARGUMENT_CONTROL_PATTERN` | const | `Readonly<RegExp>` | Matches one control, format, line-separator, or paragraph-separator code point — the class `renderArguments` encodes and a memo's one-line name and description may not hold, frozen. |
1559
+ | `ARGUMENT_BLANK_PATTERN` | const | `Readonly<RegExp>` | Matches a text that is blank: empty after white space and default-ignorable code points, such as U+3164, are removed, frozen. |
1560
+ | `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 turn's tool ceiling, the context scope's tool allow-list intersected with the run scope's, or whose name no definition advertises this turn. |
1561
+ | `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
1562
+ | `IMAGE_TOKEN_ESTIMATE` | const | `512` | Names the coarse, deliberately approximate per-image token cost `estimateMessages` charges for each attached image — `512`, because a base64 payload's length is no reliable token proxy. |
1563
+ | `AGENT_OPTION_KEYS` | const | `readonly ["on", "error", "system", "tools", "instructions", "skills", "memos", "workspaces", "scope", "limit", "timeout", "budget", "allowance", "scheduler", "signal", "authority", "conversations", "strict", "select", "builtins", "workspace"]` | Lists the members `AgentOptions` declares, frozen — the keys the `Agent` constructor admits. |
1564
+ | `AGENT_RUN_KEYS` | const | `readonly ["think", "schema", "limit", "timeout", "budget", "allowance", "signal", "conversation", "prompt", "scope", "workspace"]` | Lists the members `AgentRunOptions` declares, frozen — the keys the `stream` and `generate` methods admit. |
1565
+ | `AUTHORITY_OPTION_KEYS` | const | `readonly ["rules", "fallback", "ask"]` | Lists the members `AuthorityOptions` declares, frozen — the keys the `Authority` constructor admits. |
1566
+ | `REGISTRY_OPTION_KEYS` | const | `readonly ["providers", "tools", "authorities", "schedulers", "store", "skills", "memos", "workspaces"]` | Lists the members `AgentRegistryOptions` declares, frozen — the keys the `AgentRegistry` constructor admits. |
1567
+ | `QUEUE_OPTION_KEYS` | const | `readonly ["registry", "partial", "concurrency", "retries", "timeout", "store"]` | Lists the members `AgentQueueOptions` declares, frozen — the keys `createAgentQueue` admits. |
1568
+ | `RUNNER_OPTION_KEYS` | const | `readonly ["registry", "partial", "concurrency", "retries", "timeout"]` | Lists the members `AgentRunnerOptions` declares, frozen — the keys `createAgentRunner` admits. |
1633
1569
 
1634
1570
  #### Errors
1635
1571
 
1636
1572
  The following table lists the errors the agents module declares and the guards that narrow them:
1637
1573
 
1638
- | Name | Kind | Signature | Summary |
1639
- | ----------------- | -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1640
- | `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'`. |
1641
- | `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. |
1642
- | `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. |
1643
- | `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`. |
1574
+ | Name | Kind | Signature | Summary |
1575
+ | ----------------- | -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1576
+ | `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'`. |
1577
+ | `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. |
1578
+ | `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, or a strict run's answer that fails its schema. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'SCHEMA'` 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. |
1579
+ | `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`. |
1644
1580
 
1645
1581
  #### Shapes and contracts
1646
1582
 
@@ -1698,49 +1634,49 @@ The following table lists the classes the agents module declares:
1698
1634
 
1699
1635
  The following table lists the helpers the agents module declares:
1700
1636
 
1701
- | Name | Kind | Signature | Summary |
1702
- | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1703
- | `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. |
1704
- | `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. |
1705
- | `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. |
1706
- | `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
1707
- | `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. |
1708
- | `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. |
1709
- | `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). |
1710
- | `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. |
1711
- | `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. |
1712
- | `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. |
1713
- | `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. |
1714
- | `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. |
1715
- | `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. |
1716
- | `scanJobTree` | function | `(root: AgentJobInput) => readonly string[]` | Scans every job under a root for a member that exceeds its own parent's; an empty result clears the tree. |
1717
- | `collectJobRefusals` | function | `(job: Pick<AgentJobInput, 'tools' \| 'builtins' \| 'authority'>) => readonly string[]` | Collects the refusals a job the contract admitted would meet at its build: tools or built-ins with no authority, a `builtins` list `requireBuiltins` refuses, and a built-in its own `tools` name. |
1718
- | `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. |
1719
- | `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. |
1720
- | `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. |
1721
- | `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`. |
1722
- | `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. |
1723
- | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a positive safe integer, or throws a coded error. |
1724
- | `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. |
1725
- | `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. |
1726
- | `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. |
1727
- | `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. |
1728
- | `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. |
1729
- | `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. |
1730
- | `requireScope` | function | `(value: unknown) => ScopeInterface \| undefined` | Returns a scope a run can bind, or throws a `ContractError` coded `'placement'`; `undefined` passes through. |
1731
- | `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. |
1732
- | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1733
- | `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. |
1734
- | `collectBuiltinDefinitions` | function | `(options: Pick<AgentOptions, 'builtins'>) => readonly ToolDefinition[]` | Collects the definitions of the tools an agent serves itself, as a run advertises them. |
1735
- | `requireBuiltins` | function | `(value: unknown, tools: Pick<ToolManagerInterface, 'tool'>) => readonly AgentBuiltin[]` | Returns an agent's `builtins` option as an owned, frozen list, or throws a coded error before the agent is built. |
1736
- | `requireWorkspace` | function | `(value: unknown) => string \| undefined` | Returns a `workspace` option unchanged, or throws a `ContractError` coded `'placement'`; `undefined` passes through. |
1737
- | `filterAdvertisedTools` | function | `(definitions: readonly ToolDefinition[], names: readonly string[] \| undefined, skills: readonly Skill[], shown: readonly string[]) => readonly ToolDefinition[]` | Returns the definitions a turn advertises from the allow-list, the registered skills, and the shown skills. |
1738
- | `filterBuiltinCandidates` | function | `(definitions: readonly ToolDefinition[], ceiling: ScopeFilter) => readonly ToolDefinition[]` | Returns the definitions a run offers before the allow-list, without `remember` unless the ceiling's `memos` list names a memo, without `switch` unless its `workspaces` list names a workspace, and without `load` and `unload` while its `skills` list is empty. |
1739
- | `describeCandidates` | function | `(subject: string, names: readonly string[]) => string` | Returns the refusal that names a subject and at most `BUILTIN_LIMITS.candidates` of the names a caller can use. |
1740
- | `matchesPlainLine` | function | `(text: string) => boolean` | Checks whether a text is one nonblank line: it holds a code point other than white space and default-ignorable code points (`ARGUMENT_BLANK_PATTERN`), and no control, format, line-separator, or paragraph-separator code point (`ARGUMENT_CONTROL_PATTERN`). |
1741
- | `matchesHeadLists` | function | `(left: ScopeFilter, right: ScopeFilter) => boolean` | Checks whether two ceilings carry the same lists of what a head renders: `instructions`, `skills`, `memos`, `files`, and `workspaces`. |
1742
- | `resolveDisclosure` | function | `(context: AgentContextInterface, conversation: Pick<ConversationInterface, 'sections' \| 'messages'>, workspace: string \| undefined, ceiling: ScopeFilter, builtins: readonly AgentBuiltin[]) => AgentDisclosure` | Resolves what a turn shows: the conversation's record, and the given workspace, within the ceiling and the registries. |
1743
- | `collectDisclosure` | function | `(conversation: Pick<ConversationInterface, 'sections' \| 'messages'>, builtins: readonly AgentBuiltin[]) => AgentDisclosure` | Collects the loaded skills and the selected workspace a conversation's stored built-in calls record, counting only the built-ins a run enables. |
1637
+ | Name | Kind | Signature | Summary |
1638
+ | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1639
+ | `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. |
1640
+ | `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. |
1641
+ | `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. |
1642
+ | `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
1643
+ | `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. |
1644
+ | `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. |
1645
+ | `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). |
1646
+ | `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 and the unit a ledger prices its requests in, a provider-independent approximation for conforming messages rather than an exact tokenizer count. |
1647
+ | `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`. A `consumer` a context budget over provider requests can measure each request through, a provider-independent heuristic rather than an exact tokenizer count. |
1648
+ | `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. |
1649
+ | `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. |
1650
+ | `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. |
1651
+ | `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. |
1652
+ | `scanJobTree` | function | `(root: AgentJobInput) => readonly string[]` | Scans every job under a root for a member that exceeds its own parent's; an empty result clears the tree. |
1653
+ | `collectJobRefusals` | function | `(job: Pick<AgentJobInput, 'tools' \| 'builtins' \| 'authority'>) => readonly string[]` | Collects the refusals a job the contract admitted would meet at its build: tools or built-ins with no authority, a `builtins` list `requireBuiltins` refuses, and a built-in its own `tools` name. |
1654
+ | `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. |
1655
+ | `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. |
1656
+ | `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. |
1657
+ | `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`. |
1658
+ | `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. |
1659
+ | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a positive safe integer, or throws a coded error. |
1660
+ | `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. |
1661
+ | `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. |
1662
+ | `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. |
1663
+ | `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. |
1664
+ | `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. |
1665
+ | `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. |
1666
+ | `requireScope` | function | `(value: unknown) => ScopeInterface \| undefined` | Returns a scope a run can bind, or throws a `ContractError` coded `'placement'`; `undefined` passes through. |
1667
+ | `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. |
1668
+ | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1669
+ | `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. |
1670
+ | `collectBuiltinDefinitions` | function | `(options: Pick<AgentOptions, 'builtins'>) => readonly ToolDefinition[]` | Collects the definitions of the tools an agent serves itself, as a run advertises them. |
1671
+ | `requireBuiltins` | function | `(value: unknown, tools: Pick<ToolManagerInterface, 'tool'>) => readonly AgentBuiltin[]` | Returns an agent's `builtins` option as an owned, frozen list, or throws a coded error before the agent is built. |
1672
+ | `requireWorkspace` | function | `(value: unknown) => string \| undefined` | Returns a `workspace` option unchanged, or throws a `ContractError` coded `'placement'`; `undefined` passes through. |
1673
+ | `filterAdvertisedTools` | function | `(definitions: readonly ToolDefinition[], names: readonly string[] \| undefined, skills: readonly Skill[], shown: readonly string[]) => readonly ToolDefinition[]` | Returns the definitions a turn advertises from the allow-list, the registered skills, and the shown skills. |
1674
+ | `filterBuiltinCandidates` | function | `(definitions: readonly ToolDefinition[], ceiling: ScopeFilter) => readonly ToolDefinition[]` | Returns the definitions a run offers before the allow-list, without `remember` unless the ceiling's `memos` list names a memo, without `switch` unless its `workspaces` list names a workspace, and without `load` and `unload` while its `skills` list is empty. |
1675
+ | `describeCandidates` | function | `(subject: string, names: readonly string[]) => string` | Returns the refusal that names a subject and at most `BUILTIN_LIMITS.candidates` of the names a caller can use. |
1676
+ | `matchesPlainLine` | function | `(text: string) => boolean` | Checks whether a text is one nonblank line: it holds a code point other than white space and default-ignorable code points (`ARGUMENT_BLANK_PATTERN`), and no control, format, line-separator, or paragraph-separator code point (`ARGUMENT_CONTROL_PATTERN`). |
1677
+ | `matchesHeadLists` | function | `(left: ScopeFilter, right: ScopeFilter) => boolean` | Checks whether two ceilings carry the same lists of what a head renders: `instructions`, `skills`, `memos`, `files`, and `workspaces`. |
1678
+ | `resolveDisclosure` | function | `(context: AgentContextInterface, conversation: Pick<ConversationInterface, 'messages'>, workspace: string \| undefined, ceiling: ScopeFilter, builtins: readonly AgentBuiltin[]) => AgentDisclosure` | Resolves what a turn shows: the conversation's record, and the given workspace, within the ceiling and the registries. |
1679
+ | `collectDisclosure` | function | `(conversation: Pick<ConversationInterface, 'messages'>, builtins: readonly AgentBuiltin[]) => AgentDisclosure` | Collects the loaded skills and the selected workspace a conversation's stored built-in calls record, counting only the built-ins a run enables. |
1744
1680
 
1745
1681
  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.
1746
1682
 
@@ -1797,97 +1733,94 @@ The `ledgers` module serves a conversation through event-sourced records: the `L
1797
1733
 
1798
1734
  The following table lists the types the ledger declares, each with its shape:
1799
1735
 
1800
- | Name | Kind | Signature | Summary |
1801
- | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1802
- | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1803
- | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1804
- | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1805
- | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1806
- | `LedgerShare` | interface | `{ prompt, tail, skills }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1807
- | `LedgerNote` | interface | `{ cue, results, repeat, closure, overflow }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1808
- | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1809
- | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1810
- | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1811
- | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1812
- | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1813
- | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1814
- | `LedgerWriteResult` | interface | `{ targets }` | Carries what a write handler read from one write result: the ids and owners it names, and the ids whose state the call changed or removed. |
1815
- | `LedgerWriteHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerWriteResult \| undefined` | Reads one successful write result into the ids and owners it names and the ids whose state it changed. |
1816
- | `LedgerWrite` | interface | `{ tool, read }` | Carries one application write: the `consequential` tool the model calls and the handler that reads its results. |
1817
- | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result, targets? }` | Carries one successful lookup result as the ledger read it. |
1818
- | `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. |
1819
- | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1820
- | `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. |
1821
- | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1822
- | `LedgerGaugeSnapshot` | interface | `{ digest }` | Carries a stored gauge: its price and the digest of the tool definitions that price measured. |
1823
- | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'strict' \| 'authority' \| 'builtins' \| 'workspace'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1824
- | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, writes?, 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, writes, gauge, shares, snapshot, recall limit, correction filter, and agent options. |
1825
- | `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge?, window? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
1826
- | `LedgerExchangeSnapshot` | interface | `{ request, copy?, reply, lines }` | Carries the sent request text, stored pair ids, and sentence placements of one exchange. |
1827
- | `LedgerWindowSnapshot` | interface | `{ digest, exchanges, amendments }` | Carries a nonempty exchange window, its message, copy, and receipt checksum, and its accepted edges. |
1828
- | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1829
- | `LedgerAgentInterface` | type | `Pick<AgentInterface, 'emitter' \| 'id' \| 'status' \| 'context' \| 'abort'>` | Holds the members of a ledger's agent a host reads: its emitter, id, status, context, and abort. |
1830
- | `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. |
1831
- | `LedgerCommit` | interface | `{ price, turn, skill? }` | Carries one price a request committed: the tokens, the count of calls observed when it was committed, and the skill a `load` names. |
1832
- | `LedgerListing` | interface | `{ result, lines, groups, turn }` | Carries a recall result, its accepted whole groups, lookup line translations, and provider-turn position. |
1833
- | `LedgerRecovery` | interface | `{ digest, omitted }` | Carries the answer note and the partial messages omitted from its prompt. |
1834
- | `LedgerRequestInterface` | interface | `{ scope, apply(), sent, fault(), faulted(), message, plan, selection, boundary, usage, calls, attempts, signal, aborted, abort(), enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), release(), deny(), denied(), recall(), close(), list(), listings, lines(), commit(), committed, loads }` | 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. |
1835
- | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1836
- | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1837
- | `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. |
1838
- | `LedgerReceipt` | interface | `{ key, title, source, sentence }` | Identifies an original sentence at one record placement. |
1839
- | `LedgerOccurrence` | interface | `{}` | Carries a rendered sentence with its record placement. |
1840
- | `LedgerExchange` | interface | `{ request, reply, lines }` | Carries a completed request copy, its stored reply, and the sentences the copy rendered. |
1841
- | `LedgerDraft` | interface | `{ copy, lines, evidence, window }` | Carries a planned copy and its validity evidence to request settlement. |
1842
- | `LedgerEvidence` | interface | `{ messages, amendments }` | Captures held message identities and the accepted edges used to validate their copies. |
1843
- | `LedgerRenderResult` | interface | `{ text, lines }` | Carries rendered record text and its sentences in emission order. |
1844
- | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1845
- | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1846
- | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1847
- | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1848
- | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1849
- | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1850
- | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1851
- | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1852
- | `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. |
1853
- | `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. |
1854
- | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1855
- | `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. |
1856
- | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1857
- | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1858
- | `GaugeCall` | interface | `{ estimate, spared?, added?, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1859
- | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1860
- | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1861
- | `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. |
1862
- | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION' \| 'WRITE' \| 'OVERFLOW'` | Names the machine-readable conditions a `LedgerError` error reports. |
1736
+ | Name | Kind | Signature | Summary |
1737
+ | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1738
+ | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1739
+ | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1740
+ | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1741
+ | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1742
+ | `LedgerShare` | interface | `{ prompt, tail, skills }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1743
+ | `LedgerNote` | interface | `{ cue, results, repeat, closure, overflow }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1744
+ | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1745
+ | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1746
+ | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1747
+ | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1748
+ | `LedgerWriteResult` | interface | `{ targets }` | Carries what a write handler read from one write result: the ids and owners it names, and the ids whose state the call changed or removed. |
1749
+ | `LedgerWriteHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerWriteResult \| undefined` | Reads one successful write result into the ids and owners it names and the ids whose state it changed. |
1750
+ | `LedgerWrite` | interface | `{ tool, read }` | Carries one application write: the `consequential` tool the model calls and the handler that reads its results. |
1751
+ | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result, targets? }` | Carries one successful lookup result as the ledger read it. |
1752
+ | `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. |
1753
+ | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1754
+ | `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. |
1755
+ | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1756
+ | `LedgerGaugeSnapshot` | interface | `{ digest, model }` | Carries a stored gauge: its price, the digest of the tool definitions that price measured, and the provider model it was measured on. |
1757
+ | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'authority' \| 'builtins' \| 'workspace'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1758
+ | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict, think?, gauge?, lookups?, writes?, share?, agent?, snapshot? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity and generation cap, and the optional first-pass thinking, lookups, writes, gauge, shares, snapshot, and agent options. |
1759
+ | `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge?, window? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
1760
+ | `LedgerExchangeSnapshot` | interface | `{ request, copy?, reply, lines }` | Carries the sent request text, stored pair ids, and sentence placements of one exchange. |
1761
+ | `LedgerWindowSnapshot` | interface | `{ digest, exchanges, amendments }` | Carries a nonempty exchange window, its message, copy, and receipt checksum, and its accepted edges. |
1762
+ | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1763
+ | `LedgerAgentInterface` | type | `Pick<AgentInterface, 'emitter' \| 'id' \| 'status' \| 'context' \| 'abort'>` | Holds the members of a ledger's agent a host reads: its emitter, id, status, context, and abort. |
1764
+ | `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), stream(), calibrate(), snapshot(), destroy() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1765
+ | `LedgerCommit` | interface | `{ price, turn, skill? }` | Carries one price a request committed: the tokens, the count of calls observed when it was committed, and the skill a `load` names. |
1766
+ | `LedgerListing` | interface | `{ result, lines, groups, turn }` | Carries a recall result, its accepted whole groups, lookup line translations, and provider-turn position. |
1767
+ | `LedgerRecovery` | interface | `{ digest, omitted }` | Carries the answer note and the partial messages omitted from its prompt. |
1768
+ | `LedgerRequestInterface` | interface | `{ scope, apply(), sent, fault(), faulted(), message, plan, selection, boundary, usage, calls, attempts, signal, aborted, abort(), enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), release(), deny(), denied(), recall(), close(), list(), listings, lines(), commit(), committed, loads }` | 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. |
1769
+ | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1770
+ | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1771
+ | `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. |
1772
+ | `LedgerReceipt` | interface | `{ key, title, source, sentence }` | Identifies an original sentence at one record placement. |
1773
+ | `LedgerOccurrence` | interface | `{}` | Carries a rendered sentence with its record placement. |
1774
+ | `LedgerExchange` | interface | `{ request, reply, lines }` | Carries a completed request copy, its stored reply, and the sentences the copy rendered. |
1775
+ | `LedgerDraft` | interface | `{ copy, lines, evidence, window }` | Carries a planned copy and its validity evidence to request settlement. |
1776
+ | `LedgerEvidence` | interface | `{ messages, amendments }` | Captures held message identities and the accepted edges used to validate their copies. |
1777
+ | `LedgerRenderResult` | interface | `{ text, lines }` | Carries rendered record text and its sentences in emission order. |
1778
+ | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1779
+ | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1780
+ | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1781
+ | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1782
+ | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1783
+ | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1784
+ | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1785
+ | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1786
+ | `ClassifierOptions` | interface | `{ conversation, judge, questions, topics, thresholds, assign, entities, 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 scheduler. |
1787
+ | `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. |
1788
+ | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1789
+ | `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. |
1790
+ | `ClassifierResult` | interface | `{ judgments, usage?, attempts, holds, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1791
+ | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1792
+ | `GaugeCall` | interface | `{ estimate, spared?, added?, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1793
+ | `GaugeOptions` | interface | `{ capacity, predict, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1794
+ | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1795
+ | `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. |
1796
+ | `LedgerErrorCode` | type | `'REQUEST' \| 'HOLD' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION' \| 'WRITE' \| 'OVERFLOW' \| 'DESTROYED'` | Names the machine-readable conditions a `LedgerError` error reports. |
1863
1797
 
1864
1798
  #### Constants
1865
1799
 
1866
1800
  The following table lists the constants that hold the ledger's categories, record keys, measured wording, shares, and limits:
1867
1801
 
1868
- | Name | Kind | Signature | Summary |
1869
- | --------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1870
- | `LEDGER_CATEGORIES` | const | `readonly ["fact", "rule", "correction", "request", "opinion", "chatter", "distractor"]` | Lists the categories the ledger files a message under, in the order the category question names them — the one list the `LedgerCategory` union derives from. |
1871
- | `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
1872
- | `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the records render. |
1873
- | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1874
- | `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
1875
- | `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
1876
- | `LEDGER_RECALL_LABELS` | const | `Readonly<{ request: "Earlier request:"; reply: "Earlier reply:"; }>` | Labels recalled conversation text by its origin. |
1877
- | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1878
- | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1879
- | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt, tail, and skills shares. |
1880
- | `DEFAULT_LEDGER_LIMIT` | const | `8` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
1881
- | `DEFAULT_RECALL_LIMIT` | const | `2` | Caps the `recall` calls of one request at 2 calls. |
1882
- | `LEDGER_SLICE` | const | `5` | Sets the 5 milliseconds a paced classifier files between host turns. |
1883
- | `LEDGER_SCALE_DRIFT` | const | `0.06` | Holds back the share of the prompt budget the scale can rise by between calibration and a request's first call. |
1884
- | `LEDGER_SAMPLE_BYTES` | const | `3` | Sets the 3 UTF-8 bytes one UTF-16 code unit encodes to at most, the divisor that sizes the workspace text a calibration's third call carries. |
1885
- | `LEDGER_WORD` | const | `RegExp` | Matches a run of letters and digits, which the ledger reads as one word. |
1886
- | `DETERMINISTIC_JUDGE_ERROR` | const | `RegExp` | Matches the logprob decoding failure `invalid or duplicate top logprob token`, which the ledger holds for the ledger's life. |
1887
- | `LEDGER_OPTION_KEYS` | const | `readonly ["judge", "system", "topics", "questions", "thresholds", "capacity", "predict", "think", "gauge", "lookups", "writes", "share", "recall", "correction", "agent", "snapshot"]` | Lists the members `LedgerOptions` declares, frozen — the keys the `Ledger` constructor admits. |
1888
- | `LEDGER_AGENT_KEYS` | const | `readonly ["limit", "timeout", "on", "scheduler", "instructions", "skills", "memos", "workspaces", "strict", "authority", "builtins", "workspace"]` | Lists the members the `LedgerAgentOptions` pick declares, frozen — the keys a ledger's `agent` option admits. |
1889
- | `CLASSIFIER_OPTION_KEYS` | const | `readonly ["strict", "conversation", "judge", "questions", "topics", "thresholds", "assign", "entities", "correction", "scheduler"]` | Lists the members `ClassifierOptions` declares, frozen — the keys the `Classifier` constructor admits. |
1890
- | `GAUGE_OPTION_KEYS` | const | `readonly ["scale", "overhead", "capacity", "predict", "replay"]` | Lists the members `GaugeOptions` declares, frozen — the keys the `Gauge` constructor admits. |
1802
+ | Name | Kind | Signature | Summary |
1803
+ | ------------------------ | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1804
+ | `LEDGER_CATEGORIES` | const | `readonly ["fact", "rule", "correction", "request", "opinion", "chatter", "distractor"]` | Lists the categories the ledger files a message under, in the order the category question names them — the one list the `LedgerCategory` union derives from. |
1805
+ | `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
1806
+ | `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the records render. |
1807
+ | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1808
+ | `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
1809
+ | `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
1810
+ | `LEDGER_RECALL_LABELS` | const | `Readonly<{ request: "Earlier request:"; reply: "Earlier reply:"; }>` | Labels recalled conversation text by its origin. |
1811
+ | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1812
+ | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1813
+ | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt, tail, and skills shares. |
1814
+ | `DEFAULT_LEDGER_LIMIT` | const | `8` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
1815
+ | `LEDGER_RECALL_LIMIT` | const | `2` | Caps the `recall` calls of one request at 2 calls. |
1816
+ | `LEDGER_SLICE` | const | `5` | Sets the 5 milliseconds a paced classifier files between host turns. |
1817
+ | `LEDGER_SCALE_DRIFT` | const | `0.06` | Holds back the share of the prompt budget the scale can rise by between calibration and a request's first call. |
1818
+ | `LEDGER_SAMPLE_BYTES` | const | `3` | Sets the 3 UTF-8 bytes one UTF-16 code unit encodes to at most, the divisor that sizes the workspace text a calibration's third call carries. |
1819
+ | `LEDGER_WORD` | const | `RegExp` | Matches a run of letters and digits, which the ledger reads as one word. |
1820
+ | `LEDGER_OPTION_KEYS` | const | `readonly ["judge", "system", "topics", "questions", "thresholds", "capacity", "predict", "think", "gauge", "lookups", "writes", "share", "agent", "snapshot"]` | Lists the members `LedgerOptions` declares, frozen — the keys the `Ledger` constructor admits. |
1821
+ | `LEDGER_AGENT_KEYS` | const | `readonly ["limit", "timeout", "on", "scheduler", "instructions", "skills", "memos", "workspaces", "authority", "builtins", "workspace"]` | Lists the members the `LedgerAgentOptions` pick declares, frozen — the keys a ledger's `agent` option admits. |
1822
+ | `CLASSIFIER_OPTION_KEYS` | const | `readonly ["conversation", "judge", "questions", "topics", "thresholds", "assign", "entities", "scheduler"]` | Lists the members `ClassifierOptions` declares, frozen — the keys the `Classifier` constructor admits. |
1823
+ | `GAUGE_OPTION_KEYS` | const | `readonly ["scale", "overhead", "capacity", "predict", "replay"]` | Lists the members `GaugeOptions` declares, frozen — the keys the `Gauge` constructor admits. |
1891
1824
 
1892
1825
  #### Errors
1893
1826
 
@@ -1913,7 +1846,7 @@ The following table lists the classes that serve, file, and price a conversation
1913
1846
  | Name | Kind | Signature | Summary |
1914
1847
  | --------------- | ----- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1915
1848
  | `Ledger` | class | `new (provider: ProviderInterface, options: LedgerOptions) => LedgerInterface` | Serves one conversation through classified records, a bounded copy of each request turn that carries them, and a final answer pass. |
1916
- | `LedgerRequest` | class | `new (content: string, limit?: number) => LedgerRequestInterface` | Holds what one ledger request keeps while it is served: its message, its filing attempts and plan, the gauge calls of its passes, and its repeat and recall stops. |
1849
+ | `LedgerRequest` | class | `new (content: string) => LedgerRequestInterface` | Holds what one ledger request keeps while it is served: its message, its filing attempts and plan, the gauge calls of its passes, and its repeat and recall stops. |
1917
1850
  | `Classifier` | class | `new (options: ClassifierOptions) => ClassifierInterface` | Files messages through the conversation's judgment manager and reads their categories and corrections. |
1918
1851
  | `Gauge` | class | `new (options: GaugeOptions) => GaugeInterface` | Prices prompts in tokens from a measured scale and overhead cost, and measures the room a request has left. |
1919
1852
 
@@ -1921,17 +1854,17 @@ The following table lists the classes that serve, file, and price a conversation
1921
1854
 
1922
1855
  The following guards validate ledger fractions, capacity, and snapshots:
1923
1856
 
1924
- | Name | Kind | Signature | Summary |
1925
- | ------------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1926
- | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1927
- | `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. |
1928
- | `ledgerWindowShape` | const | `import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes the minimal serialized evidence of a nonempty exchange window. |
1929
- | `ledgerWindowContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>>` | Reads structural faults of a serialized exchange window. |
1930
- | `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; digest: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; window: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a ledger snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
1931
- | `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; digest: string; } & {}>; window?: Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>; }>>` | Reads structural faults of a ledger snapshot, including its optional held exchange window. |
1932
- | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1933
- | `isLedgerWindowSnapshot` | function | `(value: unknown) => value is LedgerWindowSnapshot` | Checks whether a value has the exact shape of a nonempty exchange window. |
1934
- | `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
1857
+ | Name | Kind | Signature | Summary |
1858
+ | ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1859
+ | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1860
+ | `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. |
1861
+ | `ledgerWindowShape` | const | `import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes the minimal serialized evidence of a nonempty exchange window. |
1862
+ | `ledgerWindowContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>>` | Reads structural faults of a serialized exchange window. |
1863
+ | `ledgerSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").ObjectShape<{ id: 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>>; 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; digest: import("@orkestrel/contract").StringShape; model: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; window: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a ledger snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
1864
+ | `ledgerSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ conversation: Readonly<{ id: 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; digest: string; model: string; } & {}>; window?: Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>; }>>` | Reads structural faults of a ledger snapshot, including its optional held exchange window. |
1865
+ | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1866
+ | `isLedgerWindowSnapshot` | function | `(value: unknown) => value is LedgerWindowSnapshot` | Checks whether a value has the exact shape of a nonempty exchange window. |
1867
+ | `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
1935
1868
 
1936
1869
  #### Helpers
1937
1870
 
@@ -1954,7 +1887,7 @@ The following table lists the pure helpers that read text, project and select re
1954
1887
  | `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
1955
1888
  | `buildRequestMessage` | function | `(request: Message, records: string) => Message` | Builds the copy of a request turn that carries the rendered records ahead of the request. |
1956
1889
  | `renderTopicNames` | function | `(topics: readonly LedgerTopic[]) => string` | Renders topic names as a comma-separated list in their supplied order. |
1957
- | `renderCauseChain` | function | `(error: unknown) => string` | Renders an error and its causes, stopping after 4 entries. |
1890
+ | `collectQuestionKeys` | function | `(question: JudgeQuestion) => readonly string[]` | Collects the candidate keys of a judge question: a choice's criteria keys in their order, a score's level indexes as text, and `true` and `false` for a noul. |
1958
1891
  | `extractWords` | function | `(message: Message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
1959
1892
  | `splitWords` | function | `(part: string) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
1960
1893
  | `rankLedgerCut` | function | `(group: LedgerPlanGroup, unsettled: boolean, category: LedgerCategory \| undefined) => number` | Ranks a source the records render for removal before the next prompt. |
@@ -1971,7 +1904,7 @@ The following table lists the pure helpers that read text, project and select re
1971
1904
  | `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
1972
1905
  | `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState, write?: boolean, offered?: boolean) => string` | Renders the tail stub of a lookup result from an earlier request. |
1973
1906
  | `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
1974
- | `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
1907
+ | `requirePredict` | function | `(predict: number, capacity: number) => number` | Checks the generation cap against the context capacity and returns it. |
1975
1908
  | `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
1976
1909
  | `collectWriteSupersessions` | function | `(messages: readonly Message[], findings: readonly LedgerLookupFinding[]) => ReadonlyMap<string, readonly string[]>` | Collects each finding a write made stale, mapped to the writes that supersede it. |
1977
1910
  | `collectRetiredFindings` | function | `(messages: readonly Message[], findings: readonly LedgerLookupFinding[]) => ReadonlySet<string>` | Collects the findings a write superseded or a later finding of the same lookup replaced. |
@@ -2026,12 +1959,12 @@ classifier.quiet(rule.id) // false
2026
1959
  classifier.topics(rule.id) // Set { 'refunds' }
2027
1960
  classifier.classification().categories.get(rule.id) // 'rule'
2028
1961
 
2029
- const gauge = new Gauge({ scale: 1.25, overhead: 120, capacity: 32_768 })
1962
+ const gauge = new Gauge({ scale: 1.25, overhead: 120, capacity: 32_768, predict: 8_192 })
2030
1963
  const calls = [{ estimate: 400, prompt: 640, completion: 30, tools: 2 }]
2031
1964
  gauge.rate(calls) // 1.25 — the scale, because no two calls with one tool count are observed
2032
1965
  gauge.remainder(calls) // 32098 — the capacity less the last call's prompt and completion
2033
1966
  gauge.reserve(calls, '') // 36.25 — an empty reply and one recall call, priced at the rate
2034
- gauge.room(calls, '') // 12824.7 — half of what is left beyond the reserve, in estimate units
1967
+ gauge.room(calls, '') // 9547.9 — half of what is left beyond the generation cap and the reserve, in estimate units
2035
1968
  gauge.observe(calls)
2036
1969
  gauge.scale // 1.3 — the first call's prompt less the overhead cost, over its estimate
2037
1970
  ```
@@ -2240,11 +2173,11 @@ The name-keyed skill registry a host supplies skills through. `add` mints each `
2240
2173
 
2241
2174
  The richer turn context. `apply` changes the active per-turn filter, `select` runs the selection handler for one request, and `build` assembles the provider input. The `system` / `instructions` / `skills` / `memos` / `messages` / `tools` / `scope` / `workspaces` / `conversations` readonly data members stay Surface rows.
2242
2175
 
2243
- | Method | Returns | Summary |
2244
- | -------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2245
- | `apply` | `void` | Applies the given scope as the active per-turn filter; passing `undefined` explicitly removes filtering. |
2246
- | `select` | `Promise<Selection> \| undefined` | Runs the selection handler for one request — the run scope's `select`, else the active scope's, else the agent default — and checks that the conversation did not change under it. |
2247
- | `build` | `readonly Message[]` | Builds the provider input for the next turn: a leading `system` message folding the prompt, the scope-filtered instructions, the scope-filtered skills index (each section's header and each item's rendering resolved through the format cascade), and last the bodies of the skills `disclosure` shows under `## Loaded skills`, then one `user` context message holding the scope-filtered memos index, the admitted workspace ids under `## Workspaces` when `switchable` is `true`, and the rendered workspace's scope-filtered (`scope.files`) text files as fenced reference blocks in a `## Workspace` section, then the active conversation's `view()`, or the selection's `messages` when a selection is passed, with the rendered workspace's image files' `base64` payload attached to the last user message. With no override set, each section renders on its manager's built-in framing. The `system` message is prepended only when some part of it exists, the context message only when one of its sections renders, one workspace renders, tools are advertised structurally rather than in the prompt, and the input is built fresh on each call. |
2176
+ | Method | Returns | Summary |
2177
+ | -------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2178
+ | `apply` | `void` | Applies the given scope as the active per-turn filter; passing `undefined` explicitly removes filtering. |
2179
+ | `select` | `Promise<Selection> \| undefined` | Runs the selection handler for one request — the run scope's `select`, else the active scope's, else the agent default — and checks that the conversation did not change under it. |
2180
+ | `build` | `readonly Message[]` | Builds the provider input for the next turn: a leading `system` message folding the prompt, the scope-filtered instructions, the scope-filtered skills index (each section's header and each item's rendering resolved through the format cascade), and last the bodies of the skills `disclosure` shows under `## Loaded skills`, then one `user` context message holding the scope-filtered memos index, the admitted workspace ids under `## Workspaces` when `switchable` is `true`, and the rendered workspace's scope-filtered (`scope.files`) text files as fenced reference blocks in a `## Workspace` section, then the active conversation's `messages()`, or the selection's `messages` when a selection is passed, with the rendered workspace's image files' `base64` payload attached to the last user message. With no override set, each section renders on its manager's built-in framing. The `system` message is prepended only when some part of it exists, the context message only when one of its sections renders, one workspace renders, tools are advertised structurally rather than in the prompt, and the input is built fresh on each call. |
2248
2181
 
2249
2182
  #### `AgentInterface`
2250
2183
 
@@ -2355,33 +2288,31 @@ const results = await runner.execute([parent]) // the parent's result, then the
2355
2288
 
2356
2289
  #### `ConversationInterface`
2357
2290
 
2358
- A conversation that owns its live message tail directly (the flat store verbs folded in, like a `Workspace` owns its files). `add` mints each message's `id` and stores it (batch overloads); `message` / `messages` look up the live tail; `remove` / `clear` drop from it. `view` is the model input; `compact` folds the older live messages into a summarized `Section` and emits `compact`; `rehydrate` / `search` read the retained originals; `reference` renders this conversation as a provenance-labeled block to pull into another (a pure string, no model call). The `id` / `judgments` / `emitter` / `sections` / `summarizable` / `count` data members stay Surface rows (`emitter` is a `readonly` accessor — a property, not a method).
2291
+ A conversation that owns its messages directly (the flat store verbs folded in, like a `Workspace` owns its files). `add` mints each message's `id` and stores an owned, deep-frozen copy (batch overloads); `message` / `messages` look up the stored messages; `remove` drops a message with the rest of its call group, and `remove` / `clear` drop every judgment that quotes a removed message. `search` reads every stored message; `reference` renders this conversation as a provenance-labeled block to pull into another (a pure string, no model call); `destroy` tears down the emitter. The `id` / `judgments` / `emitter` / `count` data members stay Surface rows (`emitter` is a `readonly` accessor — a property, not a method).
2359
2292
 
2360
- | Method | Returns | Summary |
2361
- | ----------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2362
- | `add` | `Message` / `readonly Message[]` | Appends one `MessageInput` to the live tail, or a batch — mints each message's `id` (a random UUID) and returns the created message or messages; a stored message is immutable. |
2363
- | `message` | `Message \| undefined` | Looks up one live message by id (`undefined` when absent). |
2364
- | `messages` | `readonly Message[]` | Lists every live, uncompacted message in the tail, in insertion order. |
2365
- | `remove` | `boolean` | Removes one live message by id, or a batch, from the tail — `true` only when every supplied id was removed. |
2366
- | `clear` | `void` | Empties the live tail, leaving the compacted `sections` untouched. |
2367
- | `view` | `readonly Message[]` | Builds the model input for the next turn — each section as one synthetic recap message, its summary prefixed with `CONVERSATION_RECAP_PREFIX` so a small model reads it as a recap rather than a literal turn, then the live tail verbatim. |
2368
- | `compact` | `Promise<Section \| undefined>` | Folds whole exchanges from the oldest `count - keep` live messages, cut short at the newest user message, into a summarized `Section` through the `ConversationSummaryHandler`, removes them from the live tail, and emits `compact` — resolving `undefined` when nothing folds. |
2369
- | `rehydrate` | `readonly Message[] \| undefined` | Returns the full original messages of a known section and emits its `id` through `rehydrate`, including an empty list; returns `undefined` without an event for an unknown `id`. Never reinserts messages. |
2370
- | `search` | `readonly Message[]` | Searches `content` for a case-insensitive substring across every message — the retained originals of each section, then the live tail. |
2371
- | `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`. |
2372
- | `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. |
2293
+ | Method | Returns | Summary |
2294
+ | ----------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2295
+ | `add` | `Message` / `readonly Message[]` | Appends one `MessageInput`, or a batch — mints each message's `id` (a random UUID), stores an owned, deep-frozen copy, emits `add` per message, and returns the stored message or messages. |
2296
+ | `message` | `Message \| undefined` | Looks up one stored message by id (`undefined` when absent). |
2297
+ | `messages` | `readonly Message[]` | Lists every stored message, in insertion order. |
2298
+ | `remove` | `boolean` | Removes one message by id, or a batch, with the rest of each call group a removed message belongs to and every judgment that quotes a removed message, then emits `remove` per removed message — `true` only when every supplied id was present. |
2299
+ | `clear` | `void` | Removes every stored message and every judgment that quotes one, then emits one `clear`. |
2300
+ | `search` | `readonly Message[]` | Searches every stored message's `content` for a case-insensitive substring. |
2301
+ | `reference` | `string` | Renders this conversation as a self-labeled provenance block fenced at both ends, to pull into another conversation — a pure string with no model call: an opening `[Reference — conversation "<label>" — NOT part of this conversation]` marker, then the cherry-picked excerpts (`- role: content`) when `messages` is supplied, then a closing `[End of reference "<label>"]` marker. |
2302
+ | `snapshot` | `ConversationSnapshot` | Serializes this conversation to a plain, JSON-serializable `ConversationSnapshot` — its `id`, its messages, and its judgments when it holds one. |
2303
+ | `destroy` | `void` | Tears down the emitter: drops every listener, so later mutations reach no observer. |
2373
2304
 
2374
- 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.
2305
+ `reference` refuses a label holding a double quote or a line break with `ConversationError` `'LABEL'`, because either could rewrite the block's markers. A hydrate takes an owned, deep-frozen copy of each message and refuses, with `ConversationError` `'SNAPSHOT'`, a snapshot `snapshot()` couldn't have written: a malformed value, a repeated id, or a value JSON would change.
2375
2306
 
2376
2307
  #### `ConversationManagerInterface`
2377
2308
 
2378
- 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`).
2309
+ The id-keyed registry of `Conversation` instances with an active pointer. `add(input?)` mints a conversation 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`).
2379
2310
 
2380
2311
  | Method | Returns | Summary |
2381
2312
  | --------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2382
2313
  | `conversation` | `ConversationInterface \| undefined` | Looks up one conversation by id (`undefined` when absent). |
2383
2314
  | `conversations` | `readonly ConversationInterface[]` | Lists every conversation, in insertion order. |
2384
- | `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. |
2315
+ | `add` | `ConversationInterface` | Mints a conversation, taking its `id` from the input or a fresh UUID — auto-activates the first, and an already-present `id` throws. |
2385
2316
  | `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. |
2386
2317
  | `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. |
2387
2318
  | `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. |
@@ -2420,13 +2351,15 @@ The driver-backed implementation keeps an explicit table because its class name
2420
2351
 
2421
2352
  #### `LedgerInterface`
2422
2353
 
2423
- The conversation ledger. The `respond` method serves one request through to its reply, the `calibrate` method measures the price of a prompt, and the `snapshot` method serializes the ledger for a later ledger to hydrate from. The `agent`, `conversation`, and `gauge` data members stay Surface rows. A `respond` or `calibrate` call while either is in flight rejects with `AgentError` code `CONCURRENCY`, and a `snapshot` call while either is in flight throws that error.
2354
+ The conversation ledger. The `respond` method serves one request through to its reply, the `stream` method serves it the same way while it yields each pass's chunks, the `calibrate` method measures the price of a prompt, the `snapshot` method serializes the ledger for a later ledger to hydrate from, and the `destroy` method tears it down. The `agent`, `conversation`, and `gauge` data members stay Surface rows. A `respond`, `stream`, or `calibrate` call while any of them is in flight rejects with `AgentError` code `CONCURRENCY`, and a `snapshot` or `destroy` call while one is in flight throws that error. After `destroy`, each of the other four methods refuses with `LedgerError` code `DESTROYED`.
2424
2355
 
2425
- | Method | Returns | Summary |
2426
- | ----------- | ----------------------- | -------------------------------------------------------------------------------------------------------- |
2427
- | `respond` | `Promise<LedgerResult>` | Appends `content` as a user message and serves it through to its reply. |
2428
- | `calibrate` | `Promise<LedgerGauge>` | Measures the gauge, holds it as `gauge`, and returns it. |
2429
- | `snapshot` | `LedgerSnapshot` | Serializes the conversation, the marked ids, and the gauge into a snapshot a later ledger hydrates from. |
2356
+ | Method | Returns | Summary |
2357
+ | ----------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
2358
+ | `respond` | `Promise<LedgerResult>` | Appends `content` as a user message and serves it through to its reply. |
2359
+ | `stream` | `StreamInterface<AgentChunk, LedgerResult>` | Appends `content` as a user message and serves it as `respond` does, yielding each pass's chunks as they arrive. |
2360
+ | `calibrate` | `Promise<LedgerGauge>` | Measures the gauge, holds it as `gauge`, and returns it. |
2361
+ | `snapshot` | `LedgerSnapshot` | Serializes the conversation, the marked ids, and the gauge into a snapshot a later ledger hydrates from. |
2362
+ | `destroy` | `void` | Tears the ledger down: destroys its conversation's emitter and its agent's emitter, which ends every subscription on them, and refuses every later call. |
2430
2363
 
2431
2364
  #### `LedgerRequestInterface`
2432
2365
 
@@ -2462,7 +2395,7 @@ import type { Selection } from '@orkestrel/agent'
2462
2395
  import { createConversation, LedgerRequest } from '@orkestrel/agent'
2463
2396
 
2464
2397
  const conversation = createConversation()
2465
- const request = new LedgerRequest('Does the $148.50 refund need a manager?', 1) // 1 recall call
2398
+ const request = new LedgerRequest('Does the $148.50 refund need a manager?') // LEDGER_RECALL_LIMIT recall calls
2466
2399
  const message = request.enter(conversation) // the appended user message
2467
2400
  request.enter(conversation) === message // true — a later call appends nothing
2468
2401
 
@@ -2493,7 +2426,8 @@ request.deny('refund_order', { id: 'BW-5512' }) // as the agent's `deny` event w
2493
2426
  request.denied('refund_order', { id: 'BW-5512' }) // true — the ledger denies its identical retry as a repeat
2494
2427
  request.denied('refund_order', { id: 'BW-5513' }) // false — other arguments are another call
2495
2428
  request.recall()
2496
- request.recall() // throws Error(LEDGER_NOTES.closure) — the 1 recall call is spent
2429
+ request.recall()
2430
+ request.recall() // throws Error(LEDGER_NOTES.closure) — the 2 recall calls are spent
2497
2431
 
2498
2432
  const listed = 'lookup_order {"id":"BW-5512"}: Refund due $148.50.'
2499
2433
  request.list(listed, new Map([[listed, 'Order BW-5512 for account BW-20931: Brightwater Studio.']]))
@@ -2507,7 +2441,7 @@ The ledger's filing engine. The `classify` method asks the judge what the conver
2507
2441
 
2508
2442
  | Method | Returns | Summary |
2509
2443
  | ---------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
2510
- | `classify` | `Promise<ClassifierResult>` | Asks every filing question the conversation's judgments lack an answer for. |
2444
+ | `classify` | `Promise<ClassifierResult>` | Asks every filing question the conversation's judgments lack a reading for. |
2511
2445
  | `category` | `LedgerCategory \| undefined` | Returns the assigned or recorded category, or undefined when no category reaches its cutoff or the user literal floor suppresses a quiet winner. |
2512
2446
  | `quiet` | `boolean` | Returns true for a quiet assignment or a recorded quiet weight at the cutoff, except for a user message carrying an id or number; false otherwise. |
2513
2447
  | `decisive` | `boolean` | Returns true if the message is filed as decisive; false otherwise. |
@@ -2531,21 +2465,21 @@ The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read th
2531
2465
  These invariants hold across `src/core` ↔ `agent.md`:
2532
2466
 
2533
2467
  - **Doc ↔ source bijection.** Every row in the `## Surface` tables is a real export of `src/core`, and every export appears as a Surface row.
2534
- - **`ProviderInterface` is the inference boundary; `AgentProvider` is the engine behind it.** A provider turns a conversation, optional `tools`, and optional `ProviderStreamOptions` into a turn: `generate` resolves the assembled `ProviderResult`, and `stream` yields channel-tagged `ProviderDelta` values and returns the same result. `AgentProvider` owns the deadline, the transport, the `headers` hook, the bounded error read, the decode loop, reasoning separation, and result assembly, and a subclass supplies one vendor's wire through `frame`, `encode`, `read`, and `finish`. The loop and its tools run in the host that constructs them; see [Placement proofs](#placement-proofs) for each placement's receipt.
2468
+ - **`ProviderInterface` is the inference boundary; `AgentProvider` is the engine behind it.** A provider turns a conversation, optional `tools`, and optional `ProviderStreamOptions` into a turn: `generate` resolves the assembled `ProviderResult`, and `stream` yields channel-tagged `ProviderDelta` values and returns the same result. `AgentProvider` owns the deadline, the transport, the `headers` hook, the bounded error read, the decode loop, reasoning separation, and result assembly, and a subclass supplies one vendor's wire through `frame`, `encode`, `read`, and `finish`. A provider carries `model`, the non-empty name of the model it serves, which `AgentProviderInput.model` configures on the engine; `createAgent` and `createLedger` refuse a provider whose `model` is missing, not a string, or empty with `ContractError` coded `'placement'`, its `context` naming the path `['provider', 'model']`. The loop and its tools run in the host that constructs them; see [Placement proofs](#placement-proofs) for each placement's receipt.
2535
2469
  - **`stream` yields deltas and returns the assembled result.** `stream` yields each non-empty answer delta as `{ channel: 'content', text }` and each native reasoning delta as `{ channel: 'thinking', text }`, and returns the `ProviderResult` whose `content` is the authoritative clean answer. A provider reading a raw wire routes content through a per-stream `ThinkSplitter` armed by `split` and surfaces the reasoning as `ProviderResult.thinking`, which the agent records on the assistant message and sends back only as the provider's `replay` policy allows. `RelayProvider` constructs with `split: false`, so it preserves each upstream delta verbatim, a literal `<think>` tag included.
2536
2470
  - **Usage reuses `TokenUsage`.** `ProviderResult.usage` is the [budgets](budget.md) `TokenUsage` shape `{ prompt, completion, total }`, present only when the turn reported it.
2537
2471
  - **The caller's signal and the engine's deadline both bound the call.** `generate` and `stream` take an `AbortSignal`, and an already-aborted signal rejects before any content streams. `AgentProvider` folds a per-call `Timeout` of `AgentProviderInput.timeout` milliseconds (`DEFAULT_PROVIDER_TIMEOUT` when omitted) with that signal through `AbortSignal.any`, covering the `headers` hook, the error-body read, and the stream. The deadline is cleared on every exit.
2538
2472
  - **A local cancel and a remotely reported one are different failures.** A `stream` cancelled by its bound throws `ProviderAbortError` whose `partial` holds what was assembled locally, with a throw that raced the cancel carried as its `cause`. A relay `abort` frame makes `RelayProvider.read` throw a reconstructed `ProviderAbortError` carrying the upstream partial while the local signal stays unaborted, and the engine propagates that instance unchanged.
2539
2473
  - **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.
2540
- - **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, the scope-filtered skills index, and the bodies of the shown skills into one leading `system` message, renders the scope-filtered memos index, the admitted workspace ids when `switchable` is `true`, and the shown 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.
2541
- - **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`, `workspaces` by `id`), applied through `filterAllowList`, and `narrow` intersects each list, so narrowing only tightens. A write is the exception: `remember` writes and `switch` selects only a name their list holds, so an absent or empty `memos` or `workspaces` list lets neither act. 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.
2474
+ - **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, the scope-filtered skills index, and the bodies of the shown skills into one leading `system` message, renders the scope-filtered memos index, the admitted workspace ids when `switchable` is `true`, and the shown workspace's scope-filtered text files into one `user` context message after it, then appends the active conversation's `messages()`, 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.
2475
+ - **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`, `workspaces` by `id`), applied through `filterAllowList`, and `narrow` intersects each list, so narrowing only tightens. A write is the exception: `remember` writes and `switch` selects only a name their list holds, so an absent or empty `memos` or `workspaces` list lets neither act. The scope's filters never touch messages; message inclusion is the conversation's 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.
2542
2476
  - **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.
2543
2477
  - **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.
2544
2478
  - **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.
2545
- - **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.
2479
+ - **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. The loop races a scheduler's yield and the approver's answer 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.
2546
2480
  - **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`, `request`) 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`.
2547
- - **Options refuse a member their type does not declare.** The constructor of `Agent`, `Ledger`, `Scope`, `Authority`, `AgentRegistry`, `AgentContext`, `Conversation`, `ConversationManager`, `InstructionManager`, `MemoManager`, `ScopeManager`, `SkillManager`, `Classifier`, `Gauge`, `RelayProvider`, `RelayStream`, `AgentProvider`, `AgentJudge`, and `SystemOneJudge`, and the `createAgentQueue`, `createAgentRunner`, and `createRelay` factories, each refuse an own enumerable member outside the key list beside its type with `ContractError` coded `'structure'`, through `refuseOptionKeys`, before anything is built. The `add` method of a `ConversationManager` reads its `ConversationInput` the same way, because that input is per-conversation options with `summarize`, `on`, and `error` handlers. A declared member holding `undefined` reads as omitted.
2548
- - **Per-call options refuse the same way.** `stream` and `generate` of an agent, `narrow` of a scope, `build` of an `AgentContext`, `compact` and `reference` of a `Conversation`, and `generate` and `stream` of an `AgentProvider` refuse an undeclared member with `ContractError` coded `'structure'`, a run before it changes anything.
2481
+ - **Options refuse a member their type does not declare.** The constructor of `Agent`, `Ledger`, `Scope`, `Authority`, `AgentRegistry`, `AgentContext`, `Conversation`, `ConversationManager`, `InstructionManager`, `MemoManager`, `ScopeManager`, `SkillManager`, `Classifier`, `Gauge`, `RelayProvider`, `RelayStream`, `AgentProvider`, `AgentJudge`, and `SystemOneJudge`, and the `createAgentQueue`, `createAgentRunner`, and `createRelay` factories, each refuse an own enumerable member outside the key list beside its type with `ContractError` coded `'structure'`, through `refuseOptionKeys`, before anything is built. The `add` method of a `ConversationManager` reads its `ConversationInput` the same way, because that input is per-conversation options with `on` and `error` handlers. A declared member holding `undefined` reads as omitted.
2482
+ - **Per-call options refuse the same way.** `stream` and `generate` of an agent, `narrow` of a scope, `build` of an `AgentContext`, `reference` of a `Conversation`, and `generate` and `stream` of an `AgentProvider` refuse an undeclared member with `ContractError` coded `'structure'`, a run before it changes anything.
2549
2483
  - **A stored data record refuses as a record.** `Conversation.add` admits a `MessageInput` through the exact `isMessageInput` guard: a value that is not a plain record, such as a class instance or an object that inherits its `role`, refuses first, and an input holding an undeclared member, or a declared member holding `undefined`, refuses too, each with `ConversationError` coded `'MESSAGE'` and the faults under `context.faults`; a tool call keeps `id`, `name`, and `arguments` and leaves the members the `ToolCall` interface of `@orkestrel/tool` admits beyond them. The `add` methods of an `InstructionManager`, a `MemoManager`, and a `SkillManager`, and the `Instruction` constructor, admit each input through its exact contract, `instructionInputContract`, `memoInputContract`, or `skillInputContract`, with the `requireRecordInput` helper: a missing required member, an undeclared member, a declared member holding `undefined`, and a member of another type each refuse with `ContractError` coded `'structure'`, whose `context` names the first fault's `path`, so a stored record carries no member holding `undefined` and a memo set's snapshot hydrates. A skill's `tools` member is read first and refuses with code `'placement'`. A batch stores nothing when one input refuses.
2550
2484
  - **Error constructors and internal helpers take no door.** The options of `AgentError`, `ContextError`, `ConversationError`, `LedgerError`, `ProviderError`, `ProviderAbortError`, `JudgeError`, and `JudgeAbortError` mirror the platform's `ErrorOptions`, which admits any member, and a refusal thrown while an error is built would hide the error it reports. A helper that receives a value an admitted door built reads its named members and refuses nothing.
2551
2485
  - **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.
@@ -2555,27 +2489,17 @@ These invariants hold across `src/core` ↔ `agent.md`:
2555
2489
  - **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.
2556
2490
  - **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.
2557
2491
  - **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. Before a unit spawns or runs, that method walks the whole tree under it and throws `AgentError` with code `REGISTRY` when any job exceeds its own parent, so nothing in a refused tree runs.
2558
- - **The conversation layer (`Conversation` + `ConversationManager`).** `compact()` folds the oldest `count - keep` live messages through the `ConversationSummaryHandler` into a `Section`, stopping before the newest user message, moving a cut inside an exchange back to its start so a fold removes whole exchanges, folding the messages before the first user message, which form their own exchange, only together with the first user exchange, and moving a cut that would split an assistant call from its tool results before that call, emits `compact`, and throws `ConversationError` with code `SUMMARIZER` when no summarizer was supplied. Calls run one at a time, and a fold commits only when its messages are still the live entries after the summarizer settles. A `remove` or `clear` during the initial summarizer leaves no section. A summarizer must not compact the conversation it serves: with no other fold in flight, its own call summarizes the same slice again, and one section commits. An abort of `CompactOptions.signal` rejects with the reason at once and commits nothing after the abort; a fold committed before an aborted overflow merge stays. `view()` renders each section as one assistant recap prefixed with `CONVERSATION_RECAP_PREFIX`, then the live tail, while `rehydrate`, `search`, and `reference` are pure reads. `ConversationManager` is the event-free id-keyed registry with an active pointer, `switch`, and the `open` / `save` store seam.
2559
- - **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.
2560
- - **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.
2492
+ - **The conversation layer (`Conversation` + `ConversationManager`).** `add` and a hydrate own each message through JSON and store it deep-frozen. `remove` of any member of a call group removes the whole group, so a provider never receives half of one, and `remove` and `clear` drop every judgment that quotes a removed message. The emitter reports `add`, `remove`, and `clear` after each change, and `destroy()` drops every listener. `search` and `reference` are pure reads, and `reference` refuses a label holding a double quote or a line break with `ConversationError` `'LABEL'`. `ConversationManager` is the event-free id-keyed registry with an active pointer, `switch`, and the `open` / `save` store seam.
2493
+ - **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 `messages()`, and appends every assistant and tool message to it, so a later `switch`, `open`, `remove`, `clear`, or same-id `add` never moves a live run, and the conversation needs no registration.
2494
+ - **The whole conversation, sent.** The loop sends every message the run's conversation holds, after the `replay` policy, or the selection's messages when a handler runs. When no selection handler runs, the loop adds no `await` before the first provider request.
2561
2495
  - **Active workspace rendering by carrier.** `build()` reads one workspace, the one its `disclosure` option names, else the active one, and only while the ceiling's `workspaces` list admits it; it filters that workspace's 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 rendered workspace, or no text file, the context message holds the memos index and the workspace ids alone, and with neither of those, no context message renders.
2562
- - **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.
2496
+ - **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events; the hydrate owns each message through JSON, so a snapshot that holds a value JSON would change, or a member its shape doesn't declare, refuses with `ConversationError` `'SNAPSHOT'`. `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.
2563
2497
  - **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`, `prompt`, and `scope` have no construction default, a run `scope` narrows the context scope, which the construction `scope` option sets first, and never replaces it, 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 positive safe integer throws `AgentError` with code `LIMIT`.
2564
2498
  - **Construction-time context wiring.** `AgentOptions.instructions`, `skills`, `memos`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
2565
2499
  - **The built-ins and what a run shows (`builtins` / `workspace`).** Each enabled built-in is a tool the run owns, advertised only where the ceiling admits its name, and each call passes the scope check, `evaluate`, the `consequential` floor, the approver, and the ceiling its handler reads when it runs. A run shows the skills the conversation's successful `load` and `unload` calls record, and the workspace its last successful `switch` call records, else the one the `workspace` option names, else the active one, each kept only where its registry holds it and the ceiling admits it. A shown body renders last in the one `system` message. While `builtins` enables `load`, a tool a registered skill lists is advertised only while a shown skill lists it, unless the ceiling's `tools` list admits no `load` definition, which leaves the allow-list alone to decide. A change to that view reaches the next turn's head.
2566
- - **`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.
2567
- - **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.
2568
- - **`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`.
2569
- - **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.
2570
-
2571
- 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.
2572
-
2573
- In the from-stop reading of 2026-11-03, `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. In the separate fixture reading of 2026-11-03, 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.
2574
-
2575
- Beside that stop, `cumulative` has a reading and no recommendation. In the cumulative reading of 2026-11-03, seeded from that run's goal 32 on Ollama 0.40.14, it sealed goals 33 to 48 with three folds, each into one section, and the first prompts after those folds read 2958 to 3192 tokens, where the first prompts after the first seven folds of the 2026-11-02 and 2026-11-03 recording without it read 2733 to 11176. Its recaps kept fewer literals by `extractLiterals`: at goal 48, 11 of 170 ids and 14 of 112 numbers of 147 folded messages (254018 characters, median 577, 95th percentile 6716, maximum 6911) in a recap of 3456 characters; at goal 34, 14 of 138 ids and 15 of 96 numbers of 116 folded messages (177397 characters, median 580, 95th percentile 4824, maximum 5030) in a recap of 4844 characters. The 2026-11-02 and 2026-11-03 recording without it kept 57 of 138 ids and 41 of 96 numbers over the same 116 messages at goal 34, in 6 recaps of 31077 characters, and 48 of 122 ids and 41 of 87 numbers over 104 messages of 158238 characters at goal 32, in 5 recaps of 23135 characters. The originals stay on the section, and `search` and `rehydrate` read them back; they reach the model only through a tool the host registers, and Agent ships none. This is one arm, one seed, and one recording on two Ollama versions, so the figures state no cause, and no quality label reads these recaps. No reading on this model compares a `sections` cap with `cumulative`.
2576
-
2500
+ - **`strict` — fault escalation.** `AgentOptions.strict` defaults to `true`: each selection fault emits `fault` and then settles 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'`. A cancel at a select site wins over `strict`.
2577
2501
  - **`sanitizeUsage`.** `sanitizeToken` turns a non-finite or non-positive count into `0` and floors a positive fraction, and `sanitizeUsage` applies it to each field. A settled provider result crosses the provider-result guard before charging or folding its usage; malformed present usage refuses the result. The loop sanitizes an abort partial's usage, and absent usage retains the estimate.
2578
- - **`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`, a `conversation` that does not implement `ConversationInterface`, a `scope` that does not implement `ScopeInterface`, or a `workspace` that is not a string throws `ContractError` with code `placement` before either bound starts, and a refused run appends no `prompt`. `isAgentError` narrows a caught value. A `REGISTRY` error from a registry lookup names the `category` and `name` in its `context`, and one from the fan-out check carries its `findings` there.
2502
+ - **`AgentError` — the concurrency guard.** `stream()` throws `AgentError` with code `CONCURRENCY` and `context: { agent }` synchronously when the run's effective `budget` or `allowance` is an instance a live run holds; after that check 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 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 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`, a `conversation` that does not implement `ConversationInterface`, a `scope` that does not implement `ScopeInterface`, or a `workspace` that is not a string throws `ContractError` with code `placement` before either bound starts, and a refused run appends no `prompt`. `isAgentError` narrows a caught value. A `REGISTRY` error from a registry lookup names the `category` and `name` in its `context`, and one from the fan-out check carries its `findings` there.
2579
2503
  - **`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.
2580
2504
  - **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.
2581
2505
  - **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.
@@ -2591,8 +2515,8 @@ These invariants hold across `src/core` ↔ `agent.md`:
2591
2515
  - **The System One response model and usage.** On the System One wire, `JudgeResult.model` reports the model the response named, verbatim, and a response that names no model reports the configured `model` option. `extractSystemOneUsage` maps `input_tokens` and `output_tokens` onto `{ prompt, completion, total }`, and `usage` is absent when either count is missing, `null`, negative, or not finite.
2592
2516
  - **Header-hook authentication.** Both engines read the `headers` hook through `buildProviderHeaders`: the headers start from `Content-Type: application/json`, the hook is awaited with the call's combined signal and raced against it, and each entry it returns is set over the defaults.
2593
2517
  - **Three selection homes.** `AgentOptions.select` is the agent default, the active scope's `select` overrides it, and a run scope's `select` overrides both for its run, and `context.select` resolves the handler once per call and returns `undefined` when no home holds one, so the default path awaits nothing.
2594
- - **Select sites and the receipt.** The loop calls the handler with the request captured at run entry and the run's signal at run entry, the pre-first-turn compaction fold, and each compaction rebuild, folds the result through `build({ selection, scope })` with the run scope as `scope`, a build that carries `selection.messages` after the unchanged system and context messages, and then emits `select`. A `Selection` has no tool member, so advertising and admission stay the scope's.
2595
- - **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.
2518
+ - **The select site and the receipt.** The loop calls the handler with the request captured at run entry and the run's signal at run entry, folds the result through `build({ selection, scope })` with the run scope as `scope`, a build that carries `selection.messages` after the unchanged system and context messages, and then emits `select`. A `Selection` has no tool member, so advertising and admission stay the scope's.
2519
+ - **Selection faults.** A thrown handler, a returned `fault`, a conversation changed under the handler, and a selected `system` message, carrying `ConversationError` `'ROLE'` over `messages()`, each emit `fault`; a throw builds from `messages()` with no `select` event, and a returned `fault` charges its usage before `fault` fires. With `strict` set, each settles the run `error`. Each error a selection lists in `recoveries` emits `fault` before the build, and none settles the run `error`. A cancel at a select site wins over every fault, and the run commits partial without a further provider call.
2596
2520
  - **Selection cost.** Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`, with no `usage` chunk or `usage` event.
2597
2521
  - **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.
2598
2522
  - **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`.
@@ -2604,7 +2528,7 @@ The following list holds the documented limits: the ledger's first, then those o
2604
2528
  - **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.
2605
2529
  - **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.
2606
2530
  - **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.
2607
- - **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.
2531
+ - **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. The `respond` call rejects with that error, after the agent's `fault` event and before it reaches the provider, and the ledger stays free for a later call.
2608
2532
  - **A ledger tool called by hand joins the request in flight.** The ledger holds a request's state in a `LedgerRequest` value from the start of its `respond` call until the call settles. Host code that calls a ledger tool by hand through `agent.context.tools` while a request runs reaches that request's state: a lookup or a write meets that request's repeat stop, and a `recall` call spends that request's recall limit. Between requests, and during calibration, such a call reads no request's state and runs with no repeat stop, recall limit, or close rule.
2609
2533
  - **The ledger's agent emitter can clear the ledger's listeners.** `ledger.agent.emitter` exposes `emit`, `clear`, and `destroy`, as every agent's emitter does, so code that holds it can emit a `usage` event the active request counts as spent, or clear the listeners the ledger registered there, the `request` listener that runs the capacity gate included. Hand it only to code you trust with `ledger.agent.context`, which can change every registry.
2610
2534
  - **A host's own selection during a pass files the request again.** A direct `ledger.agent.context.select` call for the active request's message, made during one of its passes, files that request a second time, so that `respond` call's `attempts` member holds the second filing's attempts too. No message is stored twice.
@@ -2619,16 +2543,16 @@ The following list holds the documented limits: the ledger's first, then those o
2619
2543
  - **Lookups read, writes change; both answer to `agent.authority`.** A tool whose call changes a record is a write, never a lookup. The ledger passes its agent one authority, which denies every name the ledger doesn't advertise, allows `recall`, and hands every lookup and write to the `authority` member of the `agent` option, whose `ask` answers each asked call. Without that member, the ledger allows each lookup itself and holds no approver, so a `consequential` lookup meets the floor and is denied as unanswered at every call. A tool a host adds later reads `the ledger advertises no such tool` under either.
2620
2544
  - **A repeated write asks before it stops.** The repeat stop runs when a call executes, after its approval, so a write that repeats an earlier call of the same request that ran asks the approver and then returns the `repeat` note. A write that repeats a call the authority denied, declined, or left unanswered in the same request is denied as a repeat before the ask instead.
2621
2545
  - **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. A host that migrates or redacts a snapshot can delete its `window` member as the clean path, because the stored copies repeat conversation text: the hydrated ledger derives the newest pair plain, and no stored copy keeps the old text in the snapshot's bytes or can send it.
2622
- - **A stored gauge holds for the tool definitions it priced.** The `gauge` member of a snapshot, a `LedgerGaugeSnapshot` value, holds the scale, the overhead cost, and a required `digest` member, which the `digestLedgerTools` helper computes over the calibrated definitions the calibration request carried, or over the ledger's calibrated definitions at construction when the `gauge` option supplied the price. A ledger hydrated with calibrated definitions of another digest, because an application added, removed, or edited a lookup or a write, changed the tools a skill holds back, or changed the topics the `recall` definition names, drops the stored gauge, reads `undefined` from its `gauge` member, and calibrates before its first pass, so a hydrated ledger never plans with an overhead priced on other definitions. Each `respond` call compares the digest again at its entry, over the calibrated definitions then, so a tool a host adds or removes between requests drops the gauge and calibrates before that request's first pass. A reordered list changes the digest too and costs one calibration. With the same definitions, the hydrated ledger reuses the gauge and makes no calibration call. The `isLedgerSnapshot` guard refuses a gauge with no `digest` member, and construction refuses that snapshot with `LedgerError` code `'SNAPSHOT'`. The `snapshot` method omits the gauge when JSON can't render its definitions. A `gauge` option is the application's own price for the calibrated definitions at construction: the ledger keeps it while those definitions stay the same, and a `respond` call that finds others drops it and calibrates, as it does a stored gauge. The digest is its only check: the ledger never compares a stored gauge with the provider's reports, so after you change the model or the provider, delete the `gauge` member of the snapshot you hydrate, and the ledger calibrates before its first pass.
2546
+ - **A stored gauge holds for the tool definitions it priced and the model it was measured on.** The `gauge` member of a snapshot, a `LedgerGaugeSnapshot` value, holds the scale, the overhead cost, a required `digest` member, which the `digestLedgerTools` helper computes over the calibrated definitions the calibration request carried, or over the ledger's calibrated definitions at construction when the `gauge` option supplied the price, and a required `model` member, the `model` of the ledger's provider. A ledger hydrated with calibrated definitions of another digest, because an application added, removed, or edited a lookup or a write, changed the tools a skill holds back, or changed the topics the `recall` definition names, or hydrated under a provider whose `model` differs from the stored one, drops the stored gauge, reads `undefined` from its `gauge` member, and calibrates before its first pass, so a hydrated ledger never plans with an overhead priced on other definitions or a scale measured on another model's tokenizer. Nothing else reports the drop: no event fires and no error is thrown. Each `respond` call compares the digest again at its entry, over the calibrated definitions then, so a tool a host adds or removes between requests drops the gauge and calibrates before that request's first pass. A reordered list changes the digest too and costs one calibration. With the same definitions, the hydrated ledger reuses the gauge and makes no calibration call. The `isLedgerSnapshot` guard refuses a gauge with no `digest` member or with no non-empty `model` member, and construction refuses that snapshot with `LedgerError` code `'SNAPSHOT'`. The `snapshot` method omits the gauge when JSON can't render its definitions. A `gauge` option is the application's own price for the calibrated definitions at construction: the ledger keeps it while those definitions stay the same, and a `respond` call that finds others drops it and calibrates, as it does a stored gauge. The digest and the stored `model` are its only checks: the ledger never compares a stored gauge with the provider's reports, so after you change what a provider sends while its `model` stays the same, such as its chat template or its server, delete the `gauge` member of the snapshot you hydrate, and the ledger calibrates before its first pass.
2623
2547
  - **A supplied gauge is your statement of the price.** The `gauge` option states the tokens one unit of estimate costs and the tokens the ledger's definitions add. The ledger prices every request with it as stated and doesn't compare it with the usage the provider reports. Take it from `calibrate`, or from the ledger's `gauge` member, on the same provider, model, and definitions: the ledger compares the definitions at every request and nothing else, so a gauge measured on another model stays in use. A gauge that states less than the provider charges sends requests over `capacity` less `predict`, from the first request. A gauge that states more refuses requests that fit: the first pass ends with the reason `overflow`, or `respond` rejects with `LedgerError` code `'OVERFLOW'`. Don't raise the overhead for margin on a provider that reports usage: the ledger rescales from each request's first call against the stated overhead, so an overhead stated too high lowers the scale, and a later, longer request is priced under what the provider charges. With a provider that reports no usage, the gauge is the only price the ledger holds, and nothing rescales it, so state it at or over what the provider charges. To have the ledger measure the price, omit the option: the ledger calibrates before its first pass.
2624
2548
  - **A partial set is priced by its text's length.** The `computeToolPrice` helper credits a calibrated definition a call leaves out at the lower of the gauge's scale and the calibrated set's overhead per estimate unit, so the credit never exceeds that definition's proportional share of the measured overhead, and it prices a definition a call advertises beyond the calibrated set at the higher of the two. That price assumes a definition's tokens follow its text's length. Where a provider charges one definition far more or less than its length suggests, hiding it is credited its length's share, so the ledger can refuse a request that fits or send one that doesn't. Where a model's template adds fixed text for any tool list, a call that advertises part of the calibrated set can report slightly more than its price: on the 2026-11-12 run with `qwen3.5:4b-q4_K_M`, the difference was about 2% of the first prompt. A ledger whose calls always advertise part of the calibrated set keeps the scale calibration measured, because the gauge rescales only from a first call that advertises every calibrated definition or none.
2625
2549
  - **A shown skill is priced over its charge.** The plan prices the definitions a shown skill adds at the higher of the gauge's scale and the calibrated set's overhead per estimate unit, and that overhead holds the fixed text a model's template adds for any tool list, so the plan reserves more than such a call uses: on the 2026-11-12 run with `qwen3.5:4b-q4_K_M` over a consumer application's catalog, the first call of a request on a thread that showed a loaded skill reported 0.603 to 0.775 of the price the plan gave it.
2626
2550
  - **The set estimate rounds the set, not each definition.** The plan estimates a definition set from the set's whole text, so a provider that charges each definition's own rounded estimate can charge a token or two over the price: in a scripted check on 2026-11-12, 1 of 741 first requests on such a provider went 1 to 2 tokens over `capacity` less `predict`. Keep a context margin of a few tokens on such a provider.
2627
- - **A snapshot carries no gauge observations.** The `gauge` member of a snapshot holds the price and its digest alone. A hydrated ledger has observed no reply and no earlier request, so its window admission starts with the longest stored reply as its reserve forecast. Runtime recall uses the current request's measurements; lost marginal-rate history can still change the fit, so live and hydrated calls can list different numbers of items. The window's rungs retain their reserve rule. A hydrated ledger sends what the uninterrupted one would when the live and hydrated reserves admit the same rung. A rung that lies between the two reserves can differ, which moves the prefix and never the record coverage.
2551
+ - **A snapshot carries no gauge observations.** The `gauge` member of a snapshot holds the price, its digest, and its model alone. A hydrated ledger has observed no reply and no earlier request, so its window admission starts with the longest stored reply as its reserve forecast. Runtime recall uses the current request's measurements; lost marginal-rate history can still change the fit, so live and hydrated calls can list different numbers of items. The window's rungs retain their reserve rule. A hydrated ledger sends what the uninterrupted one would when the live and hydrated reserves admit the same rung. A rung that lies between the two reserves can differ, which moves the prefix and never the record coverage.
2628
2552
  - **A short head measures the scale coarsely.** The scale is the reported prompt of the head, with the workspace text when one renders, over its estimate, so a head of a few words measures it to within the provider's rounding of a few tokens until the first served request rescales it. A host that needs it tighter supplies the `gauge` option.
2629
- - **The scale holds for the text it sampled.** The estimate reads length alone, so text of identifiers and amounts costs more a unit than prose: on the 2026-11-12 run with `qwen3.5:4b-q4_K_M` on Ollama 0.40.16, a policy record cost 2.43 tokens an estimate unit against the head's 0.84. A workspace shown after calibration, a `switch` included, and lookup results in record lines are priced at the scale the gauge holds, and a first call that carried that record at the head's rate reported 1.346 of its price. A first call stays inside the window while the uncounted tokens stay under the share of the limit the plan leaves free, 0.3 by default before the drift margin. Call `calibrate` after you show a workspace of another kind, and size a workspace of records by what `calibrate` measures with it shown. A thread calibrated with a dense workspace prices its conversation at the sample's rate, over its charge. A ledger whose calls advertise part of the calibrated set never rescales, as **A partial set is priced by its text's length.** states.
2553
+ - **The scale holds for the text it sampled.** The estimate reads length alone, so text of identifiers and amounts costs more a unit than prose: on the 2026-11-12 run with `qwen3.5:4b-q4_K_M` on Ollama 0.40.16, a policy record cost 2.43 tokens an estimate unit against the head's 0.84. A workspace shown after calibration, a `switch` included, and lookup results in record lines are priced at the scale the gauge holds, and a first call that carried that record at the head's rate reported 1.346 of its price. A first call stays inside the window while the uncounted tokens stay under what the plan leaves free: the share of the limit the `prompt` share leaves, none at the default of 1, and the `LEDGER_SCALE_DRIFT` margin. Call `calibrate` after you show a workspace of another kind, and size a workspace of records by what `calibrate` measures with it shown. A thread calibrated with a dense workspace prices its conversation at the sample's rate, over its charge. A ledger whose calls advertise part of the calibrated set never rescales, as **A partial set is priced by its text's length.** states.
2630
2554
  - **The calibration refusal reads the reported prompt.** The ledger compares the prompt the provider reports for each calibration call with `capacity` and admits a prompt equal to it, so `capacity` must be at most the window the provider serves: a provider that cuts an oversized prompt to its window reports a count the comparison can't see past.
2631
- - **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.
2555
+ - **A held question stays held until what it reads changes.** A question the judge refused is a refused judgment of the conversation, so a ledger hydrated from the snapshot under the same judge identity asks it no more. Only a change to its wording, its desk topic, its message, or the judge's `model`, or a removal of the judgment or its message, asks it again. One key holds one judgment, so a judge that alternates between models A, B, and A asks it again on its return to A.
2632
2556
  - **A snapshot carries the window.** The `window` member of a `LedgerSnapshot` value is optional and present only while the window holds an exchange, so the snapshot of an empty window reads as one with no such member. A 0.0.36 snapshot holds none, reads as it did, and derives the newest pair plain. The `snapshot` method omits a window its conversation can't support, as after a host removes a held message, so a removal doesn't leave a snapshot that hydrating refuses. The `isLedgerSnapshot` guard reads a stored window's exact shape alone, so it refuses a malformed window or one with no `digest` member, and construction refuses that snapshot with `LedgerError` code `'SNAPSHOT'`. It reads no reference or sentence range, so a well-shaped window that names a removed message or sentence passes the guard, and hydrating discards it, because its digest disagrees or can't be computed.
2633
2557
  - **A stored window carries a digest.** The `window` member of a snapshot holds a required `digest` member, a checksum the `digestLedgerWindow` helper computes over the canonical form of its held messages, each request, reply, and record line's source, every lookup result and every message holding a call, because an owner heading can print a lookup no line holds, its stored copies, and its sentence receipts. An edit to any of those, by a host migrating or redacting, makes the digest disagree: hydrating discards the whole window and the ledger derives the newest pair from the edited conversation, so old held text doesn't reach a provider. A digest that can't be computed discards the window the same way. The digest detects an edit, can collide, and makes no security claim. The canonical form sorts keys, so a store that reorders them doesn't make the digest disagree. A held message the canonical form can't render, such as one with an `undefined` tool argument, makes the `snapshot` method omit the window. A held lookup's call arguments count too, through the assistant message that made the call.
2634
2558
  - **A follow-up can read the reply again.** A model server that keeps a prompt cache reuses a prompt that extends the last. On a model whose generation prefix differs from how it renders a reply in history, the server reads the reply itself again, so a follow-up costs the reply plus the text the last prompt didn't hold: small with short replies, and larger with long ones. After a request that called a tool, the prompt shares its prefix only through that request's copy, because tool calls and results stay out of the window, so that reply is read again on any model. Anything ahead of the window moves the prefix too: a system or instruction edit, a memo or workspace change in the context message, a seed stub whose `shown` or `hidden` state flips, and a seed exchange whose cut moves when the gauge rescales. So do an emptied window, a fall to a lower rung, a workspace image, which attaches to the last user message, and a reply whose thinking the `replay` policy leaves out.
@@ -2643,8 +2567,7 @@ The following list holds the documented limits: the ledger's first, then those o
2643
2567
  - **A replaced seed lookup keeps its stub.** When a later finding of the same lookup with different text replaces a seed lookup, the seed stub reads `result not shown` while a later copy can print the replacing result, unless the window and the copy fully receive a finding with the same canonical lookup identity and text as the seed finding. That full receipt makes a duplicate stub read `shown`, even when its own source is retired.
2644
2568
  - **A change can sit beside its not-shown note.** When an amender was superseded with no live successor, or when a later message amends the amender and files no edge of its own to the earliest message, the earliest message's note reads “A later change is not shown.” beside a change the copy prints, because no other edge is inferred. The note can also read this way when the change sits raw in the seed tail, because the record's amendment rendering doesn't read that tail.
2645
2569
  - **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.
2646
- - **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. In the reading of 2026-11-06, of 12 corrections two blind readers agreed on, across ABCD and Taskmaster-1, 8 carry no id or number and 4 carry only the new value, and none repeats the old one. Read those messages alone, because their dialogs weren't at hand, so only a shared registry entity could admit their pairs.
2647
- - **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction recorded on 2026-11-03 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.
2570
+ - **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction recorded on 2026-11-03 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 caller's abort signal ends them.
2648
2571
  - **A loaded skill stays shown for its thread.** A wrong load stays shown too and can draw the next request's call; for the reading on a ledger and the host's levers, see [Composing a records desk for a small local GPU](#composing-a-records-desk-for-a-small-local-gpu).
2649
2572
  - **The model learns which memo names it may write from a refusal.** The memos index lists only the memos that exist, so a name the ceiling's `memos` list holds and no memo holds reaches the model only through a `remember` refusal, which lists the writable names, and an approver can be asked about a `remember` its handler then refuses, because the authority runs before the handler reads the ceiling. State the names a model may write in your instruction text.
2650
2573
  - **Visible text has a floor.** A `remember` name or description that holds U+2800, a lone surrogate, a private-use or unassigned code point, or a combining mark alone passes as visible text and can read blank in the memos index, which sits in the context message and never in `system`.
@@ -2677,7 +2600,7 @@ budget.consume(result.usage ?? { prompt: 0, completion: 0, total: 0 })
2677
2600
 
2678
2601
  ### Writing a provider for a new wire
2679
2602
 
2680
- Reach a backend that this package doesn't ship a provider for by extending `AgentProvider` rather than implementing `ProviderInterface` from nothing. The base already holds the deadline, the transport, the `headers` hook, the request, the bounded error read, the decode loop, reasoning separation, and result assembly (the provider-engine clause), so a subclass is the wire and nothing else: `name` identifies the backend, `frame` returns fresh framing state for the call, `encode` projects a `ProviderRequest` onto the vendor's request shape, `read` turns one framed record into a `ProviderIncrement`, and `finish` hands back whatever the parser still held at end of input. Pass the vendor's endpoint through `super`, and set `split` and `strict` to match what the wire actually delivers. The fence writes `AgentProvider<string>` because this wire frames nothing: each decoded chunk is one raw-text record, so `TRecord` is `string`. A wire that frames JSON objects extends bare `AgentProvider` and takes the default record type, and a wire with its own record type names that type instead.
2603
+ Reach a backend that this package doesn't ship a provider for by extending `AgentProvider` rather than implementing `ProviderInterface` from nothing. The base already holds the deadline, the transport, the `headers` hook, the request, the bounded error read, the decode loop, reasoning separation, and result assembly (the provider-engine clause), so a subclass is the wire and nothing else: `name` identifies the backend, `frame` returns fresh framing state for the call, `encode` projects a `ProviderRequest` onto the vendor's request shape, `read` turns one framed record into a `ProviderIncrement`, and `finish` hands back whatever the parser still held at end of input. Pass the vendor's endpoint and the `model` the provider serves through `super`, and set `split` and `strict` to match what the wire actually delivers. The base exposes that `model`, so `encode` names the model on the wire from the same member that `createAgent` and `createLedger` check and that a ledger's gauge is keyed to. The fence writes `AgentProvider<string>` because this wire frames nothing: each decoded chunk is one raw-text record, so `TRecord` is `string`. A wire that frames JSON objects extends bare `AgentProvider` and takes the default record type, and a wire with its own record type names that type instead.
2681
2604
 
2682
2605
  ```ts
2683
2606
  import type {
@@ -2709,7 +2632,7 @@ class TextProvider extends AgentProvider<string> {
2709
2632
  return new TextFrame()
2710
2633
  }
2711
2634
  encode(request: ProviderRequest): object {
2712
- return { messages: request.messages }
2635
+ return { model: this.model, messages: request.messages }
2713
2636
  }
2714
2637
  read(record: string): ProviderIncrement {
2715
2638
  return { content: record, thinking: '', tools: [] }
@@ -2822,15 +2745,15 @@ That judge answers through `ask` like any other. With `batch: false` the engine
2822
2745
 
2823
2746
  Every configuration sends one request layout, position by position. The following table lists what fills each position under each strategy:
2824
2747
 
2825
- | Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
2826
- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2827
- | `system` | the `system` option, then `## Instructions`, then `## Skills`, then `## Loaded skills`; absent when all are empty | the same | the `system` option, then `## Instructions` and `## Skills` from the `agent` option |
2828
- | `user` context message | `## Memos`, then `## Workspaces` while `switch` is advertised, then `## Workspace`; absent when all are empty; a minted id, never stored and never folded | the same | the same, from the `agent` option |
2829
- | Tail | `view()` | one `assistant` recap per section, opening with `CONVERSATION_RECAP_PREFIX`, then the live tail | the seed tail, with each lookup result as its stub, then each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall |
2830
- | Request | the last stored `user` message; images attach here | the same | a built copy of the `user` turn: the `## Records` and `## Rules` lines the window doesn't hold and `## Request` before the prompt, or the prompt alone when it has no line to add; images attach here |
2831
- | Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
2748
+ | Position | Plain agent | Ledger, first pass of a request |
2749
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2750
+ | `system` | the `system` option, then `## Instructions`, then `## Skills`, then `## Loaded skills`; absent when all are empty | the `system` option, then `## Instructions` and `## Skills` from the `agent` option |
2751
+ | `user` context message | `## Memos`, then `## Workspaces` while `switch` is advertised, then `## Workspace`; absent when all are empty; a minted id, never stored | the same, from the `agent` option |
2752
+ | Tail | `messages()` | the seed tail, with each lookup result as its stub, then each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall |
2753
+ | Request | the last stored `user` message; images attach here | a built copy of the `user` turn: the `## Records` and `## Rules` lines the window doesn't hold and `## Request` before the prompt, or the prompt alone when it has no line to add; images attach here |
2754
+ | Run turns | each `assistant` message with its calls, then one `tool` message per call | the same |
2832
2755
 
2833
- A host writes the `system` message through the `system` option, `instructions.add`, the skill index, and the bodies of the skills it registers, and nothing else reaches it: a `load` call names a registered skill, and the body comes from the registry. A stored message plays `user`, `assistant`, or `tool`: `add`, a snapshot, a job seed, and a selection each refuse a `system` role with `ConversationError` `'ROLE'`. `Conversation.reference()` returns text for a `user` message or a workspace file, and it never belongs in the `system` message. Because an instruction never folds, a rule in an instruction survives every round of compaction. A loaded body never folds either, because a run shows it from the conversation's record, and a host scope with an explicit `skills` allow-list filters a loaded body as it filters the index. The model shows a skill's body only through `load`, enabled through the `builtins` option, as [Enabling the built-in tools](#enabling-the-built-in-tools) states.
2756
+ A host writes the `system` message through the `system` option, `instructions.add`, the skill index, and the bodies of the skills it registers, and nothing else reaches it: a `load` call names a registered skill, and the body comes from the registry. A stored message plays `user`, `assistant`, or `tool`: `add`, a snapshot, a job seed, and a selection each refuse a `system` role with `ConversationError` `'ROLE'`. `Conversation.reference()` returns text for a `user` message or a workspace file, and it never belongs in the `system` message. An instruction renders in every head a run builds. A run shows a loaded body from the conversation's record, and a host scope with an explicit `skills` allow-list filters a loaded body as it filters the index. The model shows a skill's body only through `load`, enabled through the `builtins` option, as [Enabling the built-in tools](#enabling-the-built-in-tools) states.
2834
2757
 
2835
2758
  ### Serving one agent per principal
2836
2759
 
@@ -2923,6 +2846,7 @@ const messages = [{ id: '1', role: 'user', content: 'Say hello.' }] as const
2923
2846
 
2924
2847
  const browser: ProviderInterface = createRelayProvider({
2925
2848
  url: 'https://app.example/relay',
2849
+ model: 'qwen3:4b', // the model the relay's upstream provider serves
2926
2850
  headers: () => ({ authorization: `Bearer ${bearer}` }),
2927
2851
  })
2928
2852
  const result = await browser.generate(messages, abort.signal) // a ProviderResult like a local provider's
@@ -2961,7 +2885,7 @@ const tools = createToolManager()
2961
2885
  tools.add(
2962
2886
  PAGE_TOOLS.map((definition) => createTool({ ...definition, execute: () => readSelection() })),
2963
2887
  )
2964
- const browser = createRelayProvider({ url: 'https://app.example/relay' })
2888
+ const browser = createRelayProvider({ url: 'https://app.example/relay', model: 'qwen3:4b' })
2965
2889
  const agent = createAgent(browser, {
2966
2890
  tools,
2967
2891
  authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
@@ -3340,7 +3264,7 @@ const agent = createAgent(provider, {
3340
3264
  agent.emitter.on('abort', (reason) => log('cancelled', reason))
3341
3265
  ```
3342
3266
 
3343
- The `request` event fires once a turn, after the loop admits the request and before the provider receives it, so after a compaction fold it carries the rebuilt request. Its listener receives the turn index, the request the provider receives, and the conversation the run is bound to, which tells overlapping runs apart. The loop freezes the request object and its `messages` and `tools` arrays, so a listener can't add, remove, replace, or reorder a message or a definition, or replace `options`. The freeze is one level deep: each message, each definition, and `options` are objects the turn shares with the conversation and the agent. A `request` listener is host code: it reads the request and never writes to it. A turn cancelled before its request is composed emits none, and a request whose turn advertises no tool carries no `tools` member. A run aborted while a turn's `request` listeners run sends nothing for that turn: the provider receives no call for it, and the turn ends as a cancel, which is how a ledger stops a request it prices over its capacity.
3267
+ The `request` event fires once a turn, before the provider receives the request. Its listener receives the turn index, the request the provider receives, and the conversation the run is bound to, which tells overlapping runs apart. The loop freezes the request object and its `messages` and `tools` arrays, so a listener can't add, remove, replace, or reorder a message or a definition, or replace `options`. The freeze is one level deep: each message, each definition, and `options` are objects the turn shares with the conversation and the agent. A `request` listener is host code: it reads the request and never writes to it. A turn cancelled before its request is composed emits none, and a request whose turn advertises no tool carries no `tools` member. A run aborted while a turn's `request` listeners run sends nothing for that turn: the provider receives no call for it, and the turn ends as a cancel, which is how a ledger stops a request it prices over its capacity.
3344
3268
 
3345
3269
  The following listener reads the request each turn of one thread dispatches:
3346
3270
 
@@ -3367,25 +3291,23 @@ Object.isFrozen(sent[0]?.messages) // true
3367
3291
 
3368
3292
  ### Pulling context from another conversation (with provenance)
3369
3293
 
3370
- One agent serves many conversations: each run binds the conversation its `AgentRunOptions.conversation` names, or the one active at its call, which `conversations.switch(id)` sets at any moment without moving a live run; each thread keeps its own history. When the active conversation A needs something decided in another conversation B, don't merge B's turns into A's live tail — that pollutes A's thread and (for a small model) blurs which conversation said what. Instead pull a provenance-labeled reference of B into A's active workspace (the fenced reference channel `build()` folds into the user context message), so the model reads it as clearly-foreign material and attributes it to B.
3294
+ One agent serves many conversations: each run binds the conversation its `AgentRunOptions.conversation` names, or the one active at its call, which `conversations.switch(id)` sets at any moment without moving a live run; each thread keeps its own history. When the active conversation A needs something decided in another conversation B, don't merge B's turns into A's messages — that pollutes A's thread and (for a small model) blurs which conversation said what. Instead pull a provenance-labeled reference of B into A's active workspace (the fenced reference channel `build()` folds into the user context message), so the model reads it as clearly-foreign material and attributes it to B.
3371
3295
 
3372
- The flow is **search / rehydrate → reference → write-to-workspace** — and cherry-pick, never dump:
3296
+ The flow is **search → reference → write-to-workspace** — and cherry-pick, never dump:
3373
3297
 
3374
3298
  ```ts
3375
3299
  import type { ProviderInterface } from '@orkestrel/agent'
3376
3300
  import { createAgent, createConversationManager } from '@orkestrel/agent'
3377
3301
 
3378
3302
  declare const provider: ProviderInterface
3379
- const conversations = createConversationManager({
3380
- summarize: /* a ConversationSummaryHandler */ undefined,
3381
- })
3303
+ const conversations = createConversationManager()
3382
3304
  const a = conversations.add({ id: 'auth' }) // the ACTIVE thread (the first add auto-activates it)
3383
3305
  const b = conversations.add({ id: 'planning' }) // the OTHER thread to pull from
3384
3306
 
3385
3307
  const agent = createAgent(provider, { conversations }) // its active conversation (a) is the message source
3386
3308
 
3387
- // 1. search / rehydrate → SELECT the few right turns (never B's whole history)
3388
- const picked = b.search('database') // or b.rehydrate(sectionId) for a compacted slice
3309
+ // 1. search → SELECT the few right turns (never B's whole history)
3310
+ const picked = b.search('database')
3389
3311
  // 2. reference → FRAME them as a self-labeled provenance block (a pure string, no model call)
3390
3312
  const block = b.reference({ label: 'planning', messages: picked })
3391
3313
  // 3. write-to-workspace → into the ACTIVE conversation's context active workspace, keyed by the source id
@@ -3394,9 +3316,7 @@ agent.context.workspaces.add().write(`conversation:${b.id}.md`, block)
3394
3316
  // The model can then use B's decision AND attribute it: "Postgres, decided in the planning conversation."
3395
3317
  ```
3396
3318
 
3397
- Why this shape: `reference()` leads with `[Reference — conversation "<label>" — NOT part of this conversation]`, so the model treats the excerpts as a quoted foreign source (it answers "decided in the planning conversation", not "we decided here"). Keep the excerpts cherry-picked — this content enters another context window a small model must read, and a full dump re-bloats it. `reference()` is event-free and never calls a model; provenance lives in the `label` (default the conversation's `id`).
3398
-
3399
- **Within a conversation, the same provenance instinct applies to recaps.** `view()` folds each compacted section into a synthetic `assistant` recap — and prefixes it with `CONVERSATION_RECAP_PREFIX` (`[Summary of earlier messages] …`) so a small model reads it as a condensed recap of earlier turns rather than a literal turn to echo or treat as the live answer. The label is deliberately lean (a fixed handful of tokens — no per-section blow-up) and is a `view()`-only presentation concern (a `sections` cap merge re-reads the unframed summaries).
3319
+ Why this shape: `reference()` leads with `[Reference — conversation "<label>" — NOT part of this conversation]`, so the model treats the excerpts as a quoted foreign source (it answers "decided in the planning conversation", not "we decided here"). Keep the excerpts cherry-picked — this content enters another context window a small model must read, and a full dump re-bloats it. `reference()` is event-free and never calls a model; provenance lives in the `label` (default the conversation's `id`). Both markers name the label between double quotes, so `reference()` refuses a label holding a double quote or a line break with `ConversationError` `'LABEL'`, and it indents every continuation line of an excerpt by two spaces, so no excerpt text starts a line where it could read as a marker.
3400
3320
 
3401
3321
  ### Persisting a conversation through either store
3402
3322
 
@@ -3533,7 +3453,7 @@ isAgentError(refused) && refused.code // 'REGISTRY'
3533
3453
 
3534
3454
  ### Giving the model documents to read
3535
3455
 
3536
- A workspace reaches the model through `context.workspaces`, and this is the only channel documents have. Each build renders one workspace by carrier, filtered by the scope: the one the run shows, else the active one. A run builds its head at entry, at each compaction rebuild, and at each turn whose view changed, as [Scoping a turn](#scoping-a-turn) states, so an edit to a file reaches the model at the next build and never needs a re-mount. Register one (the first `add` auto-activates it) and its text files fold into the `## Workspace` section of the user context message as fenced reference blocks, while its image files' base64 rides the last user message.
3456
+ A workspace reaches the model through `context.workspaces`, and this is the only channel documents have. Each build renders one workspace by carrier, filtered by the scope: the one the run shows, else the active one. A run builds its head at entry and at each turn whose view changed, as [Scoping a turn](#scoping-a-turn) states, so an edit to a file reaches the model at the next build and never needs a re-mount. Register one (the first `add` auto-activates it) and its text files fold into the `## Workspace` section of the user context message as fenced reference blocks, while its image files' base64 rides the last user message.
3537
3457
 
3538
3458
  ```ts
3539
3459
  import type { ProviderInterface } from '@orkestrel/agent'
@@ -3582,7 +3502,7 @@ A switch between runs changes the files the next run's prompt carries, and `scop
3582
3502
 
3583
3503
  A mode is a scope an application keeps ready: its allow-lists and an optional `select` handler. Load the data from a plain file, and attach each handler in code through a guarded lookup, because a file carries no function. Switch modes with `context.apply`; each change applies at the sites [Scoping a turn](#scoping-a-turn) names.
3584
3504
 
3585
- `mode.narrow({ tools: [] })` is the answer mode that keeps the mode's handler, because `narrow` keeps the parent's `name` and `select`. `apply(undefined)` and a plain answer scope with no handler fall back to the agent default. A mode that must run with no selection under a default carries a pass-through handler that returns `view()`; the package exports no such handler.
3505
+ `mode.narrow({ tools: [] })` is the answer mode that keeps the mode's handler, because `narrow` keeps the parent's `name` and `select`. `apply(undefined)` and a plain answer scope with no handler fall back to the agent default. A mode that must run with no selection under a default carries a pass-through handler that returns `messages()`; the package exports no such handler.
3586
3506
 
3587
3507
  The following modes load from data, attach their handlers in code, and switch between runs:
3588
3508
 
@@ -3603,8 +3523,8 @@ const MODES = [
3603
3523
  ]
3604
3524
  const POLICIES: Readonly<Record<string, SelectionHandler>> = {
3605
3525
  recent,
3606
- // No selection under the judging default: a pass-through handler returns view().
3607
- none: async (conversation) => ({ messages: conversation.view(), judgments: [] }),
3526
+ // No selection under the judging default: a pass-through handler returns messages().
3527
+ none: async (conversation) => ({ messages: conversation.messages(), judgments: [] }),
3608
3528
  }
3609
3529
  const modes = new Map(
3610
3530
  MODES.map(({ policy, ...data }): [string, ScopeInterface] => {
@@ -3690,15 +3610,12 @@ const result = await agent.generate() // { content: 'Refunds need a manager.', p
3690
3610
 
3691
3611
  ### Serving requests through a ledger
3692
3612
 
3693
- The ledger is the records strategy: it keeps every message and serves each request through records, where automatic compaction folds older turns into recaps. The following table compares the strategies. It recommends no form and changes no default, and the **compaction floor** clause under [Contract](#contract) holds the one reading behind its compaction rows.
3613
+ The ledger is the records strategy: it keeps every message and serves each request through records. The following table compares it with a plain agent. It recommends no form and changes no default.
3694
3614
 
3695
- | Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
3696
- | -------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
3697
- | Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
3698
- | Automatic compaction | `AgentOptions.window` and a summarizable conversation | one recap per section, then the live tail | each section's `messages`, read through `search` and `rehydrate` | every recap stays, so a request can reach the window with nothing left to fold |
3699
- | Compaction with a `sections` cap | the `sections` option, per conversation, as a manager default, or per `compact()` call | at most the cap's recaps after a merge, then the live tail | the same | a merge needs a fold with an eligible slice, and it can't combine with `cumulative` |
3700
- | Compaction with `cumulative` | `ConversationOptions.cumulative` or `ConversationInput.cumulative` | one recap, then the live tail | the same | a fold needs an eligible slice, and its summarizer reads recaps and not the originals behind them |
3701
- | Ledger | `createLedger(provider, options)` | the built head, the seed tail, each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall, and a copy of the request turn with the record lines the window doesn't hold | the conversation, read through the `recall` tool | a judge and fitted cutoffs are required, and a request priced over `capacity` less `predict` isn't sent |
3615
+ | Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
3616
+ | ----------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
3617
+ | Plain agent | `createAgent(provider)` | every message the conversation holds | the conversation | nothing trims a request, so the provider's own limit decides |
3618
+ | Ledger | `createLedger(provider, options)` | the built head, the seed tail, each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall, and a copy of the request turn with the record lines the window doesn't hold | the conversation, read through the `recall` tool | a judge and fitted cutoffs are required, and a request priced over `capacity` less `predict` isn't sent |
3702
3619
 
3703
3620
  Build a ledger from a provider, a judge, the lookups, and the measured questions, add the seed history to its conversation, and send each request through the `respond` method. Read the last message of each `select` event's selection, the copy of the request turn, to see the record lines the ledger added for that request; the exchanges before it in the selection hold the lines earlier copies showed. The following ledger serves two requests; a scripted provider stands in for the model and a scripted judge for Mica:
3704
3621
 
@@ -3727,6 +3644,7 @@ const replies = script.values()
3727
3644
  const provider: ProviderInterface = {
3728
3645
  id: 'scripted',
3729
3646
  name: 'scripted',
3647
+ model: 'scripted',
3730
3648
  generate: async () => replies.next().value ?? { content: '' },
3731
3649
  async *stream() {
3732
3650
  const reply = replies.next().value ?? { content: '' }
@@ -3784,6 +3702,7 @@ const ledger = createLedger(provider, {
3784
3702
  questions: LEDGER_QUESTIONS,
3785
3703
  thresholds,
3786
3704
  capacity: 32_768,
3705
+ predict: 8_192,
3787
3706
  lookups: [lookup],
3788
3707
  })
3789
3708
  const copies: Array<string | undefined> = []
@@ -3852,7 +3771,7 @@ copies[1]
3852
3771
  // "## Records\n### Mara Quill (C-12)\n- Contact C-12: Mara Quill.\n- Phone 555-0102.\n\n## Request\nWhat is Mara Quill's phone?" — the write retired the read of 555-0101
3853
3772
  ```
3854
3773
 
3855
- To carry a ledger across a restart, store what its `snapshot` method returns and pass it back as the `snapshot` option of a later `createLedger` call. The snapshot is plain JSON: the conversation with its judgments, the ids of the requests, notes, and failed tool results the ledger marked, the gauge with the digest of the tool definitions it priced, and the window while it holds an exchange. Narrow a parsed snapshot with the `isLedgerSnapshot` guard first, because construction refuses a snapshot the guard refuses with `LedgerError` code `'SNAPSHOT'`. The hydrated ledger makes no calibration call when the options carry a gauge or the snapshot carries one priced on the same tool definitions; with any other definitions, it calibrates before its first pass. It asks its judge no question the stored judgments answer. The following example continues the preceding ledger in a second ledger, and the second ledger sends the prompt the first would send for the same request. The window holds every line this request selects, so its copy is the request itself:
3774
+ To carry a ledger across a restart, store what its `snapshot` method returns and pass it back as the `snapshot` option of a later `createLedger` call. The snapshot is plain JSON: the conversation with its judgments, the ids of the requests, notes, and failed tool results the ledger marked, the gauge with the digest of the tool definitions it priced and the provider `model` it was measured on, and the window while it holds an exchange. Narrow a parsed snapshot with the `isLedgerSnapshot` guard first, because construction refuses a snapshot the guard refuses with `LedgerError` code `'SNAPSHOT'`. The hydrated ledger makes no calibration call when the options carry a gauge or the snapshot carries one priced on the same tool definitions under a provider of the same `model`; with any other definitions or model, it calibrates before its first pass. It asks its judge no question the stored judgments answer. The following example continues the preceding ledger in a second ledger, and the second ledger sends the prompt the first would send for the same request. The window holds every line this request selects, so its copy is the request itself:
3856
3775
 
3857
3776
  ```ts
3858
3777
  import type { LedgerInterface, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
@@ -4082,7 +4001,7 @@ const ledger = createLedger(provider, {
4082
4001
  await ledger.respond('Does the Brightwater Studio refund need a manager?')
4083
4002
  ```
4084
4003
 
4085
- The `model` member holds both judges' identities and the cutoff, so changing any of them asks each question again. This class rejects when its first judge rejects. For a fuller worked example that refers a first judge's fault to the second and checks each distribution, read `studies/memory/StudyMemoryJudge.ts` in this repository and adapt it: it holds one study's policy, and no published entry exports it. The executed transcription runs the preceding class with a scripted provider and recording judges; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
4004
+ The `model` member holds both judges' identities and the cutoff, so changing any of them asks each question again. This class rejects when its first judge rejects. For a fuller worked example that refers a first judge's fault to the second and checks each distribution, read `studies/memory/judges/StudyMemoryJudge.ts` in this repository and adapt it: it holds one study's policy, and no published entry exports it. The executed transcription runs the preceding class with a scripted provider and recording judges; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
4086
4005
 
4087
4006
  The application decides which models to run, which thresholds to keep, and whether to run two judges at all. The package ships the mechanism and none of that policy.
4088
4007
 
@@ -4185,9 +4104,9 @@ A skill the model loads stays shown for the rest of its thread, on a ledger as o
4185
4104
 
4186
4105
  ### Upgrade data written before 0.0.35
4187
4106
 
4188
- 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` with `AgentError` `'REGISTRY'`, whose `context.faults` names the message's `role`, and the job's `system` member carries that text.
4107
+ 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 and the `sections` a compacting conversation's snapshot holds 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` with `AgentError` `'REGISTRY'`, whose `context.faults` names the message's `role`, and the job's `system` member carries that text.
4189
4108
 
4190
- 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:
4109
+ 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`, because hydrating checks every message's role:
4191
4110
 
4192
4111
  ```ts
4193
4112
  import type { ConversationSnapshot, ConversationStoreInterface } from '@orkestrel/agent'
@@ -4199,17 +4118,13 @@ const stored: unknown = await store.get('thread-1')
4199
4118
  if (!isConversationSnapshot(stored)) throw new Error('Not a conversation snapshot')
4200
4119
  const cleaned: ConversationSnapshot = {
4201
4120
  ...stored,
4202
- sections: stored.sections.map((section) => ({
4203
- ...section,
4204
- messages: section.messages.filter(({ role }) => role !== 'system'),
4205
- })),
4206
4121
  messages: stored.messages.filter(({ role }) => role !== 'system'),
4207
4122
  }
4208
4123
  await store.set(cleaned)
4209
4124
  const conversation = createConversation({ snapshot: cleaned })
4210
4125
  ```
4211
4126
 
4212
- A judgment whose `sources` name a removed row hydrates unchanged, and a section the filter empties hydrates with no messages. The `isLedgerSnapshot` guard refuses a mark that names a removed row, so drop that id from a ledger snapshot's `requests`, `notes`, and `failures` lists as well.
4127
+ A judgment whose `sources` name a removed row hydrates unchanged. The `isLedgerSnapshot` guard refuses a mark that names a removed row, so drop that id from a ledger snapshot's `requests`, `notes`, and `failures` lists as well.
4213
4128
 
4214
4129
  A host that edits a stored snapshot's judgment to migrate or redact it copies the record first, because a write to the stored record throws `TypeError` in strict-mode code. A stored 0.0.34 conversation row matches in any key order after upgrade, and a record dead under the text compare becomes live, with no migration.
4215
4130
 
@@ -4272,17 +4187,18 @@ try {
4272
4187
  }
4273
4188
 
4274
4189
  // ConversationManager — `save` persists a registered conversation, `remove` / `clear` drop it.
4275
- const conversations = createConversationManager({ summarize: undefined })
4190
+ const conversations = createConversationManager()
4276
4191
  const thread = conversations.add({ id: 'thread-1' })
4277
4192
  await conversations.save(thread.id)
4278
4193
  conversations.remove(thread.id)
4279
4194
  conversations.clear()
4280
4195
 
4281
- // Conversation — `remove` one live message, `clear` the live tail, `snapshot` for durability.
4196
+ // Conversation — `remove` one message with its call group, `clear` every message, `snapshot` for durability.
4282
4197
  const message = thread.add({ role: 'user', content: 'hi' })
4283
4198
  thread.remove(message.id)
4284
4199
  thread.clear()
4285
- thread.snapshot() // { id, sections, messages, judgments? } — the durable payload
4200
+ thread.snapshot() // { id, messages, judgments? } — the durable payload
4201
+ thread.destroy() // drops every listener, so later changes reach no observer
4286
4202
 
4287
4203
  const agent = createAgent(provider)
4288
4204
  void agent
@@ -4298,7 +4214,7 @@ The following practices apply when you build on this package:
4298
4214
  - **Register tools in a `ToolManager`** — add your `Tool` instances through `add`, hand `definitions()` to the provider, and dispatch the `ToolCall` values the model returns through `execute`; read the outcome by narrowing on `success` rather than catching, because a handler's throw already arrives as the failure arm. When in-process code wants a typed error instead, call `tools.tool(name)` and call the `execute` method of that tool directly.
4299
4215
  - **Narrow tool `args`** — a `ToolCall.arguments` is model-supplied `unknown`; narrow it inside `execute` with a guard.
4300
4216
  - **Collect turns in an `AgentContext`** — append turns through `context.messages.add` (the `id` is minted for you), then call `build()` each turn to produce the provider input; tools travel as the provider's `tools` argument, so never fold a tool's schema into a message yourself.
4301
- - **Pull cross-conversation context with provenance, never by merging turns** — to use something from another conversation B in the active one, follow `B.search` / `B.rehydrate` (cherry-pick the few right turns) → `B.reference({ label, messages })` (frame it) → `context.workspaces.active?.write(...)` (write it into the active workspace). The provenance label keeps a small model from reading B's content (or a recap) as part of the live thread; cherry-pick — don't dump B's whole history into another context window.
4217
+ - **Pull cross-conversation context with provenance, never by merging turns** — to use something from another conversation B in the active one, follow `B.search` (cherry-pick the few right turns) → `B.reference({ label, messages })` (frame it) → `context.workspaces.active?.write(...)` (write it into the active workspace). The provenance label keeps a small model from reading B's content as part of the live thread; cherry-pick — don't dump B's whole history into another context window.
4302
4218
  - **Run the loop with `createAgent`** — don't hand-roll the context → provider → tools cycle; `createAgent` does it, bounded by `AbortSignal.any([signal, timeout, budget])`, paced by `scheduler`, capped at `limit`. Drain `stream().events` to render `token` / `think` / `usage` / `ask` / `tool` chunks live, or `generate()` for the settled result; either way `result` resolves partial on a cancel (read `result.partial`), rejecting only on a real error.
4303
4219
  - **Run many durable agents with `createAgentQueue`** — describe each agent as a serializable `AgentJobInput` (names for the provider / tools / authority / scheduler, data for the rest), register the live pieces once in a `createAgentRegistry`, and enqueue the jobs. Persist them with a `store` so `restore()` re-runs outstanding work after a crash. Decide the partial policy up front — `partial: false` (default) retries a cancelled job, `true` accepts the partial.
4304
4220
  - **Fan out sub-agents with `createAgentRunner`** — declare a parent job's sub-agents in its `children`; the runner spawns each through `controller.spawn` on the same bounded queue. Don't reach for the controller yourself — express fan-out as data on the job (it stays serializable) and let the runner spawn it.
@@ -4313,7 +4229,7 @@ The following practices apply when you build on this package:
4313
4229
  The following test files back this guide:
4314
4230
 
4315
4231
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the Surface and method parity with `src/core`, the `Summary`, titled example, and pitch equality, and the executed flagship fences with the Contract clauses they back: scope timing, selection, judgments, modes, answer-only runs, recorded thinking and the replay policy, the ledger over a scripted provider and judge with its thinking budget, the classifier and the gauge, the relay over a loopback listener, the page wire to a Node agent over a loopback listener with its approval asks, its refusals, its two principals, and its `409` overlap, the System One judge over a recorded response, the server fence: one session entry per principal, the refused overlap that adds no user turn, and the user turn a rejected run keeps, both server fences tied to their transcriptions byte for byte, and the boundary, limit, and upgrade sentences: the request layout, the refused stored `system` row and its recovery, the selected `system` fault, the page-tool declaration and its `422`, the `consequential` lookup, the frozen judgment copy, the built-ins: a load at the next turn with its held tool, the `workspace` option, a load kept per conversation and through a snapshot, the memo write and the workspace switch, the refusal text, and the relay's acceptance of a page's built-ins, a ledger's built-ins with a skill's held lookup, each request served under its area scope and one thread moved between that scope and the skills index, the memo set two ledgers of one principal share, the over-window paths and the ledger's refusals, the no-slice fold, a second `select` during a paced filing, and the limits of the ledger's agent emitter and of a host's own selection during a pass.
4316
- - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the root helpers `filterAllowList`, `joinThinking`, `stripThinking`, `sanitizeToken`, `sanitizeUsage`, `sumUsage`, `removeEntries`, `collectExchanges`, `hasCalls`, `collectToolGroups`, `findToolCall`, `renderJSON`, `matchesJSON`, and `matchesJudgment`, the `MESSAGE_ROLES` role list, and the `CONVERSATION_ROLES` stored role list with the `ConversationRole` and `MessageInput` role types.
4232
+ - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the root helpers `filterAllowList`, `joinThinking`, `stripThinking`, `sanitizeToken`, `sanitizeUsage`, `sumUsage`, `removeEntries`, `collectExchanges`, `hasCalls`, `collectToolGroups`, `findToolCall`, `renderJSON`, `matchesJSON`, `matchesJudgment`, and `raceSignal`, the `MESSAGE_ROLES` role list, and the `CONVERSATION_ROLES` stored role list with the `ConversationRole` and `MessageInput` role types.
4317
4233
  - [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — `copyJSON` copying a proxied record where a structured clone refuses it and returning `undefined` for a value JSON can't carry, and `freezeJSON` returning a copy whose every nested record and list is frozen while its input stays unchanged, freezing every member of a very wide list, and returning `undefined` wherever `copyJSON` does.
4318
4234
  - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — the root guards `isJudgeEntry`, `isJudgeQuestion`, and `isNonNegativeSafeInteger`, each total over malformed input.
4319
4235
  - [`tests/src/core/contracts.test.ts`](../tests/src/core/contracts.test.ts) — the message contract's round trip and malformed paths, function-valued arguments accepted in the domain and refused on the wire, the `MESSAGE_GUARD_CASES` agreement between `isMessage` and `messageContract`, and seeded wire messages kept in the domain.
@@ -4330,12 +4246,12 @@ The following test files back this guide:
4330
4246
  - [`tests/src/core/providers/contracts.test.ts`](../tests/src/core/providers/contracts.test.ts) — the request, result, and relay-frame contracts' round trips, malformed paths, and non-JSON refusals.
4331
4247
  - [`tests/src/core/providers/shapers.test.ts`](../tests/src/core/providers/shapers.test.ts) — the request, result, and relay wire shapes assignable to their domain types.
4332
4248
  - [`tests/src/core/providers/validators.test.ts`](../tests/src/core/providers/validators.test.ts) — the System One guards `isSystemOneResponse` and `isSystemOneAnswer` over recorded, transliterated, and malformed envelopes.
4333
- - [`tests/src/core/conversations/Conversation.test.ts`](../tests/src/core/conversations/Conversation.test.ts) — the conversation's construction, `view`, `compact` with `keep` and its no-op and missing-summarizer cases, `rehydrate`, `search`, `reference`, `snapshot`, the `sections` cap, hydration, and the stored roles and snapshot checks: a `system` add or batch refused with nothing stored, a snapshot refused for a `system` role, a repeated id, or a malformed shape, the single read of its members, and `'JUDGMENT'` kept for a non-JSON judgment.
4334
- - [`tests/src/core/conversations/ConversationManager.test.ts`](../tests/src/core/conversations/ConversationManager.test.ts) — the registry's accessors, active pointer and `switch`, removal, the inherited `summarize`, `keep`, and `sections` defaults, independence, the durable `open` / `save` seam, a 0.0.29 snapshot read through `open` without its conversation `summary`, and `open` refusing a stored `system` role with the registry and `active` unchanged.
4249
+ - [`tests/src/core/conversations/Conversation.test.ts`](../tests/src/core/conversations/Conversation.test.ts) — the conversation's construction, the owned and frozen stored messages, `remove` of a whole call group, the judgments `remove` and `clear` drop, the `add`, `remove`, and `clear` events and `destroy`, `search`, `reference` with its fenced block and its label refusal, `snapshot`, hydration and its refusal of `sections`, and the stored roles and snapshot checks: a `system` add or batch refused with nothing stored, a snapshot refused for a `system` role, a repeated id, or a malformed shape, the single read of its members, and `'JUDGMENT'` kept for a non-JSON judgment.
4250
+ - [`tests/src/core/conversations/ConversationManager.test.ts`](../tests/src/core/conversations/ConversationManager.test.ts) — the registry's accessors, active pointer and `switch`, removal, independence, the durable `open` / `save` seam, a 0.0.29 snapshot read through `open` without its conversation `summary`, and `open` refusing a stored `system` role with the registry and `active` unchanged.
4335
4251
  - [`tests/src/core/conversations/JudgmentManager.test.ts`](../tests/src/core/conversations/JudgmentManager.test.ts) — the keyed storage of `JudgmentManager` and its `resolve` method, which asks only unmatched questions, attaches one-question usage, records partial answers on abort, restores from a snapshot, and reuses a hydrated judgment whose keys were sorted, and the frozen records it returns.
4336
4252
  - [`tests/src/core/conversations/factories.test.ts`](../tests/src/core/conversations/factories.test.ts) — `createConversation`, `createConversationManager`, `createMemoryConversationStore`, and `createDatabaseConversationStore`, each driving the instance it returns.
4337
- - [`tests/src/core/conversations/helpers.test.ts`](../tests/src/core/conversations/helpers.test.ts) — `buildJudgments`, `buildSummaryMessage`, `buildRecapMessage`, `requireJudgment`, `requireRole`, `requireConversationSnapshot`, `requireSectionsCap`, `requireKeep`, and `raceSignal`.
4338
- - [`tests/src/core/conversations/validators.test.ts`](../tests/src/core/conversations/validators.test.ts) — `isMessage`, `isJudgment` with snapshot carriage and its verdicts pinned over edge records, `isSection`, `isConversationSnapshot`, and `isConversation`, each total over malformed input.
4253
+ - [`tests/src/core/conversations/helpers.test.ts`](../tests/src/core/conversations/helpers.test.ts) — `buildJudgments`, `requireJudgment`, `requireRole`, `requireConversationSnapshot`, `requireStoredMessage`, `collectRemovals`, `requireLabel`, and `renderReference`.
4254
+ - [`tests/src/core/conversations/validators.test.ts`](../tests/src/core/conversations/validators.test.ts) — `isMessage`, `isJudgment` with snapshot carriage and its verdicts pinned over edge records, `isConversationSnapshot`, and `isConversation`, each total over malformed input.
4339
4255
  - [`tests/src/core/conversations/stores/MemoryConversationStore.test.ts`](../tests/src/core/conversations/stores/MemoryConversationStore.test.ts) — the in-memory store's round trip, upsert, deletion, coexisting ids, JSON parity, and tool messages with and without `call`.
4340
4256
  - [`tests/src/core/conversations/stores/DatabaseConversationStore.test.ts`](../tests/src/core/conversations/stores/DatabaseConversationStore.test.ts) — the driver-backed store's round trip, upsert, deletion, coexisting ids, driver overloads, and durability across instances.
4341
4257
  - [`tests/src/core/contexts/AgentContext.test.ts`](../tests/src/core/contexts/AgentContext.test.ts) — the system boundary, freshness, and tool exclusion of `build()`, the context managers, the skills and memos indexes, workspace carriers and `scope.files`, scope filtering, format cascade, the default conversation and switch, `select` resolution over the conversation passed with its `'ROLE'` fault over a selected `system` message and a run scope's `select`, `build` with a selection and a run scope, the shown skills' bodies closing the `system` message within the ceiling, memo text kept out of the `system` message, and the shown workspace with the workspace index.
@@ -4350,7 +4266,7 @@ The following test files back this guide:
4350
4266
  - [`tests/src/core/contexts/skills/SkillManager.test.ts`](../tests/src/core/contexts/skills/SkillManager.test.ts) — the skill registry's add, the `tools` list copied in, files minted through `createFile`, same-name replace, lookup, removal, format cascade, and emitter.
4351
4267
  - [`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.
4352
4268
  - [`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.
4353
- - [`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, the run `scope` option with its per-turn ceiling over seeded sequences, its narrowing and widening `apply` calls, its `select` order, overlapping runs under distinct run scopes, one read a turn, the head built under it at entry and after a fold, and its `placement` refusal, the `request` event with its frozen request, its fold, its cancelled turn, and a run a `request` listener aborts at its first and at a later turn, which sends nothing for that turn, the forwarded skills and memos, and the built-ins and disclosure: the construction refusals, the request unchanged with built-ins and a workspace absent, a skill's held tools over seeded scopes, a load at the next turn, one `system` message at index 0, the head refresh, the `workspace` option with a run value over the agent value and the thread's `switch` over both, the `unload` of a loaded skill, no option set that shows a skill, the ceiling read each turn and in each handler, overlapping runs and a restored snapshot, the refusal text, `remember` with its approver, `switch`, the run's own built-in instances, and the relay.
4269
+ - [`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, the whole conversation sent on every turn, recorded thinking and the replay policy, multi-conversation runs and the run-bound conversation under a switch 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, the run `scope` option with its per-turn ceiling over seeded sequences, its narrowing and widening `apply` calls, its `select` order, overlapping runs under distinct run scopes, one read a turn, the head built under it at entry, and its `placement` refusal, the `request` event with its frozen request, its cancelled turn, and a run a `request` listener aborts at its first and at a later turn, which sends nothing for that turn, the forwarded skills and memos, and the built-ins and disclosure: the construction refusals, the request unchanged with built-ins and a workspace absent, a skill's held tools over seeded scopes, a load at the next turn, one `system` message at index 0, the head refresh, the `workspace` option with a run value over the agent value and the thread's `switch` over both, the `unload` of a loaded skill, no option set that shows a skill, the ceiling read each turn and in each handler, overlapping runs and a restored snapshot, the refusal text, `remember` with its approver, `switch`, the run's own built-in instances, and the relay.
4354
4270
  - [`tests/src/core/agents/AgentRun.test.ts`](../tests/src/core/agents/AgentRun.test.ts) — the internal `AgentRun` class: a built-in name answered from the run's own tools after a later host add, the advertised candidates with `remember` and `switch` only under a list that names a key, a head built with another view reported stale, and each built-in handler's refusals and its read of the live ceiling.
4355
4271
  - [`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, an empty registry, and a job's `scope`, `workspace`, and `builtins`: the job contract over each, what a job holds of the shared pools, its workspace within its scope, no drawn job that shows a skill, its built-ins under its authority, and `remember` on a job.
4356
4272
  - [`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.
@@ -4363,12 +4279,12 @@ The following test files back this guide:
4363
4279
  - [`tests/src/core/agents/contracts.test.ts`](../tests/src/core/agents/contracts.test.ts) — the frame, prompt, answer, and job contracts over every frame arm and every refused wire row, a throwing `Proxy`, and seeded values that agree with `parse`.
4364
4280
  - [`tests/src/core/agents/validators.test.ts`](../tests/src/core/agents/validators.test.ts) — `isAuthorityDecision` over each verdict with and without `reason`, and its refusal of a `{ zone, allowed }` decision, an unknown verdict, a non-string `zone` or `reason`, a non-object, a throwing getter, a revoked `Proxy`, and a `Proxy` whose `get` trap throws.
4365
4281
  - [`tests/src/core/agents/AgentFanout.test.ts`](../tests/src/core/agents/AgentFanout.test.ts) — `AgentFanout` through a real runner: one fan-out per unit across a retried attempt, every distinct unit's children, the partial policy, and the refusal of a child that exceeds its parent on each member, its `builtins` and each `scope` list included, at any depth, before anything in the tree runs.
4366
- - [`tests/src/core/ledgers/Ledger.test.ts`](../tests/src/core/ledgers/Ledger.test.ts) — the ledger over a scripted provider: owner records, seed stubs paired with their calls by call id and priced at their longer form, and the seed tail, the agent record that holds no run member, built bare and hydrated, its live status and abort, the runs that are each a pass of the active `respond` call, the `'REQUEST'` fault of a direct selection no active `respond` call owns, on the ledger's conversation and another one, a lookup that awaits a second ledger or a second agent and leaves the gauge as its control arm's, the runs that stay on the ledger's conversation under a switch, the repeat stop and the stop of the identical retry of a call the authority denied, the answer pass and the abort that skips it, calibration with its replay at the next user boundary and its refusals, the filing of notes and failed lookups, the `recall` tool's listing, limit, room, and per-request offer with a host's scope kept and restored, the answer note's lines, the generation cap and thinking per pass, and retained amended sentences with unresolved scope while `recall`, the answer note, and the seed tail keep stored content, the window's extending copies, rungs, emptying, derived pair, rejected request, answered fallback, and stub state, and the snapshot and hydrate: selections and judge keys equal to the uninterrupted ledger's with each emptied mark list as a control, provider prompts equal through five JSON round trips, the `window` member's omission, refusals, and digest checked at hydrate, the JSON round trip, the `'CONCURRENCY'` refusal, judgments kept across a judge abort, the `'SNAPSHOT'` refusals, the `'ROLE'` refusal of a hydrated `system` message, the gauge precedence, the fork, a recorded correction fixture replayed through a hydrated ledger, the replay from a sorted snapshot, each lookup result read once per selection, a message removed during a judge await kept out of that selection's plan, the forwarding of the `narrow` member to the classifier, head pricing and the built-head calibration, and the host turns: each entry refused during one, another thread's refused selection, a `recall` a host calls by hand that spends the request's recall limit, an append and a removal that fault the selection with no question about a gone message, a judgment removed during one asked again, an abort and a scheduler fault that leave the ledger free, the same bytes when paced, and the agent's turn between its own turns, and disclosure in the ledger: the `'AUTHORITY'` refusal and the host authority on every built-in call, the repeat stop of a built-in, filing and the answer pass with every shown body, an area scope and the skills index on one kept ledger, no drawn option set that shows a skill, calibration over the definitions no skill holds back and a hydrate that shows what its thread showed, the plan's holdback, the room admission of `load`, `remember`, and `switch` with the `skills` share and the calls an `unload` reopens, the shown set in every build, the capacity gate over seeded arms and its refusals in every ledger, host acts inside a request, a supplied gauge that states more or less than its provider charges, the spared rate on a provider rated from a live run, and the memos of one principal.
4367
- - [`tests/src/core/ledgers/LedgerRequest.test.ts`](../tests/src/core/ledgers/LedgerRequest.test.ts) — the request's recall-limit refusal, its single `enter`, its passes with their selections, usage, calls, and thinking, its filing attempts and plan, the draft its last provider turn adopted as the `sent` member, the repeat stop and its release, the denied calls, the recall limit and `close`, the abort of the current pass, the listings of a recall result, and the prices `commit` records, with the `committed` sum and the `loads` it derives from the call in flight.
4368
- - [`tests/src/core/ledgers/Classifier.test.ts`](../tests/src/core/ledgers/Classifier.test.ts) — the measured question bytes and asking order, judgment reuse and usage, exact cutoffs, the category tie in `LEDGER_CATEGORIES` order, pair questions, deterministic and transient judge failures, abort faults that keep the completed judgments, the cached, skipped, resolved, failed, and aborted attempts each of those paths records, each message's quiet flag and near set read once per classification, with a change to the conversation or the judge's model read at the next call, the pairs of every eligible earlier message asked in conversation order and the narrower set of the `narrow` member, and the host turns: a yield after a slice elapses on a recording and a real scheduler, none in a live slice or with no scheduler, the same questions when paced, the asks a removed source skips, an abort during a turn, and a scheduler fault.
4282
+ - [`tests/src/core/ledgers/Ledger.test.ts`](../tests/src/core/ledgers/Ledger.test.ts) — the ledger over a scripted provider: owner records, seed stubs paired with their calls by call id and priced at their longer form, and the seed tail, the agent record that holds no run member, built bare and hydrated, its live status and abort, the runs that are each a pass of the active `respond` call, the `'REQUEST'` fault of a direct selection no active `respond` call owns, on the ledger's conversation and another one, a lookup that awaits a second ledger or a second agent and leaves the gauge as its control arm's, the runs that stay on the ledger's conversation under a switch, the repeat stop and the stop of the identical retry of a call the authority denied, the answer pass and the abort that skips it, calibration with its replay at the next user boundary and its refusals, the filing of notes and failed lookups, the `recall` tool's listing, limit, room, and per-request offer with a host's scope kept and restored, the answer note's lines, the generation cap and thinking per pass, and retained amended sentences with unresolved scope while `recall`, the answer note, and the seed tail keep stored content, the window's extending copies, rungs, emptying, derived pair, rejected request, and stub state, and the snapshot and hydrate: selections and judge keys equal to the uninterrupted ledger's with each emptied mark list as a control, provider prompts equal through five JSON round trips, the `window` member's omission, refusals, and digest checked at hydrate, the JSON round trip, the `'CONCURRENCY'` refusal, judgments kept across a judge abort, the `'SNAPSHOT'` refusals, the `'ROLE'` refusal of a hydrated `system` message, the gauge precedence, the fork, a recorded correction fixture replayed through a hydrated ledger, the replay from a sorted snapshot, each lookup result read once per selection, a question the judge refuses held as a refused judgment, reported once through `fault`, skipped by later requests and a hydrate, asked again under another judge model, filed on its owner record, and dropped with its message, the measured prompt share by default, head pricing and the built-head calibration, the stream's chunks in pass order, the result and the rejection it settles as `respond` does, its caller abort, handle abort, and early break, the teardown and its `'DESTROYED'` refusal, the marks and the window a removed message takes with it, at the removal and at the commit of a request in flight, and the host turns: each entry refused during one, another thread's refused selection, a `recall` a host calls by hand that spends the request's recall limit, an append and a removal that reject the request with no question about a gone message, a judgment removed during one asked again, an abort that leaves the ledger free, the same bytes when paced, and the agent's turn between its own turns, and disclosure in the ledger: the `'AUTHORITY'` refusal and the host authority on every built-in call, the repeat stop of a built-in, filing and the answer pass with every shown body, an area scope and the skills index on one kept ledger, no drawn option set that shows a skill, calibration over the definitions no skill holds back and a hydrate that shows what its thread showed, the plan's holdback, the room admission of `load`, `remember`, and `switch` with the `skills` share and the calls an `unload` reopens, the shown set in every build, the capacity gate over seeded arms and its refusals in every ledger, host acts inside a request, a supplied gauge that states more or less than its provider charges, the spared rate on a provider rated from a live run, and the memos of one principal.
4283
+ - [`tests/src/core/ledgers/LedgerRequest.test.ts`](../tests/src/core/ledgers/LedgerRequest.test.ts) — its single `enter`, its passes with their selections, usage, calls, and thinking, its filing attempts and plan, the draft its last provider turn adopted as the `sent` member, the repeat stop and its release, the denied calls, the fixed recall limit and `close`, the abort of the current pass, the listings of a recall result, and the prices `commit` records, with the `committed` sum and the `loads` it derives from the call in flight.
4284
+ - [`tests/src/core/ledgers/Classifier.test.ts`](../tests/src/core/ledgers/Classifier.test.ts) — the measured question bytes and asking order, judgment reuse and usage, exact cutoffs, the category tie in `LEDGER_CATEGORIES` order, pair questions, held and transient judge failures, abort faults that keep the completed judgments, the cached, skipped, resolved, failed, and aborted attempts each of those paths records, each message's quiet flag and near set read once per classification, with a change to the conversation or the judge's model read at the next call, the pairs of every eligible earlier message asked in conversation order, and the host turns: a yield after a slice elapses on a recording and a real scheduler, none in a live slice or with no scheduler, the same questions when paced, the asks a removed source skips, an abort during a turn, and a scheduler fault.
4369
4285
  - [`tests/src/core/ledgers/Gauge.test.ts`](../tests/src/core/ledgers/Gauge.test.ts) — the gauge's construction refusals and its `observe`, `rate`, `remainder`, `reserve`, and `room` methods, under the generation cap and each replay policy, with the definitions a call adds beyond the calibrated set in the fallback remainder and a first call that adds some kept out of the rescale.
4370
- - [`tests/src/core/ledgers/factories.test.ts`](../tests/src/core/ledgers/factories.test.ts) — `createLedger` and its `LedgerError` refusals for thresholds, shares, capacity, limits, topics, lookups, and a supplied gauge, the keys of the `LedgerAgentOptions` type, and the barrel exports of the ledger module.
4371
- - [`tests/src/core/ledgers/helpers.test.ts`](../tests/src/core/ledgers/helpers.test.ts) — the projection helpers from `splitSentences` through `buildRecords` and `selectRecords`, the `normalizeWord` fold, the alias index the `buildLedgerIndex` function builds for the `matchEntities` function, the record renderers, `rankLedgerCut`, `findLedgerCut`, `buildLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `buildRequestMessage`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `resolvePredict`, `fitSlope`, `digestLedgerWindow`, `collectRecallMessages`, `collectRetiredFindings`, `hasHiddenRecall`, `buildLedgerLineKey`, `collectLedgerLines`, `collectLedgerReplies`, `collectLedgerEvidence`, `computeToolDensity`, `computeToolPrice` with its table of calibrated, advertised, and replaced sets on both sides of the scale and the density samples the 4B read, and `computeSkillPrice`.
4286
+ - [`tests/src/core/ledgers/factories.test.ts`](../tests/src/core/ledgers/factories.test.ts) — `createLedger` and its `LedgerError` refusals for thresholds, shares, capacity, the generation cap, limits, topics, lookups, and a supplied gauge, its refusal of the retired `recall` and `correction` members, the keys of the `LedgerAgentOptions` type, and the barrel exports of the ledger module.
4287
+ - [`tests/src/core/ledgers/helpers.test.ts`](../tests/src/core/ledgers/helpers.test.ts) — the projection helpers from `splitSentences` through `buildRecords` and `selectRecords`, the `normalizeWord` fold, the alias index the `buildLedgerIndex` function builds for the `matchEntities` function, the record renderers, `rankLedgerCut`, `findLedgerCut`, `buildLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `buildRequestMessage`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `requirePredict`, `collectQuestionKeys`, `fitSlope`, `digestLedgerWindow`, `collectRecallMessages`, `collectRetiredFindings`, `hasHiddenRecall`, `buildLedgerLineKey`, `collectLedgerLines`, `collectLedgerReplies`, `collectLedgerEvidence`, `computeToolDensity`, `computeToolPrice` with its table of calibrated, advertised, and replaced sets on both sides of the scale and the density samples the 4B read, and `computeSkillPrice`.
4372
4288
  - [`tests/src/core/ledgers/validators.test.ts`](../tests/src/core/ledgers/validators.test.ts) — `isFraction`, `isPositiveSafeInteger`, `isLedgerSnapshot`, which refuses every malformed snapshot, an unknown or mis-roled id, a throwing getter, and a revoked proxy, and accepts a snapshot a ledger returned, and `isLedgerWindowSnapshot`, which agrees with the `ledgerWindowContract` constant on a valid window and its malformed neighbors.
4373
4289
 
4374
4290
  ### Placement proofs