dsh-boost 0.0.0-stage → 0.1.1

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 (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +526 -0
  4. package/README.md +444 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +283 -0
  43. package/dist/hooks/llm-stream.js +1086 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +257 -0
  49. package/dist/hooks/post-execute.js +1950 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +25 -0
  64. package/dist/host/root.js +64 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +984 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +380 -0
  100. package/dist/tools/boost.js +801 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +130 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1,1950 @@
1
+ /**
2
+ * Host hook assembly: the four mount points the plugin owns, and the
3
+ * post-execute decision path that turns the gate into a working product.
4
+ *
5
+ * Registration stays split one function per mount so each body can be replaced
6
+ * without rewriting the mount:
7
+ *
8
+ * - `tools/post-execute` first gates on the same cached scope judgement the
9
+ * protocol section reads, then canonicalises the result and runs a
10
+ * conservative invalidation check. It files the arriving receipt under
11
+ * `'root'`, works the substitution decision (`decide` → admission → pending
12
+ * queue / shadow receipt / fallback), then the double-projection guard, and
13
+ * finally projects the receipt when the scope document asks for it. Order is
14
+ * fixed: `next() → scope gate → canonicalise → invalidate → decide →
15
+ * (shadow receipt | admit and enqueue | fallback) → double-projection guard →
16
+ * projection → return the decision` (plan §Task 23b). A call with no
17
+ * `exec.agent` is not the plugin's to inspect: the downstream decision is
18
+ * returned untouched and a `skip:no-scope` receipt keeps the pass visible
19
+ * (design §5.5). A call carrying `exec.parent` is a PTC inner dispatch and
20
+ * returns before any of this: it is not the step's root receipt.
21
+ * - `llm/stream` is the model-request waterfall. Its body lives in
22
+ * `./llm-stream.ts` (Task 23c-1) and is re-exported below: it lets the
23
+ * plugin's own selector request through untouched, then answers a pending
24
+ * decision with a synthesized turn or delegates to `next()` after the
25
+ * turn/anchor checks. The mount is registered here because `registerHooks`
26
+ * is the single assembly surface.
27
+ * - `tools/execute` looks the session's pending substitution up with `peek`
28
+ * (never `take`: the entry must survive to this hook), compares the arriving
29
+ * `callId` itself. A **differing** `callId` is not tampering: the host assigns
30
+ * call ids and our synthesized turn sets the one we chose, so a call carrying
31
+ * a different id is an ordinary call that has nothing to do with the
32
+ * substitution — it passes through untouched. Only when the ids are equal does
33
+ * `rejectIfTampered` run, and only then is the entry cleared (on accept or
34
+ * reject), because the entry has then served its purpose.
35
+ * - the `systemPrompt` section reads the per-agent judgement cache
36
+ * synchronously. Its `text` must be a function, never a static string: a
37
+ * static string would inject the protocol into every session unconditionally
38
+ * and defeat the scope document (design §5.5).
39
+ *
40
+ * ## What Task 23b added
41
+ *
42
+ * The receipt map (`ReceiptSessionState`) keys `'root'` to the receipt that
43
+ * just arrived and each executed candidate's id to its own receipt, so guards
44
+ * and `$public` templates always read the arrival-time canonical text and a
45
+ * later step can project a value from an earlier step. The executable args
46
+ * always come from the *decision* (`decision.args` / `decision.candidates[i]
47
+ * .args`), never from `plan.steps[i].args`, which still holds `$public`
48
+ * templates. A plan is one-shot per receipt: the first post-execute that reads
49
+ * it removes it, so neither a guard failure nor a commit can leave the block
50
+ * alive to fire against a later receipt (the model writes a new block for its
51
+ * next call). It also means `decide` cannot re-commit the same step.
52
+ *
53
+ * The `shadow` flag from the scope document drives both `decide` (which skips
54
+ * the whitelist) and the record-only branch: a shadow commit writes a
55
+ * `{kind:'shadow'}` receipt and neither enqueues nor takes budget. It does
56
+ * **not** suppress projection: `shadow` and `projection` are independent
57
+ * switches (design §5.2-5), and projection-shadow mode writes only its
58
+ * accounting receipt. Admission runs in the mandated order — existence,
59
+ * `worthSubstituting`, then `budget.take()` — so a fallback never spends budget
60
+ * for a call it did not substitute.
61
+ *
62
+ * Everything here is contained: the host turns a throwing `post-execute`
63
+ * listener into an error result and the tool's real output is lost, so every
64
+ * foreign call (stores, queue, clock, usage, estimator) is wrapped. The
65
+ * `tools/execute` mount is contained too, failing open on an internal error:
66
+ * the design's fail-closed definition is "pass through, do not substitute",
67
+ * never "intercept the call" (design §5.5).
68
+ *
69
+ * The provider's `c.scope` is the agent itself at runtime: the host builds the
70
+ * assembly context as `{ agent, scope: agent, signal }`
71
+ * (`@deepseek-ai/dsh-agent/lib/index.js:410`), even though the declared type is
72
+ * the opaque `ScopeKey`. Keying the cache on anything else — or falling back to
73
+ * a no-argument judgement — would leak one session's visibility into another.
74
+ *
75
+ * @module dsh-boost/hooks/post-execute
76
+ */
77
+ import { worthSubstituting } from '../admission/ledger.js';
78
+ import { DEFAULT_CONFIG } from '../config.js';
79
+ import { decide } from '../gate/decide.js';
80
+ import { alreadySpilled, looksPruned } from '../gate/invalidate.js';
81
+ import { isPosixOnly } from '../host/platform.js';
82
+ import { PROTOCOL_NAME, PROTOCOL_ORDER, PROTOCOL_TEXT } from '../prompt/protocol.js';
83
+ import { projectApply, projectShadow } from '../projection/apply.js';
84
+ import { canonicalise } from '../projection/canonicalise.js';
85
+ import { DEFAULT_SCOPE, isVisible } from '../scope/doc.js';
86
+ import { SELECTOR_SYSTEM_PROMPT, choose, selectorPromptText } from '../selector/jev.js';
87
+ import { familyOf } from '../tools/family.js';
88
+ import { rejectIfTampered } from './execute.js';
89
+ import { receiptsStopped, sessionBudget, sessionClock, sessionUsage, settleDiscarded, streamHook, } from './llm-stream.js';
90
+ import { callIdFor } from './pending.js';
91
+ import { ReceiptSessionState, appendReceipt, callPreview, clearAnchors, clearPlan, clearPending, clockTurnOf, peekPending, previewOf, } from './session-state.js';
92
+ /**
93
+ * The `llm/stream` body lives in its own module (Task 23c-1). It is re-exported
94
+ * here because `registerHooks` is the assembly surface the rest of the plugin
95
+ * and the integration tests import; the mount below uses the same function.
96
+ */
97
+ export { streamHook };
98
+ /**
99
+ * The substitution whitelist: exactly the read-only trio (design §5.2-5).
100
+ *
101
+ * One constant drives both `decide` (non-shadow) and the `whitelisted` field
102
+ * written to the shadow/substitute receipts, so the policy the gate enforced
103
+ * and the policy the audit trail reports cannot drift. `bash`, `web_fetch` and
104
+ * every write tool stay out: they have no deterministic read-only judgement.
105
+ */
106
+ export const SUBSTITUTION_WHITELIST = new Set(['read', 'grep', 'glob']);
107
+ /**
108
+ * Hard cap on the receipt text shown to the selector.
109
+ *
110
+ * A full 40 KB receipt would dominate the selector call before the candidate
111
+ * summaries are added. This cap keeps the receipt near 300 tokens even when the
112
+ * tool family's projection window is larger, while still showing the
113
+ * projection's head/tail shape. The actual input+output charge is computed
114
+ * from the text that is sent, never from this cap alone.
115
+ */
116
+ const SELECTOR_RECEIPT_MAX_CHARS = 1_200;
117
+ /** Skip reasons that mean the projection machinery degraded, not "nothing to cut". */
118
+ const PROJECTION_DEGRADATIONS = new Set([
119
+ 'no-spill',
120
+ 'no-owner',
121
+ 'projection-skipped:no-footer',
122
+ 'spill-failed',
123
+ 'footer-failed',
124
+ ]);
125
+ /** The judgement-cache key carried by the assembly context's `scope`. */
126
+ function agentKeyOf(scope) {
127
+ const id = scope?.session?.header?.id;
128
+ return typeof id === 'string' ? id : undefined;
129
+ }
130
+ /** The session a hook call belongs to, or `undefined` when the host supplied none. */
131
+ function sessionIdOf(exec) {
132
+ const id = exec?.agent?.session?.header?.id;
133
+ return typeof id === 'string' ? id : undefined;
134
+ }
135
+ /**
136
+ * Whether the host cancelled the call that produced this result.
137
+ *
138
+ * `tools/post-execute` is async, and the host contract (`dsh-tools`'
139
+ * `events.d.ts`) requires async listeners to observe `exec.signal`. A
140
+ * cancelled call's result never reaches the model, so projecting it would pay
141
+ * a spill write and persist an artifact nobody can read. The signal crosses
142
+ * the host boundary, so a malformed one means "not cancelled" rather than a
143
+ * reason to throw out of the hook.
144
+ */
145
+ function cancelled(exec) {
146
+ try {
147
+ return exec?.signal?.aborted === true;
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ }
153
+ /**
154
+ * The protocol section's synchronous provider.
155
+ *
156
+ * It may only read the cached judgement: the host assembles prompts
157
+ * synchronously, so there is nothing to await. A missing store, a store without
158
+ * `judgement`, a context without `scope`, and a scope without a session id all
159
+ * mean "inject nothing" (fail-closed, design §5.5).
160
+ */
161
+ function protocolText(scope, context) {
162
+ if (scope == null || typeof scope.judgement !== 'function')
163
+ return '';
164
+ const key = agentKeyOf(context?.scope);
165
+ if (key === undefined)
166
+ return '';
167
+ return scope.judgement(key) ? PROTOCOL_TEXT : '';
168
+ }
169
+ // ---------------------------------------------------------------------------
170
+ // Defensive readers: every foreign call is wrapped
171
+ // ---------------------------------------------------------------------------
172
+ /**
173
+ * The host step index, or `undefined` when no clock can supply one.
174
+ *
175
+ * `undefined` is fail-closed: the decision path refuses to invent a step
176
+ * (a plugin-side counter would collide two substitutions in one turn — T23a).
177
+ */
178
+ function clockStepOf(deps, sessionId) {
179
+ try {
180
+ const step = sessionClock(deps, sessionId)?.step();
181
+ return typeof step === 'number' && Number.isFinite(step) ? step : undefined;
182
+ }
183
+ catch {
184
+ return undefined;
185
+ }
186
+ }
187
+ /** The session's anchors without ever failing the call. */
188
+ function pendingAnchorsOf(deps, sessionId) {
189
+ try {
190
+ return deps.anchors?.get(sessionId);
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ }
196
+ /**
197
+ * The only invalidation branch that is live at this call site: the prune marker.
198
+ *
199
+ * `invalidate` also compares the anchor text, but a `tools/post-execute` receipt
200
+ * is a *different* call's body, so that comparison can never establish the
201
+ * anchored receipt's identity here; it would fire `compaction-reset` after every
202
+ * commit, drop the anchors obligation 10 exists to keep for 23c, and skip one
203
+ * decision (review F1). The anchor branch belongs on the model-request path
204
+ * (`llm/stream`, 23c), where the compared text is the anchored receipt's current
205
+ * body in the outgoing messages.
206
+ */
207
+ function markerResetOf(pending, receiptText) {
208
+ try {
209
+ if (pending == null)
210
+ return undefined;
211
+ return looksPruned(receiptText) ? 'pruned-reset' : undefined;
212
+ }
213
+ catch {
214
+ return undefined;
215
+ }
216
+ }
217
+ /** Write one ledger record, keyed to the session and host turn. */
218
+ function ledgerEntry(ctx, kind, code, extra = {}) {
219
+ return {
220
+ version: 1,
221
+ ts: new Date().toISOString(),
222
+ sessionId: ctx.sessionId,
223
+ turn: ctx.turn,
224
+ kind,
225
+ code,
226
+ ...(typeof ctx.exec.name === 'string' ? { tool: ctx.exec.name } : {}),
227
+ // The operator's evidence line: the canonical receipt head and the executed
228
+ // args. Without args every same-tool/same-turn receipt hashed identically
229
+ // (stepId is always 'root').
230
+ preview: previewOf(ctx.receipt.text),
231
+ ...(ctx.exec.arguments !== undefined ? { args: ctx.exec.arguments } : {}),
232
+ ...extra,
233
+ };
234
+ }
235
+ /**
236
+ * Caps on the plan evidence a substitution receipt carries.
237
+ *
238
+ * G2 (design line 71) requires the receipt to answer "why was the model not
239
+ * asked" with 计划、守卫、绑定、回执、节省量; without the plan and the guards an
240
+ * auditor sees what ran but not why it was legitimate. The plan is
241
+ * model-written text though, and a receipt is one line: 256 code points of
242
+ * goal (the same order as `preview`), at most 8 guards, and at most 300 code
243
+ * points per guard. The bound is a *code-point* cap, not a byte cap: one
244
+ * pathological plan can contribute up to ~9.6 KB from the guards alone
245
+ * (8 × 300 code points × 4 UTF-8 bytes for 4-byte characters) plus up to
246
+ * ~1 KB from the 256-code-point goal. That is bounded and auditable, but a
247
+ * receipt line can exceed 10 KB — status and readers must not assume 2.7 KB.
248
+ * Truncation is always visible: the goal ends in `…`, an oversized guard
249
+ * becomes `{truncated_json: "…"}`, and `guards_total` is present whenever
250
+ * guards were left out.
251
+ */
252
+ const MAX_RECEIPT_PLAN_CODE_POINTS = 256;
253
+ const MAX_RECEIPT_GUARDS = 8;
254
+ const MAX_RECEIPT_GUARD_CODE_POINTS = 300;
255
+ /** Cap a string by code point so a surrogate pair is never split. */
256
+ function capText(value, cap) {
257
+ const points = Array.from(value);
258
+ if (points.length <= cap)
259
+ return value;
260
+ return `${points.slice(0, Math.max(0, cap - 1)).join('')}…`;
261
+ }
262
+ /**
263
+ * The plan/goal and guard evidence for one committed candidate.
264
+ *
265
+ * Guards are carried as written while they fit. Only a guard whose own JSON
266
+ * exceeds {@link MAX_RECEIPT_GUARD_CODE_POINTS} (a multi-KB `text_contains`,
267
+ * say) is replaced by a `truncated_json` marker, so the array stays bounded
268
+ * without silently dropping the guard's form.
269
+ */
270
+ export function substitutionEvidence(goal, guards) {
271
+ const carried = guards.slice(0, MAX_RECEIPT_GUARDS).map((guard) => {
272
+ const json = JSON.stringify(guard) ?? '';
273
+ return Array.from(json).length <= MAX_RECEIPT_GUARD_CODE_POINTS
274
+ ? guard
275
+ : { truncated_json: capText(json, MAX_RECEIPT_GUARD_CODE_POINTS) };
276
+ });
277
+ return {
278
+ plan: capText(typeof goal === 'string' ? goal : '', MAX_RECEIPT_PLAN_CODE_POINTS),
279
+ guards: carried,
280
+ ...(guards.length > MAX_RECEIPT_GUARDS ? { guards_total: guards.length } : {}),
281
+ };
282
+ }
283
+ /**
284
+ * Append one `skip:no-scope` receipt.
285
+ *
286
+ * The no-agent case has no session id and no turn; the empty session id and
287
+ * turn zero are honest placeholders, and the `code` is the field status counts.
288
+ */
289
+ async function appendSkipNoScope(receipts, exec, sessionId = '', turn = 0) {
290
+ if (receipts == null || typeof receipts.append !== 'function')
291
+ return;
292
+ try {
293
+ await receipts.append({
294
+ version: 1,
295
+ ts: new Date().toISOString(),
296
+ sessionId,
297
+ turn,
298
+ kind: 'skip',
299
+ code: 'skip:no-scope',
300
+ tool: exec?.name,
301
+ });
302
+ }
303
+ catch {
304
+ // A receipt is evidence, not a precondition: never break the call for it.
305
+ }
306
+ }
307
+ /** Append one invalidation receipt; a receipt failure never breaks the call. */
308
+ async function appendResetReceipt(receipts, exec, sessionId, turn, stepId, code) {
309
+ if (receipts == null || typeof receipts.append !== 'function')
310
+ return;
311
+ try {
312
+ await receipts.append({
313
+ version: 1,
314
+ ts: new Date().toISOString(),
315
+ sessionId,
316
+ turn,
317
+ stepId,
318
+ kind: 'reset',
319
+ code,
320
+ tool: exec?.name,
321
+ });
322
+ }
323
+ catch {
324
+ // A receipt is evidence, not a precondition: never break the call for it.
325
+ }
326
+ }
327
+ /**
328
+ * Abandon the pending decision after an external rewrite.
329
+ *
330
+ * Only the plugin's own anchor record is touched — the session log's current
331
+ * body is never read (design §5.2-7). Clearing happens before the receipt write
332
+ * so a stalled store cannot leave the stale anchors in place; both steps are
333
+ * contained so the tool result survives.
334
+ *
335
+ * The decision-time usage mark is settled **without** a settlement receipt
336
+ * first, exactly like `applyAbandon`: the substitution was never synthesized,
337
+ * so there is no saving to report. Leaving the mark would let the next real
338
+ * request pair itself with it and write a `substitute-settled` line for a
339
+ * substitution that never ran (row 1).
340
+ */
341
+ async function resetInvalidatedPending(deps, exec, sessionId, turn, pending, code) {
342
+ // Design §5.2-7: a reset returns to the slow path *and* empties pending, so no
343
+ // queued substitution can fire from anchors that no longer name live text. The
344
+ // plan is dropped too: it was written for the invalidated receipt, and leaving
345
+ // it would let it fire against a later one. A dispatch accepted for the
346
+ // invalidated decision must not settle a later mark that reuses its id.
347
+ clearAcceptedDispatch(deps, sessionId);
348
+ settleDiscarded(deps, sessionId);
349
+ clearAnchors(deps, sessionId);
350
+ clearPending(deps, sessionId);
351
+ clearPlan(deps, sessionId);
352
+ await appendResetReceipt(deps.receipts, exec, sessionId, turn, pending.stepId, code);
353
+ }
354
+ /**
355
+ * The host's spill-notice predicate, resolved at most once per process.
356
+ *
357
+ * The spill policy is never declared as a dependency (design §5.4), so its notice module is
358
+ * imported dynamically: a static import would make the plugin fail to load on
359
+ * a host without it. A missing package means no receipt can carry its footer,
360
+ * so the guard simply does not fire. The deps seam wins, which is what keeps
361
+ * the guard testable without the host.
362
+ */
363
+ let noticePredicate;
364
+ function resolveNoticePredicate(deps) {
365
+ if (typeof deps.hasSpillNotice === 'function')
366
+ return Promise.resolve(deps.hasSpillNotice);
367
+ noticePredicate ??= import('@deepseek-ai/dsh-spill-policy/notice')
368
+ .then((module) => (typeof module.hasSpillNotice === 'function' ? module.hasSpillNotice : undefined))
369
+ .catch(() => undefined);
370
+ return noticePredicate;
371
+ }
372
+ /**
373
+ * The host's spill footer renderer, resolved lazily.
374
+ *
375
+ * `projectApply` cannot statically import the spill policy for the same reason
376
+ * the notice predicate cannot. A missing package makes apply-mode projection
377
+ * degrade to `projection-skipped:no-footer` in `projectApply` itself — and,
378
+ * because that turns the plugin's headline feature off, the first resolution
379
+ * that yields nothing is logged once (never per receipt, which would drown the
380
+ * log of a busy session). `status` maps the same receipt code to
381
+ * `ERR_HOST_NO_SPILL_NOTICE`, so the degradation also reaches the operator who
382
+ * never reads the log.
383
+ */
384
+ let footerFormatter;
385
+ /** One warning per process; a missing host module is not a per-call event. */
386
+ let footerMissingLogged = false;
387
+ /** Log the missing-footer degradation once; a foreign logger must not throw. */
388
+ function noteMissingFooter(deps) {
389
+ if (footerMissingLogged)
390
+ return;
391
+ footerMissingLogged = true;
392
+ try {
393
+ deps.logger?.warn?.('dsh-boost: ERR_HOST_NO_SPILL_NOTICE: @deepseek-ai/dsh-spill-policy/notice resolved no formatSpillNotice; ' +
394
+ 'apply-mode projection is disabled (projection-skipped:no-footer) until the host spill policy is available');
395
+ }
396
+ catch {
397
+ // A logger failure must not become a tool failure.
398
+ }
399
+ }
400
+ function resolveFooterFormatter(deps) {
401
+ // The seam wins over the memoised import, exactly like `hasSpillNotice`: a
402
+ // test states "the module resolved nothing" without uninstalling the host
403
+ // package. It is deliberately not memoised — it belongs to one deps object.
404
+ if (typeof deps.resolveFooter === 'function') {
405
+ return Promise.resolve()
406
+ .then(() => deps.resolveFooter?.())
407
+ .then((formatter) => {
408
+ if (formatter === undefined)
409
+ noteMissingFooter(deps);
410
+ return formatter;
411
+ })
412
+ .catch(() => {
413
+ noteMissingFooter(deps);
414
+ return undefined;
415
+ });
416
+ }
417
+ footerFormatter ??= import('@deepseek-ai/dsh-spill-policy/notice')
418
+ .then((module) => {
419
+ if (typeof module.formatSpillNotice !== 'function')
420
+ return undefined;
421
+ return (omitted, ref) =>
422
+ // T6's `SpillBackend` widens the host's branded `SpillLocator` to
423
+ // `string`; the value is the same at runtime.
424
+ module.formatSpillNotice(omitted, ref);
425
+ })
426
+ .catch(() => undefined)
427
+ .then((formatter) => {
428
+ if (formatter === undefined)
429
+ noteMissingFooter(deps);
430
+ return formatter;
431
+ });
432
+ return footerFormatter;
433
+ }
434
+ /**
435
+ * The canonical text of the decision that will enter history, when it carries
436
+ * a content array.
437
+ *
438
+ * The host spill policy registers with `{ prepend: true }`: it calls `next()`
439
+ * and applies its footer to *that* decision, so the footer lives in
440
+ * `decision.content` and never in the `result.content` this listener received.
441
+ * `undefined` means "the decision carries no content"; the caller then falls
442
+ * back to the receiver as it arrived.
443
+ */
444
+ function decisionTextOf(decision) {
445
+ const content = decision.content;
446
+ if (!Array.isArray(content))
447
+ return undefined;
448
+ return canonicalise(content, false).text;
449
+ }
450
+ /**
451
+ * Whether projection must be skipped because the host already spilled this
452
+ * receipt (design §5.4).
453
+ *
454
+ * A predicate that throws counts as "already spilled": when the notice cannot
455
+ * be ruled out, a second projection could hide the original twice, so the safe
456
+ * direction is to leave the receipt alone.
457
+ */
458
+ async function isAlreadySpilled(deps, receiptText) {
459
+ try {
460
+ const hasNotice = await resolveNoticePredicate(deps);
461
+ return hasNotice !== undefined && alreadySpilled(receiptText, hasNotice);
462
+ }
463
+ catch {
464
+ return true;
465
+ }
466
+ }
467
+ /** Whether the plugin is active for this session (fail-closed on any doubt). */
468
+ function isActiveSession(deps, sessionId) {
469
+ const scope = deps.scope;
470
+ if (scope == null || typeof scope.judgement !== 'function')
471
+ return false;
472
+ try {
473
+ return scope.judgement(sessionId);
474
+ }
475
+ catch {
476
+ return false;
477
+ }
478
+ }
479
+ /**
480
+ * The live scope document, or the strict default when it cannot be read.
481
+ *
482
+ * Read once per decision pass rather than cached: `boost` writes the document
483
+ * while the plugin runs, and the projection/shadow switches must follow it. A
484
+ * missing or throwing reader degrades to `DEFAULT_SCOPE`, whose `shadow: true`
485
+ * makes the substitution path record-only — the safe direction.
486
+ */
487
+ async function scopeDocOf(deps) {
488
+ try {
489
+ const read = deps.scope?.read;
490
+ if (typeof read !== 'function')
491
+ return DEFAULT_SCOPE;
492
+ const result = await read.call(deps.scope);
493
+ const raw = result?.doc;
494
+ if (raw === null || typeof raw !== 'object')
495
+ return DEFAULT_SCOPE;
496
+ return raw;
497
+ }
498
+ catch {
499
+ return DEFAULT_SCOPE;
500
+ }
501
+ }
502
+ // ---------------------------------------------------------------------------
503
+ // Retrieval accounting
504
+ // ---------------------------------------------------------------------------
505
+ /** The calls that can retrieve a spilled artifact (design §5.3). */
506
+ const RETRIEVAL_TOOLS = new Set(['read', 'grep']);
507
+ /**
508
+ * Detect a retrieval without writing anything yet.
509
+ *
510
+ * Detection has to happen before the visibility gate (a projected receipt
511
+ * consumed context whether or not the workspace is still visible), but the
512
+ * cost must wait until projection has decided what the model will actually
513
+ * see (review I3). The split keeps both properties.
514
+ */
515
+ function pendingRetrievalOf(deps, exec, sessionId) {
516
+ try {
517
+ const name = exec?.name;
518
+ if (typeof name !== 'string' || !RETRIEVAL_TOOLS.has(name))
519
+ return undefined;
520
+ const ledger = deps.retrievals;
521
+ if (ledger == null || typeof ledger.locate !== 'function')
522
+ return undefined;
523
+ const locator = ledger.locate(sessionId, exec.arguments);
524
+ return locator === undefined ? undefined : { locator };
525
+ }
526
+ catch {
527
+ return undefined;
528
+ }
529
+ }
530
+ /**
531
+ * The one-time cost of one retrieval, or `undefined` when it cannot be priced.
532
+ *
533
+ * This is the **per-receipt** figure: the call block (name + arguments) plus
534
+ * the content the model saw. The replay multiplier is applied once, to both
535
+ * sides of the net formula, in `status` — multiplying only the cost by the
536
+ * horizon made a cheap partial re-read look like a loss (review C1).
537
+ *
538
+ * `content` is the decision's final visible text, so a retrieval that is itself
539
+ * projected is charged for the window, not the raw result (review I3). A
540
+ * missing/non-finite estimate is omitted rather than fabricated.
541
+ */
542
+ function retrievalCostOf(deps, exec, content) {
543
+ const estimate = estimatorOf(deps);
544
+ if (estimate === undefined)
545
+ return undefined;
546
+ const contentTokens = safeEstimate(estimate, content);
547
+ if (contentTokens === undefined)
548
+ return undefined;
549
+ let params = '';
550
+ try {
551
+ params = JSON.stringify(exec.arguments) ?? '';
552
+ }
553
+ catch {
554
+ params = '';
555
+ }
556
+ const callTokens = safeEstimate(estimate, `${exec.name ?? 'tool'} ${params}`);
557
+ if (callTokens === undefined)
558
+ return undefined;
559
+ const totalTokens = callTokens + contentTokens;
560
+ return Number.isFinite(totalTokens) ? { callTokens, contentTokens, totalTokens } : undefined;
561
+ }
562
+ /**
563
+ * Count a `read`/`grep` that names one of this session's spill locators.
564
+ *
565
+ * `appendReceipt` is the store's only write path, and `kind:'projection'` with
566
+ * `retrieved:true` is exactly what `boost status` aggregates as
567
+ * `projection_retrievals` and `projection_retrieval_tokens`. No
568
+ * `saved_projection_tokens` is written: this line documents a cost, not
569
+ * another gross saving.
570
+ *
571
+ * `visibleText` is the content that enters history after projection, which is
572
+ * what the model must pay to replay.
573
+ */
574
+ async function recordProjectionRetrieval(deps, exec, sessionId, pending, visibleText) {
575
+ try {
576
+ const name = exec?.name;
577
+ if (typeof name !== 'string')
578
+ return;
579
+ const cost = retrievalCostOf(deps, exec, visibleText);
580
+ const entry = {
581
+ version: 1,
582
+ ts: new Date().toISOString(),
583
+ sessionId,
584
+ turn: clockTurnOf(deps, sessionId) ?? 0,
585
+ kind: 'projection',
586
+ code: 'projection-retrieval',
587
+ tool: name,
588
+ retrieved: true,
589
+ locator: pending.locator,
590
+ // The visible content replays over this horizon in `status`'s net, so it
591
+ // must be the horizon in effect when the retrieval happened, not one read
592
+ // from the whole ledger later.
593
+ horizon_steps: projectionHorizonOf(deps, sessionId),
594
+ preview: previewOf(visibleText),
595
+ ...(exec.arguments !== undefined ? { args: exec.arguments } : {}),
596
+ };
597
+ if (cost === undefined) {
598
+ entry.estimate = 'unknown';
599
+ }
600
+ else {
601
+ entry.retrieval_call_tokens = cost.callTokens;
602
+ entry.retrieval_content_tokens = cost.contentTokens;
603
+ entry.retrieval_tokens = cost.totalTokens;
604
+ entry.estimate = deps.estimateKind ?? 'unknown';
605
+ }
606
+ await appendReceipt(deps, entry);
607
+ }
608
+ catch {
609
+ // A retrieval is evidence, never a precondition of the tool result.
610
+ }
611
+ }
612
+ // ---------------------------------------------------------------------------
613
+ // Admission and the decision branch
614
+ // ---------------------------------------------------------------------------
615
+ /**
616
+ * The conservative saving of skipping one model step: the last real request's
617
+ * replayed context (`input + cacheRead`).
618
+ *
619
+ * The step that is skipped would have replayed at least this much: the context
620
+ * only grows as receipts enter it. A missing ledger or sample is 0, never an
621
+ * interpolation, so admission falls back to the model when it cannot measure
622
+ * (design §5.3: measured, not estimated).
623
+ */
624
+ function savedTokensOf(deps, sessionId) {
625
+ try {
626
+ const last = sessionUsage(deps, sessionId)?.last();
627
+ if (last === undefined)
628
+ return 0;
629
+ const { input, cacheRead } = last;
630
+ if (!Number.isFinite(input) || !Number.isFinite(cacheRead) || input < 0 || cacheRead < 0)
631
+ return 0;
632
+ const total = input + cacheRead;
633
+ return Number.isFinite(total) ? total : 0;
634
+ }
635
+ catch {
636
+ return 0;
637
+ }
638
+ }
639
+ /**
640
+ * Whether this commit clears the admission threshold.
641
+ *
642
+ * A plan with exactly one candidate is the design's deterministic-single
643
+ * exemption: there is no selector call to pay for, so the threshold does not
644
+ * apply. Any other plan pays no selector either once only one candidate
645
+ * survives, but it still has to show a net win over the threshold; the
646
+ * conservative direction here is to keep the gate on.
647
+ */
648
+ function admittedFor(deps, sessionId, plan, overheadTokens) {
649
+ try {
650
+ const threshold = deps.config?.admission?.thresholdTokens;
651
+ const thresholdTokens = typeof threshold === 'number' && Number.isFinite(threshold)
652
+ ? threshold
653
+ : DEFAULT_CONFIG.admission.thresholdTokens;
654
+ return worthSubstituting({
655
+ savedTokens: savedTokensOf(deps, sessionId),
656
+ overheadTokens,
657
+ thresholdTokens,
658
+ deterministicSingle: plan.steps.length === 1,
659
+ });
660
+ }
661
+ catch {
662
+ return false;
663
+ }
664
+ }
665
+ /**
666
+ * Whether the session's turn budget is already empty, without consuming it.
667
+ *
668
+ * A selector call is real spend, so this check runs before the selector is
669
+ * priced or called; the consuming `takeBudget` stays at the commit point.
670
+ * A missing or foreign budget means "not exhausted", matching `takeBudget`'s
671
+ * no-cap contract. Shadow mode never calls this: it spends no step.
672
+ */
673
+ function budgetExhausted(deps, sessionId) {
674
+ try {
675
+ const budget = sessionBudget(deps, sessionId);
676
+ if (budget == null || typeof budget.exhausted !== 'function')
677
+ return false;
678
+ return budget.exhausted() === true;
679
+ }
680
+ catch {
681
+ return false;
682
+ }
683
+ }
684
+ /** Claim one budget step; no budget wired means no cap is applied. */
685
+ function takeBudget(deps, sessionId) {
686
+ try {
687
+ const budget = sessionBudget(deps, sessionId);
688
+ if (budget == null || typeof budget.take !== 'function')
689
+ return true;
690
+ return budget.take();
691
+ }
692
+ catch {
693
+ return false;
694
+ }
695
+ }
696
+ /** Record the substitution for the usage pairing; the stream hook settles it. */
697
+ function markSubstituted(deps, sessionId, candidateId) {
698
+ try {
699
+ sessionUsage(deps, sessionId)?.markSubstituted(candidateId);
700
+ }
701
+ catch {
702
+ // A ledger miss costs a measurement, never this call.
703
+ }
704
+ }
705
+ /** The session's pending usage-mark candidate, or `undefined` for a foreign ledger. */
706
+ function pendingCandidateOf(deps, sessionId) {
707
+ try {
708
+ return sessionUsage(deps, sessionId)?.pendingCandidateId();
709
+ }
710
+ catch {
711
+ return undefined;
712
+ }
713
+ }
714
+ /**
715
+ * The last substitution dispatch `tools/execute` accepted for a session.
716
+ *
717
+ * `ReceiptSessionState` records the same callId -> candidate mapping, but the
718
+ * candidate's own `tools/post-execute` consumes it when it files the receipt.
719
+ * A turn rollover needs the fact *after* that consumption: a late parallel
720
+ * tool result can roll the turn before the next real request, and the usage
721
+ * mark must then be reported instead of discarded as if nothing ran. The
722
+ * accepted dispatch is mirrored here together with the evidence that would
723
+ * otherwise be parked for the next settlement.
724
+ *
725
+ * One record per session: a later accepted dispatch replaces it, a session
726
+ * whose usage mark is already gone drops it, and a rollover consumes it. The
727
+ * `HookDeps` key keeps two assemblies in one process from reading each other's
728
+ * sessions. The record is small and per-session; it is never persisted.
729
+ */
730
+ const ACCEPTED_DISPATCH = new WeakMap();
731
+ /** Mirror an accepted dispatch for a possible rollover settlement. */
732
+ function noteAcceptedDispatch(deps, sessionId, turn, candidateId, evidence) {
733
+ let bySession = ACCEPTED_DISPATCH.get(deps);
734
+ if (bySession === undefined) {
735
+ bySession = new Map();
736
+ ACCEPTED_DISPATCH.set(deps, bySession);
737
+ }
738
+ bySession.set(sessionId, {
739
+ turn,
740
+ candidateId,
741
+ ...(evidence === undefined ? {} : { evidence }),
742
+ });
743
+ }
744
+ /**
745
+ * Consume the accepted dispatch that matches `candidateId`, if any.
746
+ *
747
+ * The turn check is a staleness guard: the record that a pending mark belongs
748
+ * to was written in the turn now rolling over. A record written in the new
749
+ * turn cannot belong to it.
750
+ */
751
+ function takeAcceptedDispatch(deps, sessionId, candidateId, turn) {
752
+ const bySession = ACCEPTED_DISPATCH.get(deps);
753
+ const record = bySession?.get(sessionId);
754
+ bySession?.delete(sessionId);
755
+ if (record === undefined || record.candidateId !== candidateId || record.turn === turn) {
756
+ return undefined;
757
+ }
758
+ return record.evidence === undefined ? {} : { evidence: record.evidence };
759
+ }
760
+ /** Drop the mirrored dispatch; no pending mark is waiting to settle it. */
761
+ export function clearAcceptedDispatch(deps, sessionId) {
762
+ ACCEPTED_DISPATCH.get(deps)?.delete(sessionId);
763
+ }
764
+ /**
765
+ * Settle the usage mark at a turn rollover, reporting a substitution that ran.
766
+ *
767
+ * The ordinary path settles at the first real request after synthesis. A late
768
+ * parallel tool result can roll the turn before that request; the mark must not
769
+ * survive into the new turn, where it would pair with a request that is not the
770
+ * substitution's next one. If `tools/execute` never accepted the synthesized
771
+ * dispatch, the substitution did not run and the mark is a discard. If it did,
772
+ * the model round really was skipped: the settlement line is written with
773
+ * whatever sample the ledger holds (`'unknown'` when no after-mark request has
774
+ * run yet) and with the evidence captured at dispatch, so the substitution is
775
+ * reported instead of disappearing.
776
+ */
777
+ async function settleRollover(deps, sessionId, turn) {
778
+ const candidateId = pendingCandidateOf(deps, sessionId);
779
+ if (candidateId === undefined) {
780
+ settleDiscarded(deps, sessionId);
781
+ return;
782
+ }
783
+ const dispatched = takeAcceptedDispatch(deps, sessionId, candidateId, turn);
784
+ if (dispatched === undefined) {
785
+ settleDiscarded(deps, sessionId);
786
+ return;
787
+ }
788
+ let settled;
789
+ try {
790
+ const ledger = sessionUsage(deps, sessionId);
791
+ if (ledger === undefined) {
792
+ settleDiscarded(deps, sessionId);
793
+ return;
794
+ }
795
+ settled = ledger.settle();
796
+ }
797
+ catch {
798
+ settleDiscarded(deps, sessionId);
799
+ return;
800
+ }
801
+ // The parked evidence lives in `llm-stream`'s private map and would outlive
802
+ // the mark. `settleDiscarded` is the module's idempotent cleanup: the ledger
803
+ // was settled above, so this call only forgets that evidence. It runs before
804
+ // the receipt write so the `await` cannot let a new mark be created and then
805
+ // be consumed by this cleanup.
806
+ settleDiscarded(deps, sessionId);
807
+ await appendReceipt(deps, {
808
+ version: 1,
809
+ ts: new Date().toISOString(),
810
+ sessionId,
811
+ turn,
812
+ stepId: 'root',
813
+ kind: 'substitute-settled',
814
+ code: 'substitute-settled',
815
+ candidateId,
816
+ ...(dispatched.evidence ?? {}),
817
+ saved_input_tokens: settled.saved_input_tokens,
818
+ cache_hit_delta: settled.cache_hit_delta,
819
+ output_tokens: settled.output_tokens,
820
+ });
821
+ }
822
+ /**
823
+ * The receipt ids a candidate's `$public` templates refer to, plus `'root'`.
824
+ *
825
+ * These are the anchors the invalidation check compares against: the chosen
826
+ * candidate's arguments were computed from those receipts, so if any of them
827
+ * is rewritten externally the decision is stale. The walk is iterative and
828
+ * depth-capped because it runs over model-written args; `parsePlan` already
829
+ * caps them at 64 levels, but the hook must not depend on that.
830
+ */
831
+ function referencedReceiptIds(args) {
832
+ const ids = new Set(['root']);
833
+ const stack = [{ value: args, depth: 1 }];
834
+ while (stack.length > 0) {
835
+ const frame = stack.pop();
836
+ if (frame === undefined)
837
+ break;
838
+ if (frame.depth > 64)
839
+ continue;
840
+ if (Array.isArray(frame.value)) {
841
+ for (const child of frame.value) {
842
+ if (typeof child === 'object' && child !== null) {
843
+ stack.push({ value: child, depth: frame.depth + 1 });
844
+ }
845
+ }
846
+ continue;
847
+ }
848
+ if (typeof frame.value !== 'object' || frame.value === null)
849
+ continue;
850
+ const { $public: template, ...rest } = frame.value;
851
+ if (typeof template === 'object' &&
852
+ template !== null &&
853
+ typeof template.after === 'string') {
854
+ ids.add(template.after);
855
+ }
856
+ for (const child of Object.values(rest)) {
857
+ if (typeof child === 'object' && child !== null) {
858
+ stack.push({ value: child, depth: frame.depth + 1 });
859
+ }
860
+ }
861
+ }
862
+ return ids;
863
+ }
864
+ /**
865
+ * Store the session's anchors for the committed candidate.
866
+ *
867
+ * `stepId` is `'root'` because the guards and templates were evaluated against
868
+ * the receipt that just arrived; the map carries that receipt's canonical text
869
+ * plus the text of every receipt the candidate's `$public` templates reference
870
+ * (design §5.2-7). Missing references are omitted rather than invented.
871
+ */
872
+ function setAnchors(deps, ctx, candidateArgs) {
873
+ try {
874
+ const anchorsStore = deps.anchors;
875
+ if (anchorsStore == null || typeof anchorsStore.set !== 'function')
876
+ return;
877
+ const receipts = ctx.state.receiptsFor(ctx.sessionId, ctx.turn);
878
+ const anchors = {};
879
+ for (const id of referencedReceiptIds(candidateArgs)) {
880
+ const receipt = receipts.get(id);
881
+ if (receipt !== undefined)
882
+ anchors[id] = receipt.text;
883
+ }
884
+ anchorsStore.set(ctx.sessionId, { stepId: 'root', anchors });
885
+ }
886
+ catch {
887
+ // Anchors are a guard input, not the guard: losing them costs a reset.
888
+ }
889
+ }
890
+ /**
891
+ * Whether the session may be substituted for right now.
892
+ *
893
+ * Both gates must agree: the cached judgement said yes (the listener would
894
+ * have returned otherwise), and the live document still lists the session's
895
+ * workspace. The second check cannot be skipped: the cache is refreshed by a
896
+ * different task, and a stale "visible" must never authorize a replacement.
897
+ */
898
+ function substitutableSession(deps, sessionId, doc) {
899
+ try {
900
+ const workspaceId = deps.resolveSession?.(sessionId);
901
+ if (typeof workspaceId !== 'string')
902
+ return false;
903
+ return isVisible(doc, workspaceId);
904
+ }
905
+ catch {
906
+ return false;
907
+ }
908
+ }
909
+ /**
910
+ * A selector-facing summary of one already-bound candidate.
911
+ *
912
+ * The selector only needs to tell candidates apart; the args are included so
913
+ * two calls to the same tool with different paths are distinguishable. The
914
+ * bound tree is safe to show (it is what will run) and bounded so one huge
915
+ * argument cannot dominate the selector prompt.
916
+ */
917
+ function selectorSummary(candidate) {
918
+ let args = '';
919
+ try {
920
+ args = JSON.stringify(candidate.args) ?? '';
921
+ }
922
+ catch {
923
+ // A model-written plan is already JSON, but the summary is evidence-shaped
924
+ // and must not make the selector call throw.
925
+ }
926
+ const text = `${candidate.tool} ${args}`.trim();
927
+ const points = Array.from(text);
928
+ return points.length > 200 ? `${points.slice(0, 200).join('')}…` : text;
929
+ }
930
+ /** Bound the receipt the selector pays for, using the projection's head/tail shape. */
931
+ function selectorReceiptOf(deps, ctx) {
932
+ const text = ctx.receipt.text;
933
+ const points = Array.from(text);
934
+ if (points.length <= SELECTOR_RECEIPT_MAX_CHARS)
935
+ return text;
936
+ const toolName = ctx.exec.name;
937
+ const family = toolName === undefined ? undefined : familyOf(toolName);
938
+ const params = family !== undefined ? deps.config.projection[family] : undefined;
939
+ const configured = params !== undefined ? params.headChars + params.tailChars : 0;
940
+ const total = Math.min(SELECTOR_RECEIPT_MAX_CHARS, configured > 0 ? configured : SELECTOR_RECEIPT_MAX_CHARS);
941
+ const ratio = configured > 0 && params !== undefined ? params.headChars / configured : 0.8;
942
+ const headChars = Math.min(total, Math.max(0, Math.round(total * ratio)));
943
+ const tailChars = total - headChars;
944
+ const head = points.slice(0, headChars).join('');
945
+ const tail = tailChars > 0 ? points.slice(-tailChars).join('') : '';
946
+ const omitted = points.length - headChars - tailChars;
947
+ return `${head}\n…[selector window: omitted ${omitted} chars]…\n${tail}`;
948
+ }
949
+ /** The configured selector output budget, with the design default as a fallback. */
950
+ function selectorMaxTokens(deps) {
951
+ const raw = deps.config?.selector?.maxTokens;
952
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {
953
+ return DEFAULT_CONFIG.selector.maxTokens;
954
+ }
955
+ return Math.floor(raw);
956
+ }
957
+ /** The route the selector call would inherit, or `undefined` when it cannot run. */
958
+ function selectorRouteOf(deps, sessionId) {
959
+ try {
960
+ const route = deps.selectorRoute?.(sessionId);
961
+ if (route === undefined ||
962
+ typeof route.provider !== 'string' ||
963
+ typeof route.model !== 'string') {
964
+ return undefined;
965
+ }
966
+ return route;
967
+ }
968
+ catch {
969
+ return undefined;
970
+ }
971
+ }
972
+ /** Whether the selector is missing its LLM or its effective route. */
973
+ function selectorSeamUnavailable(deps, ctx) {
974
+ const llm = deps.llm;
975
+ return llm == null || typeof llm.stream !== 'function' || selectorRouteOf(deps, ctx.sessionId) === undefined;
976
+ }
977
+ /**
978
+ * The selector's fast upper bound: its output cap plus the estimated input.
979
+ *
980
+ * `maxTokens` bounds only the output; everything the request sends is input:
981
+ * the system prompt, the user template, the candidate list and the receipt.
982
+ * Charging only the receipt and the candidates under-counts the call by the
983
+ * prompt (about 60–70 tokens) and makes admission optimistic exactly where it
984
+ * decides whether to call. The priced string is built with the selector's own
985
+ * exported template, so the estimate cannot drift from the request (row 36).
986
+ * `undefined` means the caller cannot price the call; it must not guess.
987
+ */
988
+ function selectorChargeOf(deps, candidates, receiptText) {
989
+ const estimate = deps.estimateText;
990
+ if (typeof estimate !== 'function')
991
+ return undefined;
992
+ const prompt = selectorPromptText({
993
+ candidates: candidates.map((candidate) => ({
994
+ id: candidate.id,
995
+ summary: selectorSummary(candidate),
996
+ })),
997
+ receiptText,
998
+ });
999
+ const input = safeEstimate(estimate, `${SELECTOR_SYSTEM_PROMPT}\n${prompt}`);
1000
+ if (input === undefined || input < 0)
1001
+ return undefined;
1002
+ return selectorMaxTokens(deps) + input;
1003
+ }
1004
+ /**
1005
+ * Ask the selector to pick one of `decision.candidates` and return that same
1006
+ * decision candidate, whose `args` are already bound.
1007
+ *
1008
+ * Never throws and never guesses. A missing LLM seam, a missing route, an
1009
+ * abstention or a thrown call all leave the plan untouched and write one
1010
+ * `skip` receipt explaining why; the next post-execute may try again. The
1011
+ * `SELECTOR_PURPOSE` marker is set by `choose` itself, so the frozen stream
1012
+ * hook can recognize and pass the aux request through.
1013
+ */
1014
+ async function chooseCandidate(deps, ctx, candidates, receiptText) {
1015
+ const llm = deps.llm;
1016
+ if (llm == null || typeof llm.stream !== 'function') {
1017
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }));
1018
+ return undefined;
1019
+ }
1020
+ let route;
1021
+ try {
1022
+ route = deps.selectorRoute?.(ctx.sessionId);
1023
+ }
1024
+ catch {
1025
+ route = undefined;
1026
+ }
1027
+ if (route === undefined ||
1028
+ typeof route.provider !== 'string' ||
1029
+ typeof route.model !== 'string') {
1030
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }));
1031
+ return undefined;
1032
+ }
1033
+ try {
1034
+ const result = await choose({
1035
+ llm,
1036
+ provider: route.provider,
1037
+ model: route.model,
1038
+ ...(typeof route.reasoningEffort === 'string'
1039
+ ? { reasoningEffort: route.reasoningEffort }
1040
+ : {}),
1041
+ candidates: candidates.map((candidate) => ({
1042
+ id: candidate.id,
1043
+ summary: selectorSummary(candidate),
1044
+ })),
1045
+ receiptText,
1046
+ maxTokens: deps.config.selector.maxTokens,
1047
+ });
1048
+ if ('choice' in result) {
1049
+ // `candidates` are the decision's copies: their args are the bound tree.
1050
+ return candidates.find((candidate) => candidate.id === result.choice);
1051
+ }
1052
+ // §5.2-3 distinguishes a timeout/no-label abstention from a failed call:
1053
+ // `choose` maps its own dispatch failure to `abstain: 'error'`, and that is
1054
+ // the `selector-error` branch, not a second abstention reason.
1055
+ const code = result.abstain === 'error' ? 'selector-error' : 'selector-abstain';
1056
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', code, { stepId: 'root', reason: result.abstain }));
1057
+ return undefined;
1058
+ }
1059
+ catch {
1060
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-error', { stepId: 'root', reason: 'error' }));
1061
+ return undefined;
1062
+ }
1063
+ }
1064
+ /**
1065
+ * The substitution decision and its side effects.
1066
+ *
1067
+ * The fixed order is the plan's: existence of a plan and a receipt first, then
1068
+ * `worthSubstituting`, then `budget.take()`. Nothing below spends budget on a
1069
+ * decision that will not be dispatched.
1070
+ *
1071
+ * `ask-selector` is fulfilled here since Task 23c-2: the decision carries only
1072
+ * already-bound candidates, so the selector's choice is committed from
1073
+ * `decision.candidates[].args` — never from `plan.steps[i].args`, which still
1074
+ * holds `$public` templates. The selector call is the plugin's own aux request
1075
+ * (`purpose: 'boost-selector'`), so the frozen stream hook passes it through.
1076
+ * A missing route or a missing LLM is a record-only abstention, never a guess.
1077
+ * `fallback` records the decision code and leaves the pending entry alone: this
1078
+ * invocation has enqueued nothing, so any entry it finds belongs to another
1079
+ * call, and clearing it would cancel a live substitution in a multi-call step.
1080
+ * A plan is **one-shot per receipt**: the first post-execute that reads it
1081
+ * removes it from the session map, whatever the outcome (commit, guard
1082
+ * failure, selector abstention, no candidate). The protocol says a block
1083
+ * describes the next call and may be omitted when unsure; retaining it would
1084
+ * let a plan the model has withdrawn fire against a much later receipt. The
1085
+ * remaining candidates are not reused either; the model writes a fresh block
1086
+ * for the next call (and may still reference an earlier receipt by id).
1087
+ *
1088
+ * A shadow commit parks nothing, but projection is independent of the shadow
1089
+ * flag (design §5.2-5) and still runs in `applyDecision`.
1090
+ */
1091
+ async function decideSubstitution(deps, ctx) {
1092
+ // Fail-closed gate (design §5.2-3): a store that cannot record evidence
1093
+ // cannot justify spending a selector call or a budget step. No receipt is
1094
+ // attempted here either; the store is already failing, and status exposes
1095
+ // `receipts.stopped()` to the operator.
1096
+ //
1097
+ // The plan is still consumed here. This receipt cannot use it, and a plan is
1098
+ // one-shot per receipt: keeping it for a later receipt is exactly the stale
1099
+ // plan the one-shot rule exists to prevent. A store that recovers mid-turn
1100
+ // would otherwise let the next receipt fire a decision the model wrote for
1101
+ // this one.
1102
+ if (receiptsStopped(deps)) {
1103
+ clearPlan(deps, ctx.sessionId);
1104
+ return;
1105
+ }
1106
+ const plan = safePlan(deps, ctx.sessionId);
1107
+ if (plan === undefined)
1108
+ return;
1109
+ // One-shot: capture the plan for this pass, then drop it before any branch can
1110
+ // return, so no later receipt can reuse it.
1111
+ clearPlan(deps, ctx.sessionId);
1112
+ // Design §9: no token meter means no substitution. The meter is what prices
1113
+ // `worthSubstituting` and the selector's input, so running without it would
1114
+ // spend real money on a fabricated estimate. Refuse before `decide`, before
1115
+ // the selector and before admission; shadow mode is record-only and may
1116
+ // still run. Projection is not gated (it needs no token numbers to clip).
1117
+ const estimator = estimatorOf(deps);
1118
+ if (!ctx.doc.shadow &&
1119
+ (estimator === undefined || safeEstimate(estimator, 'dsh-boost meter probe') === undefined)) {
1120
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'ERR_HOST_NO_TOKENMETER', {
1121
+ stepId: 'root',
1122
+ reason: 'no-token-meter',
1123
+ }));
1124
+ return;
1125
+ }
1126
+ let decision;
1127
+ try {
1128
+ decision = decide({
1129
+ plan,
1130
+ stepId: 'root',
1131
+ receipts: ctx.state.receiptsFor(ctx.sessionId, ctx.turn),
1132
+ whitelist: SUBSTITUTION_WHITELIST,
1133
+ shadow: ctx.doc.shadow,
1134
+ });
1135
+ }
1136
+ catch {
1137
+ return;
1138
+ }
1139
+ // Substitution synthesises a dispatch and expects POSIX process semantics;
1140
+ // on Windows it is refused **before** the selector, admission and budget, so
1141
+ // the path cannot spend anything to decline. Shadow mode is record-only and
1142
+ // stays available: it changes nothing the model sees. The stable operator
1143
+ // signal is `boost status`'s `ERR_HOST_PLATFORM_UNSUPPORTED`; this receipt
1144
+ // keeps the refusal auditable per call rather than silently doing less.
1145
+ if (!isPosixOnly() && !ctx.doc.shadow) {
1146
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitution-unavailable', {
1147
+ stepId: 'root',
1148
+ reason: 'platform-unsupported',
1149
+ }));
1150
+ return;
1151
+ }
1152
+ let candidate;
1153
+ let boundArgs;
1154
+ let candidateId;
1155
+ // A selector call pays its output cap plus the input actually sent. A single
1156
+ // surviving candidate pays no selector at all. This must run before `choose`:
1157
+ // a selector call that cannot be paid for is never sent.
1158
+ let selectorOverhead = 0;
1159
+ let selectorReceiptText = '';
1160
+ if (decision.kind === 'ask-selector') {
1161
+ // Row 2: the budget is checked before the selector is paid for. Without
1162
+ // this, an exhausted step would still send a real model request and then
1163
+ // record `steps-exhausted` after the money was spent. Shadow mode is
1164
+ // record-only and takes no step, so it keeps measuring.
1165
+ if (!ctx.doc.shadow && budgetExhausted(deps, ctx.sessionId)) {
1166
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }));
1167
+ return;
1168
+ }
1169
+ // Availability is checked before pricing: a missing LLM/route is the
1170
+ // `selector-unavailable` degradation, not an admission decision.
1171
+ if (selectorSeamUnavailable(deps, ctx)) {
1172
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'selector-unavailable', { stepId: 'root' }));
1173
+ return;
1174
+ }
1175
+ selectorReceiptText = selectorReceiptOf(deps, ctx);
1176
+ const charge = selectorChargeOf(deps, decision.candidates, selectorReceiptText);
1177
+ if (charge === undefined) {
1178
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root', reason: 'no-estimator' }));
1179
+ return;
1180
+ }
1181
+ selectorOverhead = charge;
1182
+ if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {
1183
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }));
1184
+ return;
1185
+ }
1186
+ // The decision's candidates already carry the bound trees; committing from
1187
+ // the plan here would dispatch a `$public` template.
1188
+ const chosen = await chooseCandidate(deps, ctx, decision.candidates, selectorReceiptText);
1189
+ if (chosen === undefined)
1190
+ return;
1191
+ candidate = chosen;
1192
+ boundArgs = chosen.args;
1193
+ candidateId = chosen.id;
1194
+ }
1195
+ else if (decision.kind === 'fallback') {
1196
+ // This invocation enqueued nothing, so any pending entry belongs to another
1197
+ // call in the step; cancelling it would leave the budget spent and usage
1198
+ // marked for a substitution that never runs (review F2).
1199
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', decision.code, { stepId: 'root' }));
1200
+ return;
1201
+ }
1202
+ else {
1203
+ candidate = plan.steps.find((step) => step.id === decision.candidateId);
1204
+ boundArgs = decision.args;
1205
+ candidateId = decision.candidateId;
1206
+ }
1207
+ if (candidate === undefined || boundArgs === undefined || candidateId === undefined) {
1208
+ // decide only commits its own plan's ids; this is containment, not a path.
1209
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'no-candidate', { stepId: 'root' }));
1210
+ return;
1211
+ }
1212
+ // The live visibility check runs for the shadow path too: the record-only
1213
+ // measurement must describe the same population the real admission would
1214
+ // consider, not a broader one (review F2). The cached judgement passed above,
1215
+ // but the document may have changed while the session ran.
1216
+ if (!substitutableSession(deps, ctx.sessionId, ctx.doc)) {
1217
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'skip:no-scope', { stepId: 'root' }));
1218
+ return;
1219
+ }
1220
+ if (ctx.doc.shadow) {
1221
+ // Record-only: the same `shadow` flag was passed to `decide` above, so the
1222
+ // recorded potential matches the policy that produced it. No queue entry
1223
+ // and no budget. Projection is a separate switch and still runs afterwards
1224
+ // (design §5.2-5); this branch only stops the substitution side.
1225
+ await appendReceipt(deps, ledgerEntry(ctx, 'shadow', 'ok', {
1226
+ decision: 'commit',
1227
+ candidateId,
1228
+ // The executed tool is the model's call; the candidate's tool is what
1229
+ // the gate decided. The shadow report's per-family hit rate must use
1230
+ // the latter (the shadow receipt's `tool` is the former).
1231
+ candidateTool: candidate.tool,
1232
+ admitted: admittedFor(deps, ctx.sessionId, plan, selectorOverhead),
1233
+ whitelisted: SUBSTITUTION_WHITELIST.has(candidate.tool),
1234
+ stepId: 'root',
1235
+ args: boundArgs,
1236
+ // G2: the plan and the guards are why this candidate was legitimate.
1237
+ ...substitutionEvidence(plan.goal, candidate.guards),
1238
+ }));
1239
+ return;
1240
+ }
1241
+ const step = clockStepOf(deps, ctx.sessionId);
1242
+ if (step === undefined) {
1243
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-step' }));
1244
+ return;
1245
+ }
1246
+ if (deps.queue == null || typeof deps.queue.set !== 'function') {
1247
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'substitution-unavailable', { stepId: 'root', reason: 'no-queue' }));
1248
+ return;
1249
+ }
1250
+ if (!admittedFor(deps, ctx.sessionId, plan, selectorOverhead)) {
1251
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'not-admitted', { stepId: 'root' }));
1252
+ return;
1253
+ }
1254
+ if (!takeBudget(deps, ctx.sessionId)) {
1255
+ // No entry is ours to clear here: this invocation enqueued nothing, so a
1256
+ // live entry belongs to another call in the step (review F2).
1257
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', 'steps-exhausted', { stepId: 'root' }));
1258
+ return;
1259
+ }
1260
+ const callId = callIdFor(ctx.sessionId, ctx.turn, step, candidateId);
1261
+ const entry = {
1262
+ callId,
1263
+ candidateId,
1264
+ // The candidate's tool name identifies the call; the executable args are
1265
+ // the *decision's* bound tree, never the plan's `$public` template.
1266
+ name: candidate.tool,
1267
+ args: boundArgs,
1268
+ turn: ctx.turn,
1269
+ step,
1270
+ // The plan is one-shot (cleared above), so the evidence must travel with
1271
+ // the entry: the synth-time receipt is written after this turn's plan is
1272
+ // gone, and the settled receipt only knows the candidate id.
1273
+ evidence: substitutionEvidence(plan.goal, candidate.guards),
1274
+ };
1275
+ try {
1276
+ deps.queue.set(ctx.sessionId, entry);
1277
+ }
1278
+ catch {
1279
+ await appendReceipt(deps,
1280
+ // The step was already taken and this receipt is the only evidence that
1281
+ // it bought no substitution; a throwing queue must not also hide the cost.
1282
+ ledgerEntry(ctx, 'skip', 'substitution-unavailable', {
1283
+ stepId: 'root',
1284
+ reason: 'queue-failed',
1285
+ budget: 'spent',
1286
+ }));
1287
+ return;
1288
+ }
1289
+ markSubstituted(deps, ctx.sessionId, candidateId);
1290
+ // Anchors name the templates the executed call was bound from: the decision's
1291
+ // args are already expanded, so only the plan copy still carries the
1292
+ // `$public` references. That tree is inspected here, never dispatched.
1293
+ setAnchors(deps, ctx, plan.steps.find((step) => step.id === candidateId)?.args ?? boundArgs);
1294
+ return;
1295
+ }
1296
+ /** The session's plan, or `undefined` when none is known (or the map is foreign). */
1297
+ function safePlan(deps, sessionId) {
1298
+ try {
1299
+ const plans = deps.plans;
1300
+ if (plans == null || typeof plans.get !== 'function')
1301
+ return undefined;
1302
+ const plan = plans.get(sessionId);
1303
+ if (plan === undefined || plan === null)
1304
+ return undefined;
1305
+ // A spent plan has nothing left to decide; skipping the call also avoids a
1306
+ // `guard-trivial` receipt on every later tool call of the turn.
1307
+ if (!Array.isArray(plan.steps) || plan.steps.length === 0)
1308
+ return undefined;
1309
+ return plan;
1310
+ }
1311
+ catch {
1312
+ return undefined;
1313
+ }
1314
+ }
1315
+ // ---------------------------------------------------------------------------
1316
+ // Projection
1317
+ // ---------------------------------------------------------------------------
1318
+ /** The text projection may replace, or `undefined` when it must stay intact. */
1319
+ function projectionTargetOf(decision, receipt, result) {
1320
+ // A `value` replacement cannot be combined with `content`: the host throws a
1321
+ // TypeError for both, which would replace the tool result with an error.
1322
+ if (Object.hasOwn(decision, 'value'))
1323
+ return undefined;
1324
+ if (decision.kind !== 'accept')
1325
+ return undefined;
1326
+ if (Object.hasOwn(decision, 'content')) {
1327
+ const content = decision.content;
1328
+ if (!Array.isArray(content))
1329
+ return undefined;
1330
+ // Replacing a multi-block result with one text block is only lossless when
1331
+ // every block is text; an image or file block must stay where it is.
1332
+ if (!content.every((block) => textBlock(block)))
1333
+ return undefined;
1334
+ return canonicalise(content, false).text;
1335
+ }
1336
+ const content = result?.content;
1337
+ if (content !== undefined && !(Array.isArray(content) && content.every((block) => textBlock(block)))) {
1338
+ return undefined;
1339
+ }
1340
+ return receipt.text;
1341
+ }
1342
+ /** Whether a block is a text block this hook can fold into one string. */
1343
+ function textBlock(block) {
1344
+ return typeof block === 'object' && block !== null && block.type === 'text';
1345
+ }
1346
+ /** The estimator, or `undefined` when none is wired (projection then stays off). */
1347
+ function estimatorOf(deps) {
1348
+ const estimate = deps.estimateText;
1349
+ return typeof estimate === 'function' ? estimate : undefined;
1350
+ }
1351
+ /** One estimate, sanitised: a non-finite or throwing result means "cannot price". */
1352
+ function safeEstimate(estimate, text) {
1353
+ try {
1354
+ const value = estimate(text);
1355
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
1356
+ }
1357
+ catch {
1358
+ return undefined;
1359
+ }
1360
+ }
1361
+ /**
1362
+ * The replay horizon in effect for one projection decision, pinned on its receipt.
1363
+ *
1364
+ * `status` applies `(1 + horizon)` to every projection's saving. Reading one
1365
+ * current horizon at status time re-valued receipts from other sessions and
1366
+ * other moments whenever the cross-session minimum moved, so a historical net
1367
+ * saving jumped when an unrelated session started or ended. The receipt now
1368
+ * carries the horizon its decision was made under; `status` only falls back to
1369
+ * the current horizon for receipts that predate the field, and says how many
1370
+ * those were.
1371
+ *
1372
+ * The runtime horizon is design §5.3's `min(config, mean of the session's last
1373
+ * historyTurns turns)`. Its instance lives in `src/index.ts` (`apply` builds
1374
+ * one `RuntimeStepHorizon`), so the decision path can only read it through
1375
+ * {@link HookDeps.horizonFor}; until that one line is wired, the resolved
1376
+ * config's `horizonSteps` is the value in effect. A throwing or malformed
1377
+ * answer falls back the same way, never to a fabricated number.
1378
+ */
1379
+ function projectionHorizonOf(deps, sessionId) {
1380
+ try {
1381
+ const live = deps.horizonFor?.(sessionId);
1382
+ if (typeof live === 'number' && Number.isFinite(live) && live >= 0)
1383
+ return Math.floor(live);
1384
+ }
1385
+ catch {
1386
+ // A foreign horizon is evidence, never a reason to lose the receipt.
1387
+ }
1388
+ const raw = deps.config?.horizonSteps;
1389
+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0
1390
+ ? Math.floor(raw)
1391
+ : DEFAULT_CONFIG.horizonSteps;
1392
+ }
1393
+ /** `projection-skipped:<reason>`; `projectApply` already prefixes one reason. */
1394
+ function projectionSkipCode(reason) {
1395
+ return reason.startsWith('projection-skipped:') ? reason : `projection-skipped:${reason}`;
1396
+ }
1397
+ /**
1398
+ * Project the receipt that will enter history.
1399
+ *
1400
+ * Shadow mode only prices the receipt: it writes a `{kind:'shadow'}` record and
1401
+ * returns the decision untouched, so nothing the model sees changes. Apply mode
1402
+ * persists the canonical original through the host spill backend and replaces
1403
+ * the content only after `projectApply`'s own guards pass; a skip leaves the
1404
+ * decision intact. The regression guard (`assembled.length < original.length`)
1405
+ * lives inside `projectApply`; here only pricing and evidence are added.
1406
+ *
1407
+ * The live visibility recheck runs before either mode. The listener gate reads
1408
+ * the cached judgement from prompt assembly time; a workspace disabled since
1409
+ * then must not have its receipt clipped or accounted, in shadow or apply mode.
1410
+ */
1411
+ async function projectDecision(deps, receipt, decision, ctx) {
1412
+ const mode = ctx.doc.projection;
1413
+ if (mode === 'off')
1414
+ return decision;
1415
+ // Projection gets the same live recheck substitution performs. The cached
1416
+ // judgement passed the listener gate, but the prompt was assembled before
1417
+ // the tool ran: `boost` may have disabled the workspace in between, and a
1418
+ // projection changes what the model sees. The cache alone must not authorize
1419
+ // that (design §5.5).
1420
+ if (!substitutableSession(deps, ctx.sessionId, ctx.doc))
1421
+ return decision;
1422
+ const toolName = ctx.exec.name;
1423
+ const family = toolName === undefined ? undefined : familyOf(toolName);
1424
+ if (family === undefined) {
1425
+ // `edit`, `web_fetch`, `todo_write`, `boost` and friends are by-design
1426
+ // passes, not mapper gaps. Only a decorated (`mcp__*`) name means the
1427
+ // mapper may have missed a real family, so only that is counted.
1428
+ if (typeof toolName === 'string' && toolName.startsWith('mcp__')) {
1429
+ try {
1430
+ deps.projectionCounters?.unknownFamily(toolName);
1431
+ }
1432
+ catch {
1433
+ // A counter is evidence, never a precondition.
1434
+ }
1435
+ }
1436
+ return decision;
1437
+ }
1438
+ const target = projectionTargetOf(decision, receipt, ctx.result);
1439
+ if (target === undefined)
1440
+ return decision;
1441
+ // Clipping does not need a token meter; only its accounting does (design
1442
+ // §9). With no estimator the replacement still happens, but the receipts
1443
+ // carry `estimate:'unknown'` and no fabricated numbers.
1444
+ const estimate = estimatorOf(deps);
1445
+ try {
1446
+ if (mode === 'shadow') {
1447
+ const outcome = await projectShadow({
1448
+ text: target,
1449
+ isError: receipt.isError,
1450
+ family,
1451
+ cfg: deps.config,
1452
+ // Same sanitiser as the apply path: a throwing or non-finite host
1453
+ // estimate must never become `null` in the shadow account. Without a
1454
+ // meter the NaN makes `projectShadow` record an unpriced event.
1455
+ estimate: (text) => estimate === undefined ? Number.NaN : (safeEstimate(estimate, text) ?? Number.NaN),
1456
+ });
1457
+ if (outcome.kind === 'shadow') {
1458
+ const priced = outcome.before !== undefined &&
1459
+ outcome.after !== undefined &&
1460
+ outcome.saved !== undefined;
1461
+ await appendReceipt(deps, ledgerEntry(ctx, 'shadow', 'projection-shadow', {
1462
+ decision: 'projection',
1463
+ unit: 'raw',
1464
+ // The shadow ledger's one-time figure is replayable with the same
1465
+ // horizon as the applied one; pinning it keeps the two comparable.
1466
+ horizon_steps: projectionHorizonOf(deps, ctx.sessionId),
1467
+ ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),
1468
+ ...(priced
1469
+ ? {
1470
+ before: outcome.before,
1471
+ after: outcome.after,
1472
+ saved_projection_tokens: outcome.saved,
1473
+ }
1474
+ : {}),
1475
+ estimate: priced ? (deps.estimateKind ?? 'unknown') : 'unknown',
1476
+ }));
1477
+ }
1478
+ return decision;
1479
+ }
1480
+ const { content, outcome } = await projectApply({
1481
+ text: target,
1482
+ isError: receipt.isError,
1483
+ family,
1484
+ cfg: deps.config,
1485
+ sessionId: ctx.sessionId,
1486
+ toolName: ctx.exec.name ?? 'tool',
1487
+ callId: typeof ctx.exec.callId === 'string' ? ctx.exec.callId : undefined,
1488
+ label: family,
1489
+ spill: deps.spill,
1490
+ formatFooter: await resolveFooterFormatter(deps),
1491
+ });
1492
+ if (outcome.kind === 'applied') {
1493
+ // Remember the artifact's only address: this is what makes a later read
1494
+ // of it a counted retrieval instead of a free one (design §5.3).
1495
+ if (outcome.locator !== undefined)
1496
+ deps.retrievals?.record(ctx.sessionId, outcome.locator);
1497
+ // The applied event is always recorded; only the token figures depend on
1498
+ // the meter. `estimate` is always present and names the producer
1499
+ // (`deps.estimateKind`, defaulting to `'unknown'`), never a guess.
1500
+ // One-time `before`/`after`/`saved_projection_tokens` are the
1501
+ // authoritative names (§5.3); `status` applies the replay factor once to
1502
+ // the aggregate, never per receipt. `horizon_steps` is the horizon this
1503
+ // decision was made under, so a later status cannot re-value it.
1504
+ const before = estimate === undefined ? undefined : safeEstimate(estimate, target);
1505
+ const after = estimate === undefined ? undefined : safeEstimate(estimate, content);
1506
+ if (before !== undefined && after !== undefined) {
1507
+ await appendReceipt(deps, ledgerEntry(ctx, 'projection', 'projected', {
1508
+ unit: 'raw',
1509
+ horizon_steps: projectionHorizonOf(deps, ctx.sessionId),
1510
+ ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),
1511
+ before,
1512
+ after,
1513
+ saved_projection_tokens: before - after,
1514
+ estimate: deps.estimateKind ?? 'unknown',
1515
+ }));
1516
+ }
1517
+ else {
1518
+ await appendReceipt(deps, ledgerEntry(ctx, 'projection', 'projected', {
1519
+ unit: 'raw',
1520
+ horizon_steps: projectionHorizonOf(deps, ctx.sessionId),
1521
+ ...(ctx.retrievalCall === true ? { call_was_retrieval: true } : {}),
1522
+ estimate: 'unknown',
1523
+ }));
1524
+ }
1525
+ return { ...decision, content: [{ type: 'text', text: content }] };
1526
+ }
1527
+ if (outcome.kind === 'skipped' &&
1528
+ outcome.reason !== undefined &&
1529
+ PROJECTION_DEGRADATIONS.has(outcome.reason)) {
1530
+ // `projection-skipped:no-spill` is the receipt behind
1531
+ // `boost status`'s `ERR_HOST_NO_SPILL`; the other degradation codes
1532
+ // exist for the same audit trail. Ordinary "not worth it" skips are
1533
+ // deterministic policy, not a per-call decision (design §5.3), so they
1534
+ // write nothing.
1535
+ // A skip projected nothing, so it is a `skip` receipt, not a
1536
+ // `projection` one. `kind:'projection'` is not a promise of numeric
1537
+ // fields: the meterless apply branch above always writes
1538
+ // `estimate:'unknown'` but omits `before`/`after`/
1539
+ // `saved_projection_tokens` entirely (design §9), and consumers must
1540
+ // treat those as unpriced rather than assume the numbers exist.
1541
+ await appendReceipt(deps, ledgerEntry(ctx, 'skip', projectionSkipCode(outcome.reason)));
1542
+ }
1543
+ return decision;
1544
+ }
1545
+ catch {
1546
+ // `projectApply`/`projectShadow` already contain their own host calls; this
1547
+ // is the last belt for a bug in either of them.
1548
+ return decision;
1549
+ }
1550
+ }
1551
+ /**
1552
+ * The decision + projection stage.
1553
+ *
1554
+ * Both seams live in one place so the listener's order is visible in one
1555
+ * function: decide, then the double-projection guard, then project. A shadow
1556
+ * substitution does not stop the projection: the two switches are independent
1557
+ * (design §5.2-5), and in projection-shadow mode the projection writes only
1558
+ * its accounting line.
1559
+ */
1560
+ async function applyDecision(deps, decision, ctx) {
1561
+ // Projection below runs for a shadow commit too: the decision side never
1562
+ // suppresses the projection ledger.
1563
+ await decideSubstitution(deps, ctx);
1564
+ // Second-projection guard. Two host shapers are outer to this listener:
1565
+ //
1566
+ // - The spill policy registers with `{ prepend: true }`: it calls `next()`
1567
+ // and adds its footer to *that* decision after this listener returns. So
1568
+ // this check sees only a footer an inner listener already wrote, never the
1569
+ // host's own; it must not be read as full double-spill detection.
1570
+ // - For `glob`/`grep`, `@deepseek-ai/dsh-tool-fs-search` is outer too
1571
+ // (`dsh-base` loads it first) and would replace an over-cap result with its
1572
+ // own spill-backed preview. The plugin pre-empts it **deliberately**:
1573
+ // `acceptedDirectCallValue` does nothing as soon as the decision carries
1574
+ // `content` (`dsh-tool-fs-search/lib/index.js:490-493`), so the projection
1575
+ // accept below wins and the host preview never runs. That is the intended
1576
+ // trade for these two families: the plugin's window triggers at 700
1577
+ // characters, far below the host's 100-path / 250-match caps, and its own
1578
+ // footer keeps the spill locator, so the host preview has nothing to add
1579
+ // to a receipt this listener already clipped. A family the plugin does not
1580
+ // project leaves the host shaper untouched.
1581
+ //
1582
+ // Both the receiver as it arrived and the decision that will enter history
1583
+ // are checked (design §5.4).
1584
+ if (await isAlreadySpilled(deps, ctx.receipt.text))
1585
+ return decision;
1586
+ const downstreamText = decisionTextOf(decision) ?? ctx.receipt.text;
1587
+ if (downstreamText !== ctx.receipt.text && await isAlreadySpilled(deps, downstreamText)) {
1588
+ return decision;
1589
+ }
1590
+ return projectDecision(deps, ctx.receipt, decision, ctx);
1591
+ }
1592
+ // ---------------------------------------------------------------------------
1593
+ // The two listeners
1594
+ // ---------------------------------------------------------------------------
1595
+ /**
1596
+ * The `tools/post-execute` body.
1597
+ *
1598
+ * `next()` runs first, exactly like the host's own spill policy: a listener
1599
+ * either returns a decision or calls `next()` and returns its result, and
1600
+ * bypassing it would silently drop the listeners mounted after this one. The
1601
+ * fixed order that follows is `scope gate → canonicalise → invalidate →
1602
+ * substitution decision → double-projection guard → projection → return the
1603
+ * decision` (design §5.2-7/§5.4-5).
1604
+ *
1605
+ * Everything after `next()` is contained: the host turns a throwing
1606
+ * `post-execute` listener into an error result and the real tool output is
1607
+ * lost. A failure in our own wiring must therefore return the decision as it
1608
+ * arrived, never a thrown error.
1609
+ */
1610
+ async function postExecute(deps, state, exec, result, next) {
1611
+ const decision = await next();
1612
+ // The host cancels a call by aborting `exec.signal`; an async listener must
1613
+ // observe it before doing work whose result the model will never receive.
1614
+ // `next()` still runs — the waterfall must not drop the listeners mounted
1615
+ // after this one, and the host only replaces a successful accepted outcome
1616
+ // after they settle — but nothing after it does.
1617
+ if (cancelled(exec))
1618
+ return decision;
1619
+ // A PTC inner call traverses this waterfall with `parent` set. Its result
1620
+ // belongs to the enclosing `run_code` step, not to a step of its own: it must
1621
+ // not become `root`, drive a decision, consume the outer plan or overwrite the
1622
+ // outer anchors. Leaving it untouched is what keeps a plan from being decided
1623
+ // from an inner receipt.
1624
+ if (exec !== undefined && exec.parent !== undefined)
1625
+ return decision;
1626
+ if (exec?.agent === undefined) {
1627
+ await appendSkipNoScope(deps.receipts, exec);
1628
+ return decision;
1629
+ }
1630
+ // Exposure gate: an out-of-scope session pays nothing. This is the same
1631
+ // cached judgement the protocol section reads; a miss is false (fail-closed,
1632
+ // design §5.5).
1633
+ const sessionId = sessionIdOf(exec);
1634
+ if (sessionId === undefined) {
1635
+ // The agent exists but carries no usable session id, so neither the scope
1636
+ // gate nor the retrieval ledger can attribute this call. Fail closed and
1637
+ // keep the pass visible; the no-agent branch above does the same.
1638
+ await appendSkipNoScope(deps.receipts, exec);
1639
+ return decision;
1640
+ }
1641
+ // The mirrored dispatch is only meaningful while its usage mark is pending.
1642
+ // Once the mark is gone (settled by the next real request, or discarded), the
1643
+ // record is stale and a later turn's mark could reuse the candidate id.
1644
+ if (pendingCandidateOf(deps, sessionId) === undefined)
1645
+ clearAcceptedDispatch(deps, sessionId);
1646
+ // A substituted call denied by `tools/pre-execute` (approval or sandbox)
1647
+ // returns a post-result without invoking `tools/execute`, while post-execute
1648
+ // still runs. Matching the call id here clears the pending entry even though
1649
+ // no dispatch mapping exists, so the substitution is not re-synthesized on
1650
+ // every later step of the turn.
1651
+ clearMatchingPending(deps, sessionId, exec);
1652
+ // Detect the retrieval before the visibility gate (a projected receipt
1653
+ // already consumed context regardless of today's scope), but write its cost
1654
+ // only after projection, when the final visible content is known (review I3).
1655
+ const retrieval = pendingRetrievalOf(deps, exec, sessionId);
1656
+ if (!isActiveSession(deps, sessionId)) {
1657
+ if (retrieval !== undefined) {
1658
+ const arrival = canonicalise(result?.content ?? [], result?.isError === true);
1659
+ await recordProjectionRetrieval(deps, exec, sessionId, retrieval, arrival.text);
1660
+ }
1661
+ await appendSkipNoScope(deps.receipts, exec, sessionId, clockTurnOf(deps, sessionId) ?? 0);
1662
+ return decision;
1663
+ }
1664
+ try {
1665
+ // Canonicalise the original receiver, not a downstream replacement: guards
1666
+ // and the selector read the receipt as it arrived.
1667
+ const receipt = canonicalise(result?.content ?? [], result?.isError === true);
1668
+ const turn = clockTurnOf(deps, sessionId) ?? 0;
1669
+ // The receipt map is the gate's memory for this turn. `begin` folds the
1670
+ // previous turn away (anchors live in the store, receipts and in-flight
1671
+ // dispatches here), then the arriving receipt becomes `root` and, if it is
1672
+ // the call we substituted, also becomes the candidate's receipt.
1673
+ const { rolledOver } = state.begin(sessionId, turn);
1674
+ if (rolledOver) {
1675
+ // A pending entry and its decision-time usage mark from the previous turn
1676
+ // can never match a call in this one, so both are dead weight; the reset
1677
+ // path does the same mid-turn (F2). The mark is settled **without** a
1678
+ // settlement receipt when no substitution ran, exactly like
1679
+ // `resetInvalidatedPending` and `applyAbandon`. This branch is reachable
1680
+ // with a live mark because a parallel tool result can land after the host
1681
+ // advanced the turn but before this turn's first `llm/stream`, so the old
1682
+ // "the stream always runs first" argument does not hold (D1). When the
1683
+ // synthesized dispatch *was* accepted, the skipped model round is real:
1684
+ // `settleRollover` reports it with the sample the ledger has (row 28).
1685
+ await settleRollover(deps, sessionId, turn);
1686
+ clearAnchors(deps, sessionId);
1687
+ clearPending(deps, sessionId);
1688
+ // The plan map is normally reconciled by `SessionRuntime.notePlanTurn` on
1689
+ // the first real request of a turn. If that request has not run yet, a
1690
+ // plan still in the map belongs to the previous turn and would fire
1691
+ // against this new-turn receipt; drop it. When the request did run,
1692
+ // `notePlanTurn` reports false and the plan present was parsed by that
1693
+ // request's response: keep it, because clearing would discard a valid
1694
+ // new-turn plan.
1695
+ let planForThisTurn = false;
1696
+ try {
1697
+ planForThisTurn = deps.sessions?.notePlanTurn(sessionId, turn) === false;
1698
+ }
1699
+ catch {
1700
+ planForThisTurn = false;
1701
+ }
1702
+ if (!planForThisTurn)
1703
+ clearPlan(deps, sessionId);
1704
+ }
1705
+ state.recordRoot(sessionId, turn, receipt);
1706
+ fileDispatchedReceipt(state, exec, sessionId, turn, receipt);
1707
+ // Conservative local invalidation check. The tool-result path cannot see
1708
+ // the host pruner (it rewrites session surface nodes, not this waterfall)
1709
+ // or compaction, so only the **marker** branch is meaningful here: it
1710
+ // catches a receipt whose tool output itself carries the pruner literal.
1711
+ // The anchor comparison needs the anchored receipt's current text and
1712
+ // belongs to the model-request path (23c); running it here would compare a
1713
+ // different call's text and fire a false compaction-reset after every
1714
+ // commit (review F1). A hit only abandons the decision, which is safe.
1715
+ const pending = pendingAnchorsOf(deps, sessionId);
1716
+ // `!= null` rather than `!== undefined`: a foreign store can hand back a
1717
+ // null, and dereferencing it would throw out of the hook.
1718
+ if (pending != null) {
1719
+ const reset = markerResetOf(pending, receipt.text);
1720
+ if (reset !== undefined) {
1721
+ await resetInvalidatedPending(deps, exec, sessionId, turn, pending, reset);
1722
+ if (retrieval !== undefined) {
1723
+ await recordProjectionRetrieval(deps, exec, sessionId, retrieval, receipt.text);
1724
+ }
1725
+ return decision;
1726
+ }
1727
+ }
1728
+ const ctx = {
1729
+ sessionId,
1730
+ exec,
1731
+ receipt,
1732
+ doc: await scopeDocOf(deps),
1733
+ result,
1734
+ state,
1735
+ turn,
1736
+ retrievalCall: retrieval !== undefined,
1737
+ };
1738
+ const outgoing = await applyDecision(deps, decision, ctx);
1739
+ if (retrieval !== undefined) {
1740
+ // The retrieval receipt's content figure must price what enters history
1741
+ // after projection, not the raw result it arrived with.
1742
+ const visible = decisionTextOf(outgoing) ?? receipt.text;
1743
+ await recordProjectionRetrieval(deps, exec, sessionId, retrieval, visible);
1744
+ }
1745
+ return outgoing;
1746
+ }
1747
+ catch {
1748
+ // Never lose the tool's real output to a wiring bug in this listener.
1749
+ return decision;
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Drop a pending entry whose call id matches the arriving result.
1754
+ *
1755
+ * The execute hook clears the entry when it inspects an accepted or rejected
1756
+ * dispatch, but a call denied by `tools/pre-execute` never reaches that hook;
1757
+ * post-execute is then the only observer that knows the substituted call is
1758
+ * over. A different call id is an ordinary call and leaves the entry alone.
1759
+ */
1760
+ function clearMatchingPending(deps, sessionId, exec) {
1761
+ const pending = peekPending(deps, sessionId);
1762
+ if (pending === undefined)
1763
+ return;
1764
+ if (typeof exec.callId !== 'string' || exec.callId !== pending.callId)
1765
+ return;
1766
+ clearPending(deps, sessionId);
1767
+ }
1768
+ /** File an executed candidate's receipt under its plan id, consuming the dispatch record. */
1769
+ function fileDispatchedReceipt(state, exec, sessionId, turn, receipt) {
1770
+ const callId = exec?.callId;
1771
+ if (typeof callId !== 'string')
1772
+ return;
1773
+ const candidateId = state.takeDispatch(sessionId, turn, callId);
1774
+ if (candidateId === undefined)
1775
+ return;
1776
+ state.recordCandidate(sessionId, turn, candidateId, receipt);
1777
+ }
1778
+ /** The host's `ToolExecutionResult` failure branch for a refused dispatch. */
1779
+ function dispatchFailure(message) {
1780
+ return {
1781
+ isError: true,
1782
+ error: {
1783
+ message,
1784
+ info: { name: 'DispatchRejectedError', code: 'dispatch-rejected' },
1785
+ },
1786
+ content: [{ type: 'text', text: `Error: ${message}` }],
1787
+ };
1788
+ }
1789
+ /** Record one refused dispatch; a receipt write never changes the verdict. */
1790
+ async function appendDispatchRejected(deps, exec, entry, sessionId) {
1791
+ await appendReceipt(deps, {
1792
+ version: 1,
1793
+ ts: new Date().toISOString(),
1794
+ sessionId,
1795
+ turn: clockTurnOf(deps, sessionId) ?? 0,
1796
+ stepId: 'root',
1797
+ kind: 'skip',
1798
+ code: 'dispatch-rejected',
1799
+ tool: exec.name,
1800
+ callId: typeof exec.callId === 'string' ? exec.callId : undefined,
1801
+ candidateId: entry.candidateId,
1802
+ // The refused call's own args, not the pending decision's: the operator
1803
+ // needs to see exactly what the host was asked to run.
1804
+ args: exec.arguments,
1805
+ preview: callPreview(exec.name, exec.arguments),
1806
+ });
1807
+ }
1808
+ /**
1809
+ * The inspect half of `tools/execute`: no `next()` is called here, so a throw
1810
+ * can never cause the dispatch to run twice.
1811
+ *
1812
+ * Every operation is contained (the lookup, the clearing, the receipt write),
1813
+ * so the only throw this function can produce is a bug of its own; the caller
1814
+ * then fails open.
1815
+ */
1816
+ async function inspectDispatch(deps, exec) {
1817
+ const sessionId = sessionIdOf(exec);
1818
+ if (sessionId === undefined)
1819
+ return { kind: 'next' };
1820
+ const entry = peekPending(deps, sessionId);
1821
+ if (entry === undefined)
1822
+ return { kind: 'next' };
1823
+ const reject = async (message) => {
1824
+ clearPending(deps, sessionId);
1825
+ await appendDispatchRejected(deps, exec, entry, sessionId);
1826
+ return { kind: 'reject', message };
1827
+ };
1828
+ // A different call id is an ordinary call, not tampering: the host assigns
1829
+ // call ids, so only a call that carries the id we chose is the dispatch under
1830
+ // inspection. Rejecting the rest would lose a legitimate tool's output (F2).
1831
+ if (typeof exec.callId !== 'string' || exec.callId !== entry.callId) {
1832
+ return { kind: 'next' };
1833
+ }
1834
+ // `rejectIfTampered` compares name and parsed arguments only; the call id was
1835
+ // compared above.
1836
+ if (rejectIfTampered(exec, entry).reject) {
1837
+ return reject('dsh-boost refused a substituted call: the dispatched arguments do not match the pending decision');
1838
+ }
1839
+ // Accept path: the entry has done its job, so drop it before dispatching.
1840
+ clearPending(deps, sessionId);
1841
+ return {
1842
+ kind: 'accept',
1843
+ sessionId,
1844
+ callId: entry.callId,
1845
+ candidateId: entry.candidateId,
1846
+ evidence: entry.evidence,
1847
+ };
1848
+ }
1849
+ /**
1850
+ * The `tools/execute` hook body: refuse a tampered substitution.
1851
+ *
1852
+ * With no pending entry the plugin is not substituting this call, so `next()`
1853
+ * runs untouched. The entry describes the dispatch we synthesised: a call that
1854
+ * carries the **same** call id is inspected, compared with the decision, and
1855
+ * the entry is cleared on both the accept and the reject path so it cannot
1856
+ * outlive its dispatch. A call with a **different** call id is an ordinary call
1857
+ * — the host assigns ids — and passes through without touching the entry
1858
+ * (review F2: rejecting it would lose a legitimate tool's output). On the
1859
+ * accept path the call id is remembered so the following `post-execute` can
1860
+ * file the receipt under its candidate id.
1861
+ *
1862
+ * The mount fails open on an internal error (the design's fail-closed means
1863
+ * "pass through, do not substitute", never "intercept"): a broken queue must
1864
+ * not block every tool call in the process.
1865
+ */
1866
+ async function executeHook(deps, state, exec, next) {
1867
+ let outcome;
1868
+ try {
1869
+ outcome = await inspectDispatch(deps, exec);
1870
+ }
1871
+ catch {
1872
+ return next();
1873
+ }
1874
+ if (outcome.kind === 'reject')
1875
+ return dispatchFailure(outcome.message);
1876
+ if (outcome.kind === 'accept') {
1877
+ const turn = clockTurnOf(deps, outcome.sessionId) ?? 0;
1878
+ try {
1879
+ state.recordDispatch(outcome.sessionId, turn, outcome.callId, outcome.candidateId);
1880
+ }
1881
+ catch {
1882
+ // Losing the mapping costs the candidate receipt, not this call.
1883
+ }
1884
+ // The same fact, kept outside `ReceiptSessionState` because the candidate's
1885
+ // post-execute consumes that mapping before a rollover can look at it.
1886
+ noteAcceptedDispatch(deps, outcome.sessionId, turn, outcome.candidateId, outcome.evidence);
1887
+ }
1888
+ return next();
1889
+ }
1890
+ // ---------------------------------------------------------------------------
1891
+ // Registration
1892
+ // ---------------------------------------------------------------------------
1893
+ /** Mount the projection waterfall. */
1894
+ function registerPostExecute(ctx, deps, state) {
1895
+ ctx.on('tools/post-execute', (exec, result, next) => postExecute(deps, state, exec, result, next));
1896
+ }
1897
+ /** Mount the model-request waterfall; the hook function is built once per registration. */
1898
+ function registerLlmStream(ctx, deps) {
1899
+ const hook = streamHook(deps);
1900
+ ctx.on('llm/stream', (options, next) => hook(options, next));
1901
+ }
1902
+ /** Mount the dispatch waterfall. */
1903
+ function registerExecute(ctx, deps, state) {
1904
+ ctx.on('tools/execute', (exec, next) => executeHook(deps, state, exec, next));
1905
+ }
1906
+ /** Mount the protocol section, whose provider stays synchronous and per-agent. */
1907
+ function registerProtocolSection(ctx, scope) {
1908
+ ctx.systemPrompt.section({
1909
+ name: PROTOCOL_NAME,
1910
+ order: PROTOCOL_ORDER,
1911
+ interpolate: false,
1912
+ text: (context) => protocolText(scope, context),
1913
+ });
1914
+ }
1915
+ /**
1916
+ * Register the plugin's four host integration points.
1917
+ *
1918
+ * The prompt section is registered first on purpose: it is the only mount that
1919
+ * rejects a duplicate name, so a second `apply` aborts here before any event
1920
+ * hook is mounted twice (the host turns a duplicate section into an error, and
1921
+ * `apply` treats that as "already mounted"). Registering it last would leave
1922
+ * three live duplicate listeners behind.
1923
+ *
1924
+ * One `ReceiptSessionState` belongs to the whole registration: the execute
1925
+ * mount writes the in-flight call mapping and the post-execute mount consumes
1926
+ * it, so the two waterfalls must share it.
1927
+ *
1928
+ * `scope`, `receipts`, `anchors` and `resolveSession` are required by
1929
+ * `HookDeps`, but they are still checked at the point of use: a host wiring the
1930
+ * plugin without one of the optional pieces still gets the four mount points,
1931
+ * and every degraded path is fail-closed instead of throwing during
1932
+ * registration.
1933
+ */
1934
+ export function registerHooks(ctx, deps) {
1935
+ const state = deps.sessionState ?? new ReceiptSessionState();
1936
+ // Publish the instance we created. `clearSession` and Task 23c-2's session-end
1937
+ // wiring reach the state through `deps.sessionState`; a caller that omits it
1938
+ // (the plan's 23c-2 assembly list does) would otherwise leave the created
1939
+ // receipt/dispatch maps unreachable and leaked per session.
1940
+ deps.sessionState = state;
1941
+ // The logger is a host service the caller already has; publishing it here
1942
+ // keeps the degradation warnings reachable without widening every caller's
1943
+ // deps literal. A deps object that already names one keeps it.
1944
+ deps.logger ??= ctx.logger;
1945
+ registerProtocolSection(ctx, deps.scope);
1946
+ registerPostExecute(ctx, deps, state);
1947
+ registerLlmStream(ctx, deps);
1948
+ registerExecute(ctx, deps, state);
1949
+ }
1950
+ //# sourceMappingURL=post-execute.js.map