@orkestrel/scaffold 0.0.122 → 0.0.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/skills/orkestrel-harden/scripts/interleave.js +539 -0
- package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +1163 -0
- package/dist/bin/main.js +21 -19
- package/dist/bin/main.js.map +1 -1
- package/dist/host/agents/orchestration.md +13 -7
- package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +4 -3
- package/dist/host/agents/skills/orkestrel-dispatch/references/launch.md +1 -1
- package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +4 -2
- package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +2 -2
- package/dist/host/agents/skills/orkestrel-harden/SKILL.md +16 -3
- package/dist/host/agents/skills/orkestrel-harden/references/bindings.md +18 -12
- package/dist/host/agents/skills/orkestrel-harden/references/document.md +1 -0
- package/dist/host/agents/skills/orkestrel-harden/references/equivalence.md +2 -1
- package/dist/host/agents/skills/orkestrel-harden/references/hardening.md +1 -1
- package/dist/host/agents/skills/orkestrel-harden/references/methods.md +642 -0
- package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +665 -0
- package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +14 -13
- package/dist/host/agents/skills/orkestrel-parallel/references/claude-code.md +13 -13
- package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +1 -0
- package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1433 -0
- package/dist/host/agents/skills/orkestrel-publish/SKILL.md +2 -1
- package/dist/host/agents/skills/orkestrel-publish/references/wave.md +18 -1
- package/dist/host/claude/AGENTS.md +1 -1
- package/dist/host/claude/agents/analyst.md +1 -1
- package/dist/host/claude/agents/builder.md +1 -1
- package/dist/host/claude/agents/distiller.md +2 -1
- package/dist/host/claude/agents/grok.md +2 -2
- package/dist/host/claude/agents/opus.md +2 -2
- package/dist/host/claude/agents/orkestrel.md +30 -30
- package/dist/host/claude/agents/reviewer.md +2 -2
- package/dist/host/claude/agents/scout.md +2 -1
- package/dist/host/claude/agents/verifier.md +1 -1
- package/dist/host/claude/rules/campaign.md +12 -11
- package/dist/host/claude/rules/documentation.md +1 -0
- package/dist/host/claude/rules/patterns.md +14 -0
- package/dist/host/claude/rules/quality.md +4 -1
- package/dist/host/claude/rules/tests.md +4 -0
- package/dist/host/claude/rules/writing.md +1 -1
- package/dist/host/claude/skills/orkestrel-parallel/SKILL.md +1 -1
- package/dist/host/codex/agents/analyst.toml +4 -1
- package/dist/host/codex/agents/astra.toml +1 -1
- package/dist/host/codex/agents/builder.toml +1 -1
- package/dist/host/codex/agents/distiller.toml +4 -2
- package/dist/host/codex/agents/grok.toml +5 -2
- package/dist/host/codex/agents/opus.toml +3 -3
- package/dist/host/codex/agents/reviewer.toml +6 -2
- package/dist/host/codex/agents/scout.toml +5 -1
- package/dist/host/codex/agents/verifier.toml +6 -1
- package/dist/host/guides/agent.md +1119 -457
- package/dist/host/guides/contract.md +226 -104
- package/dist/host/guides/database.md +12 -12
- package/dist/host/guides/ndjson.md +94 -21
- package/dist/host/guides/ollama.md +22 -18
- package/dist/host/guides/probe.md +29 -27
- package/dist/host/guides/reason.md +377 -114
- package/dist/host/guides/scaffold.md +43 -21
- package/dist/host/guides/study.md +538 -450
- package/dist/host/guides/tool.md +163 -58
- package/dist/host/manifest.json +70 -52
- package/dist/src/core/index.cjs +21 -20
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +1 -4
- package/dist/src/core/index.d.ts +1 -4
- package/dist/src/core/index.js +21 -20
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +87 -8
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +50 -6
- package/dist/src/server/index.d.ts +50 -6
- package/dist/src/server/index.js +87 -10
- package/dist/src/server/index.js.map +1 -1
- package/package.json +15 -15
|
@@ -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 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
|
|
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`.
|
|
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 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 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.
|
|
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
|
|
|
@@ -51,7 +51,7 @@ const streamed = await print(provider.stream(messages, abort.signal)) // the ass
|
|
|
51
51
|
|
|
52
52
|
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.
|
|
53
53
|
|
|
54
|
-
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 before reaching the registry, with the scope denial.
|
|
54
|
+
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:
|
|
55
55
|
|
|
56
56
|
```ts
|
|
57
57
|
import { createTool, createToolManager } from '@orkestrel/tool'
|
|
@@ -99,7 +99,7 @@ const result = await provider.generate(input, abort.signal, definitions)
|
|
|
99
99
|
|
|
100
100
|
`context.messages.add` mints each message's `id` (a random UUID) and returns the created message(s); `build()` is computed fresh on every call, so it always reflects the current conversation. Without a system prompt, `build()` is only the conversation, and no tool's name, description, or parameter schema ever appears in its output.
|
|
101
101
|
|
|
102
|
-
Drive the whole turn with an `Agent` (`createAgent`) — it composes the provider, its `AgentContext`, and the tool registry into the bounded context → provider → tools → repeat loop. Seed the conversation through `agent.context.messages`, then either `generate()` for a one-shot `AgentResult` or `stream()` for a live `AgentChunk` stream (`token` answer deltas, `think` reasoning deltas, `
|
|
102
|
+
Drive the whole turn with an `Agent` (`createAgent`) — it composes the provider, its `AgentContext`, and the tool registry into the bounded context → provider → tools → repeat loop. Seed the conversation through `agent.context.messages`, then either `generate()` for a one-shot `AgentResult` or `stream()` for a live `AgentChunk` stream (`token` answer deltas, `think` reasoning deltas, `usage`, `ask` handoffs to the approver, `tool` dispatches) whose `result` resolves the same `AgentResult`. `generate` drains that same stream, so they can't diverge:
|
|
103
103
|
|
|
104
104
|
```ts
|
|
105
105
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
@@ -129,7 +129,7 @@ for await (const chunk of stream.events) {
|
|
|
129
129
|
const result = await stream.result // { content, usage?, partial } — usage summed across the turn
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
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. 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:
|
|
132
|
+
Both `generate` and `stream` accept optional per-run `AgentRunOptions` — `think` and `schema` (forwarded to the provider as `ProviderStreamOptions`) plus `limit` / `timeout` / `budget` / `allowance` / `signal`, each overriding its `AgentOptions` construction default for this run only. Omitting one keeps the constructed default, so a caller that passes no options gets the agent it configured. The same options carry `conversation`, which binds the run, and `prompt`, which the run appends as a `user` turn after its guards; a run with no `prompt` reads its request from the conversation's tail. A per-run `signal` composes with (never replaces) a constructed `signal` — either aborting cancels the run; the loop calls `start()` on a per-run `budget` or `allowance` for that run and charges it, leaving a constructed one untouched:
|
|
133
133
|
|
|
134
134
|
```ts
|
|
135
135
|
const agent = createAgent(provider, { tools, limit: 10, timeout: 60_000 }) // construction defaults
|
|
@@ -147,35 +147,59 @@ const result = await agent.generate({
|
|
|
147
147
|
|
|
148
148
|
The turn is bounded by one cancel folded from the external `signal` + the `timeout` deadline + the `budget` and `allowance` signals through `AbortSignal.any`; `agent.abort(reason)` (or `stream.abort(reason)`) fires it. A cancel — external, deadline, budget, allowance, or `abort()` — commits a partial result: the `result` promise resolves with `{ partial: true, content: <what accumulated> }`, never rejects (a cancel isn't an error); only a genuine provider / tool error rejects. A genuine provider error after streaming still charges the `budget` the failed call's streamed-answer estimate, once, before the run rejects. The loop yields to an optional `scheduler` between turns; tool iteration is capped at `limit` (default `DEFAULT_AGENT_LIMIT`). Exhausting `limit` while the model still holds unresolved tool intent (it requested tools on the very last allowed turn) is a distinct, non-cancel cause of `partial: true` — it fires an `exhaust` event (the turns reached) instead of `abort`. A natural finish on the last allowed turn, or `limit: 0` (which never enters the loop), stays `partial: false`. `agent.status` transitions `idle` → `running` → `done` / `error`.
|
|
149
149
|
|
|
150
|
-
Gate the model's tool calls with an optional `Authority` (`createAuthority`) — a synchronous policy gate the loop consults after scope admits a call, passed through `AgentOptions.authority`. It walks ordered `rules` first-match-wins (a matched rule allows unless its `
|
|
150
|
+
Gate the model's tool calls with an optional `Authority` (`createAuthority`) — a synchronous policy gate the loop consults after scope admits a call, passed through `AgentOptions.authority`. It walks ordered `rules` first-match-wins (a matched rule allows unless its `verdict` is `ask` or `deny`), falling back to a configurable default when none match — allow-unmatched by default (a denylist), or deny-by-default when its `fallback` denies (an allowlist). A denied call is never executed: the loop synthesizes the failure arm of `ToolResult` (`error: '"<name>" did not run: <reason>'`) and feeds it back as a `tool` chunk and a tool message, so no handler runs, no budget is spent, and the model still receives the denial and can request another call. An allowed call dispatches normally. An asked call dispatches only when the authority's `ask` approver resolves `true`; a refusal, a rejection, or no approver denies it. The loop raises an `allow` to an `ask` for a tool whose advertised definition is annotated `consequential`, and with no `authority` set it uses a default `Authority`, so every other scope-admitted call dispatches:
|
|
151
151
|
|
|
152
152
|
```ts
|
|
153
153
|
import { createAgent, createAuthority } from '@orkestrel/agent'
|
|
154
154
|
import { createTool, createToolManager } from '@orkestrel/tool'
|
|
155
155
|
|
|
156
|
-
// `provider` and `
|
|
156
|
+
// `provider`, `drop`, and `confirm` come from the host application.
|
|
157
157
|
const tools = createToolManager()
|
|
158
158
|
tools.add([
|
|
159
159
|
createTool({ name: 'add', execute: (args) => Number(args.a) + Number(args.b) }),
|
|
160
160
|
createTool({ name: 'delete', execute: (args) => drop(args.id) }),
|
|
161
161
|
])
|
|
162
162
|
|
|
163
|
-
// A denylist: deny `delete`, allow everything else (the default allow fallback)
|
|
163
|
+
// A denylist: deny `delete`, allow everything else (the default allow fallback), and answer an
|
|
164
|
+
// asked call through the host's `confirm`.
|
|
164
165
|
const authority = createAuthority({
|
|
165
166
|
rules: [
|
|
166
167
|
{
|
|
167
168
|
match: (c) => c.call.name === 'delete',
|
|
168
169
|
zone: 'restricted',
|
|
169
|
-
|
|
170
|
+
verdict: 'deny',
|
|
170
171
|
reason: 'read-only mode',
|
|
171
172
|
},
|
|
172
173
|
],
|
|
174
|
+
ask: (context) => confirm(`Run ${context.call.name}?`),
|
|
173
175
|
})
|
|
174
176
|
const agent = createAgent(provider, { tools, authority })
|
|
175
177
|
agent.context.messages.add({ role: 'user', content: 'Delete record 42.' })
|
|
176
|
-
// When the model calls `delete`, the loop feeds back { error: '
|
|
178
|
+
// When the model calls `delete`, the loop feeds back { error: '"delete" did not run: read-only mode' } — never runs it.
|
|
177
179
|
```
|
|
178
180
|
|
|
181
|
+
Every call passes the gate in one order: scope, then `evaluate`, then the `consequential` floor, then the approver, and a call that `allow` cleared is checked once more against the tool instance the turn advertised before it dispatches. The floor reads the advertised definition, so a tool annotated `consequential` asks with or without rules, and with no approver that ask is denied as unanswered. `ask: () => true` is the visible relaxation of the floor: it answers yes to every asked call.
|
|
182
|
+
|
|
183
|
+
Keep the two guard seams apart. An `ask` handler is a call guard: it reads the full `call`, so an approver must see that call before it answers, and it runs in the loop's own process, where a run `timeout` cancels it. An `execute` wrapper is a content guard: it reads what the handler returns and can refuse or rewrite it before the model reads it. The gate reads no model text, so rewording an injected instruction leaves its outcome unchanged, and it doesn't stop the model from choosing a tool that carries no annotation and no rule.
|
|
184
|
+
|
|
185
|
+
An allowlist is a `fallback` that denies, with one rule per listed tool. To stop a run at its first denial, call `agent.abort` from a `deny` listener, so the denied call stores nothing and no further turn runs. The following fence does both:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import type { ToolManagerInterface } from '@orkestrel/tool'
|
|
189
|
+
import { createAgent, createAuthority } from '@orkestrel/agent'
|
|
190
|
+
|
|
191
|
+
// `provider` comes from the host application.
|
|
192
|
+
declare const tools: ToolManagerInterface // holds `search` and `delete_order`
|
|
193
|
+
const authority = createAuthority({
|
|
194
|
+
rules: [{ match: (context) => context.call.name === 'search', zone: 'read' }],
|
|
195
|
+
fallback: { zone: 'blocked', verdict: 'deny', reason: 'that tool is not on the list' },
|
|
196
|
+
})
|
|
197
|
+
const agent = createAgent(provider, { tools, authority })
|
|
198
|
+
agent.emitter.on('deny', (call, reason) => agent.abort(`${call.name}: ${reason}`))
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
A rule's `reason` reaches the model verbatim in its denial, so the host authors every rule reason. A ledger lookup's finding is a records source: what a lookup returned enters the records of a later request, and the `read` handler names the ids and owners it files under.
|
|
202
|
+
|
|
179
203
|
Alongside the conversation store sits the standalone `InstructionManager` a richer context assembles a prompt from — named directives, keyed by `name`, listed by descending `priority`. It mirrors the registry shape — `add` (one or a batch) mints each `id` and overwrites a same-key entry (last write wins), an `instruction(name)` / `instructions()` accessor pair, `remove` (one or a batch) / `clear` / `count` — holds immutable entries, and is observable (`emitter` with an `add` / `remove` / `clear` event map, wired through the reserved `on` option; an `error` option receives a listener's throw). It carries the **build-contract** members a context's assembly step calls: `open` (the section header text, `'## Instructions'`) and `render(instruction)` (per-item rendering — the instruction's `content`):
|
|
180
204
|
|
|
181
205
|
```ts
|
|
@@ -191,7 +215,67 @@ instructions.open // '## Instructions'
|
|
|
191
215
|
instructions.render(safety) // 'Refuse unsafe requests.'
|
|
192
216
|
```
|
|
193
217
|
|
|
194
|
-
|
|
218
|
+
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`:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { createAgentContext, createMemoManager, createSkillManager } from '@orkestrel/agent'
|
|
222
|
+
|
|
223
|
+
const memos = createMemoManager({ id: 'ada' })
|
|
224
|
+
const tone = { name: 'tone', description: 'Prefers short replies.', content: 'Answer briefly.' }
|
|
225
|
+
memos.add(tone)
|
|
226
|
+
memos.add(tone) // unchanged text: the same revision, no event
|
|
227
|
+
memos.add({ name: 'tone', description: 'Prefers bullet lists.', content: 'Answer in bullets.' })
|
|
228
|
+
memos.count // 1
|
|
229
|
+
memos.history('tone').length // 2
|
|
230
|
+
memos.memo('tone')?.description // 'Prefers bullet lists.'
|
|
231
|
+
memos.add({ name: 'reach', description: 'Answers by email.', content: 'Reply by email.' })
|
|
232
|
+
createAgentContext({ memos }).build()[0]?.content
|
|
233
|
+
// '## Memos\n\n- tone: Prefers bullet lists.\n- reach: Answers by email.'
|
|
234
|
+
|
|
235
|
+
const restored = createMemoManager({ snapshot: memos.snapshot() })
|
|
236
|
+
restored.id // 'ada'
|
|
237
|
+
memos.remove('tone') // true
|
|
238
|
+
memos.history('tone') // []
|
|
239
|
+
restored.history('tone').length // 2
|
|
240
|
+
|
|
241
|
+
const skills = createSkillManager()
|
|
242
|
+
const review = skills.add({
|
|
243
|
+
name: 'review',
|
|
244
|
+
description: 'Reviews a change for defects.',
|
|
245
|
+
content: 'Read the diff, then list each defect with its line.',
|
|
246
|
+
files: [{ path: 'checklist.md', content: { text: '- Tests pass', language: 'markdown' } }],
|
|
247
|
+
})
|
|
248
|
+
skills.skill('review')?.files[0]?.path // 'checklist.md'
|
|
249
|
+
skills.skills() // [review]
|
|
250
|
+
skills.render(review) // '- review: Reviews a change for defects.'
|
|
251
|
+
skills.open // '## Skills'
|
|
252
|
+
createAgentContext({ skills }).build()[0]?.content // '## Skills\n\n- review: Reviews a change for defects.'
|
|
253
|
+
skills.remove('review') // true
|
|
254
|
+
skills.clear()
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
To persist one memo set, store its snapshot as JSON and narrow what you read back, because a stored row is untrusted until `isMemoSnapshot` accepts it:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
import { createMemoManager, isMemoSnapshot } from '@orkestrel/agent'
|
|
261
|
+
|
|
262
|
+
const memos = createMemoManager({ id: 'ada' })
|
|
263
|
+
memos.add({ name: 'tone', description: 'Prefers short replies.', content: 'Answer briefly.' })
|
|
264
|
+
|
|
265
|
+
const stored = JSON.stringify(memos.snapshot())
|
|
266
|
+
const parsed: unknown = JSON.parse(stored)
|
|
267
|
+
if (!isMemoSnapshot(parsed)) throw new Error('Not a memo snapshot')
|
|
268
|
+
const restored = createMemoManager({ snapshot: parsed })
|
|
269
|
+
restored.memo('tone')?.description // 'Prefers short replies.'
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
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.
|
|
273
|
+
|
|
274
|
+
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.
|
|
275
|
+
|
|
276
|
+
`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.
|
|
277
|
+
|
|
278
|
+
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.
|
|
195
279
|
|
|
196
280
|
```ts
|
|
197
281
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
@@ -205,7 +289,7 @@ const result = await provider.generate(
|
|
|
205
289
|
)
|
|
206
290
|
```
|
|
207
291
|
|
|
208
|
-
`AgentContext` wires the instruction
|
|
292
|
+
`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.
|
|
209
293
|
|
|
210
294
|
````ts
|
|
211
295
|
import { createAgentContext } from '@orkestrel/agent'
|
|
@@ -216,9 +300,9 @@ context.workspaces.add().write('src/main.ts', 'export const x = 1') // the activ
|
|
|
216
300
|
context.messages.add({ role: 'user', content: 'Review this.' })
|
|
217
301
|
|
|
218
302
|
const input = context.build()
|
|
219
|
-
// input[0] = { role: 'system', content:
|
|
220
|
-
//
|
|
221
|
-
// input[
|
|
303
|
+
// input[0] = { role: 'system', content: 'You are a code reviewer.\n\n## Instructions\n\nBe terse.' }
|
|
304
|
+
// input[1] = { role: 'user', content: '## Workspace\n\nFile: src/main.ts\n```typescript\nexport const x = 1\n```' }
|
|
305
|
+
// input[2] = { role: 'user', content: 'Review this.' }
|
|
222
306
|
````
|
|
223
307
|
|
|
224
308
|
### Conversations & compaction
|
|
@@ -264,10 +348,10 @@ Calls to `compact()` run one at a time: a call made while another is in flight w
|
|
|
264
348
|
|
|
265
349
|
Register a conversation in a `ConversationManager` and pass that registry through `AgentContextOptions.conversations` to make it the message source. `context.messages` then is the active conversation's live tail, and `build()` folds its `view()`. The scope's filters never touch messages; message inclusion is the conversation's through compaction and, when a handler is set, the selection's. When the registry is omitted, the context creates one with an active default conversation.
|
|
266
350
|
|
|
267
|
-
Pass that registry through `AgentOptions.conversations` together with an `AgentOptions.window` context [`Budget`](budget.md) to enable automatic compaction. Before the first provider request and between turns, the loop measures the
|
|
351
|
+
Pass that registry through `AgentOptions.conversations` together with an `AgentOptions.window` context [`Budget`](budget.md) to enable automatic compaction. Before the first provider request and between turns, the loop measures each request it will send, with its messages after the `replay` policy, its advertised tools, and its per-call `options`, against the window and, when that request reaches the ceiling, compacts the run's conversation, when it is summarizable, before continuing on the rebuilt view. Omit `window` and the loop doesn't auto-compact. See the [Contract](#contract) (the automatic-compaction clause) for the exact trigger and the compaction floor.
|
|
268
352
|
|
|
269
353
|
```ts
|
|
270
|
-
import { createAgent, createConversationManager,
|
|
354
|
+
import { createAgent, createConversationManager, estimateRequest } from '@orkestrel/agent'
|
|
271
355
|
import { createBudget } from '@orkestrel/budget'
|
|
272
356
|
|
|
273
357
|
// `provider` and `summarize` come from the host application.
|
|
@@ -276,43 +360,62 @@ const conversation = conversations.add()
|
|
|
276
360
|
const agent = createAgent(provider, {
|
|
277
361
|
conversations,
|
|
278
362
|
// A context Budget: consumer = a token estimator, max = the context window. The loop measures
|
|
279
|
-
//
|
|
280
|
-
//
|
|
281
|
-
window: createBudget({ max: 8_000, consumer:
|
|
363
|
+
// each request against it. A request that reaches the window folds once and continues on the
|
|
364
|
+
// rebuilt (smaller) view; only `strict` refuses a request still over the window.
|
|
365
|
+
window: createBudget({ max: 8_000, consumer: estimateRequest }),
|
|
282
366
|
})
|
|
283
367
|
agent.context.messages.add({ role: 'user', content: 'Hi' })
|
|
284
368
|
await agent.generate() // folds older turns into a section mid-run when the prompt reaches the window, then continues
|
|
285
369
|
```
|
|
286
370
|
|
|
287
|
-
|
|
371
|
+
Set `max` under a hard ceiling: on 11 agent requests with no tool call, recorded on 2026-11-02 on Qwen 3.5 2B on Ollama 0.40.13, over a scripted support-desk conversation of up to 38 messages and 46713 characters (median 640, 95th percentile 3367, maximum 3506), `estimateRequest` read 147 to 204 tokens under the daemon's prompt count of 1850 to 12283, so leave at least that headroom. No other model and no request holding a tool call has a reading here.
|
|
288
372
|
|
|
289
|
-
|
|
373
|
+
##### One agent per principal, one conversation per run (binding a run to its thread)
|
|
374
|
+
|
|
375
|
+
`agent.context.conversations` is the structural registry, supplied at construction and never reassigned, and its active conversation is the default a run binds. `context.messages` is dynamic: it always points at the current active conversation's live tail (the same reference, no duplication) and follows `conversations.switch(id)`. The registry always has an active conversation (a default is added when it has none). A run binds its conversation once, at its `generate` or `stream` call: the `AgentRunOptions.conversation` it names, else the active one. The run reads its request from that conversation, appends every reply to it, and folds it, so a later `switch`, `open`, `remove`, `clear`, or same-id `add` never moves a live run, and a switch sets only the next run's default. Each conversation accumulates its own history and compacts independently (one thread's sections never leak into another). On a server, the application's session table holds one entry per authenticated principal, `{ agent, threads }`: `threads` is a `createConversationManager()` value that principal owns, and `agent` is one `Agent` built once for that principal from shared providers, tools, rules, and immutable host text. Each request names its thread, looked up in the principal's own `threads` and never in a process-global registry, and passes the request's text as the run's `AgentRunOptions.prompt`. The run appends the prompt to the thread as a `user` turn after its guards, so a refused run appends nothing; a run with no `prompt` reads its request from the conversation's tail:
|
|
290
376
|
|
|
291
377
|
```ts
|
|
292
|
-
import {
|
|
378
|
+
import type { AgentInterface, ConversationManagerInterface } from '@orkestrel/agent'
|
|
379
|
+
import { createAgent, createConversationManager, estimateRequest } from '@orkestrel/agent'
|
|
293
380
|
import { createBudget } from '@orkestrel/budget'
|
|
294
381
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
382
|
+
interface Session {
|
|
383
|
+
readonly agent: AgentInterface
|
|
384
|
+
readonly threads: ConversationManagerInterface
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Per request: find or add the thread in the principal's own registry, then run on it with the
|
|
388
|
+
// request's text as the prompt, which the run appends after its guards.
|
|
389
|
+
async function handle(session: Session, threadId: string, text: string): Promise<string> {
|
|
390
|
+
const thread = session.threads.conversation(threadId) ?? session.threads.add({ id: threadId })
|
|
391
|
+
return (await session.agent.generate({ conversation: thread, prompt: { content: text } })).content
|
|
392
|
+
}
|
|
301
393
|
|
|
302
|
-
//
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
394
|
+
// `provider` and `summarize` come from the host application.
|
|
395
|
+
// The session table: one entry per authenticated principal, held by the application.
|
|
396
|
+
const sessions = new Map<string, Session>()
|
|
397
|
+
for (const principal of ['ada', 'grace']) {
|
|
398
|
+
// Each entry owns its threads and its window; neither is shared across principals.
|
|
399
|
+
const threads = createConversationManager({ summarize, keep: 2 })
|
|
400
|
+
const agent = createAgent(provider, {
|
|
401
|
+
conversations: threads,
|
|
402
|
+
window: createBudget({ max: 8_000, consumer: estimateRequest }),
|
|
403
|
+
})
|
|
404
|
+
sessions.set(principal, { agent, threads })
|
|
308
405
|
}
|
|
309
406
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
407
|
+
const ada = sessions.get('ada')
|
|
408
|
+
const grace = sessions.get('grace')
|
|
409
|
+
if (ada === undefined || grace === undefined) throw new Error('unknown principal')
|
|
410
|
+
// Ada's trip thread accumulates and compacts on its own.
|
|
411
|
+
await handle(ada, 'trip', 'Hi, I am Ada.')
|
|
412
|
+
// Ada's math thread is independent of her trip thread.
|
|
413
|
+
await handle(ada, 'math', 'What is 2 + 2?')
|
|
414
|
+
// The same thread id under Grace is her own thread: it carries none of Ada's turns.
|
|
415
|
+
await handle(grace, 'trip', 'What did I say my name was?')
|
|
313
416
|
```
|
|
314
417
|
|
|
315
|
-
> **Concurrency caveat.**
|
|
418
|
+
> **Concurrency caveat.** [Serving one agent per principal](#serving-one-agent-per-principal) holds what this session table shares and refuses. Here a refused overlap rejects the promise `handle` returns, so the caller rethrows or maps `AgentError` `'CONCURRENCY'`.
|
|
316
419
|
|
|
317
420
|
##### Production behaviors of automatic compaction
|
|
318
421
|
|
|
@@ -320,8 +423,9 @@ Auto-compaction (the `window` budget) is hardened for a long-running app:
|
|
|
320
423
|
|
|
321
424
|
- **Pre-first-turn + run-entry reset.** The budget check runs before the first provider request and between turns — so a resumed or already-long conversation whose initial prompt already exceeds the window compacts immediately (not only after a tool turn). The `window` budget is reset at run entry, so no stale measurement carries across runs or a conversation switch.
|
|
322
425
|
- **No fold after a cancel.** When the run's signal has aborted by the time tool dispatch ends, the loop records the tool messages and folds nothing, so a cancel never waits on the summarizer. The next run's pre-first-turn check folds the earlier exchanges, call groups whole.
|
|
426
|
+
- **What a cancel waits for.** The loop races a scheduler's yield, the approver's answer, and the summarizer against the run signal, so one that ignores its signal still ends on a cancel; a provider stream, a judge, a tool handler, and a selection handler are awaited until they settle, because each can carry usage or finished work, so one that ignores its signal holds the run past a cancel or a timeout, and on a ledger its held scan, until it returns.
|
|
323
427
|
- **Observable summarizer failure, non-fatal unless strict.** If the summarizer throws during automatic compaction, the loop emits the error as a `fault` event, so the failure is never silently lost. Without `AgentOptions.strict`, the run doesn't crash: the loop skips compaction that turn and continues, and the over-window prompt proceeds to the provider. With `strict` set, the run settles `error` after the `fault` event (see the `strict` clause under [Contract](#contract)). A manual `conversation.compact()` call you make yourself always propagates its error.
|
|
324
|
-
- **Futile-compaction guard
|
|
428
|
+
- **Futile-compaction guard.** If `compact()` folds nothing (returns `undefined`) between turns while the prompt is still over the window — that is, the section summaries, the run's request, and the run's own turns, which that fold never takes, already exceed it — the loop stops auto-compacting for the rest of that run (a per-run latch), avoiding per-turn churn. The over-window prompt then proceeds to the provider, and the provider decides what happens past its window. A plain fold takes the live tail and leaves the existing sections; a `sections` cap and `cumulative` fold existing sections too, each on a fold that has an eligible slice, as the `cumulative` folds and compaction floor clauses under [Contract](#contract) state.
|
|
325
429
|
|
|
326
430
|
The following listener observes an automatic-compaction summarizer failure:
|
|
327
431
|
|
|
@@ -334,7 +438,7 @@ agent.emitter.on('fault', (error) =>
|
|
|
334
438
|
|
|
335
439
|
### Scoping a turn
|
|
336
440
|
|
|
337
|
-
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` / `tools` / `files` list keyed by each category's identity — `instructions` (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:
|
|
441
|
+
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:
|
|
338
442
|
|
|
339
443
|
```ts
|
|
340
444
|
import { createAgent, createScope } from '@orkestrel/agent'
|
|
@@ -355,13 +459,13 @@ agent.context.apply(
|
|
|
355
459
|
const result = await agent.generate()
|
|
356
460
|
```
|
|
357
461
|
|
|
358
|
-
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 name
|
|
462
|
+
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.
|
|
359
463
|
|
|
360
|
-
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, files, and `select`) applies at the next build or select site: run entry, the pre-first-turn compaction fold, or a compaction rebuild.
|
|
464
|
+
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.
|
|
361
465
|
|
|
362
466
|
When no tool is advertised, including an empty registry, the provider's `content` field ends the run as the answer with a `partial: false` result. The assistant message is recorded without calls. Each dropped call emits a `deny` event with the `no tool is advertised in the active scope` reason, without a tool result or tool message.
|
|
363
467
|
|
|
364
|
-
When at least one tool is advertised, a call excluded by the tool allow-list emits a `deny` event with the `TOOL is not in the active scope` reason, where the `TOOL` placeholder is the requested name. Its denial `ToolResult` value carries the `
|
|
468
|
+
When at least one tool is advertised, a call excluded by the tool allow-list or naming no advertised tool emits a `deny` event with the `TOOL is not in the active scope` reason, where the `TOOL` placeholder is the requested name. Its denial `ToolResult` value carries the `"TOOL" did not run: it is not one of the listed tools. Use a listed tool or answer with what you have.` error and is fed back as a tool message. Admitted calls pass through authority and dispatch normally. The loop continues with results in the reply's call order, including when calls share an ID.
|
|
365
469
|
|
|
366
470
|
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.
|
|
367
471
|
|
|
@@ -369,9 +473,9 @@ A `ScopeManager` registry stores reusable named scopes, keyed by a minted `id` f
|
|
|
369
473
|
|
|
370
474
|
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.
|
|
371
475
|
|
|
372
|
-
The loop calls the handler at each select site (run entry, the pre-first-turn compaction fold, and a compaction rebuild) with the user message that ends
|
|
476
|
+
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.
|
|
373
477
|
|
|
374
|
-
A `Selection` carries the `messages`, the `judgments` keys they rest on, the judge `usage` spent, an optional `fault
|
|
478
|
+
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.
|
|
375
479
|
|
|
376
480
|
The following agent selects through its default handler, then through a mode's override:
|
|
377
481
|
|
|
@@ -408,10 +512,10 @@ receipts.map((selection) => selection.messages.length) // [2, 1]
|
|
|
408
512
|
|
|
409
513
|
const plain = createAgent(provider)
|
|
410
514
|
const request = plain.context.messages.add({ role: 'user', content: 'Invoice 42.' })
|
|
411
|
-
plain.context.select(request, new AbortController().signal) // undefined — no handler in either home
|
|
515
|
+
plain.context.select(plain.context.messages, request, new AbortController().signal) // undefined — no handler in either home
|
|
412
516
|
```
|
|
413
517
|
|
|
414
|
-
A selection fails
|
|
518
|
+
A selection fails four ways. A handler throw emits `fault`, and the loop builds from `view()` with no `select` event. A returned `fault` charges its usage first, then emits `fault`, and the loop builds from the returned `messages` and emits `select`. A conversation changed under the handler is a fault as well: `context.select` returns the current `view()` with a `fault` that names the change. A `system` message in a handler's selection is a fault over `view()` carrying `ConversationError` `'ROLE'`. With `AgentOptions.strict` set, all four settle the run `error`. A cancel at a select site wins over all of them, and the run commits partial with no provider call.
|
|
415
519
|
|
|
416
520
|
Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`. No `usage` chunk or `usage` event carries it, so that chunk keeps its one-provider-call meaning.
|
|
417
521
|
|
|
@@ -419,10 +523,12 @@ Selection usage is charged in full to the cost `budget` and folded into `AgentRe
|
|
|
419
523
|
|
|
420
524
|
A conversation's `judgments` store records what a judge answered about its messages. Each record is keyed by the caller's question id, and adding an existing key replaces the record in place, last write wins, at its original insertion position, and the `add` method stamps the `time` member. A record carries the question, the answer or the refusal, the judge's configured `model`, the ordered `sources` ids, and the rendered `state`, and it carries `usage` only when its request asked that one question.
|
|
421
525
|
|
|
422
|
-
The `resolve(judge, request, sources, signal)` method reuses every recorded judgment that matches and asks the judge once for the rest, recording what returns. A match compares the question
|
|
526
|
+
The `resolve(judge, request, sources, signal)` method reuses every recorded judgment that matches and asks the judge once for the rest, recording what returns. A match compares the question as a JSON value, the sources in order, the rendered state, and the judge's configured `model` rather than the name a server reports, so a question whose keys arrive in another order, from a store that returns keys sorted or a host that builds it in another order, matches, and a changed criterion, a changed state, or a changed source order asks again. Criteria order reaches the prompt and a small model reads options by position, so a reused answer keeps the reading its first order earned; call `remove(id)` to ask again after reordering. A cancel keeps the records of the questions that completed and rethrows the abort.
|
|
423
527
|
|
|
424
528
|
A question id is a caller key that the prompt never carries, so the whole question lives in `instructions`, and a judgment that needs an earlier answer is a second request. A snapshot carries `judgments` only while the store holds one, so a conversation without judgments serializes as `{ id, sections, messages }`, and a snapshot written without the member still validates and restores.
|
|
425
529
|
|
|
530
|
+
The `judgment`, `add`, and `resolve` methods return the stored deep-frozen record, and the `judgments` method returns a fresh array of them. `ConversationInterface.snapshot()` and `LedgerInterface.snapshot().conversation` carry those records. `MemoryConversationStore.get` hands back the stored snapshot object itself: its messages and sections are shared with the store, so an edit to them changes what the next `get` returns, and its judgments are frozen records, so a write to one throws `TypeError` in strict-mode code; copy a judgment through `copyJSON` to migrate or redact it. Hydrating takes an owned frozen copy and never touches its input.
|
|
531
|
+
|
|
426
532
|
The following conversation records one answer and then reuses it:
|
|
427
533
|
|
|
428
534
|
```ts
|
|
@@ -463,26 +569,26 @@ The usage in the comment is the one the recorded Ollama response of 2026-10-07 r
|
|
|
463
569
|
|
|
464
570
|
Treat a judge as frozen at inference: change thresholds and criteria in code, record corrections as judgments, and train another model only offline, as a batch on rows collected for that purpose, refitting temperature on rows the training run didn't use.
|
|
465
571
|
|
|
466
|
-
Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https://docs.typesafe.ai/model-jaggedness/jev-1.13.md)). Scoping words and negations count, so keep a `noul` whose true side means yes, and keep indirection such as a double negative out of the text. Keep arithmetic and date comparison in code, filter irrelevant state before asking, and treat a note inside the state as data that can move the answer. Reorder options to check for a lean toward the first one.
|
|
572
|
+
Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https://docs.typesafe.ai/model-jaggedness/jev-1.13.md)). Scoping words and negations count, so keep a `noul` whose true side means yes, and keep indirection such as a double negative out of the text. Keep arithmetic and date comparison in code, filter irrelevant state before asking, and treat a note inside the state as data that can move the answer. Reorder options to check for a lean toward the first one, under a new question id or after `remove(id)`, because a matching judgment keeps its first reading.
|
|
467
573
|
|
|
468
574
|
### Serving a conversation through a ledger
|
|
469
575
|
|
|
470
|
-
A ledger serves one conversation as
|
|
576
|
+
A ledger serves one conversation as event-sourced records with one record per owner. The `createLedger(provider, options)` factory returns a `LedgerInterface` value that owns the conversation, the agent that answers it, and that agent's tools, and its `respond` method appends a request as a user message and serves it through to the reply. The conversation is the event log. Each request reads the system message, which holds the `system` option and whatever instructions and skills the `agent` option supplies, then the context message when the `agent` option supplies memos or an active workspace, then a tail of the seed history (the messages added before the first request), then a copy of the request turn: the records the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. An earlier request and its reply don't re-enter a planned prompt; what its lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the agent builds the prompt from the whole conversation view instead, earlier requests and replies included, with no records.
|
|
471
577
|
|
|
472
|
-
Run the ledger's agent only through the `respond` method
|
|
578
|
+
Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. An active `respond` call owns a run on that conversation whose request, the newest message, is that call's request or one of the ledger's notes. A run that no active `respond` call owns, such as a direct call to the agent's `generate` method or a run on another conversation, gets a faulted selection when its newest message is a user message: the selection's `fault` is a `LedgerError` with code `'REQUEST'`, so the agent emits `fault` and builds the prompt from the whole view of the run's conversation with no records, and the ledger asks its judge nothing for that run. When its newest message isn't a user message, the run gets no selection and builds from the whole view. Calibration admits no run, so a run during the `calibrate` method, or during the calibration that opens a `respond` call, is one that no active `respond` call owns.
|
|
473
579
|
|
|
474
580
|
The method has the following pieces, each named by its export:
|
|
475
581
|
|
|
476
|
-
- **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. A judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value reads the filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `
|
|
582
|
+
- **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. The `narrow` member of the `correction` option keeps only the eligible earlier messages that also share a registry entity with the correction or an id or a number in their content, so a desk topic alone admits no pair, and a correction with no id, owner, or desk topic still asks no pair. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, `narrow` took 24 judge calls and 45 s against 68 and 136 s at a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059), and 26 judge calls and 45 s against 109 and 196 s at a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883). Those calls include the category and topic questions `narrow` leaves in place. Filings were equal at those two corrections, on 5 pairs and 1 supersession. A third correction, forecast from recorded answers and not run, lost 0 of 8 pairs. The 173 pairs `narrow` drops across the three, 196 questions, filed 0 on recorded answers, on text whose corrections repeat a literal by construction, and the registry-entity path admitted no pair on this recording. A true supersession outside that set is never asked, and no run on any model measures how often one occurs. Set `narrow` when a correction's wait costs more than a missed supersession and your corrections repeat the id, number, or looked-up entity they correct. Leave it off for a host with no lookups or with free-text values. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. A judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value reads the filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `ClassifierAttempt` value per logical filing question it attempted, in asking order, and observes the filing without changing it. An attempt names the question's key and its `ClassifierPhase` value, and its `ClassifierOutcome` value says whether the conversation already held the judgment (`cached`), the classifier held the question after a deterministic failure or because a message it names left the conversation (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal (`failed`), or was cut short by an abort (`aborted`). A `resolved`, `failed`, or `aborted` attempt carries the monotonic milliseconds the classifier waited on that call as `duration`, and a `cached` or `skipped` attempt carries none. A question that a caller abort preceded has no attempt, because it never began. The attempts count logical questions and resolve requests, never the physical wire calls a judge makes for them, and they record no join of pending requests. The `attempts` member of the `LedgerResult` value holds the attempts of the filing selections of that `respond` call alone; the `Selection` values the ledger emits carry none. A page passes `agent: { scheduler: createBrowserScheduler() }` from `@orkestrel/workflow/browser`, so the classifier hands the host a turn each time the `LEDGER_SLICE` constant's milliseconds have run while it files, and the plan after the filing still runs as one task; a page that omits the option also runs each stretch of cached filing as one task, and the host gets a turn only while the classifier waits on the judge. A direct `agent.context.select` for the same request during a paced filing's yield rejects with `AgentError` `'CONCURRENCY'`, and one for a message the call does not own returns a selection whose `fault` is `LedgerError` `'REQUEST'`. A `classify` call reads each message's quiet flag and near set at most once while it pairs corrections, so a judgment or message written during a pair-phase await reads at the next `classify` call, and `LedgerLookup.read` runs one time per tool message for each plan, each `recall` call, and each filing pass. The **What a cancel waits for.** bullet under [Production behaviors of automatic compaction](#production-behaviors-of-automatic-compaction) applies to this filing: what it names holds the run, and on a ledger its held scan, until it returns.
|
|
477
583
|
- **The records.** The `buildRecords` helper projects the filing into one `LedgerRecord` value per owner a lookup result names, plus one rules record for the rules and corrections no owner claims. Each line is a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. A message filed quiet or superseded isn't live. Accepted message-level amendments preserve every original indexed sentence of live earlier sources; the projection lists distinct direct edges in its `amendments` member. Sentence scope remains unresolved. The `recall` tool and the answer note keep the stored content of each message they carry. The seed tail keeps stored content except for lookup results, which the plan replaces with stubs.
|
|
478
|
-
- **Amendment scope.** The first retained occurrence of an amended source
|
|
479
|
-
- **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the
|
|
480
|
-
- **The `recall` tool.** The ledger registers a `recall` tool beside the application's lookups. It lists the earlier messages and lookup
|
|
481
|
-
- **The repeat stop.** A lookup 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
|
|
584
|
+
- **Amendment scope.** The first retained occurrence of an amended source opens with its `[N]` reference and a note on its later changes. Distinct retained sources receive decimal references starting at 1 in first-occurrence emission order, after deduplication. References are local to one rendering of the records and are recomputed after each trim; omitted sources do not shift them. Repeated occurrences share one reference. Recall and storage retain original source IDs. Authored content is unchanged. A fully included later source opens with its own [M] reference, and the earlier source's note reads “Changed later by [M].” If any effective correction is absent, partial, or superseded, the note reads “A later change is not shown.” The omission note exposes no omitted identity, text, owner, or count. Completeness uses every original sentence identity after source deduplication and each trim; annotations count against the existing room. Effective superseded amenders retain provenance without restoring their text. No transitive amendment edge is inferred. Earlier text can conflict with its correction; downstream correction application and semantic sentence withdrawal remain unproved.
|
|
585
|
+
- **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the built head (the system message and the context message), the tail, and the copy of the request turn that carries the records inside a token budget: the `capacity` option less the `predict` option, times the `prompt` share, less the overhead cost of the gauge and held back by the `LEDGER_SCALE_DRIFT` constant, of which the tail takes at most the `tail` share. Owner records with the same member ids in the same order render once, under their titles joined with `; `; before trimming, the view keeps the first requested record's key, members, and lines. The projection, held sources, and recall stay unchanged. The budget bounds only the records and the tail of a request's first call: the plan prices the built head, the tail, and the copy of the request turn with the records and images it carries. The request, each lookup result, the pass's own assistant turns with their calls and replayed thinking, the answer note and the `cue` note, and the whole view a faulted selection builds from enter the prompt unbounded, so any of them can carry a prompt past the budget. The plan prices each lookup stub in the tail at the longer of its `shown` and `hidden` forms, so a tail that fits the plan still fits after the records decide which results they show. The `share` option sets both shares, and the `DEFAULT_LEDGER_SHARE` constant holds the defaults. Until the records fit, the ledger drops the rules off the request's topics, then the sources outside the selected records, then the rules on its topics, then the owner lines. Inside an owner record, it drops the lines whose source isn't a rule or a correction first, oldest first, then the lines of rules and corrections, oldest first. The `Gauge` class prices the prompt; without the `gauge` option, the ledger calibrates before its first pass, and the `calibrate` method measures the price on demand. A lookup in the tail reaches the model as the stub the `renderStub` helper writes, which says whether the records show its result. The plan reaches the agent as a `Selection` value whose `messages` member is the tail, then the copy of the request turn that the `buildRequestMessage` helper writes: the records, a blank line, a `## Request` heading, and the request. When no records render, the copy is the request itself. The answer pass carries the same copy, and the stored request keeps its own content.
|
|
586
|
+
- **The `recall` tool.** The ledger registers a `recall` tool beside the application's lookups. It lists the earlier messages and lookup findings that match a topic (an owner name, an id, or a topic) with their stored content, 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. The tool cuts the list by whole items to the room the gauge leaves for the reply, naming how many older items it left out. 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, or when the capacity left less the `predict` option falls under twice the reply's reserve, it returns the `closure` note.
|
|
587
|
+
- **The repeat stop.** A lookup 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.
|
|
482
588
|
- **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. 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.
|
|
483
589
|
- **The thinking budget.** The `predict` option reserves the generation room that thinking and the reply share, taking it out of the plan budget, the recall room, and the close rule. 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.
|
|
484
590
|
|
|
485
|
-
Display references identify sources within
|
|
591
|
+
Display references identify sources within the rendered records while the line keeps the stored identity:
|
|
486
592
|
|
|
487
593
|
```ts
|
|
488
594
|
import type { LedgerLine } from '@orkestrel/agent'
|
|
@@ -508,21 +614,31 @@ The application supplies the following through `LedgerOptions`:
|
|
|
508
614
|
- 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;
|
|
509
615
|
- the capacity, through the `capacity` option, the model's context window in tokens;
|
|
510
616
|
- the generation cap, through the `predict` option, in tokens with thinking included, 0 by default and less than `capacity`;
|
|
511
|
-
- the thinking of the first pass, through the boolean `think` option; the answer pass always runs with thinking off
|
|
617
|
+
- the thinking of the first pass, through the boolean `think` option; the answer pass always runs with thinking off;
|
|
618
|
+
- 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, and the gauge, which a `gauge` option overrides.
|
|
512
619
|
|
|
513
620
|
The method has the following documented limits:
|
|
514
621
|
|
|
515
622
|
- **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.
|
|
516
623
|
- **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.
|
|
517
624
|
- **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.
|
|
518
|
-
- **A
|
|
625
|
+
- **A direct run beside a request is refused or unowned.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`; during the calibration that opens the call it is a run no active `respond` call owns. A run on another conversation started during a `respond` call gets no ledger selection, yet adds its turns and usage to that call's gauge readings and shares its repeat stop. A run on another conversation can still reach the `recall` and lookup tools, which the ledger's agent advertises to every run and which read the ledger's `conversation`.
|
|
519
626
|
- **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.
|
|
520
627
|
- **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.
|
|
521
628
|
- **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.
|
|
522
629
|
- **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.
|
|
523
|
-
- **Only the seed forms the tail.** Only the messages added before the first request form the seed tail, so an application message added after the first request reaches a planned prompt only through the
|
|
524
|
-
- **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
|
|
630
|
+
- **Only the seed forms the tail.** Only the messages added before the first request form the seed tail, so an application message added after the first request reaches a planned prompt only through the records or the `recall` tool.
|
|
631
|
+
- **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup replaces it, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows.
|
|
525
632
|
- **The ledger refuses no over-window prompt.** A request, a lookup result, the pass's own turns, the answer note, or the whole view a faulted selection builds from reaches the provider whole when it's larger than the room the `capacity` option leaves, and the provider's own context limit decides what happens to it.
|
|
633
|
+
- **A memo written between passes enters unpriced.** A memo written during a request's first pass, by a lookup or a host tool, enters the answer pass's context message unpriced: the plan prices the head the first pass sends, and the answer pass rebuilds the context message from the managers as they read then, so the system, tail, and request positions stay byte-identical and the context message can change.
|
|
634
|
+
- **A heading inside a record line reads as one.** A record line and the request copy render a message's or a lookup's text verbatim, so text holding a `## Rules` or `## Request` heading reads as one inside the user turn's copy; it changes no filing and never reaches `system`, and no delimiter marks such text.
|
|
635
|
+
- **A lookup is a read.** A ledger lookup is a read; a tool whose call has a consequence is not a lookup, and a ledger refuses a `consequential` lookup at every call. `LedgerAgentOptions` carries no `authority`, so such a lookup meets the default `Authority` floor with no approver and is denied as unanswered.
|
|
636
|
+
- **A snapshot's judgments are frozen records.** `LedgerInterface.snapshot().conversation` carries the stored deep-frozen judgments, so a write to one throws `TypeError` in strict-mode code, and a host copies a record through `copyJSON` before it migrates or redacts it.
|
|
637
|
+
- **A snapshot carries no gauge observations.** The `gauge` member of a snapshot holds the scale and the overhead cost alone. A hydrated ledger has observed no reply and no earlier request, so until it completes a request of its own, the `recall` tool sizes its room and applies its close rule as a ledger that has served nothing does, and a `recall` call can list a different number of items than the same call on the ledger that took the snapshot.
|
|
638
|
+
- **A hydrated ledger asks a held question again.** A snapshot doesn't carry the questions the classifier held after a refused question or a deterministic judge failure, so a ledger hydrated from it asks each of them again in its next request.
|
|
639
|
+
- **A snapshot survives a store that sorts keys.** A judgment matches by JSON value, so a `DatabaseConversationStore` column that returns keys in another order, a binary JSON column included, keeps every memoized judgment. A structured `state` compares by its JSON text, key order included, so pass the same key order on each resolve or render it to a string first. A restored answer keeps the probability order its store returned, so `measureAnswer` can name another winner on an exact tie; the `category` method of the `Classifier` class walks `LEDGER_CATEGORIES`, so a ledger's filing doesn't depend on that order. A restored lookup call's arguments render in the order the column returns them, so a records line, an item the `recall` tool lists, a lookup stub in the tail, and the provider request can differ in bytes from the ones the original run sent, and a stub's `hidden` form can tell the model to recall with another string argument, because it names the first string in that order. A restored message object keeps the member order its column returned, so a provider whose encode passes `request.messages` through by spread sends those members in that order; the relay projection and the judge requests fix their member order. `matchesJSON` is bounded to JSON data and promises nothing for a cycle, a `toJSON` object, `NaN`, an infinity, or an `undefined`, function, symbol, or hole inside a list.
|
|
640
|
+
- **The `narrow` member can hide a supersession.** The ledger never compares an earlier message that shares only a desk topic with the correction, so a supersession on a pair sharing no registry entity and no id or number is never filed. For example, "the refund limit is 500" then "no, the refund limit is 600" shares no literal, so with no shared registry entity `narrow` never asks about that pair, where the unset rule does.
|
|
641
|
+
- **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction of the recording under **The filing.**, one correction asked 98 pair questions over 93 earlier messages, inside 109 judge calls and 196 s on the Mica v0.1 4B judge. The `narrow` member lowers them, and the caller's abort signal ends them.
|
|
526
642
|
|
|
527
643
|
### Customizing the format (the cascade)
|
|
528
644
|
|
|
@@ -563,6 +679,8 @@ When a provider's model has a framing preference, such as XML tags, install that
|
|
|
563
679
|
|
|
564
680
|
### The HTTP provider engine
|
|
565
681
|
|
|
682
|
+
A provider decides how message text reaches its model. Agent neutralizes no model control token in any message, so a provider that renders messages into one prompt owes that escape, and a host that loads text into `system` must author that text. The `@orkestrel/ollama` provider through 0.0.28 escapes none, so a listed token inside any message reaches Ollama's renderer as the real token. From 0.0.29 it escapes a listed token in message content, a replayed call's name, and each top-level argument key and string value, and `guides/ollama.md` states that reach and its limits.
|
|
683
|
+
|
|
566
684
|
`ProviderInterface` is the boundary; `AgentProvider` is the engine behind it. Every HTTP-backed provider needs the same machinery — a deadline, a transport, an authorization hook, a bounded error read, a chunk decoder, reasoning separation, and result assembly — and rewriting that per vendor is how a fleet of providers drifts apart. `AgentProvider` owns all of it and leaves exactly one thing open: the wire. A subclass supplies `name` and the wire seams — `frame()` returns fresh framing state for the call, `encode(request)` projects a `ProviderRequest` onto the vendor's request shape, `read(record)` decodes one framed record into a `ProviderIncrement`, and `finish(parser)` returns whatever the parser still held at end of input. The engine is generic over `TRecord`: the record type a call's `frame()` parser emits and `read` consumes, defaulting to `Readonly<Record<string, unknown>>` for a wire whose records are JSON objects. The constructor switches decide the rest: `split` separates in-content `<think>` reasoning from the answer (default `true`), and `strict` requires the wire to carry a settled `result` record rather than assembling one at end of input (default `false`).
|
|
567
685
|
|
|
568
686
|
```ts
|
|
@@ -591,14 +709,14 @@ result.content // the assembled answer, with any <think> span routed to result.t
|
|
|
591
709
|
The engine's failures arrive as one error class. A `ProviderError` carries a machine-readable `code` and, for an HTTP failure alone, the response `status`; `isProviderError` narrows a caught value so a caller can branch on the code:
|
|
592
710
|
|
|
593
711
|
- `'HTTP'` — a non-OK response. The message is `provider error: <status>`, with ` - <excerpt>` appended only when the response body carried text. The excerpt is read to at most `MAX_ERROR_BODY_LENGTH` bytes and the remainder of the body is cancelled, so a stalled error body can't hold the call open past its deadline.
|
|
594
|
-
- `'PROTOCOL'` — a successful response with no body, a wire record the concrete provider refuses, or a `strict` stream that ended without a settled result.
|
|
712
|
+
- `'PROTOCOL'` — a successful response with no body, a line the provider's framing refuses, a wire record the concrete provider refuses, or a `strict` stream that ended without a settled result. A throw from a provider's framing seam (its parser's `parse` or the provider's `finish`) that races no cancel and is not already a `ProviderError` or `ProviderAbortError` rejects with this code and carries that throw as its `cause`.
|
|
595
713
|
- `'PROVIDER'` — an upstream failure a relay reported in an `error` frame.
|
|
596
714
|
|
|
597
715
|
A cancel isn't in that taxonomy: the call's own deadline and the caller's signal are folded into one bound, and a cancel throws `ProviderAbortError` carrying the partial assembled so far.
|
|
598
716
|
|
|
599
717
|
### Recording and replaying thinking
|
|
600
718
|
|
|
601
|
-
A thinking model's reasoning arrives as `ProviderResult.thinking`, apart from the answer in `content`. The agent loop records each call's non-empty thinking as the `thinking` member of the assistant message that call appends, on a tool-call turn and on the final answer alike. The joined `AgentResult.thinking` also includes thinking from calls that appended no message, such as an aborted call. Only recorded thinking can return to a provider. Thinking stays out of `content`, the selection state a judge reads, a ledger
|
|
719
|
+
A thinking model's reasoning arrives as `ProviderResult.thinking`, apart from the answer in `content`. The agent loop records each call's non-empty thinking as the `thinking` member of the assistant message that call appends, on a tool-call turn and on the final answer alike. The joined `AgentResult.thinking` also includes thinking from calls that appended no message, such as an aborted call. Only recorded thinking can return to a provider. Thinking stays out of `content`, the selection state a judge reads, a ledger's records, and a section summary. Compaction removes thinking before calling the summarizer and retains it on the section's original messages.
|
|
602
720
|
|
|
603
721
|
The provider's `replay` member decides which recorded thinking goes back to the model. Set it through the `replay` option of `ProviderOptions`, which `AgentProviderInput` and `RelayProviderOptions` extend, or declare it on a `ProviderInterface` you write. A `ThinkingReplay` value is one of the following:
|
|
604
722
|
|
|
@@ -645,7 +763,7 @@ turn.filter((message) => 'thinking' in message).map(({ id }) => id) // ['4'] —
|
|
|
645
763
|
|
|
646
764
|
### The judge engine
|
|
647
765
|
|
|
648
|
-
The `JudgeInterface` contract is the decision boundary beside `ProviderInterface`, and it is never a provider. Its `ask(request, signal)` method answers typed questions about one state with a probability distribution per question. A `JudgeRequest` carries the `state` and the `questions` keyed by your own ids, which the prompt never carries; each question is a `ChoiceQuestion`, a `ScoreQuestion`, or a `NoulQuestion`, named by its `form` member. A `JudgeResult` carries the answering model in its `model` member, the `answers` map keyed by the same ids, the `refusals` map of the questions a wire refused, and the `usage` member with the tokens the calls spent. An answer stores only the distribution the server returned: `probabilities` for a choice or a score, and `noul`, the probability of yes, for a noul question. The `
|
|
766
|
+
The `JudgeInterface` contract is the decision boundary beside `ProviderInterface`, and it is never a provider. Its `ask(request, signal)` method answers typed questions about one state with a probability distribution per question. A `JudgeRequest` carries the `state` and the `questions` keyed by your own ids, which the prompt never carries; each question is a `ChoiceQuestion`, a `ScoreQuestion`, or a `NoulQuestion`, named by its `form` member. A `JudgeResult` carries the answering model in its `model` member, the `answers` map keyed by the same ids, the `refusals` map of the questions a wire refused, and the `usage` member with the tokens the calls spent. An answer stores only the distribution the server returned: `probabilities` for a choice or a score, and `noul`, the probability of yes, for a noul question. The `measureAnswer` function derives every measure from that distribution, so every server reads on one scale and no stored measure can drift from its distribution (the derived-measure clause).
|
|
649
767
|
|
|
650
768
|
The `AgentJudge` class is the engine behind that boundary, as the `AgentProvider` class is the engine behind `ProviderInterface`. It owns each call's deadline, the transport, the `headers` hook, the validation before inference, the bounded error read, and the merge of every call's result, and it leaves the wire open: a subclass supplies `name`, `encode(request)`, which projects one call's `JudgeRequest` onto the protocol's request shape, and `read(value, request)`, which decodes one call's parsed response into a `JudgeResult`. A one-shot JSON response has no framing state and no buffered tail, so the engine has no `frame` or `finish` seam. In place of the `split` and `strict` switches it takes one `batch` switch: `true`, the default, sends every question in one call, and `false` sends one call per question in key order.
|
|
651
769
|
|
|
@@ -661,14 +779,13 @@ A cancel isn't in that taxonomy: it throws `JudgeAbortError`, whose `partial` me
|
|
|
661
779
|
|
|
662
780
|
### The relay
|
|
663
781
|
|
|
664
|
-
In the page-to-Node placement, the page owns `Agent`, `RelayProvider`, and its tool registry. Node owns the `createRelay` handler and upstream provider. The hop carries inference requests and replies; a tool handler executes where its registry lives. The Chromium receipt is planned in the `@orkestrel/mcp` distribution proof named under [Placement proofs](#placement-proofs) and isn't recorded here as passed.
|
|
782
|
+
In the page-to-Node placement, the page owns `Agent`, `RelayProvider`, and the handlers of its tool registry; the relay forwards a page tool definition only when the server declares it or `tools.accept` admits it. Node owns the `createRelay` handler and upstream provider. The hop carries inference requests and replies; a tool handler executes where its registry lives. The Chromium receipt is planned in the `@orkestrel/mcp` distribution proof named under [Placement proofs](#placement-proofs) and isn't recorded here as passed.
|
|
665
783
|
|
|
666
|
-
A browser must not hold a model credential, so this package ships the hop rather than the credential. `createRelay` returns a `RelayHandler` — a plain `(request: Request) => Promise<Response>` you mount on any fetch-standard router — that authorizes the request, validates its JSON body against `providerRequestContract`, and streams one upstream `provider.stream` call back as newline-delimited `RelayFrame` records under `RELAY_CONTENT_TYPE`. `createRelayProvider` is the other end: a `ProviderInterface` the browser drives exactly like a local one, which posts the request and decodes those frames back into deltas and the settled result. `RelayStream` is the response half `createRelay` composes, exported for a host that mounts its own route.
|
|
784
|
+
A browser must not hold a model credential, so this package ships the hop rather than the credential. `createRelay` returns a `RelayHandler` — a plain `(request: Request) => Promise<Response>` you mount on any fetch-standard router — that authorizes the request, validates its JSON body against `providerRequestContract`, refuses a page `system` message and an undeclared tool definition unless `RelayOptions` admits them, and streams one upstream `provider.stream` call back as newline-delimited `RelayFrame` records under `RELAY_CONTENT_TYPE`. `createRelayProvider` is the other end: a `ProviderInterface` the browser drives exactly like a local one, which posts the request and decodes those frames back into deltas and the settled result. `RelayStream` is the response half `createRelay` composes, exported for a host that mounts its own route.
|
|
667
785
|
|
|
668
786
|
```ts
|
|
669
787
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
670
788
|
import { createRelay, createRelayProvider } from '@orkestrel/agent'
|
|
671
|
-
// ... RelayFrameParser from "Reaching the relay from the browser" omitted.
|
|
672
789
|
|
|
673
790
|
declare const upstream: ProviderInterface // the server-side provider holding the credential
|
|
674
791
|
|
|
@@ -682,12 +799,11 @@ const handler = createRelay({
|
|
|
682
799
|
// In the browser: a provider like any other, reached over that route.
|
|
683
800
|
const browser = createRelayProvider({
|
|
684
801
|
url: 'https://app.example/relay',
|
|
685
|
-
parser: () => new RelayFrameParser(),
|
|
686
802
|
headers: () => ({ authorization: 'Bearer session-token' }),
|
|
687
803
|
})
|
|
688
804
|
```
|
|
689
805
|
|
|
690
|
-
The frame vocabulary is `RelayFrame`: a `ProviderDelta` (`content` or `thinking`) per streamed delta, one `{ channel: 'result', result }` when the turn settles, `{ channel: 'abort', partial }` when the upstream call was cancelled, and `{ channel: 'error', message }` for anything else — always the fixed `RELAY_PROVIDER_MESSAGE` text, so an upstream failure's own message never reaches the browser. A refusal never becomes a frame: the handler answers `401` when `authorize` refuses or throws, `400` when the body is missing, unreadable, or rejected by the contract, `413` when the body reaches the byte limit, and `502` when the upstream call can't be constructed.
|
|
806
|
+
The frame vocabulary is `RelayFrame`: a `ProviderDelta` (`content` or `thinking`) per streamed delta, one `{ channel: 'result', result }` when the turn settles, `{ channel: 'abort', partial }` when the upstream call was cancelled, and `{ channel: 'error', message }` for anything else — always the fixed `RELAY_PROVIDER_MESSAGE` text, so an upstream failure's own message never reaches the browser. A refusal never becomes a frame: the handler answers `401` when `authorize` refuses or throws, `400` when the body is missing, unreadable, or rejected by the contract, `413` when the body reaches the byte limit, `422` when the relay's policy refuses a page `system` message or tool definition, and `502` when the upstream call can't be constructed. The `422` alone carries a body, one `text/plain` line per refused member; every other refusal carries no body. Each refusal reaches the browser as a `ProviderError` with the `HTTP` code and that status.
|
|
691
807
|
|
|
692
808
|
The wire is strictly narrower than the domain on purpose. `providerRequestContract` and `relayFrameContract` are compiled from the shapes listed under [Providers module](#providers-module), and `RelayProvider.encode` refuses a request the JSON wire can't carry — a function-valued tool argument, a parameter schema holding one — before it fetches. The body it sends is an owned snapshot of that projection read through property descriptors, so a serializer reachable only through a `get` trap or a prototype is never consulted; an own function-valued property such as a `toJSON` method is a value outside JSON and is refused before fetching, with the clone's failure as the refusal's `cause`. A `ToolContext` stays with local execution; the call envelope carries only `id`, `name`, and `arguments`.
|
|
693
809
|
|
|
@@ -704,6 +820,7 @@ The following table lists the types the root declares:
|
|
|
704
820
|
| Name | Kind | Signature | Summary |
|
|
705
821
|
| ------------------- | --------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
706
822
|
| `MessageRole` | type | `(typeof MESSAGE_ROLES)[number]` | Names the role a `Message` plays in a conversation turn. |
|
|
823
|
+
| `ConversationRole` | type | `(typeof CONVERSATION_ROLES)[number]` | Names the role a stored conversation message plays: any `MessageRole` except `system`. |
|
|
707
824
|
| `ThinkingReplay` | type | `'none' \| 'turn' \| 'all'` | Names which thinking the agent loop, a relay server, and a ledger retain before calling a provider: `'none'` retains none, `'turn'` retains thinking after the last `user` message, and `'all'` retains all thinking. A direct `generate` or `stream` call sends messages as given. |
|
|
708
825
|
| `Message` | interface | `{ id, role, content, calls?, call?, images?, thinking? }` | Represents one conversation turn fed to a `ProviderInterface` — a stored, identified message. |
|
|
709
826
|
| `MessageInput` | interface | `{ role, content, calls?, call?, images?, thinking? }` | Carries the minimal data needed to author a `Message` — the `id` is assigned by the layer that stores it, so a caller supplies only role / content (and, for a replayed assistant turn, its `calls`; for a tool turn, the `call` it answers). |
|
|
@@ -716,7 +833,7 @@ The following table lists the types the root declares:
|
|
|
716
833
|
| `NoulQuestion` | interface | `{ form, instructions?, criteria? }` | Asks the model whether a statement about the state holds. |
|
|
717
834
|
| `JudgeQuestion` | type | `ChoiceQuestion \| ScoreQuestion \| NoulQuestion` | Names one question by its form, the protocol's type field under the fleet's named discriminant. |
|
|
718
835
|
| `JudgeRequest` | interface | `{ state, questions }` | Carries one state and the questions asked about it, keyed by caller ids the prompt never carries; each question is evaluated on its own. |
|
|
719
|
-
| `ChoiceAnswer` | interface | `{ form, probabilities }` | Carries a choice distribution keyed by option name, in criteria order.
|
|
836
|
+
| `ChoiceAnswer` | interface | `{ form, probabilities }` | Carries a choice distribution keyed by option name, in criteria order for a fresh answer; a restored record keeps the order its store returned. |
|
|
720
837
|
| `ScoreAnswer` | interface | `{ form, probabilities }` | Carries a score distribution indexed by level. |
|
|
721
838
|
| `NoulAnswer` | interface | `{ form, noul }` | Carries the probability that the answer is yes; the protocol's noul field. |
|
|
722
839
|
| `JudgeAnswer` | type | `ChoiceAnswer \| ScoreAnswer \| NoulAnswer` | Names one answer by its form; it stores only the distribution a server returned. |
|
|
@@ -726,14 +843,16 @@ The following table lists the types the root declares:
|
|
|
726
843
|
| `Judgment` | interface | `{ id, question, answer?, refusal?, model, sources, state, time, usage? }` | Records an answered or refused question with its sources, state, model, and storage time. |
|
|
727
844
|
| `JudgmentInput` | interface | `{ id, question, answer?, refusal?, model, sources, state, usage? }` | Supplies an answered or refused question for storage before its time is stamped. |
|
|
728
845
|
| `CodedErrorOptions` | interface | `{ cause?, context? }` | Carries the optional cause and context an error class with a machine-readable `code` takes at construction. |
|
|
846
|
+
| `LiteralSet` | interface | `{ ids, numbers }` | Holds the ids and numbers one text carries. |
|
|
729
847
|
|
|
730
848
|
#### Constants
|
|
731
849
|
|
|
732
850
|
The following table lists the constants the root declares:
|
|
733
851
|
|
|
734
|
-
| Name
|
|
735
|
-
|
|
|
736
|
-
| `MESSAGE_ROLES`
|
|
852
|
+
| Name | Kind | Signature | Summary |
|
|
853
|
+
| -------------------- | ----- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
854
|
+
| `MESSAGE_ROLES` | const | `readonly ["system", "user", "assistant", "tool"]` | Lists the roles any message can play, the built `system` head included, in the order the wire contract names them — the one list the `MessageRole` union derives from, the message guard tests membership against, and the message shape passes to its literal contract. |
|
|
855
|
+
| `CONVERSATION_ROLES` | const | `readonly ["user", "assistant", "tool"]` | Lists the roles a stored conversation message can play: every `MESSAGE_ROLES` member except `system`, in wire order — the one list the `ConversationRole` union derives from and a conversation checks each stored or selected role against. |
|
|
737
856
|
|
|
738
857
|
#### Errors
|
|
739
858
|
|
|
@@ -748,19 +867,21 @@ The following table lists the errors the root declares and the guards that narro
|
|
|
748
867
|
|
|
749
868
|
The following table lists the root wire shapes and the contract compiled from them:
|
|
750
869
|
|
|
751
|
-
| Name | Kind | Signature | Summary
|
|
752
|
-
| ----------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
753
|
-
| `toolCallShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>` | Describes a tool call's JSON wire projection.
|
|
754
|
-
| `messageShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a conversation message's JSON wire projection.
|
|
755
|
-
| `
|
|
870
|
+
| Name | Kind | Signature | Summary |
|
|
871
|
+
| ----------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
872
|
+
| `toolCallShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>` | Describes a tool call's JSON wire projection. |
|
|
873
|
+
| `messageShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a conversation message's JSON wire projection. |
|
|
874
|
+
| `tokenUsageShape` | const | `import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>` | Describes a token usage record's JSON wire projection — its `prompt`, `completion`, and `total` counts, shared by the provider result and the agent frame wires. |
|
|
875
|
+
| `messageContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>>` | Validates and projects conversation messages at a JSON wire boundary. |
|
|
756
876
|
|
|
757
877
|
#### Cloners
|
|
758
878
|
|
|
759
879
|
The following table lists the cloners the root declares:
|
|
760
880
|
|
|
761
|
-
| Name
|
|
762
|
-
|
|
|
763
|
-
| `copyJSON`
|
|
881
|
+
| Name | Kind | Signature | Summary |
|
|
882
|
+
| ------------ | -------- | ----------------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
883
|
+
| `copyJSON` | function | `(value: unknown) => unknown` | Owns a value by serializing it to JSON and parsing the text, so the copy shares nothing with its source. |
|
|
884
|
+
| `freezeJSON` | function | `(value: unknown) => unknown` | Owns a value through JSON and freezes every record and list of the copy, leaving the value unchanged. |
|
|
764
885
|
|
|
765
886
|
#### Helpers
|
|
766
887
|
|
|
@@ -771,15 +892,17 @@ The following table lists the helpers the root declares:
|
|
|
771
892
|
| `filterAllowList` | function | `<T>(allow: readonly string[] \| undefined, members: readonly T[], key: (member: T) => string) => readonly T[]` | Filters a list of members by a `ScopeInterface` allow-list of keys — `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys alone, order preserved. The pure, total set-membership primitive the context's build step and the agent loop's tool-advertise step apply a scope through. |
|
|
772
893
|
| `sanitizeToken` | function | `(value: number) => number` | Sanitizes one reported token count into a non-negative integer — a non-finite or non-positive value becomes `0`, and a positive fractional value floors down. |
|
|
773
894
|
| `sanitizeUsage` | function | `(usage: TokenUsage) => TokenUsage` | Sanitizes a `TokenUsage` into non-negative integers — the guard an agent's abort-usage path applies to a provider's partial usage before it is charged against a budget or folded into the run total. |
|
|
774
|
-
| `joinThinking` | function | `(
|
|
895
|
+
| `joinThinking` | function | `(prior: string \| undefined, next: string) => string` | Joins the reasoning a run's provider calls separated from the answer — the first call seeds the accumulation, a later call appends blank-line separated so each turn's reasoning stays readable. |
|
|
775
896
|
| `stripThinking` | function | `(messages: readonly Message[], replay: ThinkingReplay) => readonly Message[]` | Applies a `ThinkingReplay` policy to a conversation, returning the messages a provider sends with only the assistant thinking the policy allows. |
|
|
776
|
-
| `sumUsage` | function | `(
|
|
897
|
+
| `sumUsage` | function | `(prior: TokenUsage \| undefined, next: TokenUsage) => TokenUsage` | Adds two `TokenUsage` values field by field — the running total an agent run keeps across its provider calls. |
|
|
777
898
|
| `removeEntries` | function | `<K>(keys: readonly K[], remove: (key: K) => boolean) => boolean` | Removes each key through a single-key remover and folds the outcomes, so a batch `remove` reports whether the whole batch applied. |
|
|
778
899
|
| `collectExchanges` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects whole exchanges, joining every exchange spanned by a tool group. |
|
|
779
900
|
| `collectToolGroups` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects each assistant message that carries calls together with the tool messages that answer it, then each run of tool messages that no assistant message owns. |
|
|
780
901
|
| `hasCalls` | function | `(message: Pick<Message, 'calls'>) => boolean` | Checks whether a message carries at least one tool call. |
|
|
781
902
|
| `renderJSON` | function | `(value: unknown) => string \| undefined` | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
|
|
782
|
-
| `
|
|
903
|
+
| `matchesJSON` | function | `(left: unknown, right: unknown) => boolean` | Matches two values of JSON data by JSON value, whatever their key order, and reads a value with no JSON text as no match. |
|
|
904
|
+
| `matchesJudgment` | function | `(judgment: Judgment, question: JudgeQuestion, sources: readonly string[], state: string, model: string) => boolean` | Matches a recorded question by JSON value, the ordered sources, the rendered state, and the judge identity. |
|
|
905
|
+
| `extractLiterals` | function | `(text: string) => LiteralSet` | Reads the ids and the numbers of a text. |
|
|
783
906
|
|
|
784
907
|
#### Validators
|
|
785
908
|
|
|
@@ -817,14 +940,18 @@ The following table lists the types the providers module declares:
|
|
|
817
940
|
| `TextRead` | interface | `{ text, complete }` | Carries a decoded stream prefix and whether the stream ended within its byte budget. |
|
|
818
941
|
| `RelayFrame` | type | `ProviderDelta \| { readonly channel: 'result'; readonly result: ProviderResult; } \| { readonly channel: 'abort'; readonly partial: ProviderResult; } \| { readonly channel: 'error'; readonly message: string; }` | Carries a relay delta, settled result, remote abort, or remote failure. |
|
|
819
942
|
| `RelayHandler` | type | `(request: Request) => Promise<Response>` | Defines a host-independent relay request handler. |
|
|
820
|
-
| `
|
|
821
|
-
| `
|
|
943
|
+
| `RelaySystemOptions` | interface | `{ text?, accept? }` | Configures who writes the system turn a relay forwards. |
|
|
944
|
+
| `RelayToolOptions` | interface | `{ definitions?, accept? }` | Configures which tool definitions a relay forwards. |
|
|
945
|
+
| `RelayOptions` | interface | `{ provider, authorize, limit?, system?, tools? }` | Configures the upstream provider, mandatory authorization, request byte limit, and request head policy. |
|
|
946
|
+
| `RelayRefusalReason` | type | `'system' \| 'head' \| 'tool' \| 'mismatch'` | Names why a relay refuses a request member. |
|
|
947
|
+
| `RelayRefusal` | interface | `{ reason, index, name? }` | Carries one refused request member and where it sits. |
|
|
948
|
+
| `RelayProviderOptions` | interface | `{ url, parser? }` | Configures a relay destination and an optional fresh parser factory. |
|
|
822
949
|
| `RelayStreamOptions` | interface | `{ provider, request, signal }` | Carries the upstream call and cancellation bound of a relay response stream. |
|
|
823
950
|
| `ThinkSplitterInterface` | interface | `{ content, thinking, split(), flush() }` | Splits a thinking model's in-content `<think>…</think>` reasoning spans away from the answer, delta by delta with per-stream state, so a provider yields clean content alone and surfaces the reasoning as `ProviderResult.thinking`. |
|
|
824
951
|
| `AgentJudgeInput` | interface | `{ url, path?, model, batch? }` | Configures the judge engine's destination, identity, and call split. |
|
|
825
952
|
| `AgentJudgeInterface` | interface | `{ encode(), read() }` | Defines the wire seams of the shared judge engine. |
|
|
826
953
|
| `JudgeErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'QUESTION'` | Names the machine-readable judge failure conditions. |
|
|
827
|
-
| `
|
|
954
|
+
| `AnswerMeasure` | interface | `{ winner, probability, confidence, score? }` | Carries the measures `measureAnswer` derives from an answer; nothing stores them. |
|
|
828
955
|
| `SystemOneJudgeOptions` | interface | `{ url, model }` | Configures the System One server, model, transport, authentication, and deadline. |
|
|
829
956
|
| `SystemOneEntry` | type | `JudgeEntry \| null` | Carries a TypeSafe System One entry, including the wire's explicit null. |
|
|
830
957
|
| `SystemOneQuestion` | interface | `{ type, instructions?, criteria? }` | Transliterates a TypeSafe System One question with its protocol discriminant and criteria. |
|
|
@@ -840,20 +967,22 @@ The following table lists the types the providers module declares:
|
|
|
840
967
|
|
|
841
968
|
The following table lists the constants the providers module declares:
|
|
842
969
|
|
|
843
|
-
| Name
|
|
844
|
-
|
|
|
845
|
-
| `THINK_OPEN`
|
|
846
|
-
| `THINK_CLOSE`
|
|
847
|
-
| `DEFAULT_PROVIDER_TIMEOUT`
|
|
848
|
-
| `MAX_ERROR_BODY_LENGTH`
|
|
849
|
-
| `DEFAULT_RELAY_LIMIT`
|
|
850
|
-
| `RELAY_CONTENT_TYPE`
|
|
851
|
-
| `RELAY_PROVIDER_MESSAGE`
|
|
852
|
-
| `UNAUTHORIZED_RELAY_STATUS`
|
|
853
|
-
| `INVALID_RELAY_STATUS`
|
|
854
|
-
| `OVERSIZED_RELAY_STATUS`
|
|
855
|
-
| `
|
|
856
|
-
| `
|
|
970
|
+
| Name | Kind | Signature | Summary |
|
|
971
|
+
| ---------------------------- | ----- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
972
|
+
| `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`. |
|
|
973
|
+
| `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. |
|
|
974
|
+
| `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. |
|
|
975
|
+
| `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. |
|
|
976
|
+
| `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. |
|
|
977
|
+
| `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`. |
|
|
978
|
+
| `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. |
|
|
979
|
+
| `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. |
|
|
980
|
+
| `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. |
|
|
981
|
+
| `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. |
|
|
982
|
+
| `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. |
|
|
983
|
+
| `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`. |
|
|
984
|
+
| `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. |
|
|
985
|
+
| `SYSTEM_ONE_PATH` | const | `"/v1/systemone"` | Names the System One decision endpoint shared by compatible servers. |
|
|
857
986
|
|
|
858
987
|
#### Errors
|
|
859
988
|
|
|
@@ -938,10 +1067,12 @@ The following table lists the helpers the providers module declares:
|
|
|
938
1067
|
| `readBodyText` | function | `(body: ReadableStream<Uint8Array>, limit?: number, signal?: AbortSignal) => Promise<TextRead>` | Reads a UTF-8 prefix of a byte stream and cancels its remainder. |
|
|
939
1068
|
| `readChunks` | function | `(body: ReadableStream<Uint8Array>, signal?: AbortSignal) => AsyncGenerator<string>` | Decodes UTF-8 chunks with a final flush and releases the stream on every exit. |
|
|
940
1069
|
| `releaseReader` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>) => Promise<void>` | Cancels a stream reader and releases its lock, swallowing a cancellation failure so the caller's own outcome stands. |
|
|
941
|
-
| `
|
|
1070
|
+
| `measureAnswer` | function | `(answer: JudgeAnswer) => AnswerMeasure` | Derives the winner, its probability, the published confidence, and a score answer's expected level from a judge answer's distribution. |
|
|
942
1071
|
| `buildJudgeResult` | function | `(model: string, results: readonly JudgeResult[]) => JudgeResult` | Merges the results of a judge request's calls into one result. |
|
|
943
1072
|
| `buildProviderHeaders` | function | `(hook: ProviderOptions['headers'], signal: AbortSignal) => Promise<Headers>` | Builds a request's JSON headers, awaiting the caller's header hook inside the call's cancellation bound. |
|
|
944
1073
|
| `requestToRelay` | function | `(request: ProviderRequest) => ProviderRequest` | Projects a provider request onto the declared members the relay wire carries. |
|
|
1074
|
+
| `buildRelayRequest` | function | `(request: ProviderRequest, policy: Pick<RelayOptions, 'system' \| 'tools'>) => Result<ProviderRequest, readonly RelayRefusal[]>` | Builds the request a relay forwards under its system turn and tool definition policy, or every refusal that policy finds. |
|
|
1075
|
+
| `describeRelayRefusal` | function | `(refusal: RelayRefusal) => string` | Describes one relay refusal as the line its `422` response body carries. |
|
|
945
1076
|
| `questionToSystemOne` | function | `(question: JudgeQuestion) => SystemOneQuestion` | Projects a judge question onto the System One wire while preserving omitted members. |
|
|
946
1077
|
| `extractSystemOneAnswer` | function | `(answer: SystemOneAnswer, question: JudgeQuestion) => JudgeAnswer \| undefined` | Extracts a System One distribution in question criteria order and drops server measures. |
|
|
947
1078
|
| `extractSystemOneUsage` | function | `(usage: SystemOneUsage \| undefined) => TokenUsage \| undefined` | Maps complete System One token counts onto validated token usage. |
|
|
@@ -965,21 +1096,21 @@ The following table lists the types the conversations module declares:
|
|
|
965
1096
|
|
|
966
1097
|
| Name | Kind | Signature | Summary |
|
|
967
1098
|
| ------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
968
|
-
| `MessageManagerInterface` | interface | `{ count, add(), message(), messages(), remove(), clear() }` | Stores immutable `Message` records in insertion order and mints each `id` on `add` — the message-store contract `
|
|
1099
|
+
| `MessageManagerInterface` | interface | `{ count, add(), message(), messages(), remove(), clear() }` | Stores immutable `Message` records in insertion order and mints each `id` on `add` — the message-store contract every `ConversationInterface` satisfies structurally, the `AgentContextInterface.messages` conversation included. |
|
|
969
1100
|
| `ConversationSummaryHandler` | type | `(messages: readonly Message[], signal?: AbortSignal) => Promise<string>` | Summarizes a conversation, provider-agnostically — the seam the agent runtime supplies so core never imports a provider. Given the folded messages, it resolves their digest, the model-written summary of a compacted `Section` or of the oldest sections a `sections` cap merges. |
|
|
970
1101
|
| `Section` | interface | `{ id, summary, messages }` | Holds a slice of folded messages digested into a summary — the unit of compaction a `ConversationInterface` produces when its `compact()` call folds the live tail. |
|
|
971
1102
|
| `ConversationEventMap` | type | `{ readonly compact: readonly [section: Section]; readonly rehydrate: readonly [id: string]; readonly collapse: readonly [section: Section]; }` | Maps the push observation surface of a `ConversationInterface` — the compaction moments a fire-and-forget observer subscribes to through `conversation.emitter.on`. |
|
|
972
|
-
| `ConversationOptions` | interface | `{ id?, on?, error?, summarize?, keep?, sections?,
|
|
1103
|
+
| `ConversationOptions` | interface | `{ id?, on?, error?, summarize?, keep?, sections?, cumulative?, snapshot? }` | Configures `createConversation` — the optional `id`, the reserved `on` hooks, the provider-agnostic `summarize` seam, the retained-tail size, an optional cap on the compacted `sections` list, and a `ConversationSnapshot` to hydrate from. |
|
|
973
1104
|
| `CompactOptions` | interface | `{ keep?, sections?, signal? }` | Configures one `ConversationInterface.compact` call — the retained-tail size, the `sections` cap, or both, overridden for one fold. |
|
|
974
1105
|
| `ConversationReferenceOptions` | interface | `{ label?, messages? }` | Configures `ConversationInterface.reference` — how to render one conversation as a self-labeled, fenced provenance block to pull into another conversation by writing it to the active workspace of the active context: `label` names the source and `messages` lists the cherry-picked excerpts. |
|
|
975
1106
|
| `ConversationInterface` | interface | `{ id, judgments, emitter, sections, summarizable, count, add(), message(), messages(), remove(), clear(), view(), compact(), rehydrate(), search(), reference(), snapshot() }` | Groups messages above the flat `MessageManagerInterface` — a live uncompacted tail plus compacted, summarized `Section` records, with on-demand `rehydrate`, substring `search`, a cross-conversation `reference`, and a JSON `snapshot`, driven by a provider-agnostic `ConversationSummaryHandler` seam; `summarizable` reports whether that seam was supplied, and the agent loop gates automatic compaction on it. |
|
|
976
|
-
| `ConversationInput` | interface | `{ id?, summarize?, keep?, sections?,
|
|
1107
|
+
| `ConversationInput` | interface | `{ id?, summarize?, keep?, sections?, cumulative?, on?, error?, snapshot? }` | Carries the data to author a `ConversationInterface` through a `ConversationManagerInterface` — the optional `id`, a `summarize` override, a `keep` override, a `sections` cap override, the `cumulative` switch, the reserved `on` hooks, and a `ConversationSnapshot` to hydrate from. |
|
|
977
1108
|
| `ConversationManagerOptions` | interface | `{ summarize?, keep?, sections?, store? }` | Configures `createConversationManager` — the default `ConversationSummaryHandler`, retained-tail size, and `sections` cap the conversations it creates inherit, plus the optional durable `store` backing `open` / `save`. |
|
|
978
1109
|
| `ConversationManagerInterface` | interface | `{ count, active, conversation(), conversations(), add(), switch(), open(), save(), remove(), clear() }` | Registers `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContextInterface` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManagerInterface`); the observability lives on each `ConversationInterface`. |
|
|
979
1110
|
| `ConversationSnapshot` | interface | `{ id, judgments?, sections, messages }` | Holds a JSON-serializable snapshot of the state of a conversation — its `id`, the compacted `sections`, and the live tail `messages` — the durable payload the `ConversationStoreInterface` persists. The exact analogue of `WorkspaceSnapshot`. |
|
|
980
1111
|
| `ConversationStoreInterface` | interface | `{ get(), set(), delete() }` | Persists a `ConversationSnapshot` durably — the async `get` / `set` / `delete` primitives, keyed by a conversation id and holding no expiry, the exact analogue of `WorkspaceStoreInterface`. |
|
|
981
1112
|
| `ConversationSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseConversationStore` persists — a conversation `id` plus its `ConversationSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. The exact analogue of `WorkspaceSnapshotRow`. |
|
|
982
|
-
| `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP'`
|
|
1113
|
+
| `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'SNAPSHOT'` | Names the machine-readable condition a `ConversationError` reports. |
|
|
983
1114
|
| `JudgmentManagerInterface` | interface | `{ count, add(), judgment(), judgments(), remove(), clear(), resolve() }` | Stores judgments by caller key and resolves requests by reusing matching records. |
|
|
984
1115
|
|
|
985
1116
|
#### Constants
|
|
@@ -995,10 +1126,10 @@ The following table lists the constants the conversations module declares:
|
|
|
995
1126
|
|
|
996
1127
|
The following table lists the errors the conversations module declares and the guards that narrow them:
|
|
997
1128
|
|
|
998
|
-
| Name | Kind | Signature | Summary
|
|
999
|
-
| --------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
|
|
1000
|
-
| `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap below `1`, a `keep` that is not a nonnegative safe integer,
|
|
1001
|
-
| `isConversationError` | function | `(value: unknown) => value is ConversationError` | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`.
|
|
1129
|
+
| Name | Kind | Signature | Summary |
|
|
1130
|
+
| --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1131
|
+
| `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap below `1`, a `keep` that is not a nonnegative safe integer, a summarizer digest whose trimmed text is empty, a judgment or judge request that JSON cannot carry, a stored or selected message whose role is not a conversation role, or a malformed snapshot — thrown by the `compact()` and `add` methods of a `ConversationInterface`, its construction, or its judgment store, or returned as the `fault` of an agent selection, carrying the machine-readable `code` `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'SNAPSHOT'`. |
|
|
1132
|
+
| `isConversationError` | function | `(value: unknown) => value is ConversationError` | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
|
|
1002
1133
|
|
|
1003
1134
|
#### Factories
|
|
1004
1135
|
|
|
@@ -1027,27 +1158,31 @@ The following table lists the classes the conversations module declares:
|
|
|
1027
1158
|
|
|
1028
1159
|
The following table lists the helpers the conversations module declares:
|
|
1029
1160
|
|
|
1030
|
-
| Name
|
|
1031
|
-
|
|
|
1032
|
-
| `buildSummaryMessage`
|
|
1033
|
-
| `buildRecapMessage`
|
|
1034
|
-
| `requireJudgment`
|
|
1035
|
-
| `
|
|
1036
|
-
| `
|
|
1037
|
-
| `
|
|
1038
|
-
| `
|
|
1039
|
-
| `
|
|
1161
|
+
| Name | Kind | Signature | Summary |
|
|
1162
|
+
| ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1163
|
+
| `buildSummaryMessage` | function | `(section: Section) => Message` | Builds the raw synthetic summary message for one compacted section — role `'assistant'`, the section's stable `id`, and its `summary` verbatim as content. |
|
|
1164
|
+
| `buildRecapMessage` | function | `(section: Section) => Message` | Builds the framed recap message for one compacted section — the same role and stable `id` as `buildSummaryMessage`, with the content prefixed by `CONVERSATION_RECAP_PREFIX`. |
|
|
1165
|
+
| `requireJudgment` | function | `(value: unknown) => Judgment` | Returns a stored judgment record after checking it, or throws a coded error. |
|
|
1166
|
+
| `requireRole` | function | `(role: unknown) => ConversationRole` | Returns a stored message role after checking it is a conversation role, or throws a coded error. |
|
|
1167
|
+
| `requireConversationSnapshot` | function | `(value: unknown) => ConversationSnapshot` | Returns a conversation snapshot after checking its shape, its stored roles, and its ids, or throws a coded error. |
|
|
1168
|
+
| `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking its lower bound, or throws a coded error. |
|
|
1169
|
+
| `requireCumulative` | function | `(cumulative: boolean, cap: number \| undefined) => boolean` | Returns the cumulative switch after checking it does not combine with a `sections` cap, or throws a coded error. |
|
|
1170
|
+
| `requireKeep` | function | `(keep: number) => number` | Returns a retained-tail size after checking it is a nonnegative safe integer, or throws a coded error. |
|
|
1171
|
+
| `requireSummary` | function | `(summary: string) => string` | Returns a summarizer digest after checking it carries non-whitespace text, or throws a coded error. |
|
|
1172
|
+
| `raceSignal` | function | `<T>(promise: Promise<T>, signal: AbortSignal \| undefined) => Promise<T>` | Settles with a promise, or rejects with the reason of a signal that aborts first, so a caller is released at once even when the work behind the promise ignores the signal. |
|
|
1173
|
+
| `buildJudgments` | function | `(request: JudgeRequest, result: JudgeResult, sources: readonly string[], state: string, model: string) => readonly JudgmentInput[]` | Builds records for answered or refused request keys, attaching usage only for a single question. |
|
|
1040
1174
|
|
|
1041
1175
|
#### Validators
|
|
1042
1176
|
|
|
1043
1177
|
The following table lists the guards the conversations module declares:
|
|
1044
1178
|
|
|
1045
|
-
| Name | Kind | Signature
|
|
1046
|
-
| ------------------------ | -------- |
|
|
1047
|
-
| `isMessage` | function | `(value: unknown) => value is Message`
|
|
1048
|
-
| `isSection` | function | `(value: unknown) => value is Section`
|
|
1049
|
-
| `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot`
|
|
1050
|
-
| `
|
|
1179
|
+
| Name | Kind | Signature | Summary |
|
|
1180
|
+
| ------------------------ | -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1181
|
+
| `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
|
|
1182
|
+
| `isSection` | function | `(value: unknown) => value is Section` | Checks whether an `unknown` is structurally a `Section` record — a `string` `id` and `summary` beside a `messages` array of valid `Message` records, the per-section step of the `isConversationSnapshot` read-boundary narrow. Total, never throwing, and never an assertion. |
|
|
1183
|
+
| `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id` and valid `sections` and `messages` arrays; the total boundary guard for an untrusted snapshot read (a storage row a `DatabaseConversationStore` reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact analogue of `isWorkspaceSnapshot`. |
|
|
1184
|
+
| `isConversation` | function | `(value: unknown) => value is ConversationInterface` | Checks whether a value carries the `ConversationInterface` members a run reads: a string `id`, a boolean `summarizable`, and `view`, `add`, `compact`, and `messages` methods. |
|
|
1185
|
+
| `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
|
|
1051
1186
|
|
|
1052
1187
|
A `DatabaseConversationStore` reads its snapshot column back as `unknown` and narrows it through `isConversationSnapshot`, so a malformed blob resolves `undefined` rather than a broken conversation:
|
|
1053
1188
|
|
|
@@ -1060,62 +1195,96 @@ const snapshot = isConversationSnapshot(row) ? row : undefined
|
|
|
1060
1195
|
|
|
1061
1196
|
### Contexts module
|
|
1062
1197
|
|
|
1063
|
-
The `contexts` module holds the turn context, its instruction and scope managers, and the selection seam.
|
|
1198
|
+
The `contexts` module holds the turn context, its instruction and scope managers, the memo and skill managers with the memo guards and stores, and the selection seam.
|
|
1064
1199
|
|
|
1065
1200
|
#### Types
|
|
1066
1201
|
|
|
1067
1202
|
The following table lists the types the contexts module declares:
|
|
1068
1203
|
|
|
1069
|
-
| Name | Kind | Signature | Summary
|
|
1070
|
-
| ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1071
|
-
| `
|
|
1072
|
-
| `
|
|
1073
|
-
| `
|
|
1074
|
-
| `
|
|
1075
|
-
| `
|
|
1076
|
-
| `
|
|
1077
|
-
| `
|
|
1078
|
-
| `
|
|
1079
|
-
| `
|
|
1080
|
-
| `
|
|
1081
|
-
| `
|
|
1082
|
-
| `
|
|
1083
|
-
| `
|
|
1084
|
-
| `
|
|
1085
|
-
| `
|
|
1086
|
-
| `
|
|
1204
|
+
| Name | Kind | Signature | Summary |
|
|
1205
|
+
| ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1206
|
+
| `ContextErrorCode` | type | `'SNAPSHOT'` | Names the machine-readable condition a `ContextError` reports. |
|
|
1207
|
+
| `ContextSectionFormat` | interface | `{ open?, render?, close? }` | Overrides one context section's format — an `open` / `render` / `close` trio that frames a section in the `AgentContext` build cascade: a top line rendered once before the items, a per-item rendering, and a bottom line rendered once after the items. |
|
|
1208
|
+
| `InstructionInterface` | interface | `{ id, name, content, priority, override? }` | Represents an immutable instruction — a named directive a richer context places between the system prompt and the conversation, ordered by descending `priority`. |
|
|
1209
|
+
| `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`. |
|
|
1210
|
+
| `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`. |
|
|
1211
|
+
| `InstructionManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createInstructionManager` — the reserved `on` hooks plus an optional per-section format override. |
|
|
1212
|
+
| `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. |
|
|
1213
|
+
| `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. |
|
|
1214
|
+
| `Selection` | interface | `{ messages, judgments, usage?, fault? }` | Carries the conversation part of the next prompt and the receipt for it. |
|
|
1215
|
+
| `SelectionHandler` | type | `(conversation: ConversationInterface, request: Message, signal: AbortSignal) => Promise<Selection>` | Chooses the conversation messages the next prompt carries for one user request. |
|
|
1216
|
+
| `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). |
|
|
1217
|
+
| `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. |
|
|
1218
|
+
| `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. |
|
|
1219
|
+
| `ScopeManagerOptions` | interface | `{ on?, error? }` | Configures `createScopeManager` — the reserved `on` hooks: initial listeners for the manager's `ScopeManagerEventMap`, wired at construction. |
|
|
1220
|
+
| `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. |
|
|
1221
|
+
| `Memo` | interface | `{ id, name, description, content, time, origin? }` | Holds one memo revision: a durable fact kept across conversations. |
|
|
1222
|
+
| `MemoOrigin` | interface | `{ conversation, message? }` | Names where a memo revision came from: a conversation and, optionally, one of its messages. |
|
|
1223
|
+
| `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`. |
|
|
1224
|
+
| `MemoSnapshot` | interface | `{ id, memos }` | Holds every revision of a memo set, oldest first; the current memo of a name is its last revision. |
|
|
1225
|
+
| `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`. |
|
|
1226
|
+
| `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. |
|
|
1227
|
+
| `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. |
|
|
1228
|
+
| `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`. |
|
|
1229
|
+
| `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`. |
|
|
1230
|
+
| `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. |
|
|
1231
|
+
| `SkillInput` | interface | `{ name, description, content, files? }` | Carries the data to author a `Skill`; the `SkillManagerInterface` that stores it mints the `id` and each file. |
|
|
1232
|
+
| `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. |
|
|
1233
|
+
| `SkillManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createSkillManager`: the reserved `on` hooks and a section format override. |
|
|
1234
|
+
| `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. |
|
|
1235
|
+
| `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`. |
|
|
1236
|
+
| `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. |
|
|
1087
1237
|
|
|
1088
1238
|
#### Constants
|
|
1089
1239
|
|
|
1090
1240
|
The following table lists the constants the contexts module declares:
|
|
1091
1241
|
|
|
1092
|
-
| Name | Kind | Signature | Summary
|
|
1093
|
-
| -------------------------- | ----- | ---------------- |
|
|
1094
|
-
| `WORKSPACE_SECTION_HEADER` | const | `"## Workspace"` | Names the section header the `build()` method of `AgentContext` renders the active workspace's text files under — `'## Workspace'`, the
|
|
1242
|
+
| Name | Kind | Signature | Summary |
|
|
1243
|
+
| -------------------------- | ----- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1244
|
+
| `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. |
|
|
1245
|
+
| `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. |
|
|
1246
|
+
| `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. |
|
|
1247
|
+
|
|
1248
|
+
#### Errors
|
|
1249
|
+
|
|
1250
|
+
The following table lists the errors the contexts module declares and the guards that narrow them:
|
|
1251
|
+
|
|
1252
|
+
| Name | Kind | Signature | Summary |
|
|
1253
|
+
| ---------------- | -------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1254
|
+
| `ContextError` | class | `new (code: ContextErrorCode, message: string, options?: CodedErrorOptions) => ContextError` | Reports a context snapshot that `isMemoSnapshot` refuses, thrown by the construction of a `MemoManager` before it seats any state, carrying the machine-readable `code` `'SNAPSHOT'`. |
|
|
1255
|
+
| `isContextError` | function | `(value: unknown) => value is ContextError` | Narrows an unknown caught value to a `ContextError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
|
|
1095
1256
|
|
|
1096
1257
|
#### Factories
|
|
1097
1258
|
|
|
1098
1259
|
The following table lists the factories the contexts module declares:
|
|
1099
1260
|
|
|
1100
|
-
| Name | Kind | Signature | Summary
|
|
1101
|
-
| -------------------------- | -------- | ---------------------------------------------------------------------- |
|
|
1102
|
-
| `createInstruction` | function | `(input: InstructionInput) => InstructionInterface` | Creates an instruction — an immutable `InstructionInterface` (a named directive) from its `name` / `content` and optional `priority`, the `id` minted at construction.
|
|
1103
|
-
| `createInstructionManager` | function | `(options?: InstructionManagerOptions) => InstructionManagerInterface` | Creates an instruction registry — an `InstructionManagerInterface` holding immutable instructions keyed by `name`, listed by descending `priority`.
|
|
1104
|
-
| `createScope` | function | `(input: ScopeInput) => ScopeInterface` | Creates a named scope — an immutable `ScopeInterface` from its `name` and its per-category allow-lists, the `id` minted at construction.
|
|
1105
|
-
| `createScopeManager` | function | `(options?: ScopeManagerOptions) => ScopeManagerInterface` | Creates a scope registry — a `ScopeManagerInterface` holding immutable scopes keyed by their minted `id`, in insertion order.
|
|
1106
|
-
| `
|
|
1261
|
+
| Name | Kind | Signature | Summary |
|
|
1262
|
+
| -------------------------- | -------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1263
|
+
| `createInstruction` | function | `(input: InstructionInput) => InstructionInterface` | Creates an instruction — an immutable `InstructionInterface` (a named directive) from its `name` / `content` and optional `priority`, the `id` minted at construction. |
|
|
1264
|
+
| `createInstructionManager` | function | `(options?: InstructionManagerOptions) => InstructionManagerInterface` | Creates an instruction registry — an `InstructionManagerInterface` holding immutable instructions keyed by `name`, listed by descending `priority`. |
|
|
1265
|
+
| `createScope` | function | `(input: ScopeInput) => ScopeInterface` | Creates a named scope — an immutable `ScopeInterface` from its `name` and its per-category allow-lists, the `id` minted at construction. |
|
|
1266
|
+
| `createScopeManager` | function | `(options?: ScopeManagerOptions) => ScopeManagerInterface` | Creates a scope registry — a `ScopeManagerInterface` holding immutable scopes keyed by their minted `id`, in insertion order. |
|
|
1267
|
+
| `createMemoManager` | function | `(options?: MemoManagerOptions) => MemoManagerInterface` | Creates a memo set — a `MemoManagerInterface` holding durable facts keyed by `name`, where a same-name `add` with changed text appends a revision and the earlier ones stay readable. |
|
|
1268
|
+
| `createMemoryMemoStore` | function | `() => MemoStoreInterface` | Creates the in-memory memo store — a `MemoStoreInterface` backed by a process-lifetime map, the default twin of `createDatabaseMemoStore`. |
|
|
1269
|
+
| `createDatabaseMemoStore` | function | `(driver?: DriverInterface) => MemoStoreInterface` | Creates a `DatabaseMemoStore` over any `DriverInterface` — the durable, driver-pluggable backing for a memo set, holding each snapshot as one opaque JSON column in a `memos` table. |
|
|
1270
|
+
| `createSkillManager` | function | `(options?: SkillManagerOptions) => SkillManagerInterface` | Creates a skill registry — a `SkillManagerInterface` holding the skills a host supplies, keyed by `name` and listed in insertion order. |
|
|
1271
|
+
| `createAgentContext` | function | `(options?: AgentContextOptions) => AgentContextInterface` | Creates a richer turn context — an `AgentContextInterface` assembling a provider request from the optional system prompt, the instruction registry, the skill registry, the memo set, the workspace registry (the only document channel), the conversation registry that is its `messages` source, the tool registry, and the active scope, which `build()` folds into the next turn's input. |
|
|
1107
1272
|
|
|
1108
1273
|
#### Classes
|
|
1109
1274
|
|
|
1110
1275
|
The following table lists the classes the contexts module declares:
|
|
1111
1276
|
|
|
1112
|
-
| Name | Kind | Signature | Summary
|
|
1113
|
-
| -------------------- | ----- | -------------------------------------------------------------------------- |
|
|
1114
|
-
| `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`.
|
|
1115
|
-
| `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`.
|
|
1116
|
-
| `Scope` | class | `new (input: ScopeInput) => ScopeInterface` | Represents a named, immutable filter over a richer context's items — an optional allow-list per category (`instructions` / `tools` / `files`), each keyed by that category's identity (an instruction's
|
|
1117
|
-
| `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.
|
|
1118
|
-
| `
|
|
1277
|
+
| Name | Kind | Signature | Summary |
|
|
1278
|
+
| -------------------- | ----- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1279
|
+
| `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`. |
|
|
1280
|
+
| `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`. |
|
|
1281
|
+
| `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. |
|
|
1282
|
+
| `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. |
|
|
1283
|
+
| `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`. |
|
|
1284
|
+
| `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. |
|
|
1285
|
+
| `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`. |
|
|
1286
|
+
| `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`. |
|
|
1287
|
+
| `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`. |
|
|
1119
1288
|
|
|
1120
1289
|
#### Helpers
|
|
1121
1290
|
|
|
@@ -1129,6 +1298,16 @@ The following table lists the helpers the contexts module declares:
|
|
|
1129
1298
|
| `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. |
|
|
1130
1299
|
| `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. |
|
|
1131
1300
|
| `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. |
|
|
1301
|
+
| `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. |
|
|
1302
|
+
|
|
1303
|
+
#### Validators
|
|
1304
|
+
|
|
1305
|
+
The following table lists the guards the contexts module declares:
|
|
1306
|
+
|
|
1307
|
+
| Name | Kind | Signature | Summary |
|
|
1308
|
+
| ---------------- | -------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1309
|
+
| `isMemo` | const | `Guard<Memo>` | Checks whether a value is a stored memo revision: a record with a string `id`, `name`, `description`, and `content`, a finite `time`, and an optional `origin`. |
|
|
1310
|
+
| `isMemoSnapshot` | function | `(value: unknown) => value is MemoSnapshot` | Checks whether a value is a stored memo set: a record with a string `id` and a dense `memos` array of `isMemo` values. |
|
|
1132
1311
|
|
|
1133
1312
|
### Agents module
|
|
1134
1313
|
|
|
@@ -1138,56 +1317,78 @@ The `agents` module holds the loop, the authority gate, the channel, and the dur
|
|
|
1138
1317
|
|
|
1139
1318
|
The following table lists the types the agents module declares:
|
|
1140
1319
|
|
|
1141
|
-
| Name | Kind | Signature
|
|
1142
|
-
| ------------------------ | --------- |
|
|
1143
|
-
| `AgentStatus` | type | `'idle' \| 'running' \| 'done' \| 'error'`
|
|
1144
|
-
| `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; }`
|
|
1145
|
-
| `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 deny: readonly [call: ToolCall, reason: string \| 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.
|
|
1146
|
-
| `AgentResult` | interface | `{ content, thinking?, usage?, partial, stop? }`
|
|
1147
|
-
| `AgentRunResult` | interface | `{ content, thinking, usage, partial, exhausted, stop }`
|
|
1148
|
-
| `AgentTurn` | interface | `{ content, thinking, usage, spent, messages, outcome, partial, futile, estimate, interrupted, truncated }`
|
|
1149
|
-
| `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; }`
|
|
1150
|
-
| `AgentErrorCode` | type | `'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'WINDOW'`
|
|
1151
|
-
| `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }`
|
|
1152
|
-
| `RequestMeasure` | interface | `{ messages, tools, schema }`
|
|
1153
|
-
| `ChannelInterface` | interface | `{ push(), close(), fail(), drain() }`
|
|
1154
|
-
| `StreamInterface` | interface | `{ events, result, abort() }`
|
|
1155
|
-
| `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>`
|
|
1156
|
-
| `
|
|
1157
|
-
| `
|
|
1158
|
-
| `
|
|
1159
|
-
| `
|
|
1160
|
-
| `
|
|
1161
|
-
| `
|
|
1162
|
-
| `
|
|
1163
|
-
| `
|
|
1164
|
-
| `
|
|
1165
|
-
| `
|
|
1166
|
-
| `
|
|
1167
|
-
| `
|
|
1168
|
-
| `
|
|
1320
|
+
| Name | Kind | Signature | Summary |
|
|
1321
|
+
| ------------------------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1322
|
+
| `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). |
|
|
1323
|
+
| `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`. |
|
|
1324
|
+
| `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. |
|
|
1325
|
+
| `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`. |
|
|
1326
|
+
| `AgentRunResult` | interface | `{ content, thinking, usage, partial, exhausted, stop }` | Holds the immutable outcome of one agent loop, assembled into the `AgentResult` resolved by the stream handle. |
|
|
1327
|
+
| `AgentTurn` | interface | `{ content, thinking, usage, spent, messages, outcome, partial, futile, estimate, interrupted, truncated }` | Holds what one agent loop turn contributed to its run and how the turn ended — the readonly record the loop appends for each turn, from which the run derives its `AgentRunResult`. |
|
|
1328
|
+
| `AgentStop` | type | `{ readonly layer: 'meter' \| 'budget'; readonly id: string; readonly max: number; readonly consumed: number; readonly estimate?: number; readonly usage?: TokenUsage; } \| { readonly layer: 'model'; readonly id: string; readonly estimate?: number; readonly usage?: TokenUsage; }` | Represents why one of a run's three allowed failure layers stopped it — the meter's estimate allowance, the cost budget, or the model's own token limit — with the readings that layer crossed. |
|
|
1329
|
+
| `AgentErrorCode` | type | `'APPROVER' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'WINDOW'` | Names the machine-readable agent approver, concurrency, limit, registry, and window failures. |
|
|
1330
|
+
| `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
|
|
1331
|
+
| `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
|
|
1332
|
+
| `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`. |
|
|
1333
|
+
| `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. |
|
|
1334
|
+
| `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
|
|
1335
|
+
| `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`. |
|
|
1336
|
+
| `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. |
|
|
1337
|
+
| `AgentAnswer` | interface | `{ id, approved }` | Carries a page's answer to one `ask` frame; only `approved: true` approves. |
|
|
1338
|
+
| `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. |
|
|
1339
|
+
| `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. |
|
|
1340
|
+
| `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. |
|
|
1341
|
+
| `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. |
|
|
1342
|
+
| `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
|
|
1343
|
+
| `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
|
|
1344
|
+
| `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
|
|
1345
|
+
| `AuthorityRule` | interface | `{ match, zone, verdict?, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
|
|
1346
|
+
| `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
|
|
1347
|
+
| `AuthorityOptions` | interface | `{ rules?, fallback?, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
|
|
1348
|
+
| `AuthorityInterface` | interface | `{ evaluate(), ask?() }` | Gates each tool call before it runs — the synchronous policy that turns one `AuthorityContext` into an `AuthorityDecision`, and the optional approver that answers an `ask` verdict. |
|
|
1349
|
+
| `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
|
|
1350
|
+
| `AgentJobInput` | interface | `{ provider, messages, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, children? }` | Represents a JSON-serializable agent job — the descriptor a durable queue or runner runs. Its non-serializable pieces (the provider, tools, authority, scheduler) are referenced by name and resolved to live objects through an `AgentRegistryInterface` at handler time, while its data fields (the seed `messages`, `system`, `limit`, `timeout`, and a token `budget` ceiling) carry directly. |
|
|
1351
|
+
| `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
|
|
1352
|
+
| `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
|
|
1353
|
+
| `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`. |
|
|
1354
|
+
| `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`. |
|
|
1169
1355
|
|
|
1170
1356
|
#### Constants
|
|
1171
1357
|
|
|
1172
1358
|
The following table lists the constants the agents module declares:
|
|
1173
1359
|
|
|
1174
|
-
| Name | Kind | Signature
|
|
1175
|
-
| ------------------------ | ----- |
|
|
1176
|
-
| `DEFAULT_AGENT_LIMIT` | const | `10`
|
|
1177
|
-
| `DEFAULT_AUTHORITY_ZONE` | const | `"default"`
|
|
1178
|
-
| `
|
|
1179
|
-
| `
|
|
1360
|
+
| Name | Kind | Signature | Summary |
|
|
1361
|
+
| ------------------------ | ----- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1362
|
+
| `DEFAULT_AGENT_LIMIT` | const | `10` | Caps an `AgentInterface` turn's tool iterations by default — `10` context → provider → tools cycles before the loop stops, so a model that keeps requesting tools can never loop forever. Overridable per agent through `AgentOptions.limit`. |
|
|
1363
|
+
| `DEFAULT_AUTHORITY_ZONE` | const | `"default"` | Names the default zone for an unmatched tool call allowed by an authority. |
|
|
1364
|
+
| `AUTHORITY_NOTES` | const | `AuthorityNote` | Holds the model-facing texts the loop writes after a tool name in a denial result — the `denied` note for a deny with no reason, an evaluate throw, an invalid decision, or a tool changed after its decision; the `refused` note for an ask the approver refused; and the `unanswered` note for an ask no approver answered, frozen. |
|
|
1365
|
+
| `SCOPE_NOTE` | const | `"it is not one of the listed tools. Use a listed tool or answer with what you have."` | Holds the model-facing text the loop writes after a tool name in the denial result of a call outside the active scope's tool allow-list or whose name no definition advertises this turn. |
|
|
1366
|
+
| `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
|
|
1367
|
+
| `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. |
|
|
1180
1368
|
|
|
1181
1369
|
#### Errors
|
|
1182
1370
|
|
|
1183
1371
|
The following table lists the errors the agents module declares and the guards that narrow them:
|
|
1184
1372
|
|
|
1185
|
-
| Name | Kind | Signature | Summary
|
|
1186
|
-
| ----------------- | -------- | ---------------------------------------------------------------------------------------- |
|
|
1187
|
-
| `AgentJobError` | class | `new (message: string, partial: AgentResult) => AgentJobError` | Reports an `AgentInterface` run that ended `AgentResult.partial` under a `partial` policy of `false` (the default) — thrown by an agent-job handler (a `createAgentQueue` / `createAgentRunner` job), carrying the partial `AgentResult` so the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`.
|
|
1188
|
-
| `isAgentJobError` | function | `(value: unknown) => value is AgentJobError` | Narrows an unknown caught value to an `AgentJobError` through its identity brand and declared members, so a `catch` can recover its `partial` result.
|
|
1189
|
-
| `AgentError` | class | `new (code: AgentErrorCode, message: string, options?: CodedErrorOptions) => AgentError` | Reports a run sharing accounting with a live run, a `limit` that is not a nonnegative safe integer, a name absent from a registry pool, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead. Await the call inside `try`/`catch` to catch it. |
|
|
1190
|
-
| `isAgentError` | function | `(value: unknown) => value is AgentError` | Narrows an unknown caught value to an `AgentError` through its identity brand and declared members, so a `catch` can branch on its `code`.
|
|
1373
|
+
| Name | Kind | Signature | Summary |
|
|
1374
|
+
| ----------------- | -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1375
|
+
| `AgentJobError` | class | `new (message: string, partial: AgentResult) => AgentJobError` | Reports an `AgentInterface` run that ended `AgentResult.partial` under a `partial` policy of `false` (the default) — thrown by an agent-job handler (a `createAgentQueue` / `createAgentRunner` job), carrying the partial `AgentResult` so the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`. |
|
|
1376
|
+
| `isAgentJobError` | function | `(value: unknown) => value is AgentJobError` | Narrows an unknown caught value to an `AgentJobError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
|
|
1377
|
+
| `AgentError` | class | `new (code: AgentErrorCode, message: string, options?: CodedErrorOptions) => AgentError` | Reports an `ask` on an authority that has no approver or that its approver refuses, a run sharing accounting or a conversation with a live run, a `limit` that is not a nonnegative safe integer, a name absent from a registry pool, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead, and an `'APPROVER'` refusal rejects the promise the `ask` method of an `Authority` or the `ask` handler of an `Approver` returns. Await the call inside `try`/`catch` to catch it. |
|
|
1378
|
+
| `isAgentError` | function | `(value: unknown) => value is AgentError` | Narrows an unknown caught value to an `AgentError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
|
|
1379
|
+
|
|
1380
|
+
#### Shapes and contracts
|
|
1381
|
+
|
|
1382
|
+
The following table lists the agent wire shapes and the contracts compiled from them:
|
|
1383
|
+
|
|
1384
|
+
| Name | Kind | Signature | Summary |
|
|
1385
|
+
| --------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1386
|
+
| `agentFrameShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["token"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["think"]>; content: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [true]>; name: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["tool"]>; success: import("@orkestrel/contract").LiteralShape<readonly [false]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["usage"]>; usage: import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>; estimate: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["ask"]>; id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; zone: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["finish"]>; content: import("@orkestrel/contract").StringShape; partial: import("@orkestrel/contract").BooleanShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; layer: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").LiteralShape<readonly ["meter", "budget", "model"]>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ category: import("@orkestrel/contract").LiteralShape<readonly ["error"]>; }, boolean \| ContractShape>]>` | Describes the agent frame wire — one exact object per `AgentFrame` arm, discriminated by `category`. |
|
|
1387
|
+
| `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. |
|
|
1388
|
+
| `agentAnswerShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; approved: import("@orkestrel/contract").BooleanShape; }, boolean \| ContractShape>` | Describes the agent answer wire — the `id` of one `ask` frame and a boolean `approved`. |
|
|
1389
|
+
| `agentFrameContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ category: "token"; content: string; } & {}> \| Readonly<{ category: "think"; content: string; } & {}> \| Readonly<{ category: "tool"; success: true; name: string; } & {}> \| Readonly<{ category: "tool"; success: false; } & {}> \| Readonly<{ category: "usage"; usage: Readonly<{ prompt: number; completion: number; total: number; } & {}>; estimate: number; } & {}> \| Readonly<{ category: "ask"; id: string; name: string; zone: string; arguments: string; } & {}> \| Readonly<{ category: "finish"; content: string; partial: boolean; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; layer?: "budget" \| "meter" \| "model"; }> \| Readonly<{ category: "error"; } & {}>>` | Validates and projects agent frames at a JSON wire boundary. |
|
|
1390
|
+
| `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. |
|
|
1391
|
+
| `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. |
|
|
1191
1392
|
|
|
1192
1393
|
#### Factories
|
|
1193
1394
|
|
|
@@ -1197,6 +1398,7 @@ The following table lists the factories the agents module declares:
|
|
|
1197
1398
|
| --------------------- | -------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1198
1399
|
| `createAgent` | function | `(provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Creates an agent loop — an `AgentInterface` composing a `ProviderInterface`, its `AgentContextInterface`, and a tool registry into a bounded context → provider → tools → repeat turn, exposed as a one-shot `generate` and a live `stream`. |
|
|
1199
1400
|
| `createAuthority` | function | `(options?: AuthorityOptions) => AuthorityInterface` | Creates a policy gate — an `AuthorityInterface` the agent loop consults before each tool call runs, evaluating the ordered rules first-match-wins and falling back to the configured default when none match. |
|
|
1401
|
+
| `createApprover` | function | `() => ApproverInterface` | Creates an approver — an `ApproverInterface` that holds a server's waiting asks between the run that asked them and the page that answers them. |
|
|
1200
1402
|
| `createChannel` | function | `<T>() => ChannelInterface<T>` | Creates an empty unbounded async channel — a `ChannelInterface` a producer writes values into (`push`) and ends (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
|
|
1201
1403
|
| `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. |
|
|
1202
1404
|
| `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. |
|
|
@@ -1210,7 +1412,8 @@ The following table lists the classes the agents module declares:
|
|
|
1210
1412
|
| --------------- | ----- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1211
1413
|
| `Agent` | class | `new (provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Composes a `ProviderInterface`, an `AgentContext`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn, exposed as both a one-shot `generate` and a live `stream` that share one private run — bounded by the run `signal`, the `timeout`, and the `budget` folded through `AbortSignal.any`, paced by `scheduler`, with tool iteration capped at `limit`. |
|
|
1212
1414
|
| `AgentFanout` | class | `new (registry: AgentRegistryInterface, partial: boolean) => AgentFanout` | Executes one runner's agent jobs — spawning each unit's declared children on its first attempt only, then rehydrating the unit through a registry with the controller signal and settling it under the shared partial-result policy. |
|
|
1213
|
-
| `Authority` | class | `new (options?: AuthorityOptions) => AuthorityInterface` | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to a configurable default, which allows an unmatched call unless its `fallback`
|
|
1415
|
+
| `Authority` | class | `new (options?: AuthorityOptions) => AuthorityInterface` | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to a configurable default, which allows an unmatched call unless its `fallback` decides otherwise, and the approver that answers an `ask` verdict. |
|
|
1416
|
+
| `Approver` | class | `new () => ApproverInterface` | Holds a server's waiting asks between the run that asked them and the page that answers them — an `ApproverInterface` whose `ask` is the authority's handler, keyed by the asked call object. |
|
|
1214
1417
|
| `AgentRegistry` | class | `new (options: AgentRegistryOptions) => AgentRegistryInterface` | Makes a durable, JSON-serializable `AgentJobInput` runnable — holds the named pools of live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name absent from its pool, and its `build` method returns a seeded, signal-wired `Agent` from a job's names and data. |
|
|
1215
1418
|
| `Channel` | class | `new <T>() => ChannelInterface<T>` | Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through the `drain` async-iterator. Decoupling write from read is what lets a producer make progress without a consumer pulling, and it is why an agent's `result` settles whether or not its `events` are drained. |
|
|
1216
1419
|
|
|
@@ -1218,26 +1421,32 @@ The following table lists the classes the agents module declares:
|
|
|
1218
1421
|
|
|
1219
1422
|
The following table lists the helpers the agents module declares:
|
|
1220
1423
|
|
|
1221
|
-
| Name | Kind | Signature | Summary
|
|
1222
|
-
| --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1223
|
-
| `agentResultToJSON` | function | `(value: unknown) => JSONValue \| undefined` | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving finite negative and fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a non-finite usage number, a throwing getter, or a
|
|
1224
|
-
| `tokenUsageToJSON` | function | `(value: unknown) => TokenUsage \| undefined` | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving finite negative and fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing or non-finite count, a throwing getter, or a
|
|
1225
|
-
| `
|
|
1226
|
-
| `
|
|
1227
|
-
| `
|
|
1228
|
-
| `
|
|
1229
|
-
| `
|
|
1230
|
-
| `
|
|
1231
|
-
| `
|
|
1232
|
-
| `
|
|
1233
|
-
| `
|
|
1234
|
-
| `
|
|
1235
|
-
| `
|
|
1236
|
-
| `
|
|
1237
|
-
| `
|
|
1238
|
-
| `
|
|
1239
|
-
| `
|
|
1240
|
-
| `
|
|
1424
|
+
| Name | Kind | Signature | Summary |
|
|
1425
|
+
| --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1426
|
+
| `agentResultToJSON` | function | `(value: unknown) => JSONValue \| undefined` | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving finite negative and fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a non-finite usage number, a throwing getter, or a malformed or revoked proxy. |
|
|
1427
|
+
| `tokenUsageToJSON` | function | `(value: unknown) => TokenUsage \| undefined` | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving finite negative and fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing or non-finite count, a throwing getter, or a malformed or revoked proxy. |
|
|
1428
|
+
| `agentChunkToFrame` | function | `(chunk: AgentChunk) => AgentFrame \| undefined` | Projects one `AgentChunk` onto the `AgentFrame` a page receives, member by member, or returns `undefined` for an `ask` chunk. |
|
|
1429
|
+
| `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
|
|
1430
|
+
| `agentStreamToFrames` | function | `(stream: AgentStreamInterface, approver: ApproverInterface \| undefined) => AsyncGenerator<AgentFrame, void, undefined>` | Projects a run's live handle onto the frames a page receives — one frame per projected chunk, in order, then exactly one terminal `finish` or `error`, last. |
|
|
1431
|
+
| `inferStop` | function | `(reason: unknown, allowance: BudgetInterface<TokenUsage> \| undefined, budget: BudgetInterface<TokenUsage> \| undefined, provider: string, turn: AgentTurn \| undefined) => AgentStop \| undefined` | Infers which of a run's three failure layers stopped it — the meter allowance, a cost budget, or the model's own token limit — and returns the stop record with the final call's readings, or `undefined` when no layer stopped the run. |
|
|
1432
|
+
| `estimateTokens` | function | `(text: string) => number` | Estimates the context-token footprint of a string — the deterministic `ceil(length / 4)` character heuristic `estimateMessages` sums over a conversation's messages (the default context-budget estimator). |
|
|
1433
|
+
| `estimateMessages` | function | `(messages: readonly Message[]) => number` | Estimates the context-token footprint of a batch of messages — each message's content plus `MESSAGE_TOKEN_OVERHEAD`, a tool-call JSON estimate, a thinking estimate, and `IMAGE_TOKEN_ESTIMATE` for each attached image. The `estimateRequest` message term for an agent's context budget (the `AgentOptions` `window`), a provider-independent approximation for conforming messages rather than an exact tokenizer count. |
|
|
1434
|
+
| `estimateRequest` | function | `(request: ProviderRequest) => number` | Estimates the context-token footprint of a complete provider request — its messages through `estimateMessages`, plus the rendered advertised `tools`, plus the rendered `options.schema`. The `consumer` estimator an agent's `window` budget measures every request through, a provider-independent heuristic rather than an exact tokenizer count. |
|
|
1435
|
+
| `measureMessage` | function | `(message: Message) => MessageMeasure` | Measures the disjoint estimate components of one message — its content, framing, rendered calls, thinking, and attached images — as the same heuristic units `estimateMessages` sums. |
|
|
1436
|
+
| `measureRequest` | function | `(request: ProviderRequest) => RequestMeasure` | Measures the disjoint estimate components of a complete provider request — each message through `measureMessage`, plus the rendered advertised `tools` and `options.schema` — as the same heuristic units `estimateRequest` sums. |
|
|
1437
|
+
| `settleAgentJob` | function | `(agent: AgentInterface, partial: boolean) => Promise<AgentResult>` | Runs one rehydrated agent and applies the partial-as-configurable-failure policy — a partial run throws an `AgentJobError` unless the `partial` policy allows it, and a natural finish resolves. The shared job-handler step `createAgentQueue` and `createAgentRunner` both settle each job through, so the policy can never diverge between them. |
|
|
1438
|
+
| `handleAgentQueueJob` | function | `(registry: AgentRegistryInterface, partial: boolean, input: AgentJobInput, context: QueueContext) => Promise<AgentResult>` | Handles one queued agent job by rehydrating it through a registry with the queue attempt's signal, then applying the shared partial-result policy. |
|
|
1439
|
+
| `assembleResult` | function | `(outcome: AgentRunResult) => AgentResult` | Assembles the settled `AgentResult` from a run's `AgentRunResult` — `thinking`, `usage`, and `stop` are carried only when the run surfaced them, and the loop-internal `exhausted` flag is left out. |
|
|
1440
|
+
| `denyCall` | function | `(call: ToolCall, reason: string \| undefined) => ToolResult` | Synthesizes the denial `ToolResult` a blocked call is fed back with — the call's `id` / `name` keyed back, carrying a denial `error` instead of a value. |
|
|
1441
|
+
| `renderArguments` | function | `(value: Readonly<Record<string, unknown>>) => string \| undefined` | Renders a tool call's arguments as escaped canonical JSON text — sorted keys, with every control, format, line-separator, and paragraph-separator code point written as `\uXXXX` — or returns `undefined` when they cannot be rendered. |
|
|
1442
|
+
| `resolveDecision` | function | `(decision: AuthorityDecision, definition: ToolDefinition \| undefined) => AuthorityDecision` | Applies the `consequential` floor to one `AuthorityDecision` — an `allow` for a tool whose advertised definition is annotated `consequential` becomes an `ask`. |
|
|
1443
|
+
| `chargeUsage` | function | `(budget: BudgetInterface<TokenUsage> \| undefined, usage: TokenUsage, charged: number) => void` | Consumes a reported usage against a budget over what was already charged, so a turn's total draw is never less than the report and nothing is charged twice. |
|
|
1444
|
+
| `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a nonnegative safe integer, or throws a coded error. |
|
|
1445
|
+
| `requireBudget` | function | `(value: BudgetInterface<TokenUsage> \| undefined, key: 'budget' \| 'allowance') => BudgetInterface<TokenUsage> \| undefined` | Returns a run's budget or allowance after checking it implements `BudgetInterface`, or throws a coded error before the run starts it. |
|
|
1446
|
+
| `requireConversation` | function | `(value: unknown) => ConversationInterface \| undefined` | Returns a run's `conversation` option after checking it implements `ConversationInterface`, or throws a coded error before the run starts. |
|
|
1447
|
+
| `renderToolValue` | function | `(value: unknown) => string` | Renders a tool's output as the string content of its tool message. |
|
|
1448
|
+
| `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
|
|
1449
|
+
| `extractQueueOptions` | function | `(options: Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>) => Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>` | Extracts the present concurrency, retry, and deadline options for an agent job queue. |
|
|
1241
1450
|
|
|
1242
1451
|
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.
|
|
1243
1452
|
|
|
@@ -1275,59 +1484,69 @@ const fanout = new AgentFanout(registry, false) // one per runner: it records th
|
|
|
1275
1484
|
const runnerHandler = fanout.execute.bind(fanout)
|
|
1276
1485
|
```
|
|
1277
1486
|
|
|
1487
|
+
#### Validators
|
|
1488
|
+
|
|
1489
|
+
The following table lists the guards the agents module declares:
|
|
1490
|
+
|
|
1491
|
+
| Name | Kind | Signature | Summary |
|
|
1492
|
+
| --------------------- | -------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1493
|
+
| `isAuthorityDecision` | function | `(value: unknown) => value is AuthorityDecision` | Checks whether a value is an authority decision: an object whose `zone` is a string, whose `verdict` is `allow`, `ask`, or `deny`, and whose `reason` is absent or a string. |
|
|
1494
|
+
|
|
1278
1495
|
### Ledgers module
|
|
1279
1496
|
|
|
1280
|
-
The `ledgers` module serves a conversation through
|
|
1497
|
+
The `ledgers` module serves a conversation through event-sourced records: the `Ledger` entity, the `LedgerRequest` class that holds one request's state while it is served, the `Classifier` class that files messages through a judge, the `Gauge` class that prices a prompt, and the pure projection helpers. For the method, see [Serving a conversation through a ledger](#serving-a-conversation-through-a-ledger); for a ledger built end to end, see [Serving requests through a ledger](#serving-requests-through-a-ledger).
|
|
1281
1498
|
|
|
1282
1499
|
#### Types
|
|
1283
1500
|
|
|
1284
1501
|
The following table lists the types the ledger declares, each with its shape:
|
|
1285
1502
|
|
|
1286
|
-
| Name | Kind | Signature
|
|
1287
|
-
| ------------------------- | --------- |
|
|
1288
|
-
| `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]`
|
|
1289
|
-
| `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }`
|
|
1290
|
-
| `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }`
|
|
1291
|
-
| `LedgerTopic` | interface | `{ name, criterion, requested? }`
|
|
1292
|
-
| `LedgerShare` | interface | `{ prompt, tail }`
|
|
1293
|
-
| `LedgerNote` | interface | `{ cue, results, repeat, closure }`
|
|
1294
|
-
| `LedgerRecallOptions` | interface | `{ limit? }`
|
|
1295
|
-
| `
|
|
1296
|
-
| `
|
|
1297
|
-
| `
|
|
1298
|
-
| `
|
|
1299
|
-
| `
|
|
1300
|
-
| `
|
|
1301
|
-
| `
|
|
1302
|
-
| `
|
|
1303
|
-
| `
|
|
1304
|
-
| `
|
|
1305
|
-
| `
|
|
1306
|
-
| `
|
|
1307
|
-
| `
|
|
1308
|
-
| `
|
|
1309
|
-
| `
|
|
1310
|
-
| `
|
|
1311
|
-
| `
|
|
1312
|
-
| `
|
|
1313
|
-
| `
|
|
1314
|
-
| `
|
|
1315
|
-
| `
|
|
1316
|
-
| `
|
|
1317
|
-
| `
|
|
1318
|
-
| `
|
|
1319
|
-
| `
|
|
1320
|
-
| `
|
|
1321
|
-
| `
|
|
1322
|
-
| `
|
|
1323
|
-
| `
|
|
1324
|
-
| `
|
|
1325
|
-
| `
|
|
1326
|
-
| `
|
|
1327
|
-
| `
|
|
1328
|
-
| `
|
|
1329
|
-
| `
|
|
1330
|
-
| `
|
|
1503
|
+
| Name | Kind | Signature | Summary |
|
|
1504
|
+
| ------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1505
|
+
| `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
|
|
1506
|
+
| `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
|
|
1507
|
+
| `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
|
|
1508
|
+
| `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
|
|
1509
|
+
| `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
|
|
1510
|
+
| `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
|
|
1511
|
+
| `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
|
|
1512
|
+
| `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
|
|
1513
|
+
| `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
|
|
1514
|
+
| `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
|
|
1515
|
+
| `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
|
|
1516
|
+
| `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
|
|
1517
|
+
| `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
|
|
1518
|
+
| `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
|
|
1519
|
+
| `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
|
|
1520
|
+
| `LedgerIndex` | interface | `{ ids, aliases, carriers, names, words, keys, ranks }` | Carries a registry prepared for matching: its ids, each owner name's owners, and the compiled needles. |
|
|
1521
|
+
| `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
|
|
1522
|
+
| `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
|
|
1523
|
+
| `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, correction?, agent?, snapshot? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, snapshot, recall limit, correction filter, and agent options. |
|
|
1524
|
+
| `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
|
|
1525
|
+
| `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
|
|
1526
|
+
| `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), calibrate(), snapshot() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
|
|
1527
|
+
| `LedgerRequestInterface` | interface | `{ message, plan, selection, boundary, usage, calls, attempts, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), lines() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing attempts and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
|
|
1528
|
+
| `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
|
|
1529
|
+
| `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
|
|
1530
|
+
| `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
|
|
1531
|
+
| `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
|
|
1532
|
+
| `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
|
|
1533
|
+
| `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
|
|
1534
|
+
| `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
|
|
1535
|
+
| `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
|
|
1536
|
+
| `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
|
|
1537
|
+
| `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
|
|
1538
|
+
| `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
|
|
1539
|
+
| `ClassifierOptions` | interface | `{ conversation, judge, questions, topics, thresholds, assign, entities, correction?, scheduler? }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, the ledger's handlers, and the optional correction filter and scheduler. |
|
|
1540
|
+
| `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
|
|
1541
|
+
| `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
|
|
1542
|
+
| `ClassifierAttempt` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
|
|
1543
|
+
| `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
|
|
1544
|
+
| `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
|
|
1545
|
+
| `GaugeCall` | interface | `{ estimate, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
|
|
1546
|
+
| `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
|
|
1547
|
+
| `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
|
|
1548
|
+
| `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names the planning group of a source the records render: a topic match, an off-topic rule or correction, or a name match. |
|
|
1549
|
+
| `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT'` | Names the machine-readable conditions a `LedgerError` error reports. |
|
|
1331
1550
|
|
|
1332
1551
|
#### Constants
|
|
1333
1552
|
|
|
@@ -1337,7 +1556,7 @@ The following table lists the constants that hold the ledger's categories, recor
|
|
|
1337
1556
|
| --------------------------- | ----- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1338
1557
|
| `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. |
|
|
1339
1558
|
| `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
|
|
1340
|
-
| `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the
|
|
1559
|
+
| `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the records render. |
|
|
1341
1560
|
| `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
|
|
1342
1561
|
| `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
|
|
1343
1562
|
| `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
|
|
@@ -1346,7 +1565,9 @@ The following table lists the constants that hold the ledger's categories, recor
|
|
|
1346
1565
|
| `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt and tail shares. |
|
|
1347
1566
|
| `DEFAULT_LEDGER_LIMIT` | const | `8` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
|
|
1348
1567
|
| `DEFAULT_RECALL_LIMIT` | const | `2` | Caps the `recall` calls of one request at 2 calls. |
|
|
1568
|
+
| `LEDGER_SLICE` | const | `5` | Sets the 5 milliseconds a paced classifier files between host turns. |
|
|
1349
1569
|
| `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. |
|
|
1570
|
+
| `LEDGER_WORD` | const | `RegExp` | Matches a run of letters and digits, which the ledger reads as one word. |
|
|
1350
1571
|
| `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. |
|
|
1351
1572
|
|
|
1352
1573
|
#### Errors
|
|
@@ -1372,62 +1593,67 @@ The following table lists the classes that serve, file, and price a conversation
|
|
|
1372
1593
|
|
|
1373
1594
|
| Name | Kind | Signature | Summary |
|
|
1374
1595
|
| --------------- | ----- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1375
|
-
| `Ledger` | class | `new (provider: ProviderInterface, options: LedgerOptions) => LedgerInterface` | Serves one conversation through classified records, a bounded
|
|
1376
|
-
| `LedgerRequest` | class | `new (content: string, limit?: number) => LedgerRequestInterface` | Holds what one ledger request keeps while it is served: its message, its filing
|
|
1596
|
+
| `Ledger` | class | `new (provider: ProviderInterface, options: LedgerOptions) => LedgerInterface` | Serves one conversation through classified records, a bounded copy of each request turn that carries them, and a final answer pass. |
|
|
1597
|
+
| `LedgerRequest` | class | `new (content: string, limit?: number) => LedgerRequestInterface` | Holds what one ledger request keeps while it is served: its message, its filing attempts and plan, the gauge calls of its passes, and its repeat and recall stops. |
|
|
1377
1598
|
| `Classifier` | class | `new (options: ClassifierOptions) => ClassifierInterface` | Files messages through the conversation's judgment manager and reads their categories and corrections. |
|
|
1378
1599
|
| `Gauge` | class | `new (options: GaugeOptions) => GaugeInterface` | Prices prompts in tokens from a measured scale and overhead cost, and measures the room a request has left. |
|
|
1379
1600
|
|
|
1380
1601
|
#### Validators
|
|
1381
1602
|
|
|
1382
|
-
The following guards validate ledger fractions and
|
|
1603
|
+
The following guards validate ledger fractions, capacity, and snapshots:
|
|
1383
1604
|
|
|
1384
|
-
| Name | Kind | Signature
|
|
1385
|
-
| ----------------------- | -------- |
|
|
1386
|
-
| `isFraction` | function | `(value: unknown) => value is number`
|
|
1387
|
-
| `isPositiveSafeInteger` | function | `(value: unknown) => value is number`
|
|
1605
|
+
| Name | Kind | Signature | Summary |
|
|
1606
|
+
| ----------------------- | -------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------- |
|
|
1607
|
+
| `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
|
|
1608
|
+
| `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
|
|
1609
|
+
| `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
|
|
1388
1610
|
|
|
1389
1611
|
#### Helpers
|
|
1390
1612
|
|
|
1391
|
-
The following table lists the pure helpers that read text, project and select records, render
|
|
1392
|
-
|
|
1393
|
-
| Name | Kind | Signature
|
|
1394
|
-
| -------------------------- | -------- |
|
|
1395
|
-
| `splitSentences` | function | `(text: string) => readonly string[]`
|
|
1396
|
-
| `
|
|
1397
|
-
| `
|
|
1398
|
-
| `
|
|
1399
|
-
| `
|
|
1400
|
-
| `
|
|
1401
|
-
| `matchEntities` | function | `(
|
|
1402
|
-
| `
|
|
1403
|
-
| `
|
|
1404
|
-
| `
|
|
1405
|
-
| `
|
|
1406
|
-
| `
|
|
1407
|
-
| `
|
|
1408
|
-
| `
|
|
1409
|
-
| `
|
|
1410
|
-
| `
|
|
1411
|
-
| `
|
|
1412
|
-
| `
|
|
1413
|
-
| `
|
|
1414
|
-
| `
|
|
1415
|
-
| `
|
|
1416
|
-
| `
|
|
1417
|
-
| `
|
|
1418
|
-
| `
|
|
1419
|
-
| `
|
|
1420
|
-
| `
|
|
1421
|
-
| `
|
|
1422
|
-
| `
|
|
1423
|
-
| `
|
|
1424
|
-
| `
|
|
1425
|
-
| `
|
|
1426
|
-
| `
|
|
1427
|
-
| `
|
|
1428
|
-
| `
|
|
1429
|
-
| `
|
|
1430
|
-
| `
|
|
1613
|
+
The following table lists the pure helpers that read text, project and select records, render the records, and fit a price:
|
|
1614
|
+
|
|
1615
|
+
| Name | Kind | Signature | Summary |
|
|
1616
|
+
| -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
1617
|
+
| `splitSentences` | function | `(text: string) => readonly string[]` | Splits a message into its sentences. |
|
|
1618
|
+
| `collectNames` | function | `(text: string) => readonly string[]` | Collects the capitalized name runs of a text, leaving out the run that opens each sentence. |
|
|
1619
|
+
| `identifyLookup` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string \| undefined` | Identifies a lookup finding for projection by its tool name and normalized arguments. |
|
|
1620
|
+
| `linkOwners` | function | `(findings: readonly LedgerLookupFinding[], owners: ReadonlyMap<string, readonly string[]>) => ReadonlyMap<string, string>` | Links each id-shaped lookup argument to its owner. |
|
|
1621
|
+
| `collectRegistry` | function | `(findings: readonly LedgerLookupFinding[]) => LedgerRegistry` | Collects the ids and the owner names the lookup findings named. |
|
|
1622
|
+
| `buildLedgerIndex` | function | `(registry: LedgerRegistry) => LedgerIndex` | Builds a registry's matching index: each name's owners, each word's carriers, the needles, keys, and ranks. |
|
|
1623
|
+
| `matchEntities` | function | `(index: LedgerIndex, text: string, partial: boolean) => ReadonlySet<string>` | Matches the registry ids and owners a text names. |
|
|
1624
|
+
| `normalizeWord` | function | `(word: string) => string` | Normalizes a run of letters and digits to the one form each of its cases folds to. |
|
|
1625
|
+
| `buildRecords` | function | `(input: LedgerProjectionInput) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
|
|
1626
|
+
| `selectRecords` | function | `(projection: LedgerProjection, request: LedgerProjectionRequest) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
|
|
1627
|
+
| `findLedgerCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
|
|
1628
|
+
| `collectProjectionIds` | function | `(projection: LedgerProjection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
|
|
1629
|
+
| `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. |
|
|
1630
|
+
| `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
|
|
1631
|
+
| `buildRequestMessage` | function | `(request: Message, records: string) => Message` | Builds the copy of a request turn that carries the rendered records ahead of the request. |
|
|
1632
|
+
| `renderTopicNames` | function | `(topics: readonly LedgerTopic[]) => string` | Renders topic names as a comma-separated list in their supplied order. |
|
|
1633
|
+
| `renderCauseChain` | function | `(error: unknown) => string` | Renders an error and its causes, stopping after 4 entries. |
|
|
1634
|
+
| `extractWords` | function | `(message: Message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
|
|
1635
|
+
| `splitWords` | function | `(part: string) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
|
|
1636
|
+
| `rankLedgerCut` | function | `(group: LedgerPlanGroup, unsettled: boolean, category: LedgerCategory \| undefined) => number` | Ranks a source the records render for removal before the next prompt. |
|
|
1637
|
+
| `findLedgerCut` | function | `<T>(low: number, high: number, probe: (cut: number) => T \| undefined, found?: T) => T \| undefined` | Finds the first cut in a range whose probe returns a value, by bisection. |
|
|
1638
|
+
| `buildLedgerCut` | function | `(steps: ReadonlyArray<LedgerLine \| string>, records: readonly LedgerRecord[], included: ReadonlySet<string>) => { readonly records: readonly LedgerRecord[]; readonly included: ReadonlySet<string>; }` | Builds the cut the given steps leave: each step drops the line it is, by identity, or the source it names. |
|
|
1639
|
+
| `renderLedgerRecord` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one record as a heading and one list item per line. |
|
|
1640
|
+
| `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. |
|
|
1641
|
+
| `splitTopic` | function | `(topic: string) => readonly string[]` | Splits a recall topic at its joints. |
|
|
1642
|
+
| `cutListing` | function | `(entries: readonly string[], room: number) => string` | Cuts entries to a room and names how many it left out. |
|
|
1643
|
+
| `matchesCutLine` | function | `(line: string) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
|
|
1644
|
+
| `normalizeArgument` | function | `(value: string) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
|
|
1645
|
+
| `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. |
|
|
1646
|
+
| `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
|
|
1647
|
+
| `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState) => string` | Renders the tail stub of a lookup result from an earlier request. |
|
|
1648
|
+
| `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
|
|
1649
|
+
| `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
|
|
1650
|
+
| `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
|
|
1651
|
+
| `collectLive` | function | `(input: LedgerProjectionInput) => readonly string[]` | Collects the ids of the live messages in conversation order. |
|
|
1652
|
+
| `placeMember` | function | `(input: LedgerProjectionInput, links: ReadonlyMap<string, string>, amended: ReadonlyMap<string, readonly string[]>, id: string, seen: ReadonlySet<string>, settled?: Map<string, ReadonlySet<string>>) => ReadonlySet<string>` | Places a message on the record keys it joins. |
|
|
1653
|
+
| `buildLedgerRenderContext` | function | `(messages: readonly Message[], lines: readonly LedgerLine[], amendments: readonly LedgerAmendment[]) => LedgerRenderContext` | Derives complete source identities, first occurrences, and local references from the actual lines of the records. |
|
|
1654
|
+
| `renderLedgerAnnotation` | function | `(line: LedgerLine, context: LedgerRenderContext) => string` | Renders a source's reference and its later changes at the source's first retained line. |
|
|
1655
|
+
| `collectAmendments` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, live: readonly string[]) => readonly LedgerAmendment[]` | Collects accepted direct amendments of live messages. |
|
|
1656
|
+
| `buildLines` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, id: string, holders: readonly string[], system: readonly string[]) => readonly LedgerLine[]` | Builds the record lines of one message. |
|
|
1431
1657
|
|
|
1432
1658
|
The `Classifier` and `Gauge` classes the ledger composes are public, so a harness can file a conversation or price a prompt without a ledger. The following classifier files one rule, and the following gauge prices the calls of one request:
|
|
1433
1659
|
|
|
@@ -1452,7 +1678,7 @@ const classifier = new Classifier({
|
|
|
1452
1678
|
})
|
|
1453
1679
|
const filed = await classifier.classify(new Set(), signal)
|
|
1454
1680
|
filed.judgments.length // 2 — the category question and the refunds topic question
|
|
1455
|
-
filed.
|
|
1681
|
+
filed.attempts.map((attempt) => attempt.outcome) // ['resolved', 'resolved'] — the judge answered both
|
|
1456
1682
|
classifier.category(rule.id) // 'rule'
|
|
1457
1683
|
classifier.decisive(rule.id) // true
|
|
1458
1684
|
classifier.quiet(rule.id) // false
|
|
@@ -1469,11 +1695,11 @@ gauge.observe(calls)
|
|
|
1469
1695
|
gauge.scale // 1.3 — the first call's prompt less the overhead cost, over its estimate
|
|
1470
1696
|
```
|
|
1471
1697
|
|
|
1472
|
-
Agent-owned readonly data members stay in the preceding Surface tables; their call-signature methods are documented under [`## Methods`](#methods). For tool contracts, see [Tool](tool.md), and for workspace contracts, see [Workspace](workspace.md); neither dependency surface is duplicated or re-exported here. Note where the boundary falls inside the context: `instructions`, `conversations`, and `workspaces` are the managers `build()` renders a prompt from, while `tools` is loop machinery for advertising and dispatch and is never read by `build()` at all.
|
|
1698
|
+
Agent-owned readonly data members stay in the preceding Surface tables; their call-signature methods are documented under [`## Methods`](#methods). For tool contracts, see [Tool](tool.md), and for workspace contracts, see [Workspace](workspace.md); neither dependency surface is duplicated or re-exported here. Note where the boundary falls inside the context: `instructions`, `skills`, `memos`, `conversations`, and `workspaces` are the managers `build()` renders a prompt from, while `tools` is loop machinery for advertising and dispatch and is never read by `build()` at all.
|
|
1473
1699
|
|
|
1474
1700
|
## Methods
|
|
1475
1701
|
|
|
1476
|
-
The tables list every public call-signature member of `ProviderInterface`, `AgentProviderInterface`, `ProviderParserInterface`, `RelayProvider`, `JudgeInterface`, `AgentJudgeInterface`, `SystemOneJudge`, `ThinkSplitterInterface`, `JudgmentManagerInterface`, `MessageManagerInterface`, `InstructionManagerInterface`, `ScopeInterface`, `ScopeManagerInterface`, `AgentContextInterface`, `AgentInterface`, `StreamInterface`, `ChannelInterface`, `AuthorityInterface`, `AgentRegistryInterface`, `ConversationInterface`, `ConversationManagerInterface`, `ConversationStoreInterface`, `MemoryConversationStore`, `DatabaseConversationStore`, `LedgerInterface`, `LedgerRequestInterface`, `ClassifierInterface`, and `GaugeInterface`. Their readonly data members remain Surface rows. `AgentProvider`, `AgentJudge`, `ThinkSplitter`, `InstructionManager`, `Scope`, `ScopeManager`, `AgentContext`, `Agent`, `Authority`, `AgentRegistry`, `Conversation`, `ConversationManager`, `JudgmentManager`, `Ledger`, `LedgerRequest`, `Classifier`, and `Gauge` implement their interfaces exactly, so the tables also describe those classes' instance methods. `RelayProvider`, `SystemOneJudge`, and the store classes keep explicit tables because their class names have no same-name interface contract. `MessageManagerInterface` has no separate concrete class here: the active `Conversation` satisfies it structurally. `RelayStream` exposes `response` alone, a data member, so it keeps its Surface row and takes no table. Tool and workspace methods live in their dependency guides.
|
|
1702
|
+
The tables list every public call-signature member of `ProviderInterface`, `AgentProviderInterface`, `ProviderParserInterface`, `RelayProvider`, `JudgeInterface`, `AgentJudgeInterface`, `SystemOneJudge`, `ThinkSplitterInterface`, `JudgmentManagerInterface`, `MessageManagerInterface`, `InstructionManagerInterface`, `ScopeInterface`, `ScopeManagerInterface`, `MemoManagerInterface`, `MemoStoreInterface`, `MemoryMemoStore`, `DatabaseMemoStore`, `SkillManagerInterface`, `AgentContextInterface`, `AgentInterface`, `StreamInterface`, `ChannelInterface`, `AuthorityInterface`, `ApproverInterface`, `AgentRegistryInterface`, `ConversationInterface`, `ConversationManagerInterface`, `ConversationStoreInterface`, `MemoryConversationStore`, `DatabaseConversationStore`, `LedgerInterface`, `LedgerRequestInterface`, `ClassifierInterface`, and `GaugeInterface`. Their readonly data members remain Surface rows. `AgentProvider`, `AgentJudge`, `ThinkSplitter`, `InstructionManager`, `Scope`, `ScopeManager`, `MemoManager`, `SkillManager`, `AgentContext`, `Agent`, `Authority`, `Approver`, `AgentRegistry`, `Conversation`, `ConversationManager`, `JudgmentManager`, `Ledger`, `LedgerRequest`, `Classifier`, and `Gauge` implement their interfaces exactly, so the tables also describe those classes' instance methods. `RelayProvider`, `SystemOneJudge`, and the store classes keep explicit tables because their class names have no same-name interface contract. `MessageManagerInterface` has no separate concrete class here: the active `Conversation` satisfies it structurally. `RelayStream` exposes `response` alone, a data member, so it keeps its Surface row and takes no table. Tool and workspace methods live in their dependency guides.
|
|
1477
1703
|
|
|
1478
1704
|
#### `ProviderInterface`
|
|
1479
1705
|
|
|
@@ -1555,7 +1781,7 @@ The stream-stateful `<think>…</think>` separator a provider routes raw content
|
|
|
1555
1781
|
|
|
1556
1782
|
#### `JudgmentManagerInterface`
|
|
1557
1783
|
|
|
1558
|
-
The conversation's judgment store. `add` stamps each record's `time` and carries batch overloads (one input → one record, a batch → the array), replacing an existing key in place; `remove` carries batch overloads (one key or a list). The `count` data member stays a Surface row.
|
|
1784
|
+
The conversation's judgment store. `add` stamps each record's `time` and carries batch overloads (one input → one record, a batch → the array), replacing an existing key in place; `remove` carries batch overloads (one key or a list). Every record the store returns is the stored record, deep-frozen, so a caller copies a record before changing it. The `count` data member stays a Surface row.
|
|
1559
1785
|
|
|
1560
1786
|
| Method | Returns | Summary |
|
|
1561
1787
|
| ----------- | ---------------------------------- | ------------------------------------------------------------------------------- |
|
|
@@ -1611,15 +1837,73 @@ The id-keyed registry of reusable named scopes. `add` mints + stores a scope (ne
|
|
|
1611
1837
|
| `remove` | `boolean` | Removes one scope by id, or a batch. True if every supplied id was removed; false otherwise. |
|
|
1612
1838
|
| `clear` | `void` | Removes every scope. |
|
|
1613
1839
|
|
|
1840
|
+
#### `MemoManagerInterface`
|
|
1841
|
+
|
|
1842
|
+
The name-keyed memo set a host keeps durable facts in. `add` appends a revision only when the text changed and carries batch overloads; `remove` forgets a memo with its whole history and carries batch overloads. The `id` / `emitter` / `count` / `open` / `close` data members stay Surface rows.
|
|
1843
|
+
|
|
1844
|
+
| Method | Returns | Summary |
|
|
1845
|
+
| ---------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1846
|
+
| `add` | `Memo` / `readonly Memo[]` | Adds one `MemoInput`, or a batch, appending a revision only when the name holds no current revision with the same `description` and `content`. |
|
|
1847
|
+
| `memo` | `Memo \| undefined` | Looks up the current revision of one memo (`undefined` when absent). |
|
|
1848
|
+
| `memos` | `readonly Memo[]` | Lists the current revision of every memo, ordered by each name's first revision. |
|
|
1849
|
+
| `history` | `readonly Memo[]` | Lists every revision of one memo, oldest first. |
|
|
1850
|
+
| `render` | `string` | Renders one memo's index line: the manager-options `render`, else `- name: description`. |
|
|
1851
|
+
| `remove` | `boolean` | Removes one memo and its whole history by name, or a batch. True if every supplied name was removed; false otherwise. |
|
|
1852
|
+
| `clear` | `void` | Removes every memo. |
|
|
1853
|
+
| `snapshot` | `MemoSnapshot` | Returns the memo set as plain data: its `id` and every revision, oldest first. |
|
|
1854
|
+
|
|
1855
|
+
#### `MemoStoreInterface`
|
|
1856
|
+
|
|
1857
|
+
The persistence contract stores a `MemoSnapshot` under its own identity.
|
|
1858
|
+
|
|
1859
|
+
| Method | Returns | Summary |
|
|
1860
|
+
| -------- | ------------------------------------ | ------------------------------------------------------------------------ |
|
|
1861
|
+
| `get` | `Promise<MemoSnapshot \| undefined>` | Resolves the stored snapshot for `id`, or `undefined` if none is stored. |
|
|
1862
|
+
| `set` | `Promise<void>` | Inserts or replaces a snapshot under its own `snapshot.id`. |
|
|
1863
|
+
| `delete` | `Promise<void>` | Drops a snapshot by id; an absent id is a no-op. |
|
|
1864
|
+
|
|
1865
|
+
#### `MemoryMemoStore`
|
|
1866
|
+
|
|
1867
|
+
The in-memory implementation keeps an explicit table because its class name has no same-name interface contract.
|
|
1868
|
+
|
|
1869
|
+
| Method | Returns | Summary |
|
|
1870
|
+
| -------- | ------------------------------------ | ------------------------------------------------------------------------ |
|
|
1871
|
+
| `get` | `Promise<MemoSnapshot \| undefined>` | Resolves the stored snapshot for `id`, or `undefined` if none is stored. |
|
|
1872
|
+
| `set` | `Promise<void>` | Inserts or replaces a snapshot under its own `snapshot.id`. |
|
|
1873
|
+
| `delete` | `Promise<void>` | Drops a snapshot by id; an absent id is a no-op. |
|
|
1874
|
+
|
|
1875
|
+
#### `DatabaseMemoStore`
|
|
1876
|
+
|
|
1877
|
+
The driver-backed implementation keeps an explicit table because its class name has no same-name interface contract.
|
|
1878
|
+
|
|
1879
|
+
| Method | Returns | Summary |
|
|
1880
|
+
| -------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------- |
|
|
1881
|
+
| `get` | `Promise<MemoSnapshot \| undefined>` | Resolves the stored snapshot for `id`, narrowing the opaque JSON column back to a `MemoSnapshot`. |
|
|
1882
|
+
| `set` | `Promise<void>` | Inserts or replaces under the snapshot's own `id` (no separate id param) — the row is `{ id, snapshot }`. |
|
|
1883
|
+
| `delete` | `Promise<void>` | Drops a snapshot by id; an absent id is a no-op (no throw). |
|
|
1884
|
+
|
|
1885
|
+
#### `SkillManagerInterface`
|
|
1886
|
+
|
|
1887
|
+
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.
|
|
1888
|
+
|
|
1889
|
+
| Method | Returns | Summary |
|
|
1890
|
+
| -------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
1891
|
+
| `add` | `Skill` / `readonly Skill[]` | Adds one `SkillInput`, or a batch: mints each `id` and file, and overwrites a same-name skill, last write wins. |
|
|
1892
|
+
| `skill` | `Skill \| undefined` | Looks up one skill by name (`undefined` when absent). |
|
|
1893
|
+
| `skills` | `readonly Skill[]` | Lists every skill, in insertion order. |
|
|
1894
|
+
| `render` | `string` | Renders one skill's index line: the manager-options `render`, else `- name: description`. |
|
|
1895
|
+
| `remove` | `boolean` | Removes one skill by name, or a batch. True if every supplied name was removed; false otherwise. |
|
|
1896
|
+
| `clear` | `void` | Removes every skill. |
|
|
1897
|
+
|
|
1614
1898
|
#### `AgentContextInterface`
|
|
1615
1899
|
|
|
1616
|
-
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` / `messages` / `tools` / `scope` / `workspaces` / `conversations` readonly data members stay Surface rows.
|
|
1900
|
+
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.
|
|
1617
1901
|
|
|
1618
|
-
| Method | Returns | Summary
|
|
1619
|
-
| -------- | --------------------------------- |
|
|
1620
|
-
| `apply` | `void` | Applies the given scope as the active per-turn filter; passing `undefined` explicitly removes filtering.
|
|
1621
|
-
| `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.
|
|
1622
|
-
| `build` | `readonly Message[]` | Builds the provider input for the next turn: a leading `system` message folding the prompt, the scope-filtered instructions (each section's header and each item's rendering resolved through the format cascade),
|
|
1902
|
+
| Method | Returns | Summary |
|
|
1903
|
+
| -------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1904
|
+
| `apply` | `void` | Applies the given scope as the active per-turn filter; passing `undefined` explicitly removes filtering. |
|
|
1905
|
+
| `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. |
|
|
1906
|
+
| `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. |
|
|
1623
1907
|
|
|
1624
1908
|
#### `AgentInterface`
|
|
1625
1909
|
|
|
@@ -1664,18 +1948,28 @@ for await (const value of channel.drain()) {
|
|
|
1664
1948
|
value // 1
|
|
1665
1949
|
}
|
|
1666
1950
|
|
|
1667
|
-
const
|
|
1668
|
-
|
|
1669
|
-
|
|
1951
|
+
const failed = createChannel<number>()
|
|
1952
|
+
failed.push(2)
|
|
1953
|
+
failed.fail(new Error('upstream died')) // the 2 is delivered, then the drain throws
|
|
1670
1954
|
```
|
|
1671
1955
|
|
|
1672
1956
|
#### `AuthorityInterface`
|
|
1673
1957
|
|
|
1674
|
-
The
|
|
1958
|
+
The policy gate the agent loop consults before each tool call. `evaluate` is synchronous; the optional `ask` answers an `ask` verdict asynchronously. It has no data members.
|
|
1959
|
+
|
|
1960
|
+
| Method | Returns | Summary |
|
|
1961
|
+
| ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1962
|
+
| `evaluate` | `AuthorityDecision` | Evaluates one tool call against the ordered rules — returns the first matching rule's verdict, which allows when the rule names none, or the fallback when none match. |
|
|
1963
|
+
| `ask` | `Promise<boolean>` | Resolves `true` to approve one asked call; absent, every ask reads as unanswered. |
|
|
1964
|
+
|
|
1965
|
+
#### `ApproverInterface`
|
|
1966
|
+
|
|
1967
|
+
The server half of a page's approval. Its `ask` is a readonly data member that holds the bound `AuthorityHandler`, so `createAuthority({ rules, ask: approver.ask })` wires it; `frame` reads a waiting ask's `ask` frame for the page, and `answer` settles that ask from the page's `AgentAnswer`.
|
|
1675
1968
|
|
|
1676
|
-
| Method
|
|
1677
|
-
|
|
|
1678
|
-
| `
|
|
1969
|
+
| Method | Returns | Summary |
|
|
1970
|
+
| -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1971
|
+
| `frame` | `AgentFrame \| undefined` | Returns the frame of the call's waiting ask, or `undefined` when none waits; a call framed with no waiting ask is refused when it is asked later. |
|
|
1972
|
+
| `answer` | `boolean` | Settles the waiting ask whose `id` the answer names; only `approved: true` approves. |
|
|
1679
1973
|
|
|
1680
1974
|
#### `AgentRegistryInterface`
|
|
1681
1975
|
|
|
@@ -1734,11 +2028,11 @@ A conversation that owns its live message tail directly (the flat store verbs fo
|
|
|
1734
2028
|
| `reference` | `string` | Renders this conversation as a self-labeled, fenced provenance block to pull into another conversation — a pure string with no model call: a leading `[Reference — conversation "<label>" — NOT part of this conversation]` marker, then the cherry-picked excerpts (`- role: content`) when `messages` is supplied. The `label` option names the source. Default: the `id`. |
|
|
1735
2029
|
| `snapshot` | `ConversationSnapshot` | Serializes this conversation to a plain, JSON-serializable `ConversationSnapshot` — its `id`, the compacted `sections`, and the live tail; the live `summarize` / `keep` are configuration re-supplied on hydrate rather than serialized. |
|
|
1736
2030
|
|
|
1737
|
-
A supplied `sections` cap must satisfy `>= 1`; `NaN` throws `ConversationError` with code `SECTIONS` before a fold starts. A successful capped merge retains at most `Math.ceil(sections)` entries. An absent cap, fractional caps `>= 1`, and positive infinity retain their existing behavior. A supplied `keep` must be a nonnegative safe integer; any other value throws `ConversationError` with code `KEEP`, carrying the value as `context.keep`, before a fold starts. `compact()` calls run one at a time. A `remove` or `clear` during the initial summarizer leaves no section. `CompactOptions.signal` rejects a call with its reason at once and commits nothing after the abort; a fold committed before an aborted overflow merge stays.
|
|
2031
|
+
A supplied `sections` cap must satisfy `>= 1`; `NaN` throws `ConversationError` with code `SECTIONS` before a fold starts. A successful capped merge retains at most `Math.ceil(sections)` entries. An absent cap, fractional caps `>= 1`, and positive infinity retain their existing behavior. A supplied `keep` must be a nonnegative safe integer; any other value throws `ConversationError` with code `KEEP`, carrying the value as `context.keep`, before a fold starts. `compact()` calls run one at a time. A `remove` or `clear` during the initial summarizer leaves no section. `CompactOptions.signal` rejects a call with its reason at once and commits nothing after the abort; a fold committed before an aborted overflow merge stays. A summarizer digest whose trimmed text is empty rejects with `ConversationError` code `SUMMARY`: a fold commits nothing, and a refused overflow merge leaves the appended section.
|
|
1738
2032
|
|
|
1739
2033
|
#### `ConversationManagerInterface`
|
|
1740
2034
|
|
|
1741
|
-
The id-keyed registry of `Conversation` instances with an active pointer. `add(input?)` mints a conversation (flowing the manager's default `summarize` / `keep` in unless the input overrides them) and auto-activates the first one; a later `add` leaves `active` unchanged. `add` forwards the input's `on` hooks and `error` handler to the conversation's emitter, so a throwing listener reports to that handler. `open(id)` returns the conversation registered under `id` while its store read was pending rather than overwriting it, and resolves `undefined` for a stored snapshot whose `id` is not `id`. `switch(id)` re-points `active` (an unknown `id` returns `undefined`, leaving `active` unchanged — lenient, never throws); `remove` carries batch overloads and clears `active` when the removed conversation was active. The `count` and `active` data members stay Surface rows (`active` is a `readonly` accessor — a property, not a method); the manager is event-free (each conversation owns its `emitter`).
|
|
2035
|
+
The id-keyed registry of `Conversation` instances with an active pointer. `add(input?)` mints a conversation (flowing the manager's default `summarize` / `keep` in unless the input overrides them) and auto-activates the first one; a later `add` leaves `active` unchanged. `add` forwards the input's `on` hooks and `error` handler to the conversation's emitter, so a throwing listener reports to that handler. `open(id)` returns the conversation registered under `id` while its store read was pending rather than overwriting it, and resolves `undefined` for a stored snapshot whose `id` is not `id`. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, and the registry and `active` stay unchanged. `switch(id)` re-points `active` (an unknown `id` returns `undefined`, leaving `active` unchanged — lenient, never throws); `remove` carries batch overloads and clears `active` when the removed conversation was active. The `count` and `active` data members stay Surface rows (`active` is a `readonly` accessor — a property, not a method); the manager is event-free (each conversation owns its `emitter`).
|
|
1742
2036
|
|
|
1743
2037
|
| Method | Returns | Summary |
|
|
1744
2038
|
| --------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -1783,16 +2077,17 @@ The driver-backed implementation keeps an explicit table because its class name
|
|
|
1783
2077
|
|
|
1784
2078
|
#### `LedgerInterface`
|
|
1785
2079
|
|
|
1786
|
-
The conversation ledger. The `respond` method serves one request through to its reply,
|
|
2080
|
+
The conversation ledger. The `respond` method serves one request through to its reply, the `calibrate` method measures the price of a prompt, and the `snapshot` method serializes the ledger for a later ledger to hydrate from. The `agent`, `conversation`, and `gauge` data members stay Surface rows. A `respond` or `calibrate` call while either is in flight rejects with `AgentError` code `CONCURRENCY`, and a `snapshot` call while either is in flight throws that error.
|
|
1787
2081
|
|
|
1788
|
-
| Method | Returns | Summary
|
|
1789
|
-
| ----------- | ----------------------- |
|
|
1790
|
-
| `respond` | `Promise<LedgerResult>` | Appends `content` as a user message and serves it through to its reply.
|
|
1791
|
-
| `calibrate` | `Promise<LedgerGauge>` | Measures the gauge, holds it as `gauge`, and returns it.
|
|
2082
|
+
| Method | Returns | Summary |
|
|
2083
|
+
| ----------- | ----------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
2084
|
+
| `respond` | `Promise<LedgerResult>` | Appends `content` as a user message and serves it through to its reply. |
|
|
2085
|
+
| `calibrate` | `Promise<LedgerGauge>` | Measures the gauge, holds it as `gauge`, and returns it. |
|
|
2086
|
+
| `snapshot` | `LedgerSnapshot` | Serializes the conversation, the marked ids, and the gauge into a snapshot a later ledger hydrates from. |
|
|
1792
2087
|
|
|
1793
2088
|
#### `LedgerRequestInterface`
|
|
1794
2089
|
|
|
1795
|
-
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 `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, and `
|
|
2090
|
+
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 `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, and `attempts` data members stay Surface rows.
|
|
1796
2091
|
|
|
1797
2092
|
| Method | Returns | Summary |
|
|
1798
2093
|
| --------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
|
@@ -1802,12 +2097,12 @@ The state of one `respond` call. The ledger creates one request per call and dro
|
|
|
1802
2097
|
| `observe` | `void` | Starts a gauge call in the current pass, making that pass's call in flight final. |
|
|
1803
2098
|
| `spend` | `void` | Adds one call's reported usage to the current pass and records it on the call in flight. |
|
|
1804
2099
|
| `think` | `void` | Records the thinking share of the call in flight, read from the first assistant message after the call's position. |
|
|
1805
|
-
| `file` | `void` | Appends the
|
|
2100
|
+
| `file` | `void` | Appends the attempts of one planning selection and holds its plan when planning succeeded. |
|
|
1806
2101
|
| `admit` | `void` | Admits one tool call of the request, compared by tool name and canonical arguments. |
|
|
1807
2102
|
| `recall` | `void` | Counts one `recall` call, closing the request's recall tool when its recalls reach the limit. |
|
|
1808
2103
|
| `close` | `void` | Closes the request's recall tool, so every later `recall` call throws the closure note. |
|
|
1809
2104
|
| `list` | `void` | Holds the stored first line of each lookup a recall result listed, keyed by its listed line. |
|
|
1810
|
-
| `
|
|
2105
|
+
| `lines` | `ReadonlyMap<string, string> \| undefined` | Returns the stored first lines a recall result listed. |
|
|
1811
2106
|
|
|
1812
2107
|
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 and a recall past its limit:
|
|
1813
2108
|
|
|
@@ -1840,8 +2135,8 @@ request.recall() // throws Error(LEDGER_NOTES.closure) — the 1 recall call is
|
|
|
1840
2135
|
|
|
1841
2136
|
const listed = 'lookup_order {"id":"BW-5512"}: Refund due $148.50.'
|
|
1842
2137
|
request.list(listed, new Map([[listed, 'Order BW-5512 for account BW-20931: Brightwater Studio.']]))
|
|
1843
|
-
request.
|
|
1844
|
-
request.
|
|
2138
|
+
request.lines(listed)?.get(listed) // 'Order BW-5512 for account BW-20931: Brightwater Studio.'
|
|
2139
|
+
request.lines('Refunds over $100 need a manager.') // undefined — no recall returned that text
|
|
1845
2140
|
```
|
|
1846
2141
|
|
|
1847
2142
|
#### `ClassifierInterface`
|
|
@@ -1879,53 +2174,61 @@ These invariants hold across `src/core` ↔ `agent.md`:
|
|
|
1879
2174
|
- **Usage reuses `TokenUsage`.** `ProviderResult.usage` is the [budgets](budget.md) `TokenUsage` shape `{ prompt, completion, total }`, present only when the turn reported it.
|
|
1880
2175
|
- **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.
|
|
1881
2176
|
- **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.
|
|
1882
|
-
- **The message-store contract (`MessageManagerInterface`).** `context.messages`
|
|
1883
|
-
- **The richer turn context (`AgentContext`).** `AgentContext` composes the optional `system` prompt, the `instructions`, `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
|
|
1884
|
-
- **Scope filtering.** A scope holds one three-way allow-list per category (`instructions` 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.
|
|
2177
|
+
- **The message-store contract (`MessageManagerInterface`).** Every `ConversationInterface`, the `context.messages` conversation included, satisfies `MessageManagerInterface` structurally. `add` mints each message's `id`, carries `calls` only when supplied, and returns the stored immutable message that `message(id)` later resolves; `remove` reports `true` only when every supplied id was removed.
|
|
2178
|
+
- **The richer turn context (`AgentContext`).** `AgentContext` composes the optional `system` prompt, the `instructions`, `skills`, `memos`, `workspaces`, and `conversations` managers, `messages`, the `tools` registry, and a readonly active `scope`, creating each omitted manager fresh. `build()` folds the system prompt, the scope-filtered instructions, and the scope-filtered skills index into one leading `system` message, renders the scope-filtered memos index and the active workspace's scope-filtered text files into one `user` context message after it, then appends the active conversation's `view()`, or a passed selection's `messages`. The `system` message holds host-authored text alone. It never reads `tools`, never mutates a manager or a stored message, and builds fresh on each call.
|
|
2179
|
+
- **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.
|
|
1885
2180
|
- **The agent loop (`Agent` / `createAgent`).** `Agent` builds the provider input, then iterates up to `limit`: stream a turn, fold its usage, append any assistant tool calls, and dispatch them. Each `ToolResult` becomes a tool message whose `call` names the paired call, in the reply's call order, because ids can repeat; a string value is the content unchanged, `undefined` is `''`, another value is its `JSON.stringify` text, or `String(value)` when JSON can't carry it, and a failure's content is its `error`. A reply with no tool calls ends the loop.
|
|
1886
2181
|
- **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.
|
|
1887
|
-
- **The `AgentChunk` stream.** `stream().events` yields, per turn, each answer delta as `token`, each reasoning delta as `think`, then optional `usage`, 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.
|
|
2182
|
+
- **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.
|
|
1888
2183
|
- **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.
|
|
1889
|
-
- **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`, `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`.
|
|
2184
|
+
- **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`.
|
|
1890
2185
|
- **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.
|
|
1891
|
-
- **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins, a matched rule allowing unless its `
|
|
1892
|
-
- **A denied call is fed back, never executed.** The loop consults `authority` after scope admits a call, and
|
|
2186
|
+
- **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins, a matched rule allowing unless its `verdict` is `ask` or `deny`, and returns the `fallback` when none match, which defaults to `{ zone: DEFAULT_AUTHORITY_ZONE, verdict: 'allow' }`. `evaluate` is synchronous. `ask(context, decision, signal)` resolves the `ask` option's answer and rejects with an `AgentError` coded `'APPROVER'` when no handler is set. The gate is event-free.
|
|
2187
|
+
- **A denied call is fed back, never executed.** The loop consults `authority`, or a default `Authority` when none is set, after scope admits a call. A call no definition advertises is denied with the scope note before the authority evaluates it, under every verdict, and its `deny` event carries no decision. A `deny` verdict, and an `ask` the approver refuses or leaves unanswered, become the failure arm `{ success: false, id, name, error }` without running the tool. A call that `allow` cleared whose tool is replaced or removed before dispatch is denied too: the model reads the `denied` note of `AUTHORITY_NOTES`, and its `deny` event carries the reason `<name> changed after its decision` and no decision. Executed results and denials merge in the reply's call order, each producing a `tool` chunk and a tool message.
|
|
1893
2188
|
- **Durable, serializable agent jobs (`AgentJobInput` + `AgentRegistry`).** An `AgentJobInput` names its `provider`, `tools`, `authority`, and `scheduler` and carries its data directly, and `AgentRegistry.build(input, signal?)` rehydrates a seeded, signal-wired `Agent` from the named pools. An unknown name throws `AgentError` with code `REGISTRY` and the message `unknown <category>: <name>`.
|
|
1894
2189
|
- **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.
|
|
1895
2190
|
- **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.
|
|
1896
2191
|
- **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.
|
|
1897
2192
|
- **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.
|
|
1898
|
-
- **The context's
|
|
1899
|
-
- **Automatic compaction (the context `window` budget).** With `AgentOptions.window` set and a summarizable
|
|
1900
|
-
- **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
|
|
1901
|
-
- **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, sections, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events. `MemoryConversationStore` keeps snapshots in a map and `DatabaseConversationStore` in one opaque JSON column narrowed by `isConversationSnapshot`, both through `get`, `set`, and `delete`. `open(id)` activates a registry hit or hydrates a store hit, keeps a conversation registered under `id` during the store read, and refuses a snapshot whose `id` is not `id`; `DatabaseConversationStore.get` refuses such a row too. `save(id)` returns `false` when no store or conversation exists.
|
|
1902
|
-
- **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, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a nonnegative safe integer throws `AgentError` with code `LIMIT`.
|
|
1903
|
-
- **Construction-time context wiring.** `AgentOptions.instructions`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
|
|
1904
|
-
- **`strict` — fault escalation.** With `AgentOptions.strict` set, an automatic-compaction summarizer failure and each selection fault emit `fault` and then settle the run `error`; without it, the run continues. A cancel at a select site wins over `strict`, and a manual `conversation.compact()` always propagates its own error.
|
|
1905
|
-
- **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `Math.ceil(sections)` entries after a successful merge; when a fold exceeds it, the oldest sections merge into one through a summarizer call and `collapse` fires. A cap below 1 throws `ConversationError` with code `SECTIONS`, and a `keep` that is not a nonnegative safe integer throws it with code `KEEP`.
|
|
1906
|
-
- **`
|
|
2193
|
+
- **The context's default conversation and a run's conversation.** `context.messages` is the `conversations` registry's active conversation, always defined and read on each access, so it follows `conversations.switch(id)`. A run binds its conversation once, at its `stream()` or `generate()` call: `AgentRunOptions.conversation`, else the active one. The run appends `AgentRunOptions.prompt` to that conversation as a `user` turn after its guards, or reads its request from the conversation's tail when it has no `prompt`, then selects and builds over its `view()`, appends every assistant and tool message to it, and folds it under `window`, so a later `switch`, `open`, `remove`, `clear`, or same-id `add` never moves a live run, and the conversation needs no registration.
|
|
2194
|
+
- **Automatic compaction (the context `window` budget).** With `AgentOptions.window` set and a summarizable run conversation, the loop measures each request it will send, with its messages after the `replay` policy, its advertised tools, and its per-call `options`, against the window before the first provider request and between turns, and compacts and rebuilds when the window is exhausted. A summarizer throw emits `fault` and the run continues over-window unless `strict` is set, and a fold that compacts nothing between turns while over the window stops auto-compaction for the rest of the run. A run whose signal aborted by the end of tool dispatch folds nothing before it settles. When no selection handler runs, and either `window` is absent or the run's conversation has no summarizer, the loop adds no `await` before the first provider request.
|
|
2195
|
+
- **Active workspace rendering by carrier.** `build()` reads only the active workspace, filters its files through `scope.files`, renders text files under `WORKSPACE_SECTION_HEADER` through `renderFencedFile` into one `user` context message with a minted id, which is never stored, and attaches the base64 data of binary `image/` files to a copy of the last user message of the conversation. With no active workspace, or no text file, the context message holds the memos index alone, and with no memos index either, no context message renders.
|
|
2196
|
+
- **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, sections, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events. `MemoryConversationStore` keeps snapshots in a map and `DatabaseConversationStore` in one opaque JSON column narrowed by `isConversationSnapshot`, both through `get`, `set`, and `delete`. `open(id)` activates a registry hit or hydrates a store hit, keeps a conversation registered under `id` during the store read, and refuses a snapshot whose `id` is not `id`; `DatabaseConversationStore.get` refuses such a row too. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, the registry and `active` unchanged. `save(id)` returns `false` when no store or conversation exists. `MemoStoreInterface` is the memo twin: `MemoryMemoStore` and `DatabaseMemoStore` persist a `MemoSnapshot` by its memo set id through `get`, `set`, and `delete`, and the host authors what it stores, because a memo can be model-written and a stored memo set hydrates as written after `isMemoSnapshot` accepts it.
|
|
2197
|
+
- **Limit exhaustion, the three failure layers, and per-run options.** A run that exhausts `limit` while its last turn still requested tools settles `partial: true` and emits `exhaust` instead of `abort`. The loop charges the `allowance` mid-stream from the `estimateTokens` estimate of each turn's content, and charges the cost `budget` the reported usage after each call, net of the estimate only when the `allowance` is the `budget`, or the estimate when the call reported none, a call that failed with a genuine provider error included; it never charges twice. `AgentResult.stop` names the one layer, `meter`, `budget`, or `model`, that stopped the final provider call first. `AgentRunOptions` members override their construction defaults for one run, `conversation` and `prompt` have no construction default, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a nonnegative safe integer throws `AgentError` with code `LIMIT`.
|
|
2198
|
+
- **Construction-time context wiring.** `AgentOptions.instructions`, `skills`, `memos`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
|
|
2199
|
+
- **`strict` — fault escalation.** With `AgentOptions.strict` set, an automatic-compaction summarizer failure and each selection fault emit `fault` and then settle the run `error`; without it, the run continues. A strict run also refuses a request still over the window with `AgentError` `'WINDOW'`, whose message reads `the request measures <consumed> against a window of <max> and this run folds no further`. A cancel at a select site wins over `strict`, and a manual `conversation.compact()` always propagates its own error.
|
|
2200
|
+
- **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `Math.ceil(sections)` entries after a successful merge; when a fold exceeds it, the oldest sections merge into one through a summarizer call and `collapse` fires. A cap below 1 throws `ConversationError` with code `SECTIONS`, and a `keep` that is not a nonnegative safe integer throws it with code `KEEP`. A digest that is not a string or whose trimmed text is empty refuses the fold it would commit with `'SUMMARY'`; such a digest for a capped merge refuses the merge and keeps the fold already committed, one section over the cap, which the next sound merge collapses.
|
|
2201
|
+
- **`cumulative` folds.** `ConversationOptions.cumulative` and `ConversationInput.cumulative` are booleans that default to `false`; the manager holds no default and `CompactOptions` has no member. A cumulative `compact()` makes one summarizer call over the framed recaps of every prior section followed by the eligible live slice with thinking stripped, using the same cut rules and protecting the newest user exchange. After the call settles and the abort check passes, it verifies the slice and the prior sections are unchanged, then replaces all prior sections with one section holding their original messages in order followed by the slice, removes only the slice from the live tail, and emits `compact` once with no `collapse`. A throw, an abort, or a changed input commits nothing, and a fold with no eligible slice makes no call. The originals behind the recaps are never sent to the summarizer, and a hydrated snapshot with several sections folds them all at the next fold that has an eligible slice. Combining `cumulative` with a `sections` cap, whether configured, inherited from a manager, or passed to `compact()`, throws `ConversationError` with code `SECTIONS`.
|
|
2202
|
+
- **The compaction floor on one recording.** The smallest request a fold can leave holds every recap, the exchange that `keep` retains, and the new request. One recorded run reads it: a scripted support-desk conversation, one desk request per goal, on Qwen 3.5 2B `q4_K_M` on Ollama 0.40.13 on 2026-11-02 and 2026-11-03, under `keep: 2`, `strict`, and a window of 11776 tokens with 8192 tokens reserved for output, measured by a study gauge that adds 354 tokens to the estimate. That is the study's configuration and not Agent's defaults. At goal 35 the conversation held 118 folded messages of 182898 characters (median 580, 95th percentile 4913, maximum 5030), 7 recaps of 33822 characters, and 4 live messages of 17925 characters. After eight folds, with recaps of 567 to 1882 tokens summing to 8993, the rebuilt request at goal 36 measured 11940 against 11776, and the run refused it with `AgentError` `'WINDOW'` before any dispatch.
|
|
2203
|
+
|
|
2204
|
+
With `strict` false, the default, no error and no agent event marks that point: the loop sends the over-window request, and no reading covers the provider's behavior past its window. The `consumed` and `exhausted` members of your `window` `Budget` read the last request the loop measured, so read them after a run, or set `strict`.
|
|
2205
|
+
|
|
2206
|
+
From that stop, `compact({ keep: 0 })` frees one request: with a scripted summarizer and the same text, under a gauge overhead of 352, the next request measured 10358 tokens with 9 recaps, the new recap being the recorded 2385 characters. A conversation at `keep: 0` from goal 35, whose fold at goal 36 takes 4 messages and leaves 8 recaps, measured 9750 under that recap and 11139 under a recap of 7942 characters. The sections stay, so each later fold adds a recap against the same window. Only a `sections` cap or `cumulative` lowers that smallest request, and each needs a fold with an eligible slice. At that stop under `keep: 2` the live tail is a user, an assistant, and a user message, so `compact()` folds nothing and a strict retry refuses again; the sections merge at `compact({ keep: 0 })` or at the admission of a later run whose new prompt leaves an eligible slice. The two can't combine. `cumulative` has no per-call form, so it needs a conversation rebuilt from `snapshot()` with `ConversationInput.cumulative`. A host that reserves less output can set a larger `max` on the same model.
|
|
2207
|
+
|
|
2208
|
+
Beside that stop, `cumulative` has a reading and no recommendation. 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 run 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 run 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`.
|
|
2209
|
+
|
|
1907
2210
|
- **`sanitizeUsage`.** `sanitizeToken` turns a non-finite or non-positive count into `0` and floors a positive fraction, and `sanitizeUsage` applies it to each field. The loop sanitizes a provider's usage and an abort partial's usage before charging or folding it.
|
|
1908
|
-
- **`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;
|
|
2211
|
+
- **`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`.
|
|
1909
2212
|
- **`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.
|
|
1910
2213
|
- **The provider engine's request and stream.** The engine posts `JSON.stringify(encode(request))` to `url + (path ?? '')` with a JSON content type the `headers` hook can extend, decodes the body through `readChunks`, and feeds every framed record and the `finish` tail through `read`. A record whose `read` returns a `result` ends the call with that result, and with `strict: true` a stream that ends with no settled result throws `ProviderError` with code `PROTOCOL`. A non-OK body is read through `readBodyText` to at most `MAX_ERROR_BODY_LENGTH` bytes and its remainder cancelled, and each reader releases its lock on every exit.
|
|
1911
2214
|
- **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.
|
|
1912
|
-
- **The relay protocol (`createRelay` / `RelayStream` / `RelayProvider`).** The request is a `POST` of one `providerRequestContract` document, and the response is newline-delimited `RelayFrame` records under `RELAY_CONTENT_TYPE`, written under backpressure, with every upstream failure reduced to `RELAY_PROVIDER_MESSAGE`. `authorize` is mandatory and runs before the body is read; the handler answers `401`, `413` at the byte `limit`, `400`, or `502` with no body, and the browser receives each as a `ProviderError` with code `HTTP`. An inbound abort, a client disconnecting included, cancels the upstream turn.
|
|
2215
|
+
- **The relay protocol (`createRelay` / `RelayStream` / `RelayProvider`).** The request is a `POST` of one `providerRequestContract` document, and the response is newline-delimited `RelayFrame` records under `RELAY_CONTENT_TYPE`, written under backpressure, with every upstream failure reduced to `RELAY_PROVIDER_MESSAGE`. `authorize` is mandatory and runs before the body is read; the handler answers `401`, `413` at the byte `limit`, `400`, or `502` with no body, or `422` with one `text/plain` line per page `system` message or tool definition its policy refuses, and the browser receives each as a `ProviderError` with code `HTTP`. An inbound abort, a client disconnecting included, cancels the upstream turn.
|
|
1913
2216
|
- **`ProviderError` and its codes.** `ProviderError` carries a `code` and, for `HTTP` alone, a `status`: `HTTP` reports a non-OK response as `provider error: <status>` with ` - <excerpt>` only when the error body had text, `PROTOCOL` a missing body, a refused record, or a `strict` stream with no settled result, and `PROVIDER` a relay `error` frame. A cancel throws `ProviderAbortError`, never `ProviderError`.
|
|
1914
2217
|
- **The judge boundary (`JudgeInterface`).** `JudgeInterface` is the sibling of `ProviderInterface` and never a provider: `ask(request, signal)` answers each question of a `JudgeRequest` about its one `state`, keyed by caller ids the prompt never carries. An id appears in `answers` or in `refusals`, never both, `refusals` is absent when nothing was refused, and a `Refusal` invents no probability.
|
|
1915
|
-
- **The stored distribution and the derived
|
|
2218
|
+
- **The stored distribution and the derived measure (`measureAnswer`).** An answer stores only its distribution, and `measureAnswer` derives the `AnswerMeasure`: `winner` is the first strictly greatest candidate in enumeration order, so a noul of exactly 0.5 names `'false'`, and `probability` is the winner's. `confidence` is `(max(p) - 1/n) / (1 - 1/n)` for a choice, `|2p - 1|` for a noul, and for a score one minus the probability-weighted distance from the winning level over the mean distance from the middle level, floored at 0, and `score`, the expected level `sum(i * p_i)`, is set for a score answer alone. A choice or score with fewer than 2 candidates throws `JudgeError` with code `PROTOCOL`.
|
|
1916
2219
|
- **The protocol's null and the absence law.** An undescribed choice option or score level stays `null`, because JSON carries no `undefined` member and a level is positional, while `instructions`, `NoulCriteria`, and each noul side are omitted when absent and `isJudgeQuestion` refuses a `null` there. The System One wire sends an omitted member omitted and a `null` criterion as `null`.
|
|
1917
2220
|
- **Validation before inference and the server's limits.** `ask` refuses an invalid `state`, an empty question map, or a question `isJudgeQuestion` rejects with `JudgeError` code `QUESTION` before any call, and a wire can refuse its own limits the same way. A server refusal throws code `HTTP` with the response `status` and the message `judge error: <status>`, plus ` - <excerpt>` read from at most `MAX_ERROR_BODY_LENGTH` bytes when the body has text, and a `null` or non-JSON success body throws code `PROTOCOL`.
|
|
1918
2221
|
- **Each call's own deadline, and the abort partial (`JudgeAbortError`).** Each call runs under a `Timeout` of `AgentJudgeInput.timeout` milliseconds (`DEFAULT_PROVIDER_TIMEOUT` when omitted) folded with the caller's signal, covering the `headers` hook, the transport, both body reads, and `read`. A cancel throws `JudgeAbortError` whose `partial` merges the answers, refusals, and usage of the completed calls, with a throw that raced the cancel as its `cause`. A cancel that lands while `read` decodes the answer is reported with no `cause`, and that call's answer is left out of the `partial`.
|
|
1919
2222
|
- **The batch switch and the merge (`buildJudgeResult`).** `AgentJudgeInput.batch` (default `true`) sends every question in one call, and `false` sends one call per question in key order with the shared `state`, every body built before the first call. `buildJudgeResult` joins answers and refusals by id, sums each call's sanitized usage, and takes `model` from the first call, or the configured `model` when no call completed.
|
|
1920
|
-
- **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 `
|
|
2223
|
+
- **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.
|
|
1921
2224
|
- **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.
|
|
1922
2225
|
- **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.
|
|
1923
2226
|
- **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.
|
|
1924
|
-
- **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
|
|
1925
|
-
- **Selection faults.** A thrown handler, a returned `fault`,
|
|
2227
|
+
- **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.
|
|
2228
|
+
- **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.
|
|
1926
2229
|
- **Selection cost.** Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`, with no `usage` chunk or `usage` event.
|
|
1927
|
-
- **Judgments.** A conversation's `judgments` store keys each record by the caller's question id, last write wins in place, stamps `time` on `add`,
|
|
1928
|
-
- **Judgments in a snapshot.** A snapshot carries `judgments` only while the store holds one, and a snapshot without the member validates and restores.
|
|
2230
|
+
- **Judgments.** A conversation's `judgments` store keys each record by the caller's question id, last write wins in place, stamps `time` on `add`, attaches `usage` only for a one-question request, and returns each record deep-frozen. `resolve` reuses each record whose question JSON value, ordered sources, rendered state, and configured judge `model` match, asks once for the rest, and keeps the completed records when a cancel interrupts it.
|
|
2231
|
+
- **Judgments in a snapshot.** A snapshot carries `judgments` only while the store holds one, and a snapshot without the member validates and restores. Its judgments are the stored frozen records, so copy one before you edit it, and hydrating takes an owned frozen copy. A judgment whose `usage` member is present with the value `undefined` is refused, so omit the member from an in-memory snapshot. `isJudgment` and `isMemo` are guard constants, so each reads an empty `.name`.
|
|
1929
2232
|
|
|
1930
2233
|
## Patterns
|
|
1931
2234
|
|
|
@@ -2000,10 +2303,10 @@ That provider drives the whole runtime unchanged — `createAgent`, the tool loo
|
|
|
2000
2303
|
|
|
2001
2304
|
### Asking a System One server a choice, a noul, and a score
|
|
2002
2305
|
|
|
2003
|
-
Ask every question about one state in one request, and read each answer with the `
|
|
2306
|
+
Ask every question about one state in one request, and read each answer with the `measureAnswer` function. The `SystemOneJudge` class speaks the System One decision protocol. Its wire was recorded against Ollama 0.40.0 serving the `tev1:0.8b` model on 2026-10-07. It also accepts a score's `probabilities` and `legend` as an array, and it drops the measures a server adds beside the distribution. Point the `url` option at the server origin; the wire appends the `SYSTEM_ONE_PATH` constant and fills the request's `model` member from the judge's configured model.
|
|
2004
2307
|
|
|
2005
2308
|
```ts
|
|
2006
|
-
import {
|
|
2309
|
+
import { measureAnswer, createSystemOneJudge } from '@orkestrel/agent'
|
|
2007
2310
|
|
|
2008
2311
|
const judge = createSystemOneJudge({ url: 'http://localhost:11434', model: 'tev1:0.8b' })
|
|
2009
2312
|
const result = await judge.ask(
|
|
@@ -2032,17 +2335,17 @@ const result = await judge.ask(
|
|
|
2032
2335
|
},
|
|
2033
2336
|
AbortSignal.timeout(30_000),
|
|
2034
2337
|
)
|
|
2035
|
-
const
|
|
2036
|
-
Object.entries(result.answers).map(([id, answer]) => [id,
|
|
2338
|
+
const measures = Object.fromEntries(
|
|
2339
|
+
Object.entries(result.answers).map(([id, answer]) => [id, measureAnswer(answer)]),
|
|
2037
2340
|
)
|
|
2038
2341
|
result.model // 'tev1:0.8b' — the model the server named
|
|
2039
2342
|
result.usage // { prompt: 975, completion: 4, total: 979 }
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2343
|
+
measures.label // { winner: 'bug', probability: 0.9691, confidence: 0.9536 } to 4 decimals
|
|
2344
|
+
measures.refund // { winner: 'true', probability: 0.9979, confidence: 0.9958 } to 4 decimals
|
|
2345
|
+
measures.severity // { winner: '1', probability: 0.9494, confidence: 0.9241, score: 0.9919 } to 4 decimals
|
|
2043
2346
|
```
|
|
2044
2347
|
|
|
2045
|
-
The values in the comments are the
|
|
2348
|
+
The values in the comments are the measures of the response Ollama 0.40.0 returned for this request on 2026-10-07. That same response carried the server's own measures, and the wire drops them: a `confidence` of 0.8718 for `label` and 0.7864 for `severity`, where the published formulas read 0.9536 and 0.9241. A server's own measures can follow other formulas, while the stored `probabilities` and `noul` mean the same on every server, so the `measureAnswer` function derives each measure locally and every server reads on one scale. A `choice` member repeats the most likely option and a `legend` member repeats the question's criteria, so the wire drops both as well (the System One wire clause).
|
|
2046
2349
|
|
|
2047
2350
|
A server that takes a key receives it through the `headers` hook, which each call awaits inside its own deadline (the header-hook authentication clause). TypeSafe Jev takes a bearer key:
|
|
2048
2351
|
|
|
@@ -2094,15 +2397,67 @@ const judge = new YesJudge({
|
|
|
2094
2397
|
|
|
2095
2398
|
That judge answers through `ask` like any other. With `batch: false` the engine makes one call per question in key order, each carrying the shared `state` and one question, and merges their answers into one `JudgeResult`. Throw `JudgeError` with code `PROTOCOL` from `read` for a response the wire can't read; the engine passes it to the caller unchanged. Throw `JudgeError` with code `QUESTION` from `encode` for a question the protocol can't carry; the engine builds every body before the first call, so that refusal lands before any inference. A wire that reads candidates out of a model's own output and can't find one returns a `Refusal` under `refusals`, listing the caller's keys it couldn't read, instead of inventing a probability.
|
|
2096
2399
|
|
|
2400
|
+
### The request layout
|
|
2401
|
+
|
|
2402
|
+
Every configuration sends one request layout, position by position. The following table lists what fills each position under each strategy:
|
|
2403
|
+
|
|
2404
|
+
| Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
|
|
2405
|
+
| ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2406
|
+
| `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 |
|
|
2407
|
+
| `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 |
|
|
2408
|
+
| 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 |
|
|
2409
|
+
| Request | the last stored `user` message; images attach here | the same | a built copy of the `user` turn: `## Records`, `## Rules`, and `## Request` before the prompt, or the prompt alone when nothing renders; images attach here |
|
|
2410
|
+
| Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
|
|
2411
|
+
|
|
2412
|
+
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.
|
|
2413
|
+
|
|
2414
|
+
### Serving one agent per principal
|
|
2415
|
+
|
|
2416
|
+
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:
|
|
2417
|
+
|
|
2418
|
+
- **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.
|
|
2419
|
+
- **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.
|
|
2420
|
+
- **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`.
|
|
2421
|
+
- **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.
|
|
2422
|
+
- **The kept tail.** A run that rejects, aborts, or times out before any assistant append leaves the user turn as the thread's tail; the next request carries it unanswered directly before the new turn, so the model might answer it or call tools for it, and a call the authority allows outright runs without asking. An application that wants a cancelled ask withdrawn removes the thread's tail after the run settles while that tail is still a `user` turn whose `content` equals the prompt it sent.
|
|
2423
|
+
- **The store keyed by principal.** `open` and `save` key a snapshot by conversation id alone, so key any durable conversation store by principal, and key a memo set's `id` the same way.
|
|
2424
|
+
- **An orphaned instance.** A run stays bound to the conversation instance it named, so a `remove`, `clear`, or same-id `add` leaves that instance live and appended to while the registry holds another. Open each thread once, because the concurrency guard compares instances and two values opened from one stored snapshot both run on an agent with no `window` and distinct budgets. The application owns the session entry's lifetime and eviction.
|
|
2425
|
+
|
|
2426
|
+
### Who writes and who enforces each inlet
|
|
2427
|
+
|
|
2428
|
+
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:
|
|
2429
|
+
|
|
2430
|
+
| Inlet | Node alone | Page alone | Page to Node relay | Page to Node agent |
|
|
2431
|
+
| ----------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
2432
|
+
| 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 |
|
|
2433
|
+
| 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` |
|
|
2434
|
+
| 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 |
|
|
2435
|
+
| 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 |
|
|
2436
|
+
| 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 |
|
|
2437
|
+
| 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 |
|
|
2438
|
+
|
|
2439
|
+
The following rules complete the table:
|
|
2440
|
+
|
|
2441
|
+
- The thread id is bound to the principal: look it up only in that principal's registry, and key any durable conversation store by principal as well, because `open` and `save` key snapshots by conversation id alone.
|
|
2442
|
+
- Host a memo set per principal: key a memo set's `id` by principal, as a conversation store is keyed.
|
|
2443
|
+
- 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.
|
|
2444
|
+
- Accept `{ role: 'user', content }` only from a client, through `agentPromptContract`. Read client history and client snapshots as untrusted input.
|
|
2445
|
+
- 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.
|
|
2446
|
+
- A `deny` `reason` reaches the model verbatim, so the host authors every rule reason.
|
|
2447
|
+
- 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/).
|
|
2448
|
+
- [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.
|
|
2449
|
+
- A page `Ledger` stays responsive only with `agent: { scheduler: createBrowserScheduler() }`, as **The filing.** states.
|
|
2450
|
+
- Core and its dependencies call `Map.groupBy`, `AbortSignal.any`, `Promise.withResolvers`, and `Iterator.from` and ship no polyfill, so a page needs a browser that provides them, in a secure context for `crypto.randomUUID`. A server needs Node 22.18.0 or later.
|
|
2451
|
+
|
|
2097
2452
|
### Relaying a browser provider through your own server
|
|
2098
2453
|
|
|
2099
|
-
When you compose `createAgent(browser, { tools })` in the page, the agent dispatches page tools there after the Node provider returns a tool call. The Node server runs the relay handler and upstream inference. See [Placement proofs](#placement-proofs) for the planned Chromium receipt; the executed transcription described next proves an HTTP hop in Node.
|
|
2454
|
+
When you compose `createAgent(browser, { tools })` in the page, the agent dispatches page tools there after the Node provider returns a tool call, for the definitions the relay forwards: those the server declares in `tools.definitions` or `tools.accept` admits. The Node server runs the relay handler and upstream inference. See [Placement proofs](#placement-proofs) for the planned Chromium receipt; the executed transcription described next proves an HTTP hop in Node.
|
|
2100
2455
|
|
|
2101
2456
|
A browser must never hold a model credential. Mount `createRelay` on your own server, where the credential already lives, and give the browser `createRelayProvider` pointed at that route: the browser drives a `ProviderInterface` like any other, and the credential never leaves the server. The handler is a plain `(request: Request) => Promise<Response>`, so any fetch-standard router mounts it — this composition mounts it on an `@orkestrel/router` dispatcher. Each half that follows runs in its own process: copy the server half into your server and the browser half into your browser bundle.
|
|
2102
2457
|
|
|
2103
|
-
The `@orkestrel/agent` package
|
|
2458
|
+
The `@orkestrel/agent` package frames the relay's newline-delimited JSON through its `@orkestrel/ndjson` dependency and declares no runtime dependency on a router or on a server adapter, which the server application supplies. The `@orkestrel/router` and `@orkestrel/server` development dependencies this package declares serve the executed transcription of these fences (see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts)). That transcription runs the server half and the browser half for real: it mounts the relay handler on the dispatcher route the server half declares, starts `@orkestrel/server` on a loopback listener, and drives the browser half against that listener over an HTTP hop in Node. The hop proves the round trip returning the upstream's settled result, the `405` with its `Allow: POST` header a `GET` to `/relay` answers, the `404` a `POST` to another path answers, the `401` a wrong bearer answers with the upstream provider unentered, and the upstream turn a disconnected reader cancels through the adapter's abort of the inbound request.
|
|
2104
2459
|
|
|
2105
|
-
The transcription substitutes where a test process differs from a deployment. The fence's `declare` placeholders become a scripted upstream provider and a fictional bearer, and the `messages` binding is typed as `readonly Message[]` rather than narrowed with `as const`. It
|
|
2460
|
+
The transcription substitutes where a test process differs from a deployment. The fence's `declare` placeholders become a scripted upstream provider and a fictional bearer, and the `messages` binding is typed as `readonly Message[]` rather than narrowed with `as const`. It drives the browser half's default strict parser through the HTTP hop. The parser retains incomplete records across chunks, accepts LF and CRLF record terminators, ignores blank lines, and trims each line before it parses it, so a line inside the stream wrapped in a byte-order mark or a no-break space parses, and the decoder removes a byte-order mark at the start of the stream before the parser reads it. A malformed or non-object line rejects the call with a `ProviderError` with code `PROTOCOL` whose `cause` is the `NDJSONError`. Each provider call receives a fresh parser; `clear()` discards any buffered fragment. It adds `host: '127.0.0.1'` to the `createServer` call, because a test listener binds loopback where a deployed server binds every interface. It points the browser half's `url` option at that address and the port `await server.start()` resolved, in place of the fence's fixed public URL. It closes each case with `await server.stop()` — the fence's own call — rather than the `SIGTERM` listener, which a test process outlives. The byte-limit refusal stays a direct handler call. The `limit` option of the `createRelay` factory caps the body the relay reads, and the `limit` option of the `createServer` factory caps the `body()` read a middleware context makes. This composition registers no middleware, so the `limit` option of the `createServer` factory never applies to these bytes.
|
|
2106
2461
|
|
|
2107
2462
|
#### Mounting the relay on your server
|
|
2108
2463
|
|
|
@@ -2137,29 +2492,9 @@ The `serve` function is the entry a server runtime's adapter calls, and the adap
|
|
|
2137
2492
|
#### Reaching the relay from the browser
|
|
2138
2493
|
|
|
2139
2494
|
```ts
|
|
2140
|
-
import type { ProviderInterface
|
|
2141
|
-
import { createRelayProvider
|
|
2495
|
+
import type { ProviderInterface } from '@orkestrel/agent'
|
|
2496
|
+
import { createRelayProvider } from '@orkestrel/agent'
|
|
2142
2497
|
import { createAbort } from '@orkestrel/abort'
|
|
2143
|
-
import { isRecord, parseJSONAs } from '@orkestrel/contract'
|
|
2144
|
-
|
|
2145
|
-
class RelayFrameParser implements ProviderParserInterface {
|
|
2146
|
-
#pending = ''
|
|
2147
|
-
parse(chunk: string): ReadonlyArray<Readonly<Record<string, unknown>>> {
|
|
2148
|
-
this.#pending += chunk
|
|
2149
|
-
const lines = this.#pending.split(/\r\n|\n/)
|
|
2150
|
-
this.#pending = lines.pop() ?? ''
|
|
2151
|
-
return lines
|
|
2152
|
-
.filter((line) => line.trim().length > 0)
|
|
2153
|
-
.map((line) => {
|
|
2154
|
-
const record = parseJSONAs(line, isRecord)
|
|
2155
|
-
if (record === undefined) throw new ProviderError('PROTOCOL', 'invalid JSON record')
|
|
2156
|
-
return record
|
|
2157
|
-
})
|
|
2158
|
-
}
|
|
2159
|
-
clear(): void {
|
|
2160
|
-
this.#pending = ''
|
|
2161
|
-
}
|
|
2162
|
-
}
|
|
2163
2498
|
|
|
2164
2499
|
declare const bearer: string
|
|
2165
2500
|
const abort = createAbort()
|
|
@@ -2167,13 +2502,255 @@ const messages = [{ id: '1', role: 'user', content: 'Say hello.' }] as const
|
|
|
2167
2502
|
|
|
2168
2503
|
const browser: ProviderInterface = createRelayProvider({
|
|
2169
2504
|
url: 'https://app.example/relay',
|
|
2170
|
-
parser: () => new RelayFrameParser(),
|
|
2171
2505
|
headers: () => ({ authorization: `Bearer ${bearer}` }),
|
|
2172
2506
|
})
|
|
2173
2507
|
const result = await browser.generate(messages, abort.signal) // a ProviderResult like a local provider's
|
|
2174
2508
|
```
|
|
2175
2509
|
|
|
2176
|
-
`authorize` is mandatory and carries obligations the mechanism deliberately doesn't assume for you: it must not read the request body, and it performs no origin or method check of its own, so an application that authorizes on an ambient credential such as a cookie composes origin and CSRF middleware in front of the handler. A bearer header the browser sets explicitly, as here, isn't reachable cross-site. Every refusal — `401` for a failed authorization, `413` for a body that reaches the byte limit, `400` for a missing, unreadable, or rejected body, `502` for an upstream call that can't be constructed — arrives at the browser as a `ProviderError` with code `'HTTP'` and that status. The `401`, `400`, and `413` refusals leave the upstream provider unentered; the `502` is answered after `provider.stream` was entered and threw before returning its iterator, so that refusal has already reached the provider. An upstream failure that does happen mid-stream reaches the browser as the fixed `RELAY_PROVIDER_MESSAGE` text, never the upstream's own message (the relay-protocol clause).
|
|
2510
|
+
`authorize` is mandatory and carries obligations the mechanism deliberately doesn't assume for you: it must not read the request body, and it performs no origin or method check of its own, so an application that authorizes on an ambient credential such as a cookie composes origin and CSRF middleware in front of the handler. A bearer header the browser sets explicitly, as here, isn't reachable cross-site. Every refusal — `401` for a failed authorization, `413` for a body that reaches the byte limit, `400` for a missing, unreadable, or rejected body, `422` for a page `system` message or tool definition the relay's policy refuses, `502` for an upstream call that can't be constructed — arrives at the browser as a `ProviderError` with code `'HTTP'` and that status. The `401`, `400`, and `413` refusals leave the upstream provider unentered; the `502` is answered after `provider.stream` was entered and threw before returning its iterator, so that refusal has already reached the provider. An upstream failure that does happen mid-stream reaches the browser as the fixed `RELAY_PROVIDER_MESSAGE` text, never the upstream's own message (the relay-protocol clause).
|
|
2511
|
+
|
|
2512
|
+
The relay forwards the page's options (`think`, `schema`) and its history upstream under the operator's credential; the page chooses them, and Agent 0.0.35 applies no operator policy over them. [Serving one agent per principal](#serving-one-agent-per-principal) holds the session rules when the agent itself runs in Node, and [Who writes and who enforces each inlet](#who-writes-and-who-enforces-each-inlet) names each side of the hop.
|
|
2513
|
+
|
|
2514
|
+
#### Declaring page tools and server text
|
|
2515
|
+
|
|
2516
|
+
By default `createRelay` answers `422` for a page `system` message and for a tool definition the server did not declare, so declare the page's tools and set the server's text. Keep the definitions in a data-only module that both halves import, so the server never imports a page handler:
|
|
2517
|
+
|
|
2518
|
+
```ts
|
|
2519
|
+
// shared.ts: data only, imported by the page and by the server.
|
|
2520
|
+
import type { ToolDefinition } from '@orkestrel/tool'
|
|
2521
|
+
|
|
2522
|
+
export const PAGE_TOOLS: readonly ToolDefinition[] = [
|
|
2523
|
+
{
|
|
2524
|
+
name: 'read_selection',
|
|
2525
|
+
description: 'Read the text the user selected on the page.',
|
|
2526
|
+
parameters: { type: 'object', properties: {} },
|
|
2527
|
+
},
|
|
2528
|
+
]
|
|
2529
|
+
```
|
|
2530
|
+
|
|
2531
|
+
The page binds a handler to each definition and sets no `system` text, because the server writes it:
|
|
2532
|
+
|
|
2533
|
+
```ts
|
|
2534
|
+
import { createAgent, createRelayProvider } from '@orkestrel/agent'
|
|
2535
|
+
import { createTool, createToolManager } from '@orkestrel/tool'
|
|
2536
|
+
|
|
2537
|
+
// PAGE_TOOLS comes from the shared module, and `readSelection` from the page.
|
|
2538
|
+
declare function readSelection(): string
|
|
2539
|
+
const tools = createToolManager()
|
|
2540
|
+
tools.add(
|
|
2541
|
+
PAGE_TOOLS.map((definition) => createTool({ ...definition, execute: () => readSelection() })),
|
|
2542
|
+
)
|
|
2543
|
+
const browser = createRelayProvider({ url: 'https://app.example/relay' })
|
|
2544
|
+
const agent = createAgent(browser, { tools })
|
|
2545
|
+
```
|
|
2546
|
+
|
|
2547
|
+
The server mounts the same definitions beside its own text:
|
|
2548
|
+
|
|
2549
|
+
```ts
|
|
2550
|
+
import type { ProviderInterface } from '@orkestrel/agent'
|
|
2551
|
+
import { createRelay } from '@orkestrel/agent'
|
|
2552
|
+
|
|
2553
|
+
// PAGE_TOOLS comes from the shared module.
|
|
2554
|
+
declare const upstream: ProviderInterface
|
|
2555
|
+
declare function authorize(request: Request): boolean
|
|
2556
|
+
const handler = createRelay({
|
|
2557
|
+
provider: upstream,
|
|
2558
|
+
authorize,
|
|
2559
|
+
system: { text: 'You help on the Larkspur order page.' },
|
|
2560
|
+
tools: { definitions: PAGE_TOOLS },
|
|
2561
|
+
})
|
|
2562
|
+
```
|
|
2563
|
+
|
|
2564
|
+
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.
|
|
2565
|
+
|
|
2566
|
+
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 }`.
|
|
2567
|
+
|
|
2568
|
+
### Serving a Node agent to a page
|
|
2569
|
+
|
|
2570
|
+
When the agent, its provider, its tools, and its approver run in Node and a page drives them, the page sends an `AgentPrompt` to a frame route, reads the run back as newline-delimited `AgentFrame` values, and answers each `ask` frame with an `AgentAnswer` to an answer route. The route owns identity, the session table of one `{ agent, threads, approver }` entry per authenticated principal, statuses, and timeouts, and looks a thread id up only in the principal's own `threads`. Both routes compose the origin and CSRF checks before they read the body, because under an ambient credential such as a cookie a cross-site simple `POST` would otherwise append a stored user turn to the principal's thread and run that principal's agent. The frame route passes the narrowed body as the run's `prompt`, which the run appends after its guards, so a refused run appends nothing and nothing removes the user turn after the run starts.
|
|
2571
|
+
|
|
2572
|
+
[Serving one agent per principal](#serving-one-agent-per-principal) holds what this session table shares and refuses. Here the frame route answers `AgentError` `'CONCURRENCY'` with `409`, passes `signal: request.signal`, and calls `stream.abort()` from its `cancel` when the page stops reading.
|
|
2573
|
+
|
|
2574
|
+
`ask: approver.ask` wires the approver directly. A host handler that wraps it must pass the received `context` unchanged and synchronously to the approver, which keys each waiting ask by the call object. A handler that redacts or copies the call gets no frame and waits until the run `timeout`, when one is set, or until the page disconnects and the route's `cancel` aborts the run, because the frame carries the call's own arguments and no server-written redaction.
|
|
2575
|
+
|
|
2576
|
+
The kept tail under [Serving one agent per principal](#serving-one-agent-per-principal) applies to a run this route rejects, aborts, or times out.
|
|
2577
|
+
|
|
2578
|
+
The following server fence fills the session table and mounts the frame route and the answer route:
|
|
2579
|
+
|
|
2580
|
+
```ts
|
|
2581
|
+
import type {
|
|
2582
|
+
AgentInterface,
|
|
2583
|
+
ApproverInterface,
|
|
2584
|
+
AuthorityRule,
|
|
2585
|
+
ConversationManagerInterface,
|
|
2586
|
+
ProviderInterface,
|
|
2587
|
+
} from '@orkestrel/agent'
|
|
2588
|
+
import {
|
|
2589
|
+
agentAnswerContract,
|
|
2590
|
+
agentPromptContract,
|
|
2591
|
+
agentStreamToFrames,
|
|
2592
|
+
createAgent,
|
|
2593
|
+
createApprover,
|
|
2594
|
+
createAuthority,
|
|
2595
|
+
createConversationManager,
|
|
2596
|
+
isAgentError,
|
|
2597
|
+
} from '@orkestrel/agent'
|
|
2598
|
+
import { parseJSONAs } from '@orkestrel/contract'
|
|
2599
|
+
import { createDispatcher } from '@orkestrel/router'
|
|
2600
|
+
import { createServer } from '@orkestrel/server'
|
|
2601
|
+
import type { ToolManagerInterface } from '@orkestrel/tool'
|
|
2602
|
+
|
|
2603
|
+
declare const provider: ProviderInterface // the server-side provider every principal shares
|
|
2604
|
+
declare const tools: ToolManagerInterface // the server-side tools every principal shares
|
|
2605
|
+
declare const rules: readonly AuthorityRule[] // the host's policy, an `ask` verdict included
|
|
2606
|
+
declare function authenticate(request: Request): string | undefined // the session's principal
|
|
2607
|
+
declare function verify(request: Request): boolean // the origin and CSRF checks
|
|
2608
|
+
|
|
2609
|
+
interface PageSession {
|
|
2610
|
+
readonly agent: AgentInterface
|
|
2611
|
+
readonly threads: ConversationManagerInterface
|
|
2612
|
+
readonly approver: ApproverInterface
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
// The session table: one entry per authenticated principal, filled before any request.
|
|
2616
|
+
const sessions = new Map<string, PageSession>()
|
|
2617
|
+
for (const principal of ['ada', 'grace']) {
|
|
2618
|
+
// Each entry owns its threads, approver, and agent; none is shared across principals.
|
|
2619
|
+
const threads = createConversationManager()
|
|
2620
|
+
const approver = createApprover()
|
|
2621
|
+
const agent = createAgent(provider, {
|
|
2622
|
+
tools,
|
|
2623
|
+
conversations: threads,
|
|
2624
|
+
authority: createAuthority({ rules, ask: approver.ask }),
|
|
2625
|
+
})
|
|
2626
|
+
sessions.set(principal, { agent, threads, approver })
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
const dispatcher = createDispatcher({
|
|
2630
|
+
routes: [
|
|
2631
|
+
{
|
|
2632
|
+
method: 'POST',
|
|
2633
|
+
path: '/threads/:thread',
|
|
2634
|
+
handler: async (request, context) => {
|
|
2635
|
+
const principal = authenticate(request)
|
|
2636
|
+
const session = principal === undefined ? undefined : sessions.get(principal)
|
|
2637
|
+
if (session === undefined) return new Response(null, { status: 401 })
|
|
2638
|
+
if (!verify(request)) return new Response(null, { status: 403 })
|
|
2639
|
+
const prompt = parseJSONAs(await request.text(), agentPromptContract.is)
|
|
2640
|
+
const id = context.params.thread
|
|
2641
|
+
if (prompt === undefined || id === undefined) {
|
|
2642
|
+
return new Response(null, { status: 400 })
|
|
2643
|
+
}
|
|
2644
|
+
const thread = session.threads.conversation(id) ?? session.threads.add({ id })
|
|
2645
|
+
try {
|
|
2646
|
+
// The run appends the prompt after its guards, so a refused run adds no turn.
|
|
2647
|
+
const stream = session.agent.stream({
|
|
2648
|
+
conversation: thread,
|
|
2649
|
+
prompt,
|
|
2650
|
+
signal: request.signal,
|
|
2651
|
+
})
|
|
2652
|
+
const frames = agentStreamToFrames(stream, session.approver)
|
|
2653
|
+
const lines = new ReadableStream<string>({
|
|
2654
|
+
pull: async (controller) => {
|
|
2655
|
+
const step = await frames.next()
|
|
2656
|
+
if (step.done) controller.close()
|
|
2657
|
+
else controller.enqueue(`${JSON.stringify(step.value)}\n`)
|
|
2658
|
+
},
|
|
2659
|
+
cancel: () => stream.abort(),
|
|
2660
|
+
})
|
|
2661
|
+
return new Response(lines.pipeThrough(new TextEncoderStream()), {
|
|
2662
|
+
headers: {
|
|
2663
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
2664
|
+
'cache-control': 'no-store',
|
|
2665
|
+
},
|
|
2666
|
+
})
|
|
2667
|
+
} catch (error) {
|
|
2668
|
+
if (isAgentError(error) && error.code === 'CONCURRENCY') {
|
|
2669
|
+
return new Response(null, { status: 409 })
|
|
2670
|
+
}
|
|
2671
|
+
throw error
|
|
2672
|
+
}
|
|
2673
|
+
},
|
|
2674
|
+
},
|
|
2675
|
+
{
|
|
2676
|
+
method: 'POST',
|
|
2677
|
+
path: '/answers',
|
|
2678
|
+
handler: async (request) => {
|
|
2679
|
+
const principal = authenticate(request)
|
|
2680
|
+
const session = principal === undefined ? undefined : sessions.get(principal)
|
|
2681
|
+
if (session === undefined) return new Response(null, { status: 401 })
|
|
2682
|
+
if (!verify(request)) return new Response(null, { status: 403 })
|
|
2683
|
+
const answer = parseJSONAs(await request.text(), agentAnswerContract.is)
|
|
2684
|
+
if (answer === undefined) return new Response(null, { status: 400 })
|
|
2685
|
+
// An unknown, settled, or other principal's ask id settles nothing.
|
|
2686
|
+
return new Response(null, { status: session.approver.answer(answer) ? 204 : 404 })
|
|
2687
|
+
},
|
|
2688
|
+
},
|
|
2689
|
+
],
|
|
2690
|
+
})
|
|
2691
|
+
|
|
2692
|
+
const server = createServer({ dispatcher, state: () => undefined })
|
|
2693
|
+
await server.start()
|
|
2694
|
+
```
|
|
2695
|
+
|
|
2696
|
+
The page posts its prompt to its thread's path, frames the body through one strict `@orkestrel/ndjson` parser, checks each record against `agentFrameContract`, renders each `ask` frame's `name`, `zone`, and `arguments` as text before it posts its `AgentAnswer`, and treats a thrown `NDJSONError`, a refused record, or a body that ends without `finish` or `error` as a protocol error:
|
|
2697
|
+
|
|
2698
|
+
```ts
|
|
2699
|
+
import type { AgentAnswer } from '@orkestrel/agent'
|
|
2700
|
+
import { agentFrameContract } from '@orkestrel/agent'
|
|
2701
|
+
import { createNDJSONParser } from '@orkestrel/ndjson'
|
|
2702
|
+
|
|
2703
|
+
declare const token: string // the CSRF token the page holds for its session
|
|
2704
|
+
declare function render(text: string): void // writes text into the page, never markup
|
|
2705
|
+
declare function decide(id: string): Promise<boolean> // the user's answer to the ask
|
|
2706
|
+
|
|
2707
|
+
// Frames decoded text through one strict parser, completing a last line that has no newline.
|
|
2708
|
+
class RecordSplitter implements Transformer<string, unknown> {
|
|
2709
|
+
readonly #parser = createNDJSONParser({ strict: true })
|
|
2710
|
+
transform(chunk: string, controller: TransformStreamDefaultController<unknown>): void {
|
|
2711
|
+
for (const record of this.#parser.parse(chunk)) controller.enqueue(record)
|
|
2712
|
+
}
|
|
2713
|
+
flush(controller: TransformStreamDefaultController<unknown>): void {
|
|
2714
|
+
for (const record of this.#parser.parse('\n')) controller.enqueue(record)
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
const headers = { 'content-type': 'application/json', 'x-csrf-token': token }
|
|
2719
|
+
const response = await fetch('/threads/trip', {
|
|
2720
|
+
method: 'POST',
|
|
2721
|
+
headers,
|
|
2722
|
+
body: JSON.stringify({ content: 'Archive the notes from last week.' }),
|
|
2723
|
+
})
|
|
2724
|
+
if (!response.ok || response.body === null) {
|
|
2725
|
+
throw new Error(`the run was refused: ${response.status}`)
|
|
2726
|
+
}
|
|
2727
|
+
const records = response.body
|
|
2728
|
+
.pipeThrough(new TextDecoderStream())
|
|
2729
|
+
.pipeThrough(new TransformStream(new RecordSplitter()))
|
|
2730
|
+
.getReader()
|
|
2731
|
+
for (;;) {
|
|
2732
|
+
const record = await records.read()
|
|
2733
|
+
if (record.done) throw new Error('the frames ended without finish or error')
|
|
2734
|
+
const frame = record.value
|
|
2735
|
+
if (!agentFrameContract.is(frame)) throw new Error('a frame line was refused')
|
|
2736
|
+
if (frame.category === 'error') throw new Error('the run failed')
|
|
2737
|
+
if (frame.category === 'finish') break
|
|
2738
|
+
if (frame.category === 'token') render(frame.content)
|
|
2739
|
+
if (frame.category === 'tool') {
|
|
2740
|
+
render(frame.success ? `${frame.name} ran` : 'a call did not run')
|
|
2741
|
+
}
|
|
2742
|
+
if (frame.category === 'ask') {
|
|
2743
|
+
render(`${frame.name} asks in ${frame.zone} with ${frame.arguments}`)
|
|
2744
|
+
const answer: AgentAnswer = { id: frame.id, approved: await decide(frame.id) }
|
|
2745
|
+
const answered = await fetch('/answers', {
|
|
2746
|
+
method: 'POST',
|
|
2747
|
+
headers,
|
|
2748
|
+
body: JSON.stringify(answer),
|
|
2749
|
+
})
|
|
2750
|
+
if (answered.status !== 204) render(`the answer was not taken: ${answered.status}`)
|
|
2751
|
+
}
|
|
2752
|
+
}
|
|
2753
|
+
```
|
|
2177
2754
|
|
|
2178
2755
|
### Dispatching the model's tool calls
|
|
2179
2756
|
|
|
@@ -2217,7 +2794,7 @@ if (result.partial) keep(result.content) // a cancel RESOLVED partial, not an er
|
|
|
2217
2794
|
|
|
2218
2795
|
### Cancelling work inside a tool
|
|
2219
2796
|
|
|
2220
|
-
Every handler receives `(args, context)`, with the run's bound signal at `context.signal`; handlers may omit unused parameters. The agent passes this context through
|
|
2797
|
+
Every handler receives `(args, context)`, with the run's bound signal at `context.signal`; handlers may omit unused parameters. The agent passes this context through every dispatched call, allowed or approved, and supplies no `caller` identity. An agent abort, a stream abort, an external signal, or the deadline can abort a running handler's signal. The allowance is charged during provider streaming and the token budget after each provider call and between turns, before tool dispatch; exhaustion ends the run without dispatching, never inside a handler.
|
|
2221
2798
|
|
|
2222
2799
|
When the signal has aborted before the tool block, the agent leaves the prior conversation intact: it appends neither an assistant turn carrying calls nor tool messages and emits no `tool` chunk. The streamed content remains in the result, which settles with `partial: true`. After dispatch begins, cancellation is cooperative: the handler must stop its own work, and the agent waits for a handler that ignores the signal, records its real result, and then settles the run with `partial: true`. A cancelled run runs no automatic compaction after dispatch; the next run's pre-first-turn check folds instead.
|
|
2223
2800
|
|
|
@@ -2287,7 +2864,11 @@ result.stop?.layer // 'meter' when the estimate ran out first, 'budget' when the
|
|
|
2287
2864
|
|
|
2288
2865
|
### Observing an agent (push vs. pull)
|
|
2289
2866
|
|
|
2290
|
-
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)`), `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.
|
|
2867
|
+
An `Agent` exposes a pull and a push observation surface. Pull — the `AgentChunk` stream (`stream().events`) — is for a live consumer rendering per-token answer deltas and per-think reasoning deltas as they arrive. Push — the `emitter` (`AgentEventMap`) — is for fire-and-forget observers (logging, metrics, tracing) that want the loop's lifecycle moments without draining the stream: `start` (a run begins), `turn` (each iteration), `tool` (a dispatched call + its result), `usage` (a turn's token usage and the `estimate` of the answer it streamed, as `(usage, estimate)`), `allow` (a call cleared for dispatch, with its decision), `ask` (a call handed to the approver, with its decision), `deny` (a denied call; the event is never a chunk, and a call that scope or authority denies still yields a `tool` chunk that carries its denial result, while a call made when the active scope advertises no tools yields no chunk), `finish` (the settled result), `error` (a genuine failure), `abort` (a cancel), and `exhaust` (the limit was reached while the model still held unresolved tool intent — fires instead of `abort`, still followed by `finish`). Per-token / per-thinking deltas stay the stream's job exclusively — there is deliberately no `token` or `think` event on the emitter; reach for the stream when you need live output, the emitter when you need lifecycle.
|
|
2868
|
+
|
|
2869
|
+
An allow clears a call for the tool instance the registry held when the turn advertised it; if that instance is replaced or removed before dispatch, a `deny` follows with the reason `<name> changed after its decision` and no decision, so `deny` can follow that call's `allow`, and neither instance runs. A tool handler that replaces a later tool in the same batch before its first await is host code and is not re-checked. A cancel that ends the turn before dispatch emits no such `deny`.
|
|
2870
|
+
|
|
2871
|
+
The following observers wire at construction and later:
|
|
2291
2872
|
|
|
2292
2873
|
```ts
|
|
2293
2874
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
@@ -2314,7 +2895,7 @@ agent.emitter.on('abort', (reason) => log('cancelled', reason))
|
|
|
2314
2895
|
|
|
2315
2896
|
### Pulling context from another conversation (with provenance)
|
|
2316
2897
|
|
|
2317
|
-
One agent serves many conversations
|
|
2898
|
+
One agent serves many conversations: each run binds the conversation its `AgentRunOptions.conversation` names, or the one active at its call, which `conversations.switch(id)` sets at any moment without moving a live run; each thread keeps its own history. When the active conversation A needs something decided in another conversation B, don't merge B's turns into A's live tail — that pollutes A's thread and (for a small model) blurs which conversation said what. Instead pull a provenance-labeled reference of B into A's active workspace (the fenced reference channel `build()` folds into the user context message), so the model reads it as clearly-foreign material and attributes it to B.
|
|
2318
2899
|
|
|
2319
2900
|
The flow is **search / rehydrate → reference → write-to-workspace** — and cherry-pick, never dump:
|
|
2320
2901
|
|
|
@@ -2374,6 +2955,8 @@ for (const store of stores) {
|
|
|
2374
2955
|
}
|
|
2375
2956
|
```
|
|
2376
2957
|
|
|
2958
|
+
A `MemoryConversationStore` hands back the object it stored, so its snapshot's judgments are the frozen records `snapshot()` carried. Copy a judgment through `copyJSON` before you edit it. The `createMemoryMemoStore` and `createDatabaseMemoStore` factories apply the same `set`, `get`, and `delete` workflow to a memo set, keyed by its `id`. The host authors what a store holds: a memo can be model-written, so narrow a read through `isMemoSnapshot` and render a stored memo only in the context message, where the context puts it.
|
|
2959
|
+
|
|
2377
2960
|
### Recording a judgment on a conversation
|
|
2378
2961
|
|
|
2379
2962
|
A conversation carries its own judgment store, so a judge's answer about a message is recorded beside the messages it concerns and survives the snapshot round trip. `add` stamps the record's `time`; `judgment` reads one record by its key and `judgments` lists them in insertion order.
|
|
@@ -2441,7 +3024,7 @@ const results = await runner.execute([parent]) // [parent result, …then spawne
|
|
|
2441
3024
|
|
|
2442
3025
|
### Giving the model documents to read
|
|
2443
3026
|
|
|
2444
|
-
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`
|
|
3027
|
+
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.
|
|
2445
3028
|
|
|
2446
3029
|
```ts
|
|
2447
3030
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
@@ -2454,7 +3037,7 @@ const agent = createAgent(provider, { tools: createToolManager() })
|
|
|
2454
3037
|
// The first add auto-activates — agent.context.workspaces.active is this workspace, so build()
|
|
2455
3038
|
// renders its text files into the `## Workspace` section on every turn.
|
|
2456
3039
|
const workspace = agent.context.workspaces.add()
|
|
2457
|
-
workspace.write('
|
|
3040
|
+
workspace.write('notes.txt', 'The vault code is 7731.')
|
|
2458
3041
|
```
|
|
2459
3042
|
|
|
2460
3043
|
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.
|
|
@@ -2574,7 +3157,17 @@ const result = await agent.generate() // { content: 'Refunds need a manager.', p
|
|
|
2574
3157
|
|
|
2575
3158
|
### Serving requests through a ledger
|
|
2576
3159
|
|
|
2577
|
-
|
|
3160
|
+
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.
|
|
3161
|
+
|
|
3162
|
+
| Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
|
|
3163
|
+
| -------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
3164
|
+
| Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
|
|
3165
|
+
| 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 |
|
|
3166
|
+
| 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` |
|
|
3167
|
+
| 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 |
|
|
3168
|
+
| Ledger | `createLedger(provider, options)` | the built head, the seed tail, and a copy of the request turn with its records | the conversation, read through the `recall` tool | a judge and fitted cutoffs are required, and the ledger refuses no over-window prompt |
|
|
3169
|
+
|
|
3170
|
+
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 records the ledger wrote ahead of the request. The following ledger serves two requests; a scripted provider stands in for the model and a scripted judge for Mica:
|
|
2578
3171
|
|
|
2579
3172
|
```ts
|
|
2580
3173
|
import type {
|
|
@@ -2649,8 +3242,8 @@ const ledger = createLedger(provider, {
|
|
|
2649
3242
|
capacity: 32_768,
|
|
2650
3243
|
lookups: [lookup],
|
|
2651
3244
|
})
|
|
2652
|
-
const
|
|
2653
|
-
ledger.agent.emitter.on('select', (selection) =>
|
|
3245
|
+
const copies: Array<string | undefined> = []
|
|
3246
|
+
ledger.agent.emitter.on('select', (selection) => copies.push(selection.messages.at(-1)?.content))
|
|
2654
3247
|
ledger.conversation.add({ role: 'user', content: 'Refunds over $100 need a manager.' })
|
|
2655
3248
|
|
|
2656
3249
|
const gauge = await ledger.calibrate(AbortSignal.timeout(30_000))
|
|
@@ -2659,15 +3252,70 @@ const first = await ledger.respond('Can Brightwater Studio get a refund on order
|
|
|
2659
3252
|
first.content // 'Order BW-5512 qualifies for a $148.50 refund.'
|
|
2660
3253
|
const second = await ledger.respond('Does the Brightwater Studio refund need a manager?')
|
|
2661
3254
|
second.content // 'Yes. Refunds over $100 need a manager.'
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
3255
|
+
copies[0]
|
|
3256
|
+
// '## Rules\n- Refunds over $100 need a manager.\n\n## Request\nCan Brightwater Studio get a refund on order BW-5512?' — no lookup has named an owner yet
|
|
3257
|
+
copies[1]
|
|
3258
|
+
// '## Records\n### Brightwater Studio (BW-20931)\n- Order BW-5512 for account BW-20931: Brightwater Studio.\n- Refund due $148.50.\n\n## Rules\n- Refunds over $100 need a manager.\n\n## Request\nDoes the Brightwater Studio refund need a manager?'
|
|
2665
3259
|
```
|
|
2666
3260
|
|
|
2667
|
-
The second request names Brightwater Studio, so its
|
|
3261
|
+
The second request names Brightwater Studio, so its records carry that owner's record, built from the first request's lookup result, while neither the first request nor its reply reaches the second prompt, and the system message holds the `system` option alone. The executed transcription runs this fence with its own cutoffs and reads the prompts the provider received; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
|
|
3262
|
+
|
|
3263
|
+
To carry a ledger across a restart, store what its `snapshot` method returns and pass it back as the `snapshot` option of a later `createLedger` call. The snapshot is plain JSON: the conversation with its judgments, the ids of the requests, notes, and failed tool results the ledger marked, and the gauge. Narrow a parsed snapshot with the `isLedgerSnapshot` guard first, because construction refuses a snapshot the guard refuses with `LedgerError` code `'SNAPSHOT'`. The hydrated ledger makes no calibration call when the snapshot or the options carry a gauge, and it asks its judge no question the stored judgments answer. The following example continues the preceding ledger in a second ledger, and the second ledger writes the records the first would write for the same request:
|
|
3264
|
+
|
|
3265
|
+
```ts
|
|
3266
|
+
import type { LedgerInterface, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
|
|
3267
|
+
import { createLedger, isLedgerSnapshot } from '@orkestrel/agent'
|
|
3268
|
+
|
|
3269
|
+
declare const ledger: LedgerInterface // the ledger above, after its two requests
|
|
3270
|
+
declare const options: LedgerOptions // the options that built it, which carry no gauge
|
|
3271
|
+
declare const provider: ProviderInterface // scripted with one reply: 'Not yet. A manager must approve it.'
|
|
3272
|
+
|
|
3273
|
+
const stored = JSON.stringify(ledger.snapshot())
|
|
3274
|
+
const parsed: unknown = JSON.parse(stored)
|
|
3275
|
+
if (!isLedgerSnapshot(parsed)) throw new Error('Not a ledger snapshot')
|
|
3276
|
+
parsed.requests.length // 2 — the two requests the ledger served
|
|
3277
|
+
const restored = createLedger(provider, { ...options, snapshot: parsed })
|
|
3278
|
+
restored.gauge?.overhead // 120 — read from the snapshot, so the ledger calibrates nothing
|
|
3279
|
+
const copies: Array<string | undefined> = []
|
|
3280
|
+
restored.agent.emitter.on('select', (selection) => copies.push(selection.messages.at(-1)?.content))
|
|
3281
|
+
const third = await restored.respond('Is the Brightwater Studio refund approved yet?')
|
|
3282
|
+
third.content // 'Not yet. A manager must approve it.'
|
|
3283
|
+
copies[0]
|
|
3284
|
+
// '## Records\n### Brightwater Studio (BW-20931)\n- Order BW-5512 for account BW-20931: Brightwater Studio.\n- Refund due $148.50.\n\n## Rules\n- Refunds over $100 need a manager.\n\n## Request\nIs the Brightwater Studio refund approved yet?' — what the first ledger writes for the same request
|
|
3285
|
+
```
|
|
2668
3286
|
|
|
2669
3287
|
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.
|
|
2670
3288
|
|
|
3289
|
+
### Upgrade data written before 0.0.35
|
|
3290
|
+
|
|
3291
|
+
Stored data written before 0.0.35 meets the checks of 0.0.35 at its next read. A stored snapshot that holds a `system` row rejects with `ConversationError` `'ROLE'` and the message `a conversation snapshot holds a system message; a snapshot written before 0.0.35 can hold a system row; remove it before loading`. A queued `AgentJobInput` seed that holds a `system` message fails at `AgentRegistry.build` through `add`, with `ConversationError` `'ROLE'` and the message `a stored message role must be one of "user", "assistant", "tool"; received "system"; host text goes in the system option or an instruction`, and the job's `system` member carries that text.
|
|
3292
|
+
|
|
3293
|
+
The following fence removes the row from a snapshot read from a store. It narrows the read through `isConversationSnapshot`, which stays structural, and it filters `messages` and each section's `messages`, because hydrating checks both and a fold can hold the row in a section:
|
|
3294
|
+
|
|
3295
|
+
```ts
|
|
3296
|
+
import type { ConversationSnapshot, ConversationStoreInterface } from '@orkestrel/agent'
|
|
3297
|
+
import { createConversation, isConversationSnapshot } from '@orkestrel/agent'
|
|
3298
|
+
|
|
3299
|
+
declare const store: ConversationStoreInterface // the host's store
|
|
3300
|
+
|
|
3301
|
+
const stored: unknown = await store.get('thread-1')
|
|
3302
|
+
if (!isConversationSnapshot(stored)) throw new Error('Not a conversation snapshot')
|
|
3303
|
+
const cleaned: ConversationSnapshot = {
|
|
3304
|
+
...stored,
|
|
3305
|
+
sections: stored.sections.map((section) => ({
|
|
3306
|
+
...section,
|
|
3307
|
+
messages: section.messages.filter(({ role }) => role !== 'system'),
|
|
3308
|
+
})),
|
|
3309
|
+
messages: stored.messages.filter(({ role }) => role !== 'system'),
|
|
3310
|
+
}
|
|
3311
|
+
await store.set(cleaned)
|
|
3312
|
+
const conversation = createConversation({ snapshot: cleaned })
|
|
3313
|
+
```
|
|
3314
|
+
|
|
3315
|
+
A judgment whose `sources` name a removed row hydrates unchanged, and a section the filter empties hydrates with no messages. The `isLedgerSnapshot` guard refuses a mark that names a removed row, so drop that id from a ledger snapshot's `requests`, `notes`, and `failures` lists as well.
|
|
3316
|
+
|
|
3317
|
+
A host that edits a stored snapshot's judgment to migrate or redact it copies the record first, because a write to the stored record throws `TypeError` in strict-mode code. A stored 0.0.34 conversation row matches in any key order after upgrade, and a record dead under the text compare becomes live, with no migration.
|
|
3318
|
+
|
|
2671
3319
|
### Removing / clearing entries, and the less-common accessors
|
|
2672
3320
|
|
|
2673
3321
|
Agent-owned registries expose their less-common removal, clearing, persistence, and lookup methods here. Tool and workspace registry operations are documented in their dependency guides.
|
|
@@ -2709,9 +3357,11 @@ scopes.scopes() // every stored scope, in insertion order
|
|
|
2709
3357
|
scopes.remove(scope.id)
|
|
2710
3358
|
scopes.clear()
|
|
2711
3359
|
|
|
2712
|
-
// Authority — `evaluate`
|
|
2713
|
-
const authority = createAuthority()
|
|
2714
|
-
|
|
3360
|
+
// Authority — `evaluate` decides and `ask` approves (both also reached through the agent loop internally).
|
|
3361
|
+
const authority = createAuthority({ ask: () => true })
|
|
3362
|
+
const call = { id: '1', name: 'add', arguments: {} }
|
|
3363
|
+
const decision = authority.evaluate({ call }) // { zone: 'default', verdict: 'allow' }
|
|
3364
|
+
await authority.ask?.({ call }, decision, new AbortController().signal) // true (`ask` is optional on the interface)
|
|
2715
3365
|
|
|
2716
3366
|
// AgentRegistry — `scheduler(name)` resolves a registered scheduler by name (throws when absent).
|
|
2717
3367
|
const registry = createAgentRegistry({ providers: { main: provider } })
|
|
@@ -2749,10 +3399,10 @@ The following practices apply when you build on this package:
|
|
|
2749
3399
|
- **Narrow tool `args`** — a `ToolCall.arguments` is model-supplied `unknown`; narrow it inside `execute` with a guard.
|
|
2750
3400
|
- **Collect turns in an `AgentContext`** — append turns through `context.messages.add` (the `id` is minted for you), then call `build()` each turn to produce the provider input; tools travel as the provider's `tools` argument, so never fold a tool's schema into a message yourself.
|
|
2751
3401
|
- **Pull cross-conversation context with provenance, never by merging turns** — to use something from another conversation B in the active one, follow `B.search` / `B.rehydrate` (cherry-pick the few right turns) → `B.reference({ label, messages })` (frame it) → `context.workspaces.active?.write(...)` (write it into the active workspace). The provenance label keeps a small model from reading B's content (or a recap) as part of the live thread; cherry-pick — don't dump B's whole history into another context window.
|
|
2752
|
-
- **Run the loop with `createAgent`** — don't hand-roll the context → provider → tools cycle; `createAgent` does it, bounded by `AbortSignal.any([signal, timeout, budget])`, paced by `scheduler`, capped at `limit`. Drain `stream().events` to render `token` / `think` / `
|
|
3402
|
+
- **Run the loop with `createAgent`** — don't hand-roll the context → provider → tools cycle; `createAgent` does it, bounded by `AbortSignal.any([signal, timeout, budget])`, paced by `scheduler`, capped at `limit`. Drain `stream().events` to render `token` / `think` / `usage` / `ask` / `tool` chunks live, or `generate()` for the settled result; either way `result` resolves partial on a cancel (read `result.partial`), rejecting only on a real error.
|
|
2753
3403
|
- **Run many durable agents with `createAgentQueue`** — describe each agent as a serializable `AgentJobInput` (names for the provider / tools / authority / scheduler, data for the rest), register the live pieces once in a `createAgentRegistry`, and enqueue the jobs. Persist them with a `store` so `restore()` re-runs outstanding work after a crash. Decide the partial policy up front — `partial: false` (default) retries a cancelled job, `true` accepts the partial.
|
|
2754
3404
|
- **Fan out sub-agents with `createAgentRunner`** — declare a parent job's sub-agents in its `children`; the runner spawns each through `controller.spawn` on the same bounded queue. Don't reach for the controller yourself — express fan-out as data on the job (it stays serializable) and let the runner spawn it.
|
|
2755
|
-
- **Pull and push surfaces on the `Agent`, none elsewhere** — observe the `Agent` each way: pull the `AgentChunk` stream for per-token / per-thinking deltas + usage/tool chunks, or push `agent.emitter.on(...)` (`AgentEventMap`) for lifecycle + usage/tool/deny moments a fire-and-forget observer wants. A listener throw can never corrupt the loop (the emitter isolates it, routing it to the `error` option). Don't reach for an Emitter on the provider contract, the tool registry, the conversation store, the context, or the job layer — those stay event-free; and don't expect per-token `token` or `think` events (those stay the stream's job).
|
|
3405
|
+
- **Pull and push surfaces on the `Agent`, none elsewhere** — observe the `Agent` each way: pull the `AgentChunk` stream for per-token / per-thinking deltas + usage/ask/tool chunks, or push `agent.emitter.on(...)` (`AgentEventMap`) for lifecycle + usage/tool/deny moments a fire-and-forget observer wants. A listener throw can never corrupt the loop (the emitter isolates it, routing it to the `error` option). Don't reach for an Emitter on the provider contract, the tool registry, the conversation store, the context, or the job layer — those stay event-free; and don't expect per-token `token` or `think` events (those stay the stream's job).
|
|
2756
3406
|
- **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.
|
|
2757
3407
|
- **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.
|
|
2758
3408
|
- **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.
|
|
@@ -2762,60 +3412,72 @@ The following practices apply when you build on this package:
|
|
|
2762
3412
|
|
|
2763
3413
|
The following test files back this guide:
|
|
2764
3414
|
|
|
2765
|
-
- [`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, and the System One judge over a recorded response.
|
|
2766
|
-
- [`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`, and `matchesJudgment`, and the `
|
|
2767
|
-
- [`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.
|
|
2768
|
-
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — the root guards `isJudgeEntry`, `isJudgeQuestion`, and `isNonNegativeSafeInteger`, each total over
|
|
2769
|
-
- [`tests/src/core/contracts.test.ts`](../tests/src/core/contracts.test.ts) — the message contract's round trip and malformed paths,
|
|
2770
|
-
- [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — the message
|
|
2771
|
-
- [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — the in-process relay hop and provider-agnosticism, where a minimal provider drives the full loop and differently named providers swap in.
|
|
2772
|
-
- [`tests/src/core/providers/AgentProvider.test.ts`](../tests/src/core/providers/AgentProvider.test.ts) — the HTTP engine's request composition, stream assembly and settled results, bounded error body, header hook inside the cancellation bound, cancellation partials, cleanup on every exit, and isolation between concurrent calls.
|
|
2773
|
-
- [`tests/src/core/providers/RelayProvider.test.ts`](../tests/src/core/providers/RelayProvider.test.ts) — the browser end's owned request snapshot, wire refusals, frame mapping, remote abort reconstruction, and terminal-result recovery.
|
|
3415
|
+
- [`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.
|
|
3416
|
+
- [`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.
|
|
3417
|
+
- [`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.
|
|
3418
|
+
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — the root guards `isJudgeEntry`, `isJudgeQuestion`, and `isNonNegativeSafeInteger`, each total over malformed input.
|
|
3419
|
+
- [`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.
|
|
3420
|
+
- [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — the message, tool-call, and token usage wire shapes at the type level, with execution context kept off the wire, and the provider result schema unchanged by the shared usage shape.
|
|
3421
|
+
- [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — the in-process relay hop, its `422` refusal and server-written system turn, and provider-agnosticism, where a minimal provider drives the full loop and differently named providers swap in.
|
|
3422
|
+
- [`tests/src/core/providers/AgentProvider.test.ts`](../tests/src/core/providers/AgentProvider.test.ts) — the HTTP engine's request composition, stream assembly and settled results, bounded error body, header hook inside the cancellation bound, translation of a throw from the framing seam, cancellation partials, cleanup on every exit, and isolation between concurrent calls.
|
|
3423
|
+
- [`tests/src/core/providers/RelayProvider.test.ts`](../tests/src/core/providers/RelayProvider.test.ts) — the browser end's owned request snapshot, wire refusals, default strict framing, supplied parser factory, frame mapping, remote abort reconstruction, and terminal-result recovery.
|
|
2774
3424
|
- [`tests/src/core/providers/RelayStream.test.ts`](../tests/src/core/providers/RelayStream.test.ts) — the relay response half's upstream replay policy, validated frames, fixed error message, backpressure, and inbound-abort finalization.
|
|
2775
3425
|
- [`tests/src/core/providers/ThinkSplitter.test.ts`](../tests/src/core/providers/ThinkSplitter.test.ts) — the `ThinkSplitter` state machine.
|
|
2776
3426
|
- [`tests/src/core/providers/AgentJudge.test.ts`](../tests/src/core/providers/AgentJudge.test.ts) — the judge engine's identity and request composition, refusals before inference, HTTP and protocol failures, header hook, and cancellation partials.
|
|
2777
3427
|
- [`tests/src/core/providers/SystemOneJudge.test.ts`](../tests/src/core/providers/SystemOneJudge.test.ts) — the System One wire against the bodies recorded on 2026-10-07.
|
|
2778
|
-
- [`tests/src/core/providers/factories.test.ts`](../tests/src/core/providers/factories.test.ts) — the `createThinkSplitter` factory
|
|
2779
|
-
- [`tests/src/core/providers/helpers.test.ts`](../tests/src/core/providers/helpers.test.ts) — `buildProviderResult`, `armReaderAbort`, `readFailure`, `readBodyText`, `readChunks`, `
|
|
3428
|
+
- [`tests/src/core/providers/factories.test.ts`](../tests/src/core/providers/factories.test.ts) — the `createThinkSplitter` factory; the authorization, body-limit, malformed-body, policy, and upstream-construction refusals of `createRelay`; its server-written system turn and tool definitions; and its construction checks.
|
|
3429
|
+
- [`tests/src/core/providers/helpers.test.ts`](../tests/src/core/providers/helpers.test.ts) — `buildProviderResult`, `armReaderAbort`, `readFailure`, `readBodyText`, `readChunks`, `measureAnswer`, `buildJudgeResult`, `buildProviderHeaders`, `requestToRelay`, `buildRelayRequest`, `describeRelayRefusal`, the System One helpers, and `releaseReader`.
|
|
2780
3430
|
- [`tests/src/core/providers/contracts.test.ts`](../tests/src/core/providers/contracts.test.ts) — the request, result, and relay-frame contracts' round trips, malformed paths, and non-JSON refusals.
|
|
2781
3431
|
- [`tests/src/core/providers/shapers.test.ts`](../tests/src/core/providers/shapers.test.ts) — the request, result, and relay wire shapes assignable to their domain types.
|
|
2782
|
-
- [`tests/src/core/providers/validators.test.ts`](../tests/src/core/providers/validators.test.ts) — the System One guards `isSystemOneResponse` and `isSystemOneAnswer` over recorded, transliterated, and
|
|
2783
|
-
- [`tests/src/core/conversations/Conversation.test.ts`](../tests/src/core/conversations/Conversation.test.ts) — the conversation's construction, `view`, `compact` with `keep` and its no-op and missing-summarizer cases, `rehydrate`, `search`, `reference`, `snapshot`, the `sections` cap, and
|
|
2784
|
-
- [`tests/src/core/conversations/ConversationManager.test.ts`](../tests/src/core/conversations/ConversationManager.test.ts) — the registry's accessors, active pointer and `switch`, removal, the inherited `summarize`, `keep`, and `sections` defaults, independence, the durable `open` / `save` seam,
|
|
2785
|
-
- [`tests/src/core/conversations/JudgmentManager.test.ts`](../tests/src/core/conversations/JudgmentManager.test.ts) — the keyed storage of `JudgmentManager` and its `resolve` method, which asks only unmatched questions, attaches one-question usage, records partial answers on abort,
|
|
3432
|
+
- [`tests/src/core/providers/validators.test.ts`](../tests/src/core/providers/validators.test.ts) — the System One guards `isSystemOneResponse` and `isSystemOneAnswer` over recorded, transliterated, and malformed envelopes.
|
|
3433
|
+
- [`tests/src/core/conversations/Conversation.test.ts`](../tests/src/core/conversations/Conversation.test.ts) — the conversation's construction, `view`, `compact` with `keep` and its no-op and missing-summarizer cases, `rehydrate`, `search`, `reference`, `snapshot`, the `sections` cap, hydration, and the stored roles and snapshot checks: a `system` add or batch refused with nothing stored, a snapshot refused for a `system` role, a repeated id, or a malformed shape, the single read of its members, and `'JUDGMENT'` kept for a non-JSON judgment.
|
|
3434
|
+
- [`tests/src/core/conversations/ConversationManager.test.ts`](../tests/src/core/conversations/ConversationManager.test.ts) — the registry's accessors, active pointer and `switch`, removal, the inherited `summarize`, `keep`, and `sections` defaults, independence, the durable `open` / `save` seam, a 0.0.29 snapshot read through `open` without its conversation `summary`, and `open` refusing a stored `system` role with the registry and `active` unchanged.
|
|
3435
|
+
- [`tests/src/core/conversations/JudgmentManager.test.ts`](../tests/src/core/conversations/JudgmentManager.test.ts) — the keyed storage of `JudgmentManager` and its `resolve` method, which asks only unmatched questions, attaches one-question usage, records partial answers on abort, restores from a snapshot, and reuses a hydrated judgment whose keys were sorted, and the frozen records it returns.
|
|
2786
3436
|
- [`tests/src/core/conversations/factories.test.ts`](../tests/src/core/conversations/factories.test.ts) — `createConversation`, `createConversationManager`, `createMemoryConversationStore`, and `createDatabaseConversationStore`, each driving the instance it returns.
|
|
2787
|
-
- [`tests/src/core/conversations/helpers.test.ts`](../tests/src/core/conversations/helpers.test.ts) — `buildJudgments`, `buildSummaryMessage`, `buildRecapMessage`, `requireJudgment`, `requireSectionsCap`, `requireKeep`, and `raceSignal`.
|
|
2788
|
-
- [`tests/src/core/conversations/validators.test.ts`](../tests/src/core/conversations/validators.test.ts) — `isMessage`, `isJudgment` with snapshot carriage, `isSection`, and `
|
|
3437
|
+
- [`tests/src/core/conversations/helpers.test.ts`](../tests/src/core/conversations/helpers.test.ts) — `buildJudgments`, `buildSummaryMessage`, `buildRecapMessage`, `requireJudgment`, `requireRole`, `requireConversationSnapshot`, `requireSectionsCap`, `requireKeep`, and `raceSignal`.
|
|
3438
|
+
- [`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.
|
|
2789
3439
|
- [`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`.
|
|
2790
3440
|
- [`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.
|
|
2791
|
-
- [`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, workspace carriers and `scope.files`, scope filtering, format cascade,
|
|
2792
|
-
- [`tests/src/core/contexts/factories.test.ts`](../tests/src/core/contexts/factories.test.ts) — `createInstruction`, `createInstructionManager`, `createScope`, `createScopeManager`, and `createAgentContext
|
|
2793
|
-
- [`tests/src/core/contexts/helpers.test.ts`](../tests/src/core/contexts/helpers.test.ts) — `renderFencedFile`, `renderSection`, `attachImages`, `attachUserImages`, `collectImageData`, and `intersectKeys`.
|
|
3441
|
+
- [`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)`.
|
|
3442
|
+
- [`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.
|
|
3443
|
+
- [`tests/src/core/contexts/helpers.test.ts`](../tests/src/core/contexts/helpers.test.ts) — `renderFencedFile`, `renderSection`, `renderIndexEntry`, `attachImages`, `attachUserImages`, `collectImageData`, and `intersectKeys`.
|
|
3444
|
+
- [`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.
|
|
2794
3445
|
- [`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`.
|
|
2795
3446
|
- [`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.
|
|
2796
|
-
- [`tests/src/core/contexts/
|
|
3447
|
+
- [`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.
|
|
3448
|
+
- [`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.
|
|
2797
3449
|
- [`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.
|
|
2798
|
-
- [`tests/src/core/
|
|
2799
|
-
- [`tests/src/core/
|
|
2800
|
-
- [`tests/src/core/
|
|
2801
|
-
- [`tests/src/core/agents/
|
|
2802
|
-
- [`tests/src/core/agents/
|
|
2803
|
-
- [`tests/src/core/agents/
|
|
3450
|
+
- [`tests/src/core/contexts/skills/SkillManager.test.ts`](../tests/src/core/contexts/skills/SkillManager.test.ts) — the skill registry's add, files minted through `createFile`, same-name replace, lookup, removal, format cascade, and emitter.
|
|
3451
|
+
- [`tests/src/core/contexts/stores/MemoryMemoStore.test.ts`](../tests/src/core/contexts/stores/MemoryMemoStore.test.ts) — the in-memory memo store's restore into a manager, its JSON parity, and the object its `get` method returns.
|
|
3452
|
+
- [`tests/src/core/contexts/stores/DatabaseMemoStore.test.ts`](../tests/src/core/contexts/stores/DatabaseMemoStore.test.ts) — the driver-backed memo store's malformed and foreign-id rows read as absent, its copy on read, and its table kept apart from the conversation store's on one driver.
|
|
3453
|
+
- [`tests/src/core/agents/Agent.test.ts`](../tests/src/core/agents/Agent.test.ts) — the loop over a scripted provider: the recorded-request control, scope dispatch, tool iteration, authority, `generate` and `stream` parity, chunks, bounds, cancellation timing, the emitter, automatic compaction, recorded thinking and the replay policy, multi-conversation runs and the run-bound conversation under a switch, a fold, and a removal, limit exhaustion, budget reconciliation, per-run options, the concurrency guard with its refusal of a second run on one conversation, usage sanitizing, the selection seam, the turn records, the three failure layers, the stored-ingress canary that refuses a `system` message through `add`, a snapshot, a job seed, and a selection and sends none, the scope denial of a name no definition advertises under every verdict, the `ask` chunk and its order, the approver over a real run with its page answers, timeouts, aborts, and injected arguments, the `prompt` option with its exact check and its append after the run's guards, and the forwarded skills and memos.
|
|
3454
|
+
- [`tests/src/core/agents/AgentRegistry.test.ts`](../tests/src/core/agents/AgentRegistry.test.ts) — the registry's accessors, rehydrating `build` and its field wiring, a job seed holding a `system` role refused, isolation, the conversation store seam, and an empty registry.
|
|
3455
|
+
- [`tests/src/core/agents/Authority.test.ts`](../tests/src/core/agents/Authority.test.ts) — first-match-wins ordering, a matched rule's default allow, the fallback, the `{ call }` context, and the `ask` approver with its `'APPROVER'` refusal.
|
|
3456
|
+
- [`tests/src/core/agents/Approver.test.ts`](../tests/src/core/agents/Approver.test.ts) — the bound `ask`, the ask registered before it suspends, the frame's members and minted id, strict approval, identity keying, the missed mark, the second-ask and unrenderable-argument refusals with the call name encoded, and the release of the run signal on an answer and an abort.
|
|
3457
|
+
- [`tests/src/core/agents/Channel.test.ts`](../tests/src/core/agents/Channel.test.ts) — the channel's lost-wakeup, `undefined` values, buffer-before-close, `fail`, concurrent readers, push after end, FIFO order, end semantics, the unread rest before an end, and a `return()` while a read is parked.
|
|
3458
|
+
- [`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.
|
|
3459
|
+
- [`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.
|
|
3460
|
+
- [`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`.
|
|
3461
|
+
- [`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.
|
|
3462
|
+
- [`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`.
|
|
3463
|
+
- [`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.
|
|
2804
3464
|
- [`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.
|
|
2805
|
-
- [`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, the repeat stop, 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, and room, 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.
|
|
2806
|
-
- [`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
|
|
2807
|
-
- [`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, pair questions, deterministic and transient judge failures, abort faults that keep the completed judgments,
|
|
3465
|
+
- [`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, 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, and room, 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, and the snapshot and hydrate: selections and judge keys equal to the uninterrupted ledger's with each emptied mark list as a control, 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.
|
|
3466
|
+
- [`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 repeat stop, the recall limit and `close`, and the listings of a recall result.
|
|
3467
|
+
- [`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.
|
|
2808
3468
|
- [`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.
|
|
2809
|
-
- [`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, and the barrel exports of the ledger module.
|
|
2810
|
-
- [`tests/src/core/ledgers/helpers.test.ts`](../tests/src/core/ledgers/helpers.test.ts) — the projection helpers from `splitSentences` through `buildRecords` and `selectRecords`, the record renderers, `findLedgerCall`, `rankLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `resolvePredict`, and `fitSlope`.
|
|
3469
|
+
- [`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.
|
|
3470
|
+
- [`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`, and `fitSlope`.
|
|
3471
|
+
- [`tests/src/core/ledgers/validators.test.ts`](../tests/src/core/ledgers/validators.test.ts) — `isFraction`, `isPositiveSafeInteger`, and `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.
|
|
2811
3472
|
|
|
2812
3473
|
### Placement proofs
|
|
2813
3474
|
|
|
2814
3475
|
Each placement has a named proof location:
|
|
2815
3476
|
|
|
2816
3477
|
- **Node alone.** The agent, provider, and tools run in Node. The `src:core` project executes “runs the agent tool loop in Node and feeds the result into the next provider turn” in [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts).
|
|
2817
|
-
- **Page alone.** The agent, an in-page provider, and page tools run in the page. The receipt is planned in the `tests/distribution.test.ts` file of the `@orkestrel/mcp` checkout, in the `distribution` project: the planned proof “executes a page tool through an agent without network requests”. That receipt must come from installed artifacts in Chromium; this guide doesn't record it as passed.
|
|
3478
|
+
- **Page alone.** The agent, an in-page provider, and page tools run in the page. A page `Ledger` stays responsive only with `agent: { scheduler: createBrowserScheduler() }`, as **The filing.** states. The receipt is planned in the `tests/distribution.test.ts` file of the `@orkestrel/mcp` checkout, in the `distribution` project: the planned proof “executes a page tool through an agent without network requests”. That receipt must come from installed artifacts in Chromium; this guide doesn't record it as passed.
|
|
2818
3479
|
- **Page to Node relay.** The agent, relay provider, and page tools run in the page; `createRelay` and the upstream provider run in Node. The receipt is planned in the same `@orkestrel/mcp` distribution proof file: the planned proof “executes a page tool through an agent over a Node relay”. This guide doesn't record that Chromium receipt as passed. The guide transcription's HTTP hop runs in Node and proves that narrower placement.
|
|
3480
|
+
- **Page to Node agent.** The agent, provider, tools, and approver run in Node; the page sends an `AgentPrompt`, renders `AgentFrame` values, and answers an `ask` frame with an `AgentAnswer`. The `guides` project executes “serves the page wire over an HTTP hop” in [`tests/guides.test.ts`](../tests/guides.test.ts), which runs both fences of the Serving a Node agent to a page section over an HTTP hop in Node.
|
|
2819
3481
|
|
|
2820
3482
|
## See also
|
|
2821
3483
|
|
|
@@ -2830,6 +3492,6 @@ The following guides and packages relate to this one:
|
|
|
2830
3492
|
- [Tool](tool.md) — the tool runtime this loop advertises from and dispatches through: definitions, calls, and the success-discriminated `ToolResult`.
|
|
2831
3493
|
- [Workspace](workspace.md) — the file domain whose active workspace `AgentContext` renders into a turn: files, editing, events, and persistence.
|
|
2832
3494
|
- [Contract](contract.md) — the shape DSL other tools (for example the `createWorkspaceTool` function of the `@orkestrel/toolbox` package) compile against; the shared `describedLiteral` (a discriminant's description-carrier) and `schemaToParameters` (the tool-parameters narrowing) live there.
|
|
2833
|
-
- [Database](database.md) — the `DriverInterface` / `TableInterface` seam `createDatabaseConversationStore` persists conversation snapshots through.
|
|
3495
|
+
- [Database](database.md) — the `DriverInterface` / `TableInterface` seam `createDatabaseConversationStore` persists conversation snapshots through and `createDatabaseMemoStore` persists memo sets through.
|
|
2834
3496
|
- [AGENTS.md](../AGENTS.md) — the repository's authority pointer; the coding rules it resolves to live in `@orkestrel/scaffold`.
|
|
2835
3497
|
- [Guides](README.md) — the guides index.
|