@orkestrel/scaffold 0.0.122 → 0.0.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/agents/skills/orkestrel-harden/scripts/interleave.js +539 -0
  2. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +1163 -0
  3. package/dist/bin/main.js +8 -6
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/agents/orchestration.md +13 -7
  6. package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +4 -3
  7. package/dist/host/agents/skills/orkestrel-dispatch/references/launch.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +4 -2
  9. package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +2 -2
  10. package/dist/host/agents/skills/orkestrel-harden/SKILL.md +16 -3
  11. package/dist/host/agents/skills/orkestrel-harden/references/bindings.md +18 -12
  12. package/dist/host/agents/skills/orkestrel-harden/references/document.md +1 -0
  13. package/dist/host/agents/skills/orkestrel-harden/references/equivalence.md +2 -1
  14. package/dist/host/agents/skills/orkestrel-harden/references/hardening.md +1 -1
  15. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +642 -0
  16. package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +665 -0
  17. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +14 -13
  18. package/dist/host/agents/skills/orkestrel-parallel/references/claude-code.md +13 -13
  19. package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +1 -0
  20. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1433 -0
  21. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +2 -1
  22. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +18 -1
  23. package/dist/host/claude/AGENTS.md +1 -1
  24. package/dist/host/claude/agents/analyst.md +1 -1
  25. package/dist/host/claude/agents/builder.md +1 -1
  26. package/dist/host/claude/agents/distiller.md +2 -1
  27. package/dist/host/claude/agents/grok.md +2 -2
  28. package/dist/host/claude/agents/opus.md +2 -2
  29. package/dist/host/claude/agents/orkestrel.md +7 -7
  30. package/dist/host/claude/agents/reviewer.md +2 -2
  31. package/dist/host/claude/agents/scout.md +2 -1
  32. package/dist/host/claude/agents/verifier.md +1 -1
  33. package/dist/host/claude/rules/campaign.md +12 -11
  34. package/dist/host/claude/rules/documentation.md +1 -0
  35. package/dist/host/claude/rules/patterns.md +14 -0
  36. package/dist/host/claude/rules/quality.md +4 -1
  37. package/dist/host/claude/rules/tests.md +4 -0
  38. package/dist/host/claude/rules/writing.md +1 -1
  39. package/dist/host/claude/skills/orkestrel-parallel/SKILL.md +1 -1
  40. package/dist/host/codex/agents/analyst.toml +4 -1
  41. package/dist/host/codex/agents/astra.toml +1 -1
  42. package/dist/host/codex/agents/builder.toml +1 -1
  43. package/dist/host/codex/agents/distiller.toml +4 -2
  44. package/dist/host/codex/agents/grok.toml +5 -2
  45. package/dist/host/codex/agents/opus.toml +3 -3
  46. package/dist/host/codex/agents/reviewer.toml +6 -2
  47. package/dist/host/codex/agents/scout.toml +5 -1
  48. package/dist/host/codex/agents/verifier.toml +6 -1
  49. package/dist/host/guides/agent.md +1119 -457
  50. package/dist/host/guides/ndjson.md +81 -21
  51. package/dist/host/guides/ollama.md +22 -18
  52. package/dist/host/guides/probe.md +29 -27
  53. package/dist/host/guides/scaffold.md +36 -14
  54. package/dist/host/guides/study.md +538 -450
  55. package/dist/host/manifest.json +66 -48
  56. package/dist/src/core/index.cjs +8 -7
  57. package/dist/src/core/index.cjs.map +1 -1
  58. package/dist/src/core/index.d.cts +1 -4
  59. package/dist/src/core/index.d.ts +1 -4
  60. package/dist/src/core/index.js +8 -7
  61. package/dist/src/core/index.js.map +1 -1
  62. package/dist/src/server/index.cjs +87 -8
  63. package/dist/src/server/index.cjs.map +1 -1
  64. package/dist/src/server/index.d.cts +50 -6
  65. package/dist/src/server/index.d.ts +50 -6
  66. package/dist/src/server/index.js +87 -10
  67. package/dist/src/server/index.js.map +1 -1
  68. package/package.json +2 -2
@@ -1,18 +1,25 @@
1
1
  # NDJSON
2
2
 
3
3
  > A stateful newline-delimited-JSON (NDJSON) stream parser: a self-contained handle
4
- > that turns string chunks into the complete records decoded so far, and never throws
5
- > on a malformed, blank, or non-record line.
4
+ > that turns string chunks into the complete records decoded so far, skips a blank
5
+ > line, and skips a malformed or non-record line unless strict mode refuses it.
6
6
 
7
7
  `parse(chunk)` appends `chunk` to an internal buffer and splits it on `\n`: every
8
8
  line before the last is `\n`-terminated, hence complete, and is parsed to a record,
9
9
  while the final segment is held back for the next call, so a line split across chunk
10
10
  boundaries is reassembled the moment its closing `\n` arrives. Each trimmed line is
11
11
  filtered — a blank or whitespace-only line (including one whose only content was a
12
- CRLF's trailing `\r`) is skipped, malformed JSON is skipped silently, and a
13
- non-record value (an array, a primitive, `null`) is dropped — so only plain records
14
- come back, and a line the stream never terminates is never emitted even when the
15
- buffered text already happens to be valid JSON. `clear()` drops the buffered partial
12
+ CRLF's trailing `\r`) is skipped, and by default malformed JSON is skipped silently
13
+ and a non-record value (an array, a primitive, `null`) is dropped — so only plain
14
+ records come back, and a line the stream never terminates is never emitted even when
15
+ the buffered text already happens to be valid JSON. With `strict: true` the parser
16
+ refuses such a line instead: `parse` throws an `NDJSONError` with code `'SYNTAX'`
17
+ for a complete line that is not valid JSON and `'RECORD'` for a complete line that is
18
+ not a plain record. The throwing call returns no record, discards the lines after the
19
+ refused line in the same call too, and leaves the parser cleared, as `clear()` leaves
20
+ it. Blank lines are skipped, and lines are split and trimmed, the same way in both
21
+ modes. An unterminated line throws nothing until a later chunk completes it, so a
22
+ caller ends a stream with `parse('\n')`. `clear()` drops the buffered partial
16
23
  line so a handle can be reused for a fresh stream. Nothing else is wired in: no
17
24
  Emitter, no server, HTTP, or agent coupling. Pair it with a streaming `TextDecoder`
18
25
  when reading a byte stream — the decoder handles partial characters, the parser
@@ -40,6 +47,8 @@ parser.clear() // drop any buffered partial - ready for a fresh stream
40
47
  | Name | Kind | Signature | Summary |
41
48
  | ----------------------- | --------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
42
49
  | `NDJSONParserInterface` | interface | `{ parse(), clear() }` | Represents the stateful NDJSON (newline-delimited JSON) stream-parser contract a consumer holds — a `parse` that turns each string chunk into the complete records decoded so far, and a `clear` that drops the buffered partial line. |
50
+ | `NDJSONParserOptions` | interface | `{ strict? }` | Configures the parser `createNDJSONParser` builds and the `NDJSONParser` constructor accepts — `strict` decides whether a complete line that is not a JSON object is skipped or refused. |
51
+ | `NDJSONErrorCode` | type | `'SYNTAX' \| 'RECORD'` | Names the machine-readable code an `NDJSONError` carries — `'SYNTAX'` for a complete line that is not valid JSON, and `'RECORD'` for a complete line that is valid JSON but not a plain record. |
43
52
 
44
53
  Types a helper's parameter as `NDJSONParserInterface` and returns the records
45
54
  its `parse` call completes:
@@ -52,16 +61,46 @@ function feed(parser: NDJSONParserInterface, chunk: string): readonly Record<str
52
61
  }
53
62
  ```
54
63
 
64
+ ### Errors
65
+
66
+ A strict parser throws an `NDJSONError`, and `isNDJSONError` narrows a caught value to
67
+ one:
68
+
69
+ | Name | Kind | Signature | Summary |
70
+ | --------------- | -------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
71
+ | `NDJSONError` | class | `new (code: NDJSONErrorCode, message: string) => NDJSONError` | Represents the refusal of a complete NDJSON line by a strict parser, carrying the machine-readable `NDJSONErrorCode` a `catch` branches on. |
72
+ | `isNDJSONError` | function | `(value: unknown) => value is NDJSONError` | Narrows an unknown caught value to an `NDJSONError`. |
73
+
74
+ Catches the refusal of a truncated line and branches on its code:
75
+
76
+ ```ts
77
+ import { createNDJSONParser, isNDJSONError } from '@orkestrel/ndjson'
78
+
79
+ const parser = createNDJSONParser({ strict: true })
80
+ try {
81
+ parser.parse('{"a":\n')
82
+ } catch (error) {
83
+ if (isNDJSONError(error)) error.code // 'SYNTAX'
84
+ }
85
+ ```
86
+
87
+ `isNDJSONError` recognizes the own identity brand and the declared code across package
88
+ copies and module formats. It accepts subclass instances without requiring their name and
89
+ refuses unbranded look-alikes, transparent proxies, objects carrying only the brand, and an
90
+ unknown code. The constructor stores the error itself under
91
+ `Symbol.for('@orkestrel/ndjson.NDJSONError')` as a non-enumerable, non-writable own
92
+ property. The message is fixed per code and quotes no text from the refused line.
93
+
55
94
  ### Factories
56
95
 
57
- | Name | Kind | Signature | Summary |
58
- | -------------------- | -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
59
- | `createNDJSONParser` | function | `() => NDJSONParserInterface` | Creates an NDJSON (newline-delimited JSON) stream parser and returns it as an `NDJSONParserInterface` — a fresh `NDJSONParser` holding the buffer, so a caller holds the published contract rather than the class. |
96
+ | Name | Kind | Signature | Summary |
97
+ | -------------------- | -------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
98
+ | `createNDJSONParser` | function | `(options?: NDJSONParserOptions) => NDJSONParserInterface` | Creates an NDJSON (newline-delimited JSON) stream parser and returns it as an `NDJSONParserInterface` — a fresh `NDJSONParser` holding the buffer, so a caller holds the published contract rather than the class. |
60
99
 
61
100
  #### Create a parser
62
101
 
63
102
  Creates a parser through the factory and feeds it two complete lines, then a
64
- line that completes only once its own newline arrives:
103
+ line that completes only after its own newline arrives:
65
104
 
66
105
  ```ts
67
106
  import { createNDJSONParser } from '@orkestrel/ndjson'
@@ -72,11 +111,30 @@ parser.parse('{"c":3}') // [] — buffered until its trailing newline arrives
72
111
  parser.parse('\n') // [{ c: 3 }]
73
112
  ```
74
113
 
114
+ #### Create a strict parser
115
+
116
+ Creates a parser that refuses a non-record line, then shows that the refusal dropped the
117
+ partial line the same call carried:
118
+
119
+ ```ts
120
+ import { createNDJSONParser, isNDJSONError } from '@orkestrel/ndjson'
121
+
122
+ const parser = createNDJSONParser({ strict: true })
123
+ parser.parse('{"a":1}\n\n') // [{ a: 1 }] - a blank line is still skipped
124
+ try {
125
+ parser.parse('[1,2]\n{"b"')
126
+ } catch (error) {
127
+ if (isNDJSONError(error)) error.code // 'RECORD'
128
+ }
129
+ parser.parse('\n') // [] - the refusal dropped the partial line
130
+ parser.parse('{"b":2}\n') // [{ b: 2 }]
131
+ ```
132
+
75
133
  ### Classes
76
134
 
77
- | Name | Kind | Signature | Summary |
78
- | -------------- | ----- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
79
- | `NDJSONParser` | class | `new () => NDJSONParserInterface` | Decodes an NDJSON (newline-delimited JSON) stream statefully, implementing `NDJSONParserInterface` over a private buffer the instance owns — each `parse` call returns the records completed so far and reassembles a record split across chunk boundaries. |
135
+ | Name | Kind | Signature | Summary |
136
+ | -------------- | ----- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
137
+ | `NDJSONParser` | class | `new (options?: NDJSONParserOptions) => NDJSONParserInterface` | Decodes an NDJSON (newline-delimited JSON) stream statefully, implementing `NDJSONParserInterface` over a private buffer the instance owns — each `parse` call returns the records completed so far and reassembles a record split across chunk boundaries. |
80
138
 
81
139
  ## Methods
82
140
 
@@ -85,13 +143,14 @@ surface.
85
143
 
86
144
  #### `NDJSONParserInterface`
87
145
 
88
- | Method | Returns | Summary |
89
- | ------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
90
- | `parse` | `readonly Record<string, unknown>[]` | Appends `chunk` to the buffer and returns every complete `\n`-terminated line parsed to a record, skipping a malformed or non-record line; the trailing partial line is retained for the next call, so a line split across a chunk boundary is reassembled when its closing `\n` arrives. |
91
- | `clear` | `void` | Drops any buffered partial line, leaving the handle ready for a fresh stream. |
146
+ | Method | Returns | Summary |
147
+ | ------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
148
+ | `parse` | `readonly Record<string, unknown>[]` | Appends `chunk` to the buffer and returns every complete `\n`-terminated line parsed to a record, skipping a malformed or non-record line unless the parser is strict; the trailing partial line is retained for the next call unless a strict refusal in the same call clears the buffer, so a line split across a chunk boundary is reassembled when its closing `\n` arrives. |
149
+ | `clear` | `void` | Drops any buffered partial line, leaving the handle ready for a fresh stream. |
92
150
 
93
- `parse` holds an unterminated line indefinitely and the buffer has no size
94
- limit, so a caller fronting an untrusted upstream enforces its own byte cap.
151
+ `parse` holds an unterminated line indefinitely, unless a strict refusal in the
152
+ same call clears the buffer, and the buffer has no size limit, so a caller fronting an
153
+ untrusted upstream enforces its own byte cap.
95
154
 
96
155
  ```ts
97
156
  import { NDJSONParser } from '@orkestrel/ndjson'
@@ -105,8 +164,9 @@ parser.parse('{"c":3}\n') // [{ c: 3 }]
105
164
 
106
165
  ## Tests
107
166
 
108
- - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` bijection (value and type exports), the `NDJSONParserInterface` ↔ `NDJSONParser` method bijection, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Create a parser` fence against the `@example` block of that title (pinned so the titled pair cannot be retired silently), and the README pitch against this guide's tagline. It also runs the flagship fences and asserts the values their comments claim.
109
- - [`tests/src/core/NDJSONParser.test.ts`](../tests/src/core/NDJSONParser.test.ts) — that `parse` returns the same records however a stream is cut into chunks, skipping malformed, blank, and non-record lines, withholding a line the stream never terminates, and never throwing on any input.
167
+ - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` bijection (value and type exports), the `NDJSONParserInterface` ↔ `NDJSONParser` method bijection, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Create a parser` and `Create a strict parser` fences against the `@example` blocks of those titles (pinned so the titled pairs cannot be retired silently), and the README pitch against this guide's tagline. It also runs the flagship fences, the strict and Errors fences included, and asserts the values their comments claim.
168
+ - [`tests/src/core/NDJSONParser.test.ts`](../tests/src/core/NDJSONParser.test.ts) — that `parse` returns the same records however a stream is cut into chunks, skipping malformed, blank, and non-record lines, withholding a line the stream never terminates, and never throwing on any input by default; and that a strict parser refuses each malformed line as `'SYNTAX'` and each non-record line as `'RECORD'` with a fixed message, returns no record from the refusing call and leaves the parser cleared, keeps its records however a clean stream is cut into chunks, trims every Unicode space `String.prototype.trim` strips, and returns what the default returns when `strict` is `false`.
169
+ - [`tests/src/core/errors.test.ts`](../tests/src/core/errors.test.ts) — that `isNDJSONError` accepts an `NDJSONError` and a subclass, refuses a look-alike, a transparent proxy, a plain object carrying the brand, and an unknown code, and that the constructor stamps a hidden, fixed brand.
110
170
  - [`tests/policy.test.ts`](../tests/policy.test.ts) — repository coding law: source placement, exports, readonly contracts, syntax, and the prose this guide is written in.
111
171
  - [`tests/config.test.ts`](../tests/config.test.ts) — the root configuration's aliases and projects, the policy Oxlint plugin's rules against its rule tester, and the configuration helpers.
112
172
 
@@ -7,7 +7,7 @@ The package supplies a chat provider wire on the `/api/chat` path and a raw judg
7
7
 
8
8
  The design is deliberately spare — an external boundary kept honest. Every `unknown` wire value is narrowed through the `@orkestrel/contract` guards (`isRecord`, `isString`, `isNumber`) rather than a type assertion, and a missing or malformed field degrades to a sensible default (empty content, no usage, `{}` arguments) rather than a throw. Every provider call streams: the request always carries `stream: true`, and `generate` drains the same NDJSON path `stream` exposes, so neither call can report content the other would not. The wire `think` flag is configurable through `OllamaOptions.think` (default `false`) and overrideable per call through `ProviderStreamOptions.think`; with `think: true` the daemon returns reasoning on the separate `message.thinking` channel, streamed live as `thinking` deltas. Either way the base's splitter separates any `<think>` span the daemon inlines anyway, so the assembled `content` is clean and the reasoning surfaces as `ProviderResult.thinking`. The agent records that reasoning on the assistant message. The provider's `replay` policy filters stored reasoning at the provider input boundary; the Ollama request mapper omits that reasoning from the wire. A per-call `ProviderStreamOptions.schema` (a JSON schema object, from `@orkestrel/agent`) forwards verbatim as the wire's structured-output `format` field, and is omitted from the request when no schema is supplied. `OllamaOptions.truncate` and `OllamaOptions.shift` are opt-in context controls: each is sent as a top-level wire key only when set, so omission delegates to the daemon default and leaves the request body unchanged, and `false` requests refusal instead of truncation or shifting. A fixture test proves the encoding and makes no claim about daemon support. Token usage reuses the `TokenUsage` shape rather than minting its own.
9
9
 
10
- The dependency is strictly one-way: this surface imports the base and the contract types from `@orkestrel/agent` and reaches errors through that base, the parser factory from `@orkestrel/ndjson`, tool-call shapes from `@orkestrel/tool`, the usage shape from `@orkestrel/budget`, and the guards from `@orkestrel/contract` — those packages never import from here. The package publishes two faces. The core face, `@orkestrel/ollama`, is built from `src/core`, which reaches no `node:*` module and no DOM global, so the same build serves a server process and a browser page. The server face, `@orkestrel/ollama/server`, is built from `src/server` and runs in Node only: it imports Node modules, the process session from `@orkestrel/process`, the emitter from `@orkestrel/emitter`, the guards from `@orkestrel/contract`, and the terminal timing reader from the core face, and nothing in `src/core` imports it. The core face is tested live against `qwen3.5:2b-q4_K_M` in a dedicated `service` test project that requires the daemon and warms the model first, with no `skipIf`, while the `src:core` project stays hermetic on canned-transport and recording-proxy assertions that pass with the daemon down. Source: [`src/core`](../src/core), surfaced through the `@orkestrel/ollama` barrel and aliased `@src/core` inside this repo, and [`src/server`](../src/server), surfaced through the `@orkestrel/ollama/server` barrel and aliased `@src/server`.
10
+ The dependency is strictly one-way: this surface imports the base and the contract types from `@orkestrel/agent` and reaches errors through that base, the parser factory from `@orkestrel/ndjson`, tool-call shapes from `@orkestrel/tool`, the usage shape from `@orkestrel/budget`, and the guards from `@orkestrel/contract` — those packages never import from here. The package publishes two faces. The core face, `@orkestrel/ollama`, is built from `src/core`, which reaches no `node:*` module and no DOM global, so the same build serves a server process and a browser page. The server face, `@orkestrel/ollama/server`, is built from `src/server` and runs in Node only: it imports Node modules, the process session from `@orkestrel/process`, the emitter from `@orkestrel/emitter`, the guards from `@orkestrel/contract`, and the terminal timing reader from the core face, and nothing in `src/core` imports it. The core face is tested live against `qwen3.5:4b-q4_K_M` in a dedicated `service` test project that requires the daemon and warms the model first, with no `skipIf`, while the `src:core` project stays hermetic on canned-transport and recording-proxy assertions that pass with the daemon down. Source: [`src/core`](../src/core), surfaced through the `@orkestrel/ollama` barrel and aliased `@src/core` inside this repo, and [`src/server`](../src/server), surfaced through the `@orkestrel/ollama/server` barrel and aliased `@src/server`.
11
11
 
12
12
  ## Surface
13
13
 
@@ -84,7 +84,7 @@ Pass `tools` (a non-empty `ToolDefinition[]` from `@orkestrel/tool`) to advertis
84
84
  | `DEFAULT_OLLAMA_URL` | const | `"http://localhost:11434"` | Names the local Ollama daemon base URL, `'http://localhost:11434'`, assumed when `OllamaOptions.url` is omitted. |
85
85
  | `DEFAULT_KEEP_ALIVE` | const | `"5m"` | Names how long the model stays resident after a call — `'5m'` when `OllamaOptions.keepAlive` is omitted, Ollama's own `keep_alive` default, expressed as a duration string. |
86
86
  | `OLLAMA_CHAT_PATH` | const | `"/api/chat"` | Names the Ollama chat endpoint appended to the configured base URL. |
87
- | `mapMessages` | function | `(messages: readonly Message[]) => WireChatRequest['messages']` | Maps conversation turns onto the `/api/chat` wire's minimal message shape. |
87
+ | `mapMessages` | function | `(messages: readonly Message[]) => WireChatRequest['messages']` | Maps conversation turns onto the `/api/chat` wire's minimal message shape, escaping each listed control token in message content, call names, and top-level arguments. |
88
88
  | `extractContent` | function | `(record: Readonly<Record<string, unknown>>) => string` | Extracts the assistant text of one wire record. |
89
89
  | `extractThinking` | function | `(record: Readonly<Record<string, unknown>>) => string` | Extracts the daemon-side reasoning of one wire record. |
90
90
  | `extractUsage` | function | `(record: Readonly<Record<string, unknown>>) => TokenUsage \| undefined` | Extracts the token usage of one wire record. |
@@ -97,7 +97,13 @@ Pass `tools` (a non-empty `ToolDefinition[]` from `@orkestrel/tool`) to advertis
97
97
 
98
98
  The wire leaves — `mapMessages` and the `extract*` narrowing set — are the pure request projection and response extractions `OllamaProvider` composes. They are exported and unit-tested on their own so the package's highest-risk code, the boundary narrowing of every wire `unknown` through the `@orkestrel/contract` guards, is provable without a daemon. Everything they do not do lives in `@orkestrel/agent`: the deadline, the transport seam, the streaming spine, the splitter, and the assembly of a `ProviderResult`.
99
99
 
100
- `OllamaProvider` declares `name` (`'ollama'`) and inherits the rest of its data members from the base: `id` is the stable per-instance trace label, and `replay` selects which stored assistant reasoning reaches the provider input (default `'none'`). The Ollama request mapper omits stored reasoning from the wire regardless of that policy. Its wire seams are documented under [Methods](#methods), and the `generate` / `stream` boundary it inherits under `AgentProviderInterface` in [`agent.md`](agent.md). `AgentProvider` / `AgentProviderInterface` / `ProviderInterface` / `ProviderOptions` / `ProviderRequest` / `ProviderIncrement` / `ProviderParserInterface` / `ProviderResult` / `ProviderDelta` / `ProviderStreamOptions` / `ProviderError` / `isProviderError` / `ProviderAbortError` / `isProviderAbortError` / `Message` / `ContextSectionFormat` / `InstructionInterface` are owned by `@orkestrel/agent`; `ToolDefinition` / `ToolCall` by `@orkestrel/tool`; the `TokenUsage` shape by `@orkestrel/budget`; `createNDJSONParser` by `@orkestrel/ndjson`. All are reused here, never redefined. The agent package also owns the `JudgeInterface` interface, `JudgeRequest` type, `JudgeResult` interface, `JudgeAnswer` type, `Refusal` interface, `AgentJudge` class, `JudgeError` class, `JudgeAbortError` class, and `computeReading` function.
100
+ `mapMessages` escapes the tokens `MICA_SPECIAL_TOKENS` lists, the list Mica's judge prompt also uses, on every role, the host's `system` text included: message content, a replayed call's name, and each top-level argument key and string value. `escapeSpecialTokens` inserts U+200B after each listed token's opening `<`, so a request holding no listed token keeps its bytes. A nested argument, a tool definition, `format`, `options`, `images`, and `model` stay as given. So when a tool's name spells a listed token, its replayed call reads apart from its definition, and a model that copies the replay names no tool. Two keys of one argument object that differ only by the escape collapse to one in the request, and the last value wins. Stored messages and the call a tool ran with keep their text.
101
+
102
+ The reach is measured on one model and one daemon. On Ollama 0.40.14 with `qwen3.5:2b-q4_K_M`, `<|im_start|>` collapses into one control token in `system`, user, assistant, and tool content, a replayed call's name, an argument key, and a top-level argument string, reading 4 or 5 tokens under the misspelling `<|im_strat|>` of the same length. A tool description and a nested argument string read as text there, 1 token apart, because the renderer encodes them as JSON, and another renderer might differ. The list covers Qwen's role, turn, tool, and reasoning tokens. It does not neutralize other vocabulary tokens or other model families, and a family without a renderer stays a stated limit until the package tests one by the same measurement.
103
+
104
+ A false positive costs an invisible character: text that spells a listed token reaches the model with U+200B inside it, and a model can copy that character into a file.
105
+
106
+ `OllamaProvider` declares `name` (`'ollama'`) and inherits the rest of its data members from the base: `id` is the stable per-instance trace label, and `replay` selects which stored assistant reasoning reaches the provider input (default `'none'`). The Ollama request mapper omits stored reasoning from the wire regardless of that policy. Its wire seams are documented under [Methods](#methods), and the `generate` / `stream` boundary it inherits under `AgentProviderInterface` in [`agent.md`](agent.md). `AgentProvider` / `AgentProviderInterface` / `ProviderInterface` / `ProviderOptions` / `ProviderRequest` / `ProviderIncrement` / `ProviderParserInterface` / `ProviderResult` / `ProviderDelta` / `ProviderStreamOptions` / `ProviderError` / `isProviderError` / `ProviderAbortError` / `isProviderAbortError` / `Message` / `ContextSectionFormat` / `InstructionInterface` are owned by `@orkestrel/agent`; `ToolDefinition` / `ToolCall` by `@orkestrel/tool`; the `TokenUsage` shape by `@orkestrel/budget`; `createNDJSONParser` by `@orkestrel/ndjson`. All are reused here, never redefined. The agent package also owns the `JudgeInterface` interface, `JudgeRequest` type, `JudgeResult` interface, `JudgeAnswer` type, `Refusal` interface, `AgentJudge` class, `JudgeError` class, `JudgeAbortError` class, and `measureAnswer` function.
101
107
 
102
108
  The raw judge exports the following declarations.
103
109
 
@@ -108,7 +114,7 @@ The raw judge exports the following declarations.
108
114
  | `WireGenerateRequest` | interface | `{ model, prompt, raw, stream, logprobs, top_logprobs, keep_alive, options }` | Transliterates the Ollama raw, non-streaming `POST /api/generate` request. |
109
115
  | `Logprob` | interface | `{ token, logprob }` | Carries a token and its log probability from Ollama's top logprob list. |
110
116
  | `createOllamaJudge` | function | `(options: OllamaJudgeOptions) => JudgeInterface` | Creates a Mica judge that reads calibrated candidate probabilities from raw Ollama logprobs. |
111
- | `escapeSpecialTokens` | function | `(text: string) => string` | Escapes Mica control tokens by inserting U+200B after their opening angle bracket. |
117
+ | `escapeSpecialTokens` | function | `(text: string) => string` | Escapes each listed control token by inserting U+200B after its opening angle bracket. |
112
118
  | `renderJudgePrompt` | function | `(state: JudgeEntry, question: JudgeQuestion, system: string) => string` | Mirrors the TypeSafe adapter path of Mica's server, from the `rows_from_request` function in the `typesafe_server.py` file to the `prompt_for` function in the `native.py` file, with disabled thinking. Serializes structured state as JSON with a one-space indent and JavaScript numeric spelling; parity is byte-exact for string states and structured states whose numbers spell the same in both runtimes. |
113
119
  | `buildJudgeLabels` | function | `(question: JudgeQuestion) => ReadonlyMap<string, string>` | Pairs caller candidate keys with Mica's output labels in criteria order. |
114
120
  | `extractTopLogprobs` | function | `(value: unknown) => readonly Logprob[]` | Extracts the first generated position's top logprobs without changing token text. |
@@ -120,7 +126,7 @@ The raw judge exports the following declarations.
120
126
  | `MICA_RENDER_REVISION` | const | `"mica-native-2026-10-07-v1"` | Identifies the Mica prompt render revision used in judge identities. |
121
127
  | `MICA_OPTION_LABELS` | const | `readonly string[]` | Lists Mica's letter labels in codebook order. |
122
128
  | `MICA_NOUL_LABELS` | const | `readonly string[]` | Lists Mica's false and true labels in readout order. |
123
- | `MICA_SPECIAL_TOKENS` | const | `readonly string[]` | Lists the control tokens escaped by Mica's native renderer. |
129
+ | `MICA_SPECIAL_TOKENS` | const | `readonly string[]` | Lists the control tokens escaped on Mica's judge prompt and in chat messages; it neutralizes no other vocabulary token and no other model family. |
124
130
 
125
131
  The server face, `@orkestrel/ollama/server`, exports the following daemon session declarations. It runs in Node only; [Daemon session](#daemon-session) states the lifecycle these declarations carry.
126
132
 
@@ -216,7 +222,7 @@ These invariants hold across `src/core`, `src/server`, and `ollama.md`. The doc
216
222
  2. **Imports each boundary from its owner, no cycle.** `OllamaProvider` extends `AgentProvider` and implements `AgentProviderInterface`; that base, `ProviderRequest`, `ProviderIncrement`, `ProviderParserInterface`, `ProviderInterface`, `ProviderOptions`, and `Message` come from `@orkestrel/agent`. `createNDJSONParser` comes from `@orkestrel/ndjson`, `ToolCall` from `@orkestrel/tool`, `TokenUsage` from `@orkestrel/budget`, and the guards (`isRecord` / `isString` / `isNumber` / `isNonNegativeInteger` / `parseJSONAs`) from `@orkestrel/contract`. The provider errors are owned by `@orkestrel/agent` and `ToolDefinition` by `@orkestrel/tool`: `src/core` imports neither, and both reach a caller through the base — the base throws the errors this wire's failures become, and it accepts the `ToolDefinition[]` a call advertises. Each dependency is one-way and never imports from `@src/core`. No module under `src/` imports `@orkestrel/timeout` — the base arms the deadline — and the manifest declares it as a development dependency for the guide's bounding pattern, which imports it as a consumer would.
217
223
  3. **The `/api/chat` wire body.** `OllamaProvider` POSTs to `${url}${OLLAMA_CHAT_PATH}`, defaulting `url` to `DEFAULT_OLLAMA_URL` and `keep_alive` to `DEFAULT_KEEP_ALIVE`. The body carries `model`, the mapped `messages`, `stream: true` on every provider call, `keep_alive`, and `think` (the per-call `ProviderStreamOptions.think` override when present, else `OllamaOptions.think`, default `false`), adding `options` only when configured, `format` only when the call supplies a `ProviderStreamOptions.schema`, and `tools` only when a non-empty `ToolDefinition[]` is passed. The top-level `truncate` and `shift` keys follow `tools`, each present only when its `OllamaOptions` member is set, with `false` carried verbatim and neither nested in `options`; `generate` and `stream` encode them identically. `false` requires daemon support to take effect. Each tool maps to `{ type: 'function', function: { name } }`, with `description` and `parameters` added only when the corresponding `ToolDefinition` fields are supplied. `title` and `annotations` are **never sent**: the `/api/chat` tool function object carries no field for either. Messages map to the wire's minimal `{ role, content }` turn, with `tool_calls` added only on a turn that replays them and `images` only on a multimodal turn. A non-OK status is the base's failure, not this package's: it throws `ProviderError` with code `'HTTP'`, the response `status`, and a message bounded to an excerpt of the response body.
218
224
  4. **Configurable `think` on the wire; the base's splitter keeps the assembled content clean.** For a thinking-capable model (for example `qwen3`) the per-request `think` flag is the only wire-level reasoning control (its native renderer honours neither the qwen3 `/no_think` token nor a Modelfile `PARAMETER think false`). It is configurable through `OllamaOptions.think` (default `false` — so the general-purpose provider stays immediate for non-thinking models and tests fast) and overrideable per call through `ProviderStreamOptions.think`. Set `think: true` when the caller displays reasoning separately from the answer: the daemon then separates reasoning natively, returning it on the distinct `message.thinking` channel, which `read` reports and the engine yields as `ProviderDelta` `{ channel: 'thinking', text }` and accumulates onto `ProviderResult.thinking`. Either way the base's `split` behaviour stays armed, because a daemon may ignore `think: false` for a thinking model and render reasoning inline as `<think>…</think>` content; `OllamaProvider` passes no `split` to `super`, so the default separation applies and the assembled `content` is the splitter's clean accumulation. The agent records the reasoning on the assistant message. `OllamaOptions.replay` filters its return to the provider input, defaulting to `'none'`; the Ollama request mapper omits stored reasoning from the wire.
219
- 5. **One provider NDJSON path.** Every provider call consumes NDJSON — one JSON object per `\n`-terminated line. `frame()` returns `createNDJSONParser()`, fresh per call, so no call inherits another's half-read record, and the base pairs it with a streaming `TextDecoder` so a record split across byte reads is reassembled. At end of input the base calls `finish(parser)`, which feeds a trailing `\n` through the parser: a non-conformant proxy's final unterminated line is recovered rather than silently dropped. `OllamaProvider` passes no `strict` to `super`, so a stream that ends without a settled record still assembles its result from the deltas it carried.
225
+ 5. **One provider NDJSON path.** Every provider call consumes NDJSON — one JSON object per `\n`-terminated line. `frame()` returns `createNDJSONParser({ strict: true })`, fresh per call, so no call inherits another's half-read record, and the base pairs it with a streaming `TextDecoder` so a record split across byte reads is reassembled. A line that is not JSON, or is JSON and not an object, rejects the call as `ProviderError` `'PROTOCOL'` with the parser's `NDJSONError` as its `cause`. The strict parser does not catch the daemon's in-band `{"error": ...}` record or a stream cut on a line boundary before `done`. At end of input the base calls `finish(parser)`, which feeds a trailing `\n` through the parser: a non-conformant proxy's valid final unterminated line is recovered rather than silently dropped, and a malformed one rejects. `OllamaProvider` passes no `strict` to `super`, so a stream that ends without a settled record still assembles its result from the deltas it carried; that option is the engine's and differs from the parser's.
220
226
  6. **`stream` yields deltas and returns the assembled result.** The engine yields each non-empty clean content delta as `{ channel: 'content', text }` and each daemon-side reasoning delta as `{ channel: 'thinking', text }`; its return value is the assembled `ProviderResult` whose `content` is the splitter's authoritative clean accumulation — the concatenation of the yielded content deltas, except across an implicit-open reclassification, where the reasoning prefix had already streamed before a bare `</think>` revealed it and the yields cannot be recalled — plus any tool calls collected across lines, the usage from the `done` line, and the separated `thinking` when the turn produced any.
221
227
  7. **Usage and truncation from the `done` line (reuses `TokenUsage`).** `read` reports `usage` only for a record whose `done` is `true` and whose `prompt_eval_count` and `eval_count` are both numbers — mapped to `{ prompt, completion, total: prompt + completion }`, the `TokenUsage` shape, imported rather than redefined. A delta line carries no counts and a `done: false` line's counts are ignored, so neither contributes usage, and `ProviderResult.usage` is absent when the turn reported none. `read` projects the same record's `done_reason` through `extractTruncated`: `'length'` (the `num_predict` cap or a full context window) becomes `truncated: true` on the increment and so on `ProviderResult.truncated`, and any other reason, a missing one, or a `done_reason` on a record that is not `done` leaves `truncated` absent. The projection does not read the request's `truncate` setting, so a prompt the daemon truncates under its default returns normally and reports nothing.
222
228
  8. **Tool-call extraction with id-generation (no `as`).** `result.tools` is the model's `message.tool_calls`, each entry narrowed to `{ id, name, arguments }`: the entry and its `function` must be records and `name` a string (else the entry is dropped); `arguments` is the wire object as-is, a JSON string parsed to a record, or `{}` when neither; `id` is the wire's `id` when a string, else a freshly minted `crypto.randomUUID()`. An empty result `tools` is never surfaced — its absence means "no calls".
@@ -225,7 +231,7 @@ These invariants hold across `src/core`, `src/server`, and `ollama.md`. The doc
225
231
  11. **Context framing.** An instruction manager accepts a `ContextSectionFormat<InstructionInterface>` through `createInstructionManager({ format })`. The agent uses that manager to build the instruction text. Ollama structured output uses the separate per-call `ProviderStreamOptions.schema` value, forwarded as the wire `format` field.
226
232
  12. **Event-free.** The provider and the judge are a pure functional boundary — no Emitter, no events. Each call is a function of its arguments. The server face's daemon session is the one emitter in the package, through `OllamaDaemonInterface.emitter`.
227
233
  13. **A core face that runs in a browser.** The `.` entry is built from `src/core`, which imports no `node:*` module and no DOM global; the scoped core typecheck compiles it with the `ESNext` and `WebWorker` libraries and no ambient `@types`, so neither Node's globals nor the DOM's are in scope, and the base binds `globalThis.fetch` to its own receiver so a browser does not throw `Illegal invocation` on a bare transport reference. The `./server` entry, built from `src/server`, imports Node modules and the process session, so a browser bundle takes the `.` entry alone. [`tests/service/page.test.ts`](../tests/service/page.test.ts) gates that claim rather than recording it: it launches the host's own Chrome or Edge through `@orkestrel/browser`, serves the built `@orkestrel/ollama` core entry and its whole `@orkestrel` import closure from an import map on a `127.0.0.1` fixture, and reads the page's requests from the browser's own request log. The page loads with no uncaught error and no console error, on the recorders a deliberate page fault then makes report; an `Agent` holding a page-defined DOM-writing `Tool` completes a tool loop against the live daemon through a same-origin `createRelay` server, where the model's recorded call reaches the page, the tool's minted receipt is read back out of the real DOM and found again as the `role: 'tool'` message of the relay request and the `/api/chat` request that follow the turn the call was dispatched in, and the run settles with `partial: false`; the page issues exactly one `POST /inference` per turn and nothing else across the whole operation window, with a deliberate `/control` request proving such a window can report one; a wrong bearer arrives as `ProviderError` with code `'HTTP'` and status `401` with no daemon request made; and `createOllama` in the page answers a prompt over `/api/chat` on the daemon's own origin after `requireDaemonOrigin` confirms the daemon permits the page's origin. Each attempt ends within its allowance plus its release share, so nothing the attempt schedules outlasts the case that holds it. The attempt's signal cancels the part of the connection the installed `BrowserOptions.signal` races — discovery, the port-free check, the launch, and `client.connect()` — and the attempt's own race is what bounds every phase after that, the target listing the connection ends with included; [`tests/service/page.test.ts`](../tests/service/page.test.ts) and the `PAGE_BOUNDS` table it spends state the mechanism. The model's choice to call a tool is retried at most 3 times, and that choice is the only reading another attempt buys: every attempt retains its observations before any page read can throw, and only a run that completed an answer without dispatching the tool spends another launch. An acquisition, read, release, or run failure ends the retry, and so does a run that deadline interrupted before it settled — an interrupted run reports no tool call for a reason another launch cannot clear, so retrying it would report the exhaustion as the model never choosing the tool. The request accounting is asserted over each retained attempt, so what the gate establishes is that the model called the tool within those attempts and that no attempt's traffic went unread. The daemon is the remaining limit — a page reaches `/api/chat` directly only where the daemon, or a proxy in front of it, answers the page's origin; otherwise relay the call through your own server ([Relaying through your own server](#relaying-through-your-own-server)).
228
- 14. **Tested live against a real local Ollama (no `skipIf`).** The live tests run against a real Ollama daemon — no mocks, only genuine third-party calls — model `qwen3.5:2b-q4_K_M`, with `OLLAMA_HOST` / `OLLAMA_MODEL` overridable. Unlike the other surfaces, the dedicated `service` project requires the daemon: `tests/setupService.ts` throws a clear error if it is unreachable and warms the model (a `num_predict: 1` chat) before the suite, so the live tests run unconditionally (no `describe.skipIf`). The project runs serially (`fileParallelism: false`) with a 120s test/hook timeout so a cold load cannot flake it; `keep_alive` keeps the model resident across files, and `bash scripts/ollama.sh` brings the daemon and model up before the battery in CI. Assertions are structural — they hold whatever wording a small model produces — and never pin exact output. The hermetic half sits in `tests/src/core/`, and the relay round trip is proved hermetically in [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) and live in [`tests/service/relay.test.ts`](../tests/service/relay.test.ts).
234
+ 14. **Tested live against a real local Ollama (no `skipIf`).** The live tests run against a real Ollama daemon — no mocks, only genuine third-party calls — model `qwen3.5:4b-q4_K_M`, with `OLLAMA_HOST` / `OLLAMA_MODEL` overridable. Unlike the other surfaces, the dedicated `service` project requires the daemon: `tests/setupService.ts` throws a clear error if it is unreachable and warms the model (a `num_predict: 1` chat) before the suite, so the live tests run unconditionally (no `describe.skipIf`). The project runs serially (`fileParallelism: false`) with a 120s test/hook timeout so a cold load cannot flake it; `keep_alive` keeps the model resident across files, and `bash scripts/ollama.sh` brings the daemon and model up before the battery in CI. Assertions are structural — they hold whatever wording a small model produces — and never pin exact output. The hermetic half sits in `tests/src/core/`, and the relay round trip is proved hermetically in [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) and live in [`tests/service/relay.test.ts`](../tests/service/relay.test.ts).
229
235
  15. **Doc ↔ source method bijection.** Each `## Methods` table lists the methods its class or interface declares: `frame`, `encode`, `read`, and `finish` for `OllamaProvider`; `encode` and `read` for `OllamaJudge`; `start`, `unload`, `stop`, and `destroy` for `OllamaDaemonInterface`, which `OllamaDaemon` implements with no other public method. The inherited `generate`, `stream`, and `ask` methods are declared by the agent package's engines.
230
236
 
231
237
  16. **Render.** The raw prompt mirrors the TypeSafe adapter path of Mica's server: the `rows_from_request` function in the `typesafe_server.py` file followed by the `prompt_for` function in the `native.py` file. Structured state uses JSON with a one-space indent and JavaScript numeric spelling: JavaScript cannot distinguish 100.0 from 100 and spells an exponent as 1e-7 where Python spells 1e-07. Parity is byte-exact for string states and structured states whose numbers spell the same in both runtimes. The wire preserves the system prompt and escapes control tokens in state, instructions, option names, and descriptions with U+200B after the opening angle bracket. Noul criteria render false before true; an absent or empty side renders its key. Choice names render in brackets unless empty, positional (including Unicode decimal digits), or equal to the wire label. A null description renders the `None` text. Score levels omit names. The assistant suffix disables thinking with the `<think>\n\n</think>\n\n` text.
@@ -307,10 +313,10 @@ Declare each model's digest as the `digest` field its `/api/tags` entry reports,
307
313
 
308
314
  ### Ask Mica a noul
309
315
 
310
- Supply the prompt Mica was trained with, declared as the `MICA_SYSTEM` constant, and the calibration shipped with the model. The answer stores the probability of yes; the `computeReading` function derives the winning side and its probability. The recorded daemon body returns a false winner near 0.990 for this state. Set the `timeout` option to 300000 ms; a recorded cold load took 230850 ms on a CPU host.
316
+ Supply the prompt Mica was trained with, declared as the `MICA_SYSTEM` constant, and the calibration shipped with the model. The answer stores the probability of yes; the `measureAnswer` function derives the winning side and its probability. The recorded daemon body returns a false winner near 0.990 for this state. Set the `timeout` option to 300000 ms; a recorded cold load took 230850 ms on a CPU host.
311
317
 
312
318
  ```ts
313
- import { computeReading } from '@orkestrel/agent'
319
+ import { measureAnswer } from '@orkestrel/agent'
314
320
  import { createOllamaJudge } from '@orkestrel/ollama'
315
321
 
316
322
  const MICA_SYSTEM =
@@ -340,7 +346,7 @@ const result = await judge.ask(
340
346
  new AbortController().signal,
341
347
  )
342
348
  const answer = result.answers.deletion
343
- if (answer !== undefined) console.log(computeReading(answer))
349
+ if (answer !== undefined) console.log(measureAnswer(answer))
344
350
  else console.log(result.refusals?.deletion?.missing)
345
351
  ```
346
352
 
@@ -349,7 +355,7 @@ else console.log(result.refusals?.deletion?.missing)
349
355
  For a model that Ollama serves on the System One endpoint, use the agent package's factory. A request carries the choice, noul, and score together. Ollama 0.40.0 serves the `tev1:0.8b` model on this path and refuses Mica with HTTP 400; the package makes no capability check.
350
356
 
351
357
  ```ts
352
- import { computeReading, createSystemOneJudge } from '@orkestrel/agent'
358
+ import { measureAnswer, createSystemOneJudge } from '@orkestrel/agent'
353
359
 
354
360
  const judge = createSystemOneJudge({ url: 'http://localhost:11434', model: 'tev1:0.8b' })
355
361
  const result = await judge.ask(
@@ -379,7 +385,7 @@ const result = await judge.ask(
379
385
  new AbortController().signal,
380
386
  )
381
387
  for (const [id, answer] of Object.entries(result.answers)) {
382
- console.log(id, computeReading(answer))
388
+ console.log(id, measureAnswer(answer))
383
389
  }
384
390
  ```
385
391
 
@@ -535,12 +541,11 @@ const url = `http://127.0.0.1:${port}/inference` // the route the browser half d
535
541
 
536
542
  `createRelay` returns a plain `(request: Request) => Promise<Response>` handler and stops there, so a runtime adapter turns the runtime's inbound request into a `Request`, hands the dispatcher's `Response` back to the runtime, and aborts that request's signal when the client disconnects, so a reader that goes away cancels the daemon turn instead of leaving it running. `@orkestrel/server` supplies that adapter ([`server.md`](server.md)), and a runtime whose own handler already takes a `Request` and returns a `Response` needs none.
537
543
 
538
- In the browser, `createRelayProvider` drives that route like a local provider over the page's own `fetch`. `@orkestrel/agent` declares no parser dependency, so the browser application supplies one — `createNDJSONParser` from `@orkestrel/ndjson` here.
544
+ In the browser, `createRelayProvider` drives that route like a local provider over the page's own `fetch`. The relay provider frames with Agent's strict default and refuses a malformed frame as `ProviderError` `'PROTOCOL'`.
539
545
 
540
546
  ```ts
541
547
  import { createAbort } from '@orkestrel/abort'
542
548
  import { createRelayProvider } from '@orkestrel/agent'
543
- import { createNDJSONParser } from '@orkestrel/ndjson'
544
549
 
545
550
  declare const url: string // the route the server half bound
546
551
  const abort = createAbort()
@@ -548,14 +553,13 @@ const messages = [{ id: '1', role: 'user', content: 'Say hello.' }] as const
548
553
 
549
554
  const browser = createRelayProvider({
550
555
  url,
551
- parser: createNDJSONParser,
552
556
  headers: () => ({ authorization: 'Bearer session-token' }),
553
557
  })
554
558
  const relayed = await browser.generate(messages, abort.signal)
555
559
  relayed.content // the daemon's answer, reassembled from the relay's frames
556
560
  ```
557
561
 
558
- A refusal never becomes a frame: a wrong credential reaches the browser as a `ProviderError` with code `'HTTP'` and status `401`, and the provider on the server is never entered. [`agent.md`](agent.md) states the frame vocabulary, the byte limit, and the rest of the refusal statuses. A page calling the relay from another origin needs CORS permission headers the relay route does not send, so serve the page from the relay server's own origin (which is what [`tests/service/page.test.ts`](../tests/service/page.test.ts) does, from one loopback fixture serving the page, its modules, and the route) or put an origin-checking, CORS-answering middleware in front of the route (see the server guide), naming the `OPTIONS` preflight the browser sends with `authorization` and `content-type` as the requested headers.
562
+ A refusal never becomes a frame: a wrong credential reaches the browser as a `ProviderError` with code `'HTTP'` and status `401`, and the provider on the server is never entered. A relay refuses a page `system` message and an undeclared tool definition with status `422` by default, the `RelayOptions.system` and `RelayOptions.tools` options admit them, and [`agent.md`](agent.md) states the policy. [`agent.md`](agent.md) also states the frame vocabulary, the byte limit, and the rest of the refusal statuses. A page calling the relay from another origin needs CORS permission headers the relay route does not send, so serve the page from the relay server's own origin (which is what [`tests/service/page.test.ts`](../tests/service/page.test.ts) does, from one loopback fixture serving the page, its modules, and the route) or put an origin-checking, CORS-answering middleware in front of the route (see the server guide), naming the `OPTIONS` preflight the browser sends with `authorization` and `content-type` as the requested headers.
559
563
 
560
564
  ### Routing through your own server (obfuscated tokens)
561
565
 
@@ -791,7 +795,7 @@ The hermetic projects — `src:core`, `src:server`, `setup`, `guides`, `conforma
791
795
 
792
796
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` and `src/server` bijection (value + type exports), the `OllamaProvider`, `OllamaJudge`, and `OllamaDaemonInterface` method bijections, and the equality gate: every `Summary` cell against its declaration's description paragraph, each titled fence — `Ask Mica a noul` and `createOllama + generate` — against the `@example` block of that title, with `Ask Mica a noul` pinned so the titled pair cannot be retired silently, and the README pitch against this guide's tagline. It also runs the flagship fences and asserts the values they log. Of the server face's fences, it runs the declaration refusal, the model digest comparison, and the retained unload reply, none of which starts a process, and never runs the dedicated daemon fence, which starts a real executable. It extracts each streaming fence from the README and from this guide and executes it, with its real imports and a global `fetch` the test replaces, over the turns the fence handles: this guide's over a plain, a reclassified, a cancelled, and a refused turn, and the README's, which has no `catch` arm, over the plain and the reclassified turn. It asserts the logged values, the deltas, the fence's message list, the whole body of each request, and the error the fence throws.
793
797
  - [`tests/src/core/OllamaProvider.test.ts`](../tests/src/core/OllamaProvider.test.ts) — hermetic provider request-shape (including the opt-in `truncate` and `shift` keys), framing, transport-seam, abort, deadline, and unreachable-upstream coverage, plus the streaming fold — deltas, tool-call accumulation, done-line usage, the `done_reason: 'length'` truncation and its stray-reason refusals, the unterminated tail flush, and think separation — driven over a canned NDJSON transport. Its recording proxy uses a deliberately unreachable default and asserts only captured requests and local provider behavior.
794
- - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the wire leaves: the request projection and every response extraction, including each malformed-wire degradation, the `done_reason` reader's `'length'`, other-reason, missing, and non-string cases, and the terminal timing reader's verbatim nanoseconds, zero, absent, malformed, and `done` cases.
798
+ - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the wire leaves: the request projection with its control-token escape and every response extraction, including each malformed-wire degradation, the `done_reason` reader's `'length'`, other-reason, missing, and non-string cases, and the terminal timing reader's verbatim nanoseconds, zero, absent, malformed, and `done` cases.
795
799
  - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — hermetic `createOllama` shape, identity, defaults, passthrough, and unreachable-upstream coverage.
796
800
  - [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — the `src/core` integration scope. A real `@orkestrel/server` + `@orkestrel/router` relay in front of this provider carries ordered content and thinking deltas, tools, and usage while keeping the browser and daemon credentials apart, refuses a wrong bearer with an empty `401` before the daemon transport is entered, crosses a browser cancel and a server deadline as an abort frame with its partial, reduces a daemon stream failure to the fixed public error frame, and replays a returned tool call. Beside those, a real agent over a canned NDJSON stream reports the model, meter, and budget layers in `result.stop`, and hermetic context framing, recap, reference, cherry-pick, canonical assembly order, scope allow-lists, workspace injection, and conversation selection run through the unreachable recording proxy, with a compile-time drift gate asserting the wire request and response shapes stay compatible with the official `ollama` client's types; that gate's authoritative check is `npm run check` (root tsc), while its run under vitest is an incidental no-op (`expectTypeOf` performs no runtime assertions).
797
801
  - [`tests/setup.test.ts`](../tests/setup.test.ts) — the shared host-independent test infrastructure, over the conversation padding, the window consumers, the throwing and recording summarizers, the workspace seeder, and the `PAGE_TOOL` definition `tests/setup.ts` exports, and over the host-independent half of `tests/setupServer.ts`: its request-narrowing guards, its refusing and streaming transports, its tool fixtures, its scripted agent stream and agent-stream driver, and its environment readers.
@@ -804,7 +808,7 @@ The hermetic projects — `src:core`, `src:server`, `setup`, `guides`, `conforma
804
808
  - [`tests/service/factories.test.ts`](../tests/service/factories.test.ts) — live `createOllama` generation and streaming coverage.
805
809
  - [`tests/service/relay.test.ts`](../tests/service/relay.test.ts) — the browser-to-server relay against the live daemon: a generated answer through the authenticated route, streamed deltas joining to the settled content, and a cancel after a live delta returning the relay's partial.
806
810
  - [`tests/service/transport.test.ts`](../tests/service/transport.test.ts) — the transparent wire proxy, end-to-end. A `createRecordingProxy(OLLAMA_CONFIG.host)` — a real `@orkestrel/server` + `@orkestrel/router` HTTP server — records the inbound request, forwards it to the selected Ollama service, and streams the response back.
807
- - [`tests/service/page.test.ts`](../tests/service/page.test.ts) — the live page receipt, in a real Chrome or Edge that `@orkestrel/browser` launches against a `127.0.0.1` fixture serving the page, the installed `@orkestrel` module tree, this workspace's own build, a `/control` route, and the authenticated relay from one origin. It proves that the published closure evaluates in the page with the page error recorder and the console recorder quiet, that the page parks exactly the operation table this proof evaluates by name, read back out of the running browser, that an `Agent` holding a page-defined DOM-writing `Tool` completes a tool loop against the live daemon over the same-origin relay and carries the minted receipt into the next turn's `role: 'tool'` message on the relay wire and the daemon wire, that the browser log, the page's Resource Timing drain, and the fixture's own record each report a request the page deliberately made, and the page error recorder and the console recorder each report a fault the page deliberately produced, that a wrong bearer is refused before the daemon is contacted, and that `createOllama` in the page answers a prompt on the daemon's own origin. Controls beside those drive a real browser through each interleaving the attempt bound covers, and assert the elapsed time of the whole call against the allowance plus the release share every time: an allowance too short to finish reads the attempt's own expiry error back rather than an inner browser timeout; an allowance the observation outlasts leaves the session released; an acquisition that settles after the allowance is released rather than abandoned, and is never reported as stranded; and an attempt whose release crossed the allowance reports that release rather than the answer the observation had already returned. Every precondition is a hard throw naming its fix — the daemon and model from `tests/setupService.ts`, the browser from `requirePageBrowser`, the build from `requireBuild`, and the daemon's permission for the page origin from `requireDaemonOrigin` — so a host missing one fails the project rather than skipping.
811
+ - [`tests/service/page.test.ts`](../tests/service/page.test.ts) — the live page receipt, in a real Chrome or Edge that `@orkestrel/browser` launches against a `127.0.0.1` fixture serving the page, the installed `@orkestrel` module tree, this workspace's own build, a `/control` route, and the authenticated relay from one origin. It proves that the published closure evaluates in the page with the page error recorder and the console recorder quiet, that the page parks exactly the operation table this proof evaluates by name, read back out of the running browser, that an `Agent` holding a page-defined DOM-writing `Tool` completes a tool loop against the live daemon over the same-origin relay and carries the minted receipt into the next turn's `role: 'tool'` message on the relay wire and the daemon wire, that the browser log, the page's Resource Timing drain, and the fixture's own record each report a request the page deliberately made, and the page error recorder and the console recorder each report a fault the page deliberately produced, that a wrong bearer is refused before the daemon is contacted, that `createOllama` in the page answers a prompt on the daemon's own origin, and that a real browser's prompt, frames, and answer cross the frame route to an `Agent` in Node, with the tool running after the approval. Controls beside those drive a real browser through each interleaving the attempt bound covers, and assert the elapsed time of the whole call against the allowance plus the release share every time: an allowance too short to finish reads the attempt's own expiry error back rather than an inner browser timeout; an allowance the observation outlasts leaves the session released; an acquisition that settles after the allowance is released rather than abandoned, and is never reported as stranded; and an attempt whose release crossed the allowance reports that release rather than the answer the observation had already returned. Every precondition is a hard throw naming its fix — the daemon and model from `tests/setupService.ts`, the browser from `requirePageBrowser`, the build from `requireBuild`, and the daemon's permission for the page origin from `requireDaemonOrigin` — so a host missing one fails the project rather than skipping.
808
812
  - [`tests/service/tools.test.ts`](../tests/service/tools.test.ts) and [`tests/service/authority.test.ts`](../tests/service/authority.test.ts) — live tool dispatch through the agent loop, and the authority gate's approval and denial paths.
809
813
  - [`tests/service/budget.test.ts`](../tests/service/budget.test.ts) and [`tests/service/lifecycle.test.ts`](../tests/service/lifecycle.test.ts) — live token-budget enforcement on the reported usage, the meter layer's mid-stream trip under `allowance: budget`, the daemon's `done_reason: 'length'` at a `num_predict` cap with its `result.truncated` and model-layer `stop`, and the agent's status, event, and abort lifecycle.
810
814
  - [`tests/service/schema.test.ts`](../tests/service/schema.test.ts) and [`tests/service/scopes.test.ts`](../tests/service/scopes.test.ts) — a live structured-output `schema` constraining the answer, and a live scope filtering what reaches the wire.
@@ -393,19 +393,18 @@ only a verdict you assembled by hand and passed to `computeReceipt` yourself.
393
393
  than the message beside it. **A `claimant` issue is a tool's diagnostic about a candidate draft,
394
394
  and nothing else. Every other claimant fault is a throw.** That invariant is what lets one union
395
395
  serve both an issue and a failure: without it, a caller's own mistake — a test path no project
396
- collects, a `Claim.project` path that escapes the workspace — would arrive as a `claimant`
396
+ collects, a `Claim.project` path that resolves outside the workspace — would arrive as a `claimant`
397
397
  issue and satisfy the condition that a test which never ran must never satisfy. A `workspace` issue
398
398
  carries the target tree's own defect, such as a symbolic link in a mutation path, a mutation path
399
399
  whose existing components cannot be inspected, a specification directory the target tree blocks
400
400
  probe from creating, a Vitest project the root configuration declares as a path string, into which
401
401
  the runtime stage can install no overlay, or a covered module the workspace's own configuration
402
- served before the runtime overlay. An `instrument` issue carries this package's own
403
- message about an inspection that did not complete — a specification it could not write, after its
404
- directory exists, for a reason the target tree does not own, a module that ran no test, or a covered
405
- module probe's own loader received and did not resolve.
406
- `formatIssue` renders the value first as `[claimant]`, `[workspace]`, or `[instrument]`, so the
407
- ownership survives `formatVerdict`. A clean runtime stage result means every collected test
408
- passed, not that the module reported itself passed.
402
+ served before the runtime overlay. An `instrument` issue carries this package's own message about an
403
+ inspection that did not complete — a specification it could not write, after its directory exists,
404
+ for a reason the target tree does not own, a module that ran no test, or a covered module probe's
405
+ own loader received and did not resolve. `formatIssue` renders the value first as `[claimant]`,
406
+ `[workspace]`, or `[instrument]`, so the ownership survives `formatVerdict`. A clean runtime stage
407
+ result means every collected test passed, not that the module reported itself passed.
409
408
 
410
409
  **A diagnostic about a project belongs to the workspace.** The compiler reports a configuration
411
410
  fault — a JSON syntax error, an option it cannot apply, a `types` entry or an extended project it
@@ -468,17 +467,17 @@ and does not match the contract it is read against, `destroyed` builds a replace
468
467
  teardown is permanent, and `deadline` changes the budget or the work it bounds. Neither axis is
469
468
  derivable from the other. These are the pairs this package raises:
470
469
 
471
- | Party | Code | Raised when |
472
- | ------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
473
- | `claimant` | `refused` | An input is rejected: a path escaping the workspace, a caller-supplied name the host refuses to inspect or create — an overlong component and one carrying a NUL byte are the shapes this package meets — a claim the tool guard rejects, a control repeating the case's candidate drafts and test byte for byte, a candidate naming no scoped project, a caller-named project whose diagnostic names no file, or a lint inspection its caller supplied no bound for. |
474
- | `claimant` | `missing` | The declared test path names no configured Vitest project, or names one the root configuration does not define. |
475
- | `claimant` | `destroyed` | A probe, a server, or a stage is used after its `destroy`. |
476
- | `claimant` | `deadline` | `ProbeOptions.deadline` expired while the stage was performing claimant-owned work, so the claim outran the budget. That stage was replaced before the next inspection began. The lint stage raises the same pair on its own when the bound its caller supplied stops a diagnostics wait, and a coordinator that armed that bound replaces the pair with its own refusal. |
477
- | `workspace` | `refused` | A mutation path crosses a symbolic link in the target tree. |
478
- | `workspace` | `missing` | The target tree does not install a tool probe resolves from it, or publishes no binary under that tool's name. |
479
- | `workspace` | `malformed` | The target tree publishes something probe cannot read: an unparsable manifest, a `bin` entry that is not a path, a TypeScript project its own compiler refuses, an unsupported tool version, a mutation path whose existing components cannot be inspected, or a directory it blocks probe from creating for the boot workbench. |
480
- | `instrument` | `malformed` | probe's own tooling could not serve: a boot control that did not report red, a language server frame it could not parse, a schema or verdict of its own it could not validate. |
481
- | `instrument` | `deadline` | A stage was not performing claimant-owned work when its budget expired, or a language server did not answer its teardown exchange within the stage's own bound. |
470
+ | Party | Code | Raised when |
471
+ | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
472
+ | `claimant` | `refused` | An input is rejected: a path resolving outside the workspace, a caller-supplied name the host refuses to inspect or create — an overlong component and one carrying a NUL byte are the shapes this package meets — a claim the tool guard rejects, a control repeating the case's candidate drafts and test byte for byte, a candidate naming no scoped project, a caller-named project whose diagnostic names no file, or a lint inspection its caller supplied no bound for. |
473
+ | `claimant` | `missing` | The declared test path names no configured Vitest project, or names one the root configuration does not define. |
474
+ | `claimant` | `destroyed` | A probe, a server, or a stage is used after its `destroy`. |
475
+ | `claimant` | `deadline` | `ProbeOptions.deadline` expired while the stage was performing claimant-owned work, so the claim outran the budget. That stage was replaced before the next inspection began. The lint stage raises the same pair on its own when the bound its caller supplied stops a diagnostics wait, and a coordinator that armed that bound replaces the pair with its own refusal. |
476
+ | `workspace` | `refused` | A mutation path crosses a symbolic link in the target tree. |
477
+ | `workspace` | `missing` | The target tree does not install a tool probe resolves from it, or publishes no binary under that tool's name. |
478
+ | `workspace` | `malformed` | The target tree publishes something probe cannot read: an unparsable manifest, a `bin` entry that is not a path, a TypeScript project its own compiler refuses, an unsupported tool version, a mutation path whose existing components cannot be inspected, or a directory it blocks probe from creating for the boot workbench. |
479
+ | `instrument` | `malformed` | probe's own tooling could not serve: a boot control that did not report red, a language server frame it could not parse, a schema or verdict of its own it could not validate. |
480
+ | `instrument` | `deadline` | A stage was not performing claimant-owned work when its budget expired, or a language server did not answer its teardown exchange within the stage's own bound. |
482
481
 
483
482
  A TypeScript project whose JSON the compiler cannot parse reaches you as that `workspace` and
484
483
  `malformed` pair, carrying the compiler's own diagnostic, the stage, and the project you named in
@@ -873,8 +872,8 @@ itself.
873
872
  The project digest is the digest of the `compilerOptions` member of `tsc --showConfig -p <project>`,
874
873
  read against the mirrored copy of the project with the mirror as the current directory, so the
875
874
  digest and the check read one set of files. `computeWorkspaceDigest` canonicalizes the record: a
876
- relative path the project declares that escapes the workspace root resolves against the mirror's
877
- own ancestors, and the mirror carries nothing such a path names. It still **moves with the
875
+ relative path the project declares that points outside the workspace root resolves against the
876
+ mirror's own ancestors, and the mirror carries nothing such a path names. It still **moves with the
878
877
  TypeScript version**, because a compiler decides which options it resolves and how it spells them.
879
878
  That is contained rather than surprising: the token already names `typescript@<version>`, so any
880
879
  policy pinning a digest already pins the version.
@@ -907,8 +906,8 @@ rather than as a limit on the token.
907
906
 
908
907
  ## What containment reaches
909
908
 
910
- Containment is not one rule, and the difference between its rules decides what a hostile claim can
911
- do.
909
+ Containment is not one rule, and the difference between its rules decides what an untrusted claim
910
+ can do.
912
911
 
913
912
  **Every path a claim carries is contained lexically.** `isDraft` refuses an absolute `Draft.path`
914
913
  and one that traverses out of the workspace, and `resolveWorkspaceFile` refuses the same shapes
@@ -958,12 +957,15 @@ indeterminate answer preserves the resource; only confirmed absence permits the
958
957
  **A read is contained lexically only, and that is the reach to plan for.** The mirror carries
959
958
  regular files inside the workspace only: a symbolic link is not carried, so a file reached only
960
959
  through one is absent from the mirror and the compiler reports what its absence causes, as a
961
- claimant issue like any other. A candidate path beneath an in-workspace symbolic link resolves to a
960
+ claimant issue like any other. Of the workspace-root `tmp/` directory the mirror carries only
961
+ `tmp/probes/`, because the scaffold tmp layout keeps nothing else there that an inspection reads,
962
+ and a consumer's ignored data must never be read or copied; the match is the lowercase `tmp`
963
+ spelling exactly, and a `tmp` directory below the root is walked like any other. A candidate path beneath an in-workspace symbolic link resolves to a
962
964
  file outside the workspace, and Oxlint, which reads the workspace directly rather than a mirror of
963
965
  it, inspects it there. A `Claim.project` that reaches outside the workspace through `extends`,
964
966
  `files`, `include`, or project references reaches nothing there: the type stage reads a project
965
- against the mirror, so an escaping relative path resolves against the mirror's own ancestors, and
966
- the mirror carries nothing such a path names.
967
+ against the mirror, so a relative path that points outside the workspace resolves against the
968
+ mirror's own ancestors, and the mirror carries nothing such a path names.
967
969
 
968
970
  Measured on 2026-08-20: with `link` a symbolic link to a directory outside the workspace,
969
971
  `isDraft({ path: 'link/secret.ts', text })` returns `true`,
@@ -1239,7 +1241,7 @@ server, and the supervising Codex process remained present; no synthetic load wa
1239
1241
  the package declares, what `verdict.digest` covers, and the flagship claim run for its receipt.
1240
1242
  - [`helpers.test.ts`](../tests/src/core/helpers.test.ts) — the formatters, the receipt token's
1241
1243
  conditions, and the generated specification's marker.
1242
- - [`validators.test.ts`](../tests/src/core/validators.test.ts) — every guard against hostile shapes,
1244
+ - [`validators.test.ts`](../tests/src/core/validators.test.ts) — every guard against malformed shapes,
1243
1245
  including the draft path the advertised schema admits and the guard refuses.
1244
1246
  - [`errors.test.ts`](../tests/src/core/errors.test.ts) — the failure guard against lookalikes and a
1245
1247
  duplicate copy of the package, and every failure path a test can drive without a resident tool,