@orkestrel/scaffold 0.0.124 → 0.0.126
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-publish/scripts/steps.js +523 -0
- package/dist/agents/skills/orkestrel-publish/scripts/wave.js +70 -11
- package/dist/bin/main.js +51 -18
- package/dist/bin/main.js.map +1 -1
- package/dist/host/agents/orchestration.md +7 -2
- package/dist/host/agents/platforms/windows.md +9 -1
- package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +1 -1
- package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +1 -1
- package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +1 -0
- package/dist/host/agents/skills/orkestrel-harden/references/methods.md +32 -4
- package/dist/host/agents/skills/orkestrel-journey/SKILL.md +18 -19
- package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
- package/dist/host/agents/skills/orkestrel-parallel/references/codex.md +2 -1
- package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
- package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
- package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
- package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
- package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
- package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
- package/dist/host/claude/agents/orkestrel.md +28 -28
- package/dist/host/claude/rules/patterns.md +1 -1
- package/dist/host/claude/rules/portability.md +2 -0
- package/dist/host/claude/rules/quality.md +6 -1
- package/dist/host/claude/rules/tests.md +6 -1
- package/dist/host/claude/rules/workspace.md +8 -3
- package/dist/host/guides/agent.md +575 -346
- package/dist/host/guides/brief.md +52 -48
- package/dist/host/guides/browser.md +2 -2
- package/dist/host/guides/interpret.md +531 -155
- package/dist/host/guides/mcp.md +183 -61
- package/dist/host/guides/ndjson.md +4 -3
- package/dist/host/guides/ollama.md +125 -68
- package/dist/host/guides/program.md +117 -39
- package/dist/host/guides/qualifier.md +110 -59
- package/dist/host/guides/rater.md +85 -32
- package/dist/host/guides/scaffold.md +49 -22
- package/dist/host/guides/study.md +596 -489
- package/dist/host/guides/toolbox.md +159 -80
- package/dist/host/guides/workflow.md +44 -25
- package/dist/host/manifest.json +41 -35
- package/dist/src/core/index.cjs +12 -10
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +3 -1
- package/dist/src/core/index.d.ts +3 -1
- package/dist/src/core/index.js +12 -10
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +23 -11
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +10 -6
- package/dist/src/server/index.d.ts +10 -6
- package/dist/src/server/index.js +23 -11
- package/dist/src/server/index.js.map +1 -1
- package/package.json +7 -7
|
@@ -18,6 +18,14 @@ The loop and its tool handlers execute in the host that constructs them. See [Pl
|
|
|
18
18
|
|
|
19
19
|
## Surface
|
|
20
20
|
|
|
21
|
+
The `Conversation.add` method refuses a malformed `MessageInput` value before storing it and carries its structural faults in the error context.
|
|
22
|
+
|
|
23
|
+
`Conversation.add` stores each tool call with only its `id`, `name`, and `arguments`. It refuses
|
|
24
|
+
non-JSON arguments with `ConversationError` code `'MESSAGE'` before storing any member of a batch.
|
|
25
|
+
Hydration still admits non-JSON call arguments in an in-memory snapshot; a durable snapshot must
|
|
26
|
+
satisfy its JSON contract. A stored noul answer outside `[0, 1]` refuses a database read with
|
|
27
|
+
`ConversationError` code `'SNAPSHOT'`; the row remains available for explicit repair or deletion.
|
|
28
|
+
|
|
21
29
|
The agent-owned surface: the inference boundary and the HTTP engine behind it, the relay that carries that boundary to a browser, the judge boundary with its HTTP engine and the System One wire, the conversation layer, the context and its managers, the loop, the authority gate, the durable-job bridge, and the ledger that serves a conversation through a judge's filing. Tool and workspace entities belong to their originating packages and are consumed directly — never re-exported here — and one vendor's wire belongs to the concrete provider that extends `AgentProvider`.
|
|
22
30
|
|
|
23
31
|
A provider turns a conversation (plus optional tools) into a turn: `generate` resolves the assembled `ProviderResult` (content + any tool calls + any usage); `stream` yields channel-tagged `ProviderDelta` values as they arrive (`content` for answer text, `thinking` for live reasoning) and returns the same assembled result when the stream completes, so a caller can render tokens / reasoning live and still get the full outcome. Both bound the call with an `AbortSignal`:
|
|
@@ -103,17 +111,25 @@ Drive the whole turn with an `Agent` (`createAgent`) — it composes the provide
|
|
|
103
111
|
|
|
104
112
|
```ts
|
|
105
113
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
106
|
-
import { createAgent } from '@orkestrel/agent'
|
|
114
|
+
import { createAgent, createAuthority } from '@orkestrel/agent'
|
|
107
115
|
import { createTokenBudget } from '@orkestrel/budget'
|
|
116
|
+
import { numberShape, objectShape } from '@orkestrel/contract'
|
|
108
117
|
import { createTool, createToolManager } from '@orkestrel/tool'
|
|
109
118
|
|
|
110
119
|
declare const provider: ProviderInterface
|
|
111
120
|
const tools = createToolManager()
|
|
112
|
-
tools.add(
|
|
121
|
+
tools.add(
|
|
122
|
+
createTool({
|
|
123
|
+
name: 'add',
|
|
124
|
+
contract: objectShape({ a: numberShape(), b: numberShape() }),
|
|
125
|
+
execute: (args) => Number(args.a) + Number(args.b),
|
|
126
|
+
}),
|
|
127
|
+
)
|
|
113
128
|
|
|
114
129
|
const agent = createAgent(provider, {
|
|
115
130
|
system: 'You are concise.',
|
|
116
131
|
tools,
|
|
132
|
+
authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }), // tools need an authority
|
|
117
133
|
limit: 4, // cap tool iterations
|
|
118
134
|
timeout: 30_000, // wall-clock deadline for the whole turn
|
|
119
135
|
budget: createTokenBudget({ max: 50_000, scope: 'total' }), // cost ceiling
|
|
@@ -132,7 +148,7 @@ const result = await stream.result // { content, usage?, partial } — usage sum
|
|
|
132
148
|
Both `generate` and `stream` accept optional per-run `AgentRunOptions` — `think` and `schema` (forwarded to the provider as `ProviderStreamOptions`) plus `limit` / `timeout` / `budget` / `allowance` / `signal`, each overriding its `AgentOptions` construction default for this run only. Omitting one keeps the constructed default, so a caller that passes no options gets the agent it configured. The same options carry `conversation`, which binds the run, and `prompt`, which the run appends as a `user` turn after its guards; a run with no `prompt` reads its request from the conversation's tail. A per-run `signal` composes with (never replaces) a constructed `signal` — either aborting cancels the run; the loop calls `start()` on a per-run `budget` or `allowance` for that run and charges it, leaving a constructed one untouched:
|
|
133
149
|
|
|
134
150
|
```ts
|
|
135
|
-
const agent = createAgent(provider, { tools, limit: 10, timeout: 60_000 }) // construction defaults
|
|
151
|
+
const agent = createAgent(provider, { tools, authority, limit: 10, timeout: 60_000 }) // construction defaults
|
|
136
152
|
agent.context.messages.add({ role: 'user', content: 'Summarize this doc.' })
|
|
137
153
|
|
|
138
154
|
// A tighter, structured-output run -- overrides limit + timeout, adds a schema, for THIS call only.
|
|
@@ -145,23 +161,34 @@ const result = await agent.generate({
|
|
|
145
161
|
|
|
146
162
|
`schema`, like `think`, rides into `provider.stream` as a `ProviderStreamOptions`: the loop composes both into one options object, omitting whichever key is unset, and passes no options object at all when neither is present — a provider that never received one still never does.
|
|
147
163
|
|
|
148
|
-
The
|
|
164
|
+
The loop also enforces `schema`: the final answer must parse as JSON and satisfy the schema, read through the lenient `schemaToShape`, which widens every keyword it can't express and never narrows. A miss settles the run `error` with `AgentError` `'SCHEMA'`, whose `context.faults` names what missed, and stores no answer. A `truncated` answer skips the check and keeps its `model` stop. Pass `strict: false` to `createAgent` for a provider that ignores schemas: a miss then emits `fault` with that error and settles with the raw content.
|
|
165
|
+
|
|
166
|
+
The turn is bounded by one cancel folded from the external `signal` + the `timeout` deadline + the `budget` and `allowance` signals through `AbortSignal.any`; `agent.abort(reason)` (or `stream.abort(reason)`) fires it. A cancel — external, deadline, budget, allowance, or `abort()` — commits a partial result: the `result` promise resolves with `{ partial: true, content: <what accumulated> }`, never rejects (a cancel isn't an error); only a genuine provider / tool error rejects. A genuine provider error after streaming still charges the `budget` the failed call's streamed-answer estimate, once, before the run rejects. The loop yields to an optional `scheduler` between turns; tool iteration is capped at `limit` (default `DEFAULT_AGENT_LIMIT`). Exhausting `limit` while the model still holds unresolved tool intent (it requested tools on the very last allowed turn) is a distinct, non-cancel cause of `partial: true` — it fires an `exhaust` event (the turns reached) instead of `abort`. A natural finish on the last allowed turn stays `partial: false`. A `limit` that is not a positive safe integer throws `AgentError` coded `'LIMIT'`, `0` included, because a run of no turns answers nothing. `agent.status` transitions `idle` → `running` → `done` / `error`.
|
|
149
167
|
|
|
150
|
-
Gate the model's tool calls with an
|
|
168
|
+
Gate the model's tool calls with an `Authority` (`createAuthority`) — a synchronous policy gate the loop consults after scope admits a call, passed through `AgentOptions.authority`. An agent built with `tools` and no `authority` throws `AgentError` coded `'AUTHORITY'` at construction, so a host decides what the model may call before the model can call anything. The gate walks ordered `rules` first-match-wins, each naming its `verdict`, and the required `fallback` decides when none match: an `allow` fallback makes a denylist, and a `deny` fallback makes an allowlist. A missing `fallback` or a rule with no `verdict` throws `AgentError` coded `'AUTHORITY'` from `createAuthority`. To allow every call, pass `createAuthority({ fallback: { zone: 'default', verdict: 'allow' } })`. A denied call is never executed: the loop synthesizes the failure arm of `ToolResult` (`error: '"<name>" did not run: <reason>'`) and feeds it back as a `tool` chunk and a tool message, so no handler runs, no budget is spent, and the model still receives the denial and can request another call. An allowed call dispatches normally. An asked call dispatches only when the authority's `ask` approver resolves `true`; a refusal, a rejection, or no approver denies it. The loop raises an `allow` to an `ask` for a tool whose advertised definition is annotated `consequential`. An agent built with no `tools` holds no authority, and it denies a tool a host adds later through `context.tools`:
|
|
151
169
|
|
|
152
170
|
```ts
|
|
153
171
|
import { createAgent, createAuthority } from '@orkestrel/agent'
|
|
172
|
+
import { numberShape, objectShape } from '@orkestrel/contract'
|
|
154
173
|
import { createTool, createToolManager } from '@orkestrel/tool'
|
|
155
174
|
|
|
156
175
|
// `provider`, `drop`, and `confirm` come from the host application.
|
|
157
176
|
const tools = createToolManager()
|
|
158
177
|
tools.add([
|
|
159
|
-
createTool({
|
|
160
|
-
|
|
178
|
+
createTool({
|
|
179
|
+
name: 'add',
|
|
180
|
+
contract: objectShape({ a: numberShape(), b: numberShape() }),
|
|
181
|
+
execute: (args) => Number(args.a) + Number(args.b),
|
|
182
|
+
}),
|
|
183
|
+
createTool({
|
|
184
|
+
name: 'delete',
|
|
185
|
+
contract: objectShape({ id: numberShape() }),
|
|
186
|
+
execute: (args) => drop(args.id),
|
|
187
|
+
}),
|
|
161
188
|
])
|
|
162
189
|
|
|
163
|
-
// A denylist: deny `delete`, allow everything else
|
|
164
|
-
//
|
|
190
|
+
// A denylist: deny `delete`, allow everything else, and answer an asked call through the host's
|
|
191
|
+
// `confirm`.
|
|
165
192
|
const authority = createAuthority({
|
|
166
193
|
rules: [
|
|
167
194
|
{
|
|
@@ -171,6 +198,7 @@ const authority = createAuthority({
|
|
|
171
198
|
reason: 'read-only mode',
|
|
172
199
|
},
|
|
173
200
|
],
|
|
201
|
+
fallback: { zone: 'default', verdict: 'allow' },
|
|
174
202
|
ask: (context) => confirm(`Run ${context.call.name}?`),
|
|
175
203
|
})
|
|
176
204
|
const agent = createAgent(provider, { tools, authority })
|
|
@@ -180,6 +208,8 @@ agent.context.messages.add({ role: 'user', content: 'Delete record 42.' })
|
|
|
180
208
|
|
|
181
209
|
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
210
|
|
|
211
|
+
For a batch, the loop decides every call synchronously before entering an approver. It asks in call order, waiting for each answer before asking the next, and dispatches only after that pass unless the run is cancelled. A batch with no asked call adds no approval wait.
|
|
212
|
+
|
|
183
213
|
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
214
|
|
|
185
215
|
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:
|
|
@@ -191,7 +221,7 @@ import { createAgent, createAuthority } from '@orkestrel/agent'
|
|
|
191
221
|
// `provider` comes from the host application.
|
|
192
222
|
declare const tools: ToolManagerInterface // holds `search` and `delete_order`
|
|
193
223
|
const authority = createAuthority({
|
|
194
|
-
rules: [{ match: (context) => context.call.name === 'search', zone: 'read' }],
|
|
224
|
+
rules: [{ match: (context) => context.call.name === 'search', zone: 'read', verdict: 'allow' }],
|
|
195
225
|
fallback: { zone: 'blocked', verdict: 'deny', reason: 'that tool is not on the list' },
|
|
196
226
|
})
|
|
197
227
|
const agent = createAgent(provider, { tools, authority })
|
|
@@ -350,6 +380,8 @@ Register a conversation in a `ConversationManager` and pass that registry throug
|
|
|
350
380
|
|
|
351
381
|
Pass that registry through `AgentOptions.conversations` together with an `AgentOptions.window` context [`Budget`](budget.md) to enable automatic compaction. Before the first provider request and between turns, the loop measures each request it will send, with its messages after the `replay` policy, its advertised tools, and its per-call `options`, against the window and, when that request reaches the ceiling, compacts the run's conversation, when it is summarizable, before continuing on the rebuilt view. Omit `window` and the loop doesn't auto-compact. See the [Contract](#contract) (the automatic-compaction clause) for the exact trigger and the compaction floor.
|
|
352
382
|
|
|
383
|
+
Set the window well under the provider's context size, because `estimateTokens` under-measures and an over-window request refuses. Read on Ollama 0.40.14 with `qwen3.5:2b` on 2026-11-04, real prompt tokens over the estimate ran 1.23 to 1.78: 1.5 for ordinary English with figures, 1.23 for JSON tool arguments, and 1.47 to 1.78 for repeated filler words. A window of half of `num_ctx` covers that range.
|
|
384
|
+
|
|
353
385
|
```ts
|
|
354
386
|
import { createAgent, createConversationManager, estimateRequest } from '@orkestrel/agent'
|
|
355
387
|
import { createBudget } from '@orkestrel/budget'
|
|
@@ -361,7 +393,7 @@ const agent = createAgent(provider, {
|
|
|
361
393
|
conversations,
|
|
362
394
|
// A context Budget: consumer = a token estimator, max = the context window. The loop measures
|
|
363
395
|
// each request against it. A request that reaches the window folds once and continues on the
|
|
364
|
-
// rebuilt (smaller) view;
|
|
396
|
+
// rebuilt (smaller) view; `strict`, the default, refuses a request still over the window.
|
|
365
397
|
window: createBudget({ max: 8_000, consumer: estimateRequest }),
|
|
366
398
|
})
|
|
367
399
|
agent.context.messages.add({ role: 'user', content: 'Hi' })
|
|
@@ -424,8 +456,8 @@ Auto-compaction (the `window` budget) is hardened for a long-running app:
|
|
|
424
456
|
- **Pre-first-turn + run-entry reset.** The budget check runs before the first provider request and between turns — so a resumed or already-long conversation whose initial prompt already exceeds the window compacts immediately (not only after a tool turn). The `window` budget is reset at run entry, so no stale measurement carries across runs or a conversation switch.
|
|
425
457
|
- **No fold after a cancel.** When the run's signal has aborted by the time tool dispatch ends, the loop records the tool messages and folds nothing, so a cancel never waits on the summarizer. The next run's pre-first-turn check folds the earlier exchanges, call groups whole.
|
|
426
458
|
- **What a cancel waits for.** The loop races a scheduler's yield, the approver's answer, and the summarizer against the run signal, so one that ignores its signal still ends on a cancel; a provider stream, a judge, a tool handler, and a selection handler are awaited until they settle, because each can carry usage or finished work, so one that ignores its signal holds the run past a cancel or a timeout, and on a ledger its held scan, until it returns.
|
|
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.
|
|
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.
|
|
459
|
+
- **Observable summarizer failure, non-fatal unless strict.** If the summarizer throws during automatic compaction, the loop emits the error as a `fault` event, so the failure is never silently lost. With `strict: false`, the run doesn't crash: the loop skips compaction that turn and continues, and the over-window prompt proceeds to the provider. Under `strict`, the default, the run settles `error` after the `fault` event (see the `strict` clause under [Contract](#contract)). A manual `conversation.compact()` call you make yourself always propagates its error.
|
|
460
|
+
- **Futile-compaction guard.** If `compact()` folds nothing (returns `undefined`) between turns while the prompt is still over the window — that is, the section summaries, the run's request, and the run's own turns, which that fold never takes, already exceed it — the loop stops auto-compacting for the rest of that run (a per-run latch), avoiding per-turn churn. Under the default `strict`, the over-window request then throws `AgentError` `'WINDOW'` before it reaches the provider. With `strict: false`, it proceeds to the provider, and the provider decides what happens past its window. A plain fold takes the live tail and leaves the existing sections; a `sections` cap and `cumulative` fold existing sections too, each on a fold that has an eligible slice, as the `cumulative` folds and compaction floor clauses under [Contract](#contract) state.
|
|
429
461
|
|
|
430
462
|
The following listener observes an automatic-compaction summarizer failure:
|
|
431
463
|
|
|
@@ -443,7 +475,7 @@ A `Scope` (`createScope` / a `ScopeManager`) is a named allow-list filter the co
|
|
|
443
475
|
```ts
|
|
444
476
|
import { createAgent, createScope } from '@orkestrel/agent'
|
|
445
477
|
|
|
446
|
-
const agent = createAgent(provider, { tools }) // tools holds `search` + `delete`
|
|
478
|
+
const agent = createAgent(provider, { tools, authority }) // tools holds `search` + `delete`
|
|
447
479
|
agent.context.instructions.add([
|
|
448
480
|
{ name: 'safety', content: 'Refuse unsafe requests.' },
|
|
449
481
|
{ name: 'verbose', content: 'Explain every step.' },
|
|
@@ -463,7 +495,7 @@ A scoped-out tool is neither described nor callable. The loop snapshots the scop
|
|
|
463
495
|
|
|
464
496
|
A scope change through the `context.apply` method applies at each later site that reads the scope. The tool half applies at the next turn's snapshot: a `tool` or `usage` listener changes the next turn's advertising, and a `turn` listener reaches the same turn, because `turn` fires before the snapshot. The prompt half (instructions, skills, memos, files, and `select`) applies at the next build or select site: run entry, the pre-first-turn compaction fold, or a compaction rebuild.
|
|
465
497
|
|
|
466
|
-
When no tool is advertised, including an empty registry,
|
|
498
|
+
When no tool is advertised, including an empty registry, a reply with no calls ends the run as the answer, and a call the reply still carries is denied like any other scoped-out call: it emits a `deny` event with the `<tool name> is not in the active scope` reason, gets a denial tool result and tool message, and the loop runs another turn, up to `limit`, so a call is never read as a final answer.
|
|
467
499
|
|
|
468
500
|
When at least one tool is advertised, a call excluded by the tool allow-list or naming no advertised tool emits a `deny` event with the `TOOL is not in the active scope` reason, where the `TOOL` placeholder is the requested name. Its denial `ToolResult` value carries the `"TOOL" did not run: it is not one of the listed tools. Use a listed tool or answer with what you have.` error and is fed back as a tool message. Admitted calls pass through authority and dispatch normally. The loop continues with results in the reply's call order, including when calls share an ID.
|
|
469
501
|
|
|
@@ -515,12 +547,14 @@ const request = plain.context.messages.add({ role: 'user', content: 'Invoice 42.
|
|
|
515
547
|
plain.context.select(plain.context.messages, request, new AbortController().signal) // undefined — no handler in either home
|
|
516
548
|
```
|
|
517
549
|
|
|
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'`.
|
|
550
|
+
A selection fails four ways. A handler throw emits `fault`, and the loop builds from `view()` with no `select` event. A returned `fault` charges its usage first, then emits `fault`, and the loop builds from the returned `messages` and emits `select`. A conversation changed under the handler is a fault as well: `context.select` returns the current `view()` with a `fault` that names the change. A `system` message in a handler's selection is a fault over `view()` carrying `ConversationError` `'ROLE'`. Under `AgentOptions.strict`, the default, all four settle the run `error`; with `strict: false`, the run continues. A cancel at a select site wins over all of them, and the run commits partial with no provider call.
|
|
519
551
|
|
|
520
552
|
Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`. No `usage` chunk or `usage` event carries it, so that chunk keeps its one-provider-call meaning.
|
|
521
553
|
|
|
522
554
|
### Judgments on the conversation
|
|
523
555
|
|
|
556
|
+
Judgment writes and judge-result ingestion check the answer form, probability bounds, choice keys, and score length against the question. A judgment request must contain questions; a non-aborted result that neither answers nor refuses a requested question is an error.
|
|
557
|
+
|
|
524
558
|
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.
|
|
525
559
|
|
|
526
560
|
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.
|
|
@@ -573,20 +607,21 @@ Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https
|
|
|
573
607
|
|
|
574
608
|
### Serving a conversation through a ledger
|
|
575
609
|
|
|
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
|
|
610
|
+
A ledger serves one conversation as event-sourced records with one record per owner. The `createLedger(provider, options)` factory returns a `LedgerInterface` value that owns the conversation, the agent that answers it, and that agent's tools, and its `respond` method appends a request as a user message and serves it through to the reply. The conversation is the event log. Each request reads the system message, which holds the `system` option and whatever instructions and skills the `agent` option supplies, then the context message when the `agent` option supplies memos or an active workspace, then a tail of the seed history (the messages added before the first request), then each completed exchange in the window as it was sent, then a copy of the request turn: the record lines the window doesn't hold, which the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. The window follows the seed without changing its selection. A request or a reply the window no longer holds re-enters a planned prompt through a labeled word match from the `recall` tool, and what a request's lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the run rejects under the default `strict`, and under `strict: false` the agent builds the prompt from the whole conversation view instead, earlier requests and replies included, with no records.
|
|
577
611
|
|
|
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
|
|
612
|
+
Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. An active `respond` call owns a run on that conversation whose request, the newest message, is that call's request or one of the ledger's notes. A run that no active `respond` call owns, such as a direct call to the agent's `generate` method or a run on another conversation, gets a faulted selection when its newest message is a user message: the selection's `fault` is a `LedgerError` with code `'REQUEST'`, so under the default `strict` the run rejects with that error before it reaches the provider, and under `strict: false` the agent emits `fault` and builds the prompt from the whole view of the run's conversation with no records. Either way the ledger asks its judge nothing for that run. When its newest message isn't a user message, the run gets no selection and builds from the whole view. Calibration admits no run, so a run during the `calibrate` method, or during the calibration that opens a `respond` call, is one that no active `respond` call owns.
|
|
579
613
|
|
|
580
614
|
The method has the following pieces, each named by its export:
|
|
581
615
|
|
|
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.
|
|
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
|
|
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
|
|
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
|
|
586
|
-
- **The
|
|
587
|
-
- **The
|
|
588
|
-
- **The
|
|
589
|
-
- **The
|
|
616
|
+
- **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. A user message carrying an id or a number, as read by `extractLiterals`, stays non-quiet regardless of its recorded weights. If its winning category is quiet, `category` returns `undefined`; this floor supplies no fact, rule, or correction judgment. Shape assignments keep their categories. Hydrating recorded judgments applies the same floor, and the next filing asks the topic questions those messages previously skipped. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. The `narrow` member of the `correction` option keeps only the eligible earlier messages that also share a registry entity with the correction or an id or a number in their content, so a desk topic alone admits no pair, and a correction with no id, owner, or desk topic still asks no pair. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, `narrow` took 24 judge calls and 45 s against 68 and 136 s at a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059), and 26 judge calls and 45 s against 109 and 196 s at a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883). Those calls include the category and topic questions `narrow` leaves in place. Filings were equal at those two corrections, on 5 pairs and 1 supersession. A third correction, forecast from recorded answers and not run, lost 0 of 8 pairs. The 173 pairs `narrow` drops across the three, 196 questions, filed 0 on recorded answers, on text whose corrections repeat a literal by construction, and the registry-entity path admitted no pair on this recording. A true supersession outside that set is never asked, and no run on any model measures how often one occurs. Set `narrow` when a correction's wait costs more than a missed supersession and your corrections repeat the id, number, or looked-up entity they correct. Leave it off for a host with no lookups or with free-text values. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. Under the default `strict`, a judge failure rejects the `respond` call it belongs to, after the `fault` event, and holds nothing, so the next request asks the judge again about every question still unanswered. A failure that repeats rejects that request too, so a question the judge always refuses stops each request until you remove its message or set `strict: false`. Under `strict: false`, a judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value ignores amendment and supersession marks whose later message is quiet and reads the remaining filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `ClassifierAttempt` value per logical filing question it attempted, in asking order, and observes the filing without changing it. An attempt names the question's key and its `ClassifierPhase` value, and its `ClassifierOutcome` value says whether the conversation already held the judgment (`cached`), the classifier held the question after a deterministic failure or because a message it names left the conversation (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal (`failed`), or was cut short by an abort (`aborted`). A `resolved`, `failed`, or `aborted` attempt carries the monotonic milliseconds the classifier waited on that call as `duration`, and a `cached` or `skipped` attempt carries none. A question that a caller abort preceded has no attempt, because it never began. The attempts count logical questions and resolve requests, never the physical wire calls a judge makes for them, and they record no join of pending requests. The `attempts` member of the `LedgerResult` value holds the attempts of the filing selections of that `respond` call alone; the `Selection` values the ledger emits carry none. A page passes `agent: { scheduler: createBrowserScheduler() }` from `@orkestrel/workflow/browser`, so the classifier hands the host a turn each time the `LEDGER_SLICE` constant's milliseconds have run while it files, and the plan after the filing still runs as one task; a page that omits the option also runs each stretch of cached filing as one task, and the host gets a turn only while the classifier waits on the judge. A direct `agent.context.select` for the same request during a paced filing's yield rejects with `AgentError` `'CONCURRENCY'`, and one for a message the call does not own returns a selection whose `fault` is `LedgerError` `'REQUEST'`. A `classify` call reads each message's quiet flag and near set at most once while it pairs corrections, so a judgment or message written during a pair-phase await reads at the next `classify` call, and `LedgerLookup.read` runs one time per tool message for each plan, each `recall` call, and each filing pass. The **What a cancel waits for.** bullet under [Production behaviors of automatic compaction](#production-behaviors-of-automatic-compaction) applies to this filing: what it names holds the run, and on a ledger its held scan, until it returns.
|
|
617
|
+
- **The records.** The `buildRecords` helper projects the filing into one `LedgerRecord` value per owner a lookup result names, plus one rules record for the rules and corrections no owner claims. Each line is a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. A message filed quiet or superseded isn't live. Accepted message-level amendments preserve every original indexed sentence of live earlier sources; the projection lists distinct accepted edges in its `amendments` member. Sentence scope remains unresolved. The `recall` tool and the answer note keep the stored content of each message they carry. The seed tail keeps stored content except for lookup results, which the plan replaces with stubs.
|
|
618
|
+
- **Amendment scope.** The first retained occurrence of an amended source opens with its `[N]` reference and a note on its later changes. Distinct retained sources receive decimal references starting at 1 in first-occurrence emission order, after deduplication. References are local to one rendering of the records and are recomputed after each trim; omitted sources do not shift them. A copy that follows a window numbers its sources after the ones the window holds, so one reference names one source across the window and that copy. Repeated occurrences share one reference. Recall and storage retain original source IDs. Authored content is unchanged. A fully included later source opens with its own [M] reference, and the earlier source's note reads “Changed later by [M].” If any effective correction is absent or partial, the note reads “A later change is not shown.” The omission note exposes no omitted identity, text, owner, or count. Completeness uses every original sentence identity after source deduplication and each trim; annotations count against the existing room. An edge whose amender a newer message superseded points at that amender's newest live successor, followed through accepted supersessions alone, so a change fully received by the records is not called not shown. With no live successor, the edge keeps its endpoint, which reads as absent. Neither restores the superseded text. An amendment of an amender infers no edge to the earlier message. Earlier text can conflict with its correction; downstream correction application and semantic sentence withdrawal remain unproved.
|
|
619
|
+
- **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the built head (the system message and the context message), the tail, and the copy of the request turn that carries the records inside a token budget: the `capacity` option less the `predict` option, times the `prompt` share, less the overhead cost of the gauge and held back by the `LEDGER_SCALE_DRIFT` constant, of which the seed tail takes at most the `tail` share. The `tail` share bounds only the seed. Owner records with the same member ids in the same order render once, under their titles joined with `; `; before trimming, the view keeps the first requested record's key, members, and lines. The projection and held sources stay unchanged. The plan budget bounds the records, the tail, and the window of a request's first call: it prices the built head, the tail, the window, and the copy with its records and images. Runtime recall and recovery fit their result groups separately. A request, a lookup result, or a faulted selection's whole view can still exceed the budget. The plan prices each lookup stub in the tail at the longer of its `shown` and `hidden` forms, so a tail that fits the plan still fits after the window and the copy decide which results they show. The `share` option sets both shares, and the `DEFAULT_LEDGER_SHARE` constant holds the defaults. Until the records fit, the ledger drops the rules off the request's topics, then the sources outside the selected records, then the rules on its topics, then the owner lines. Inside an owner record, it drops the lines whose source isn't a rule or a correction first, oldest first, then the lines of rules and corrections, oldest first. The `Gauge` class prices the prompt; without the `gauge` option, 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 reads `shown` when the window and the copy together hold its whole result or the whole result of a finding with the same canonical lookup identity and text. The plan reaches the agent as a `Selection` value whose `messages` member is the tail, then each exchange in the window, then the copy of the request turn that the `buildRequestMessage` helper writes: the record lines the window doesn't hold, a blank line, a `## Request` heading, and the request. A copy with no line to add is the request itself. The answer pass carries the same copy, and the stored request keeps its own content.
|
|
620
|
+
- **The window.** The ledger holds one `LedgerExchange` value per completed exchange: the request as it was sent, its final reply, and the record lines that copy rendered. Each prompt sends those exchanges in order, so a prompt extends the one before it, within the limits the **A follow-up can read the reply again.** bullet names. A copy holds only the record lines the window doesn't hold, matched by identity and never by text, so identical words under another source render with their own attribution. A titled record's line is held by record, source, and sentence, so a source under another owner's record renders again for its attribution. A line of a source outside the selected records, which renders under no title, is held by source and sentence under any placement, so it doesn't repeat what an earlier copy printed under a title. A line the window holds stays held whether or not a later request selects its record. The seed and the records are planned without the window, so the window spends only the spare room of the plan's total and never displaces a record line or a seed message. The plan prices the following rungs in order and sends the first whose prompt fits the total and, if that rung offers `recall`, leaves an open recall open: the whole window with a copy of the lines it doesn't hold, then the newest exchange with its request plain and a copy of every selected line, then no exchange and a copy of every selected line. When no rung meets both tests, the plan sends no exchange. A recall already closed with no exchange at all doesn't prevent admission. A fall to a lower rung is silent, with no note, and an answered request leaves the window as what it sent plus its own exchange, so the exchanges a fall left out don't return. An admitted window can reduce recall listing room without closing recall. Admission retains its reserve forecast. Runtime recall reads reported usage when available, including completion and replayed thinking, and fits its result without that reserve veto. The window empties when a message it holds changes or leaves the conversation, when a source it holds leaves the records, when the accepted amendments touching a message it holds change, when a request no longer pairs with the reply held for it, or when this request's lines would change an amendment note or reference an earlier copy printed. A source missing from this request's selected records empties nothing. An empty window derives the newest request and its final reply from the conversation, with the request plain, or nothing when the newest request holds no valid reply. A window a change empties keeps its last exchange, with the request plain, when the derive gives nothing because a later request failed and that exchange's reply still stands, so a stopped request doesn't lose the reply a person read. It never carries a removed reply, and it never falls back to an exchange older than that. A derived pair seats before the request is sent. A request that rejects or ends with no reply leaves the window as it stands, a seated derived pair included, so the next prompt holds the last good exchange. A request answered through the whole view under `strict: false` joins with its stored request plain and no lines. Tool calls, tool results, and ledger notes never enter the window, so a request that called a tool joins as its copy and its final reply.
|
|
621
|
+
- **The `recall` tool.** The tool requires a nonempty topic string; an empty topic fails argument admission. The ledger registers a `recall` tool beside the application's lookups and offers it only on a request with something to find: a user statement, including a quiet one, a lookup finding with a result, an earlier request, or a nonblank call-free reply that the seed tail, the window, and the copy together don't hold whole. A lookup stub doesn't hold its result, but a fully received finding with the same canonical lookup identity and text holds an identical finding's result too. A partly shown message counts as hidden, and a finding with no result never opens the offer. A ledger note and the current request's own turns never open the offer. The `collectRecallMessages` and `hasHiddenRecall` helpers read this per request from the conversation, so a hydrated ledger offers what the uninterrupted one offers. When nothing is hidden, the ledger narrows the agent's scope to the other tools for that request, keeping a host's allow-lists and selector, and the `respond` method restores the host's own scope when it settles, a rejection or an abort included, only while the plan's scope is still active. A scope the host applied in the meantime stays active. The tool's description reads that it finds something said earlier that isn't in the messages the model can see. It lists matching statements and lookup findings first, newest first, each source followed by the amenders the topic doesn't match itself; an amender the topic matches lists as its own newer item. It then lists earlier requests and call-free, non-empty assistant replies, newest first, under `Earlier request:` and `Earlier reply:`. A conversation match contains every word of at least one part of the topic, including when that part also names an owner. This conversation route excludes the current request and its turns, ledger notes, and messages already listed. It keeps the stored text, with each run of line breaks written as a line break and two spaces so that only a label opens a line, and it admits a partial reply the conversation stored before an abort. A hidden quiet statement can open the offer by itself, and a word match can list it. A cut landing mid-stream stores no reply and carries nothing. On the statement and lookup route, only lines opening with `Earlier request:` or `Earlier reply:` gain the same two-space indent; every other byte, including stored line breaks, stays unchanged. A label names the message's role, so a host-added assistant message in the seed reads as a reply too. These listings do not promote replies or requests into records. A search that finds nothing returns `nothing earlier on "TOPIC"; answer from the messages you can see`, where `TOPIC` is the searched topic, and that result enters no answer note. A blank topic still returns its guidance as a failure. The route reads the conversation and not the prompt, so it can list a request or a reply the window already carries. The tool fits whole items, including each source's amenders, into what the measured request leaves below capacity less predict, and names how many items it left out. An oversized item is omitted, and a later fitting item can still be returned. The result and its omission line share the allowance, with tool-message framing counted. When no item fits, the line reads `N older items didn't fit in this request; answer from the messages you can see`, using `item` for one and `more` for conversation matches. A partial listing keeps `N older items not shown; name a narrower topic to narrow the recall`. A gauged direct run fits its listing to the same allowance; with no gauge, the first whole item remains unconditional. The cut line uses `more` when an omitted item precedes a kept one in listing order, or when conversation matches are listed; otherwise it uses `older`. This rule applies to both omission forms. Statements and lookup findings take priority over conversation matches. A request can call it as many times as the `limit` member of the `recall` option allows, the `DEFAULT_RECALL_LIMIT` constant by default; after that it returns the `closure` note. Lack of room never closes recall: a distinct later call is fitted independently. The prefix uses the last call's reported prompt and completion, adjusted for replay by `Gauge.remainder`; missing usage uses an estimate. Additions use the larger of `Gauge.rate` and the latest reported call's prompt less known overhead divided by its estimate, with `LEDGER_SCALE_DRIFT` headroom. As in `Gauge.observe`, a partly spared call keeps the marginal rate instead of guessing an overhead share. Calls without reported usage use the marginal rate alone. Sibling recall results share the room. A listing within the `LEDGER_SCALE_DRIFT` margin of the room can be left out, with the omission line stating that it did not fit this request.
|
|
622
|
+
- **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 when its text differs. A finding with different text or an empty result replaces the earlier one, a finding with the same text replaces nothing, so the first unsuperseded finding of the final same-text run stays live, and a thrown call files no finding, leaving the earlier result live.
|
|
623
|
+
- **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. Before that pass, the ledger prices the rebuilt prompt at the same request-local rate. If it exceeds capacity less predict, it leaves a call-free partial assistant reply out of the prompt while keeping it stored, then fits the union of result groups to the remaining room. Source and amendment groups stay whole. Only the omission line the ledger appended is excluded from the digest; a literal line inside an accepted source group is preserved, even when its text matches an omission line; groups already represented by earlier groups enter no second copy. The `passes` member of the `LedgerResult` value holds both passes, and its `content` member is the last pass's. A rejected first pass counts as unfinished. When the answer pass rejects as well, the `respond` method rejects with that pass's error, and the ledger stays free for a later request.
|
|
624
|
+
- **The thinking budget.** The `predict` option reserves the generation room that thinking and the reply share, taking it out of the plan budget, the runtime recall room, and the answer prompt allowance. The plan's reserve-based admission rule stays unchanged. The gauge counts only the thinking the next request carries: under the provider's default `replay` of `'none'`, it leaves a call's thinking out of the capacity that call used, and the `computeThinking` helper apportions that thinking from the completion by character share. Under every policy, the reply reserve reads the reply without its thinking. The `think` option requests or suppresses thinking for the first pass, and omission leaves the provider's default; the answer pass always runs with thinking off. With replay `'none'`, a ledger at a `capacity` of `W + P` with a `predict` of `P`, where `W` is a context window and `P` a generation cap, budgets like a ledger at `W` without thinking.
|
|
590
625
|
|
|
591
626
|
Display references identify sources within the rendered records while the line keeps the stored identity:
|
|
592
627
|
|
|
@@ -615,30 +650,39 @@ The application supplies the following through `LedgerOptions`:
|
|
|
615
650
|
- the capacity, through the `capacity` option, the model's context window in tokens;
|
|
616
651
|
- the generation cap, through the `predict` option, in tokens with thinking included, 0 by default and less than `capacity`;
|
|
617
652
|
- 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,
|
|
653
|
+
- the state to hydrate from, through the `snapshot` option, which takes what a ledger's `snapshot` method returned: the conversation with its judgments, the marked request, note, and failed tool result ids, the gauge, which a `gauge` option overrides, and the window while it holds an exchange.
|
|
619
654
|
|
|
620
655
|
The method has the following documented limits:
|
|
621
656
|
|
|
622
657
|
- **The person prefix trusts capital letters.** A sentence that opens with a pronoun takes the last capitalized name of the sentence before it as its party, so a capitalized word that names no person, such as a carrier named mid-sentence, is read as the party.
|
|
623
658
|
- **A desk-wide correction stays in one owner's record.** A message that names an owner joins that owner's record and not the rules record, so a correction to a desk-wide rule stated inside one owner's message isn't among the rules a request about another owner reads.
|
|
624
659
|
- **Recall identity is the topic alone.** The repeat stop compares two `recall` calls by their trimmed `topic` argument, so a second call with the same topic is a repeat whatever other arguments it carries.
|
|
625
|
-
- **A
|
|
660
|
+
- **A change during a selection rejects the request.** A selection reads the conversation it was asked about, so a host append or removal while a `respond` call's selection runs faults it with a `changed during selection` error. Under the default `strict`, `respond` rejects with that error before it reaches the provider, and the ledger stays free for a later call. Under `strict: false`, the agent emits `fault` and builds the prompt from the whole view.
|
|
661
|
+
- **A direct run beside a request is refused.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`. Under the default `strict`, any other run no active `respond` call owns whose newest message is a user message rejects with `LedgerError` `'REQUEST'` before it reaches the provider: a direct run between requests, one during the calibration that opens a call, and a run on another conversation during a call. Under `strict: false` that run emits `fault` and goes on over the whole view with no ledger selection; a run on another conversation then adds its turns and usage to that call's gauge readings, shares its repeat stop, and can reach the lookup tools, and the `recall` tool when that call's request offers it, because the ledger's agent shares its scope across runs, and those tools read the ledger's `conversation`.
|
|
626
662
|
- **A run no call owns keeps no request state.** The ledger holds a request's state in a `LedgerRequest` value from the start of its `respond` call until the call settles. A run that no `respond` call owns, including a run during calibration, reads no request's state: its lookup and `recall` calls run with no repeat stop, recall limit, or close rule, and none of its turns reach a gauge reading.
|
|
627
663
|
- **A seed tool message counts as successful.** A tool message the application adds to the conversation has no recorded result, so the ledger reads it as a successful lookup and files it as a fact, and its reading handler decides what the result names.
|
|
628
664
|
- **An abort during calibration rejects.** When the caller's signal aborts while the ledger calibrates, the `respond` method rejects with the abort reason instead of resolving a partial result; after calibration, an abort ends the request partial and skips the answer pass.
|
|
629
665
|
- **A foreign signal rejects before anything is appended.** A `signal` that isn't a native `AbortSignal` rejects the `respond` method with a `ContractError` before the request is appended, and the ledger stays free for a later request.
|
|
630
|
-
- **
|
|
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.
|
|
632
|
-
- **The ledger refuses no over-window prompt.** A request, a lookup result,
|
|
633
|
-
- **A
|
|
666
|
+
- **The seed selection stays fixed.** Only the messages added before the first request form the seed tail. Each completed exchange follows it in the window: a request as it was sent and its last call-free assistant reply, excluding notes, calls, and tool messages. A blank or missing last call-free reply carries nothing. A committed partial reply means one the conversation stored; it remains eligible after an abort, but a cut landing mid-stream stores no reply and carries nothing. A host statement reaches the prompt through records or recall, and neither that statement nor a host lookup after the reply erases the exchange. Two non-empty call-free assistants without a ledger note between them make the pairing ambiguous, so it carries nothing; answer-pass notes establish the separation between a partial first reply and the final answer. A host that removes a request must remove every turn of it too, because nothing stored links a reply to its request: a surviving reply can read as the earlier request's when that request has no reply of its own, or when the removed request's answer pass left its note behind. The seed messages and the selected record lines stay the same on every rung of the window, and only a seed stub's `shown` or `hidden` state follows the rung.
|
|
667
|
+
- **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup with different text or an empty result replaces it, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows, and a line an earlier copy showed stays in the prompt until the window empties or falls past that copy.
|
|
668
|
+
- **The ledger refuses no over-window prompt.** A request, a lookup result, or the whole view a faulted selection builds from can exceed the room the `capacity` option leaves. Recall results and recovery digests are fitted, but unbounded mandatory content can still reach the provider, and the provider's own context limit decides what happens to it. A provider that refuses an over-long prompt fails the pass, so lower `capacity`, or set `AgentOptions.window` on an agent you drive yourself, to fold the conversation first.
|
|
669
|
+
- **A host edit after fitting enters unpriced.** A memo written during a request's first pass enters the rebuilt answer context and consumes its fitting allowance. A later host edit, after fitting, remains unpriced. The context can change while the selected seed and request stay the same.
|
|
634
670
|
- **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
|
|
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
|
|
638
|
-
- **A hydrated ledger asks a held question again.** A snapshot doesn't carry the questions
|
|
671
|
+
- **A lookup is a read.** A ledger lookup is a read; a tool whose call has a consequence is not a lookup, and a ledger refuses a `consequential` lookup at every call. `LedgerAgentOptions` carries no `authority`: the ledger passes its own, which allows the names it advertises (`recall` and each lookup) and denies every other name, so a `consequential` lookup meets the floor with no approver and is denied as unanswered, and a tool a host adds later reads `the ledger advertises no such tool`.
|
|
672
|
+
- **A snapshot's judgments are frozen records.** `LedgerInterface.snapshot().conversation` carries the stored deep-frozen judgments, so a write to one throws `TypeError` in strict-mode code, and a host copies a record through `copyJSON` before it migrates or redacts it. A host that migrates or redacts a snapshot can delete its `window` member as the clean path, because the stored copies repeat conversation text: the hydrated ledger derives the newest pair plain, and no stored copy keeps the old text in the snapshot's bytes or can send it.
|
|
673
|
+
- **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 its window admission starts with the longest stored reply as its reserve forecast. Runtime recall uses the current request's measurements; lost marginal-rate history can still change the fit, so live and hydrated calls can list different numbers of items. The window's rungs retain their reserve rule. A hydrated ledger sends what the uninterrupted one would when the live and hydrated reserves admit the same rung. A rung that lies between the two reserves can differ, which moves the prefix and never the record coverage.
|
|
674
|
+
- **A hydrated ledger asks a held question again.** A snapshot doesn't carry the questions a `strict: false` classifier held after a refused question or a deterministic judge failure, so a ledger hydrated from it asks each of them again in its next request.
|
|
675
|
+
- **A snapshot carries the window.** The `window` member of a `LedgerSnapshot` value is optional and present only while the window holds an exchange, so the snapshot of an empty window reads as one with no such member. A 0.0.36 snapshot holds none, reads as it did, and derives the newest pair plain. The `snapshot` method omits a window its conversation can't support, as after a host removes a held message, so a removal doesn't leave a snapshot that hydrating refuses. The `isLedgerSnapshot` guard reads a stored window's exact shape alone, so it refuses a malformed window or one with no `digest` member, and construction refuses that snapshot with `LedgerError` code `'SNAPSHOT'`. It reads no reference or sentence range, so a well-shaped window that names a removed message or sentence passes the guard, and hydrating discards it, because its digest disagrees or can't be computed.
|
|
676
|
+
- **A stored window carries a digest.** The `window` member of a snapshot holds a required `digest` member, a checksum the `digestLedgerWindow` helper computes over the canonical form of its held messages, each request, reply, and record line's source, every lookup result and every message holding a call, because an owner heading can print a lookup no line holds, its stored copies, and its sentence receipts. An edit to any of those, by a host migrating or redacting, makes the digest disagree: hydrating discards the whole window and the ledger derives the newest pair from the edited conversation, so old held text doesn't reach a provider. A digest that can't be computed discards the window the same way. The digest detects an edit, can collide, and makes no security claim. The canonical form sorts keys, so a store that reorders them doesn't make the digest disagree. A held message the canonical form can't render, such as one with an `undefined` tool argument, makes the `snapshot` method omit the window. A held lookup's call arguments count too, through the assistant message that made the call.
|
|
677
|
+
- **A follow-up can read the reply again.** A model server that keeps a prompt cache reuses a prompt that extends the last. On a model whose generation prefix differs from how it renders a reply in history, the server reads the reply itself again, so a follow-up costs the reply plus the text the last prompt didn't hold: small with short replies, and larger with long ones. After a request that called a tool, the prompt shares its prefix only through that request's copy, because tool calls and results stay out of the window, so that reply is read again on any model. Anything ahead of the window moves the prefix too: a system or instruction edit, a memo or workspace change in the context message, a seed stub whose `shown` or `hidden` state flips, and a seed exchange whose cut moves when the gauge rescales. So do an emptied window, a fall to a lower rung, a workspace image, which attaches to the last user message, and a reply whose thinking the `replay` policy leaves out.
|
|
678
|
+
- **A changed lookup empties the window.** A later finding of the same lookup with different text or an empty result retires the source the window holds, and that empties the window. That prompt holds the derived newest pair and a copy of every selected line, so it doesn't extend the prompt before it. A lookup repeated with the same text retires nothing, so the prompt extends the one before it.
|
|
679
|
+
- **A cut stream stores nothing.** A stream cut before its reply is stored leaves the window standing, so a follow-up that refers to the cut text reads against the last completed reply.
|
|
680
|
+
- **Recall fitting depends on its measured price.** Runtime recall and recovery allow the `LEDGER_SCALE_DRIFT` margin over the larger of the gauge's marginal rate and this request's measured rate. A provider whose new text costs more than that bound is outside the capacity guarantee. Missing usage remains estimated; no exact tokenizer preflight is available. A long earlier reply still affects window admission, but never vetoes a runtime recall that fits.
|
|
681
|
+
- **A replaced seed lookup keeps its stub.** When a later finding of the same lookup with different text replaces a seed lookup, the seed stub reads `result not shown` while a later copy can print the replacing result, unless the window and the copy fully receive a finding with the same canonical lookup identity and text as the seed finding. That full receipt makes a duplicate stub read `shown`, even when its own source is retired.
|
|
682
|
+
- **A change can sit beside its not-shown note.** When an amender was superseded with no live successor, or when a later message amends the amender and files no edge of its own to the earliest message, the earliest message's note reads “A later change is not shown.” beside a change the copy prints, because no other edge is inferred. The note can also read this way when the change sits raw in the seed tail, because the record's amendment rendering doesn't read that tail.
|
|
639
683
|
- **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
|
|
684
|
+
- **The `narrow` member can hide a supersession.** The ledger never compares an earlier message that shares only a desk topic with the correction, so a supersession on a pair sharing no registry entity and no id or number is never filed. For example, "the refund limit is 500" then "no, the refund limit is 600" shares no literal, so with no shared registry entity `narrow` never asks about that pair, where the unset rule does. In the reading of 2026-11-06, of 12 corrections two blind readers agreed on, across ABCD and Taskmaster-1, 8 carry no id or number and 4 carry only the new value, and none repeats the old one. Read those messages alone, because their dialogs weren't at hand, so only a shared registry entity could admit their pairs.
|
|
685
|
+
- **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction recorded on 2026-11-03 under **The filing.**, one correction asked 98 pair questions over 93 earlier messages, inside 109 judge calls and 196 s on the Mica v0.1 4B judge. The `narrow` member lowers them, and the caller's abort signal ends them.
|
|
642
686
|
|
|
643
687
|
### Customizing the format (the cascade)
|
|
644
688
|
|
|
@@ -681,7 +725,7 @@ When a provider's model has a framing preference, such as XML tags, install that
|
|
|
681
725
|
|
|
682
726
|
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
727
|
|
|
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`
|
|
728
|
+
`ProviderInterface` is the boundary; `AgentProvider` is the engine behind it. Every HTTP-backed provider needs the same machinery — a deadline, a transport, an authorization hook, a bounded error read, a chunk decoder, reasoning separation, and result assembly — and rewriting that per vendor is how a fleet of providers drifts apart. `AgentProvider` owns all of it and leaves exactly one thing open: the wire. A subclass supplies `name` and the wire seams — `frame()` returns fresh framing state for the call, `encode(request)` projects a `ProviderRequest` onto the vendor's request shape, `read(record)` decodes one framed record into a `ProviderIncrement`, and `finish(parser)` returns whatever the parser still held at end of input. The engine is generic over `TRecord`: the record type a call's `frame()` parser emits and `read` consumes, defaulting to `Readonly<Record<string, unknown>>` for a wire whose records are JSON objects. The constructor switches decide the rest: `split` separates in-content `<think>` reasoning from the answer (default `true`), and `strict` refuses a stream that ends with neither a settled `result` nor a `done` record, because it was cut (default `true`); a wire with no terminal record passes `strict: false` to assemble at end of input.
|
|
685
729
|
|
|
686
730
|
```ts
|
|
687
731
|
import type { AgentProviderInput, ProviderInterface } from '@orkestrel/agent'
|
|
@@ -698,7 +742,7 @@ const provider = createTextProvider({
|
|
|
698
742
|
timeout: 30_000, // the base's own deadline; DEFAULT_PROVIDER_TIMEOUT when omitted
|
|
699
743
|
headers: async (signal) => ({ authorization: await token(signal) }), // awaited inside that deadline
|
|
700
744
|
split: true, // route <think> spans to `thinking`, yield the clean answer
|
|
701
|
-
strict: false, // assemble at end of input instead of
|
|
745
|
+
strict: false, // this wire has no terminal record: assemble at end of input instead of refusing
|
|
702
746
|
})
|
|
703
747
|
const result = await provider.generate(messages, abort.signal)
|
|
704
748
|
result.content // the assembled answer, with any <think> span routed to result.thinking
|
|
@@ -709,7 +753,7 @@ result.content // the assembled answer, with any <think> span routed to result.t
|
|
|
709
753
|
The engine's failures arrive as one error class. A `ProviderError` carries a machine-readable `code` and, for an HTTP failure alone, the response `status`; `isProviderError` narrows a caught value so a caller can branch on the code:
|
|
710
754
|
|
|
711
755
|
- `'HTTP'` — a non-OK response. The message is `provider error: <status>`, with ` - <excerpt>` appended only when the response body carried text. The excerpt is read to at most `MAX_ERROR_BODY_LENGTH` bytes and the remainder of the body is cancelled, so a stalled error body can't hold the call open past its deadline.
|
|
712
|
-
- `'PROTOCOL'` — a successful response with no body, a line the provider's framing refuses, a wire record the concrete provider refuses,
|
|
756
|
+
- `'PROTOCOL'` — a successful response with no body, a line the provider's framing refuses, a wire record the concrete provider refuses, a stream that ended with no settled result and no terminal record, or a result or delta that breaks the published contract at the agent's door. A throw from a provider's framing seam (its parser's `parse` or the provider's `finish`) that races no cancel and is not already a `ProviderError` or `ProviderAbortError` rejects with this code and carries that throw as its `cause`.
|
|
713
757
|
- `'PROVIDER'` — an upstream failure a relay reported in an `error` frame.
|
|
714
758
|
|
|
715
759
|
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.
|
|
@@ -726,7 +770,7 @@ The provider's `replay` member decides which recorded thinking goes back to the
|
|
|
726
770
|
|
|
727
771
|
Choose `'turn'` for a backend that reads thinking inside a tool loop. Some chat formats keep the thinking of the turn in progress and drop older thinking, such as the Qwen3 template (see [the Qwen3 model card](https://huggingface.co/Qwen/Qwen3-235B-A22B)), and some APIs refuse a tool turn that leaves out its thinking, such as DeepSeek's (see [DeepSeek thinking mode](https://api-docs.deepseek.com/guides/thinking_mode)). The `thinking` member is a plain string, so it can't carry a signature that an API requires beside the text, such as Anthropic's (see [Anthropic extended thinking](https://platform.claude.com/docs/en/build-with-claude/thinking)).
|
|
728
772
|
|
|
729
|
-
The agent loop, a relay server, and a ledger apply the policy before calling the provider. A direct `generate` or `stream` call sends messages as given. The agent applies the policy through `stripThinking` before every provider call and before every compaction estimate, and a provider without a `replay` member counts as `'none'`. `estimateRequest` counts a message's `thinking`, so the `window` budget counts the thinking the request carries and no other. A ledger applies the same policy to the tail it plans and each call it measures, and calibration applies the policy at the next user boundary, as if a user message followed the conversation view. Calibration prices the whole view; a planned request carries only the selected tail, so the retained messages can differ.
|
|
773
|
+
The agent loop, a relay server, and a ledger apply the policy before calling the provider. A direct `generate` or `stream` call sends messages as given. The agent applies the policy through `stripThinking` before every provider call and before every compaction estimate, and a provider without a `replay` member counts as `'none'`. `estimateRequest` counts a message's `thinking`, so the `window` budget counts the thinking the request carries and no other. A ledger applies the same policy to the tail and the window it plans and each call it measures, and calibration applies the policy at the next user boundary, as if a user message followed the conversation view. Calibration prices the whole view; a planned request carries only the selected tail, so the retained messages can differ.
|
|
730
774
|
|
|
731
775
|
A relay applies both policies. The agent in the browser strips the request by the policy of its `RelayProvider`, the request carries each remaining `thinking` member, and `RelayStream` strips it again by the upstream provider's policy, so the upstream call carries only the thinking that both policies keep.
|
|
732
776
|
|
|
@@ -763,11 +807,11 @@ turn.filter((message) => 'thinking' in message).map(({ id }) => id) // ['4'] —
|
|
|
763
807
|
|
|
764
808
|
### The judge engine
|
|
765
809
|
|
|
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).
|
|
810
|
+
The `JudgeInterface` contract is the decision boundary beside `ProviderInterface`, and it is never a provider. Its `ask(request, signal)` method answers typed questions about one state with a probability distribution per question. A `JudgeRequest` carries the `state` and the `questions` keyed by your own ids, which the prompt never carries; each question is a `ChoiceQuestion`, a `ScoreQuestion`, or a `NoulQuestion`, named by its `form` member. A `JudgeResult` carries the answering model in its `model` member, the `answers` map keyed by the same ids, the `refusals` map of the questions a wire refused, and the `usage` member with the tokens the calls spent; a call whose response reports no complete usage bills the estimate of its response text, as a provider call does. An answer stores only the distribution the server returned: `probabilities` for a choice or a score, and `noul`, the probability of yes, for a noul question. A choice answer names every criterion of its question, a score is as long as its levels, and each probability is in `[0, 1]`: `AgentJudge` refuses any other answer with `JudgeError` `'PROTOCOL'`, and a judgment write with `ConversationError` `'JUDGMENT'`. The `measureAnswer` function derives every measure from that distribution, so every server reads on one scale and no stored measure can drift from its distribution (the derived-measure clause).
|
|
767
811
|
|
|
768
812
|
The `AgentJudge` class is the engine behind that boundary, as the `AgentProvider` class is the engine behind `ProviderInterface`. It owns each call's deadline, the transport, the `headers` hook, the validation before inference, the bounded error read, and the merge of every call's result, and it leaves the wire open: a subclass supplies `name`, `encode(request)`, which projects one call's `JudgeRequest` onto the protocol's request shape, and `read(value, request)`, which decodes one call's parsed response into a `JudgeResult`. A one-shot JSON response has no framing state and no buffered tail, so the engine has no `frame` or `finish` seam. In place of the `split` and `strict` switches it takes one `batch` switch: `true`, the default, sends every question in one call, and `false` sends one call per question in key order.
|
|
769
813
|
|
|
770
|
-
The `SystemOneJudge` class is the wire this package ships on that engine, and the `createSystemOneJudge` factory returns it behind `JudgeInterface`. It speaks the System One decision protocol at `SYSTEM_ONE_PATH` and sends every question in one call. See [Asking a System One server a choice, a noul, and a score](#asking-a-system-one-server-a-choice-a-noul-and-a-score) for the servers it serves and a whole request; see [Writing a judge wire](#writing-a-judge-wire) for a wire of your own.
|
|
814
|
+
The `SystemOneJudge` class is the wire this package ships on that engine, and the `createSystemOneJudge` factory returns it behind `JudgeInterface`. It speaks the System One decision protocol at `SYSTEM_ONE_PATH` and sends every question in one call. Wire keys are zero-based positions in the request's question entry order. It maps answers back to the caller's ids, and a missing or invalid answer names the caller's id in its `PROTOCOL` error. Changing only the caller's ids preserves the request bytes. See [Asking a System One server a choice, a noul, and a score](#asking-a-system-one-server-a-choice-a-noul-and-a-score) for the servers it serves and a whole request; see [Writing a judge wire](#writing-a-judge-wire) for a wire of your own.
|
|
771
815
|
|
|
772
816
|
The engine's failures arrive as one error class. A `JudgeError` carries a machine-readable `code` and, for an HTTP failure alone, the response `status`; the `isJudgeError` function narrows a caught value so a caller can branch on the code:
|
|
773
817
|
|
|
@@ -867,12 +911,19 @@ The following table lists the errors the root declares and the guards that narro
|
|
|
867
911
|
|
|
868
912
|
The following table lists the root wire shapes and the contract compiled from them:
|
|
869
913
|
|
|
870
|
-
| Name
|
|
871
|
-
|
|
|
872
|
-
| `toolCallShape`
|
|
873
|
-
| `messageShape`
|
|
874
|
-
| `
|
|
875
|
-
| `
|
|
914
|
+
| Name | Kind | Signature | Summary |
|
|
915
|
+
| ----------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
916
|
+
| `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. |
|
|
917
|
+
| `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. |
|
|
918
|
+
| `messageInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a message input's JSON projection: a `messageShape` with no `id`, which the storing conversation mints. |
|
|
919
|
+
| `judgeEntryShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>` | Describes the text or JSON a judge reads: a non-empty string, a non-empty JSON array, or a JSON record. |
|
|
920
|
+
| `judgeQuestionShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>` | Describes a judge question: one exact object per form, the schema an LLM-facing wire can publish. |
|
|
921
|
+
| `judgeAnswerShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>` | Describes a judge answer: one exact object per form, each probability in `[0, 1]`. |
|
|
922
|
+
| `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. |
|
|
923
|
+
| `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. |
|
|
924
|
+
| `messageInputContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>>` | Reads the faults of a refused message input and validates a job's seed messages. |
|
|
925
|
+
| `judgeQuestionContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>>` | Reads the faults of a refused judge question. |
|
|
926
|
+
| `judgeAnswerContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>>` | Reads the faults of a refused judge answer. |
|
|
876
927
|
|
|
877
928
|
#### Cloners
|
|
878
929
|
|
|
@@ -887,32 +938,37 @@ The following table lists the cloners the root declares:
|
|
|
887
938
|
|
|
888
939
|
The following table lists the helpers the root declares:
|
|
889
940
|
|
|
890
|
-
| Name
|
|
891
|
-
|
|
|
892
|
-
| `filterAllowList`
|
|
893
|
-
| `sanitizeToken`
|
|
894
|
-
| `sanitizeUsage`
|
|
895
|
-
| `joinThinking`
|
|
896
|
-
| `stripThinking`
|
|
897
|
-
| `sumUsage`
|
|
898
|
-
| `
|
|
899
|
-
| `
|
|
900
|
-
| `
|
|
901
|
-
| `
|
|
902
|
-
| `
|
|
903
|
-
| `
|
|
904
|
-
| `
|
|
905
|
-
| `
|
|
941
|
+
| Name | Kind | Signature | Summary |
|
|
942
|
+
| ------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
943
|
+
| `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. |
|
|
944
|
+
| `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. |
|
|
945
|
+
| `sanitizeUsage` | function | `(usage: TokenUsage) => TokenUsage` | Sanitizes a `TokenUsage` into non-negative integers — the guard an agent's abort-usage path applies to a provider's partial usage before it is charged against a budget or folded into the run total, because a cancelled stream has no settled result to refuse; a settled result's usage crosses the provider-result door instead. |
|
|
946
|
+
| `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. |
|
|
947
|
+
| `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. |
|
|
948
|
+
| `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. |
|
|
949
|
+
| `describeSnapshotRefusal` | function | `(noun: string, id: unknown, faults: readonly AuditFault[]) => string` | Describes a snapshot a store refuses, naming its id, the first fault, and what a host does about it. |
|
|
950
|
+
| `describeQuestionRefusal` | function | `(id: string, faults: readonly AuditFault[], schema: JSONSchema) => string` | Describes why a judge question refuses, in the text both of its doors throw. |
|
|
951
|
+
| `scanJudgmentTies` | function | `(question: JudgeQuestion, answer: JudgeAnswer) => readonly AuditFault[]` | Scans what a judge's answer must hold to its question: the same form, every probability in `[0, 1]`, a choice's keys equal to the criteria keys, and a score as long as its levels. |
|
|
952
|
+
| `scanProbability` | function | `(value: number \| undefined, path: readonly string[]) => readonly AuditFault[]` | Scans one probability against `[0, 1]`. |
|
|
953
|
+
| `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. |
|
|
954
|
+
| `collectExchanges` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects whole exchanges, joining every exchange spanned by a tool group. |
|
|
955
|
+
| `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. |
|
|
956
|
+
| `hasCalls` | function | `(message: Pick<Message, 'calls'>) => boolean` | Checks whether a message carries at least one tool call. |
|
|
957
|
+
| `renderJSON` | function | `(value: unknown) => string \| undefined` | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
|
|
958
|
+
| `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. |
|
|
959
|
+
| `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. |
|
|
960
|
+
| `extractLiterals` | function | `(text: string) => LiteralSet` | Reads the ids and the numbers of a text. |
|
|
906
961
|
|
|
907
962
|
#### Validators
|
|
908
963
|
|
|
909
964
|
The following table lists the guards the root declares:
|
|
910
965
|
|
|
911
|
-
| Name | Kind | Signature | Summary
|
|
912
|
-
| -------------------------- | -------- | -------------------------------------------- |
|
|
913
|
-
| `isJudgeEntry` | function | `(value: unknown) => value is JudgeEntry` | Checks whether a value is a judge entry: a string, a JSON record, or a JSON array.
|
|
914
|
-
| `
|
|
915
|
-
| `
|
|
966
|
+
| Name | Kind | Signature | Summary |
|
|
967
|
+
| -------------------------- | -------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
968
|
+
| `isJudgeEntry` | function | `(value: unknown) => value is JudgeEntry` | Checks whether a value is a judge entry: a non-empty string, a non-empty JSON record, or a non-empty JSON array. |
|
|
969
|
+
| `isJudgeAnswer` | function | `(value: unknown) => value is JudgeAnswer` | Checks whether a value is a stored judge answer of the choice, score, or noul form. |
|
|
970
|
+
| `isJudgeQuestion` | function | `(value: unknown) => value is JudgeQuestion` | Checks whether a value is a well-formed judge question of the choice, score, or noul form. |
|
|
971
|
+
| `isNonNegativeSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a non-negative safe integer, `-0` included. |
|
|
916
972
|
|
|
917
973
|
### Providers module
|
|
918
974
|
|
|
@@ -930,12 +986,12 @@ The following table lists the types the providers module declares:
|
|
|
930
986
|
| `ProviderInterface` | interface | `{ id, name, replay?, generate(), stream() }` | Defines the pluggable LLM inference boundary — the one contract every agent chunk depends on. A provider turns a conversation (plus optional tools) into either a single assembled `ProviderResult` (`generate`) or a stream of `ProviderDelta` values that returns the assembled result (`stream`). The agent loop, a relay server, and a ledger apply its `replay` policy before calling it. A direct `generate` or `stream` call sends messages as given. |
|
|
931
987
|
| `ProviderParserInterface` | interface | `{ parse(), clear() }` | Defines the structural framing seam supplied by a concrete provider. |
|
|
932
988
|
| `ProviderRequest` | interface | `{ messages, tools?, options? }` | Carries the conversation and per-call configuration sent to a provider. |
|
|
933
|
-
| `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result? }`
|
|
989
|
+
| `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result?, done? }` | Holds the decoded contribution of a wire record to a provider turn. |
|
|
934
990
|
| `ProviderOptions` | interface | `{ timeout?, replay?, fetch?, headers? }` | Configures a provider's deadline, transport, and headers. |
|
|
935
991
|
| `AgentProviderInput` | interface | `{ url, path?, split?, strict? }` | Configures the HTTP destination and stream assembly of a provider base. |
|
|
936
992
|
| `AgentProviderInterface` | interface | `{ frame(), encode(), read(), finish() }` | Defines the wire-specific seams of the shared HTTP provider engine. |
|
|
937
993
|
| `ProviderErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'PROVIDER'` | Names the machine-readable provider failure conditions. |
|
|
938
|
-
| `ProviderErrorOptions` | interface | `{ status?, cause? }`
|
|
994
|
+
| `ProviderErrorOptions` | interface | `{ status?, cause?, context? }` | Carries a provider failure's HTTP status and underlying cause. |
|
|
939
995
|
| `FailureRead` | interface | `{ message, status, cause? }` | Carries an HTTP failure message, the response status, and the underlying body-read cause when available. |
|
|
940
996
|
| `TextRead` | interface | `{ text, complete }` | Carries a decoded stream prefix and whether the stream ended within its byte budget. |
|
|
941
997
|
| `RelayFrame` | type | `ProviderDelta \| { readonly channel: 'result'; readonly result: ProviderResult; } \| { readonly channel: 'abort'; readonly partial: ProviderResult; } \| { readonly channel: 'error'; readonly message: string; }` | Carries a relay delta, settled result, remote abort, or remote failure. |
|
|
@@ -1059,32 +1115,35 @@ The following table lists the classes the providers module declares:
|
|
|
1059
1115
|
|
|
1060
1116
|
The following table lists the helpers the providers module declares:
|
|
1061
1117
|
|
|
1062
|
-
| Name | Kind | Signature | Summary
|
|
1063
|
-
| ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1064
|
-
| `
|
|
1065
|
-
| `
|
|
1066
|
-
| `
|
|
1067
|
-
| `
|
|
1068
|
-
| `
|
|
1069
|
-
| `
|
|
1070
|
-
| `
|
|
1071
|
-
| `
|
|
1072
|
-
| `
|
|
1073
|
-
| `
|
|
1074
|
-
| `
|
|
1075
|
-
| `
|
|
1076
|
-
| `
|
|
1077
|
-
| `
|
|
1078
|
-
| `
|
|
1118
|
+
| Name | Kind | Signature | Summary |
|
|
1119
|
+
| ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1120
|
+
| `readProviderDelta` | function | `(value: unknown) => ProviderDelta \| undefined` | Reads a foreign delta's two members once into an owned copy, the value a run checks and consumes. |
|
|
1121
|
+
| `requireProviderResult` | function | `(value: unknown) => ProviderResult` | Owns a provider's settled result: reads each published member of the foreign value once into a fresh record, checks that copy, and returns it, or throws a coded error the run rejects with. |
|
|
1122
|
+
| `buildProviderResult` | function | `(content: string, thinking: string, tools: readonly ToolCall[], usage: TokenUsage \| undefined, truncated: boolean \| undefined) => ProviderResult` | Assembles a provider result with only populated optional fields. |
|
|
1123
|
+
| `armReaderAbort` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>, signal: AbortSignal \| undefined) => Promise<AbortController>` | Arms signal propagation to a byte reader and returns the controller that removes the listener. |
|
|
1124
|
+
| `readFailure` | function | `(response: Response, prefix: string, signal: AbortSignal) => Promise<FailureRead>` | Reads a bounded HTTP failure excerpt and preserves an unreadable body's cause. |
|
|
1125
|
+
| `readBodyText` | function | `(body: ReadableStream<Uint8Array>, limit?: number, signal?: AbortSignal) => Promise<TextRead>` | Reads a UTF-8 prefix of a byte stream and cancels its remainder. |
|
|
1126
|
+
| `readChunks` | function | `(body: ReadableStream<Uint8Array>, signal?: AbortSignal) => AsyncGenerator<string>` | Decodes UTF-8 chunks with a final flush and releases the stream on every exit. |
|
|
1127
|
+
| `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. |
|
|
1128
|
+
| `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. |
|
|
1129
|
+
| `buildJudgeResult` | function | `(model: string, results: readonly JudgeResult[]) => JudgeResult` | Merges the results of a judge request's calls into one result. |
|
|
1130
|
+
| `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. |
|
|
1131
|
+
| `requestToRelay` | function | `(request: ProviderRequest) => ProviderRequest` | Projects a provider request onto the declared members the relay wire carries. |
|
|
1132
|
+
| `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. |
|
|
1133
|
+
| `describeRelayRefusal` | function | `(refusal: RelayRefusal) => string` | Describes one relay refusal as the line its `422` response body carries. |
|
|
1134
|
+
| `questionToSystemOne` | function | `(question: JudgeQuestion) => SystemOneQuestion` | Projects a judge question onto the System One wire while preserving omitted members. |
|
|
1135
|
+
| `extractSystemOneAnswer` | function | `(answer: SystemOneAnswer, question: JudgeQuestion) => JudgeAnswer \| undefined` | Extracts a System One distribution in question criteria order and drops server measures. |
|
|
1136
|
+
| `extractSystemOneUsage` | function | `(usage: SystemOneUsage \| undefined) => TokenUsage \| undefined` | Maps complete System One token counts onto validated token usage. |
|
|
1079
1137
|
|
|
1080
1138
|
#### Validators
|
|
1081
1139
|
|
|
1082
1140
|
The following table lists the guards the providers module declares:
|
|
1083
1141
|
|
|
1084
|
-
| Name | Kind | Signature | Summary
|
|
1085
|
-
| --------------------- | -------- | ------------------------------------------------ |
|
|
1086
|
-
| `isSystemOneResponse` | function | `(value: unknown) => value is SystemOneResponse` | Checks whether a value is a System One response envelope with optional model and usage.
|
|
1087
|
-
| `
|
|
1142
|
+
| Name | Kind | Signature | Summary |
|
|
1143
|
+
| --------------------- | -------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1144
|
+
| `isSystemOneResponse` | function | `(value: unknown) => value is SystemOneResponse` | Checks whether a value is a System One response envelope with optional model and usage. |
|
|
1145
|
+
| `isProviderResult` | const | `Guard<ProviderResult>` | Checks whether a value carries the members `ProviderResult` publishes: a string `content`, and `thinking`, `tools`, `usage`, and `truncated` absent or of their published types. |
|
|
1146
|
+
| `isSystemOneAnswer` | function | `(value: unknown) => value is SystemOneAnswer` | Checks whether a value is a System One answer whose type and distribution the wire can read. |
|
|
1088
1147
|
|
|
1089
1148
|
### Conversations module
|
|
1090
1149
|
|
|
@@ -1110,7 +1169,7 @@ The following table lists the types the conversations module declares:
|
|
|
1110
1169
|
| `ConversationSnapshot` | interface | `{ id, judgments?, sections, messages }` | Holds a JSON-serializable snapshot of the state of a conversation — its `id`, the compacted `sections`, and the live tail `messages` — the durable payload the `ConversationStoreInterface` persists. The exact analogue of `WorkspaceSnapshot`. |
|
|
1111
1170
|
| `ConversationStoreInterface` | interface | `{ get(), set(), delete() }` | Persists a `ConversationSnapshot` durably — the async `get` / `set` / `delete` primitives, keyed by a conversation id and holding no expiry, the exact analogue of `WorkspaceStoreInterface`. |
|
|
1112
1171
|
| `ConversationSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseConversationStore` persists — a conversation `id` plus its `ConversationSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. The exact analogue of `WorkspaceSnapshotRow`. |
|
|
1113
|
-
| `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'SNAPSHOT'`
|
|
1172
|
+
| `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID'` | Names the machine-readable condition a `ConversationError` reports. |
|
|
1114
1173
|
| `JudgmentManagerInterface` | interface | `{ count, add(), judgment(), judgments(), remove(), clear(), resolve() }` | Stores judgments by caller key and resolves requests by reusing matching records. |
|
|
1115
1174
|
|
|
1116
1175
|
#### Constants
|
|
@@ -1126,10 +1185,10 @@ The following table lists the constants the conversations module declares:
|
|
|
1126
1185
|
|
|
1127
1186
|
The following table lists the errors the conversations module declares and the guards that narrow them:
|
|
1128
1187
|
|
|
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
|
|
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`.
|
|
1188
|
+
| Name | Kind | Signature | Summary |
|
|
1189
|
+
| --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1190
|
+
| `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap that is not a positive safe integer, a `keep` that is not a nonnegative safe integer, a summarizer digest whose trimmed text is empty, a judgment or judge request that JSON cannot carry, a stored or selected message whose role is not a conversation role, or a malformed snapshot — thrown by the `compact()` and `add` methods of a `ConversationInterface`, its construction, or its judgment store, or returned as the `fault` of an agent selection, carrying the machine-readable `code` `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP' \| 'SUMMARY' \| 'ROLE' \| 'MESSAGE' \| 'SNAPSHOT' \| 'ID'`. |
|
|
1191
|
+
| `isConversationError` | function | `(value: unknown) => value is ConversationError` | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
|
|
1133
1192
|
|
|
1134
1193
|
#### Factories
|
|
1135
1194
|
|
|
@@ -1164,10 +1223,13 @@ The following table lists the helpers the conversations module declares:
|
|
|
1164
1223
|
| `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
1224
|
| `requireJudgment` | function | `(value: unknown) => Judgment` | Returns a stored judgment record after checking it, or throws a coded error. |
|
|
1166
1225
|
| `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`
|
|
1168
|
-
| `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking
|
|
1226
|
+
| `requireConversationSnapshot` | function | `(value: unknown, contract: Pick<ContractInterface<unknown>, 'audit' \| 'schema'>) => ConversationSnapshot` | Returns a conversation snapshot after checking its shape, its stored roles, and its ids, or throws a coded error. |
|
|
1227
|
+
| `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking it is a positive safe integer, or throws a coded error. |
|
|
1169
1228
|
| `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
1229
|
| `requireKeep` | function | `(keep: number) => number` | Returns a retained-tail size after checking it is a nonnegative safe integer, or throws a coded error. |
|
|
1230
|
+
| `requireMessageInput` | function | `(input: unknown, contract: Pick<ContractInterface<unknown>, 'audit' \| 'schema'>) => MessageInput` | Returns a message input after checking its role and its members, or throws a coded error. |
|
|
1231
|
+
| `readJudgeOutcome` | function | `(result: JudgeResult, id: string) => { readonly answer: JudgeAnswer \| undefined; readonly refusal: Refusal \| undefined; }` | Reads what a judge result holds for one question, from its own keys alone. |
|
|
1232
|
+
| `requireJudgeResult` | function | `(request: JudgeRequest, result: JudgeResult) => void` | Returns after checking a complete judge result answered or refused every question it was asked, or throws a coded error naming those it left out. |
|
|
1171
1233
|
| `requireSummary` | function | `(summary: string) => string` | Returns a summarizer digest after checking it carries non-whitespace text, or throws a coded error. |
|
|
1172
1234
|
| `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
1235
|
| `buildJudgments` | function | `(request: JudgeRequest, result: JudgeResult, sources: readonly string[], state: string, model: string) => readonly JudgmentInput[]` | Builds records for answered or refused request keys, attaching usage only for a single question. |
|
|
@@ -1176,15 +1238,22 @@ The following table lists the helpers the conversations module declares:
|
|
|
1176
1238
|
|
|
1177
1239
|
The following table lists the guards the conversations module declares:
|
|
1178
1240
|
|
|
1179
|
-
| Name | Kind | Signature | Summary |
|
|
1180
|
-
| ------------------------ | -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1181
|
-
| `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
|
|
1182
|
-
| `isSection` | function | `(value: unknown) => value is Section` | Checks whether an `unknown` is structurally a `Section` record — a `string` `id` and `summary` beside a `messages` array of valid `Message` records, the per-section step of the `isConversationSnapshot` read-boundary narrow. Total, never throwing, and never an assertion. |
|
|
1183
|
-
| `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id` and valid `sections` and `messages` arrays; the total boundary guard for an untrusted snapshot read (a storage row a `DatabaseConversationStore` reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact analogue of `isWorkspaceSnapshot`. |
|
|
1184
|
-
| `isConversation` | function | `(value: unknown) => value is ConversationInterface` | Checks whether a value carries the `ConversationInterface` members a run reads: a string `id`, a boolean `summarizable`, and `view`, `add`, `compact`, and `messages` methods. |
|
|
1185
|
-
| `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
|
|
1186
|
-
|
|
1187
|
-
A `DatabaseConversationStore` reads its snapshot column back as `unknown` and narrows it through `isConversationSnapshot`, so a malformed blob resolves `undefined` rather than a broken conversation:
|
|
1241
|
+
| Name | Kind | Signature | Summary |
|
|
1242
|
+
| ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1243
|
+
| `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
|
|
1244
|
+
| `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. |
|
|
1245
|
+
| `isMessageInput` | function | `(value: unknown) => value is MessageInput` | Checks whether a value is a message input a conversation can store: a string `content`, and `calls`, `call`, `images`, and `thinking` absent or of their declared types. |
|
|
1246
|
+
| `judgmentShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>` | Describes a stored judgment: exactly one of an answer or a refusal, with its question, sources, state, model, and storage time. |
|
|
1247
|
+
| `sectionShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a compacted section: its id, its summary, and the originals it folded. |
|
|
1248
|
+
| `conversationSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; sections: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; judgments: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>>>; }, boolean \| ContractShape>` | Describes a conversation snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
|
|
1249
|
+
| `judgmentContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>>` | Reads the faults of a refused judgment. |
|
|
1250
|
+
| `sectionContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>>` | Reads the faults of a refused section. |
|
|
1251
|
+
| `conversationSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; sections: readonly Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>[]; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { judgments?: readonly (Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>)[]; }>>` | Reads the faults of a refused conversation snapshot. |
|
|
1252
|
+
| `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`. |
|
|
1253
|
+
| `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. |
|
|
1254
|
+
| `isJudgment` | const | `Guard<Judgment>` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
|
|
1255
|
+
|
|
1256
|
+
A `DatabaseConversationStore` reads its snapshot column back as `unknown` and narrows it through `isConversationSnapshot`. Only a missing row resolves `undefined`: a present row that fails the guard or names another id throws `ConversationError` `'SNAPSHOT'`, naming the id, carrying the faults, and saying to read the row through your own table and rewrite it, or to delete it with `store.delete`, and `set` refuses what `get` would. The same narrow, written by hand, reads:
|
|
1188
1257
|
|
|
1189
1258
|
```ts
|
|
1190
1259
|
import { isConversationSnapshot } from '@orkestrel/agent'
|
|
@@ -1203,7 +1272,7 @@ The following table lists the types the contexts module declares:
|
|
|
1203
1272
|
|
|
1204
1273
|
| Name | Kind | Signature | Summary |
|
|
1205
1274
|
| ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1206
|
-
| `ContextErrorCode` | type | `'SNAPSHOT'`
|
|
1275
|
+
| `ContextErrorCode` | type | `'SNAPSHOT' \| 'IMAGES'` | Names the machine-readable condition a `ContextError` reports. |
|
|
1207
1276
|
| `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
1277
|
| `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
1278
|
| `InstructionInput` | interface | `{ name, content, priority?, override? }` | Carries the minimal data to author an `InstructionInterface` — the `id` is minted by the `InstructionManagerInterface` that stores it, so a caller supplies only `name` / `content` and an optional `priority`. Default: `0`. |
|
|
@@ -1249,10 +1318,10 @@ The following table lists the constants the contexts module declares:
|
|
|
1249
1318
|
|
|
1250
1319
|
The following table lists the errors the contexts module declares and the guards that narrow them:
|
|
1251
1320
|
|
|
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`.
|
|
1321
|
+
| Name | Kind | Signature | Summary |
|
|
1322
|
+
| ---------------- | -------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1323
|
+
| `ContextError` | class | `new (code: ContextErrorCode, message: string, options?: CodedErrorOptions) => ContextError` | Reports a context snapshot that `isMemoSnapshot` refuses, thrown by the construction of a `MemoManager` before it seats any state or by a memo store, or image files a build has no user turn to carry, carrying the machine-readable `code` `'SNAPSHOT' \| 'IMAGES'`. |
|
|
1324
|
+
| `isContextError` | function | `(value: unknown) => value is ContextError` | Narrows an unknown caught value to a `ContextError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
|
|
1256
1325
|
|
|
1257
1326
|
#### Factories
|
|
1258
1327
|
|
|
@@ -1304,10 +1373,15 @@ The following table lists the helpers the contexts module declares:
|
|
|
1304
1373
|
|
|
1305
1374
|
The following table lists the guards the contexts module declares:
|
|
1306
1375
|
|
|
1307
|
-
| Name
|
|
1308
|
-
|
|
|
1309
|
-
| `isMemo`
|
|
1310
|
-
| `
|
|
1376
|
+
| Name | Kind | Signature | Summary |
|
|
1377
|
+
| ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1378
|
+
| `isMemo` | function | `(value: unknown) => value is Memo` | Checks whether a value is a stored memo revision: a record with a string `id`, `name`, `description`, and `content`, a finite `time`, and an optional `origin`. |
|
|
1379
|
+
| `memoShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo revision exactly. |
|
|
1380
|
+
| `memoSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; memos: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").StringShape; content: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; origin: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").StringShape; message: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a stored memo set exactly: an unknown key refuses. |
|
|
1381
|
+
| `memoContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>>` | Reads the faults of a refused memo revision. |
|
|
1382
|
+
| `memoSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; memos: readonly Readonly<{ id: string; name: string; description: string; content: string; time: number; } & { origin?: Readonly<{ conversation: string; } & { message?: string; }>; }>[]; } & {}>>` | Reads the faults of a refused memo snapshot. |
|
|
1383
|
+
| `isMemoOrigin` | function | `(value: unknown) => value is MemoOrigin` | Checks whether a value is a memo's origin: a record with a string `conversation` and an optional string `message`. |
|
|
1384
|
+
| `isMemoSnapshot` | function | `(value: unknown) => value is MemoSnapshot` | Checks whether a value is a stored memo set: a record with a string `id` and a dense `memos` array of `isMemo` values. |
|
|
1311
1385
|
|
|
1312
1386
|
### Agents module
|
|
1313
1387
|
|
|
@@ -1326,7 +1400,7 @@ The following table lists the types the agents module declares:
|
|
|
1326
1400
|
| `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
1401
|
| `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
1402
|
| `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'`
|
|
1403
|
+
| `AgentErrorCode` | type | `'APPROVER' \| 'AUTHORITY' \| 'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'SCHEMA' \| 'WINDOW'` | Names the machine-readable agent approver, authority, concurrency, limit, registry, schema, and window failures. |
|
|
1330
1404
|
| `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
|
|
1331
1405
|
| `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
|
|
1332
1406
|
| `ChannelInterface` | interface | `{ push(), close(), fail(), drain() }` | Buffers values in an unbounded async channel — a producer writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
|
|
@@ -1342,12 +1416,12 @@ The following table lists the types the agents module declares:
|
|
|
1342
1416
|
| `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
|
|
1343
1417
|
| `AuthorityVerdict` | type | `'allow' \| 'ask' \| 'deny'` | Names an authority's verdict on one tool call. |
|
|
1344
1418
|
| `AuthorityDecision` | interface | `{ zone, verdict, reason? }` | Holds the authority verdict on one tool call. |
|
|
1345
|
-
| `AuthorityRule` | interface | `{ match, zone, verdict
|
|
1419
|
+
| `AuthorityRule` | interface | `{ match, zone, verdict, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
|
|
1346
1420
|
| `AuthorityHandler` | type | `(context: AuthorityContext, decision: AuthorityDecision, signal: AbortSignal) => boolean \| Promise<boolean>` | Answers one `ask`; only a resolved `true` approves. |
|
|
1347
|
-
| `AuthorityOptions` | interface | `{ rules?, fallback
|
|
1421
|
+
| `AuthorityOptions` | interface | `{ rules?, fallback, ask? }` | Configures `createAuthority` — the ordered rules, the no-match fallback, and the approver. |
|
|
1348
1422
|
| `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
1423
|
| `AuthorityNote` | interface | `{ denied, refused, unanswered }` | Holds the model-facing texts the loop writes into a denial result. |
|
|
1350
|
-
| `AgentJobInput` | interface | `{ provider, messages
|
|
1424
|
+
| `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
1425
|
| `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
|
|
1352
1426
|
| `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
1427
|
| `AgentQueueOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout?, store? }` | Configures `createAgentQueue` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createQueue`. |
|
|
@@ -1360,7 +1434,6 @@ The following table lists the constants the agents module declares:
|
|
|
1360
1434
|
| Name | Kind | Signature | Summary |
|
|
1361
1435
|
| ------------------------ | ----- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1362
1436
|
| `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
1437
|
| `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
1438
|
| `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
1439
|
| `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
|
|
@@ -1370,12 +1443,12 @@ The following table lists the constants the agents module declares:
|
|
|
1370
1443
|
|
|
1371
1444
|
The following table lists the errors the agents module declares and the guards that narrow them:
|
|
1372
1445
|
|
|
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
|
|
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`.
|
|
1446
|
+
| Name | Kind | Signature | Summary |
|
|
1447
|
+
| ----------------- | -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1448
|
+
| `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'`. |
|
|
1449
|
+
| `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. |
|
|
1450
|
+
| `AgentError` | class | `new (code: AgentErrorCode, message: string, options?: CodedErrorOptions) => AgentError` | Reports an `ask` on an authority that has no approver or that its approver refuses, an authority missing its fallback or a rule's verdict, tools set with no authority, a run sharing accounting or a conversation with a live run, a `limit` that is not a positive safe integer, a name absent from a registry pool, a strict run's answer that fails its schema, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead, and an `'APPROVER'` refusal rejects the promise the `ask` method of an `Authority` or the `ask` handler of an `Approver` returns. Await the call inside `try`/`catch` to catch it. |
|
|
1451
|
+
| `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
1452
|
|
|
1380
1453
|
#### Shapes and contracts
|
|
1381
1454
|
|
|
@@ -1385,9 +1458,11 @@ The following table lists the agent wire shapes and the contracts compiled from
|
|
|
1385
1458
|
| --------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1386
1459
|
| `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
1460
|
| `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. |
|
|
1461
|
+
| `agentJobShape` | const | `import("@orkestrel/contract").ObjectShape<{ provider: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>>; system: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; authority: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; scheduler: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; limit: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; timeout: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; budget: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; children: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>>; }, boolean \| ContractShape>` | Describes a durable agent job — the record `AgentRegistry.build` checks exactly, so a misspelled key refuses instead of running an agent without it. |
|
|
1388
1462
|
| `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
1463
|
| `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
1464
|
| `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. |
|
|
1465
|
+
| `agentJobContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ provider: string; } & { messages?: readonly Readonly<{ role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; system?: string; tools?: readonly string[]; authority?: string; scheduler?: string; limit?: number; timeout?: number; budget?: number; children?: readonly { readonly [k: string]: import("@orkestrel/contract").JSONValue; }[]; }>>` | Checks a durable agent job exactly at `AgentRegistry.build`. |
|
|
1391
1466
|
| `agentAnswerContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; approved: boolean; } & {}>>` | Validates and projects a page's answers to `ask` frames at a JSON wire boundary. |
|
|
1392
1467
|
|
|
1393
1468
|
#### Factories
|
|
@@ -1397,7 +1472,7 @@ The following table lists the factories the agents module declares:
|
|
|
1397
1472
|
| Name | Kind | Signature | Summary |
|
|
1398
1473
|
| --------------------- | -------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1399
1474
|
| `createAgent` | function | `(provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Creates an agent loop — an `AgentInterface` composing a `ProviderInterface`, its `AgentContextInterface`, and a tool registry into a bounded context → provider → tools → repeat turn, exposed as a one-shot `generate` and a live `stream`. |
|
|
1400
|
-
| `createAuthority` | function | `(options
|
|
1475
|
+
| `createAuthority` | function | `(options: AuthorityOptions) => AuthorityInterface` | Creates a policy gate — an `AuthorityInterface` the agent loop consults before each tool call runs, evaluating the ordered rules first-match-wins and falling back to the required `fallback` when none match. |
|
|
1401
1476
|
| `createApprover` | function | `() => ApproverInterface` | Creates an approver — an `ApproverInterface` that holds a server's waiting asks between the run that asked them and the page that answers them. |
|
|
1402
1477
|
| `createChannel` | function | `<T>() => ChannelInterface<T>` | Creates an empty unbounded async channel — a `ChannelInterface` a producer writes values into (`push`) and ends (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
|
|
1403
1478
|
| `createAgentRegistry` | function | `(options: AgentRegistryOptions) => AgentRegistryInterface` | Creates a registry of live providers, tools, authorities, and schedulers whose `build` method returns a seeded, signal-wired `AgentInterface` from a serializable job. |
|
|
@@ -1412,7 +1487,7 @@ The following table lists the classes the agents module declares:
|
|
|
1412
1487
|
| --------------- | ----- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1413
1488
|
| `Agent` | class | `new (provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Composes a `ProviderInterface`, an `AgentContext`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn, exposed as both a one-shot `generate` and a live `stream` that share one private run — bounded by the run `signal`, the `timeout`, and the `budget` folded through `AbortSignal.any`, paced by `scheduler`, with tool iteration capped at `limit`. |
|
|
1414
1489
|
| `AgentFanout` | class | `new (registry: AgentRegistryInterface, partial: boolean) => AgentFanout` | Executes one runner's agent jobs — spawning each unit's declared children on its first attempt only, then rehydrating the unit through a registry with the controller signal and settling it under the shared partial-result policy. |
|
|
1415
|
-
| `Authority` | class | `new (options
|
|
1490
|
+
| `Authority` | class | `new (options: AuthorityOptions) => AuthorityInterface` | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to the required `fallback`, and the approver that answers an `ask` verdict. |
|
|
1416
1491
|
| `Approver` | class | `new () => ApproverInterface` | Holds a server's waiting asks between the run that asked them and the page that answers them — an `ApproverInterface` whose `ask` is the authority's handler, keyed by the asked call object. |
|
|
1417
1492
|
| `AgentRegistry` | class | `new (options: AgentRegistryOptions) => AgentRegistryInterface` | Makes a durable, JSON-serializable `AgentJobInput` runnable — holds the named pools of live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name absent from its pool, and its `build` method returns a seeded, signal-wired `Agent` from a job's names and data. |
|
|
1418
1493
|
| `Channel` | class | `new <T>() => ChannelInterface<T>` | Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through the `drain` async-iterator. Decoupling write from read is what lets a producer make progress without a consumer pulling, and it is why an agent's `result` settles whether or not its `events` are drained. |
|
|
@@ -1421,32 +1496,36 @@ The following table lists the classes the agents module declares:
|
|
|
1421
1496
|
|
|
1422
1497
|
The following table lists the helpers the agents module declares:
|
|
1423
1498
|
|
|
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
|
|
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
|
|
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
|
|
1445
|
-
| `
|
|
1446
|
-
| `
|
|
1447
|
-
| `
|
|
1448
|
-
| `
|
|
1449
|
-
| `
|
|
1499
|
+
| Name | Kind | Signature | Summary |
|
|
1500
|
+
| --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1501
|
+
| `agentResultToJSON` | function | `(value: unknown) => JSONValue \| undefined` | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a negative or non-finite usage number, a throwing getter, or a malformed or revoked proxy. |
|
|
1502
|
+
| `tokenUsageToJSON` | function | `(value: unknown) => TokenUsage \| undefined` | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing, negative, or non-finite count, a throwing getter, or a malformed or revoked proxy. |
|
|
1503
|
+
| `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. |
|
|
1504
|
+
| `agentResultToFrame` | function | `(result: AgentResult) => Extract<AgentFrame, { readonly category: 'finish'; }>` | Projects a settled `AgentResult` onto the terminal `finish` frame a page receives. |
|
|
1505
|
+
| `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. |
|
|
1506
|
+
| `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. |
|
|
1507
|
+
| `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). |
|
|
1508
|
+
| `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. |
|
|
1509
|
+
| `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. |
|
|
1510
|
+
| `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. |
|
|
1511
|
+
| `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. |
|
|
1512
|
+
| `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. |
|
|
1513
|
+
| `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. |
|
|
1514
|
+
| `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. |
|
|
1515
|
+
| `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. |
|
|
1516
|
+
| `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. |
|
|
1517
|
+
| `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`. |
|
|
1518
|
+
| `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. |
|
|
1519
|
+
| `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a positive safe integer, or throws a coded error. |
|
|
1520
|
+
| `requireAnswer` | function | `(content: string, schema: Readonly<Record<string, unknown>>) => void` | Checks a run's final answer against its schema: the content must parse as JSON and satisfy the schema, or the call throws a coded error carrying the faults. |
|
|
1521
|
+
| `settleToolResult` | function | `(result: ToolResult) => { readonly outcome: ToolResult; readonly content: string; }` | Settles one dispatched result into the result the loop reports and the content of its tool message, turning a success whose value JSON cannot carry into a tool failure the model reads. |
|
|
1522
|
+
| `requireFallback` | function | `(options: AuthorityOptions) => AuthorityDecision` | Returns an authority's no-match decision after checking the options carry one, or throws a coded error naming the two fallbacks a host chooses between. |
|
|
1523
|
+
| `requireRules` | function | `(rules: readonly AuthorityRule[] \| undefined) => readonly AuthorityRule[]` | Returns an authority's rules after checking each one names a verdict, or throws a coded error naming the first rule that does not. |
|
|
1524
|
+
| `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. |
|
|
1525
|
+
| `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. |
|
|
1526
|
+
| `renderToolValue` | function | `(value: unknown) => string \| undefined` | Renders a tool's output as the string content of its tool message, or returns `undefined` when JSON cannot carry it. |
|
|
1527
|
+
| `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
|
|
1528
|
+
| `extractQueueOptions` | function | `(options: Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>) => Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>` | Extracts the present concurrency, retry, and deadline options for an agent job queue. |
|
|
1450
1529
|
|
|
1451
1530
|
The measures are structural estimates, not tokenizer allocations. A message's `id` and `role` join a measure back to its message and are not token components, and a provider's template effects and the estimation error are not individually attributed.
|
|
1452
1531
|
|
|
@@ -1490,6 +1569,7 @@ The following table lists the guards the agents module declares:
|
|
|
1490
1569
|
|
|
1491
1570
|
| Name | Kind | Signature | Summary |
|
|
1492
1571
|
| --------------------- | -------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1572
|
+
| `isAuthorityVerdict` | function | `(value: unknown) => value is AuthorityVerdict` | Checks whether a value is an authority verdict: `allow`, `ask`, or `deny`. |
|
|
1493
1573
|
| `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
1574
|
|
|
1495
1575
|
### Ledgers module
|
|
@@ -1500,53 +1580,63 @@ The `ledgers` module serves a conversation through event-sourced records: the `L
|
|
|
1500
1580
|
|
|
1501
1581
|
The following table lists the types the ledger declares, each with its shape:
|
|
1502
1582
|
|
|
1503
|
-
| Name | Kind | Signature
|
|
1504
|
-
| ------------------------- | --------- |
|
|
1505
|
-
| `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]`
|
|
1506
|
-
| `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }`
|
|
1507
|
-
| `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }`
|
|
1508
|
-
| `LedgerTopic` | interface | `{ name, criterion, requested? }`
|
|
1509
|
-
| `LedgerShare` | interface | `{ prompt, tail }`
|
|
1510
|
-
| `LedgerNote` | interface | `{ cue, results, repeat, closure }`
|
|
1511
|
-
| `LedgerRecallOptions` | interface | `{ limit? }`
|
|
1512
|
-
| `LedgerCorrectionOptions` | interface | `{ narrow? }`
|
|
1513
|
-
| `LedgerOwner` | interface | `{ id, names }`
|
|
1514
|
-
| `LedgerLookupResult` | interface | `{ ids, owners }`
|
|
1515
|
-
| `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined`
|
|
1516
|
-
| `LedgerLookup` | interface | `{ tool, read }`
|
|
1517
|
-
| `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }`
|
|
1518
|
-
| `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'`
|
|
1519
|
-
| `LedgerRegistry` | interface | `{ ids, owners }`
|
|
1520
|
-
| `LedgerIndex` | interface | `{ ids, aliases, carriers, names, words, keys, ranks }`
|
|
1521
|
-
| `LedgerGauge` | interface | `{ scale, overhead }`
|
|
1522
|
-
| `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces'>`
|
|
1523
|
-
| `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, correction?, agent?, snapshot? }`
|
|
1524
|
-
| `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge? }`
|
|
1525
|
-
| `
|
|
1526
|
-
| `
|
|
1527
|
-
| `
|
|
1528
|
-
| `
|
|
1529
|
-
| `
|
|
1530
|
-
| `
|
|
1531
|
-
| `
|
|
1532
|
-
| `
|
|
1533
|
-
| `
|
|
1534
|
-
| `
|
|
1535
|
-
| `
|
|
1536
|
-
| `
|
|
1537
|
-
| `
|
|
1538
|
-
| `
|
|
1539
|
-
| `
|
|
1540
|
-
| `
|
|
1541
|
-
| `
|
|
1542
|
-
| `
|
|
1543
|
-
| `
|
|
1544
|
-
| `
|
|
1545
|
-
| `
|
|
1546
|
-
| `
|
|
1547
|
-
| `
|
|
1548
|
-
| `
|
|
1549
|
-
| `
|
|
1583
|
+
| Name | Kind | Signature | Summary |
|
|
1584
|
+
| ------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1585
|
+
| `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
|
|
1586
|
+
| `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
|
|
1587
|
+
| `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
|
|
1588
|
+
| `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
|
|
1589
|
+
| `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. |
|
|
1590
|
+
| `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
|
|
1591
|
+
| `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
|
|
1592
|
+
| `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
|
|
1593
|
+
| `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
|
|
1594
|
+
| `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
|
|
1595
|
+
| `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
|
|
1596
|
+
| `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
|
|
1597
|
+
| `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
|
|
1598
|
+
| `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. |
|
|
1599
|
+
| `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
|
|
1600
|
+
| `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. |
|
|
1601
|
+
| `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
|
|
1602
|
+
| `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'strict'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
|
|
1603
|
+
| `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. |
|
|
1604
|
+
| `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge?, window? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
|
|
1605
|
+
| `LedgerExchangeSnapshot` | interface | `{ request, copy?, reply, lines }` | Carries the sent request text, stored pair ids, and sentence placements of one exchange. |
|
|
1606
|
+
| `LedgerWindowSnapshot` | interface | `{ digest, exchanges, amendments }` | Carries a nonempty exchange window, its message, copy, and receipt checksum, and its accepted edges. |
|
|
1607
|
+
| `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
|
|
1608
|
+
| `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. |
|
|
1609
|
+
| `LedgerListing` | interface | `{ result, lines, groups, turn }` | Carries a recall result, its accepted whole groups, lookup line translations, and provider-turn position. |
|
|
1610
|
+
| `LedgerRecovery` | interface | `{ digest, omitted }` | Carries the answer note and the partial messages omitted from its prompt. |
|
|
1611
|
+
| `LedgerRequestInterface` | interface | `{ scope, apply(), sent, fault(), faulted(), message, plan, selection, boundary, usage, calls, attempts, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), listings, lines() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing attempts and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
|
|
1612
|
+
| `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
|
|
1613
|
+
| `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
|
|
1614
|
+
| `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. |
|
|
1615
|
+
| `LedgerReceipt` | interface | `{ key, title, source, sentence }` | Identifies an original sentence at one record placement. |
|
|
1616
|
+
| `LedgerOccurrence` | interface | `{}` | Carries a rendered sentence with its record placement. |
|
|
1617
|
+
| `LedgerExchange` | interface | `{ request, reply, lines }` | Carries a completed request copy, its stored reply, and the sentences the copy rendered. |
|
|
1618
|
+
| `LedgerDraft` | interface | `{ copy, lines, evidence, window }` | Carries a planned copy and its validity evidence to request settlement. |
|
|
1619
|
+
| `LedgerEvidence` | interface | `{ messages, amendments }` | Captures held message identities and the accepted edges used to validate their copies. |
|
|
1620
|
+
| `LedgerRenderResult` | interface | `{ text, lines }` | Carries rendered record text and its sentences in emission order. |
|
|
1621
|
+
| `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
|
|
1622
|
+
| `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
|
|
1623
|
+
| `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
|
|
1624
|
+
| `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
|
|
1625
|
+
| `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
|
|
1626
|
+
| `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
|
|
1627
|
+
| `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
|
|
1628
|
+
| `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
|
|
1629
|
+
| `ClassifierOptions` | interface | `{ strict?, conversation, judge, questions, topics, thresholds, assign, entities, correction?, scheduler? }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, the ledger's handlers, and the optional correction filter and scheduler. |
|
|
1630
|
+
| `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. |
|
|
1631
|
+
| `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
|
|
1632
|
+
| `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. |
|
|
1633
|
+
| `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
|
|
1634
|
+
| `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
|
|
1635
|
+
| `GaugeCall` | interface | `{ estimate, spared?, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
|
|
1636
|
+
| `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
|
|
1637
|
+
| `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
|
|
1638
|
+
| `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. |
|
|
1639
|
+
| `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION'` | Names the machine-readable conditions a `LedgerError` error reports. |
|
|
1550
1640
|
|
|
1551
1641
|
#### Constants
|
|
1552
1642
|
|
|
@@ -1560,6 +1650,7 @@ The following table lists the constants that hold the ledger's categories, recor
|
|
|
1560
1650
|
| `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
|
|
1561
1651
|
| `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
|
|
1562
1652
|
| `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
|
|
1653
|
+
| `LEDGER_RECALL_LABELS` | const | `Readonly<{ request: "Earlier request:"; reply: "Earlier reply:"; }>` | Labels recalled conversation text by its origin. |
|
|
1563
1654
|
| `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
|
|
1564
1655
|
| `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
|
|
1565
1656
|
| `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt and tail shares. |
|
|
@@ -1574,10 +1665,10 @@ The following table lists the constants that hold the ledger's categories, recor
|
|
|
1574
1665
|
|
|
1575
1666
|
The following table lists the error the ledger raises and the guard that narrows it:
|
|
1576
1667
|
|
|
1577
|
-
| Name | Kind | Signature
|
|
1578
|
-
| --------------- | -------- |
|
|
1579
|
-
| `LedgerError` | class | `new (code: LedgerErrorCode, message: string) => LedgerError` | Reports an invalid ledger configuration, failed calibration, or unowned request selection, carrying the machine-readable `code`. |
|
|
1580
|
-
| `isLedgerError` | function | `(value: unknown) => value is LedgerError`
|
|
1668
|
+
| Name | Kind | Signature | Summary |
|
|
1669
|
+
| --------------- | -------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1670
|
+
| `LedgerError` | class | `new (code: LedgerErrorCode, message: string, options?: CodedErrorOptions) => LedgerError` | Reports an invalid ledger configuration, failed calibration, or unowned request selection, carrying the machine-readable `code`. |
|
|
1671
|
+
| `isLedgerError` | function | `(value: unknown) => value is LedgerError` | Narrows an unknown caught value to a `LedgerError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
|
|
1581
1672
|
|
|
1582
1673
|
#### Factories
|
|
1583
1674
|
|
|
@@ -1602,58 +1693,72 @@ The following table lists the classes that serve, file, and price a conversation
|
|
|
1602
1693
|
|
|
1603
1694
|
The following guards validate ledger fractions, capacity, and snapshots:
|
|
1604
1695
|
|
|
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. |
|
|
1696
|
+
| Name | Kind | Signature | Summary |
|
|
1697
|
+
| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1698
|
+
| `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
|
|
1699
|
+
| `isLedgerQuestion` | function | `(value: unknown) => value is LedgerQuestion` | Checks whether a value holds the wording a ledger files with: a choice `category` question whose criteria describe every category, a non-empty `topic` string, and noul `amends` and `supersedes` questions. |
|
|
1700
|
+
| `ledgerWindowShape` | const | `import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes the minimal serialized evidence of a nonempty exchange window. |
|
|
1701
|
+
| `ledgerWindowContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>>` | Reads structural faults of a serialized exchange window. |
|
|
1702
|
+
| `ledgerSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; sections: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; judgments: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>>>; }, boolean \| ContractShape>; requests: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; notes: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; failures: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; gauge: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ scale: import("@orkestrel/contract").NumberShape; overhead: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; window: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a ledger snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
|
|
1703
|
+
| `ledgerSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ conversation: Readonly<{ id: string; sections: readonly Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>[]; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { judgments?: readonly (Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>)[]; }>; requests: readonly string[]; notes: readonly string[]; failures: readonly string[]; } & { gauge?: Readonly<{ scale: number; overhead: number; } & {}>; window?: Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>; }>>` | Reads structural faults of a ledger snapshot, including its optional held exchange window. |
|
|
1704
|
+
| `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
|
|
1705
|
+
| `isLedgerWindowSnapshot` | function | `(value: unknown) => value is LedgerWindowSnapshot` | Checks whether a value has the exact shape of a nonempty exchange window. |
|
|
1706
|
+
| `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
|
|
1610
1707
|
|
|
1611
1708
|
#### Helpers
|
|
1612
1709
|
|
|
1613
|
-
The following table lists the pure helpers that read text, project and select records, render the records,
|
|
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`
|
|
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
|
|
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.
|
|
1710
|
+
The following table lists the pure helpers that read text, project and select records, render the records, fit a price, and hold the window:
|
|
1711
|
+
|
|
1712
|
+
| Name | Kind | Signature | Summary |
|
|
1713
|
+
| -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1714
|
+
| `splitSentences` | function | `(text: string) => readonly string[]` | Splits a message into its sentences. |
|
|
1715
|
+
| `collectNames` | function | `(text: string) => readonly string[]` | Collects the capitalized name runs of a text, leaving out the run that opens each sentence. |
|
|
1716
|
+
| `identifyLookup` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string \| undefined` | Identifies a lookup finding for projection by its tool name and normalized arguments. |
|
|
1717
|
+
| `linkOwners` | function | `(findings: readonly LedgerLookupFinding[], owners: ReadonlyMap<string, readonly string[]>) => ReadonlyMap<string, string>` | Links each id-shaped lookup argument to its owner. |
|
|
1718
|
+
| `collectRegistry` | function | `(findings: readonly LedgerLookupFinding[]) => LedgerRegistry` | Collects the ids and the owner names the lookup findings named. |
|
|
1719
|
+
| `buildLedgerIndex` | function | `(registry: LedgerRegistry) => LedgerIndex` | Builds a registry's matching index: each name's owners, each word's carriers, the needles, keys, and ranks. |
|
|
1720
|
+
| `matchEntities` | function | `(index: LedgerIndex, text: string, partial: boolean) => ReadonlySet<string>` | Matches the registry ids and owners a text names. |
|
|
1721
|
+
| `normalizeWord` | function | `(word: string) => string` | Normalizes a run of letters and digits to the one form each of its cases folds to. |
|
|
1722
|
+
| `buildRecords` | function | `(input: LedgerProjectionInput) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
|
|
1723
|
+
| `selectRecords` | function | `(projection: LedgerProjection, request: LedgerProjectionRequest) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
|
|
1724
|
+
| `findLedgerCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
|
|
1725
|
+
| `collectProjectionIds` | function | `(projection: LedgerProjection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
|
|
1726
|
+
| `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. |
|
|
1727
|
+
| `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
|
|
1728
|
+
| `buildRequestMessage` | function | `(request: Message, records: string) => Message` | Builds the copy of a request turn that carries the rendered records ahead of the request. |
|
|
1729
|
+
| `renderTopicNames` | function | `(topics: readonly LedgerTopic[]) => string` | Renders topic names as a comma-separated list in their supplied order. |
|
|
1730
|
+
| `renderCauseChain` | function | `(error: unknown) => string` | Renders an error and its causes, stopping after 4 entries. |
|
|
1731
|
+
| `extractWords` | function | `(message: Message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
|
|
1732
|
+
| `splitWords` | function | `(part: string) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
|
|
1733
|
+
| `rankLedgerCut` | function | `(group: LedgerPlanGroup, unsettled: boolean, category: LedgerCategory \| undefined) => number` | Ranks a source the records render for removal before the next prompt. |
|
|
1734
|
+
| `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. |
|
|
1735
|
+
| `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. |
|
|
1736
|
+
| `renderLedgerRecord` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one record as a heading and one list item per line. |
|
|
1737
|
+
| `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. |
|
|
1738
|
+
| `splitTopic` | function | `(topic: string) => readonly string[]` | Splits a recall topic at its joints. |
|
|
1739
|
+
| `cutListing` | function | `(entries: readonly string[], room: number, kind?: 'older' \| 'more', first?: boolean) => string` | Cuts entries to a room and names how many it left out. |
|
|
1740
|
+
| `matchesCutLine` | function | `(line: string) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
|
|
1741
|
+
| `normalizeArgument` | function | `(value: string) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
|
|
1742
|
+
| `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. |
|
|
1743
|
+
| `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
|
|
1744
|
+
| `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState) => string` | Renders the tail stub of a lookup result from an earlier request. |
|
|
1745
|
+
| `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
|
|
1746
|
+
| `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
|
|
1747
|
+
| `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
|
|
1748
|
+
| `collectLive` | function | `(input: LedgerProjectionInput) => readonly string[]` | Collects the ids of the live messages in conversation order. |
|
|
1749
|
+
| `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. |
|
|
1750
|
+
| `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. |
|
|
1751
|
+
| `renderLedgerAnnotation` | function | `(line: LedgerLine, context: LedgerRenderContext) => string` | Renders a source's reference and its later changes at the source's first retained line. |
|
|
1752
|
+
| `collectAmendments` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, live: readonly string[]) => readonly LedgerAmendment[]` | Collects accepted amendments of live messages, following superseded amenders to live successors. |
|
|
1753
|
+
| `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. |
|
|
1754
|
+
| `collectRecallMessages` | function | `(input: LedgerProjectionInput, requests: ReadonlySet<string>, notes: ReadonlySet<string>) => readonly Message[]` | Collects stored messages eligible to open the recall offer. |
|
|
1755
|
+
| `hasHiddenRecall` | function | `(input: LedgerProjectionInput, request: string, requests: ReadonlySet<string>, notes: ReadonlySet<string>, messages: readonly Message[], lines: readonly LedgerReceipt[]) => boolean` | Checks whether an eligible earlier message is absent from the prompt or incompletely covered. A successful finding is held when a finding with the same canonical identity and text is fully received. |
|
|
1756
|
+
| `matchesLookup` | function | `(left: LedgerLookupFinding, right: LedgerLookupFinding) => boolean` | Checks whether two successful findings carry the same text for the same canonical lookup. |
|
|
1757
|
+
| `digestLedgerWindow` | function | `(exchanges: readonly LedgerExchangeSnapshot[], messages: readonly Message[]) => string \| undefined` | Digests held messages, lookup call context, stored copies, and sentence receipts using canonical text. This non-cryptographic checksum detects host edits and makes no security claim. |
|
|
1758
|
+
| `buildLedgerLineKey` | function | `(line: Pick<LedgerOccurrence, 'key' \| 'title' \| 'source' \| 'sentence'>) => string` | Encodes a sentence's record placement without comparing rendered text. |
|
|
1759
|
+
| `collectLedgerLines` | function | `(record: LedgerRecord, held: ReadonlySet<string>) => readonly LedgerOccurrence[]` | Collects the record's sentence receipts not already held by a window. |
|
|
1760
|
+
| `collectLedgerReplies` | function | `(messages: readonly Message[], requests: ReadonlySet<string>, notes: ReadonlySet<string>) => ReadonlyMap<string, Message>` | Selects each marked request's unambiguous final call-free reply. |
|
|
1761
|
+
| `collectLedgerEvidence` | function | `(messages: readonly Message[], sources: ReadonlySet<string>, amendments: readonly LedgerAmendment[]) => LedgerEvidence` | Captures source bytes and direct amendment edges for a held window. |
|
|
1657
1762
|
|
|
1658
1763
|
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:
|
|
1659
1764
|
|
|
@@ -1765,10 +1870,10 @@ The seams a judge wire fills, beneath the boundary method it inherits. `AgentJud
|
|
|
1765
1870
|
|
|
1766
1871
|
The System One wire over `AgentJudge`: it fills both seams and inherits `ask` from the engine, so a caller drives it through `JudgeInterface` like any judge. Its `name` reports `'systemone'` and stays a data member.
|
|
1767
1872
|
|
|
1768
|
-
| Method | Returns | Summary
|
|
1769
|
-
| -------- | ------------------ |
|
|
1770
|
-
| `encode` | `SystemOneRequest` | Projects the state and questions onto the System One request with the configured model. |
|
|
1771
|
-
| `read` | `JudgeResult` | Decodes
|
|
1873
|
+
| Method | Returns | Summary |
|
|
1874
|
+
| -------- | ------------------ | ----------------------------------------------------------------------------------------------------------- |
|
|
1875
|
+
| `encode` | `SystemOneRequest` | Projects the state and questions onto the System One request with the configured model and positional keys. |
|
|
1876
|
+
| `read` | `JudgeResult` | Decodes positional System One answers under caller ids and reports the server model and available usage. |
|
|
1772
1877
|
|
|
1773
1878
|
#### `ThinkSplitterInterface`
|
|
1774
1879
|
|
|
@@ -1936,6 +2041,8 @@ The unbounded async channel. A producer writes with `push` and ends it with `clo
|
|
|
1936
2041
|
|
|
1937
2042
|
Concurrent `drain` readers share one buffer: each value goes to exactly one reader, and `close` or `fail` ends every reader. A `push` after `close` or `fail` is buffered rather than refused, so a later `drain` yields it before reporting the end.
|
|
1938
2043
|
|
|
2044
|
+
A channel retains at most its newest consumed value until the next push. A paused reader holds only the value it took, not the remaining queue. Unread values remain buffered without a bound.
|
|
2045
|
+
|
|
1939
2046
|
Buffered values are always delivered before the end is reported, so a `close` or `fail` arriving alongside the last values still hands them over first:
|
|
1940
2047
|
|
|
1941
2048
|
```ts
|
|
@@ -1957,14 +2064,14 @@ failed.fail(new Error('upstream died')) // the 2 is delivered, then the drain th
|
|
|
1957
2064
|
|
|
1958
2065
|
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
2066
|
|
|
1960
|
-
| Method | Returns | Summary
|
|
1961
|
-
| ---------- | ------------------- |
|
|
1962
|
-
| `evaluate` | `AuthorityDecision` | Evaluates one tool call against the ordered rules — returns the first matching rule's verdict,
|
|
1963
|
-
| `ask` | `Promise<boolean>` | Resolves `true` to approve one asked call; absent, every ask reads as unanswered.
|
|
2067
|
+
| Method | Returns | Summary |
|
|
2068
|
+
| ---------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
2069
|
+
| `evaluate` | `AuthorityDecision` | Evaluates one tool call against the ordered rules — returns the first matching rule's verdict, or the fallback when none match. |
|
|
2070
|
+
| `ask` | `Promise<boolean>` | Resolves `true` to approve one asked call; absent, every ask reads as unanswered. |
|
|
1964
2071
|
|
|
1965
2072
|
#### `ApproverInterface`
|
|
1966
2073
|
|
|
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`.
|
|
2074
|
+
The server half of a page's approval. Its `ask` is a readonly data member that holds the bound `AuthorityHandler`, so `createAuthority({ rules, fallback, ask: approver.ask })` wires it; `frame` reads a waiting ask's `ask` frame for the page, and `answer` settles that ask from the page's `AgentAnswer`.
|
|
1968
2075
|
|
|
1969
2076
|
| Method | Returns | Summary |
|
|
1970
2077
|
| -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -2028,22 +2135,22 @@ A conversation that owns its live message tail directly (the flat store verbs fo
|
|
|
2028
2135
|
| `reference` | `string` | Renders this conversation as a self-labeled, fenced provenance block to pull into another conversation — a pure string with no model call: a leading `[Reference — conversation "<label>" — NOT part of this conversation]` marker, then the cherry-picked excerpts (`- role: content`) when `messages` is supplied. The `label` option names the source. Default: the `id`. |
|
|
2029
2136
|
| `snapshot` | `ConversationSnapshot` | Serializes this conversation to a plain, JSON-serializable `ConversationSnapshot` — its `id`, the compacted `sections`, and the live tail; the live `summarize` / `keep` are configuration re-supplied on hydrate rather than serialized. |
|
|
2030
2137
|
|
|
2031
|
-
A supplied `sections` cap must
|
|
2138
|
+
A supplied `sections` cap must be a positive safe integer; any other value throws `ConversationError` with code `SECTIONS` before a fold starts. A successful capped merge retains at most `sections` entries. An absent cap leaves the sections unbounded. A supplied `keep` must be a nonnegative safe integer; any other value throws `ConversationError` with code `KEEP`, carrying the value as `context.keep`, before a fold starts. `compact()` calls run one at a time. A `remove` or `clear` during the initial summarizer leaves no section. `CompactOptions.signal` rejects a call with its reason at once and commits nothing after the abort; a fold committed before an aborted overflow merge stays. A summarizer digest whose trimmed text is empty rejects with `ConversationError` code `SUMMARY`: a fold commits nothing, and a refused overflow merge leaves the appended section.
|
|
2032
2139
|
|
|
2033
2140
|
#### `ConversationManagerInterface`
|
|
2034
2141
|
|
|
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
|
|
2142
|
+
The id-keyed registry of `Conversation` instances with an active pointer. `add(input?)` mints a conversation (flowing the manager's default `summarize` / `keep` in unless the input overrides them) and auto-activates the first one; a later `add` leaves `active` unchanged, and `add` of an `id` already live throws `ConversationError` `'ID'`, so a live conversation is never replaced. `add` forwards the input's `on` hooks and `error` handler to the conversation's emitter, so a throwing listener reports to that handler. `open(id)` returns the conversation registered under `id` while its store read was pending rather than overwriting it, and rejects with `ConversationError` `'SNAPSHOT'` for a stored snapshot whose `id` is not `id`. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, and the registry and `active` stay unchanged. `switch(id)` re-points `active` (an unknown `id` returns `undefined`, leaving `active` unchanged — lenient, never throws); `remove` carries batch overloads and clears `active` when the removed conversation was active. The `count` and `active` data members stay Surface rows (`active` is a `readonly` accessor — a property, not a method); the manager is event-free (each conversation owns its `emitter`).
|
|
2036
2143
|
|
|
2037
|
-
| Method | Returns | Summary
|
|
2038
|
-
| --------------- | --------------------------------------------- |
|
|
2039
|
-
| `conversation` | `ConversationInterface \| undefined` | Looks up one conversation by id (`undefined` when absent).
|
|
2040
|
-
| `conversations` | `readonly ConversationInterface[]` | Lists every conversation, in insertion order.
|
|
2041
|
-
| `add` | `ConversationInterface` | Mints a conversation, taking its `id` from the input or a fresh UUID and flowing the default `summarize` / `keep` of the manager in unless the input overrides them — auto-activates the first, and an already-present `id`
|
|
2042
|
-
| `switch` | `ConversationInterface \| undefined` | Re-points `active` at the conversation with `id` and returns it; an unknown `id` returns `undefined` and leaves `active` unchanged, never throwing.
|
|
2043
|
-
| `open` | `Promise<ConversationInterface \| undefined>` | Resolves a conversation by id and activates it — from the registry when present, else hydrated from the optional `ConversationStoreInterface` (`store`); `undefined` when it is neither registered nor stored.
|
|
2044
|
-
| `save` | `Promise<boolean>` | Persists a registered conversation's `ConversationInterface.snapshot` to the optional `ConversationStoreInterface` (`store`) — `true` when persisted, `false` when there is no store or the id is unknown; a store failure propagates.
|
|
2045
|
-
| `remove` | `boolean` | Removes one conversation by id, or a batch — `true` only when every supplied id was removed; clears `active` when a removed conversation was the active one.
|
|
2046
|
-
| `clear` | `void` | Removes every conversation and clears `active`.
|
|
2144
|
+
| Method | Returns | Summary |
|
|
2145
|
+
| --------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2146
|
+
| `conversation` | `ConversationInterface \| undefined` | Looks up one conversation by id (`undefined` when absent). |
|
|
2147
|
+
| `conversations` | `readonly ConversationInterface[]` | Lists every conversation, in insertion order. |
|
|
2148
|
+
| `add` | `ConversationInterface` | Mints a conversation, taking its `id` from the input or a fresh UUID and flowing the default `summarize` / `keep` of the manager in unless the input overrides them — auto-activates the first, and an already-present `id` throws. |
|
|
2149
|
+
| `switch` | `ConversationInterface \| undefined` | Re-points `active` at the conversation with `id` and returns it; an unknown `id` returns `undefined` and leaves `active` unchanged, never throwing. |
|
|
2150
|
+
| `open` | `Promise<ConversationInterface \| undefined>` | Resolves a conversation by id and activates it — from the registry when present, else hydrated from the optional `ConversationStoreInterface` (`store`); `undefined` when it is neither registered nor stored. |
|
|
2151
|
+
| `save` | `Promise<boolean>` | Persists a registered conversation's `ConversationInterface.snapshot` to the optional `ConversationStoreInterface` (`store`) — `true` when persisted, `false` when there is no store or the id is unknown; a store failure propagates. |
|
|
2152
|
+
| `remove` | `boolean` | Removes one conversation by id, or a batch — `true` only when every supplied id was removed; clears `active` when a removed conversation was the active one. |
|
|
2153
|
+
| `clear` | `void` | Removes every conversation and clears `active`. |
|
|
2047
2154
|
|
|
2048
2155
|
#### `ConversationStoreInterface`
|
|
2049
2156
|
|
|
@@ -2087,12 +2194,15 @@ The conversation ledger. The `respond` method serves one request through to its
|
|
|
2087
2194
|
|
|
2088
2195
|
#### `LedgerRequestInterface`
|
|
2089
2196
|
|
|
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.
|
|
2197
|
+
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 `scope`, `sent`, `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, and `attempts` data members stay Surface rows. The `apply(scope)` method records the scope applied by the plan for conditional restoration when the call settles.
|
|
2091
2198
|
|
|
2092
2199
|
| Method | Returns | Summary |
|
|
2093
2200
|
| --------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
|
|
2094
2201
|
| `enter` | `Message` | Appends the request's content to a conversation as a user message, once, and holds it as `message`. |
|
|
2095
2202
|
| `open` | `void` | Opens a pass, which becomes the current pass. |
|
|
2203
|
+
| `apply` | `void` | Records the scope applied by the ledger's plan for conditional restoration at settle. |
|
|
2204
|
+
| `fault` | `void` | Records an error the request's run reported through its `fault` event. |
|
|
2205
|
+
| `faulted` | `boolean` | Reports whether the request's run reported this error through its `fault` event. |
|
|
2096
2206
|
| `adopt` | `void` | Records the selection the current pass's run adopted and adds the usage it spent. |
|
|
2097
2207
|
| `observe` | `void` | Starts a gauge call in the current pass, making that pass's call in flight final. |
|
|
2098
2208
|
| `spend` | `void` | Adds one call's reported usage to the current pass and records it on the call in flight. |
|
|
@@ -2124,6 +2234,9 @@ const selection: Selection = {
|
|
|
2124
2234
|
}
|
|
2125
2235
|
request.adopt(selection, conversation.count)
|
|
2126
2236
|
request.observe({ estimate: 40, tools: 2 }, conversation.count)
|
|
2237
|
+
const failure = new Error('the judge is unreachable')
|
|
2238
|
+
request.fault(failure)
|
|
2239
|
+
request.faulted(failure) // true — the request's run reported this error through its `fault` event
|
|
2127
2240
|
request.spend({ prompt: 52, completion: 8, total: 60 })
|
|
2128
2241
|
request.usage // { prompt: 82, completion: 10, total: 92 } — the selection's usage and the call's
|
|
2129
2242
|
request.calls // [{ estimate: 40, tools: 2, prompt: 52, completion: 8 }] — the call in flight took its usage
|
|
@@ -2143,18 +2256,18 @@ request.lines('Refunds over $100 need a manager.') // undefined — no recall re
|
|
|
2143
2256
|
|
|
2144
2257
|
The ledger's filing engine. The `classify` method asks the judge what the conversation's recorded judgments lack, and the readers derive every answer from those judgments and the cutoffs. It carries no data members.
|
|
2145
2258
|
|
|
2146
|
-
| Method | Returns | Summary
|
|
2147
|
-
| ---------------- | ----------------------------- |
|
|
2148
|
-
| `classify` | `Promise<ClassifierResult>` | Asks every filing question the conversation's judgments lack an answer for.
|
|
2149
|
-
| `category` | `LedgerCategory \| undefined` | Returns the
|
|
2150
|
-
| `quiet` | `boolean` | Returns true
|
|
2151
|
-
| `decisive` | `boolean` | Returns true if the message is filed as decisive; false otherwise.
|
|
2152
|
-
| `topics` | `ReadonlySet<string>` | Returns the desk topics the message is filed under.
|
|
2153
|
-
| `classification` | `LedgerClassification` | Returns the filing of every message in the conversation.
|
|
2259
|
+
| Method | Returns | Summary |
|
|
2260
|
+
| ---------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2261
|
+
| `classify` | `Promise<ClassifierResult>` | Asks every filing question the conversation's judgments lack an answer for. |
|
|
2262
|
+
| `category` | `LedgerCategory \| undefined` | Returns the assigned or recorded category, or undefined when no category reaches its cutoff or the user literal floor suppresses a quiet winner. |
|
|
2263
|
+
| `quiet` | `boolean` | Returns true for a quiet assignment or a recorded quiet weight at the cutoff, except for a user message carrying an id or number; false otherwise. |
|
|
2264
|
+
| `decisive` | `boolean` | Returns true if the message is filed as decisive; false otherwise. |
|
|
2265
|
+
| `topics` | `ReadonlySet<string>` | Returns the desk topics the message is filed under. |
|
|
2266
|
+
| `classification` | `LedgerClassification` | Returns the filing of every message in the conversation. |
|
|
2154
2267
|
|
|
2155
2268
|
#### `GaugeInterface`
|
|
2156
2269
|
|
|
2157
|
-
The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read the calls of the request in progress, and the `observe` method folds a finished request in. The `scale` and `overhead` data members stay Surface rows. The `scale` member holds the
|
|
2270
|
+
The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read the calls of the request in progress, and the `observe` method folds a finished request in. The `scale` and `overhead` data members stay Surface rows. The `scale` member holds the last learned price; the `overhead` member holds the construction price. A call's optional `spared` member defaults to zero. Observation rescales only when the first call held exactly all overhead (`spared` absent or zero) or none (`spared` at or above overhead), subtracting `max(0, overhead - spared)` from reported prompt usage. A partially spared first call keeps the existing scale. Estimated use adds that reduced overhead to `scale * estimate`. When no tool is advertised, the ledger spares all overhead and can rescale exactly. When some tools remain, it spares the estimated price of the JSON array of every omitted definition, capped at overhead; a partial share is not learned from, so the calibrated scale remains until a first call with exact overhead can update it.
|
|
2158
2271
|
|
|
2159
2272
|
| Method | Returns | Summary |
|
|
2160
2273
|
| ----------- | -------- | ---------------------------------------------------------------------------------------------------- |
|
|
@@ -2177,15 +2290,15 @@ These invariants hold across `src/core` ↔ `agent.md`:
|
|
|
2177
2290
|
- **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
2291
|
- **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
2292
|
- **Scope filtering.** A scope holds one three-way allow-list per category (`instructions` by `name`, `skills` by `name`, `memos` by `name`, `tools` by `name`, `files` by `path`), applied through `filterAllowList`, and `narrow` intersects each list, so narrowing only tightens. The scope's filters never touch messages; message inclusion is the conversation's through compaction and, when a handler is set, the selection's. The loop filters the advertised definitions by `scope.tools`, so a scoped-out tool is neither described nor callable, and `build()` never contains a tool's name or schema.
|
|
2180
|
-
- **The agent loop (`Agent` / `createAgent`).** `Agent` builds the provider input, then iterates up to `limit`: stream a turn, fold its usage, append any assistant tool calls, and dispatch them. Each `ToolResult` becomes a tool message whose `call` names the paired call, in the reply's call order, because ids can repeat; a string value is the content unchanged, `undefined` is `''`, another value is its `JSON.stringify` text,
|
|
2293
|
+
- **The agent loop (`Agent` / `createAgent`).** `Agent` builds the provider input, then iterates up to `limit`: stream a turn, fold its usage, append any assistant tool calls, and dispatch them. Each `ToolResult` becomes a tool message whose `call` names the paired call, in the reply's call order, because ids can repeat; a string value is the content unchanged, `undefined` is `''`, another value is its `JSON.stringify` text, a value JSON can't carry becomes a tool failure the model reads, and a failure's content is its `error`. A reply with no tool calls ends the loop.
|
|
2181
2294
|
- **One run shared by `generate` and `stream`.** `generate` drains the private run `stream` exposes, so a `generate` result deep-equals a drained `stream` on the same input.
|
|
2182
2295
|
- **The `AgentChunk` stream.** `stream().events` yields, per turn, each answer delta as `token`, each reasoning delta as `think`, then optional `usage`, then one `ask` chunk per asked call, then one `tool` chunk per dispatched call. `result` resolves the settled `AgentResult`: the content, the joined thinking, the summed optional usage, `partial`, and the optional `stop`. A `usage` chunk carries the call's streamed-answer `estimate` beside its usage.
|
|
2183
2296
|
- **Bounded, paced, capped.** Each run folds the external `signal`, the `timeout`, and the `budget` and `allowance` signals into one cancel; a cancel resolves `{ partial: true, content }` with what streamed, while a genuine provider or tool error rejects `result` and sets `status` to `error`. `scheduler.yield` runs between turns and never after the last, and `limit` caps tool iteration.
|
|
2184
2297
|
- **Pull and push observation on the `Agent`; the rest event-free.** The provider contract, the conversation registry, and the context carry no emitter, while the instruction and scope managers and each conversation own one. The `Agent` pairs the `AgentChunk` stream with an `emitter` over `AgentEventMap` (`start`, `turn`, `tool`, `usage`, `allow`, `ask`, `deny`, `finish`, `error`, `abort`, `exhaust`, `fault`, `select`) and has no `token` or `think` event. The emitter routes a listener throw to the `error` option, and a cancelled run emits `abort` then `finish`.
|
|
2185
2298
|
- **Doc ↔ source method bijection.** The `## Methods` tables list exactly the call-signature members of every interface named there, and each implementing class exposes exactly its interface's methods.
|
|
2186
|
-
- **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins,
|
|
2187
|
-
- **A denied call is fed back, never executed.** The loop consults `authority
|
|
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
|
|
2299
|
+
- **The authority gate (`Authority` / `createAuthority`).** `evaluate({ call })` walks the ordered `rules` first-match-wins, returning the matched rule's `verdict`, and returns the required `fallback` when none match. A missing `fallback` or a rule with no `verdict` throws `AgentError` coded `'AUTHORITY'` at construction. `evaluate` is synchronous. `ask(context, decision, signal)` resolves the `ask` option's answer and rejects with an `AgentError` coded `'APPROVER'` when no handler is set. The gate is event-free.
|
|
2300
|
+
- **A denied call is fed back, never executed.** The loop consults `authority` after scope admits a call, and denies the call when the agent holds none, which only a tool added later to an agent built with no `tools` can reach. A call no definition advertises is denied with the scope note before the authority evaluates it, under every verdict, and its `deny` event carries no decision. A `deny` verdict, and an `ask` the approver refuses or leaves unanswered, become the failure arm `{ success: false, id, name, error }` without running the tool. A call that `allow` cleared whose tool is replaced or removed before dispatch is denied too: the model reads the `denied` note of `AUTHORITY_NOTES`, and its `deny` event carries the reason `<name> changed after its decision` and no decision. Executed results and denials merge in the reply's call order, each producing a `tool` chunk and a tool message.
|
|
2301
|
+
- **Durable, serializable agent jobs (`AgentJobInput` + `AgentRegistry`).** An `AgentJobInput` names its `provider`, `tools`, `authority`, and `scheduler` and carries its data directly, and `AgentRegistry.build(input, signal?)` checks it exactly against `agentJobContract`, throwing `AgentError` with code `REGISTRY` and the faults on a misspelled key, then rehydrates a seeded, signal-wired `Agent` from the named pools. An unknown name throws `AgentError` with code `REGISTRY` and the message `unknown <category>: <name>`, and a job that names `tools` and no `authority` throws the same code at `build`.
|
|
2189
2302
|
- **Partial is a configurable failure (`partial`).** A durable job's handler throws `AgentJobError` carrying the partial `AgentResult` unless `partial: true`, which resolves the partial as success. `isAgentJobError` narrows a caught value.
|
|
2190
2303
|
- **Concurrency, retries, and persistence come from the substrate.** `createAgentQueue` composes `createQueue` and `createAgentRunner` composes `createRunner`, adding only rehydration through the registry and the partial policy.
|
|
2191
2304
|
- **Sub-agent fan-out through `controller.spawn`.** A runner job's handler spawns each declared child through `controller.spawn`, and the child runs as a sub-agent beside the parent. Both pass their signal into `registry.build`, so a queue or runner cancel commits the rehydrated agent's partial. A unit spawns its declared children on its first attempt only, so a retried parent never runs a child twice: the runner's handler is the `execute` method of one `AgentFanout`, which records each unit it fanned out.
|
|
@@ -2193,24 +2306,24 @@ These invariants hold across `src/core` ↔ `agent.md`:
|
|
|
2193
2306
|
- **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
2307
|
- **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
2308
|
- **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
|
|
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
|
|
2309
|
+
- **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, sections, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events. `MemoryConversationStore` keeps snapshots in a map and `DatabaseConversationStore` in one opaque JSON column narrowed by `isConversationSnapshot`, both through `get`, `set`, and `delete`. `open(id)` activates a registry hit or hydrates a store hit, keeps a conversation registered under `id` during the store read, and throws `ConversationError` `'SNAPSHOT'` on a snapshot whose `id` is not `id`; `DatabaseConversationStore.get` throws the same code on such a row and on a row that fails the guard, and `set` refuses what `get` would. `add` throws `ConversationError` `'ID'` on an id already live. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, the registry and `active` unchanged. `save(id)` returns `false` when no store or conversation exists. `MemoStoreInterface` is the memo twin: `MemoryMemoStore` and `DatabaseMemoStore` persist a `MemoSnapshot` by its memo set id through `get`, `set`, and `delete`, and the host authors what it stores, because a memo can be model-written and a stored memo set hydrates as written after `isMemoSnapshot` accepts it.
|
|
2310
|
+
- **Limit exhaustion, the three failure layers, and per-run options.** A run that exhausts `limit` while its last turn still requested tools settles `partial: true` and emits `exhaust` instead of `abort`. The loop charges the `allowance` mid-stream from the `estimateTokens` estimate of each turn's content, and charges the cost `budget` the reported usage after each call, net of the estimate only when the `allowance` is the `budget`, or the estimate when the call reported none, a call that failed with a genuine provider error included; it never charges twice. `AgentResult.stop` names the one layer, `meter`, `budget`, or `model`, that stopped the final provider call first. `AgentRunOptions` members override their construction defaults for one run, `conversation` and `prompt` have no construction default, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a positive safe integer throws `AgentError` with code `LIMIT`.
|
|
2198
2311
|
- **Construction-time context wiring.** `AgentOptions.instructions`, `skills`, `memos`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
|
|
2199
|
-
- **`strict` — fault escalation.**
|
|
2200
|
-
- **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `
|
|
2312
|
+
- **`strict` — fault escalation.** `AgentOptions.strict` defaults to `true`: an automatic-compaction summarizer failure and each selection fault emit `fault` and then settle the run `error`, and with `strict: false` the run continues. A strict run also refuses a final answer that misses the run's `schema` with `AgentError` `'SCHEMA'`, and a request still over the window with `AgentError` `'WINDOW'`, whose message reads `the request measures <consumed> against a window of <max> and this run folds no further`. A cancel at a select site wins over `strict`, and a manual `conversation.compact()` always propagates its own error.
|
|
2313
|
+
- **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `sections` entries after a successful merge; when a fold exceeds it, the oldest sections merge into one through a summarizer call and `collapse` fires. A cap that is not a positive safe integer throws `ConversationError` with code `SECTIONS`, and a `keep` that is not a nonnegative safe integer throws it with code `KEEP`. A digest that is not a string or whose trimmed text is empty refuses the fold it would commit with `'SUMMARY'`; such a digest for a capped merge refuses the merge and keeps the fold already committed, one section over the cap, which the next sound merge collapses.
|
|
2201
2314
|
- **`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
2315
|
- **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
2316
|
|
|
2204
|
-
With `strict
|
|
2317
|
+
With `strict`, the default, that request throws `AgentError` `'WINDOW'`. With `strict: false`, no error and no agent event marks that point: the loop sends the over-window request, and no reading covers the provider's behavior past its window, so read the `consumed` and `exhausted` members of your `window` `Budget`, which hold the last request the loop measured, after a run.
|
|
2205
2318
|
|
|
2206
|
-
|
|
2319
|
+
In the from-stop reading of 2026-11-03, `compact({ keep: 0 })` frees one request: with a scripted summarizer and the same text, under a gauge overhead of 352, the next request measured 10358 tokens with 9 recaps, the new recap being the recorded 2385 characters. In the separate fixture reading of 2026-11-03, a conversation at `keep: 0` from goal 35, whose fold at goal 36 takes 4 messages and leaves 8 recaps, measured 9750 under that recap and 11139 under a recap of 7942 characters. The sections stay, so each later fold adds a recap against the same window. Only a `sections` cap or `cumulative` lowers that smallest request, and each needs a fold with an eligible slice. At that stop under `keep: 2` the live tail is a user, an assistant, and a user message, so `compact()` folds nothing and a strict retry refuses again; the sections merge at `compact({ keep: 0 })` or at the admission of a later run whose new prompt leaves an eligible slice. The two can't combine. `cumulative` has no per-call form, so it needs a conversation rebuilt from `snapshot()` with `ConversationInput.cumulative`. A host that reserves less output can set a larger `max` on the same model.
|
|
2207
2320
|
|
|
2208
|
-
Beside that stop, `cumulative` has a reading and no recommendation.
|
|
2321
|
+
Beside that stop, `cumulative` has a reading and no recommendation. In the cumulative reading of 2026-11-03, seeded from that run's goal 32 on Ollama 0.40.14, it sealed goals 33 to 48 with three folds, each into one section, and the first prompts after those folds read 2958 to 3192 tokens, where the first prompts after the first seven folds of the 2026-11-02 and 2026-11-03 recording without it read 2733 to 11176. Its recaps kept fewer literals by `extractLiterals`: at goal 48, 11 of 170 ids and 14 of 112 numbers of 147 folded messages (254018 characters, median 577, 95th percentile 6716, maximum 6911) in a recap of 3456 characters; at goal 34, 14 of 138 ids and 15 of 96 numbers of 116 folded messages (177397 characters, median 580, 95th percentile 4824, maximum 5030) in a recap of 4844 characters. The 2026-11-02 and 2026-11-03 recording without it kept 57 of 138 ids and 41 of 96 numbers over the same 116 messages at goal 34, in 6 recaps of 31077 characters, and 48 of 122 ids and 41 of 87 numbers over 104 messages of 158238 characters at goal 32, in 5 recaps of 23135 characters. The originals stay on the section, and `search` and `rehydrate` read them back; they reach the model only through a tool the host registers, and Agent ships none. This is one arm, one seed, and one recording on two Ollama versions, so the figures state no cause, and no quality label reads these recaps. No reading on this model compares a `sections` cap with `cumulative`.
|
|
2209
2322
|
|
|
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.
|
|
2323
|
+
- **`sanitizeUsage`.** `sanitizeToken` turns a non-finite or non-positive count into `0` and floors a positive fraction, and `sanitizeUsage` applies it to each field. A settled provider result crosses the provider-result guard before charging or folding its usage; malformed present usage refuses the result. The loop sanitizes an abort partial's usage, and absent usage retains the estimate.
|
|
2211
2324
|
- **`AgentError` — the concurrency guard.** `stream()` throws `AgentError` with code `CONCURRENCY` and `context: { agent }` synchronously when a run is in flight and the agent carries a `window`, or when the run's effective `budget` or `allowance` is an instance a live run holds; after those checks it throws one with `context: { agent, conversation }`, naming the conversation's id, when a live run is bound to the run's conversation. Runs holding distinct instances on distinct conversations with no `window` overlap. The refused run never starts either bound, so the live run stays bound to it. The guard compares conversation instances: two `Conversation` values opened from one stored snapshot are distinct to it and run at once on an agent with no `window` and distinct budgets, so a host opens each thread once and keys its thread registry by principal and thread. A `prompt` that is not an exact `AgentPrompt`, a `budget` or `allowance` that does not implement `BudgetInterface`, or a `conversation` that does not implement `ConversationInterface` throws `ContractError` with code `placement` before either bound starts, and a refused run appends no `prompt`. `isAgentError` narrows a caught value, and a `REGISTRY` error's `context` names the `category` and `name`.
|
|
2212
2325
|
- **`agentResultToJSON` — the portable `AgentResult` projection.** The helper accepts `unknown`, never throws, reads each structural field once, and returns a fresh exact `{ content, thinking?, usage?, partial, stop? }` `JSONValue`, or `undefined` for invalid input; a malformed `stop` refuses the whole value. Finite negative and fractional usage counts are preserved, and extra fields are dropped.
|
|
2213
|
-
- **The provider engine's request and stream.** The engine posts `JSON.stringify(encode(request))` to `url + (path ?? '')` with a JSON content type the `headers` hook can extend, decodes the body through `readChunks`, and feeds every framed record and the `finish` tail through `read`. A record whose `read` returns a `result` ends the call with that result, and
|
|
2326
|
+
- **The provider engine's request and stream.** The engine posts `JSON.stringify(encode(request))` to `url + (path ?? '')` with a JSON content type the `headers` hook can extend, decodes the body through `readChunks`, and feeds every framed record and the `finish` tail through `read`. A record whose `read` returns a `result` ends the call with that result, and under the default `strict` a stream that ends with neither a settled result nor a `done` record throws `ProviderError` with code `PROTOCOL`. A non-OK body is read through `readBodyText` to at most `MAX_ERROR_BODY_LENGTH` bytes and its remainder cancelled, and each reader releases its lock on every exit.
|
|
2214
2327
|
- **The wire shapes and the compiled contracts.** The shapes declare each JSON projection and the contracts compile them, each strictly narrower than its domain type, so a value JSON can't carry is refused rather than dropped and a `ToolContext` appears in no wire shape. `RelayProvider.encode` projects the request through `requestToRelay`, which reads each declared member as the request presents it: a getter runs, and an inherited declared member crosses. The clone of that projection uses property descriptors and consults no getter, prototype, or `toJSON` serializer; a non-JSON value is refused before fetching.
|
|
2215
2328
|
- **The relay protocol (`createRelay` / `RelayStream` / `RelayProvider`).** The request is a `POST` of one `providerRequestContract` document, and the response is newline-delimited `RelayFrame` records under `RELAY_CONTENT_TYPE`, written under backpressure, with every upstream failure reduced to `RELAY_PROVIDER_MESSAGE`. `authorize` is mandatory and runs before the body is read; the handler answers `401`, `413` at the byte `limit`, `400`, or `502` with no body, or `422` with one `text/plain` line per page `system` message or tool definition its policy refuses, and the browser receives each as a `ProviderError` with code `HTTP`. An inbound abort, a client disconnecting included, cancels the upstream turn.
|
|
2216
2329
|
- **`ProviderError` and its codes.** `ProviderError` carries a `code` and, for `HTTP` alone, a `status`: `HTTP` reports a non-OK response as `provider error: <status>` with ` - <excerpt>` only when the error body had text, `PROTOCOL` a missing body, a refused record, or a `strict` stream with no settled result, and `PROVIDER` a relay `error` frame. A cancel throws `ProviderAbortError`, never `ProviderError`.
|
|
@@ -2228,7 +2341,7 @@ These invariants hold across `src/core` ↔ `agent.md`:
|
|
|
2228
2341
|
- **Selection faults.** A thrown handler, a returned `fault`, a conversation changed under the handler, and a selected `system` message, carrying `ConversationError` `'ROLE'` over `view()`, each emit `fault`; a throw builds from `view()` with no `select` event, and a returned `fault` charges its usage before `fault` fires. With `strict` set, each settles the run `error`. A cancel at a select site wins over every fault, and the run commits partial without a further provider call.
|
|
2229
2342
|
- **Selection cost.** Selection usage is charged in full to the cost `budget` and folded into `AgentResult.usage`, with no `usage` chunk or `usage` event.
|
|
2230
2343
|
- **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`
|
|
2344
|
+
- **Judgments in a snapshot.** A snapshot carries `judgments` only while the store holds one, and a snapshot without the member validates and restores. Its judgments are the stored frozen records, so copy one before you edit it, and hydrating takes an owned frozen copy. A judgment whose `usage` member is present with the value `undefined` is refused, so omit the member from an in-memory snapshot. `isJudgment` is a guard constant, so it reads an empty `.name`.
|
|
2232
2345
|
|
|
2233
2346
|
## Patterns
|
|
2234
2347
|
|
|
@@ -2282,7 +2395,8 @@ interface TextOptions extends ProviderOptions {
|
|
|
2282
2395
|
class TextProvider extends AgentProvider<string> {
|
|
2283
2396
|
readonly name = 'text'
|
|
2284
2397
|
constructor(options: TextOptions) {
|
|
2285
|
-
|
|
2398
|
+
// Raw text has no terminal record, so a stream that stops reads as complete.
|
|
2399
|
+
super({ ...options, path: '/generate', strict: false })
|
|
2286
2400
|
}
|
|
2287
2401
|
frame(): ProviderParserInterface<string> {
|
|
2288
2402
|
return new TextFrame()
|
|
@@ -2299,7 +2413,7 @@ class TextProvider extends AgentProvider<string> {
|
|
|
2299
2413
|
}
|
|
2300
2414
|
```
|
|
2301
2415
|
|
|
2302
|
-
That provider drives the whole runtime unchanged — `createAgent`, the tool loop, the authority gate, and durable jobs all read it through `ProviderInterface`. Take the switches deliberately. Leave `split` at its default when the backend inlines its reasoning as `<think>` spans in the answer, and set `split: false` when the backend already separates reasoning onto its own field, because splitting twice re-classifies text the backend has already ruled on.
|
|
2416
|
+
That provider drives the whole runtime unchanged — `createAgent`, the tool loop, the authority gate, and durable jobs all read it through `ProviderInterface`. Take the switches deliberately. Leave `split` at its default when the backend inlines its reasoning as `<think>` spans in the answer, and set `split: false` when the backend already separates reasoning onto its own field, because splitting twice re-classifies text the backend has already ruled on. A `read` that recognizes the wire's terminal record returns `done: true`, and the engine folds every increment into the settled result, so a stream that stops before that record throws `ProviderError` coded `'PROTOCOL'`. Pass `strict: false` only when the wire has no terminal record, as the raw text subclass in the preceding fence does, because then a cut stream reads as complete.
|
|
2303
2417
|
|
|
2304
2418
|
### Asking a System One server a choice, a noul, and a score
|
|
2305
2419
|
|
|
@@ -2401,13 +2515,13 @@ That judge answers through `ask` like any other. With `batch: false` the engine
|
|
|
2401
2515
|
|
|
2402
2516
|
Every configuration sends one request layout, position by position. The following table lists what fills each position under each strategy:
|
|
2403
2517
|
|
|
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
|
|
2410
|
-
| Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same
|
|
2518
|
+
| Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
|
|
2519
|
+
| ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2520
|
+
| `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 |
|
|
2521
|
+
| `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 |
|
|
2522
|
+
| Tail | `view()` | one `assistant` recap per section, opening with `CONVERSATION_RECAP_PREFIX`, then the live tail | the seed tail, with each lookup result as its stub, then each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall |
|
|
2523
|
+
| Request | the last stored `user` message; images attach here | the same | a built copy of the `user` turn: the `## Records` and `## Rules` lines the window doesn't hold and `## Request` before the prompt, or the prompt alone when it has no line to add; images attach here |
|
|
2524
|
+
| Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
|
|
2411
2525
|
|
|
2412
2526
|
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
2527
|
|
|
@@ -2451,7 +2565,7 @@ The following rules complete the table:
|
|
|
2451
2565
|
|
|
2452
2566
|
### Relaying a browser provider through your own server
|
|
2453
2567
|
|
|
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.
|
|
2568
|
+
When you compose `createAgent(browser, { tools, authority })` in the page, the agent dispatches page tools there after the Node provider returns a tool call, for the definitions the relay forwards: those the server declares in `tools.definitions` or `tools.accept` admits. The Node server runs the relay handler and upstream inference. See [Placement proofs](#placement-proofs) for the planned Chromium receipt; the executed transcription described next proves an HTTP hop in Node.
|
|
2455
2569
|
|
|
2456
2570
|
A browser must never hold a model credential. Mount `createRelay` on your own server, where the credential already lives, and give the browser `createRelayProvider` pointed at that route: the browser drives a `ProviderInterface` like any other, and the credential never leaves the server. The handler is a plain `(request: Request) => Promise<Response>`, so any fetch-standard router mounts it — this composition mounts it on an `@orkestrel/router` dispatcher. Each half that follows runs in its own process: copy the server half into your server and the browser half into your browser bundle.
|
|
2457
2571
|
|
|
@@ -2541,7 +2655,10 @@ tools.add(
|
|
|
2541
2655
|
PAGE_TOOLS.map((definition) => createTool({ ...definition, execute: () => readSelection() })),
|
|
2542
2656
|
)
|
|
2543
2657
|
const browser = createRelayProvider({ url: 'https://app.example/relay' })
|
|
2544
|
-
const agent = createAgent(browser, {
|
|
2658
|
+
const agent = createAgent(browser, {
|
|
2659
|
+
tools,
|
|
2660
|
+
authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
|
|
2661
|
+
})
|
|
2545
2662
|
```
|
|
2546
2663
|
|
|
2547
2664
|
The server mounts the same definitions beside its own text:
|
|
@@ -2621,7 +2738,11 @@ for (const principal of ['ada', 'grace']) {
|
|
|
2621
2738
|
const agent = createAgent(provider, {
|
|
2622
2739
|
tools,
|
|
2623
2740
|
conversations: threads,
|
|
2624
|
-
authority: createAuthority({
|
|
2741
|
+
authority: createAuthority({
|
|
2742
|
+
rules,
|
|
2743
|
+
fallback: { zone: 'files', verdict: 'deny' },
|
|
2744
|
+
ask: approver.ask,
|
|
2745
|
+
}),
|
|
2625
2746
|
})
|
|
2626
2747
|
sessions.set(principal, { agent, threads, approver })
|
|
2627
2748
|
}
|
|
@@ -2758,12 +2879,19 @@ Advertising and dispatch are the halves of one exchange: hand `definitions()` to
|
|
|
2758
2879
|
|
|
2759
2880
|
```ts
|
|
2760
2881
|
import type { ProviderInterface } from '@orkestrel/agent'
|
|
2882
|
+
import { numberShape, objectShape } from '@orkestrel/contract'
|
|
2761
2883
|
import { createToolManager, createTool } from '@orkestrel/tool'
|
|
2762
2884
|
|
|
2763
2885
|
// `messages` and `signal` come from the host application.
|
|
2764
2886
|
declare const provider: ProviderInterface
|
|
2765
2887
|
const tools = createToolManager()
|
|
2766
|
-
tools.add(
|
|
2888
|
+
tools.add(
|
|
2889
|
+
createTool({
|
|
2890
|
+
name: 'add',
|
|
2891
|
+
contract: objectShape({ a: numberShape(), b: numberShape() }),
|
|
2892
|
+
execute: (args) => Number(args.a) + Number(args.b),
|
|
2893
|
+
}),
|
|
2894
|
+
)
|
|
2767
2895
|
|
|
2768
2896
|
const turn = await provider.generate(messages, signal, tools.definitions())
|
|
2769
2897
|
if (turn.tools) {
|
|
@@ -2825,7 +2953,7 @@ tools.add(
|
|
|
2825
2953
|
},
|
|
2826
2954
|
}),
|
|
2827
2955
|
)
|
|
2828
|
-
const agent = createAgent(provider, { tools })
|
|
2956
|
+
const agent = createAgent(provider, { tools, authority })
|
|
2829
2957
|
const stream = agent.stream()
|
|
2830
2958
|
await entered.promise
|
|
2831
2959
|
agent.abort('request ended')
|
|
@@ -2866,7 +2994,7 @@ result.stop?.layer // 'meter' when the estimate ran out first, 'budget' when the
|
|
|
2866
2994
|
|
|
2867
2995
|
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
2996
|
|
|
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.
|
|
2997
|
+
An allow clears a call for the tool instance the registry held when the turn advertised it; if that instance is replaced or removed before dispatch, a `deny` follows with the reason `<name> changed after its decision` and no decision, so `deny` can follow that call's `allow`, and neither instance runs. Each call is checked once more right before it starts, so a handler that replaces or removes a later call's tool before its first await, or changes whether that tool is annotated `consequential`, gets the later call the same `deny`. The manager keeps its own policy for each call, and a supplied manager must resolve the tool when `execute` is entered, as `ToolManager` does. A cancel that ends the turn before dispatch emits no such `deny`.
|
|
2870
2998
|
|
|
2871
2999
|
The following observers wire at construction and later:
|
|
2872
3000
|
|
|
@@ -3032,7 +3160,7 @@ import { createAgent } from '@orkestrel/agent'
|
|
|
3032
3160
|
import { createToolManager } from '@orkestrel/tool'
|
|
3033
3161
|
|
|
3034
3162
|
declare const provider: ProviderInterface
|
|
3035
|
-
const agent = createAgent(provider, { tools: createToolManager() })
|
|
3163
|
+
const agent = createAgent(provider, { tools: createToolManager(), authority })
|
|
3036
3164
|
|
|
3037
3165
|
// The first add auto-activates — agent.context.workspaces.active is this workspace, so build()
|
|
3038
3166
|
// renders its text files into the `## Workspace` section on every turn.
|
|
@@ -3104,7 +3232,7 @@ const modes = new Map(
|
|
|
3104
3232
|
}),
|
|
3105
3233
|
)
|
|
3106
3234
|
|
|
3107
|
-
const agent = createAgent(provider, { tools, select: judged })
|
|
3235
|
+
const agent = createAgent(provider, { tools, authority, select: judged })
|
|
3108
3236
|
async function ask(content: string): Promise<void> {
|
|
3109
3237
|
agent.context.messages.add({ role: 'user', content })
|
|
3110
3238
|
await agent.generate()
|
|
@@ -3134,7 +3262,7 @@ Overlapping runs on one agent share its scope and its default handler, so an `ap
|
|
|
3134
3262
|
|
|
3135
3263
|
### Answering without tools
|
|
3136
3264
|
|
|
3137
|
-
When the next turn must answer from what it already holds, apply a scope with an empty `tools` list: `createScope({ name: 'answer', tools: [] })`. The package exports no constant for it.
|
|
3265
|
+
When the next turn must answer from what it already holds, apply a scope with an empty `tools` list: `createScope({ name: 'answer', tools: [] })`. The package exports no constant for it. A reply with no calls ends the run as the answer with `partial: false`, and each call a reply still carries emits `deny` with the reason `TOOL is not in the active scope`, gets a denial the model reads, and costs another turn, as [Scoping a turn](#scoping-a-turn) states. That reason is frozen copy, so a harness can match it verbatim.
|
|
3138
3266
|
|
|
3139
3267
|
The following run ends answer-only:
|
|
3140
3268
|
|
|
@@ -3143,13 +3271,16 @@ import type { ProviderInterface } from '@orkestrel/agent'
|
|
|
3143
3271
|
import { createAgent, createScope } from '@orkestrel/agent'
|
|
3144
3272
|
import { createTool, createToolManager } from '@orkestrel/tool'
|
|
3145
3273
|
|
|
3146
|
-
declare const provider: ProviderInterface // replies with
|
|
3274
|
+
declare const provider: ProviderInterface // replies with a stray `refund` call, then the answer
|
|
3147
3275
|
declare function log(name: string, reason: string | undefined): void
|
|
3148
3276
|
|
|
3149
3277
|
const tools = createToolManager()
|
|
3150
3278
|
tools.add(createTool({ name: 'refund', execute: () => 'refunded' }))
|
|
3151
|
-
const agent = createAgent(provider, {
|
|
3152
|
-
|
|
3279
|
+
const agent = createAgent(provider, {
|
|
3280
|
+
tools,
|
|
3281
|
+
authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }),
|
|
3282
|
+
})
|
|
3283
|
+
agent.emitter.on('deny', (call, reason) => log(call.name, reason)) // 'refund', 'refund is not in the active scope'
|
|
3153
3284
|
agent.context.apply(createScope({ name: 'answer', tools: [] }))
|
|
3154
3285
|
agent.context.messages.add({ role: 'user', content: 'Refund invoice 42.' })
|
|
3155
3286
|
const result = await agent.generate() // { content: 'Refunds need a manager.', partial: false }
|
|
@@ -3159,15 +3290,15 @@ const result = await agent.generate() // { content: 'Refunds need a manager.', p
|
|
|
3159
3290
|
|
|
3160
3291
|
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
3292
|
|
|
3162
|
-
| Strategy | Set it through | What the next request holds
|
|
3163
|
-
| -------------------------------- | -------------------------------------------------------------------------------------- |
|
|
3164
|
-
| Plain agent | `createAgent(provider)` with no `window` | the whole `view()`
|
|
3165
|
-
| Automatic compaction | `AgentOptions.window` and a summarizable conversation | one recap per section, then the live tail
|
|
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
|
|
3167
|
-
| Compaction with `cumulative` | `ConversationOptions.cumulative` or `ConversationInput.cumulative` | one recap, then the live tail
|
|
3168
|
-
| Ledger | `createLedger(provider, options)` | the built head, the seed tail, and a copy of the request turn with
|
|
3293
|
+
| Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
|
|
3294
|
+
| -------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
3295
|
+
| Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
|
|
3296
|
+
| 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 |
|
|
3297
|
+
| 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` |
|
|
3298
|
+
| 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 |
|
|
3299
|
+
| Ledger | `createLedger(provider, options)` | the built head, the seed tail, each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall, and a copy of the request turn with the record lines the window doesn't hold | the conversation, read through the `recall` tool | a judge and fitted cutoffs are required, and the ledger refuses no over-window prompt |
|
|
3169
3300
|
|
|
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
|
|
3301
|
+
Build a ledger from a provider, a judge, the lookups, and the measured questions, add the seed history to its conversation, and send each request through the `respond` method. Read the last message of each `select` event's selection, the copy of the request turn, to see the record lines the ledger added for that request; the exchanges before it in the selection hold the lines earlier copies showed. The following ledger serves two requests; a scripted provider stands in for the model and a scripted judge for Mica:
|
|
3171
3302
|
|
|
3172
3303
|
```ts
|
|
3173
3304
|
import type {
|
|
@@ -3212,7 +3343,18 @@ const judge: JudgeInterface = {
|
|
|
3212
3343
|
Object.entries(request.questions).map(([id, question]): [string, JudgeAnswer] => [
|
|
3213
3344
|
id,
|
|
3214
3345
|
question.form === 'choice'
|
|
3215
|
-
? {
|
|
3346
|
+
? {
|
|
3347
|
+
form: 'choice',
|
|
3348
|
+
probabilities: {
|
|
3349
|
+
fact: 0.1,
|
|
3350
|
+
rule: 0.9,
|
|
3351
|
+
correction: 0,
|
|
3352
|
+
request: 0,
|
|
3353
|
+
opinion: 0,
|
|
3354
|
+
chatter: 0,
|
|
3355
|
+
distractor: 0,
|
|
3356
|
+
},
|
|
3357
|
+
}
|
|
3216
3358
|
: { form: 'noul', noul: 0.1 },
|
|
3217
3359
|
]),
|
|
3218
3360
|
),
|
|
@@ -3255,12 +3397,12 @@ second.content // 'Yes. Refunds over $100 need a manager.'
|
|
|
3255
3397
|
copies[0]
|
|
3256
3398
|
// '## 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
3399
|
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##
|
|
3400
|
+
// '## Records\n### Brightwater Studio (BW-20931)\n- Order BW-5512 for account BW-20931: Brightwater Studio.\n- Refund due $148.50.\n\n## Request\nDoes the Brightwater Studio refund need a manager?' — the first copy still holds the rule
|
|
3259
3401
|
```
|
|
3260
3402
|
|
|
3261
|
-
The second request names Brightwater Studio, so its
|
|
3403
|
+
The second request names Brightwater Studio, so its copy carries that owner's record, built from the first request's lookup result. It leaves out the rule, because the first request's copy, which follows the seed tail in the window with its final reply, holds it. 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
3404
|
|
|
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
|
|
3405
|
+
To carry a ledger across a restart, store what its `snapshot` method returns and pass it back as the `snapshot` option of a later `createLedger` call. The snapshot is plain JSON: the conversation with its judgments, the ids of the requests, notes, and failed tool results the ledger marked, the gauge, and the window while it holds an exchange. Narrow a parsed snapshot with the `isLedgerSnapshot` guard first, because construction refuses a snapshot the guard refuses with `LedgerError` code `'SNAPSHOT'`. The hydrated ledger makes no calibration call when the 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 sends the prompt the first would send for the same request. The window holds every line this request selects, so its copy is the request itself:
|
|
3264
3406
|
|
|
3265
3407
|
```ts
|
|
3266
3408
|
import type { LedgerInterface, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
|
|
@@ -3281,16 +3423,100 @@ restored.agent.emitter.on('select', (selection) => copies.push(selection.message
|
|
|
3281
3423
|
const third = await restored.respond('Is the Brightwater Studio refund approved yet?')
|
|
3282
3424
|
third.content // 'Not yet. A manager must approve it.'
|
|
3283
3425
|
copies[0]
|
|
3284
|
-
// '
|
|
3426
|
+
// 'Is the Brightwater Studio refund approved yet?' — what the first ledger writes for the same request
|
|
3285
3427
|
```
|
|
3286
3428
|
|
|
3287
3429
|
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.
|
|
3288
3430
|
|
|
3431
|
+
#### Composing a records desk for a small local GPU
|
|
3432
|
+
|
|
3433
|
+
A records desk on a small local GPU runs two models by role: the agent's provider writes the replies, and the ledger's judge files the messages. Pass the provider as the first argument of the `createLedger` function and the judge as its `judge` option. The window and the `recall` offer are the ledger's own behavior and need no configuration.
|
|
3434
|
+
|
|
3435
|
+
When the two models don't fit on one GPU, run the judge on the CPU through its provider options, so that neither model evicts the other between requests. The `createOllamaJudge` function of `@orkestrel/ollama` forwards `options: { num_gpu: 0 }` to the daemon for this.
|
|
3436
|
+
|
|
3437
|
+
A judge can also be two judges. The `ask` method of `JudgeInterface` takes every question of one request, so a host can compose a two-step judge on it: a fast first judge takes each choice question, the host keeps the answers it trusts, and a second judge takes the rest. The following fence composes one and names models only as examples:
|
|
3438
|
+
|
|
3439
|
+
```ts
|
|
3440
|
+
import type {
|
|
3441
|
+
JudgeInterface,
|
|
3442
|
+
JudgeRequest,
|
|
3443
|
+
JudgeResult,
|
|
3444
|
+
LedgerThreshold,
|
|
3445
|
+
ProviderInterface,
|
|
3446
|
+
} from '@orkestrel/agent'
|
|
3447
|
+
import { buildJudgeResult, createLedger, LEDGER_QUESTIONS, measureAnswer } from '@orkestrel/agent'
|
|
3448
|
+
|
|
3449
|
+
declare const provider: ProviderInterface // the agent's model on the GPU, for example `createOllama({ model: 'qwen3.5:4b-q4_K_M' })`
|
|
3450
|
+
declare const fast: JudgeInterface // a first judge, for example `createSystemOneJudge({ url, model: 'tev1:0.8b' })`
|
|
3451
|
+
declare const slow: JudgeInterface // a second judge on the CPU, for example `createOllamaJudge({ model, system, options: { num_gpu: 0 } })`
|
|
3452
|
+
declare const thresholds: LedgerThreshold // fitted on LEDGER_QUESTIONS and your judges
|
|
3453
|
+
declare const cutoff: number // the winning probability this host trusts from the first judge, fitted on its own rows
|
|
3454
|
+
|
|
3455
|
+
class TwoStepJudge implements JudgeInterface {
|
|
3456
|
+
readonly id = 'two-step'
|
|
3457
|
+
readonly name = 'two-step'
|
|
3458
|
+
readonly model: string
|
|
3459
|
+
readonly #first: JudgeInterface
|
|
3460
|
+
readonly #second: JudgeInterface
|
|
3461
|
+
readonly #keep: number
|
|
3462
|
+
|
|
3463
|
+
constructor(first: JudgeInterface, second: JudgeInterface, keep: number) {
|
|
3464
|
+
this.#first = first
|
|
3465
|
+
this.#second = second
|
|
3466
|
+
this.#keep = keep
|
|
3467
|
+
// A stored judgment is reused only under one identity, so all that changes an answer joins it.
|
|
3468
|
+
this.model = JSON.stringify({ first: first.model, second: second.model, keep })
|
|
3469
|
+
}
|
|
3470
|
+
|
|
3471
|
+
async ask(request: JudgeRequest, signal: AbortSignal): Promise<JudgeResult> {
|
|
3472
|
+
const entries = Object.entries(request.questions)
|
|
3473
|
+
const choices = entries.filter(([, question]) => question.form === 'choice')
|
|
3474
|
+
const asked: JudgeResult =
|
|
3475
|
+
choices.length === 0
|
|
3476
|
+
? { model: this.model, answers: {} }
|
|
3477
|
+
: await this.#first.ask({ ...request, questions: Object.fromEntries(choices) }, signal)
|
|
3478
|
+
const kept = Object.entries(asked.answers).filter(([, answer]) => {
|
|
3479
|
+
const { winner, probability } = measureAnswer(answer)
|
|
3480
|
+
return probability >= this.#keep && winner !== 'correction'
|
|
3481
|
+
})
|
|
3482
|
+
const answered: JudgeResult = {
|
|
3483
|
+
model: this.model,
|
|
3484
|
+
answers: Object.fromEntries(kept),
|
|
3485
|
+
...(asked.usage === undefined ? {} : { usage: asked.usage }),
|
|
3486
|
+
}
|
|
3487
|
+
const rest = entries.filter(([id]) => !Object.hasOwn(answered.answers, id))
|
|
3488
|
+
return rest.length === 0
|
|
3489
|
+
? answered
|
|
3490
|
+
: buildJudgeResult(this.model, [
|
|
3491
|
+
answered,
|
|
3492
|
+
await this.#second.ask({ ...request, questions: Object.fromEntries(rest) }, signal),
|
|
3493
|
+
])
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
3496
|
+
|
|
3497
|
+
const ledger = createLedger(provider, {
|
|
3498
|
+
judge: new TwoStepJudge(fast, slow, cutoff),
|
|
3499
|
+
system: 'You staff the Larkspur support desk.',
|
|
3500
|
+
topics: [{ name: 'refunds', criterion: 'refund amounts and approvals' }],
|
|
3501
|
+
questions: LEDGER_QUESTIONS,
|
|
3502
|
+
thresholds,
|
|
3503
|
+
capacity: 32_768, // the agent model's context window
|
|
3504
|
+
predict: 8_192, // its generation cap, thinking included
|
|
3505
|
+
})
|
|
3506
|
+
await ledger.respond('Does the Brightwater Studio refund need a manager?')
|
|
3507
|
+
```
|
|
3508
|
+
|
|
3509
|
+
The `model` member holds both judges' identities and the cutoff, so changing any of them asks each question again. This class rejects when its first judge rejects. For a fuller worked example that refers a first judge's fault to the second and checks each distribution, read `studies/memory/StudyMemoryJudge.ts` in this repository and adapt it: it holds one study's policy, and no published entry exports it. The executed transcription runs the preceding class with a scripted provider and recording judges; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
|
|
3510
|
+
|
|
3511
|
+
The application decides which models to run, which thresholds to keep, and whether to run two judges at all. The package ships the mechanism and none of that policy.
|
|
3512
|
+
|
|
3513
|
+
The same line holds for what a request carries beyond its messages. To have a judge choose the tools, instructions, memos, or skills of a request, ask the judge before the request and apply the answer through the `narrow` method of the active scope. Narrowing only tightens, so an answer can't admit a tool the scope excludes. A tool list or system text that changes between requests costs the reuse of the prompt, and a wrong answer withholds that tool for the request.
|
|
3514
|
+
|
|
3289
3515
|
### Upgrade data written before 0.0.35
|
|
3290
3516
|
|
|
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.
|
|
3517
|
+
Stored data written before 0.0.35 meets the checks of 0.0.35 at its next read. A snapshot that carries a member its shape doesn't declare, the conversation `summary` a 0.0.29 snapshot can hold included, refuses at its next read as well: the stores throw `'SNAPSHOT'` naming the key, because a refused row read as absent would let `open` overwrite it. Read that row through your own table and rewrite it without the key, or delete it with `store.delete`. A stored snapshot that holds a `system` row rejects with `ConversationError` `'ROLE'` and the message `a conversation snapshot holds a system message; a snapshot written before 0.0.35 can hold a system row; remove it before loading`. A queued `AgentJobInput` seed that holds a `system` message fails at `AgentRegistry.build` through `add`, with `ConversationError` `'ROLE'` and the message `a stored message role must be one of "user", "assistant", "tool"; received "system"; host text goes in the system option or an instruction`, and the job's `system` member carries that text.
|
|
3292
3518
|
|
|
3293
|
-
The following fence removes the row from a snapshot read from a store. It narrows the read through `isConversationSnapshot`, which
|
|
3519
|
+
The following fence removes the row from a snapshot read from a store. It narrows the read through `isConversationSnapshot`, which is exact on keys and leaves roles and repeated ids to the hydrate, and it filters `messages` and each section's `messages`, because hydrating checks both and a fold can hold the row in a section:
|
|
3294
3520
|
|
|
3295
3521
|
```ts
|
|
3296
3522
|
import type { ConversationSnapshot, ConversationStoreInterface } from '@orkestrel/agent'
|
|
@@ -3358,7 +3584,10 @@ scopes.remove(scope.id)
|
|
|
3358
3584
|
scopes.clear()
|
|
3359
3585
|
|
|
3360
3586
|
// Authority — `evaluate` decides and `ask` approves (both also reached through the agent loop internally).
|
|
3361
|
-
const authority = createAuthority({
|
|
3587
|
+
const authority = createAuthority({
|
|
3588
|
+
fallback: { zone: 'default', verdict: 'allow' },
|
|
3589
|
+
ask: () => true,
|
|
3590
|
+
})
|
|
3362
3591
|
const call = { id: '1', name: 'add', arguments: {} }
|
|
3363
3592
|
const decision = authority.evaluate({ call }) // { zone: 'default', verdict: 'allow' }
|
|
3364
3593
|
await authority.ask?.({ call }, decision, new AbortController().signal) // true (`ask` is optional on the interface)
|
|
@@ -3449,10 +3678,10 @@ The following test files back this guide:
|
|
|
3449
3678
|
- [`tests/src/core/contexts/scopes/ScopeManager.test.ts`](../tests/src/core/contexts/scopes/ScopeManager.test.ts) — the scope registry's add, lookup, removal, and emitter.
|
|
3450
3679
|
- [`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
3680
|
- [`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
|
|
3681
|
+
- [`tests/src/core/contexts/stores/DatabaseMemoStore.test.ts`](../tests/src/core/contexts/stores/DatabaseMemoStore.test.ts) — the driver-backed memo store's malformed and foreign-id rows refusing with `SNAPSHOT` while an absent row reads as absent, its copy on read, and its table kept apart from the conversation store's on one driver.
|
|
3453
3682
|
- [`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
3683
|
- [`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
|
|
3684
|
+
- [`tests/src/core/agents/Authority.test.ts`](../tests/src/core/agents/Authority.test.ts) — first-match-wins ordering, the refusal of a missing fallback and a missing verdict, the fallback, the `{ call }` context, and the `ask` approver with its `'APPROVER'` refusal.
|
|
3456
3685
|
- [`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
3686
|
- [`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
3687
|
- [`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.
|
|
@@ -3462,13 +3691,13 @@ The following test files back this guide:
|
|
|
3462
3691
|
- [`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
3692
|
- [`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.
|
|
3464
3693
|
- [`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.
|
|
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
|
|
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.
|
|
3694
|
+
- [`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, room, and per-request offer with a host's scope kept and restored, the answer note's lines, the generation cap and thinking per pass, and retained amended sentences with unresolved scope while `recall`, the answer note, and the seed tail keep stored content, the window's extending copies, rungs, emptying, derived pair, rejected request, answered fallback, and stub state, and the snapshot and hydrate: selections and judge keys equal to the uninterrupted ledger's with each emptied mark list as a control, provider prompts equal through five JSON round trips, the `window` member's omission, refusals, and digest checked at hydrate, the JSON round trip, the `'CONCURRENCY'` refusal, the flush before capture, judgments kept across a judge abort, the `'SNAPSHOT'` refusals, the `'ROLE'` refusal of a hydrated `system` message, the gauge precedence, the fork, a recorded correction fixture replayed through a hydrated ledger, the replay from a sorted snapshot, each lookup result read once per selection, a message removed during a judge await kept out of that selection's plan, the forwarding of the `narrow` member to the classifier, head pricing and the built-head calibration, and the host turns: each entry refused during one, another thread's refused run and its recall, an append and a removal that fault the selection with no question about a gone message, a judgment removed during one asked again, an abort and a scheduler fault that leave the ledger free, the same bytes when paced, and the agent's turn between its own turns.
|
|
3695
|
+
- [`tests/src/core/ledgers/LedgerRequest.test.ts`](../tests/src/core/ledgers/LedgerRequest.test.ts) — the request's recall-limit refusal, its single `enter`, its passes with their selections, usage, calls, and thinking, its filing attempts and plan, the draft its last provider turn adopted as the `sent` member, the repeat stop, the recall limit and `close`, and the listings of a recall result.
|
|
3467
3696
|
- [`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.
|
|
3468
3697
|
- [`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.
|
|
3469
3698
|
- [`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 `
|
|
3471
|
-
- [`tests/src/core/ledgers/validators.test.ts`](../tests/src/core/ledgers/validators.test.ts) — `isFraction`, `isPositiveSafeInteger`,
|
|
3699
|
+
- [`tests/src/core/ledgers/helpers.test.ts`](../tests/src/core/ledgers/helpers.test.ts) — the projection helpers from `splitSentences` through `buildRecords` and `selectRecords`, the `normalizeWord` fold, the alias index the `buildLedgerIndex` function builds for the `matchEntities` function, the record renderers, `findLedgerCall`, `rankLedgerCut`, `findLedgerCut`, `buildLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `buildRequestMessage`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `resolvePredict`, `fitSlope`, `digestLedgerWindow`, `collectRecallMessages`, `hasHiddenRecall`, `buildLedgerLineKey`, `collectLedgerLines`, `collectLedgerReplies`, and `collectLedgerEvidence`.
|
|
3700
|
+
- [`tests/src/core/ledgers/validators.test.ts`](../tests/src/core/ledgers/validators.test.ts) — `isFraction`, `isPositiveSafeInteger`, `isLedgerSnapshot`, which refuses every malformed snapshot, an unknown or mis-roled id, a throwing getter, and a revoked proxy, and accepts a snapshot a ledger returned, and `isLedgerWindowSnapshot`, which agrees with the `ledgerWindowContract` constant on a valid window and its malformed neighbors.
|
|
3472
3701
|
|
|
3473
3702
|
### Placement proofs
|
|
3474
3703
|
|