@orkestrel/scaffold 0.0.134 → 0.0.135

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +610 -79
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +307 -16
  3. package/dist/bin/main.js +253 -35
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/AGENTS.md +1 -1
  6. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  7. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +782 -115
  8. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  9. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
  10. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +379 -27
  11. package/dist/host/claude/agents/orkestrel.md +14 -14
  12. package/dist/host/claude/rules/architecture.md +1 -1
  13. package/dist/host/claude/rules/patterns.md +2 -0
  14. package/dist/host/claude/rules/workspace.md +64 -63
  15. package/dist/host/configs/helpers.ts +88 -67
  16. package/dist/host/dotfiles/oxlintrc.json +1 -57
  17. package/dist/host/guides/agent.md +989 -395
  18. package/dist/host/guides/database.md +357 -342
  19. package/dist/host/guides/middleware.md +5 -5
  20. package/dist/host/guides/ollama.md +41 -42
  21. package/dist/host/guides/scaffold.md +177 -105
  22. package/dist/host/guides/study.md +12 -12
  23. package/dist/host/guides/test.md +158 -46
  24. package/dist/host/guides/toolbox.md +127 -81
  25. package/dist/host/guides/workspace.md +21 -14
  26. package/dist/host/manifest.json +23 -23
  27. package/dist/host/tests/config.test.ts +166 -112
  28. package/dist/src/core/index.cjs +491 -195
  29. package/dist/src/core/index.cjs.map +1 -1
  30. package/dist/src/core/index.d.cts +217 -24
  31. package/dist/src/core/index.d.ts +217 -24
  32. package/dist/src/core/index.js +482 -193
  33. package/dist/src/core/index.js.map +1 -1
  34. package/dist/src/server/index.cjs +18 -8
  35. package/dist/src/server/index.cjs.map +1 -1
  36. package/dist/src/server/index.d.cts +4 -3
  37. package/dist/src/server/index.d.ts +4 -3
  38. package/dist/src/server/index.js +19 -9
  39. package/dist/src/server/index.js.map +1 -1
  40. package/package.json +2 -2
@@ -6,11 +6,11 @@
6
6
  > assembly — and the bounded context → provider → tools → repeat loop that carries a turn to
7
7
  > its end.
8
8
 
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, and the active 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`.
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`.
10
10
 
11
11
  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
12
 
13
- Tools and files are borrowed, not owned. Callable tools come from the `@orkestrel/tool` package (see [Tool](tool.md)): the loop advertises their definitions to the model, dispatches the calls that come back, and feeds each `ToolResult` in as a tool message. A tool is loop machinery — it is never rendered into the prompt. Documents come from the `@orkestrel/workspace` package (see [Workspace](workspace.md)): the context renders the active workspace into every turn, split by carrier — text as fenced reference blocks in one user context message after the system message, images attached to the last user turn. That split is this package's own product policy, decided here because only the prompt-assembly layer defines what a turn contains.
13
+ Tools and files are borrowed, not owned. Callable tools come from the `@orkestrel/tool` package (see [Tool](tool.md)): the loop advertises their definitions to the model, dispatches the calls that come back, and feeds each `ToolResult` in as a tool message. A tool is loop machinery — it is never rendered into the prompt. Documents come from the `@orkestrel/workspace` package (see [Workspace](workspace.md)): the context renders one workspace into each prompt it builds, the one a run shows or else the active one, split by carrier — text as fenced reference blocks in one user context message after the system message, images attached to the last user turn. That split is this package's own product policy, decided here because only the prompt-assembly layer defines what a turn contains.
14
14
 
15
15
  A turn has cancellation and iteration bounds. The run's `AbortSignal` folds an agent abort, a stream abort, an external signal, a [timeout](timeout.md), and the [budget](budget.md) and `allowance` signals through `AbortSignal.any` and bounds the provider. A handler's `context.signal` is that same signal. The allowance is charged during provider streaming and the budget after each provider call and between turns, before tool dispatch; exhaustion ends the run without dispatching, never inside a handler. Tool iteration is capped at `limit`. A running tool must cooperate with cancellation: the loop awaits its result even when it ignores the signal. A cancel commits a partial `AgentResult` that resolves after the running work settles. `generate` and `stream` share one private run, so their results agree, and the emitter isolates a listener's throw.
16
16
 
@@ -59,7 +59,7 @@ const streamed = await print(provider.stream(messages, abort.signal)) // the ass
59
59
 
60
60
  Pass `tools` (a non-empty `ToolDefinition[]`) to advertise callable tools for the turn; when the model calls one, `result.tools` is a `ToolCall[]` (each with an `id`, the tool `name`, and parsed `arguments`). Aborting a `stream` mid-flight throws a `ProviderAbortError` whose `partial` holds whatever streamed before the cancel.
61
61
 
62
- A tool is a JSON-Schema-described callable from the `@orkestrel/tool` package (see [Tool](tool.md)). The registry's `definitions()` method advertises tools, and its `execute` method dispatches calls. When a turn advertises tools, the loop refuses a name excluded by the scope's tool allow-list or carried by no advertised definition before reaching the registry, with the scope denial. Such a name, unadvertised or unregistered, is refused before the authority or the registry sees it, whatever the authority would decide. The returned `ToolResult` value uses the `success` discriminant: an unknown name and a throwing handler produce the failure arm, and batch execution isolates each call from its siblings. Direct registry calls behave as follows:
62
+ A tool is a JSON-Schema-described callable from the `@orkestrel/tool` package (see [Tool](tool.md)). The registry's `definitions()` method advertises tools, and its `execute` method dispatches calls. When a turn advertises tools, the loop refuses a name excluded by the turn's tool ceiling, the context scope's tool allow-list intersected with the run scope's, or carried by no advertised definition before reaching the registry, with the scope denial. Such a name, unadvertised or unregistered, is refused before the authority or the registry sees it, whatever the authority would decide. The returned `ToolResult` value uses the `success` discriminant: an unknown name and a throwing handler produce the failure arm, and batch execution isolates each call from its siblings. Direct registry calls behave as follows:
63
63
 
64
64
  ```ts
65
65
  import { createTool, createToolManager } from '@orkestrel/tool'
@@ -145,7 +145,7 @@ for await (const chunk of stream.events) {
145
145
  const result = await stream.result // { content, usage?, partial } — usage summed across the turn
146
146
  ```
147
147
 
148
- Both `generate` and `stream` accept optional per-run `AgentRunOptions` — `think` and `schema` (forwarded to the provider as `ProviderStreamOptions`) plus `limit` / `timeout` / `budget` / `allowance` / `signal`, each overriding its `AgentOptions` construction default for this run only. Omitting one keeps the constructed default, so a caller that passes no options gets the agent it configured. The same options carry `conversation`, which binds the run, and `prompt`, which the run appends as a `user` turn after its guards; a run with no `prompt` reads its request from the conversation's tail. A per-run `signal` composes with (never replaces) a constructed `signal` — either aborting cancels the run; the loop calls `start()` on a per-run `budget` or `allowance` for that run and charges it, leaving a constructed one untouched:
148
+ Both `generate` and `stream` accept optional per-run `AgentRunOptions` — `think` and `schema` (forwarded to the provider as `ProviderStreamOptions`) plus `limit` / `timeout` / `budget` / `allowance` / `signal`, each overriding its `AgentOptions` construction default for this run only. Omitting one keeps the constructed default, so a caller that passes no options gets the agent it configured. The same options carry `conversation`, which binds the run, and `prompt`, which the run appends as a `user` turn after its guards; a run with no `prompt` reads its request from the conversation's tail. They also carry `scope`, which narrows the run's ceiling under the context scope, as [Scoping a turn](#scoping-a-turn) states. A per-run `signal` composes with (never replaces) a constructed `signal` — either aborting cancels the run; the loop calls `start()` on a per-run `budget` or `allowance` for that run and charges it, leaving a constructed one untouched:
149
149
 
150
150
  ```ts
151
151
  const agent = createAgent(provider, { tools, authority, limit: 10, timeout: 60_000 }) // construction defaults
@@ -245,7 +245,7 @@ instructions.open // '## Instructions'
245
245
  instructions.render(safety) // 'Refuse unsafe requests.'
246
246
  ```
247
247
 
248
- The standalone `MemoManager` and `SkillManager` carry the same build contract for an index of named entries. A memo is a durable fact kept across conversations, and a skill is an instruction bundle a host supplies. Each manager renders one `- name: description` line per entry through `renderIndexEntry`, under `'## Memos'` or `'## Skills'` unless a `format` option overrides it, and `build` joins those lines with a single newline into one block. An index line is one line: a run of line-break code points in a memo or skill name or description renders as one space. A same-name memo `add` with changed text appends a revision: `memo(name)` returns the last revision, and `history(name)` lists every revision, oldest first. Re-adding unchanged text returns the current revision and emits nothing, `remove` forgets a memo with its whole history, and `snapshot()` returns owned plain data that the `snapshot` option restores without an event. The constructor copies a supplied `snapshot` through JSON and checks the copy with `isMemoSnapshot`: a malformed one throws `ContextError` with code `SNAPSHOT` before any state is seated or event emitted, and the caller's objects never alias the manager's revisions. A same-name skill `add` replaces the skill in its position, and each bundled file is minted through the `createFile` function of `@orkestrel/workspace`. `AgentContext` renders the skills index in the `system` message, after the instructions, and the memos index in the context message, before the workspace text, so the following example reads each index through `build`:
248
+ The standalone `MemoManager` and `SkillManager` carry the same build contract for an index of named entries. A memo is a durable fact kept across conversations, and a skill is an instruction bundle a host supplies. Each manager renders one `- name: description` line per entry through `renderIndexEntry`, under `'## Memos'` or `'## Skills'` unless a `format` option overrides it, and `build` joins those lines with a single newline into one block. An index line is one line: a run of line-break code points in a memo or skill name or description renders as one space. A same-name memo `add` with changed text appends a revision: `memo(name)` returns the last revision, and `history(name)` lists every revision, oldest first. Re-adding unchanged text returns the current revision and emits nothing, `remove` forgets a memo with its whole history, and `snapshot()` returns owned plain data that the `snapshot` option restores without an event. The constructor copies a supplied `snapshot` through JSON and checks the copy with `isMemoSnapshot`: a malformed one throws `ContextError` with code `SNAPSHOT` before any state is seated or event emitted, and the caller's objects never alias the manager's revisions. A same-name skill `add` replaces the skill in its position, and each bundled file is minted through the `createFile` function of `@orkestrel/workspace`. A skill's `tools` list is copied in, and `add` refuses a `tools` member that isn't absent or an array of strings with `ContractError` code `placement`, before it stores that skill. `AgentContext` renders the skills index in the `system` message, after the instructions, and the memos index in the context message, before the workspace text, so the following example reads each index through `build`:
249
249
 
250
250
  ```ts
251
251
  import { createAgentContext, createMemoManager, createSkillManager } from '@orkestrel/agent'
@@ -301,9 +301,9 @@ restored.memo('tone')?.description // 'Prefers short replies.'
301
301
 
302
302
  A memo's `origin` is asserted by whoever wrote it and not verified, so read it as a claim. [Persisting a conversation through either store](#persisting-a-conversation-through-either-store) shows the store seam the memo stores share.
303
303
 
304
- A skills index with no tool that loads a skill is inert for the model. Agent ships no skill-loading tool, so a host that adds skills registers its own tool, which takes a skill name, loads the body through `context.instructions.add({ name: 'skill:<name>', content })`, and unloads it through `context.instructions.remove('skill:<name>')`. A loaded body applies as any instruction added during a run does, at the next build site named under scope changes. A run whose next turn does not fold keeps the head it built, so the model holds the tool's acknowledgement and not the body until the next run; a turn that folds rebuilds the head and carries the body. A load then serves that agent's later runs in every conversation, until the host removes the instruction. 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, and read a loaded body from `skills.skill(name)`, never from the tool'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.
304
+ 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
305
 
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.
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.
307
307
 
308
308
  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
309
 
@@ -319,7 +319,7 @@ const result = await provider.generate(
319
319
  )
320
320
  ```
321
321
 
322
- `AgentContext` wires the instruction, skill, and memo managers and the workspace registry in. Beyond `system`, `messages`, and `tools`, a context exposes its own `instructions`, `skills`, and `memos` managers and `workspaces` registry — pass pre-built ones through `AgentContextOptions`, or fresh empty ones are created — and `build()` folds them into the turn. The assembly order is one leading `system` message holding the system prompt, then the non-empty instructions block (its `open` header, each item's `render` output, and its `close` line when set), then the non-empty skills index, joined by blank lines; then one `user` context message holding the memos index, then the active workspace's text files under a `## Workspace` header; then the conversation, or the `messages` of a selection passed to `build`. With no instructions, no skills, no memos, no active workspace, and no scope, that reduces to exactly the lean `[systemMessage?, ...messages]`. The carrier split shows here: the system message holds host-authored text alone, memo and workspace text ride the context message, and image data rides the last user message.
322
+ `AgentContext` wires the instruction, skill, and memo managers and the workspace registry in. Beyond `system`, `messages`, and `tools`, a context exposes its own `instructions`, `skills`, and `memos` managers and `workspaces` registry — pass pre-built ones through `AgentContextOptions`, or fresh empty ones are created — and `build()` folds them into the turn. The assembly order is one leading `system` message holding the system prompt, then the non-empty instructions block (its `open` header, each item's `render` output, and its `close` line when set), then the non-empty skills index, then the bodies of the skills the `disclosure` option of `build` shows, under `## Loaded skills`, joined by blank lines; then one `user` context message holding the memos index, then the admitted workspace ids under `## Workspaces` when the `switchable` option of `build` is `true`, then the text files of the workspace that `disclosure` names, else of the active one, under a `## Workspace` header; then the conversation, or the `messages` of a selection passed to `build`. With no instructions, no skills, no memos, no active workspace, and no scope, that reduces to exactly the lean `[systemMessage?, ...messages]`. The carrier split shows here: the system message holds host-authored text alone, memo and workspace text ride the context message, and image data rides the last user message.
323
323
 
324
324
  ````ts
325
325
  import { createAgentContext } from '@orkestrel/agent'
@@ -470,7 +470,7 @@ agent.emitter.on('fault', (error) =>
470
470
 
471
471
  ### Scoping a turn
472
472
 
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` list keyed by each category's identity — `instructions` (by `name`), `skills` (by `name`), `memos` (by `name`), `tools` (by `name`), `files` (the active workspace's files, by `path`) — 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:
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:
474
474
 
475
475
  ```ts
476
476
  import { createAgent, createScope } from '@orkestrel/agent'
@@ -491,9 +491,37 @@ agent.context.apply(
491
491
  const result = await agent.generate()
492
492
  ```
493
493
 
494
- A scoped-out tool is neither described nor callable. The loop snapshots the scope's tool allow-list before advertising and checks each returned call against that list before consulting the `AgentOptions.authority` option. An `undefined` scope value, or an absent `tools` list, admits every advertised name and refuses a name no advertised definition carries with the scope denial. An empty `tools` list admits none.
494
+ 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
495
 
496
- A scope change through the `context.apply` method applies at each later site that reads the scope. The tool half applies at the next turn's snapshot: a `tool` or `usage` listener changes the next turn's advertising, and a `turn` listener reaches the same turn, because `turn` fires before the snapshot. The prompt half (instructions, skills, memos, files, and `select`) applies at the next build or select site: run entry, the pre-first-turn compaction fold, or a compaction rebuild.
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.
497
+
498
+ 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
+
500
+ The following run advertises only the tool both scopes admit:
501
+
502
+ ```ts
503
+ import type { AuthorityInterface, ProviderInterface } from '@orkestrel/agent'
504
+ import { createAgent, createScope } from '@orkestrel/agent'
505
+ import { createTool, createToolManager } from '@orkestrel/tool'
506
+
507
+ declare const provider: ProviderInterface // replies 'Invoice 42 is paid.'
508
+ declare const authority: AuthorityInterface // allows each tool
509
+ declare function log(names: readonly string[] | undefined): void
510
+
511
+ const tools = createToolManager()
512
+ tools.add(['search', 'refund', 'delete'].map((name) => createTool({ name, execute: () => name })))
513
+ // The context scope admits `search` and `refund`.
514
+ const agent = createAgent(provider, {
515
+ tools,
516
+ authority,
517
+ scope: createScope({ name: 'desk', tools: ['search', 'refund'] }),
518
+ })
519
+ agent.emitter.on('request', (_index, request) => log(request.tools?.map(({ name }) => name))) // ['search']
520
+ agent.context.messages.add({ role: 'user', content: 'Is invoice 42 paid?' })
521
+ // This run admits `search` and `delete`, so each of its turns advertises `search` alone.
522
+ const reader = createScope({ name: 'reader', tools: ['search', 'delete'] })
523
+ const result = await agent.generate({ scope: reader }) // { content: 'Invoice 42 is paid.', partial: false }
524
+ ```
497
525
 
498
526
  When no tool is advertised, including an empty registry, a reply with no calls ends the run as the answer, and a call the reply still carries is denied like any other scoped-out call: it emits a `deny` event with the `<tool name> is not in the active scope` reason, gets a denial tool result and tool message, and the loop runs another turn, up to `limit`, so a call is never read as a final answer.
499
527
 
@@ -501,11 +529,146 @@ When at least one tool is advertised, a call excluded by the tool allow-list or
501
529
 
502
530
  A `ScopeManager` registry stores reusable named scopes, keyed by a minted `id` field; scopes can share a `name` field. It is observable like the other managers.
503
531
 
532
+ ### Enabling the built-in tools
533
+
534
+ The `builtins` option of `AgentOptions` enables the tools an agent serves itself, each named by `AgentBuiltin`: `load` and `unload` show and hide a skill, `memo` reads a memo, `remember` writes one, and `switch` selects a workspace. A built-in passes the gate any tool passes. A turn advertises it only where the ceiling's `tools` list admits its name, and each call passes the scope check, the authority's `evaluate`, the `consequential` floor, and the approver. `remember` is annotated `consequential`, so an `allow` verdict asks, and with no approver the call is denied as unanswered. `memo` is annotated `pure` and `untrusted`, because it returns text a model can have written. Each handler also reads the ceiling when it runs, the context scope intersected with the run scope at that moment, so a narrowing made after a call's decision refuses the call. Agent supplies no default verdict, so an agent that enables a built-in with no `authority` throws `AgentError` with code `'AUTHORITY'` at construction.
535
+
536
+ The constructor refuses the `builtins` option with `AgentError` code `'BUILTIN'` when an entry is no `AgentBuiltin` name, when a name repeats, when it lists `unload` without `load`, and when the tool manager already holds a tool under an enabled name. Each run owns its built-in tools, so a tool a host registers later under an enabled name is never advertised or dispatched. With `builtins` absent, no skill holds a tool back and no skill body renders.
537
+
538
+ The following agent lets the model load a skill, and the skill's tool waits for that load:
539
+
540
+ ```ts
541
+ import type { ProviderInterface } from '@orkestrel/agent'
542
+ import { createAgent, createAuthority, createSkillManager } from '@orkestrel/agent'
543
+ import { createTool, createToolManager } from '@orkestrel/tool'
544
+
545
+ declare const provider: ProviderInterface // calls load with { skill: 'refunds' }, then refund, then answers
546
+ declare function log(names: readonly string[] | undefined): void
547
+
548
+ const tools = createToolManager()
549
+ tools.add(createTool({ name: 'refund', execute: () => 'Refund queued.' }))
550
+ const skills = createSkillManager()
551
+ skills.add({
552
+ name: 'refunds',
553
+ description: 'Refunds a paid order.',
554
+ content: 'Confirm the order is paid before you call refund.',
555
+ tools: ['refund'],
556
+ })
557
+ const agent = createAgent(provider, {
558
+ tools,
559
+ skills,
560
+ builtins: ['load', 'unload'],
561
+ authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
562
+ })
563
+ agent.emitter.on('request', (_index, request) => log(request.tools?.map(({ name }) => name)))
564
+ await agent.generate({ prompt: { content: 'Refund order 42.' } })
565
+ // turn 0: ['load', 'unload'], with refund held back
566
+ // turn 1: ['refund', 'load', 'unload'], and the system message ends with the refunds body
567
+ // turn 2: the head turn 1 built, sent again
568
+ ```
569
+
570
+ A load reaches the next turn of the same run, never its own. The loading turn's request carries neither the body nor the skill's tools. The next turn's `system` message ends with the body under the `LOADED_SECTION_HEADER` header, `## Loaded skills`, and its definitions add the tools the skill lists. The call itself returns a fixed note from `BUILTIN_NOTES`, never the body. In a batch that calls `load` and then one of the skill's tools, the loop denies the tool call with the scope denial, because the turn that decided it didn't advertise that tool, and the identical call runs the next turn. An `unload` in the same batch as the `load` it would undo is refused, because the load's tool message is stored after the batch. A load, an unload, a switch, and a change to the ceiling's lists each show at the next turn, and a run whose view doesn't change never rebuilds its head; [Scoping a turn](#scoping-a-turn) names the view a turn compares.
571
+
572
+ A skill holds its tools back while `builtins` enables `load` and the ceiling's `tools` list admits it. Then a tool any registered skill lists in `tools` is advertised only while a shown skill lists it too, and `load` and `unload` are never held back. With no `tools` list, an empty `skills` list leaves `load` and `unload` unadvertised and keeps the hold, so a ceiling that admits no skill advertises no skill's tool. While `builtins` omits `load` or the ceiling's `tools` list admits no `load` definition, because the list excludes `load` or an empty `skills` list withholds it, the allow-list alone decides, so a run scope that lists a skill's tools and not `load` calls them with no load. Holding a tool back is presentation, not authority: the ceiling's `tools` list and the authority bind every call either way. Removing a skill from the registry releases the tools it held, and a turn advertises each one wherever the allow-list admits it. A shown skill's body renders under any `tools` list, one that excludes the skill's own tools included, so list a skill's tools in every scope that admits the skill.
573
+
574
+ The host selects a run's workspace through the `workspace` option, a workspace id. On `AgentOptions` it names the workspace every run renders in place of the active one, and on `AgentRunOptions` it replaces the agent's value for that run; the thread's last `switch` outranks both. An id the registry lacks, or that the ceiling's `workspaces` list excludes, renders nothing, and the active workspace renders in its place where the list admits it. The option never moves the registry's `active` pointer. A value that is not a string throws `ContractError` with code `placement`: at construction for the agent option, and synchronously from `stream` or `generate` for the run option, before the run appends its prompt. The following runs render a chosen workspace with no built-in enabled:
575
+
576
+ ```ts
577
+ import type { ProviderInterface } from '@orkestrel/agent'
578
+ import { createAgent, createScope } from '@orkestrel/agent'
579
+
580
+ declare const provider: ProviderInterface // answers each run
581
+ const agent = createAgent(provider, { workspace: 'returns' })
582
+ agent.context.workspaces.add({ id: 'orders' }).write('orders.txt', 'Order 42 is paid.') // the active one
583
+ agent.context.workspaces.add({ id: 'returns' }).write('returns.txt', 'Return 7 is open.')
584
+ await agent.generate({ prompt: { content: 'Check return 7.' } }) // renders returns
585
+ await agent.generate({ prompt: { content: 'Check order 42.' }, workspace: 'orders' }) // renders orders
586
+ const plain = createScope({ name: 'plain', workspaces: ['orders'] })
587
+ await agent.generate({ prompt: { content: 'Check order 9.' }, scope: plain }) // renders orders
588
+ ```
589
+
590
+ 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 admits each call's arguments as the tool's argument contract admits them, lossless repairs included, so a `{ skill: 1 }` the contract 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:
591
+
592
+ ```ts
593
+ import type { ProviderInterface } from '@orkestrel/agent'
594
+ import { createAgent, createAuthority, createConversation } from '@orkestrel/agent'
595
+
596
+ declare const provider: ProviderInterface // calls load with { skill: 'refunds' } once, then answers
597
+ const agent = createAgent(provider, {
598
+ builtins: ['load', 'unload'],
599
+ authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
600
+ })
601
+ agent.context.skills.add({
602
+ name: 'refunds',
603
+ description: 'Refunds a paid order.',
604
+ content: 'Confirm the order is paid.',
605
+ })
606
+ const first = createConversation()
607
+ await agent.generate({ conversation: first, prompt: { content: 'Refund order 42.' } }) // loads refunds
608
+ const second = createConversation()
609
+ await agent.generate({ conversation: second, prompt: { content: 'Refund order 43.' } }) // no body
610
+ const restored = createConversation({ snapshot: first.snapshot() })
611
+ await agent.generate({ conversation: restored, prompt: { content: 'Refund order 44.' } }) // shows refunds
612
+ ```
613
+
614
+ `memo` returns the current revision's `content` as its tool result, in the tool role, and no memo name, description, or content enters the `system` message. `remember` writes only where the ceiling defines a `memos` list, and only a name that list holds. It creates a listed name no memo holds, and it revises a memo only when that memo's current revision carries the run's conversation id as `origin.conversation`, so a host's memo and another thread's memo stay as they are. Each revision it writes carries `origin: { conversation }` with the run's conversation id. A name or description that isn't one line of visible text refuses, a blank one included, which holds nothing but white space and default-ignorable code points such as U+3164. No built-in removes a memo. The memos index picks up a written memo at the next head build, and a write alone doesn't rebuild the head, so `memo` reads it back meanwhile. A scope's `memos` list therefore does two jobs: it filters the memos index, and it names the memos the model may write.
615
+
616
+ `switch` selects a workspace for the run's conversation alone. It selects only an id the ceiling's `workspaces` list holds. The next turn's context message renders that workspace's text files, its images attach to the last user turn, and the registry's `active` pointer never moves. While a turn advertises `switch`, the context message lists the admitted ids under the `WORKSPACE_INDEX_HEADER` header, `## Workspaces`. The shown workspace is the conversation's last switch, else the one the `workspace` option names, else the registry's active workspace. Each tool call receives that workspace as `context.caller`, an `AgentCaller` whose `workspace` member is the live workspace the turn's request rendered, or `undefined` when the ceiling admits none at the call. A `switch` shows from the next turn, so a call that shares its turn acts on the workspace that turn's request rendered. The caller's `files` member is the ceiling's `files` list at the call, `undefined` when the ceiling states none. A switched workspace that the ceiling's `workspaces` list later excludes falls back to the active workspace, which renders where the list admits it, and the switched one returns when the list admits it again. The model receives no word of either change.
617
+
618
+ `remember` and `switch` are advertised only while the ceiling's list names a key, `memos` for `remember` and `workspaces` for `switch`, and nothing reports their absence: an agent that enables them with no list, or with an empty one, runs as if it hadn't enabled them. Set each list on the agent's scope or on the run's. The following agent writes one memo and switches its workspace:
619
+
620
+ ```ts
621
+ import type { ProviderInterface } from '@orkestrel/agent'
622
+ import { createAgent, createAuthority, createScope } from '@orkestrel/agent'
623
+
624
+ declare const provider: ProviderInterface // calls remember, then switch to returns, then answers
625
+ declare function confirm(question: string): Promise<boolean> // the host's approval prompt
626
+
627
+ const agent = createAgent(provider, {
628
+ builtins: ['memo', 'remember', 'switch'],
629
+ // remember is consequential, so its allow verdict asks the approver.
630
+ authority: createAuthority({
631
+ fallback: { zone: 'default', verdict: 'allow' },
632
+ ask: (context) => confirm(`Run ${context.call.name}?`),
633
+ }),
634
+ // remember writes only a listed name, and switch selects only a listed id.
635
+ scope: createScope({ name: 'desk', memos: ['tone'], workspaces: ['orders', 'returns'] }),
636
+ })
637
+ agent.context.workspaces.add({ id: 'orders' }).write('orders.txt', 'Order 42 is paid.')
638
+ agent.context.workspaces.add({ id: 'returns' }).write('returns.txt', 'Return 7 is open.')
639
+ await agent.generate({ prompt: { content: 'Keep replies short, then open the returns.' } })
640
+ agent.context.memos.memo('tone')?.origin // { conversation: the run's conversation id }
641
+ agent.context.workspaces.active?.id // 'orders': the switch selected returns for this conversation
642
+ ```
643
+
644
+ A built-in refuses a call with `ToolError` code `'ARGUMENTS'`, and the loop feeds the text back as the call's failure result. A refused name gets a text that names its subject and lists the names the model can use, `No SUBJECT has that name. Use one of: "NAME".`, where each `NAME` placeholder is a name the model can use and the `SUBJECT` placeholder is `skill you can load` for `load`, `skill you loaded` for `unload`, `memo you can read` for `memo`, `memo you may write` for `remember`, and `workspace you can select` for `switch`. It lists at most `BUILTIN_LIMITS.candidates` names, in registry order, and past that cap a closing sentence points to the index in the prompt. With no name to list, it reads `No SUBJECT has that name, and none is available now.` The text echoes no argument, so an absent name and a name outside the ceiling read byte for byte the same. A `remember` or `switch` call that reaches its handler while the ceiling's list is absent or empty refuses with a sentence saying the host lists none. The tool's own argument contract runs first and refuses a missing, undeclared, or over-limit member before the handler runs. The following call names a skill the registry doesn't hold:
645
+
646
+ ```ts
647
+ import type { ProviderInterface } from '@orkestrel/agent'
648
+ import { createAgent, createAuthority } from '@orkestrel/agent'
649
+
650
+ declare const provider: ProviderInterface // calls load with { skill: 'billing' }, then answers
651
+ declare function log(error: string | undefined): void
652
+
653
+ const agent = createAgent(provider, {
654
+ builtins: ['load'],
655
+ authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
656
+ })
657
+ agent.context.skills.add({
658
+ name: 'refunds',
659
+ description: 'Refunds a paid order.',
660
+ content: 'Confirm.',
661
+ })
662
+ agent.emitter.on('tool', (_call, result) => log(result.success ? undefined : result.error))
663
+ await agent.generate({ prompt: { content: 'Look up the billing rules.' } })
664
+ // 'No skill you can load has that name. Use one of: "refunds".'
665
+ ```
666
+
504
667
  ### Selecting the messages a turn carries
505
668
 
506
- A selection handler chooses the conversation messages the next prompt carries for one user request. It has two homes: `AgentOptions.select` is the agent default, forwarded as `AgentContextOptions.select`, and the active scope's `select` overrides it while that scope is active. The `context.select` method resolves `scope?.select ?? default` once per call and returns `undefined` when neither home holds a handler, so the default path awaits nothing before the first provider request.
669
+ 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.
507
670
 
508
- 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)`, which carries `selection.messages` in place of `view()` after the unchanged system and context messages, and 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.
671
+ 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.
509
672
 
510
673
  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.
511
674
 
@@ -609,19 +772,21 @@ Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https
609
772
 
610
773
  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.
611
774
 
612
- Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. An active `respond` call owns a run on that conversation whose request, the newest message, is that call's request or one of the ledger's notes. A run that no active `respond` call owns, such as a direct call to the agent's `generate` method or a run on another conversation, gets a faulted selection when its newest message is a user message: the selection's `fault` is a `LedgerError` with code `'REQUEST'`, so under the default `strict` the run rejects with that error before it reaches the provider, and under `strict: false` the agent emits `fault` and builds the prompt from the whole view of the run's conversation with no records. Either way the ledger asks its judge nothing for that run. When its newest message isn't a user message, the run gets no selection and builds from the whole view. Calibration admits no run, so a run during the `calibrate` method, or during the calibration that opens a `respond` call, is one that no active `respond` call owns.
775
+ 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.
613
776
 
614
777
  The method has the following pieces, each named by its export:
615
778
 
616
779
  - **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.
617
780
  - **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.
618
781
  - **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.
619
- - **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the built head (the system message and the context message), the tail, and the copy of the request turn that carries the records inside a token budget: the `capacity` option less the `predict` option, times the `prompt` share, less the overhead cost of the gauge and held back by the `LEDGER_SCALE_DRIFT` constant, of which the seed tail takes at most the `tail` share. The `tail` share bounds only the seed. 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 tool definitions, the ledger calibrates before its first pass, and the `calibrate` method measures the price on demand and records the digest of the definitions it priced. 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. 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.
782
+ - **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.
620
783
  - **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.
621
- - **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 gauged direct run fits its listing to the same allowance; 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 latest 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.
784
+ - **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.
622
785
  - **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.
623
- - **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 scope advertises no tools makes at most one model generation, whatever the agent's `limit`. 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`.
624
- - **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. A scope a host applies during the pass decides what it advertises, and a pass whose scope advertises a tool runs on to the agent's `limit`. 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. 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.
786
+ - **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`.
787
+ - **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.
788
+ - **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.
789
+ - **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.
625
790
  - **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.
626
791
 
627
792
  Display references identify sources within the rendered records while the line keeps the stored identity:
@@ -649,50 +814,13 @@ The application supplies the following through `LedgerOptions`:
649
814
  - the desk topics, through the `topics` option;
650
815
  - the lookups, through the `lookups` option, each a tool the model calls and a reading handler that names the ids and the owners in its result;
651
816
  - 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;
652
- - the agent options, through the `agent` option, whose `authority` member gates every lookup and write and is required with writes;
817
+ - 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`;
653
818
  - the capacity, through the `capacity` option, the model's context window in tokens;
654
819
  - the generation cap, through the `predict` option, in tokens with thinking included, 0 by default and less than `capacity`;
655
820
  - the thinking of the first pass, through the boolean `think` option; the answer pass always runs with thinking off;
656
821
  - 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.
657
822
 
658
- The method has the following documented limits:
659
-
660
- - **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.
661
- - **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.
662
- - **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.
663
- - **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.
664
- - **A direct run beside a request is refused.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`. Under the default `strict`, any other run no active `respond` call owns whose newest message is a user message rejects with `LedgerError` `'REQUEST'` before it reaches the provider: a direct run between requests, one during the calibration that opens a call, and a run on another conversation during a call. Under `strict: false` that run emits `fault` and goes on over the whole view with no ledger selection; a run on another conversation then adds its turns and usage to that call's gauge readings, shares its repeat stop, and can reach the lookup tools, and the `recall` tool when that call's request offers it, because the ledger's agent shares its scope across runs, and those tools read the ledger's `conversation`.
665
- - **A run no call owns keeps no request state.** The ledger holds a request's state in a `LedgerRequest` value from the start of its `respond` call until the call settles. A run that no `respond` call owns, including a run during calibration, reads no request's state: its lookup and `recall` calls run with no repeat stop, recall limit, or close rule, and none of its turns reach a gauge reading.
666
- - **A seed tool message counts as successful.** A tool message the application adds to the conversation has no recorded result, so the ledger reads it as a successful lookup and files it as a fact, and its reading handler decides what the result names.
667
- - **An abort during calibration rejects.** When the caller's signal aborts while the ledger calibrates, the `respond` method rejects with the abort reason instead of resolving a partial result; after calibration, an abort ends the request partial and skips the answer pass.
668
- - **A foreign signal rejects before anything is appended.** A `signal` that isn't a native `AbortSignal` rejects the `respond` method with a `ContractError` before the request is appended, and the ledger stays free for a later request.
669
- - **The seed selection stays fixed.** Only the messages added before the first request form the seed tail. Each completed exchange follows it in the window: a request as it was sent and its last call-free assistant reply, excluding notes, calls, and tool messages. A blank or missing last call-free reply carries nothing. A committed partial reply means one the conversation stored; it remains eligible after an abort, but a cut landing mid-stream stores no reply and carries nothing. A host statement reaches the prompt through records or recall, and neither that statement nor a host lookup after the reply erases the exchange. Two non-empty call-free assistants without a ledger note between them make the pairing ambiguous, so it carries nothing; answer-pass notes establish the separation between a partial first reply and the final answer. A host that removes a request must remove every turn of it too, because nothing stored links a reply to its request: a surviving reply can read as the earlier request's when that request has no reply of its own, or when the removed request's answer pass left its note behind. The seed messages and the selected record lines stay the same on every rung of the window, and only a seed stub's `shown` or `hidden` state follows the rung.
670
- - **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup with different text or an empty result replaces it, a write names it among its `targets`, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows, and a line an earlier copy showed stays in the prompt until the window empties or falls past that copy.
671
- - **The ledger refuses no over-window prompt.** A request, a lookup result, or the whole view a faulted selection builds from can exceed the room the `capacity` option leaves. Recall results and recovery digests are fitted, but unbounded mandatory content can still reach the provider, and the provider's own context limit decides what happens to it. A provider that refuses an over-long prompt fails the pass, so lower `capacity`, or set `AgentOptions.window` on an agent you drive yourself, to fold the conversation first.
672
- - **A host edit after fitting enters unpriced.** A memo written during a request's first pass enters the rebuilt answer context and consumes its fitting allowance. A later host edit, after fitting, remains unpriced. The context can change while the selected seed and request stay the same.
673
- - **A heading inside a record line reads as one.** A record line and the request copy render a message's or a lookup's text verbatim, so text holding a `## Rules` or `## Request` heading reads as one inside the user turn's copy; it changes no filing and never reaches `system`, and no delimiter marks such text.
674
- - **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.
675
- - **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.
676
- - **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.
677
- - **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 tool definitions the calibration request carried, or over the ledger's definitions at construction when the `gauge` option supplied the price. A ledger hydrated with definitions of another digest, because an application added, removed, or edited a lookup or a write, 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. The comparison reads the definitions at construction, so a tool a host adds to the agent's tools afterward isn't compared. 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 and is never compared.
678
- - **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.
679
- - **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.
680
- - **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.
681
- - **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.
682
- - **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.
683
- - **A changed lookup empties the window.** A later finding of the same lookup with different text or an empty result retires the source the window holds, and that empties the window. That prompt holds the derived newest pair and a copy of every selected line, so it doesn't extend the prompt before it. A lookup repeated with the same text retires nothing, so the prompt extends the one before it.
684
- - **A write empties the window when it retires a held line.** A write that retires a source the window holds empties the window, as a changed lookup does, so that prompt doesn't extend the prompt before it.
685
- - **A write retires whole findings.** A write retires every earlier finding that names a target, so a list read loses its untouched rows too and the model reads again. A user statement about the record never retires through `targets`; the judge's supersession files that.
686
- - **A partial request can hold a completed write.** A write stores its result before the next turn, so an abort or a failure later in the request leaves the write in the conversation, retiring the reads it made stale. A host that discards a partial request's snapshot loses that write while its store keeps the change, so it must save the snapshot after any request that ran a write.
687
- - **A write's handler must be total.** A handler that throws marks the write failed, so a write that changed the store files nothing and leaves the stale read live, and a handler that misses a target leaves that target's earlier reads live. Pass the same `writes` on every hydrate: the ledger reads the targets again from the conversation, so a changed list brings retired reads back live.
688
- - **A write that changed nothing stubs as such.** A seed write whose handler reads no change stubs as `changed nothing`, where an empty lookup stubs as `no record`.
689
- - **A cut stream stores nothing.** A stream cut before its reply is stored leaves the window standing, so a follow-up that refers to the cut text reads against the last completed reply.
690
- - **Recall fitting depends on its measured price.** Runtime recall and recovery allow the `LEDGER_SCALE_DRIFT` margin over the larger of the gauge's marginal rate and this request's measured rate. A provider whose new text costs more than that bound is outside the capacity guarantee. Missing usage remains estimated; no exact tokenizer preflight is available. A long earlier reply still affects window admission, but never vetoes a runtime recall that fits.
691
- - **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.
692
- - **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.
693
- - **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.
694
- - **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.
695
- - **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.
823
+ For the ledger's documented limits, see [Limits](#limits).
696
824
 
697
825
  ### Customizing the format (the cascade)
698
826
 
@@ -963,6 +1091,7 @@ The following table lists the helpers the root declares:
963
1091
  | `removeEntries` | function | `<K>(keys: readonly K[], remove: (key: K) => boolean) => boolean` | Removes each key through a single-key remover and folds the outcomes, so a batch `remove` reports whether the whole batch applied. |
964
1092
  | `collectExchanges` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects whole exchanges, joining every exchange spanned by a tool group. |
965
1093
  | `collectToolGroups` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects each assistant message that carries calls together with the tool messages that answer it, then each run of tool messages that no assistant message owns. |
1094
+ | `findToolCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
966
1095
  | `hasCalls` | function | `(message: Pick<Message, 'calls'>) => boolean` | Checks whether a message carries at least one tool call. |
967
1096
  | `renderJSON` | function | `(value: unknown) => string \| undefined` | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
968
1097
  | `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. |
@@ -1033,22 +1162,29 @@ The following table lists the types the providers module declares:
1033
1162
 
1034
1163
  The following table lists the constants the providers module declares:
1035
1164
 
1036
- | Name | Kind | Signature | Summary |
1037
- | ---------------------------- | ----- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1038
- | `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`. |
1039
- | `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. |
1040
- | `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. |
1041
- | `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. |
1042
- | `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. |
1043
- | `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`. |
1044
- | `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. |
1045
- | `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. |
1046
- | `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. |
1047
- | `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. |
1048
- | `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. |
1049
- | `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`. |
1050
- | `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. |
1051
- | `SYSTEM_ONE_PATH` | const | `"/v1/systemone"` | Names the System One decision endpoint shared by compatible servers. |
1165
+ | Name | Kind | Signature | Summary |
1166
+ | ---------------------------- | ----- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1167
+ | `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`. |
1168
+ | `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. |
1169
+ | `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. |
1170
+ | `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. |
1171
+ | `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. |
1172
+ | `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`. |
1173
+ | `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. |
1174
+ | `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. |
1175
+ | `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. |
1176
+ | `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. |
1177
+ | `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. |
1178
+ | `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`. |
1179
+ | `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. |
1180
+ | `SYSTEM_ONE_PATH` | const | `"/v1/systemone"` | Names the System One decision endpoint shared by compatible servers. |
1181
+ | `RELAY_OPTION_KEYS` | const | `readonly ["provider", "authorize", "limit", "system", "tools"]` | Lists the members `RelayOptions` declares, frozen — the keys `createRelay` admits. |
1182
+ | `RELAY_PROVIDER_KEYS` | const | `readonly ["url", "parser", "timeout", "replay", "fetch", "headers"]` | Lists the members `RelayProviderOptions` declares, frozen — the keys the `RelayProvider` constructor admits. |
1183
+ | `RELAY_STREAM_KEYS` | const | `readonly ["provider", "request", "signal"]` | Lists the members `RelayStreamOptions` declares, frozen — the keys the `RelayStream` constructor admits. |
1184
+ | `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. |
1185
+ | `JUDGE_INPUT_KEYS` | const | `readonly ["url", "path", "model", "batch", "timeout", "fetch", "headers"]` | Lists the members `AgentJudgeInput` declares, frozen — the keys the `AgentJudge` constructor admits. |
1186
+ | `SYSTEM_ONE_OPTION_KEYS` | const | `readonly ["url", "model", "timeout", "fetch", "headers"]` | Lists the members `SystemOneJudgeOptions` declares, frozen — the keys the `SystemOneJudge` constructor admits. |
1187
+ | `STREAM_OPTION_KEYS` | const | `readonly ["think", "schema"]` | Lists the members `ProviderStreamOptions` declares, frozen — the keys the `generate` and `stream` methods of an `AgentProvider` admits. |
1052
1188
 
1053
1189
  #### Errors
1054
1190
 
@@ -1186,10 +1322,15 @@ The following table lists the types the conversations module declares:
1186
1322
 
1187
1323
  The following table lists the constants the conversations module declares:
1188
1324
 
1189
- | Name | Kind | Signature | Summary |
1190
- | --------------------------- | ----- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1191
- | `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. |
1192
- | `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. |
1325
+ | Name | Kind | Signature | Summary |
1326
+ | --------------------------- | ----- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1327
+ | `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. |
1328
+ | `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. |
1329
+ | `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. |
1330
+ | `CONVERSATION_MANAGER_KEYS` | const | `readonly ["summarize", "keep", "sections", "store"]` | Lists the members `ConversationManagerOptions` declares, frozen — the keys the `ConversationManager` constructor admits. |
1331
+ | `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. |
1332
+ | `COMPACT_OPTION_KEYS` | const | `readonly ["keep", "sections", "signal"]` | Lists the members `CompactOptions` declares, frozen — the keys the `compact` method of a `Conversation` admits. |
1333
+ | `REFERENCE_OPTION_KEYS` | const | `readonly ["label", "messages"]` | Lists the members `ConversationReferenceOptions` declares, frozen — the keys the `reference` method of a `Conversation` admits. |
1193
1334
 
1194
1335
  #### Errors
1195
1336
 
@@ -1252,7 +1393,7 @@ The following table lists the guards the conversations module declares:
1252
1393
  | ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1253
1394
  | `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
1254
1395
  | `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. |
1255
- | `isMessageInput` | function | `(value: unknown) => value is MessageInput` | Checks whether a value is a message input a conversation can store: a string `content`, and `calls`, `call`, `images`, and `thinking` absent or of their declared types. |
1396
+ | `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. |
1256
1397
  | `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. |
1257
1398
  | `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. |
1258
1399
  | `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. |
@@ -1280,49 +1421,61 @@ The `contexts` module holds the turn context, its instruction and scope managers
1280
1421
 
1281
1422
  The following table lists the types the contexts module declares:
1282
1423
 
1283
- | Name | Kind | Signature | Summary |
1284
- | ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1285
- | `ContextErrorCode` | type | `'SNAPSHOT' \| 'IMAGES'` | Names the machine-readable condition a `ContextError` reports. |
1286
- | `ContextSectionFormat` | interface | `{ open?, render?, close? }` | Overrides one context section's format — an `open` / `render` / `close` trio that frames a section in the `AgentContext` build cascade: a top line rendered once before the items, a per-item rendering, and a bottom line rendered once after the items. |
1287
- | `InstructionInterface` | interface | `{ id, name, content, priority, override? }` | Represents an immutable instruction — a named directive a richer context places between the system prompt and the conversation, ordered by descending `priority`. |
1288
- | `InstructionInput` | interface | `{ name, content, priority?, override? }` | Carries the minimal data to author an `InstructionInterface` — the `id` is minted by the `InstructionManagerInterface` that stores it, so a caller supplies only `name` / `content` and an optional `priority`. Default: `0`. |
1289
- | `InstructionManagerEventMap` | type | `{ readonly add: readonly [instruction: InstructionInterface]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of an `InstructionManagerInterface` — the mutation moments a fire-and-forget observer subscribes to through `manager.emitter.on`. |
1290
- | `InstructionManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createInstructionManager` — the reserved `on` hooks plus an optional per-section format override. |
1291
- | `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. |
1292
- | `ScopeFilter` | interface | `{ instructions?, skills?, memos?, tools?, files? }` | Lists the per-category allow-lists a `ScopeInterface` carries — an optional `readonly string[]` for `instructions`, for `skills`, for `memos`, for `tools`, and for `files`, 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`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. |
1293
- | `Selection` | interface | `{ messages, judgments, usage?, fault? }` | Carries the conversation part of the next prompt and the receipt for it. |
1294
- | `SelectionHandler` | type | `(conversation: ConversationInterface, request: Message, signal: AbortSignal) => Promise<Selection>` | Chooses the conversation messages the next prompt carries for one user request. |
1295
- | `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). |
1296
- | `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. |
1297
- | `ScopeManagerEventMap` | type | `{ readonly add: readonly [scope: ScopeInterface]; readonly remove: readonly [id: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `ScopeManagerInterface` — analogous to `InstructionManagerEventMap`, but keyed by the minted `id`, so `add` never reports a replaced scope. |
1298
- | `ScopeManagerOptions` | interface | `{ on?, error? }` | Configures `createScopeManager` — the reserved `on` hooks: initial listeners for the manager's `ScopeManagerEventMap`, wired at construction. |
1299
- | `ScopeManagerInterface` | interface | `{ emitter, count, add(), scope(), scopes(), remove(), clear() }` | Registers reusable `ScopeInterface` instances keyed by their minted `id` — `add` mints + stores one (never overwrites), `scopes()` lists them in insertion order. |
1300
- | `Memo` | interface | `{ id, name, description, content, time, origin? }` | Holds one memo revision: a durable fact kept across conversations. |
1301
- | `MemoOrigin` | interface | `{ conversation, message? }` | Names where a memo revision came from: a conversation and, optionally, one of its messages. |
1302
- | `MemoInput` | interface | `{ name, description, content, origin? }` | Carries the data to author a `Memo` revision; the `MemoManagerInterface` that stores it mints the `id` and records the `time`. |
1303
- | `MemoSnapshot` | interface | `{ id, memos }` | Holds every revision of a memo set, oldest first; the current memo of a name is its last revision. |
1304
- | `MemoManagerEventMap` | type | `{ readonly add: readonly [memo: Memo]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `MemoManagerInterface`: the mutation moments a fire-and-forget observer subscribes to through `manager.emitter.on`. |
1305
- | `MemoManagerOptions` | interface | `{ id?, on?, error?, format?, snapshot? }` | Configures `createMemoManager`: the memo set's identity, the reserved `on` hooks, a section format override, and a snapshot to restore. |
1306
- | `MemoManagerInterface` | interface | `{ id, emitter, count, open, close, add(), memo(), memos(), history(), render(), remove(), clear(), snapshot() }` | Registers `Memo` revisions keyed by `name`: `add` appends a revision when the text changed, `memo(name)` returns the current revision, and `history(name)` lists every revision. |
1307
- | `MemoStoreInterface` | interface | `{ get(), set(), delete() }` | Persists a `MemoSnapshot` by its memo set id — the async `get` / `set` / `delete` primitives, holding no expiry, the memo twin of `ConversationStoreInterface`. |
1308
- | `MemoSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseMemoStore` persists — a memo set `id` plus its `MemoSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. |
1309
- | `Skill` | interface | `{ id, name, description, content, files }` | Holds one skill: a name and a description the index shows, the instructions loading adds, and bundled files. |
1310
- | `SkillInput` | interface | `{ name, description, content, files? }` | Carries the data to author a `Skill`; the `SkillManagerInterface` that stores it mints the `id` and each file. |
1311
- | `SkillManagerEventMap` | type | `{ readonly add: readonly [skill: Skill]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `SkillManagerInterface`, as `InstructionManagerEventMap` does for instructions. |
1312
- | `SkillManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createSkillManager`: the reserved `on` hooks and a section format override. |
1313
- | `SkillManagerInterface` | interface | `{ emitter, count, open, close, add(), skill(), skills(), render(), remove(), clear() }` | Registers `Skill` values keyed by `name`: `add` mints each skill and overwrites a same-name skill, last write wins, while `skills()` lists them in insertion order. |
1314
- | `AgentContextOptions` | interface | `{ system?, tools?, instructions?, skills?, memos?, workspaces?, scope?, conversations?, select? }` | Configures `createAgentContext` — the optional system prompt plus the pre-built managers to reuse: an `instructions` registry, a `skills` registry, a `memos` set, a `workspaces` registry (the only document channel), a `conversations` registry (the message source), a `tools` registry (the loop's advertise and dispatch surface), and an initial `scope`. |
1315
- | `AgentContextInterface` | interface | `{ system, instructions, skills, memos, workspaces, messages, conversations, tools, scope, apply(), select(), build() }` | Assembles a turn's provider input from the system prompt + the context managers + the conversation, applying the active scope per category. |
1424
+ | Name | Kind | Signature | Summary |
1425
+ | ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1426
+ | `ContextErrorCode` | type | `'SNAPSHOT' \| 'IMAGES'` | Names the machine-readable condition a `ContextError` reports. |
1427
+ | `ContextSectionFormat` | interface | `{ open?, render?, close? }` | Overrides one context section's format — an `open` / `render` / `close` trio that frames a section in the `AgentContext` build cascade: a top line rendered once before the items, a per-item rendering, and a bottom line rendered once after the items. |
1428
+ | `ContextBuildOptions` | interface | `{ selection?, scope?, disclosure?, switchable? }` | Selects what one `build` call renders. |
1429
+ | `InstructionInterface` | interface | `{ id, name, content, priority, override? }` | Represents an immutable instruction — a named directive a richer context places between the system prompt and the conversation, ordered by descending `priority`. |
1430
+ | `InstructionInput` | interface | `{ name, content, priority?, override? }` | Carries the minimal data to author an `InstructionInterface` — the `id` is minted by the `InstructionManagerInterface` that stores it, so a caller supplies only `name` / `content` and an optional `priority`. Default: `0`. |
1431
+ | `InstructionManagerEventMap` | type | `{ readonly add: readonly [instruction: InstructionInterface]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of an `InstructionManagerInterface` — the mutation moments a fire-and-forget observer subscribes to through `manager.emitter.on`. |
1432
+ | `InstructionManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createInstructionManager` — the reserved `on` hooks plus an optional per-section format override. |
1433
+ | `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. |
1434
+ | `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. |
1435
+ | `Selection` | interface | `{ messages, judgments, usage?, fault? }` | Carries the conversation part of the next prompt and the receipt for it. |
1436
+ | `SelectionHandler` | type | `(conversation: ConversationInterface, request: Message, signal: AbortSignal) => Promise<Selection>` | Chooses the conversation messages the next prompt carries for one user request. |
1437
+ | `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). |
1438
+ | `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. |
1439
+ | `ScopeManagerEventMap` | type | `{ readonly add: readonly [scope: ScopeInterface]; readonly remove: readonly [id: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `ScopeManagerInterface` — analogous to `InstructionManagerEventMap`, but keyed by the minted `id`, so `add` never reports a replaced scope. |
1440
+ | `ScopeManagerOptions` | interface | `{ on?, error? }` | Configures `createScopeManager` — the reserved `on` hooks: initial listeners for the manager's `ScopeManagerEventMap`, wired at construction. |
1441
+ | `ScopeManagerInterface` | interface | `{ emitter, count, add(), scope(), scopes(), remove(), clear() }` | Registers reusable `ScopeInterface` instances keyed by their minted `id` — `add` mints + stores one (never overwrites), `scopes()` lists them in insertion order. |
1442
+ | `Memo` | interface | `{ id, name, description, content, time, origin? }` | Holds one memo revision: a durable fact kept across conversations. |
1443
+ | `MemoOrigin` | interface | `{ conversation, message? }` | Names where a memo revision came from: a conversation and, optionally, one of its messages. |
1444
+ | `MemoInput` | interface | `{ name, description, content, origin? }` | Carries the data to author a `Memo` revision; the `MemoManagerInterface` that stores it mints the `id` and records the `time`. |
1445
+ | `MemoSnapshot` | interface | `{ id, memos }` | Holds every revision of a memo set, oldest first; the current memo of a name is its last revision. |
1446
+ | `MemoManagerEventMap` | type | `{ readonly add: readonly [memo: Memo]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `MemoManagerInterface`: the mutation moments a fire-and-forget observer subscribes to through `manager.emitter.on`. |
1447
+ | `MemoManagerOptions` | interface | `{ id?, on?, error?, format?, snapshot? }` | Configures `createMemoManager`: the memo set's identity, the reserved `on` hooks, a section format override, and a snapshot to restore. |
1448
+ | `MemoManagerInterface` | interface | `{ id, emitter, count, open, close, add(), memo(), memos(), history(), render(), remove(), clear(), snapshot() }` | Registers `Memo` revisions keyed by `name`: `add` appends a revision when the text changed, `memo(name)` returns the current revision, and `history(name)` lists every revision. |
1449
+ | `MemoStoreInterface` | interface | `{ get(), set(), delete() }` | Persists a `MemoSnapshot` by its memo set id — the async `get` / `set` / `delete` primitives, holding no expiry, the memo twin of `ConversationStoreInterface`. |
1450
+ | `MemoSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseMemoStore` persists — a memo set `id` plus its `MemoSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. |
1451
+ | `Skill` | interface | `{ id, name, description, content, tools, files }` | Holds one skill: a name and a description the index shows, the body a run shows, the tools it holds back, and bundled files. |
1452
+ | `SkillInput` | interface | `{ name, description, content, tools?, files? }` | Carries the data to author a `Skill`; the `SkillManagerInterface` that stores it mints the `id` and each file. |
1453
+ | `AgentDisclosure` | interface | `{ skills, workspace? }` | Holds what one run shows within its ceiling: the loaded skills and the selected workspace. |
1454
+ | `SkillManagerEventMap` | type | `{ readonly add: readonly [skill: Skill]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `SkillManagerInterface`, as `InstructionManagerEventMap` does for instructions. |
1455
+ | `SkillManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createSkillManager`: the reserved `on` hooks and a section format override. |
1456
+ | `SkillManagerInterface` | interface | `{ emitter, count, open, close, add(), skill(), skills(), render(), remove(), clear() }` | Registers `Skill` values keyed by `name`: `add` mints each skill and overwrites a same-name skill, last write wins, while `skills()` lists them in insertion order. |
1457
+ | `AgentContextOptions` | interface | `{ system?, tools?, instructions?, skills?, memos?, workspaces?, scope?, conversations?, select? }` | Configures `createAgentContext` — the optional system prompt plus the pre-built managers to reuse: an `instructions` registry, a `skills` registry, a `memos` set, a `workspaces` registry (the only document channel), a `conversations` registry (the message source), a `tools` registry (the loop's advertise and dispatch surface), and an initial `scope`. |
1458
+ | `AgentContextInterface` | interface | `{ system, instructions, skills, memos, workspaces, messages, conversations, tools, scope, apply(), select(), build() }` | Assembles a turn's provider input from the system prompt + the context managers + the conversation, applying the active scope per category. |
1316
1459
 
1317
1460
  #### Constants
1318
1461
 
1319
1462
  The following table lists the constants the contexts module declares:
1320
1463
 
1321
- | Name | Kind | Signature | Summary |
1322
- | -------------------------- | ----- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1323
- | `WORKSPACE_SECTION_HEADER` | const | `"## Workspace"` | Names the section header the `build()` method of `AgentContext` renders the active workspace's text files under — `'## Workspace'`, the line that opens the workspace section of the user context message that follows the system message. |
1324
- | `MEMO_SECTION_HEADER` | const | `"## Memos"` | Names the built-in section header a `MemoManagerInterface` renders its index under — `'## Memos'`, the `open` value when no `format.open` overrides it. |
1325
- | `SKILL_SECTION_HEADER` | const | `"## Skills"` | Names the built-in section header a `SkillManagerInterface` renders its index under — `'## Skills'`, the `open` value when no `format.open` overrides it. |
1464
+ | Name | Kind | Signature | Summary |
1465
+ | -------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1466
+ | `WORKSPACE_SECTION_HEADER` | const | `"## Workspace"` | Names the section header the `build()` method of `AgentContext` renders the active workspace's text files under — `'## Workspace'`, the line that opens the workspace section of the user context message that follows the system message. |
1467
+ | `LOADED_SECTION_HEADER` | const | `"## Loaded skills"` | Names the section header the loaded skills' bodies render under at the end of the system message — `'## Loaded skills'`. |
1468
+ | `WORKSPACE_INDEX_HEADER` | const | `"## Workspaces"` | Names the section header the admitted workspace ids render under in the user context message — `'## Workspaces'`, rendered only while a run can select a workspace. |
1469
+ | `MEMO_SECTION_HEADER` | const | `"## Memos"` | Names the built-in section header a `MemoManagerInterface` renders its index under — `'## Memos'`, the `open` value when no `format.open` overrides it. |
1470
+ | `SKILL_SECTION_HEADER` | const | `"## Skills"` | Names the built-in section header a `SkillManagerInterface` renders its index under — `'## Skills'`, the `open` value when no `format.open` overrides it. |
1471
+ | `SCOPE_KEYS` | const | `readonly ["name", "select", "instructions", "skills", "memos", "tools", "files", "workspaces"]` | Lists the members `ScopeInput` declares, frozen — the keys a `Scope` is built from. |
1472
+ | `SCOPE_FILTER_KEYS` | const | `readonly ["instructions", "skills", "memos", "tools", "files", "workspaces"]` | Lists the members `ScopeFilter` declares, frozen — the keys the `narrow` method of a scope admits. |
1473
+ | `CONTEXT_OPTION_KEYS` | const | `readonly ["system", "tools", "instructions", "skills", "memos", "workspaces", "scope", "conversations", "select"]` | Lists the members `AgentContextOptions` declares, frozen — the keys the `AgentContext` constructor admits. |
1474
+ | `BUILD_OPTION_KEYS` | const | `readonly ["selection", "scope", "disclosure", "switchable"]` | Lists the members `ContextBuildOptions` declares, frozen — the keys the `build` method of an `AgentContext` admits. |
1475
+ | `INSTRUCTION_MANAGER_KEYS` | const | `readonly ["on", "error", "format"]` | Lists the members `InstructionManagerOptions` declares, frozen — the keys the `InstructionManager` constructor admits. |
1476
+ | `MEMO_MANAGER_KEYS` | const | `readonly ["id", "on", "error", "format", "snapshot"]` | Lists the members `MemoManagerOptions` declares, frozen — the keys the `MemoManager` constructor admits. |
1477
+ | `SCOPE_MANAGER_KEYS` | const | `readonly ["on", "error"]` | Lists the members `ScopeManagerOptions` declares, frozen — the keys the `ScopeManager` constructor admits. |
1478
+ | `SKILL_MANAGER_KEYS` | const | `readonly ["on", "error", "format"]` | Lists the members `SkillManagerOptions` declares, frozen — the keys the `SkillManager` constructor admits. |
1326
1479
 
1327
1480
  #### Errors
1328
1481
 
@@ -1353,45 +1506,57 @@ The following table lists the factories the contexts module declares:
1353
1506
 
1354
1507
  The following table lists the classes the contexts module declares:
1355
1508
 
1356
- | Name | Kind | Signature | Summary |
1357
- | -------------------- | ----- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1358
- | `Instruction` | class | `new (input: InstructionInput) => InstructionInterface` | Represents an immutable named directive — an `InstructionInterface` assembled once from its input (`name` / `content` and an optional `priority`), the `id` minted at construction. Default: `0` for `priority`. |
1359
- | `InstructionManager` | class | `new (options?: InstructionManagerOptions) => InstructionManagerInterface` | Registers the immutable `Instruction` instances a richer context assembles a directives block from — keyed by `name` so adding an instruction whose name is already stored overwrites it, last write wins, and listed by descending `priority`, carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1360
- | `Scope` | class | `new (input: ScopeInput) => ScopeInterface` | Represents a named, immutable filter over a richer context's items — an optional allow-list per category (`instructions` / `skills` / `memos` / `tools` / `files`), 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`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. `narrow` composes a tighter child by set intersection. |
1361
- | `ScopeManager` | class | `new (options?: ScopeManagerOptions) => ScopeManagerInterface` | Registers the named filters a richer context reuses — immutable `Scope` instances keyed by their minted `id`, in insertion order, where `add` always mints and stores rather than overwriting, and an observable `emitter` reports each change. |
1362
- | `MemoManager` | class | `new (options?: MemoManagerOptions) => MemoManagerInterface` | Registers the revisions of a memo set — durable facts keyed by `name`, where a same-name `add` with changed text appends a revision and the earlier ones stay readable — carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1363
- | `MemoryMemoStore` | class | `new () => MemoStoreInterface` | Implements the `MemoStoreInterface` in memory — a process-lifetime map of `MemoSnapshot` records keyed by memo set id, the store `createMemoryMemoStore` builds. |
1364
- | `DatabaseMemoStore` | class | `new (table: TableInterface<MemoSnapshotRow>) => MemoStoreInterface` | Backs a `MemoStoreInterface` with one table of the `databases` layer — a memo set's durable state is a row holding the snapshot as one opaque JSON column, narrowed back on `get` by `isMemoSnapshot`. |
1365
- | `SkillManager` | class | `new (options?: SkillManagerOptions) => SkillManagerInterface` | Registers the skills a host supplies — instruction bundles keyed by `name`, listed in insertion order, where adding a skill whose name is already stored overwrites it, last write wins — carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1366
- | `AgentContext` | class | `new (options?: AgentContextOptions) => AgentContextInterface` | Assembles a provider request from the richer turn context — the optional system prompt, the observable context managers (instructions / skills / memos / workspaces), the `ConversationManagerInterface` message source whose active conversation is `messages`, the `ToolManagerInterface` registry, and an active `ScopeInterface` changed through `AgentContextInterface.apply`. `build()` folds the system prompt, the scoped instructions, and the skills index into one system message, the memos index and the active workspace's text into one `user` context message after it, then the conversation, and never reads `tools`. |
1509
+ | Name | Kind | Signature | Summary |
1510
+ | -------------------- | ----- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1511
+ | `Instruction` | class | `new (input: InstructionInput) => InstructionInterface` | Represents an immutable named directive — an `InstructionInterface` assembled once from its input (`name` / `content` and an optional `priority`), the `id` minted at construction. Default: `0` for `priority`. |
1512
+ | `InstructionManager` | class | `new (options?: InstructionManagerOptions) => InstructionManagerInterface` | Registers the immutable `Instruction` instances a richer context assembles a directives block from — keyed by `name` so adding an instruction whose name is already stored overwrites it, last write wins, and listed by descending `priority`, carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1513
+ | `Scope` | class | `new (input: ScopeInput) => ScopeInterface` | Represents a named, immutable filter over a richer context's items — an optional allow-list per category (`instructions` / `skills` / `memos` / `tools` / `files` / `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. `narrow` composes a tighter child by set intersection. |
1514
+ | `ScopeManager` | class | `new (options?: ScopeManagerOptions) => ScopeManagerInterface` | Registers the named filters a richer context reuses — immutable `Scope` instances keyed by their minted `id`, in insertion order, where `add` always mints and stores rather than overwriting, and an observable `emitter` reports each change. |
1515
+ | `MemoManager` | class | `new (options?: MemoManagerOptions) => MemoManagerInterface` | Registers the revisions of a memo set — durable facts keyed by `name`, where a same-name `add` with changed text appends a revision and the earlier ones stay readable — carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1516
+ | `MemoryMemoStore` | class | `new () => MemoStoreInterface` | Implements the `MemoStoreInterface` in memory — a process-lifetime map of `MemoSnapshot` records keyed by memo set id, the store `createMemoryMemoStore` builds. |
1517
+ | `DatabaseMemoStore` | class | `new (table: TableInterface<MemoSnapshotRow>) => MemoStoreInterface` | Backs a `MemoStoreInterface` with one table of the `databases` layer — a memo set's durable state is a row holding the snapshot as one opaque JSON column, narrowed back on `get` by `isMemoSnapshot`. |
1518
+ | `SkillManager` | class | `new (options?: SkillManagerOptions) => SkillManagerInterface` | Registers the skills a host supplies — instruction bundles keyed by `name`, listed in insertion order, where adding a skill whose name is already stored overwrites it, last write wins — carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1519
+ | `AgentContext` | class | `new (options?: AgentContextOptions) => AgentContextInterface` | Assembles a provider request from the richer turn context — the optional system prompt, the observable context managers (instructions / skills / memos / workspaces), the `ConversationManagerInterface` message source whose active conversation is `messages`, the `ToolManagerInterface` registry, and an active `ScopeInterface` changed through `AgentContextInterface.apply`. `build()` folds the system prompt, the scoped instructions, the skills index, and the shown skills' bodies into one system message, the memos index and the rendered workspace's text into one `user` context message after it, then the conversation, and never reads `tools`. |
1367
1520
 
1368
1521
  #### Helpers
1369
1522
 
1370
1523
  The following table lists the helpers the contexts module declares:
1371
1524
 
1372
- | Name | Kind | Signature | Summary |
1373
- | ------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1374
- | `renderFencedFile` | function | `(path: string, language: string, content: string) => string` | Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line over a language-tagged fence, the framing the active-workspace text-file render of `AgentContext` emits. |
1375
- | `renderSection` | function | `<T>(open: string, members: readonly T[], render: (member: T) => string, close: string \| undefined) => string \| undefined` | Renders one context section — the resolved `open`, each item's rendering, and the resolved `close` when one exists, blank-line joined; `undefined` when the section has no items. |
1376
- | `attachImages` | function | `(message: Message, payloads: readonly string[]) => Message` | Copies a message with image data merged onto its `images` — the message's own images first, then the attached data, keeping every other field and never mutating the original. |
1377
- | `attachUserImages` | function | `(conversation: readonly Message[], payloads: readonly string[]) => readonly Message[]` | Attaches image data to a conversation's last user message — the turn a vision provider reads images off — as a new array with that one message replaced by its carrying copy, and unchanged when there is no data or no user turn. |
1378
- | `collectImageData` | function | `(files: readonly FileInterface[]) => readonly string[]` | Collects the `base64` payload of the image files in a workspace file list — the data an agent context attaches to the last user message. |
1379
- | `intersectKeys` | function | `(parent: readonly string[] \| undefined, child: readonly string[] \| undefined) => readonly string[] \| undefined` | Intersects two scope category lists under the "`undefined` is the universal set" rule — a fresh copy that can only tighten, and the primitive a scope narrows through. |
1380
- | `renderIndexEntry` | function | `(entry: Pick<Memo, 'name' \| 'description'>) => string` | Renders one index line for a memo or a skill — `- name: description`, the built-in `render` of the memo and skill managers. |
1525
+ | Name | Kind | Signature | Summary |
1526
+ | -------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1527
+ | `renderFencedFile` | function | `(path: string, language: string, content: string) => string` | Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line over a language-tagged fence, the framing the active-workspace text-file render of `AgentContext` emits. |
1528
+ | `renderSection` | function | `<T>(open: string, members: readonly T[], render: (member: T) => string, close: string \| undefined) => string \| undefined` | Renders one context section — the resolved `open`, each item's rendering, and the resolved `close` when one exists, blank-line joined; `undefined` when the section has no items. |
1529
+ | `attachImages` | function | `(message: Message, payloads: readonly string[]) => Message` | Copies a message with image data merged onto its `images` — the message's own images first, then the attached data, keeping every other field and never mutating the original. |
1530
+ | `attachUserImages` | function | `(conversation: readonly Message[], payloads: readonly string[]) => readonly Message[]` | Attaches image data to a conversation's last user message — the turn a vision provider reads images off — as a new array with that one message replaced by its carrying copy, and unchanged when there is no data or no user turn. |
1531
+ | `collectImageData` | function | `(files: readonly FileInterface[]) => readonly string[]` | Collects the `base64` payload of the image files in a workspace file list — the data an agent context attaches to the last user message. |
1532
+ | `intersectKeys` | function | `(parent: readonly string[] \| undefined, child: readonly string[] \| undefined) => readonly string[] \| undefined` | Intersects two scope category lists under the "`undefined` is the universal set" rule — a fresh copy that can only tighten, and the primitive a scope narrows through. |
1533
+ | `intersectFilters` | function | `(parent: ScopeFilter \| undefined, child: ScopeFilter \| undefined) => ScopeFilter` | Intersects two scope filters list by list; an absent side constrains nothing. |
1534
+ | `resolveWorkspace` | function | `(workspaces: WorkspaceManagerInterface, selected: string \| undefined, allowed: readonly string[] \| undefined) => WorkspaceInterface \| undefined` | Resolves the workspace a run renders and acts on: the one `selected` names, else the registry's active one, kept only while `allowed` admits its id. |
1535
+ | `renderIndexEntry` | function | `(entry: Pick<Memo, 'name' \| 'description'>) => string` | Renders one index line for a memo or a skill — `- name: description`, the built-in `render` of the memo and skill managers. |
1536
+ | `renderIndexLine` | function | `(text: string) => string` | Renders one index line from its text as `- text`, with each run of line-break code points as one space. |
1537
+ | `renderSkillBody` | function | `(skill: Pick<Skill, 'name' \| 'content'>) => string` | Renders one loaded skill's body: `### name`, a blank line, then its content. |
1538
+ | `requireRecordInput` | function | `(input: unknown, contract: Pick<ContractInterface<unknown>, 'is' \| 'audit' \| 'schema'>, owner: string, shape: string) => void` | Checks a stored record's input against its exact contract, and throws a `ContractError` coded `'structure'` when it fails. |
1381
1539
 
1382
1540
  #### Validators
1383
1541
 
1384
1542
  The following table lists the guards the contexts module declares:
1385
1543
 
1386
- | Name | Kind | Signature | Summary |
1387
- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1388
- | `isMemo` | function | `(value: unknown) => value is Memo` | Checks whether a value is a stored memo revision: a record with a string `id`, `name`, `description`, and `content`, a finite `time`, and an optional `origin`. |
1389
- | `memoShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo revision exactly. |
1390
- | `memoSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; memos: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo set exactly: an unknown key refuses. |
1391
- | `memoContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>>` | Reads the faults of a refused memo revision. |
1392
- | `memoSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; memos: readonly Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>[]; } & {}>>` | Reads the faults of a refused memo snapshot. |
1393
- | `isMemoOrigin` | function | `(value: unknown) => value is MemoOrigin` | Checks whether a value is a memo's origin: a record with a string `conversation` and an optional string `message`. |
1394
- | `isMemoSnapshot` | function | `(value: unknown) => value is MemoSnapshot` | Checks whether a value is a stored memo set: a record with a string `id` and a dense `memos` array of `isMemo` values. |
1544
+ | Name | Kind | Signature | Summary |
1545
+ | -------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1546
+ | `isMemo` | function | `(value: unknown) => value is Memo` | Checks whether a value is a stored memo revision: a record with a string `id`, `name`, `description`, and `content`, a finite `time`, and an optional `origin`. |
1547
+ | `memoShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo revision exactly. |
1548
+ | `memoSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; memos: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo set exactly: an unknown key refuses. |
1549
+ | `memoContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>>` | Reads the faults of a refused memo revision. |
1550
+ | `memoSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; memos: readonly Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>[]; } & {}>>` | Reads the faults of a refused memo snapshot. |
1551
+ | `memoInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a memo input exactly: the members of a stored revision less the `id` and `time` the manager mints, each taken from `memoShape`. |
1552
+ | `instructionInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ name: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; priority: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; override: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes an instruction input exactly: a string `name` and `content`, and an optional finite `priority` and string `override`. |
1553
+ | `skillInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; files: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>>; }, boolean \| ContractShape>` | Describes a skill input exactly: a string `name`, `description`, and `content`, optional `tools` names, and optional `files`. |
1554
+ | `memoInputContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ name: string; description: string; content: string; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>>` | Admits a memo input exactly, and reads the faults of a refused one. |
1555
+ | `instructionInputContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ name: string; content: string; } & { priority?: number; override?: string; }>>` | Admits an instruction input exactly, and reads the faults of a refused one. |
1556
+ | `skillInputContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ name: string; description: string; content: string; } & { tools?: readonly string[]; files?: readonly unknown[]; }>>` | Admits a skill input exactly, and reads the faults of a refused one. |
1557
+ | `isMemoOrigin` | function | `(value: unknown) => value is MemoOrigin` | Checks whether a value is a memo's origin: a record with a string `conversation` and an optional string `message`. |
1558
+ | `isMemoSnapshot` | function | `(value: unknown) => value is MemoSnapshot` | Checks whether a value is a stored memo set: a record with a string `id` and a dense `memos` array of `isMemo` values. |
1559
+ | `isScope` | function | `(value: unknown) => value is ScopeInterface` | Checks whether a value implements `ScopeInterface`; total, each member read one time, any implementation admitted. |
1395
1560
 
1396
1561
  ### Agents module
1397
1562
 
@@ -1401,53 +1566,68 @@ The `agents` module holds the loop, the authority gate, the channel, and the dur
1401
1566
 
1402
1567
  The following table lists the types the agents module declares:
1403
1568
 
1404
- | Name | Kind | Signature | Summary |
1405
- | ------------------------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1406
- | `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). |
1407
- | `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`. |
1408
- | `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]; }` | 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. |
1409
- | `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`. |
1410
- | `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. |
1411
- | `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`. |
1412
- | `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. |
1413
- | `AgentErrorCode` | type | `'APPROVER' \| 'AUTHORITY' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'SCHEMA' \| 'WINDOW'` | Names the machine-readable agent approver, authority, concurrency, limit, registry, schema, and window failures. |
1414
- | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1415
- | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1416
- | `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`. |
1417
- | `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. |
1418
- | `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
1419
- | `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`. |
1420
- | `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. |
1421
- | `AgentAnswer` | interface | `{ id, approved }` | Carries a page's answer to one `ask` frame; only `approved: true` approves. |
1422
- | `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. |
1423
- | `AgentOptions` | interface | `{ on?, error?, system?, tools?, instructions?, skills?, memos?, workspaces?, scope?, limit?, timeout?, budget?, allowance?, scheduler?, signal?, authority?, conversations?, window?, strict?, select? }` | 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, and the `strict` switch that aborts the run on an automatic-compaction summarizer failure instead of the lenient default. |
1424
- | `AgentRunOptions` | interface | `{ think?, schema?, limit?, timeout?, budget?, allowance?, signal?, conversation?, prompt? }` | 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, and `prompt` adds the run's user turn to it. |
1425
- | `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. |
1426
- | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1427
- | `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
1428
- | `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
1429
- | `AuthorityRule` | interface | `{ match, zone, verdict, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1430
- | `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
1431
- | `AuthorityOptions` | interface | `{ rules?, fallback, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
1432
- | `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. |
1433
- | `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
1434
- | `AgentJobInput` | interface | `{ provider, messages?, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, children? }` | Represents a JSON-serializable agent job — the descriptor a durable queue or runner runs. Its non-serializable pieces (the provider, tools, authority, scheduler) are referenced by name and resolved to live objects through an `AgentRegistryInterface` at handler time, while its data fields (the seed `messages`, `system`, `limit`, `timeout`, and a token `budget` ceiling) carry directly. |
1435
- | `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1436
- | `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
1437
- | `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`. |
1438
- | `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`. |
1569
+ | Name | Kind | Signature | Summary |
1570
+ | ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1571
+ | `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). |
1572
+ | `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. |
1573
+ | `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. |
1574
+ | `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`. |
1575
+ | `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. |
1576
+ | `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`. |
1577
+ | `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. |
1578
+ | `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`. |
1579
+ | `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. |
1580
+ | `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. |
1581
+ | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1582
+ | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1583
+ | `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`. |
1584
+ | `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. |
1585
+ | `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
1586
+ | `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`. |
1587
+ | `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. |
1588
+ | `AgentAnswer` | interface | `{ id, approved }` | Carries a page's answer to one `ask` frame; only `approved: true` approves. |
1589
+ | `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. |
1590
+ | `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`. |
1591
+ | `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. |
1592
+ | `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. |
1593
+ | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1594
+ | `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
1595
+ | `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
1596
+ | `AuthorityRule` | interface | `{ match, zone, verdict, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1597
+ | `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
1598
+ | `AuthorityOptions` | interface | `{ rules?, fallback, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
1599
+ | `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. |
1600
+ | `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
1601
+ | `BuiltinNote` | interface | `{ loaded, unloaded, remembered, switched }` | Holds the model-facing texts the built-ins return on success. |
1602
+ | `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. |
1603
+ | `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1604
+ | `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. |
1605
+ | `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`. |
1606
+ | `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`. |
1439
1607
 
1440
1608
  #### Constants
1441
1609
 
1442
1610
  The following table lists the constants the agents module declares:
1443
1611
 
1444
- | Name | Kind | Signature | Summary |
1445
- | ------------------------ | ----- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1446
- | `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`. |
1447
- | `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. |
1448
- | `SCOPE_NOTE` | const | `"it is not one of the listed tools. Use a listed tool or answer with what you have."` | Holds the model-facing text the loop writes after a tool name in the denial result of a call outside the active scope's tool allow-list or whose name no definition advertises this turn. |
1449
- | `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
1450
- | `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. |
1612
+ | Name | Kind | Signature | Summary |
1613
+ | -------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1614
+ | `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`. |
1615
+ | `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. |
1616
+ | `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. |
1617
+ | `BUILTIN_NOTES` | const | `BuiltinNote` | Holds the texts the built-ins return on success — `loaded`, `unloaded`, `remembered`, and `switched` — frozen. |
1618
+ | `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. |
1619
+ | `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. |
1620
+ | `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. |
1621
+ | `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. |
1622
+ | `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. |
1623
+ | `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
1624
+ | `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. |
1625
+ | `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. |
1626
+ | `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. |
1627
+ | `AUTHORITY_OPTION_KEYS` | const | `readonly ["rules", "fallback", "ask"]` | Lists the members `AuthorityOptions` declares, frozen — the keys the `Authority` constructor admits. |
1628
+ | `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. |
1629
+ | `QUEUE_OPTION_KEYS` | const | `readonly ["registry", "partial", "concurrency", "retries", "timeout", "store"]` | Lists the members `AgentQueueOptions` declares, frozen — the keys `createAgentQueue` admits. |
1630
+ | `RUNNER_OPTION_KEYS` | const | `readonly ["registry", "partial", "concurrency", "retries", "timeout"]` | Lists the members `AgentRunnerOptions` declares, frozen — the keys `createAgentRunner` admits. |
1451
1631
 
1452
1632
  #### Errors
1453
1633
 
@@ -1464,16 +1644,25 @@ The following table lists the errors the agents module declares and the guards t
1464
1644
 
1465
1645
  The following table lists the agent wire shapes and the contracts compiled from them:
1466
1646
 
1467
- | Name | Kind | Signature | Summary |
1468
- | --------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
1469
- | `agentFrameShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["token"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["think"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [true]>; name: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [false]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["usage"]>; usage: import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>; estimate: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["ask"]>; id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; zone: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["finish"]>; content: import("@orkestrel/contract").StringShape; partial: import("@orkestrel/contract").BooleanShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; layer: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").LiteralShape<readonly ["meter", "budget", "model"]>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["error"]>; }, boolean \| ContractShape>]>` | Describes the agent frame wire — one exact object per `AgentFrame` arm, discriminated by `category`. |
1470
- | `agentPromptShape` | const | `import("@orkestrel/contract").ObjectShape<{ content: import("@orkestrel/contract").StringShape; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; }, boolean \| ContractShape>` | Describes the agent prompt wire — the `content` and optional `images` of one user turn, read by the run's `prompt` option and by a page's request body. |
1471
- | `agentJobShape` | const | `import("@orkestrel/contract").ObjectShape<{ provider: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>>; system: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; authority: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; scheduler: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; limit: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; timeout: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; budget: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; children: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>>; }, boolean \| ContractShape>` | Describes a durable agent job — the record `AgentRegistry.build` checks exactly, so a misspelled key refuses instead of running an agent without it. |
1472
- | `agentAnswerShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; approved: import("@orkestrel/contract").BooleanShape; }, boolean \| ContractShape>` | Describes the agent answer wire — the `id` of one `ask` frame and a boolean `approved`. |
1473
- | `agentFrameContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ category: "token"; content: string; } & {}> \| Readonly<{ category: "think"; content: string; } & {}> \| Readonly<{ category: "tool"; success: true; name: string; } & {}> \| Readonly<{ category: "tool"; success: false; } & {}> \| Readonly<{ category: "usage"; usage: Readonly<{ prompt: number; completion: number; total: number; } & {}>; estimate: number; } & {}> \| Readonly<{ category: "ask"; id: string; name: string; zone: string; arguments: string; } & {}> \| Readonly<{ category: "finish"; content: string; partial: boolean; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; layer?: "budget" \| "meter" \| "model"; }> \| Readonly<{ category: "error"; } & {}>>` | Validates and projects agent frames at a JSON wire boundary. |
1474
- | `agentPromptContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ content: string; } & { images?: readonly string[]; }>>` | Validates and projects agent prompts at the run's `prompt` option and a page's request body. |
1475
- | `agentJobContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ provider: string; } & { messages?: readonly Readonly<{ role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; system?: string; tools?: readonly string[]; authority?: string; scheduler?: string; limit?: number; timeout?: number; budget?: number; children?: readonly { readonly [k: string]: import("@orkestrel/contract").JSONValue; }[]; }>>` | Checks a durable agent job exactly at `AgentRegistry.build`. |
1476
- | `agentAnswerContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; approved: boolean; } & {}>>` | Validates and projects a page's answers to `ask` frames at a JSON wire boundary. |
1647
+ | Name | Kind | Signature | Summary |
1648
+ | ---------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1649
+ | `agentFrameShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["token"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["think"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [true]>; name: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [false]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["usage"]>; usage: import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>; estimate: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["ask"]>; id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; zone: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["finish"]>; content: import("@orkestrel/contract").StringShape; partial: import("@orkestrel/contract").BooleanShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; layer: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").LiteralShape<readonly ["meter", "budget", "model"]>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["error"]>; }, boolean \| ContractShape>]>` | Describes the agent frame wire — one exact object per `AgentFrame` arm, discriminated by `category`. |
1650
+ | `agentPromptShape` | const | `import("@orkestrel/contract").ObjectShape<{ content: import("@orkestrel/contract").StringShape; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; }, boolean \| ContractShape>` | Describes the agent prompt wire — the `content` and optional `images` of one user turn, read by the run's `prompt` option and by a page's request body. |
1651
+ | `agentJobShape` | const | `import("@orkestrel/contract").ObjectShape<{ provider: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ 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>; role: import("@orkestrel/contract").LiteralShape<readonly ["user", "assistant", "tool"]>; }, boolean \| ContractShape>>>; system: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; authority: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; scheduler: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; limit: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; timeout: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; budget: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; scope: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ skills: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; memos: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; workspaces: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; workspace: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; builtins: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").LiteralShape<readonly ["load", "unload", "memo", "remember", "switch"]>>>; children: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>>; }, boolean \| ContractShape>` | Describes a durable agent job — the record `AgentRegistry.build` checks exactly, so a misspelled key refuses instead of running an agent without it. |
1652
+ | `agentAnswerShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; approved: import("@orkestrel/contract").BooleanShape; }, boolean \| ContractShape>` | Describes the agent answer wire — the `id` of one `ask` frame and a boolean `approved`. |
1653
+ | `loadToolShape` | const | `import("@orkestrel/contract").ObjectShape<{ skill: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>` | Describes the arguments of the `load` and `unload` built-ins — one `skill` name, non-empty and at most `BUILTIN_LIMITS.name` code points. |
1654
+ | `memoToolShape` | const | `import("@orkestrel/contract").ObjectShape<{ name: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>` | Describes the arguments of the `memo` built-in — one memo `name`, non-empty and at most `BUILTIN_LIMITS.name` code points. |
1655
+ | `rememberToolShape` | const | `import("@orkestrel/contract").ObjectShape<{ name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>` | Describes the arguments of the `remember` built-in — a memo `name`, the one-line `description` the memos index shows, and the `content`, each non-empty and within its `BUILTIN_LIMITS` cap. |
1656
+ | `switchToolShape` | const | `import("@orkestrel/contract").ObjectShape<{ workspace: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>` | Describes the arguments of the `switch` built-in — one `workspace` id, non-empty and at most `BUILTIN_LIMITS.name` code points. |
1657
+ | `agentFrameContract` | const | `ContractInterface<Readonly<{ category: "token"; content: string; } & {}> \| Readonly<{ category: "think"; content: string; } & {}> \| Readonly<{ category: "tool"; success: true; name: string; } & {}> \| Readonly<{ category: "tool"; success: false; } & {}> \| Readonly<{ category: "usage"; usage: Readonly<{ prompt: number; completion: number; total: number; } & {}>; estimate: number; } & {}> \| Readonly<{ category: "ask"; id: string; name: string; zone: string; arguments: string; } & {}> \| Readonly<{ category: "finish"; content: string; partial: boolean; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; layer?: "budget" \| "meter" \| "model"; }> \| Readonly<{ category: "error"; } & {}>>` | Validates and projects agent frames at a JSON wire boundary. |
1658
+ | `agentPromptContract` | const | `ContractInterface<Readonly<{ content: string; } & { images?: readonly string[]; }>>` | Validates and projects agent prompts at the run's `prompt` option and a page's request body. |
1659
+ | `agentJobContract` | const | `ContractInterface<Readonly<{ provider: string; } & { messages?: readonly Readonly<{ content: string; role: "assistant" \| "tool" \| "user"; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; system?: string; tools?: readonly string[]; authority?: string; scheduler?: string; limit?: number; timeout?: number; budget?: number; scope?: Readonly<{ skills: readonly string[]; memos: readonly string[]; workspaces: readonly string[]; } & {}>; workspace?: string; builtins?: readonly ("load" \| "memo" \| "remember" \| "switch" \| "unload")[]; children?: readonly { readonly [k: string]: import("@orkestrel/contract").JSONValue; }[]; }>>` | Checks a durable agent job exactly at `AgentRegistry.build`. |
1660
+ | `agentAnswerContract` | const | `ContractInterface<Readonly<{ id: string; approved: boolean; } & {}>>` | Validates and projects a page's answers to `ask` frames at a JSON wire boundary. |
1661
+ | `loadToolContract` | const | `ContractInterface<Readonly<{ skill: string; } & {}>>` | Checks the arguments of the `load` and `unload` built-ins; its schema is the parameters they advertise. |
1662
+ | `memoToolContract` | const | `ContractInterface<Readonly<{ name: string; } & {}>>` | Checks the arguments of the `memo` built-in; its schema is the parameters it advertises. |
1663
+ | `rememberToolContract` | const | `ContractInterface<Readonly<{ name: string; description: string; content: string; } & {}>>` | Checks the arguments of the `remember` built-in; its schema is the parameters it advertises. |
1664
+ | `switchToolContract` | const | `ContractInterface<Readonly<{ workspace: string; } & {}>>` | Checks the arguments of the `switch` built-in; its schema is the parameters it advertises. |
1665
+ | `builtinToolContracts` | const | `Readonly<Record<AgentBuiltin, Readonly<{ shape: ContractShape; contract: ContractInterface<Readonly<Record<string, unknown>>>; }>>>` | Pairs each built-in's argument shape, which its tool's door compiles, with its compiled contract, keyed by its `AgentBuiltin` name, frozen. |
1477
1666
 
1478
1667
  #### Factories
1479
1668
 
@@ -1488,6 +1677,7 @@ The following table lists the factories the agents module declares:
1488
1677
  | `createAgentRegistry` | function | `(options: AgentRegistryOptions) => AgentRegistryInterface` | Creates a registry of live providers, tools, authorities, and schedulers whose `build` method returns a seeded, signal-wired `AgentInterface` from a serializable job. |
1489
1678
  | `createAgentQueue` | function | `(options: AgentQueueOptions) => QueueInterface<AgentJobInput, AgentResult>` | Creates a durable, bounded-concurrency agent-job queue — a `QueueInterface` over serializable values of `AgentJobInput` that composes `createQueue`: each job is rehydrated through the `registry` into a live `AgentInterface`, run to its `AgentResult`, and subjected to the partial-as-configurable-failure policy. |
1490
1679
  | `createAgentRunner` | function | `(options: AgentRunnerOptions) => RunnerInterface<AgentJobInput, AgentResult>` | Creates an agent-job runner — a `RunnerInterface` over serializable values of `AgentJobInput` that composes `createRunner` (one-shot, ordered, fail-fast), each unit rehydrated through the `registry` and subjected to the partial policy. The runner also carries sub-agent fan-out: a parent job's handler can call `controller.spawn` with a child job. |
1680
+ | `createBuiltinTool` | function | `(name: AgentBuiltin, execute: ToolOptions['execute']) => ToolInterface` | Creates the tool a run serves for one built-in: its description and annotations from `BUILTIN_TOOLS`, its argument shape from `builtinToolContracts`, and the given handler. |
1491
1681
 
1492
1682
  #### Classes
1493
1683
 
@@ -1506,36 +1696,49 @@ The following table lists the classes the agents module declares:
1506
1696
 
1507
1697
  The following table lists the helpers the agents module declares:
1508
1698
 
1509
- | Name | Kind | Signature | Summary |
1510
- | --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1511
- | `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. |
1512
- | `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. |
1513
- | `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. |
1514
- | `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
1515
- | `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. |
1516
- | `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. |
1517
- | `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). |
1518
- | `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. |
1519
- | `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. |
1520
- | `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. |
1521
- | `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. |
1522
- | `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. |
1523
- | `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. |
1524
- | `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. |
1525
- | `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. |
1526
- | `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. |
1527
- | `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`. |
1528
- | `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. |
1529
- | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a positive safe integer, or throws a coded error. |
1530
- | `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. |
1531
- | `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. |
1532
- | `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. |
1533
- | `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. |
1534
- | `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. |
1535
- | `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. |
1536
- | `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. |
1537
- | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1538
- | `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. |
1699
+ | Name | Kind | Signature | Summary |
1700
+ | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1701
+ | `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. |
1702
+ | `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. |
1703
+ | `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. |
1704
+ | `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
1705
+ | `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. |
1706
+ | `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. |
1707
+ | `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). |
1708
+ | `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. |
1709
+ | `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. |
1710
+ | `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. |
1711
+ | `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. |
1712
+ | `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. |
1713
+ | `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. |
1714
+ | `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. |
1715
+ | `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. |
1716
+ | `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. |
1717
+ | `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. |
1718
+ | `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. |
1719
+ | `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`. |
1720
+ | `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. |
1721
+ | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a positive safe integer, or throws a coded error. |
1722
+ | `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. |
1723
+ | `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. |
1724
+ | `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. |
1725
+ | `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. |
1726
+ | `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. |
1727
+ | `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. |
1728
+ | `requireScope` | function | `(value: unknown) => ScopeInterface \| undefined` | Returns a scope a run can bind, or throws a `ContractError` coded `'placement'`; `undefined` passes through. |
1729
+ | `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. |
1730
+ | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1731
+ | `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. |
1732
+ | `collectBuiltinDefinitions` | function | `(options: Pick<AgentOptions, 'builtins'>) => readonly ToolDefinition[]` | Collects the definitions of the tools an agent serves itself, as a run advertises them. |
1733
+ | `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. |
1734
+ | `requireWorkspace` | function | `(value: unknown) => string \| undefined` | Returns a `workspace` option unchanged, or throws a `ContractError` coded `'placement'`; `undefined` passes through. |
1735
+ | `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. |
1736
+ | `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. |
1737
+ | `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. |
1738
+ | `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`). |
1739
+ | `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`. |
1740
+ | `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. |
1741
+ | `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. |
1539
1742
 
1540
1743
  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.
1541
1744
 
@@ -1577,10 +1780,12 @@ const runnerHandler = fanout.execute.bind(fanout)
1577
1780
 
1578
1781
  The following table lists the guards the agents module declares:
1579
1782
 
1580
- | Name | Kind | Signature | Summary |
1581
- | --------------------- | -------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1582
- | `isAuthorityVerdict` | function | `(value: unknown) => value is AuthorityVerdict` | Checks whether a value is an authority verdict: `allow`, `ask`, or `deny`. |
1583
- | `isAuthorityDecision` | function | `(value: unknown) => value is AuthorityDecision` | Checks whether a value is an authority decision: an object whose `zone` is a string, whose `verdict` is `allow`, `ask`, or `deny`, and whose `reason` is absent or a string. |
1783
+ | Name | Kind | Signature | Summary |
1784
+ | --------------------- | -------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1785
+ | `isAgentBuiltin` | function | `(value: unknown) => value is AgentBuiltin` | Checks whether a value names a built-in: `load`, `unload`, `memo`, `remember`, or `switch`. |
1786
+ | `isAuthorityVerdict` | function | `(value: unknown) => value is AuthorityVerdict` | Checks whether a value is an authority verdict: `allow`, `ask`, or `deny`. |
1787
+ | `isAuthorityDecision` | function | `(value: unknown) => value is AuthorityDecision` | Checks whether a value is an authority decision: an object whose `zone` is a string, whose `verdict` is `allow`, `ask`, or `deny`, and whose `reason` is absent or a string. |
1788
+ | `isAgentCaller` | function | `(value: unknown) => value is AgentCaller` | Checks whether a value is an agent caller: a plain record whose own keys are exactly `workspace` and `files`, whose `workspace` is `undefined` or an object, and whose `files` is `undefined` or an array of strings. |
1584
1789
 
1585
1790
  ### Ledgers module
1586
1791
 
@@ -1590,90 +1795,97 @@ The `ledgers` module serves a conversation through event-sourced records: the `L
1590
1795
 
1591
1796
  The following table lists the types the ledger declares, each with its shape:
1592
1797
 
1593
- | Name | Kind | Signature | Summary |
1594
- | ------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1595
- | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1596
- | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1597
- | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1598
- | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1599
- | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1600
- | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1601
- | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1602
- | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1603
- | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1604
- | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1605
- | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1606
- | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1607
- | `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. |
1608
- | `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. |
1609
- | `LedgerWrite` | interface | `{ tool, read }` | Carries one application write: the `consequential` tool the model calls and the handler that reads its results. |
1610
- | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result, targets? }` | Carries one successful lookup result as the ledger read it. |
1611
- | `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. |
1612
- | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1613
- | `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. |
1614
- | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1615
- | `LedgerGaugeSnapshot` | interface | `{ digest }` | Carries a stored gauge: its price and the digest of the tool definitions that price measured. |
1616
- | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'strict' \| 'authority'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1617
- | `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. |
1618
- | `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. |
1619
- | `LedgerExchangeSnapshot` | interface | `{ request, copy?, reply, lines }` | Carries the sent request text, stored pair ids, and sentence placements of one exchange. |
1620
- | `LedgerWindowSnapshot` | interface | `{ digest, exchanges, amendments }` | Carries a nonempty exchange window, its message, copy, and receipt checksum, and its accepted edges. |
1621
- | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1622
- | `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. |
1623
- | `LedgerListing` | interface | `{ result, lines, groups, turn }` | Carries a recall result, its accepted whole groups, lookup line translations, and provider-turn position. |
1624
- | `LedgerRecovery` | interface | `{ digest, omitted }` | Carries the answer note and the partial messages omitted from its prompt. |
1625
- | `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() }` | 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. |
1626
- | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1627
- | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1628
- | `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. |
1629
- | `LedgerReceipt` | interface | `{ key, title, source, sentence }` | Identifies an original sentence at one record placement. |
1630
- | `LedgerOccurrence` | interface | `{}` | Carries a rendered sentence with its record placement. |
1631
- | `LedgerExchange` | interface | `{ request, reply, lines }` | Carries a completed request copy, its stored reply, and the sentences the copy rendered. |
1632
- | `LedgerDraft` | interface | `{ copy, lines, evidence, window }` | Carries a planned copy and its validity evidence to request settlement. |
1633
- | `LedgerEvidence` | interface | `{ messages, amendments }` | Captures held message identities and the accepted edges used to validate their copies. |
1634
- | `LedgerRenderResult` | interface | `{ text, lines }` | Carries rendered record text and its sentences in emission order. |
1635
- | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1636
- | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1637
- | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1638
- | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1639
- | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1640
- | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1641
- | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1642
- | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1643
- | `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. |
1644
- | `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. |
1645
- | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1646
- | `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. |
1647
- | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1648
- | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1649
- | `GaugeCall` | interface | `{ estimate, spared?, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1650
- | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1651
- | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1652
- | `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. |
1653
- | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION' \| 'WRITE'` | Names the machine-readable conditions a `LedgerError` error reports. |
1798
+ | Name | Kind | Signature | Summary |
1799
+ | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1800
+ | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1801
+ | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1802
+ | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1803
+ | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1804
+ | `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. |
1805
+ | `LedgerNote` | interface | `{ cue, results, repeat, closure, overflow }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1806
+ | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1807
+ | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1808
+ | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1809
+ | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1810
+ | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1811
+ | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1812
+ | `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. |
1813
+ | `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. |
1814
+ | `LedgerWrite` | interface | `{ tool, read }` | Carries one application write: the `consequential` tool the model calls and the handler that reads its results. |
1815
+ | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result, targets? }` | Carries one successful lookup result as the ledger read it. |
1816
+ | `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. |
1817
+ | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1818
+ | `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. |
1819
+ | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1820
+ | `LedgerGaugeSnapshot` | interface | `{ digest }` | Carries a stored gauge: its price and the digest of the tool definitions that price measured. |
1821
+ | `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. |
1822
+ | `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. |
1823
+ | `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. |
1824
+ | `LedgerExchangeSnapshot` | interface | `{ request, copy?, reply, lines }` | Carries the sent request text, stored pair ids, and sentence placements of one exchange. |
1825
+ | `LedgerWindowSnapshot` | interface | `{ digest, exchanges, amendments }` | Carries a nonempty exchange window, its message, copy, and receipt checksum, and its accepted edges. |
1826
+ | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1827
+ | `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. |
1828
+ | `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. |
1829
+ | `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. |
1830
+ | `LedgerListing` | interface | `{ result, lines, groups, turn }` | Carries a recall result, its accepted whole groups, lookup line translations, and provider-turn position. |
1831
+ | `LedgerRecovery` | interface | `{ digest, omitted }` | Carries the answer note and the partial messages omitted from its prompt. |
1832
+ | `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. |
1833
+ | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1834
+ | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1835
+ | `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. |
1836
+ | `LedgerReceipt` | interface | `{ key, title, source, sentence }` | Identifies an original sentence at one record placement. |
1837
+ | `LedgerOccurrence` | interface | `{}` | Carries a rendered sentence with its record placement. |
1838
+ | `LedgerExchange` | interface | `{ request, reply, lines }` | Carries a completed request copy, its stored reply, and the sentences the copy rendered. |
1839
+ | `LedgerDraft` | interface | `{ copy, lines, evidence, window }` | Carries a planned copy and its validity evidence to request settlement. |
1840
+ | `LedgerEvidence` | interface | `{ messages, amendments }` | Captures held message identities and the accepted edges used to validate their copies. |
1841
+ | `LedgerRenderResult` | interface | `{ text, lines }` | Carries rendered record text and its sentences in emission order. |
1842
+ | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1843
+ | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1844
+ | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1845
+ | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1846
+ | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1847
+ | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1848
+ | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1849
+ | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1850
+ | `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. |
1851
+ | `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. |
1852
+ | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1853
+ | `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. |
1854
+ | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1855
+ | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1856
+ | `GaugeCall` | interface | `{ estimate, spared?, added?, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1857
+ | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1858
+ | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1859
+ | `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. |
1860
+ | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION' \| 'WRITE' \| 'OVERFLOW'` | Names the machine-readable conditions a `LedgerError` error reports. |
1654
1861
 
1655
1862
  #### Constants
1656
1863
 
1657
1864
  The following table lists the constants that hold the ledger's categories, record keys, measured wording, shares, and limits:
1658
1865
 
1659
- | Name | Kind | Signature | Summary |
1660
- | --------------------------- | ----- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1661
- | `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. |
1662
- | `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
1663
- | `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the records render. |
1664
- | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1665
- | `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
1666
- | `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
1667
- | `LEDGER_RECALL_LABELS` | const | `Readonly<{ request: "Earlier request:"; reply: "Earlier reply:"; }>` | Labels recalled conversation text by its origin. |
1668
- | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1669
- | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1670
- | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt and tail shares. |
1671
- | `DEFAULT_LEDGER_LIMIT` | const | `8` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
1672
- | `DEFAULT_RECALL_LIMIT` | const | `2` | Caps the `recall` calls of one request at 2 calls. |
1673
- | `LEDGER_SLICE` | const | `5` | Sets the 5 milliseconds a paced classifier files between host turns. |
1674
- | `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. |
1675
- | `LEDGER_WORD` | const | `RegExp` | Matches a run of letters and digits, which the ledger reads as one word. |
1676
- | `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. |
1866
+ | Name | Kind | Signature | Summary |
1867
+ | --------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1868
+ | `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. |
1869
+ | `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
1870
+ | `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the records render. |
1871
+ | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1872
+ | `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
1873
+ | `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
1874
+ | `LEDGER_RECALL_LABELS` | const | `Readonly<{ request: "Earlier request:"; reply: "Earlier reply:"; }>` | Labels recalled conversation text by its origin. |
1875
+ | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1876
+ | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1877
+ | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt, tail, and skills shares. |
1878
+ | `DEFAULT_LEDGER_LIMIT` | const | `8` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
1879
+ | `DEFAULT_RECALL_LIMIT` | const | `2` | Caps the `recall` calls of one request at 2 calls. |
1880
+ | `LEDGER_SLICE` | const | `5` | Sets the 5 milliseconds a paced classifier files between host turns. |
1881
+ | `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. |
1882
+ | `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. |
1883
+ | `LEDGER_WORD` | const | `RegExp` | Matches a run of letters and digits, which the ledger reads as one word. |
1884
+ | `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. |
1885
+ | `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. |
1886
+ | `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. |
1887
+ | `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. |
1888
+ | `GAUGE_OPTION_KEYS` | const | `readonly ["scale", "overhead", "capacity", "predict", "replay"]` | Lists the members `GaugeOptions` declares, frozen — the keys the `Gauge` constructor admits. |
1677
1889
 
1678
1890
  #### Errors
1679
1891
 
@@ -1735,7 +1947,6 @@ The following table lists the pure helpers that read text, project and select re
1735
1947
  | `normalizeWord` | function | `(word: string) => string` | Normalizes a run of letters and digits to the one form each of its cases folds to. |
1736
1948
  | `buildRecords` | function | `(input: LedgerProjectionInput) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
1737
1949
  | `selectRecords` | function | `(projection: LedgerProjection, request: LedgerProjectionRequest) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
1738
- | `findLedgerCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
1739
1950
  | `collectProjectionIds` | function | `(projection: LedgerProjection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
1740
1951
  | `scanAmendments` | function | `(amendments: ReadonlyMap<string, readonly string[]>, start: string, admit: (id: string) => boolean) => readonly string[]` | Scans admitted amendments in breadth-first order without revisiting a message. |
1741
1952
  | `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
@@ -1751,11 +1962,12 @@ The following table lists the pure helpers that read text, project and select re
1751
1962
  | `renderLedgerPinned` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one owner record under a `###` heading, which the records nest under their one `## Records` heading. |
1752
1963
  | `splitTopic` | function | `(topic: string) => readonly string[]` | Splits a recall topic at its joints. |
1753
1964
  | `cutListing` | function | `(entries: readonly string[], room: number, kind?: 'older' \| 'more', first?: boolean) => string` | Cuts entries to a room and names how many it left out. |
1965
+ | `cutWorkspaceSample` | function | `(head: readonly Message[], shown: readonly Message[], limit: number) => readonly Message[] \| undefined` | Cuts the workspace text a calibration sample adds over its head to a number of characters, or returns `undefined` when the sample adds anything else. |
1754
1966
  | `matchesCutLine` | function | `(line: string) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
1755
1967
  | `normalizeArgument` | function | `(value: string) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
1756
1968
  | `splitResultLines` | function | `(text: string) => readonly string[]` | Splits a tool result into its lines at each line feed, with or without a carriage return before it. |
1757
1969
  | `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
1758
- | `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState, write?: boolean) => string` | Renders the tail stub of a lookup result from an earlier request. |
1970
+ | `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. |
1759
1971
  | `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
1760
1972
  | `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
1761
1973
  | `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
@@ -1773,6 +1985,9 @@ The following table lists the pure helpers that read text, project and select re
1773
1985
  | `matchesLookup` | function | `(left: LedgerLookupFinding, right: LedgerLookupFinding) => boolean` | Checks whether two successful findings carry the same text for the same canonical lookup. |
1774
1986
  | `digestLedgerWindow` | function | `(exchanges: readonly LedgerExchangeSnapshot[], messages: readonly Message[]) => string \| undefined` | Digests held messages, lookup call context, stored copies, and sentence receipts using canonical text. This non-cryptographic checksum detects host edits and makes no security claim. |
1775
1987
  | `digestLedgerTools` | function | `(definitions: readonly ToolDefinition[]) => string \| undefined` | Digests tool definitions as the JSON a provider request carries them, in order. |
1988
+ | `computeToolDensity` | function | `(calibrated: readonly ToolDefinition[], gauge: LedgerGauge) => number` | Computes the tokens one estimate unit of a definition costs beyond the calibrated set. |
1989
+ | `computeToolPrice` | function | `(calibrated: readonly ToolDefinition[], advertised: readonly ToolDefinition[], gauge: LedgerGauge) => Required<Pick<GaugeCall, 'spared' \| 'added'>>` | Computes what a call's advertised set spares of the calibrated overhead and adds beyond it. |
1990
+ | `computeSkillPrice` | function | `(skill: Pick<Skill, 'name' \| 'content'>, added: readonly ToolDefinition[], calibrated: readonly ToolDefinition[], gauge: LedgerGauge) => number` | Computes the tokens loading a skill adds: its body, and the definitions it names beyond an advertised set. |
1776
1991
  | `computeLedgerChecksum` | function | `(text: string) => string` | Computes a checksum of text: two 32-bit FNV-1a lanes over its code points, as 16 hexadecimal digits. |
1777
1992
  | `buildLedgerLineKey` | function | `(line: Pick<LedgerOccurrence, 'key' \| 'title' \| 'source' \| 'sentence'>) => string` | Encodes a sentence's record placement without comparing rendered text. |
1778
1993
  | `collectLedgerLines` | function | `(record: LedgerRecord, held: ReadonlySet<string>) => readonly LedgerOccurrence[]` | Collects the record's sentence receipts not already held by a window. |
@@ -2010,24 +2225,24 @@ The driver-backed implementation keeps an explicit table because its class name
2010
2225
 
2011
2226
  The name-keyed skill registry a host supplies skills through. `add` mints each `id` and file, replaces a same-name skill in its position, and carries batch overloads; `remove` carries batch overloads. The `emitter` / `count` / `open` / `close` data members stay Surface rows.
2012
2227
 
2013
- | Method | Returns | Summary |
2014
- | -------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------- |
2015
- | `add` | `Skill` / `readonly Skill[]` | Adds one `SkillInput`, or a batch: mints each `id` and file, and overwrites a same-name skill, last write wins. |
2016
- | `skill` | `Skill \| undefined` | Looks up one skill by name (`undefined` when absent). |
2017
- | `skills` | `readonly Skill[]` | Lists every skill, in insertion order. |
2018
- | `render` | `string` | Renders one skill's index line: the manager-options `render`, else `- name: description`. |
2019
- | `remove` | `boolean` | Removes one skill by name, or a batch. True if every supplied name was removed; false otherwise. |
2020
- | `clear` | `void` | Removes every skill. |
2228
+ | Method | Returns | Summary |
2229
+ | -------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
2230
+ | `add` | `Skill` / `readonly Skill[]` | Adds one `SkillInput`, or a batch: mints each `id` and file, copies each `tools` list, and overwrites a same-name skill, last write wins. |
2231
+ | `skill` | `Skill \| undefined` | Looks up one skill by name (`undefined` when absent). |
2232
+ | `skills` | `readonly Skill[]` | Lists every skill, in insertion order. |
2233
+ | `render` | `string` | Renders one skill's index line: the manager-options `render`, else `- name: description`. |
2234
+ | `remove` | `boolean` | Removes one skill by name, or a batch. True if every supplied name was removed; false otherwise. |
2235
+ | `clear` | `void` | Removes every skill. |
2021
2236
 
2022
2237
  #### `AgentContextInterface`
2023
2238
 
2024
2239
  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.
2025
2240
 
2026
- | Method | Returns | Summary |
2027
- | -------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
2028
- | `apply` | `void` | Applies the given scope as the active per-turn filter; passing `undefined` explicitly removes filtering. |
2029
- | `select` | `Promise<Selection> \| undefined` | Runs the selection handler for one request — the active scope's `select`, else the agent default — and checks that the conversation did not change under it. |
2030
- | `build` | `readonly Message[]` | Builds the provider input for the next turn: a leading `system` message folding the prompt, the scope-filtered instructions, and the scope-filtered skills index (each section's header and each item's rendering resolved through the format cascade), then one `user` context message holding the scope-filtered memos index before the active 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 active 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 the memos or workspace section renders, the workspace render covers the active workspace alone, tools are advertised structurally rather than in the prompt, and the input is built fresh on each call. |
2241
+ | Method | Returns | Summary |
2242
+ | -------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2243
+ | `apply` | `void` | Applies the given scope as the active per-turn filter; passing `undefined` explicitly removes filtering. |
2244
+ | `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. |
2245
+ | `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. |
2031
2246
 
2032
2247
  #### `AgentInterface`
2033
2248
 
@@ -2099,7 +2314,7 @@ The server half of a page's approval. Its `ask` is a readonly data member that h
2099
2314
 
2100
2315
  #### `AgentRegistryInterface`
2101
2316
 
2102
- The job-rehydration bridge. `provider` / `tool` / `authority` / `scheduler` resolve a name against their pool (throwing `unknown <category>: <name>` on a miss); `build` rehydrates a seeded, signal-wired agent from a serializable job. It has no data members.
2317
+ The job-rehydration bridge. `provider` / `tool` / `authority` / `scheduler` resolve a name against their pool (throwing `unknown <category>: <name>` on a miss); `build` rehydrates a seeded, signal-wired agent from a serializable job. A registry built with `skills`, `memos`, and `workspaces` managers passes them to every job with a `scope`, read through that job's lists, and a job with no `scope` holds none of them, as [Running many durable agents as jobs](#running-many-durable-agents-as-jobs) states. It has no data members.
2103
2318
 
2104
2319
  | Method | Returns | Summary |
2105
2320
  | ----------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -2111,11 +2326,11 @@ The job-rehydration bridge. `provider` / `tool` / `authority` / `scheduler` reso
2111
2326
 
2112
2327
  #### `AgentFanout`
2113
2328
 
2114
- The runner handler `createAgentRunner` binds. One instance serves one runner, because it records every unit whose declared children it spawned, so a retried attempt of a unit spawns none again. It has no data members.
2329
+ The runner handler `createAgentRunner` binds. One instance serves one runner, because it records every unit whose declared children it spawned, so a retried attempt of a unit spawns none again. Before a unit spawns or runs, the `execute` method checks every job in the tree under it against its own parent, its `tools`, `builtins`, and `scope` lists included, and throws `AgentError` with code `REGISTRY` when one exceeds it, as [Running many durable agents as jobs](#running-many-durable-agents-as-jobs) states. It has no data members.
2115
2330
 
2116
- | Method | Returns | Summary |
2117
- | --------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2118
- | `execute` | `Promise<AgentResult>` | Executes one unit: spawns its declared children unless an earlier attempt of the unit already did, then runs the rehydrated agent and settles it under the partial policy. |
2331
+ | Method | Returns | Summary |
2332
+ | --------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
2333
+ | `execute` | `Promise<AgentResult>` | Executes one unit: refuses its tree when a job in it is malformed or exceeds its parent, spawns its declared children unless an earlier attempt of the unit already did, then runs the rehydrated agent and settles it under the partial policy. |
2119
2334
 
2120
2335
  Bind the `execute` method of a fresh instance as the handler of a runner you compose yourself:
2121
2336
 
@@ -2213,7 +2428,7 @@ The conversation ledger. The `respond` method serves one request through to its
2213
2428
 
2214
2429
  #### `LedgerRequestInterface`
2215
2430
 
2216
- The state of one `respond` call. The ledger creates one request per call and drops it when the call settles, so no request state reaches a later call or a run no call owns. Each agent run the call makes is a pass: the `open` method starts one, and the `selection`, `boundary`, and `usage` data members read the current pass. The `signal` and `aborted` data members read the current pass too, and `aborted` reads `signal`. The `scope`, `sent`, `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, `attempts`, `signal`, and `aborted` data members stay Surface rows. The `apply(scope)` method records the scope applied by the plan for conditional restoration when the call settles.
2431
+ The state of one `respond` call. The ledger creates one request per call and drops it when the call settles, so no request state reaches a later call or a ledger tool a host calls by hand between requests. Each agent run the call makes is a pass: the `open` method starts one, and the `selection`, `boundary`, and `usage` data members read the current pass. The `signal` and `aborted` data members read the current pass too, and `aborted` reads `signal`. The `scope`, `sent`, `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, `attempts`, `signal`, and `aborted` data members stay Surface rows. The `apply(scope)` method records the scope applied by the plan for conditional restoration when the call settles.
2217
2432
 
2218
2433
  | Method | Returns | Summary |
2219
2434
  | --------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
@@ -2236,6 +2451,7 @@ The state of one `respond` call. The ledger creates one request per call and dro
2236
2451
  | `abort` | `void` | Aborts the current pass's run through `signal`, with the reason `'stray'`, so the run ends after its turn. |
2237
2452
  | `list` | `void` | Holds the stored first line of each lookup a recall result listed, keyed by its listed line. |
2238
2453
  | `lines` | `ReadonlyMap<string, string> \| undefined` | Returns the stored first lines a recall result listed. |
2454
+ | `commit` | `void` | Records the tokens one cleared call commits to the next prompt. |
2239
2455
 
2240
2456
  The ledger drives each request through these methods, and a harness can drive one directly to check its stops. The following request serves one pass, then refuses a repeated lookup, admits it again after a release, records a denied write, and refuses a recall past its limit:
2241
2457
 
@@ -2263,6 +2479,9 @@ request.faulted(failure) // true — the request's run reported this error throu
2263
2479
  request.spend({ prompt: 52, completion: 8, total: 60 })
2264
2480
  request.usage // { prompt: 82, completion: 10, total: 92 } — the selection's usage and the call's
2265
2481
  request.calls // [{ estimate: 40, tools: 2, prompt: 52, completion: 8 }] — the call in flight took its usage
2482
+ request.commit(36, 'refunds') // a load's price, with the skill it loads
2483
+ request.committed // 36 — the prices committed after the call in flight started
2484
+ request.loads // ['refunds'] — the skills those loads name
2266
2485
 
2267
2486
  request.admit('lookup_order', { id: 'BW-5512' })
2268
2487
  request.admit('lookup_order', { id: 'BW-5512' }) // throws Error(LEDGER_NOTES.repeat)
@@ -2295,7 +2514,7 @@ The ledger's filing engine. The `classify` method asks the judge what the conver
2295
2514
 
2296
2515
  #### `GaugeInterface`
2297
2516
 
2298
- The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read the calls of the request in progress, and the `observe` method folds a finished request in. The `scale` and `overhead` data members stay Surface rows. The `scale` member holds the last learned price; the `overhead` member holds the construction price. A call's optional `spared` member defaults to zero. Observation rescales only when the first call held exactly all overhead (`spared` absent or zero) or none (`spared` at or above overhead), subtracting `max(0, overhead - spared)` from reported prompt usage. A partially spared first call keeps the existing scale. Estimated use adds that reduced overhead to `scale * estimate`. When no tool is advertised, the ledger spares all overhead and can rescale exactly. When some tools remain, it spares the estimated price of the JSON array of every omitted definition, capped at overhead; a partial share is not learned from, so the calibrated scale remains until a first call with exact overhead can update it.
2517
+ The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read the calls of the request in progress, and the `observe` method folds a finished request in. The `scale` and `overhead` data members stay Surface rows. The `scale` member holds the last learned price; the `overhead` member holds the construction price. A call's optional `spared` member defaults to zero. Observation rescales only when the first call held exactly all overhead (`spared` absent or zero) or none (`spared` at or above overhead), subtracting `max(0, overhead - spared)` from reported prompt usage. A partially spared first call keeps the existing scale. Estimated use adds that reduced overhead to `scale * estimate`. When no tool is advertised, the ledger spares all overhead and can rescale exactly. When some tools remain, it spares the estimate of the JSON array of every omitted definition at the lower of the scale and the calibrated definitions' overhead per estimate unit, at most their proportional share of the overhead; a partial share is not learned from, so the calibrated scale remains until a first call with exact overhead can update it.
2299
2518
 
2300
2519
  | Method | Returns | Summary |
2301
2520
  | ----------- | -------- | ---------------------------------------------------------------------------------------------------- |
@@ -2316,27 +2535,32 @@ These invariants hold across `src/core` ↔ `agent.md`:
2316
2535
  - **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.
2317
2536
  - **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.
2318
2537
  - **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.
2319
- - **The richer turn context (`AgentContext`).** `AgentContext` composes the optional `system` prompt, the `instructions`, `skills`, `memos`, `workspaces`, and `conversations` managers, `messages`, the `tools` registry, and a readonly active `scope`, creating each omitted manager fresh. `build()` folds the system prompt, the scope-filtered instructions, and the scope-filtered skills index into one leading `system` message, renders the scope-filtered memos index and the active workspace's scope-filtered text files into one `user` context message after it, then appends the active conversation's `view()`, or a passed selection's `messages`. The `system` message holds host-authored text alone. It never reads `tools`, never mutates a manager or a stored message, and builds fresh on each call.
2320
- - **Scope filtering.** A scope holds one three-way allow-list per category (`instructions` by `name`, `skills` by `name`, `memos` by `name`, `tools` by `name`, `files` by `path`), applied through `filterAllowList`, and `narrow` intersects each list, so narrowing only tightens. The scope's filters never touch messages; message inclusion is the conversation's through compaction and, when a handler is set, the selection's. The loop filters the advertised definitions by `scope.tools`, so a scoped-out tool is neither described nor callable, and `build()` never contains a tool's name or schema.
2538
+ - **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.
2539
+ - **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.
2321
2540
  - **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.
2322
2541
  - **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.
2323
2542
  - **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.
2324
2543
  - **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.
2325
- - **Pull and push observation on the `Agent`; the rest event-free.** The provider contract, the conversation registry, and the context carry no emitter, while the instruction and scope managers and each conversation own one. The `Agent` pairs the `AgentChunk` stream with an `emitter` over `AgentEventMap` (`start`, `turn`, `tool`, `usage`, `allow`, `ask`, `deny`, `finish`, `error`, `abort`, `exhaust`, `fault`, `select`) and has no `token` or `think` event. The emitter routes a listener throw to the `error` option, and a cancelled run emits `abort` then `finish`.
2544
+ - **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`.
2545
+ - **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.
2546
+ - **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.
2547
+ - **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.
2548
+ - **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.
2326
2549
  - **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.
2327
2550
  - **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins, returning the matched rule's `verdict`, and returns the required `fallback` when none match. A missing `fallback` or a rule with no `verdict` throws `AgentError` coded `'AUTHORITY'` at construction. `evaluate` is synchronous. `ask(context, decision, signal)` resolves the `ask` option's answer and rejects with an `AgentError` coded `'APPROVER'` when no handler is set. The gate is event-free.
2328
2551
  - **A denied call is fed back, never executed.** The loop consults `authority` after scope admits a call, and denies the call when the agent holds none, which only a tool added later to an agent built with no `tools` can reach. A call no definition advertises is denied with the scope note before the authority evaluates it, under every verdict, and its `deny` event carries no decision. A `deny` verdict, and an `ask` the approver refuses or leaves unanswered, become the failure arm `{ success: false, id, name, error }` without running the tool. A call that `allow` cleared whose tool is replaced or removed before dispatch is denied too: the model reads the `denied` note of `AUTHORITY_NOTES`, and its `deny` event carries the reason `<name> changed after its decision` and no decision. Executed results and denials merge in the reply's call order, each producing a `tool` chunk and a tool message.
2329
- - **Durable, serializable agent jobs (`AgentJobInput` + `AgentRegistry`).** An `AgentJobInput` names its `provider`, `tools`, `authority`, and `scheduler` and carries its data directly, and `AgentRegistry.build(input, signal?)` checks it exactly against `agentJobContract`, throwing `AgentError` with code `REGISTRY` and the faults on a misspelled key, then rehydrates a seeded, signal-wired `Agent` from the named pools. An unknown name throws `AgentError` with code `REGISTRY` and the message `unknown <category>: <name>`, and a job that names `tools` and no `authority` throws the same code at `build`.
2552
+ - **Durable, serializable agent jobs (`AgentJobInput` + `AgentRegistry`).** An `AgentJobInput` names its `provider`, `tools`, `authority`, and `scheduler` and carries its data directly, and `AgentRegistry.build(input, signal?)` checks it exactly against `agentJobContract`, throwing `AgentError` with code `REGISTRY` and the faults on a misspelled key or on a `limit`, `timeout`, or `budget` outside the bounds the agent's construction admits, then rehydrates a seeded, signal-wired `Agent` from the named pools. An unknown name throws `AgentError` with code `REGISTRY` and the message `unknown <category>: <name>`, and a job the agent's construction would refuse throws the same code at `build` with the lines `collectJobRefusals` returns under `context.refusals`.
2330
2553
  - **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.
2331
2554
  - **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.
2332
- - **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.
2555
+ - **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.
2333
2556
  - **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.
2334
2557
  - **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.
2335
2558
  - **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.
2336
- - **Active workspace rendering by carrier.** `build()` reads only the active workspace, filters its files through `scope.files`, renders text files under `WORKSPACE_SECTION_HEADER` through `renderFencedFile` into one `user` context message with a minted id, which is never stored, and attaches the base64 data of binary `image/` files to a copy of the last user message of the conversation. With no active workspace, or no text file, the context message holds the memos index alone, and with no memos index either, no context message renders.
2559
+ - **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.
2337
2560
  - **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.
2338
- - **Limit exhaustion, the three failure layers, and per-run options.** A run that exhausts `limit` while its last turn still requested tools settles `partial: true` and emits `exhaust` instead of `abort`. The loop charges the `allowance` mid-stream from the `estimateTokens` estimate of each turn's content, and charges the cost `budget` the reported usage after each call, net of the estimate only when the `allowance` is the `budget`, or the estimate when the call reported none, a call that failed with a genuine provider error included; it never charges twice. `AgentResult.stop` names the one layer, `meter`, `budget`, or `model`, that stopped the final provider call first. `AgentRunOptions` members override their construction defaults for one run, `conversation` and `prompt` have no construction default, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a positive safe integer throws `AgentError` with code `LIMIT`.
2561
+ - **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`.
2339
2562
  - **Construction-time context wiring.** `AgentOptions.instructions`, `skills`, `memos`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
2563
+ - **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.
2340
2564
  - **`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.
2341
2565
  - **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.
2342
2566
  - **`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`.
@@ -2349,7 +2573,7 @@ These invariants hold across `src/core` ↔ `agent.md`:
2349
2573
  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`.
2350
2574
 
2351
2575
  - **`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.
2352
- - **`AgentError` — the concurrency guard.** `stream()` throws `AgentError` with code `CONCURRENCY` and `context: { agent }` synchronously when a run is in flight and the agent carries a `window`, or when the run's effective `budget` or `allowance` is an instance a live run holds; after those checks it throws one with `context: { agent, conversation }`, naming the conversation's id, when a live run is bound to the run's conversation. Runs holding distinct instances on distinct conversations with no `window` overlap. The refused run never starts either bound, so the live run stays bound to it. The guard compares conversation instances: two `Conversation` values opened from one stored snapshot are distinct to it and run at once on an agent with no `window` and distinct budgets, so a host opens each thread once and keys its thread registry by principal and thread. A `prompt` that is not an exact `AgentPrompt`, a `budget` or `allowance` that does not implement `BudgetInterface`, or a `conversation` that does not implement `ConversationInterface` throws `ContractError` with code `placement` before either bound starts, and a refused run appends no `prompt`. `isAgentError` narrows a caught value, and a `REGISTRY` error's `context` names the `category` and `name`.
2576
+ - **`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.
2353
2577
  - **`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.
2354
2578
  - **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.
2355
2579
  - **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.
@@ -2364,13 +2588,66 @@ These invariants hold across `src/core` ↔ `agent.md`:
2364
2588
  - **The System One wire (`SystemOneJudge` / `createSystemOneJudge`).** `SystemOneJudge` posts every question in one call to `url` plus `SYSTEM_ONE_PATH`, writing `form` as `type` and leaving an omitted member omitted, and decodes each requested id in criteria order, accepting a score's `probabilities` as a map or an array. It ignores unrequested answers and the server's `confidence`, `score`, `choice`, and `legend` members, so `measureAnswer` derives every measure locally. A System One server answers only from the supplied options, so the wire never reports a refusal: a missing, mismatched, or out-of-range answer throws `JudgeError` with code `PROTOCOL` naming the question id.
2365
2589
  - **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.
2366
2590
  - **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.
2367
- - **Two selection homes.** `AgentOptions.select` is the agent default and the active scope's `select` overrides it, and `context.select` resolves the handler once per call and returns `undefined` when neither home holds one, so the default path awaits nothing.
2368
- - **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)`, which 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.
2591
+ - **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.
2592
+ - **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.
2369
2593
  - **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.
2370
2594
  - **Selection cost.** Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`, with no `usage` chunk or `usage` event.
2371
2595
  - **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.
2372
2596
  - **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`.
2373
2597
 
2598
+ ## Limits
2599
+
2600
+ The following list holds the documented limits: the ledger's first, then those of the built-in tools and of a job tree.
2601
+
2602
+ - **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.
2603
+ - **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.
2604
+ - **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.
2605
+ - **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.
2606
+ - **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.
2607
+ - **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.
2608
+ - **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.
2609
+ - **A seed tool message counts as successful.** A tool message the application adds to the conversation has no recorded result, so the ledger reads it as a successful lookup and files it as a fact, and its reading handler decides what the result names.
2610
+ - **An abort during calibration rejects.** When the caller's signal aborts while the ledger calibrates, the `respond` method rejects with the abort reason instead of resolving a partial result; after calibration, an abort ends the request partial and skips the answer pass.
2611
+ - **A foreign signal rejects before anything is appended.** A `signal` that isn't a native `AbortSignal` rejects the `respond` method with a `ContractError` before the request is appended, and the ledger stays free for a later request.
2612
+ - **The seed selection stays fixed.** Only the messages added before the first request form the seed tail. Each completed exchange follows it in the window: a request as it was sent and its last call-free assistant reply, excluding notes, calls, and tool messages. A blank or missing last call-free reply carries nothing. A committed partial reply means one the conversation stored; it remains eligible after an abort, but a cut landing mid-stream stores no reply and carries nothing. A host statement reaches the prompt through records or recall, and neither that statement nor a host lookup after the reply erases the exchange. Two non-empty call-free assistants without a ledger note between them make the pairing ambiguous, so it carries nothing; answer-pass notes establish the separation between a partial first reply and the final answer. A host that removes a request must remove every turn of it too, because nothing stored links a reply to its request: a surviving reply can read as the earlier request's when that request has no reply of its own, or when the removed request's answer pass left its note behind. The seed messages and the selected record lines stay the same on every rung of the window, and only a seed stub's `shown` or `hidden` state follows the rung.
2613
+ - **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup with different text or an empty result replaces it, a write names it among its `targets`, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows, and a line an earlier copy showed stays in the prompt until the window empties or falls past that copy.
2614
+ - **The ledger cuts only what it owns.** The plan cuts record lines, the seed tail, and the exchange window, so a request, a lookup result, or the whole view a faulted selection builds from can exceed the room the `capacity` option leaves, and the ledger then sends no request that carries it, as **The capacity gate.** states. A host whose provider's window exceeds the declared `capacity` meets a refusal where that provider could have answered, because `capacity` is the contract; raise it to the window.
2615
+ - **A host edit during a request is priced at its next turn.** A host edit to a scope list, a skill, a memo, a workspace, or a tool during a request reaches the next turn, and the ledger prices that turn with the edit in it. The ledger prices definitions against the set its gauge measured, so a tool freed from a skill, added, or replaced during a request is priced as an addition for the rest of the request, and the next `respond` call calibrates. The `computeToolPrice` helper compares definitions by their JSON text, and the `computeToolDensity` helper returns the tokens one estimate unit of a definition costs beyond the calibrated set. A memo written during a request's first pass enters the rebuilt answer context and consumes its fitting allowance. The context can change while the selected seed and request stay the same.
2616
+ - **A heading inside a record line reads as one.** A record line and the request copy render a message's or a lookup's text verbatim, so text holding a `## Rules` or `## Request` heading reads as one inside the user turn's copy; it changes no filing and never reaches `system`, and no delimiter marks such text.
2617
+ - **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.
2618
+ - **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.
2619
+ - **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.
2620
+ - **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.
2621
+ - **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.
2622
+ - **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.
2623
+ - **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.
2624
+ - **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.
2625
+ - **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.
2626
+ - **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.
2627
+ - **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.
2628
+ - **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.
2629
+ - **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.
2630
+ - **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.
2631
+ - **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.
2632
+ - **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.
2633
+ - **A changed lookup empties the window.** A later finding of the same lookup with different text or an empty result retires the source the window holds, and that empties the window. That prompt holds the derived newest pair and a copy of every selected line, so it doesn't extend the prompt before it. A lookup repeated with the same text retires nothing, so the prompt extends the one before it.
2634
+ - **A write empties the window when it retires a held line.** A write that retires a source the window holds empties the window, as a changed lookup does, so that prompt doesn't extend the prompt before it.
2635
+ - **A write retires whole findings.** A write retires every earlier finding that names a target, so a list read loses its untouched rows too and the model reads again. A user statement about the record never retires through `targets`; the judge's supersession files that.
2636
+ - **A partial request can hold a completed write.** A write stores its result before the next turn, so an abort or a failure later in the request leaves the write in the conversation, retiring the reads it made stale. A host that discards a partial request's snapshot loses that write while its store keeps the change, so it must save the snapshot after any request that ran a write.
2637
+ - **A write's handler must be total.** A handler that throws marks the write failed, so a write that changed the store files nothing and leaves the stale read live, and a handler that misses a target leaves that target's earlier reads live. Pass the same `writes` on every hydrate: the ledger reads the targets again from the conversation, so a changed list brings retired reads back live.
2638
+ - **A write that changed nothing stubs as such.** A seed write whose handler reads no change stubs as `changed nothing`, where an empty lookup stubs as `no record`.
2639
+ - **A cut stream stores nothing.** A stream cut before its reply is stored leaves the window standing, so a follow-up that refers to the cut text reads against the last completed reply.
2640
+ - **Recall fitting depends on its measured price.** Runtime recall and recovery allow the `LEDGER_SCALE_DRIFT` margin over the larger of the gauge's marginal rate and this request's measured rate. A provider whose new text costs more than that bound is outside the capacity guarantee. Missing usage remains estimated; no exact tokenizer preflight is available. A long earlier reply still affects window admission, but never vetoes a runtime recall that fits.
2641
+ - **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.
2642
+ - **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.
2643
+ - **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.
2644
+ - **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.
2645
+ - **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.
2646
+ - **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).
2647
+ - **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.
2648
+ - **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`.
2649
+ - **A job tree's check grows with its depth and reads `children` twice.** Each job's audit reads its whole subtree and each spawned unit checks its own subtree again, so a chain of jobs costs the check about the square of its depth, with the event loop blocked, and the check and the spawn each read a job's `children`, so a job whose `children` getter answers differently at each read can pass the check and spawn another set. A record an `add` method takes reads the same way: a getter that answers differently at each read, a memo `origin`'s among them, can pass the record check and store another value. Keep a job tree a few levels deep, and pass each job and record as plain data.
2650
+
2374
2651
  ## Patterns
2375
2652
 
2376
2653
  ### Bounding any provider call
@@ -2543,21 +2820,21 @@ That judge answers through `ask` like any other. With `batch: false` the engine
2543
2820
 
2544
2821
  Every configuration sends one request layout, position by position. The following table lists what fills each position under each strategy:
2545
2822
 
2546
- | Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
2547
- | ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2548
- | `system` | the `system` option, then `## Instructions`, then `## Skills`; absent when all are empty | the same | the `system` option, then `## Instructions` and `## Skills` from the `agent` option |
2549
- | `user` context message | `## Memos`, then `## Workspace`; absent when both are empty; a minted id, never stored and never folded | the same | the same, from the `agent` option |
2550
- | 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 |
2551
- | 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 |
2552
- | Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
2823
+ | Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
2824
+ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2825
+ | `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 |
2826
+ | `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 |
2827
+ | 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 |
2828
+ | 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 |
2829
+ | Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
2553
2830
 
2554
- A host writes the `system` message through the `system` option, `instructions.add`, a skill load, and the skill index, and nothing else reaches it. 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, and a host scope with an explicit `instructions` allow-list filters a loaded `skill:<name>` instruction. The skills index stays inert until a host registers a loading tool, as the `SkillManager` paragraph states.
2831
+ 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.
2555
2832
 
2556
2833
  ### Serving one agent per principal
2557
2834
 
2558
2835
  Hold one session entry per authenticated principal, built once from shared providers, tools, rules, and immutable host text. Name the entries for what each placement holds: `{ agent, threads }` for the Node fence under [binding a run to its thread](#one-agent-per-principal-one-conversation-per-run-binding-a-run-to-its-thread), and `{ agent, threads, approver }` for the wire fence under [Serving a Node agent to a page](#serving-a-node-agent-to-a-page), whose approver is required. Each is its own type. The following rules hold for both:
2559
2836
 
2560
- - **What one `Agent` shares.** A per-principal `Agent` shares its workspace pointer, scope, instructions, memos, emitter, and `agent.abort()` across that principal's threads. So name the thread per run through `AgentRunOptions.conversation`, because `switch` sets only the default. Forward a run's own `events` and cancel with its own `abort` or `signal`, because the emitter's events carry no run identity and `agent.abort()` cancels every live run of that agent. Agent keeps one workspace pointer per agent, so a `workspaces.switch` during one thread's run reaches the next build site of every thread that agent is running.
2837
+ - **What one `Agent` shares.** A per-principal `Agent` shares its workspace pointer, scope, instructions, memos, emitter, and `agent.abort()` across that principal's threads. So name the thread per run through `AgentRunOptions.conversation`, because `switch` sets only the default. Forward a run's own `events` and cancel with its own `abort` or `signal`, because the emitter's events carry no run identity apart from the conversation a `request` event names, and `agent.abort()` cancels every live run of that agent. A run narrows the shared scope for itself through `AgentRunOptions.scope`. Agent keeps one workspace pointer per agent, so a `workspaces.switch` during one thread's run reaches the next build site of every thread that agent is running. The `switch` built-in selects a workspace for one conversation and never moves that pointer, and a skill the model loads shows in its own conversation alone.
2561
2838
  - **The `window`, `budget`, and `allowance` rule.** Each session entry builds its own `window`, `budget`, and `allowance`, never shared across principals. While one run is live, an `Agent` built with a `window`, a `budget`, or an `allowance` refuses that principal's next run on any thread with `AgentError` `'CONCURRENCY'` and never queues it.
2562
2839
  - **The `409` or rethrow mapping.** The Node fence's `handle` rejects with that error, and the caller rethrows it or maps it. The wire fence's frame route answers `409`.
2563
2840
  - **A run the host can't finish.** The host bounds it through a `timeout` or `signal` it passes to that run, or through `agent.abort()`, because under such an `Agent` a run that never settles refuses every later run of that principal.
@@ -2569,14 +2846,14 @@ Hold one session entry per authenticated principal, built once from shared provi
2569
2846
 
2570
2847
  A model-facing inlet has one side that writes it and one side that enforces what reaches the model, and the placements under [Placement proofs](#placement-proofs) divide them differently. The following table reads each cell as writer, then enforcer, and [Serving one agent per principal](#serving-one-agent-per-principal) holds the session table each server placement keeps:
2571
2848
 
2572
- | Inlet | Node alone | Page alone | Page to Node relay | Page to Node agent |
2573
- | ----------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
2574
- | System text, instructions, the skill index and bodies | host code in Node, then the Node loop | the page, then nothing beyond the page's own code | the server through `RelaySystemOptions.text`, and the page only where `accept` admits it, then `createRelay` with `422` | host code in Node, then the Node loop |
2575
- | Tool definitions | host code in Node, then the Node loop's scope and `Authority` | the page, then the page's own loop | the server through `RelayToolOptions.definitions`, and the page only where `accept` admits it, then `createRelay` with `422` | host code in Node, then the Node loop's scope and `Authority` |
2576
- | Deny reasons | the host's rules in Node, then the Node loop | the page's rules, then the page's loop | the page's rules, then the page's loop | the host's rules in Node, then the Node loop |
2577
- | Memos and workspace | the host or a host tool in Node, then the Node context | the page, then the page's context | the page, then the page's context, and the server forwards them as a `user` message | the host or a host tool in Node, then the Node context |
2578
- | The conversation | the host in Node, then the stored-role checks | the page, then the stored-role checks | the page, then the page's stored-role checks and the relay's refusal of a page `system` message | one `AgentPrompt` from the page and every other turn from Node, then the exact prompt check and the stored-role checks |
2579
- | Tool results | the handler in Node, then the Node loop | the page's handler, then the page's loop | the page's handler, then the page's loop, and the server forwards each as history | the handler in Node, then the Node loop |
2849
+ | Inlet | Node alone | Page alone | Page to Node relay | Page to Node agent |
2850
+ | ----------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
2851
+ | System text, instructions, the skill index and bodies | host code in Node, then the Node loop | the page, then nothing beyond the page's own code | the server through `RelaySystemOptions.text`, and the page only where `accept` admits it, then `createRelay` with `422` | host code in Node, then the Node loop |
2852
+ | Tool definitions | host code in Node, then the Node loop's scope and `Authority` | the page, then the page's own loop | the server through `RelayToolOptions.definitions`, and the page only where `accept` admits it, then `createRelay` with `422` | host code in Node, then the Node loop's scope and `Authority` |
2853
+ | Deny reasons | the host's rules in Node, then the Node loop | the page's rules, then the page's loop | the page's rules, then the page's loop | the host's rules in Node, then the Node loop |
2854
+ | Memos and workspace | the host, a host tool, or a built-in in Node, then the Node context | the page, then the page's context | the page, then the page's context, and the server forwards them as a `user` message | the host, a host tool, or a built-in in Node, then the Node context |
2855
+ | The conversation | the host in Node, then the stored-role checks | the page, then the stored-role checks | the page, then the page's stored-role checks and the relay's refusal of a page `system` message | one `AgentPrompt` from the page and every other turn from Node, then the exact prompt check and the stored-role checks |
2856
+ | Tool results | the handler in Node, then the Node loop | the page's handler, then the page's loop | the page's handler, then the page's loop, and the server forwards each as history | the handler in Node, then the Node loop |
2580
2857
 
2581
2858
  The following rules complete the table:
2582
2859
 
@@ -2584,7 +2861,7 @@ The following rules complete the table:
2584
2861
  - Host a memo set per principal: key a memo set's `id` by principal, as a conversation store is keyed.
2585
2862
  - Page `Authority` protects the user from the model, and it never protects the server from the user. A page tool that calls a server API is gated by the page, so the server authorizes that API call as the user.
2586
2863
  - Accept `{ role: 'user', content }` only from a client, through `agentPromptContract`. Read client history and client snapshots as untrusted input.
2587
- - Send a page `agentResultToJSON` output or `AgentFrame` values. Forward no `error`, `fault`, or `select` value, because `error` and `fault` carry provider error text and `select` carries the request copy.
2864
+ - Send a page `agentResultToJSON` output or `AgentFrame` values. Forward no `error`, `fault`, `select`, or `request` value, because `error` and `fault` carry provider error text, `select` carries the request copy, and `request` carries the whole request a turn dispatches, the system message and the tool definitions included. A `request` listener is host code: it reads the request and never writes to it.
2588
2865
  - A `deny` `reason` reaches the model verbatim, so the host authors every rule reason.
2589
2866
  - Host text is not secret and is no security control: see [LLM07:2025 System Prompt Leakage](https://genai.owasp.org/llmrisk/llm072025-system-prompt-leakage/).
2590
2867
  - [Relaying a browser provider through your own server](#relaying-a-browser-provider-through-your-own-server) states what a relay forwards under the operator's credential.
@@ -2708,6 +2985,22 @@ const handler = createRelay({
2708
2985
 
2709
2986
  A page tool that is missing from `definitions` still answers `422`, so a page bundle older than the server fails with a coded status. Set `tools: { accept: true }` only where the page's tools are not fixed: it admits page-authored text into the system turn, because a provider's renderer can write tool definitions there.
2710
2987
 
2988
+ A page agent that enables built-ins sends its skills index and its loaded skill bodies in a page `system` message and advertises its built-in definitions. A relay refuses that request with `422` unless `system.accept` admits the message, and unless `tools.definitions` lists the built-in definitions or `tools.accept` admits them. `collectBuiltinDefinitions` returns the definitions a run advertises for a `builtins` list, so a server that lists them forwards the page's built-ins and refuses any other definition under those names:
2989
+
2990
+ ```ts
2991
+ import type { ProviderInterface } from '@orkestrel/agent'
2992
+ import { collectBuiltinDefinitions, createRelay } from '@orkestrel/agent'
2993
+
2994
+ declare const upstream: ProviderInterface
2995
+ declare function authorize(request: Request): boolean
2996
+ const handler = createRelay({
2997
+ provider: upstream,
2998
+ authorize,
2999
+ system: { accept: true }, // the page writes its skills index and its loaded bodies
3000
+ tools: { definitions: collectBuiltinDefinitions({ builtins: ['load', 'unload'] }) },
3001
+ })
3002
+ ```
3003
+
2711
3004
  For per-user text, build the handler per request: `createRelay({ ...shared, system: { text: textFor(user) } })(request)`, where the `shared` placeholder holds the provider, `authorize`, and `tools`. A page `window` prices only what the page sends, so subtract the server head's `estimateRequest` from `max`. A page `Ledger` over a relay needs `system: { accept: true }`, because `LedgerOptions.system` is required and calibration always sends a head, and it needs its `recall` tool and lookups declared in `tools.definitions` or admitted by `tools: { accept: true }`.
2712
3005
 
2713
3006
  ### Serving a Node agent to a page
@@ -3020,7 +3313,7 @@ result.stop?.layer // 'meter' when the estimate ran out first, 'budget' when the
3020
3313
 
3021
3314
  ### Observing an agent (push vs. pull)
3022
3315
 
3023
- An `Agent` exposes a pull and a push observation surface. Pull — the `AgentChunk` stream (`stream().events`) — is for a live consumer rendering per-token answer deltas and per-think reasoning deltas as they arrive. Push — the `emitter` (`AgentEventMap`) — is for fire-and-forget observers (logging, metrics, tracing) that want the loop's lifecycle moments without draining the stream: `start` (a run begins), `turn` (each iteration), `tool` (a dispatched call + its result), `usage` (a turn's token usage and the `estimate` of the answer it streamed, as `(usage, estimate)`), `allow` (a call cleared for dispatch, with its decision), `ask` (a call handed to the approver, with its decision), `deny` (a denied call; the event is never a chunk, and a call that scope or authority denies still yields a `tool` chunk that carries its denial result, while a call made when the active scope advertises no tools yields no chunk), `finish` (the settled result), `error` (a genuine failure), `abort` (a cancel), and `exhaust` (the limit was reached while the model still held unresolved tool intent — fires instead of `abort`, still followed by `finish`). Per-token / per-thinking deltas stay the stream's job exclusively — there is deliberately no `token` or `think` event on the emitter; reach for the stream when you need live output, the emitter when you need lifecycle.
3316
+ An `Agent` exposes a pull and a push observation surface. Pull — the `AgentChunk` stream (`stream().events`) — is for a live consumer rendering per-token answer deltas and per-think reasoning deltas as they arrive. Push — the `emitter` (`AgentEventMap`) — is for fire-and-forget observers (logging, metrics, tracing) that want the loop's lifecycle moments without draining the stream: `start` (a run begins), `turn` (each iteration), `request` (the request a turn dispatches, with the turn index and the run's conversation), `tool` (a dispatched call + its result), `usage` (a turn's token usage and the `estimate` of the answer it streamed, as `(usage, estimate)`), `allow` (a call cleared for dispatch, with its decision), `ask` (a call handed to the approver, with its decision), `deny` (a denied call; the event is never a chunk, and a call that scope or authority denies still yields a `tool` chunk that carries its denial result, while a call made when the turn advertises no tools yields no chunk), `finish` (the settled result), `error` (a genuine failure), `abort` (a cancel), and `exhaust` (the limit was reached while the model still held unresolved tool intent — fires instead of `abort`, still followed by `finish`). Per-token / per-thinking deltas stay the stream's job exclusively — there is deliberately no `token` or `think` event on the emitter; reach for the stream when you need live output, the emitter when you need lifecycle.
3024
3317
 
3025
3318
  An allow clears a call for the tool instance the registry held when the turn advertised it; if that instance is replaced or removed before dispatch, a `deny` follows with the reason `<name> changed after its decision` and no decision, so `deny` can follow that call's `allow`, and neither instance runs. Each call is checked once more right before it starts, so a handler that replaces or removes a later call's tool before its first await, or changes whether that tool is annotated `consequential`, gets the later call the same `deny`. The manager keeps its own policy for each call, and a supplied manager must resolve the tool when `execute` is entered, as `ToolManager` does. A cancel that ends the turn before dispatch emits no such `deny`.
3026
3319
 
@@ -3045,6 +3338,27 @@ const agent = createAgent(provider, {
3045
3338
  agent.emitter.on('abort', (reason) => log('cancelled', reason))
3046
3339
  ```
3047
3340
 
3341
+ 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.
3342
+
3343
+ The following listener reads the request each turn of one thread dispatches:
3344
+
3345
+ ```ts
3346
+ import type { ProviderInterface, ProviderRequest } from '@orkestrel/agent'
3347
+ import { createAgent } from '@orkestrel/agent'
3348
+
3349
+ declare const provider: ProviderInterface // replies 'Ticket 7 is open.'
3350
+
3351
+ const agent = createAgent(provider, { system: 'You triage tickets.' })
3352
+ const thread = agent.context.conversations.add()
3353
+ const sent: ProviderRequest[] = []
3354
+ agent.emitter.on('request', (_index, request, conversation) => {
3355
+ if (conversation === thread) sent.push(request)
3356
+ })
3357
+ await agent.generate({ conversation: thread, prompt: { content: 'Is ticket 7 open?' } })
3358
+ sent.map((request) => request.messages.map(({ role }) => role)) // [['system', 'user']]
3359
+ Object.isFrozen(sent[0]?.messages) // true
3360
+ ```
3361
+
3048
3362
  **Observation can never corrupt the loop.** The emitter isolates a listener that throws (the throw can never escape into the settle-once / wake-park engine — `generate()` / `stream()` still settle the exact same result), routing the caught error to its own `error` handler (the `error` option, surfaced as `(error, event)`, not a domain event) so the observer bug isn't silently lost. Every throwing listener surfaces (not only the first); a throwing `error` handler is swallowed too (it can neither recurse nor escape); with no handler the throw is dropped silently. So a buggy observer degrades to a routed error — it never reorders, throws into, or corrupts the run.
3049
3363
 
3050
3364
  **A cancelled run emits `abort` then `finish`.** A cancel (an external `signal`, the `timeout` deadline, an exhausted `budget` or `allowance`, or `abort()`) still resolves a partial result — so the emitter fires `abort` (carrying the cancel reason) and then `finish` (carrying the settled partial), letting an observer see both that the run was cancelled and the partial outcome it committed. A natural / cap-bounded finish fires `finish` only; a genuine provider / tool error fires `error` instead of `finish`. `generate()` and `stream()` drive the same events (they share one `#execute`).
@@ -3163,6 +3477,8 @@ const results = await Promise.all(jobs.map((job) => queue.enqueue(job)))
3163
3477
  await queue.restore()
3164
3478
  ```
3165
3479
 
3480
+ A registry can hold `skills`, `memos`, and `workspaces` managers through the matching `AgentRegistryOptions` members, and every job with a `scope` that it builds shares them. A job holds what it names: with no `scope` it holds no skill, memo, or workspace, as with no `tools` it holds no tool. A job's `scope` states the `skills`, `memos`, and `workspaces` lists, each list, with `[]` for none, and the registry refuses a scope that omits one or holds another member with `AgentError` code `REGISTRY`. A job's `tools` and `builtins` lists are its tool ceiling, and its `scope` holds no `tools` list. A job's `workspace` renders only where its scope lists the id and the pool holds it, so a job with no `scope` renders none. Name the job's workspace in its `workspace` member, because the registry's active workspace is state every job shares. A job that names `builtins` names an `authority`. `remember` runs only under an authority whose `ask` answers by itself, because a job drains no frames: an `Approver` value's `ask` waits until the job's `timeout`. The memo set serves one principal, so build one registry, or one memo set, for each principal, as **The store keyed by principal.** under [Serving one agent per principal](#serving-one-agent-per-principal) states for an agent. A retried attempt, and a child, can't revise a memo another attempt or the parent wrote, because `remember` revises only a memo its own conversation wrote.
3481
+
3166
3482
  Fan out sub-agents by declaring `children` on a parent job; the runner that `createAgentRunner` returns spawns each child through `controller.spawn` on the same bounded queue, so the children run as sibling sub-agents; a retried parent spawns them only on its first attempt:
3167
3483
 
3168
3484
  ```ts
@@ -3178,9 +3494,44 @@ const parent: AgentJobInput = {
3178
3494
  const results = await runner.execute([parent]) // [parent result, …then spawned child results]
3179
3495
  ```
3180
3496
 
3497
+ A child job runs within its parent. The runner's handler checks each job under the unit against its own parent before anything in the tree spawns or runs, and a child is within its parent when every one of the following holds:
3498
+
3499
+ - each name in its `tools` is in its parent's `tools`, and a parent with no `tools` holds none, so its child names none;
3500
+ - each of its `builtins` is one its parent names, and a parent with no `builtins` names none;
3501
+ - each name in each list of its `scope` is in its parent's same list, and a parent with no `scope` holds the three lists empty;
3502
+ - its `authority` is absent or equal to its parent's;
3503
+ - its `provider` equals its parent's;
3504
+ - its `scheduler` is absent or equal to its parent's;
3505
+ - its `limit` is at most its parent's, where an absent `limit` reads `DEFAULT_AGENT_LIMIT`;
3506
+ - where its parent holds a `timeout` or a `budget`, it holds one no larger.
3507
+
3508
+ Its `system` and `messages` are free, and so is its `workspace` within its own `scope`. The check walks the whole tree first, so a violation at any depth refuses the root before the root or any child runs. It audits each job through `agentJobContract` before it reads a member, so a malformed job at any depth refuses the same way, with its faults, and so does a job whose build would refuse it, with the lines `collectJobRefusals` returns. The refusal is an `AgentError` with code `REGISTRY` whose message opens with the rule each kind of finding breaks and then lists every finding, one a line, and whose `context.findings` member holds the same findings: a finding that names an exceeded member opens with the job's path, a dot, and the member, and a finding that refuses a whole job opens with the `JOB_REFUSAL_PREFIX` constant. The check holds each child within its parent alone, so the children of one parent can together spend more than it. The check runs on every attempt of a unit, and a retried parent spawns its children on its first attempt alone. A job that needs another provider, another authority, more room than its parent, or a skill, a memo, a workspace, or a built-in its parent lacks is a root job the host enqueues. The following parent holds no tools, so its child's tool refuses the whole tree:
3509
+
3510
+ ```ts
3511
+ import { isAgentError } from '@orkestrel/agent'
3512
+
3513
+ // `runner` and the `AgentJobInput` type come from the preceding examples.
3514
+ const planner: AgentJobInput = {
3515
+ provider: 'main',
3516
+ authority: 'desk',
3517
+ messages: [{ role: 'user', content: 'Plan the trip.' }],
3518
+ children: [
3519
+ {
3520
+ provider: 'main',
3521
+ tools: ['book'],
3522
+ authority: 'desk',
3523
+ messages: [{ role: 'user', content: 'Book flights.' }],
3524
+ },
3525
+ ],
3526
+ }
3527
+ const refused = await runner.execute([planner]).catch((error: unknown) => error)
3528
+ isAgentError(refused) && refused.code // 'REGISTRY'
3529
+ // refused.context.findings: ['job.children[0].tools: names "book", which its parent does not hold']
3530
+ ```
3531
+
3181
3532
  ### Giving the model documents to read
3182
3533
 
3183
- A workspace reaches the model through `context.workspaces`, and this is the only channel documents have. `build()` renders the active workspace by carrier on every turn — active-only and scope-filtered — so the workspace the agent is working in is always what the prompt reflects, with nothing to re-mount after an edit. 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.
3534
+ 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.
3184
3535
 
3185
3536
  ```ts
3186
3537
  import type { ProviderInterface } from '@orkestrel/agent'
@@ -3190,17 +3541,17 @@ import { createToolManager } from '@orkestrel/tool'
3190
3541
  declare const provider: ProviderInterface
3191
3542
  const agent = createAgent(provider, { tools: createToolManager(), authority })
3192
3543
 
3193
- // The first add auto-activates — agent.context.workspaces.active is this workspace, so build()
3194
- // renders its text files into the `## Workspace` section on every turn.
3544
+ // The first add auto-activates — agent.context.workspaces.active is this workspace, so each build
3545
+ // renders its text files into the `## Workspace` section.
3195
3546
  const workspace = agent.context.workspaces.add()
3196
3547
  workspace.write('notes.txt', 'The vault code is 7731.')
3197
3548
  ```
3198
3549
 
3199
- Reading is one half. To let the model edit what it reads, register the `createWorkspaceTool` published by `@orkestrel/toolbox` on `agent.context.tools` over this same `context.workspaces` registry: an `operation`-keyed `ToolInterface` whose dispatch and error semantics are that package's to document. The surfaces then close a loop — the model reads the workspace from the prompt, edits it through a tool call, and reads the edited version on the next turn.
3550
+ Reading is one half. To let the model edit what it reads, register the `createWorkspaceTool` published by `@orkestrel/toolbox` on `agent.context.tools` over this same `context.workspaces` registry: an `operation`-keyed `ToolInterface` whose dispatch and error semantics are that package's to document. The tool acts on the workspace the run shows, which each call receives as `context.caller`, so the model edits the workspace it reads in every conversation, and the next turn's request renders the edit. The tool reaches the files the prompt can render and no other: under a `files` list it refuses a path the list omits, lists and searches the listed files alone, and creates only a listed path. With no `files` list it reaches every file of the shown workspace.
3200
3551
 
3201
3552
  ### Switching which workspace the prompt carries
3202
3553
 
3203
- Only the active workspace renders; the other registered workspaces never reach the model at all. `switch` changes which one the prompt carries between runs:
3554
+ One workspace renders: the one a run shows through a `switch` call or the `workspace` option, as [Enabling the built-in tools](#enabling-the-built-in-tools) states, else the active one. The registry's `switch` method moves the active pointer, which every conversation of the agent reads, and changes which workspace the prompt carries between runs:
3204
3555
 
3205
3556
  ```ts
3206
3557
  import type { ProviderInterface } from '@orkestrel/agent'
@@ -3223,7 +3574,7 @@ agent.context.workspaces.switch(other.id) // build() renders other's files from
3223
3574
  agent.context.apply(createScope({ name: 'cfg', files: ['src/config.ts'] }))
3224
3575
  ```
3225
3576
 
3226
- A switch between runs changes the files the next run's prompt carries, and `scope.files` then filters the switched workspace's files by path.
3577
+ A switch between runs changes the files the next run's prompt carries, and `scope.files` then filters the switched workspace's files by path. The same list bounds the workspace tool, so a file the list omits is neither rendered nor reachable by a tool call.
3227
3578
 
3228
3579
  ### Switching modes with a scope
3229
3580
 
@@ -3286,7 +3637,28 @@ try {
3286
3637
  }
3287
3638
  ```
3288
3639
 
3289
- Overlapping runs on one agent share its scope and its default handler, so an `apply` made for one run reaches every run in flight at its next site. Runs that need different modes at the same moment need separate agents.
3640
+ Overlapping runs on one agent share its scope and its default handler, so an `apply` made for one run reaches every run in flight at its next site. A run that needs its own mode while others run passes that mode as its `scope` run option, as [Scoping a turn](#scoping-a-turn) states: each turn of that run reads the shared scope intersected with its own, and its own `select` runs in place of the shared one. A run scope narrows the shared scope and never widens it, so a run that needs a mode wider than the shared scope needs another agent. The following runs overlap on two threads, each under its own mode:
3641
+
3642
+ ```ts
3643
+ // `agent`, `modes`, and `triage` come from the preceding example, whose provider answers each run.
3644
+ const verbatim = modes.get('verbatim')
3645
+ if (triage === undefined || verbatim === undefined) throw new Error('Missing mode')
3646
+ const triageThread = agent.context.conversations.add()
3647
+ const verbatimThread = agent.context.conversations.add()
3648
+ agent.context.apply(undefined)
3649
+ const [sorted, quoted] = await Promise.all([
3650
+ agent.generate({
3651
+ conversation: triageThread,
3652
+ prompt: { content: 'Sort ticket 7.' },
3653
+ scope: triage,
3654
+ }), // `recent` selects; `lookup` is advertised
3655
+ agent.generate({
3656
+ conversation: verbatimThread,
3657
+ prompt: { content: 'Quote the thread.' },
3658
+ scope: verbatim,
3659
+ }), // the pass-through selects; no tool is advertised
3660
+ ])
3661
+ ```
3290
3662
 
3291
3663
  ### Answering without tools
3292
3664
 
@@ -3318,13 +3690,13 @@ const result = await agent.generate() // { content: 'Refunds need a manager.', p
3318
3690
 
3319
3691
  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.
3320
3692
 
3321
- | Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
3322
- | -------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
3323
- | Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
3324
- | 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 |
3325
- | 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` |
3326
- | 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 |
3327
- | 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 the ledger refuses no over-window prompt |
3693
+ | Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
3694
+ | -------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
3695
+ | Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
3696
+ | 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 |
3697
+ | 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` |
3698
+ | 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 |
3699
+ | 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 |
3328
3700
 
3329
3701
  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:
3330
3702
 
@@ -3502,8 +3874,134 @@ copies[0]
3502
3874
  // 'Is the Brightwater Studio refund approved yet?' — what the first ledger writes for the same request
3503
3875
  ```
3504
3876
 
3877
+ A ledger compares its tool definitions again at the entry of every request, whether its gauge came from a calibration, a snapshot, or the `gauge` option. A tool a host adds to the ledger's agent, or removes from it, between two requests drops the gauge, and the next `respond` call calibrates before its first pass, so the plan prices the definitions the request carries. The following ledger prices a definition added after construction, whose calls the ledger still denies:
3878
+
3879
+ ```ts
3880
+ import type { LedgerInterface } from '@orkestrel/agent'
3881
+ import { createTool } from '@orkestrel/tool'
3882
+
3883
+ declare const ledger: LedgerInterface // a calibrated ledger between two requests
3884
+
3885
+ const before = ledger.gauge?.overhead
3886
+ ledger.agent.context.tools.add(
3887
+ createTool({
3888
+ name: 'lookup_invoice',
3889
+ description: 'Read an invoice by its id.',
3890
+ parameters: { type: 'object', properties: { id: { type: 'string' } } },
3891
+ execute: () => 'Invoice 42 is paid.',
3892
+ }),
3893
+ )
3894
+ await ledger.respond('Is invoice 42 paid?') // calibrates before its first pass
3895
+ ledger.gauge?.overhead // above `before`: the overhead prices the added definition
3896
+ ```
3897
+
3898
+ A calibration call that reports a prompt over `capacity`, the head included, is refused, not measured. The following ledger's provider reports a prompt of 9000 for the call that carries the definitions, against a capacity of 8192:
3899
+
3900
+ ```ts
3901
+ import type { LedgerOptions, ProviderInterface } from '@orkestrel/agent'
3902
+ import { createLedger, isLedgerError } from '@orkestrel/agent'
3903
+
3904
+ declare const provider: ProviderInterface // reports a prompt of 9000 for the call with the definitions
3905
+ declare const options: LedgerOptions // the judge, system, topics, questions, and thresholds above, capacity 8192, no gauge
3906
+
3907
+ const ledger = createLedger(provider, options)
3908
+ const refused = await ledger.calibrate(AbortSignal.timeout(30_000)).catch((error: unknown) => error)
3909
+ isLedgerError(refused) ? refused.code : refused // 'GAUGE'
3910
+ isLedgerError(refused) ? refused.context : refused // { capacity: 8192, prompt: 9000 }
3911
+ isLedgerError(refused) ? refused.message : refused // 'the calibration call with the tool definitions prices 9000 tokens, the head included, over the capacity 8192; hold tools behind a skill with the `load` built-in, register fewer tools, or raise capacity'
3912
+ ledger.gauge // undefined — and the provider received the call with the definitions alone
3913
+ ```
3914
+
3505
3915
  To serve a thinking model, pass its context window as the `capacity` option and its generation cap, thinking included, as the `predict` option, and set the boolean `think` option to request or suppress thinking for the first pass. The answer pass always runs with thinking off. The plan then budgets what the window leaves after the cap, the recall room keeps the cap free, and the gauge counts only the thinking the next request carries; see [Serving a conversation through a ledger](#serving-a-conversation-through-a-ledger) for the budget.
3506
3916
 
3917
+ #### Disclosing skills through a ledger
3918
+
3919
+ A ledger serves the built-in tools through the `builtins` member of its `agent` option, under the rules **The built-ins.** and **The capacity gate.** state under [Serving a conversation through a ledger](#serving-a-conversation-through-a-ledger). Register a large tool set behind skills and enable `load`: calibration then measures only the definitions no skill holds back, so the plan keeps the room of that ungated core, and a skill's tools join a request after the model loads the skill. The following ledger holds a refund lookup back behind a skill, and the model loads the skill before it calls the lookup:
3920
+
3921
+ ```ts
3922
+ import type { LedgerLookup, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
3923
+ import { createAuthority, createLedger, createSkillManager } from '@orkestrel/agent'
3924
+
3925
+ declare const options: LedgerOptions // the judge, system, topics, questions, thresholds, and capacity, with no gauge
3926
+ declare const lookup: LedgerLookup // `lookup_order`, which reads an order by its id
3927
+ declare const refund: LedgerLookup // `lookup_refund`, which reads the refund rule of an order
3928
+ declare const provider: ProviderInterface // calibrates, calls load with { skill: 'refunds' }, then lookup_refund, then answers
3929
+
3930
+ const skills = createSkillManager()
3931
+ skills.add({
3932
+ name: 'refunds',
3933
+ description: 'Refund rules for a paid order.',
3934
+ content: 'Read the refund rule before you answer about a refund.',
3935
+ tools: ['lookup_refund'],
3936
+ })
3937
+ const ledger = createLedger(provider, {
3938
+ ...options,
3939
+ lookups: [lookup, refund],
3940
+ agent: {
3941
+ skills,
3942
+ builtins: ['load', 'unload'],
3943
+ authority: createAuthority({ fallback: { zone: 'desk', verdict: 'allow' } }),
3944
+ },
3945
+ })
3946
+ const advertised: Array<readonly string[] | undefined> = []
3947
+ ledger.agent.emitter.on('request', (_index, request) =>
3948
+ advertised.push(request.tools?.map(({ name }) => name)),
3949
+ )
3950
+ await ledger.respond('Can order BW-5512 be refunded?')
3951
+ advertised[0] // ['lookup_order', 'load', 'unload']: the refunds skill holds lookup_refund back
3952
+ advertised[1] // ['lookup_order', 'lookup_refund', 'load', 'unload'], after the load
3953
+ ```
3954
+
3955
+ Calibration priced `lookup_order`, `recall`, `load`, and `unload`, and never `lookup_refund`. A fresh thread's first request carries `load` and the ungated definitions other than `recall`, which the ledger offers only on a request with something earlier to find, and no tool a skill holds. While the first request advertised `load`, its plan held back the price of the `refunds` body and its lookup and the price of one result, so the load had room.
3956
+
3957
+ A memo set serves one principal, as **The store keyed by principal.** under [Serving one agent per principal](#serving-one-agent-per-principal) states for an agent. Give every ledger of a principal the same `MemoManager` value through the `memos` member of its `agent` option, and save that set from its `add` event, because Agent loads and saves no memo store. A memo one ledger writes then reaches the store and every other ledger of that principal, and two ledgers that each write one during overlapping requests keep both. `remember` writes only a name the ceiling's `memos` list holds, so apply a scope that lists the names a ledger may write:
3958
+
3959
+ ```ts
3960
+ import type { LedgerAgentOptions, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
3961
+ import {
3962
+ createAuthority,
3963
+ createLedger,
3964
+ createMemoManager,
3965
+ createMemoryMemoStore,
3966
+ createScope,
3967
+ } from '@orkestrel/agent'
3968
+
3969
+ declare const options: LedgerOptions // the judge, system, topics, questions, thresholds, and capacity, with a stored gauge
3970
+ declare const north: ProviderInterface // calls remember for north_notes, then answers
3971
+ declare const south: ProviderInterface // calls remember for south_notes, then answers
3972
+
3973
+ const store = createMemoryMemoStore()
3974
+ const stored = await store.get('ada')
3975
+ const memos = createMemoManager(stored === undefined ? { id: 'ada' } : { snapshot: stored })
3976
+ const saves: Array<Promise<void>> = []
3977
+ memos.emitter.on('add', () => {
3978
+ saves.push(store.set(memos.snapshot()))
3979
+ })
3980
+ const agent: LedgerAgentOptions = {
3981
+ memos,
3982
+ builtins: ['memo', 'remember'],
3983
+ // remember is consequential, so this ask, which approves every call, approves each write.
3984
+ authority: createAuthority({ fallback: { zone: 'desk', verdict: 'allow' }, ask: () => true }),
3985
+ }
3986
+ const scope = createScope({ name: 'ada', memos: ['north_notes', 'south_notes'] })
3987
+ const desks = [
3988
+ { provider: north, request: 'Save the north desk shipping day.' },
3989
+ { provider: south, request: 'Save the south desk shipping day.' },
3990
+ ]
3991
+ await Promise.all(
3992
+ desks.map(({ provider, request }) => {
3993
+ const ledger = createLedger(provider, { ...options, agent })
3994
+ ledger.agent.context.apply(scope)
3995
+ return ledger.respond(request)
3996
+ }),
3997
+ )
3998
+ await Promise.all(saves)
3999
+ memos.memo('north_notes')?.content // 'The north desk ships on Friday.'
4000
+ memos.memo('south_notes')?.content // 'The south desk ships on Monday.'
4001
+ const saved = await store.get('ada')
4002
+ saved?.memos.length // 2
4003
+ ```
4004
+
3507
4005
  #### Composing a records desk for a small local GPU
3508
4006
 
3509
4007
  A records desk on a small local GPU runs two models by role: the agent's provider writes the replies, and the ledger's judge files the messages. Pass the provider as the first argument of the `createLedger` function and the judge as its `judge` option. The window and the `recall` offer are the ledger's own behavior and need no configuration.
@@ -3588,9 +4086,104 @@ The application decides which models to run, which thresholds to keep, and wheth
3588
4086
 
3589
4087
  The same line holds for what a request carries beyond its messages. To have a judge choose the tools, instructions, memos, or skills of a request, ask the judge before the request and apply the answer through the `narrow` method of the active scope. Narrowing only tightens, so an answer can't admit a tool the scope excludes. A tool list or system text that changes between requests costs the reuse of the prompt, and a wrong answer withholds that tool for the request.
3590
4088
 
4089
+ Choose how a request shows a large tool catalog from what the host knows about the request. One recorded reading stands behind the following figures, and they're practice, not a promise: on 2026-11-12, on one host, `qwen3.5:4b-q4_K_M` on Ollama 0.40.16 served 42 requests over a fictional desk catalog of 36 tools in six areas of 6, through the `disclosure` study, whose steps the Running the disclosure reading section of `studies/README.md` in this repository lists. Read each figure as a baseline that tells a small change from a large one, and take your own reading on your model and catalog before you rely on one. A request counts as right when its first call other than `load` names the tool it needs, and first text is the median seconds to the first reply text on a conversation's first request:
4090
+
4091
+ | Composition | Right | Median prompt, tokens a request | First text |
4092
+ | ----------------------------------------------- | -------- | ------------------------------- | ---------- |
4093
+ | The known area's 6 tools, through a run scope | 42 of 42 | 1947.5 | 3.79 s |
4094
+ | The skills index and `load`, with nothing shown | 40 of 42 | 2791 | 6.20 s |
4095
+
4096
+ The reading suggests the following practice for a small model:
4097
+
4098
+ - **When the host knows the request's area,** scope the request to that area's tools. That composition read 42 of 42 at the smaller median prompt.
4099
+ - **When it doesn't,** advertise the skills index and `load` with nothing shown. That composition read 40 of 42, and each of its 15 loads opened the skill the request needed. Its first text waits for the load's round trip: 6.20 s on a conversation's first request, and 8.45 s on a later request that loaded.
4100
+ - **Serve a request under its area's scope whenever the host can tell its area,** request by request, a thread that began on the skills index included, and keep the index and `load` for the request the host can't place.
4101
+
4102
+ No request in the reading was refused for room or failed, and the `skills` share denied no `load`.
4103
+
4104
+ One skill registry serves both compositions, because a skill's `tools` list is its area. To serve a request under its area, build the request's scope from that skill: list the skill's tools, each ungated tool the request may use, and `recall` on a ledger, leave `load` out, and set `skills: []`. With no `load` in the allow-list, the allow-list alone decides what a turn advertises, and the empty `skills` list drops the skills index and every loaded body from the head. A host that already applies a ceiling for authority builds each request's scope through that ceiling's `narrow` method, which intersects each list, so an area never widens the ceiling. The following ledger applies each request's scope before its `respond` call:
4105
+
4106
+ ```ts
4107
+ import type { LedgerLookup, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
4108
+ import { createAuthority, createLedger, createScope, createSkillManager } from '@orkestrel/agent'
4109
+
4110
+ declare const options: LedgerOptions // the judge, system, topics, questions, thresholds, and capacity, with no gauge
4111
+ declare const lookups: readonly LedgerLookup[] // `lookup_order`, `lookup_refund`, and `lookup_invoice`
4112
+ declare const provider: ProviderInterface // calibrates, then answers each request with no call
4113
+
4114
+ // One skill registry serves the area scope and the skills index.
4115
+ const skills = createSkillManager()
4116
+ skills.add([
4117
+ {
4118
+ name: 'refunds',
4119
+ description: 'Refund rules for a paid order.',
4120
+ content: 'Read the refund rule before you answer about a refund.',
4121
+ tools: ['lookup_refund'],
4122
+ },
4123
+ {
4124
+ name: 'billing',
4125
+ description: 'Invoices and their payments.',
4126
+ content: 'Read the invoice before you answer about a payment.',
4127
+ tools: ['lookup_invoice'],
4128
+ },
4129
+ ])
4130
+ const ledger = createLedger(provider, {
4131
+ ...options,
4132
+ lookups,
4133
+ agent: {
4134
+ skills,
4135
+ builtins: ['load'],
4136
+ authority: createAuthority({ fallback: { zone: 'desk', verdict: 'allow' } }),
4137
+ },
4138
+ })
4139
+ const advertised: Array<readonly string[] | undefined> = []
4140
+ ledger.agent.emitter.on('request', (_index, request) =>
4141
+ advertised.push(request.tools?.map(({ name }) => name)),
4142
+ )
4143
+ const requests = [
4144
+ { area: 'refunds', text: 'Can order BW-5512 be refunded?' },
4145
+ { area: 'billing', text: 'Is invoice 42 paid?' },
4146
+ ]
4147
+ for (const { area, text } of requests) {
4148
+ // The area's tools, the ungated lookup, and `recall`; no `load`, and no skill.
4149
+ const tools = skills.skill(area)?.tools ?? []
4150
+ ledger.agent.context.apply(
4151
+ createScope({ name: area, tools: ['lookup_order', ...tools, 'recall'], skills: [] }),
4152
+ )
4153
+ await ledger.respond(text)
4154
+ }
4155
+ advertised[0] // ['lookup_order', 'lookup_refund']
4156
+ advertised[1] // ['lookup_order', 'lookup_invoice']
4157
+ ```
4158
+
4159
+ Each request advertised its area alone, its `system` message held neither the skills index nor a skill's body, and no calibration call came between the two requests, because a scope change leaves the calibrated set as it was.
4160
+
4161
+ A request the host can't place and a request it can share one thread. When the host learns the area after a request it served on the skills index, it serves the next request under that area's scope: the empty `skills` list drops the loaded bodies from the head, the conversation keeps the `load` record, and a later request on the index shows the loaded skill again with no further `load`. The following requests continue the preceding ledger:
4162
+
4163
+ ```ts
4164
+ import { createScope } from '@orkestrel/agent'
4165
+
4166
+ // `ledger`, `skills`, and `advertised` come from the preceding example. The provider loads
4167
+ // refunds, calls lookup_refund, and answers, then answers each later request with no call.
4168
+ ledger.agent.context.apply(undefined) // the skills index and `load`, for a request the host can't place
4169
+ await ledger.respond('Can order BW-5513 be refunded?')
4170
+ const billing = skills.skill('billing')?.tools ?? []
4171
+ ledger.agent.context.apply(
4172
+ createScope({ name: 'billing', tools: ['lookup_order', ...billing, 'recall'], skills: [] }),
4173
+ )
4174
+ await ledger.respond('Is invoice 43 paid?')
4175
+ ledger.agent.context.apply(undefined)
4176
+ await ledger.respond('Does order BW-5513 need a manager?')
4177
+ advertised.at(-3) // ['lookup_order', 'lookup_refund', 'load'], after the load
4178
+ advertised.at(-2) // ['lookup_order', 'lookup_invoice', 'recall']: billing alone, with no index and no body
4179
+ advertised.at(-1) // ['lookup_order', 'lookup_refund', 'load']: refunds shown with no further load
4180
+ ```
4181
+
4182
+ A skill the model loads stays shown for the rest of its thread, on a ledger as on a bare agent. On 2026-11-12, on the same host, `qwen3.5:4b-q4_K_M` on a ledger built and hydrated for each request, with the skills index and `load`, read 37 of 42 on the same desk battery, where a bare agent read 40 of 42. It read 7 of 7 on a conversation's first request, and 24 of 26 on a request in an area the thread had already loaded, with no further load. It read 6 of 9 on a request that entered another area after a load: the model loaded on 8 of those 9, named the wrong skill on 1, and on 1 called a tool of the skill already shown. A wrong load stays shown for the thread, and in that run it drew the next request's call too. The ledger's window carries earlier requests and replies, never their calls, so a later request doesn't see the thread's earlier `load` call, and the loaded skill stays shown. On a consumer application's catalog registered behind skills, the same model on a ledger loaded 3 times in 10 requests, and 1 of those loads was right. A skill's name and description are what the model chooses from, so a skill named for a resource it doesn't hold draws wrong loads. A host that sees wrong loads on a thread served on the index enables `unload` beside `load`, or opens another thread.
4183
+
3591
4184
  ### Upgrade data written before 0.0.35
3592
4185
 
3593
- Stored data written before 0.0.35 meets the checks of 0.0.35 at its next read. A snapshot that carries a member its shape doesn't declare, the conversation `summary` a 0.0.29 snapshot can hold included, refuses at its next read as well: the stores throw `'SNAPSHOT'` naming the key, because a refused row read as absent would let `open` overwrite it. Read that row through your own table and rewrite it without the key, or delete it with `store.delete`. A stored snapshot that holds a `system` row rejects with `ConversationError` `'ROLE'` and the message `a conversation snapshot holds a system message; a snapshot written before 0.0.35 can hold a system row; remove it before loading`. A queued `AgentJobInput` seed that holds a `system` message fails at `AgentRegistry.build` through `add`, with `ConversationError` `'ROLE'` and the message `a stored message role must be one of "user", "assistant", "tool"; received "system"; host text goes in the system option or an instruction`, and the job's `system` member carries that text.
4186
+ 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.
3594
4187
 
3595
4188
  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:
3596
4189
 
@@ -3711,14 +4304,14 @@ The following practices apply when you build on this package:
3711
4304
  - **Create and edit files through `@orkestrel/workspace`** — the file domain is that package's, and `AgentContext` borrows only its `isTextContent` / `isBinary` guards to decide a file's carrier. The rendering belongs to this package: the `## Workspace` fencing and the binary-plus-`image/` attachment are prompt policy that belongs here, not workspace helpers that belong there.
3712
4305
  - **Judge the argument the model passed** — a tool handler that asks a judge about a model's tool call judges the argument that call carried, or its tool description says it judges a fixed input.
3713
4306
  - **Write a refusal as the next step** — a refusal text a tool returns names the one next call and says nothing about who asked, because a reasoning model mid-task reads a refusal that addresses the user as a user turn.
3714
- - **Give the model both halves of a workspace** — `context.workspaces` is what it reads, rendered by carrier every turn, active-only and filtered by `scope.files`; the `createWorkspaceTool` published by `@orkestrel/toolbox` over that same registry is what it writes. For workspace editing, errors, and persistence, see [Workspace](workspace.md); for tool dispatch semantics, see [Tool](tool.md).
4307
+ - **Give the model both halves of a workspace** — `context.workspaces` is what it reads, one workspace rendered by carrier at each build and filtered by `scope.files`; the `createWorkspaceTool` published by `@orkestrel/toolbox` over that same registry is what it writes. For workspace editing, errors, and persistence, see [Workspace](workspace.md); for tool dispatch semantics, see [Tool](tool.md).
3715
4308
 
3716
4309
  ## Tests
3717
4310
 
3718
4311
  The following test files back this guide:
3719
4312
 
3720
- - [`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 skill load's timing, the over-window paths, the no-slice fold, and a second `select` during a paced filing.
3721
- - [`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`, `renderJSON`, `matchesJSON`, and `matchesJudgment`, the `MESSAGE_ROLES` role list, and the `CONVERSATION_ROLES` stored role list with the `ConversationRole` and `MessageInput` role types.
4313
+ - [`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.
4314
+ - [`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.
3722
4315
  - [`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.
3723
4316
  - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — the root guards `isJudgeEntry`, `isJudgeQuestion`, and `isNonNegativeSafeInteger`, each total over malformed input.
3724
4317
  - [`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.
@@ -3743,36 +4336,37 @@ The following test files back this guide:
3743
4336
  - [`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.
3744
4337
  - [`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`.
3745
4338
  - [`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.
3746
- - [`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 `build(selection)`.
4339
+ - [`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.
3747
4340
  - [`tests/src/core/contexts/factories.test.ts`](../tests/src/core/contexts/factories.test.ts) — `createInstruction`, `createInstructionManager`, `createScope`, `createScopeManager`, `createMemoManager`, `createMemoryMemoStore`, `createDatabaseMemoStore`, `createSkillManager`, and `createAgentContext`, with the memo store contract both stores run.
3748
- - [`tests/src/core/contexts/helpers.test.ts`](../tests/src/core/contexts/helpers.test.ts) — `renderFencedFile`, `renderSection`, `renderIndexEntry`, `attachImages`, `attachUserImages`, `collectImageData`, and `intersectKeys`.
3749
- - [`tests/src/core/contexts/validators.test.ts`](../tests/src/core/contexts/validators.test.ts) — `isMemo` and `isMemoSnapshot`, each total over malformed input, a sparse `memos` array, a throwing getter, a revoked proxy, and a function carrying a revision's members.
4341
+ - [`tests/src/core/contexts/helpers.test.ts`](../tests/src/core/contexts/helpers.test.ts) — `renderFencedFile`, `renderSection`, `renderIndexEntry`, `renderIndexLine`, `renderSkillBody`, `attachImages`, `attachUserImages`, `collectImageData`, `intersectKeys`, and `intersectFilters` with its list-by-list intersection, absent side, fresh copies, and one read per list.
4342
+ - [`tests/src/core/contexts/validators.test.ts`](../tests/src/core/contexts/validators.test.ts) — `isMemo` and `isMemoSnapshot`, each total over malformed input, a sparse `memos` array, a throwing getter, a revoked proxy, and a function carrying a revision's members, and `isScope` over a malformed `workspaces` list, a throwing getter, a revoked proxy, a counting proxy, a class instance, and unknown members.
3750
4343
  - [`tests/src/core/contexts/instructions/Instruction.test.ts`](../tests/src/core/contexts/instructions/Instruction.test.ts) — the minted id, default priority, carried override, and immutability of `Instruction`.
3751
4344
  - [`tests/src/core/contexts/instructions/InstructionManager.test.ts`](../tests/src/core/contexts/instructions/InstructionManager.test.ts) — the instruction registry's lookup, ordering, build contract, manager-options format, removal, and emitter.
3752
4345
  - [`tests/src/core/contexts/memos/MemoManager.test.ts`](../tests/src/core/contexts/memos/MemoManager.test.ts) — the memo set's revisions, unchanged-text no-op, history, ordering, removal of a whole history, snapshot round trip and silent hydration, format cascade, and emitter.
3753
- - [`tests/src/core/contexts/scopes/Scope.test.ts`](../tests/src/core/contexts/scopes/Scope.test.ts) — `Scope` construction, the `skills` and `memos` lists, the set intersection of `narrow`, and the `select` handler travelling with the scope.
4346
+ - [`tests/src/core/contexts/scopes/Scope.test.ts`](../tests/src/core/contexts/scopes/Scope.test.ts) — `Scope` construction, the `skills`, `memos`, and `workspaces` lists, the set intersection of `narrow`, and the `select` handler travelling with the scope.
3754
4347
  - [`tests/src/core/contexts/scopes/ScopeManager.test.ts`](../tests/src/core/contexts/scopes/ScopeManager.test.ts) — the scope registry's add, lookup, removal, and emitter.
3755
- - [`tests/src/core/contexts/skills/SkillManager.test.ts`](../tests/src/core/contexts/skills/SkillManager.test.ts) — the skill registry's add, files minted through `createFile`, same-name replace, lookup, removal, format cascade, and emitter.
4348
+ - [`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.
3756
4349
  - [`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.
3757
4350
  - [`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.
3758
- - [`tests/src/core/agents/Agent.test.ts`](../tests/src/core/agents/Agent.test.ts) — the loop over a scripted provider: the recorded-request control, scope dispatch, tool iteration, authority, `generate` and `stream` parity, chunks, bounds, cancellation timing, the emitter, automatic compaction, recorded thinking and the replay policy, multi-conversation runs and the run-bound conversation under a switch, a fold, and a removal, limit exhaustion, budget reconciliation, per-run options, the concurrency guard with its refusal of a second run on one conversation, usage sanitizing, the selection seam, the turn records, the three failure layers, the stored-ingress canary that refuses a `system` message through `add`, a snapshot, a job seed, and a selection and sends none, the scope denial of a name no definition advertises under every verdict, the `ask` chunk and its order, the approver over a real run with its page answers, timeouts, aborts, and injected arguments, the `prompt` option with its exact check and its append after the run's guards, and the forwarded skills and memos.
3759
- - [`tests/src/core/agents/AgentRegistry.test.ts`](../tests/src/core/agents/AgentRegistry.test.ts) — the registry's accessors, rehydrating `build` and its field wiring, a job seed holding a `system` role refused, isolation, the conversation store seam, and an empty registry.
4351
+ - [`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.
4352
+ - [`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.
4353
+ - [`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.
3760
4354
  - [`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.
3761
4355
  - [`tests/src/core/agents/Approver.test.ts`](../tests/src/core/agents/Approver.test.ts) — the bound `ask`, the ask registered before it suspends, the frame's members and minted id, strict approval, identity keying, the missed mark, the second-ask and unrenderable-argument refusals with the call name encoded, and the release of the run signal on an answer and an abort.
3762
4356
  - [`tests/src/core/agents/Channel.test.ts`](../tests/src/core/agents/Channel.test.ts) — the channel's lost-wakeup, `undefined` values, buffer-before-close, `fail`, concurrent readers, push after end, FIFO order, end semantics, the unread rest before an end, and a `return()` while a read is parked.
3763
4357
  - [`tests/src/core/agents/ChannelCell.test.ts`](../tests/src/core/agents/ChannelCell.test.ts) — the internal `ChannelCell` class: a new cell's value with no next cell, and the `link` method's latch, which keeps the first linked cell.
3764
- - [`tests/src/core/agents/factories.test.ts`](../tests/src/core/agents/factories.test.ts) — `createChannel`, `createAgent`, `createApprover`, `createAgentRegistry`, `createAgentQueue` with its durability, partial policy, and lifecycle, `createAgentRunner` with fan-out, and the `AgentJobError` / `isAgentJobError` block.
3765
- - [`tests/src/core/agents/helpers.test.ts`](../tests/src/core/agents/helpers.test.ts) — `agentResultToJSON` with its `stop` projection, `tokenUsageToJSON`, `inferStop`, `requireBudget`, `requireConversation`, `estimateMessages`, `estimateRequest`, `measureMessage`, `measureRequest`, `settleAgentJob`, `assembleResult`, `denyCall` with each denial note, `renderArguments` with its escaped code points, `agentChunkToFrame`, `agentResultToFrame`, `agentStreamToFrames` with its one terminal frame and the frame canary, `resolveDecision`, and `chargeUsage`.
3766
- - [`tests/src/core/agents/shapers.test.ts`](../tests/src/core/agents/shapers.test.ts) — the frame, prompt, and answer wire shapes inferring their domain types both ways.
3767
- - [`tests/src/core/agents/contracts.test.ts`](../tests/src/core/agents/contracts.test.ts) — the frame, prompt, and answer contracts over every frame arm and every refused wire row, a throwing `Proxy`, and seeded values that agree with `parse`.
4358
+ - [`tests/src/core/agents/factories.test.ts`](../tests/src/core/agents/factories.test.ts) — `createChannel`, `createAgent`, `createApprover`, `createAgentRegistry`, `createAgentQueue` with its durability, partial policy, and lifecycle, `createAgentRunner` with fan-out, the `AgentJobError` / `isAgentJobError` block, and `createBuiltinTool` with its argument door built from `builtinToolContracts` and its `BUILTIN_TOOLS` text.
4359
+ - [`tests/src/core/agents/helpers.test.ts`](../tests/src/core/agents/helpers.test.ts) — `agentResultToJSON` with its `stop` projection, `tokenUsageToJSON`, `inferStop`, `requireBudget`, `requireConversation`, `requireScope`, `scanJobTree` with each exceeded member, every depth, a malformed or unreadable job, and the refused-job prefix, `estimateMessages`, `estimateRequest`, `measureMessage`, `measureRequest`, `settleAgentJob`, `assembleResult`, `denyCall` with each denial note, `renderArguments` with its escaped code points, `agentChunkToFrame`, `agentResultToFrame`, `agentStreamToFrames` with its one terminal frame and the frame canary, `resolveDecision`, `chargeUsage`, `collectBuiltinDefinitions` with the `BUILTIN_TOOLS` record it reads and the `builtinToolContracts` parameters, `requireBuiltins` with the names `isAgentBuiltin` admits, `requireWorkspace`, `filterAdvertisedTools` over its hold table, `filterBuiltinCandidates` over absent, empty, and naming lists, `describeCandidates` with its cap, `matchesPlainLine` over the `ARGUMENT_BLANK_PATTERN` and `ARGUMENT_CONTROL_PATTERN` classes, `matchesHeadLists`, `resolveDisclosure`, and `collectDisclosure` with its derivation table and the runs the loop stored.
4360
+ - [`tests/src/core/agents/shapers.test.ts`](../tests/src/core/agents/shapers.test.ts) — the frame, prompt, and answer wire shapes inferring their domain types both ways, and the built-in argument shapes over each cap and each refused member.
4361
+ - [`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`.
3768
4362
  - [`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.
3769
- - [`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, and the partial policy.
3770
- - [`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 `'REQUEST'` fault of a run no active `respond` call owns, a run on another conversation, and the refused direct run during a request, 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, the flush before capture, 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 run and its recall, 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.
3771
- - [`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, and the listings of a recall result.
4363
+ - [`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.
4364
+ - [`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.
4365
+ - [`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.
3772
4366
  - [`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.
3773
- - [`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.
4367
+ - [`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.
3774
4368
  - [`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.
3775
- - [`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, `findLedgerCall`, `rankLedgerCut`, `findLedgerCut`, `buildLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `buildRequestMessage`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `resolvePredict`, `fitSlope`, `digestLedgerWindow`, `collectRecallMessages`, `collectRetiredFindings`, `hasHiddenRecall`, `buildLedgerLineKey`, `collectLedgerLines`, `collectLedgerReplies`, and `collectLedgerEvidence`.
4369
+ - [`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`.
3776
4370
  - [`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.
3777
4371
 
3778
4372
  ### Placement proofs