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,1086 @@
1
+ import { StepBudget } from '../admission/ledger.js';
2
+ import { UsageLedger } from '../admission/usage.js';
3
+ import { DEFAULT_CONFIG } from '../config.js';
4
+ import { looksPruned, PRUNE_MARKER } from '../gate/invalidate.js';
5
+ import { parsePlan } from '../gate/plan.js';
6
+ import { TurnClock } from './clock.js';
7
+ import { synthesizeTurn } from './synthesize.js';
8
+ import { appendReceipt, callPreview, clearAnchors, clearPlan, clearPending, clockTurnOf, peekPending, } from './session-state.js';
9
+ /** Default head/tail probe length for a receipt rewritten in place. */
10
+ const ANCHOR_PROBE_CHARS = 32;
11
+ /**
12
+ * Per-session clock, budget and usage ledger.
13
+ *
14
+ * The host numbers turns and steps per session; a single instance therefore
15
+ * lets one session's `agent/request` stamp another session's derived `callId`,
16
+ * lets one session's `StepBudget(1)` starve the next, and pairs one session's
17
+ * substitution with another session's request. The runtime keys all three by
18
+ * `sessionId` and is the only place a per-session primitive is created.
19
+ *
20
+ * The map is private: callers get the objects, never the map, and
21
+ * {@link SessionRuntime.clear} is the only way an entry leaves. `onModelRequest`
22
+ * is driven by Task 23c-2 from the host's `agent/request` payload; this module
23
+ * cannot see that event itself. A new turn resets that session's budget (the
24
+ * budget is per-turn, not per-lifetime); a non-finite or backwards turn is
25
+ * ignored by `TurnClock` and therefore resets nothing.
26
+ */
27
+ export class SessionRuntime {
28
+ bySession = new Map();
29
+ stepsPerTurn;
30
+ constructor(stepsPerTurn = DEFAULT_CONFIG.stepsPerTurn) {
31
+ // `StepBudget` already treats a non-positive max as empty; only a
32
+ // non-finite value (which no resolved config can produce) falls back.
33
+ this.stepsPerTurn = Number.isFinite(stepsPerTurn)
34
+ ? stepsPerTurn
35
+ : DEFAULT_CONFIG.stepsPerTurn;
36
+ }
37
+ /** The session's clock, created on first use. */
38
+ clockFor(sessionId) {
39
+ return this.entry(sessionId).clock;
40
+ }
41
+ /** The session's turn budget, created on first use. */
42
+ budgetFor(sessionId) {
43
+ return this.entry(sessionId).budget;
44
+ }
45
+ /** The session's usage ledger, created on first use. */
46
+ usageFor(sessionId) {
47
+ return this.entry(sessionId).usage;
48
+ }
49
+ /**
50
+ * Record one host request for a session.
51
+ *
52
+ * `turn`/`step` are the host's numbers, copied through `TurnClock` (which
53
+ * ignores non-finite and backwards turns). A turn change is the only thing
54
+ * that resets the budget: a second request in one turn must keep the spend.
55
+ */
56
+ onModelRequest(sessionId, turn, step) {
57
+ const entry = this.entry(sessionId);
58
+ const before = entry.clock.turn();
59
+ entry.clock.onModelRequest(turn, step);
60
+ if (entry.clock.turn() !== before)
61
+ entry.budget.reset();
62
+ }
63
+ /**
64
+ * Reconcile this session's plan store with `turn`; `true` on a turn change.
65
+ *
66
+ * The plan lives in `HookDeps.plans` and is keyed by session only, so
67
+ * without this note a turn that emits no new plan keeps the previous turn's
68
+ * one, and its remaining steps can still drive a substitution. The stream
69
+ * hook calls this once per **real** request (never for an auxiliary
70
+ * `purpose`, which is not a conversation step) and clears the plan map when
71
+ * it returns true, before that request's response could write a new plan.
72
+ * The first call reports true so a seeded map cannot outlive its first
73
+ * request; `clearSession` drops the note with the rest of the entry.
74
+ */
75
+ notePlanTurn(sessionId, turn) {
76
+ const entry = this.entry(sessionId);
77
+ if (entry.planTurn === turn)
78
+ return false;
79
+ entry.planTurn = turn;
80
+ return true;
81
+ }
82
+ /** Drop everything this runtime holds for one session. */
83
+ clear(sessionId) {
84
+ this.bySession.delete(sessionId);
85
+ }
86
+ /** Number of sessions with state (not the number ever seen). */
87
+ size() {
88
+ return this.bySession.size;
89
+ }
90
+ entry(sessionId) {
91
+ const existing = this.bySession.get(sessionId);
92
+ if (existing !== undefined)
93
+ return existing;
94
+ const entry = {
95
+ clock: new TurnClock(),
96
+ budget: new StepBudget(this.stepsPerTurn),
97
+ usage: new UsageLedger(),
98
+ };
99
+ this.bySession.set(sessionId, entry);
100
+ return entry;
101
+ }
102
+ }
103
+ // ---------------------------------------------------------------------------
104
+ // Defensive readers: every foreign call is wrapped
105
+ // ---------------------------------------------------------------------------
106
+ /** The request's session id, or `undefined` when the host supplied none. */
107
+ function sessionIdOf(options) {
108
+ const id = options?.sessionId;
109
+ return typeof id === 'string' && id.length > 0 ? id : undefined;
110
+ }
111
+ /**
112
+ * Which session has been lent each shared fallback instance.
113
+ *
114
+ * `apply` always passes `sessions`, so this exists for embedders and tests that
115
+ * hand in one `clock`/`budget`/`usage` instead. Those three carry per-session
116
+ * state — a turn's step counter, a pending usage mark — so lending one to a
117
+ * second session attributes B's tokens to A's candidate. That surfaces as a
118
+ * saving that never happened, which is the one error this plugin must not
119
+ * produce. Ownership is keyed by the **instance**, not by the deps object: two
120
+ * assemblies that share the same three objects (the pattern the fallback exists
121
+ * for) must agree on the one session they serve, or each claims its own loan
122
+ * and both borrow. The first session to arrive keeps the loan; every other
123
+ * session gets `undefined`, which each caller already reads as "no
124
+ * substitution" (fail closed), and the warning is emitted once per deps object
125
+ * rather than per call. `clearSession` drops the loans its session holds, so a
126
+ * disposed owner does not lock the instance for the rest of the process.
127
+ */
128
+ const fallbackLoans = new WeakMap();
129
+ /** Deps objects already warned about a refused loan (once each, not per call). */
130
+ const fallbackWarned = new WeakSet();
131
+ /** Whether the shared fallback instance may serve this session. */
132
+ function mayBorrowShared(instance, deps, sessionId) {
133
+ const held = fallbackLoans.get(instance);
134
+ if (held === undefined) {
135
+ fallbackLoans.set(instance, { sessionId });
136
+ return true;
137
+ }
138
+ if (held.sessionId === sessionId)
139
+ return true;
140
+ if (!fallbackWarned.has(deps)) {
141
+ fallbackWarned.add(deps);
142
+ try {
143
+ deps.logger?.warn(`dsh-boost: no per-session runtime is wired, and session ${sessionId} is not the one already using the shared clock/budget/usage; substitution stays off for it rather than mixing two sessions' measurements`);
144
+ }
145
+ catch {
146
+ // A logger that throws must not turn a measurement guard into a failure.
147
+ }
148
+ }
149
+ return false;
150
+ }
151
+ /** Release the shared-instance loans the disposing session holds. */
152
+ function releaseSharedLoans(deps, sessionId) {
153
+ for (const instance of [deps.clock, deps.budget, deps.usage]) {
154
+ if (instance === undefined)
155
+ continue;
156
+ if (fallbackLoans.get(instance)?.sessionId === sessionId)
157
+ fallbackLoans.delete(instance);
158
+ }
159
+ }
160
+ /**
161
+ * The session's clock: the per-session runtime when wired, the shared instance
162
+ * otherwise — but only for the one session that instance belongs to.
163
+ *
164
+ * Exported because `tools/post-execute` must resolve the *same* clock for the
165
+ * turn/step it stamps into a `callId`; two copies of this precedence rule could
166
+ * drift and let the decision and the stream hook disagree about one session.
167
+ */
168
+ export function sessionClock(deps, sessionId) {
169
+ try {
170
+ const owned = deps.sessions?.clockFor(sessionId);
171
+ if (owned !== undefined)
172
+ return owned;
173
+ }
174
+ catch {
175
+ // Fall through to the shared instance, subject to the ownership rule.
176
+ }
177
+ return deps.clock !== undefined && mayBorrowShared(deps.clock, deps, sessionId)
178
+ ? deps.clock
179
+ : undefined;
180
+ }
181
+ /** The session's turn budget; the same precedence as {@link sessionClock}. */
182
+ export function sessionBudget(deps, sessionId) {
183
+ try {
184
+ const owned = deps.sessions?.budgetFor(sessionId);
185
+ if (owned !== undefined)
186
+ return owned;
187
+ }
188
+ catch {
189
+ // Fall through to the shared instance, subject to the ownership rule.
190
+ }
191
+ return deps.budget !== undefined && mayBorrowShared(deps.budget, deps, sessionId)
192
+ ? deps.budget
193
+ : undefined;
194
+ }
195
+ /** The session's usage ledger; the same precedence as {@link sessionClock}. */
196
+ export function sessionUsage(deps, sessionId) {
197
+ try {
198
+ const owned = deps.sessions?.usageFor(sessionId);
199
+ if (owned !== undefined)
200
+ return owned;
201
+ }
202
+ catch {
203
+ // Fall through to the shared instance, subject to the ownership rule.
204
+ }
205
+ return deps.usage !== undefined && mayBorrowShared(deps.usage, deps, sessionId)
206
+ ? deps.usage
207
+ : undefined;
208
+ }
209
+ /** The session's anchors without ever failing the request. */
210
+ function anchorsOf(deps, sessionId) {
211
+ try {
212
+ return deps.anchors?.get(sessionId);
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
217
+ }
218
+ /**
219
+ * Whether the receipt store has stopped writing, fail-closed.
220
+ *
221
+ * A missing `stopped` (a partial store in a test or an older host) is "not
222
+ * stopped", so the ordinary path is unchanged. A store that *throws* cannot
223
+ * record evidence, which is exactly what stopped means.
224
+ */
225
+ export function receiptsStopped(deps) {
226
+ try {
227
+ const store = deps.receipts;
228
+ if (store == null || typeof store.stopped !== 'function')
229
+ return false;
230
+ return store.stopped() === true;
231
+ }
232
+ catch {
233
+ return true;
234
+ }
235
+ }
236
+ /**
237
+ * Whether the session resolves to a workspace.
238
+ *
239
+ * The stream hook's rule only needs the resolver: a session that does not
240
+ * resolve has no substitute-able workspace, so the decision cannot be honoured.
241
+ * The live scope-document check lives in `tools/post-execute`, which owns the
242
+ * async document read; `resolveSession` is synchronous by contract.
243
+ */
244
+ function visibleSession(deps, sessionId) {
245
+ try {
246
+ const resolve = deps.resolveSession;
247
+ if (typeof resolve !== 'function')
248
+ return false;
249
+ return typeof resolve(sessionId) === 'string';
250
+ }
251
+ catch {
252
+ return false;
253
+ }
254
+ }
255
+ /** The host turn and the entry's turn are the same, number or stringified number. */
256
+ function sameTurn(entryTurn, clockTurn) {
257
+ return String(entryTurn) === String(clockTurn);
258
+ }
259
+ /** A receipt's `turn` field is a number; entry turns may already be strings. */
260
+ function turnNumberOf(turn) {
261
+ if (typeof turn === 'number' && Number.isFinite(turn))
262
+ return turn;
263
+ const parsed = Number(turn);
264
+ return Number.isFinite(parsed) ? parsed : 0;
265
+ }
266
+ // ---------------------------------------------------------------------------
267
+ // Anchor detection against the outgoing messages (obligation 6)
268
+ // ---------------------------------------------------------------------------
269
+ /**
270
+ * Every text-block body the model will see in this request.
271
+ *
272
+ * `RequestMessage.content` is an array of blocks; only `text` blocks carry
273
+ * receipt bodies. Blocks are kept separate so a mixed message cannot make two
274
+ * unrelated texts look like one receipt. A malformed message is skipped, never
275
+ * a throw: `options.messages` is host-shaped data.
276
+ */
277
+ function messageTexts(messages) {
278
+ if (!Array.isArray(messages))
279
+ return [];
280
+ const bodies = [];
281
+ for (const message of messages) {
282
+ const content = message?.content;
283
+ if (!Array.isArray(content))
284
+ continue;
285
+ for (const block of content) {
286
+ if (typeof block !== 'object' || block === null)
287
+ continue;
288
+ const { type, text } = block;
289
+ if (type === 'text' && typeof text === 'string')
290
+ bodies.push(text);
291
+ }
292
+ }
293
+ return bodies;
294
+ }
295
+ /**
296
+ * The head/tail probe windows, clamped to the projection's own windows.
297
+ *
298
+ * Our projection keeps `headChars`/`tailChars` code points of the receipt, so
299
+ * a probe longer than a configured window can never match a projected body and
300
+ * would report `compaction-reset`. `resolveConfig` accepts any finite value
301
+ * (including 0), so the window is the smallest one any family configures,
302
+ * capped at {@link ANCHOR_PROBE_CHARS}; a 0 window drops that side of the
303
+ * probe and leaves only the other. With the design defaults this is 32/32.
304
+ */
305
+ function anchorProbe(deps) {
306
+ let head = ANCHOR_PROBE_CHARS;
307
+ let tail = ANCHOR_PROBE_CHARS;
308
+ try {
309
+ const projection = deps.config?.projection;
310
+ if (typeof projection !== 'object' || projection === null)
311
+ return { head, tail };
312
+ for (const raw of Object.values(projection)) {
313
+ const params = raw;
314
+ if (typeof params?.headChars === 'number' && Number.isFinite(params.headChars)) {
315
+ head = Math.min(head, Math.max(0, params.headChars));
316
+ }
317
+ if (typeof params?.tailChars === 'number' && Number.isFinite(params.tailChars)) {
318
+ tail = Math.min(tail, Math.max(0, params.tailChars));
319
+ }
320
+ }
321
+ }
322
+ catch {
323
+ return { head: ANCHOR_PROBE_CHARS, tail: ANCHOR_PROBE_CHARS };
324
+ }
325
+ return { head, tail };
326
+ }
327
+ /**
328
+ * The head line our own projection writes: `[output N chars; showing first H
329
+ * and last T]`. The counts use `toLocaleString('en-US')`, hence the commas.
330
+ */
331
+ const PROJECTION_HEADER = /^\[output ([\d,]+) chars; showing first ([\d,]+) and last ([\d,]+)\]$/;
332
+ /** One `en-US`-formatted count from a projection head line. */
333
+ function headerCount(raw) {
334
+ if (raw === undefined)
335
+ return undefined;
336
+ const value = Number(raw.replaceAll(',', ''));
337
+ return Number.isSafeInteger(value) ? value : undefined;
338
+ }
339
+ /**
340
+ * Whether `body` is our own projection of `anchor`.
341
+ *
342
+ * A projected receipt is `head line + head + spill footer + tail`. The head
343
+ * line names the anchor's total code points and both window sizes, and the two
344
+ * windows are the anchor's own first/last code points. A full receipt that
345
+ * merely shares the anchor's head and tail cannot produce that line, so this
346
+ * closes the probe collision without reading the middle (which the projection
347
+ * removed) and without a new stored field. Old anchors that cannot be verified
348
+ * this way simply do not match, which fails closed.
349
+ */
350
+ function ownProjectionCarries(body, anchor) {
351
+ const newline = body.indexOf('\n');
352
+ if (newline === -1)
353
+ return false;
354
+ const match = PROJECTION_HEADER.exec(body.slice(0, newline));
355
+ if (match === null)
356
+ return false;
357
+ const output = headerCount(match[1]);
358
+ const headLen = headerCount(match[2]);
359
+ const tailLen = headerCount(match[3]);
360
+ if (output === undefined || headLen === undefined || tailLen === undefined)
361
+ return false;
362
+ if (headLen <= 0 && tailLen <= 0)
363
+ return false;
364
+ const points = Array.from(anchor);
365
+ if (output !== points.length)
366
+ return false;
367
+ if (headLen + tailLen >= points.length)
368
+ return false;
369
+ const head = headLen > 0 ? points.slice(0, headLen).join('') : '';
370
+ const tail = tailLen > 0 ? points.slice(-tailLen).join('') : '';
371
+ return body.startsWith(`${match[0]}\n${head}`) && (tailLen === 0 || body.endsWith(tail));
372
+ }
373
+ /**
374
+ * Whether `body` is the anchor rewritten **by the host pruner**, and nothing
375
+ * else.
376
+ *
377
+ * `looksPruned` alone is not identity: any body that embeds the anchor's pruned
378
+ * text — a `read` of a session log, the case `invalidate` documents as
379
+ * occurring — carries the marker too, so a receipt that was compacted away
380
+ * could be declared "still carried" and a decision would survive on evidence
381
+ * the model no longer holds.
382
+ *
383
+ * The pruner replaces the middle with a single marker and keeps a head and a
384
+ * tail, so a genuine carrier is `head + marker + tail` with nothing before the
385
+ * head and nothing after the tail. Requiring the carrier to *start* with the
386
+ * anchor's first `head` code points and *end* with its last `tail` ones — the
387
+ * same windows `ownProjectionCarries` derives for our own rewrite — rejects the
388
+ * wrapper: its head is the wrapper's opening line, not the anchor's.
389
+ */
390
+ function prunedCarries(body, anchor) {
391
+ const marker = body.indexOf(PRUNE_MARKER);
392
+ if (marker === -1)
393
+ return false;
394
+ // Exactly one marker: two would mean this is not one pruned receipt.
395
+ if (body.indexOf(PRUNE_MARKER, marker + PRUNE_MARKER.length) !== -1)
396
+ return false;
397
+ const head = body.slice(0, marker);
398
+ const tail = body.slice(marker + PRUNE_MARKER.length);
399
+ if (head.length === 0 || tail.length === 0)
400
+ return false;
401
+ const points = Array.from(anchor);
402
+ const headPoints = Array.from(head);
403
+ const tailPoints = Array.from(tail);
404
+ if (headPoints.length + tailPoints.length >= points.length)
405
+ return false;
406
+ return (points.slice(0, headPoints.length).join('') === head &&
407
+ points.slice(-tailPoints.length).join('') === tail);
408
+ }
409
+ /**
410
+ * Whether `body` still carries `anchor`, verbatim or as a verified in-place
411
+ * rewrite.
412
+ *
413
+ * The host pruner replaces the middle of an oversized receipt with
414
+ * `PRUNE_MARKER` while preserving a head and a tail; apply-mode projection
415
+ * composes head line + head + spill footer + tail. Both keep the anchor's
416
+ * beginning and end, so a body holding both probes *and* the rewrite's own
417
+ * evidence is the same receipt rewritten in place.
418
+ *
419
+ * Sharing the two probes alone is not identity: a file edited in the middle and
420
+ * re-read produces a full receipt with the same 32-character head and tail but
421
+ * a different body. Accepting it would substitute against content the model no
422
+ * longer holds, so a probe match must be accompanied by the pruner marker or
423
+ * our projection's head line. Anything else is a lost anchor (fail closed).
424
+ *
425
+ * Probes are sliced by **code point**, exactly like `truncate`: a UTF-16 slice
426
+ * can end on half a surrogate pair, and a lone surrogate is not a substring a
427
+ * correctly projected body has to contain. Short anchors whose two windows
428
+ * would cover the whole text get no probe treatment: at that size the exact
429
+ * text either is present or the receipt is gone.
430
+ */
431
+ function carriesAnchor(body, anchor, probe) {
432
+ if (body.includes(anchor))
433
+ return true;
434
+ const points = Array.from(anchor);
435
+ const headLen = Math.min(probe.head, points.length);
436
+ const tailLen = Math.min(probe.tail, points.length);
437
+ if (headLen === 0 && tailLen === 0)
438
+ return false;
439
+ if (points.length <= headLen + tailLen)
440
+ return false;
441
+ const head = headLen > 0 ? points.slice(0, headLen).join('') : '';
442
+ const tail = tailLen > 0 ? points.slice(-tailLen).join('') : '';
443
+ const start = headLen > 0 ? body.indexOf(head) : 0;
444
+ if (headLen > 0 && start === -1)
445
+ return false;
446
+ if (tailLen > 0 && body.indexOf(tail, start + headLen) === -1)
447
+ return false;
448
+ return prunedCarries(body, anchor) || ownProjectionCarries(body, anchor);
449
+ }
450
+ /**
451
+ * Why the decision's anchored receipts are no longer trustworthy, if they are.
452
+ *
453
+ * Marker precedence matches `invalidate`: any carried body that contains the
454
+ * pruner literal means `pruned-reset`, because the pruner is the common case
455
+ * and it leaves the receipt in place. Only when no anchor was pruned does a
456
+ * missing carrier mean `compaction-reset` (the history was replaced by a
457
+ * summary). No anchors at all is vacuously intact: `post-execute` always writes
458
+ * them with a commit, but a missing evidence store must not block substitution
459
+ * forever.
460
+ *
461
+ * An empty anchor cannot be located in any message and is skipped; `invalidate`
462
+ * treats an empty anchor as a real value, but the stream hook has no receipt
463
+ * body to compare it with, and refusing every substitution on one empty tool
464
+ * result would be worse than the uncertainty.
465
+ */
466
+ function anchorResetOf(anchors, messages, probe) {
467
+ if (anchors == null)
468
+ return undefined;
469
+ const record = anchors.anchors;
470
+ if (typeof record !== 'object' || record === null)
471
+ return undefined;
472
+ const values = Object.values(record);
473
+ if (values.length === 0)
474
+ return undefined;
475
+ const texts = values.filter((text) => typeof text === 'string' && text.length > 0);
476
+ if (texts.length === 0) {
477
+ // An empty anchor is a real value the check skips (it cannot be located in
478
+ // any message). Any other unverifiable shape — an object from an older or
479
+ // foreign anchor store — must fail closed instead: treating it as "no
480
+ // anchors" would substitute on evidence this code cannot read.
481
+ return values.every((value) => value === '') ? undefined : 'compaction-reset';
482
+ }
483
+ const bodies = messageTexts(messages);
484
+ let compacted = false;
485
+ for (const anchor of texts) {
486
+ if (looksPruned(anchor))
487
+ return 'pruned-reset';
488
+ const carriers = bodies.filter((body) => carriesAnchor(body, anchor, probe));
489
+ if (carriers.length === 0) {
490
+ compacted = true;
491
+ continue;
492
+ }
493
+ if (carriers.some((body) => looksPruned(body)))
494
+ return 'pruned-reset';
495
+ }
496
+ return compacted ? 'compaction-reset' : undefined;
497
+ }
498
+ /**
499
+ * Per-session synthesis history, keyed by `HookDeps` first so two plugin
500
+ * instances in one process cannot read each other's session. It holds one turn
501
+ * per session and dies with the assembly; `clearSession` drops the session.
502
+ */
503
+ const SYNTHESIS_TALLY = new WeakMap();
504
+ /** The session's synthesis tally, if this turn has one. */
505
+ function synthesisTallyOf(deps, sessionId) {
506
+ try {
507
+ return SYNTHESIS_TALLY.get(deps)?.get(sessionId);
508
+ }
509
+ catch {
510
+ return undefined;
511
+ }
512
+ }
513
+ /** Count one synthesized turn, starting a new tally when the turn changed. */
514
+ function recordSynthesis(deps, sessionId, turn, callId) {
515
+ try {
516
+ let bySession = SYNTHESIS_TALLY.get(deps);
517
+ if (bySession === undefined) {
518
+ bySession = new Map();
519
+ SYNTHESIS_TALLY.set(deps, bySession);
520
+ }
521
+ let tally = bySession.get(sessionId);
522
+ if (tally === undefined || tally.turn !== turn) {
523
+ tally = { turn, count: 0, callIds: new Set() };
524
+ bySession.set(sessionId, tally);
525
+ }
526
+ tally.count += 1;
527
+ tally.callIds.add(callId);
528
+ }
529
+ catch {
530
+ // A tally miss costs a duplicate guard, never this request.
531
+ }
532
+ }
533
+ /** Drop one session's synthesis history at session end. */
534
+ function forgetSynthesis(deps, sessionId) {
535
+ try {
536
+ SYNTHESIS_TALLY.get(deps)?.delete(sessionId);
537
+ }
538
+ catch {
539
+ // Same: the tally is a guard, not a precondition.
540
+ }
541
+ }
542
+ /**
543
+ * Whether the entry's step can no longer be honoured.
544
+ *
545
+ * Two independent facts make a still-live entry unhonourable: its deterministic
546
+ * call id was already synthesized in this turn (a retry or a re-enqueue at one
547
+ * step), or the turn's paid steps are already used up by earlier syntheses.
548
+ * A budget that reports no spend at all is a fixture/legacy shape rather than
549
+ * proof of a step; the call-id half still applies there.
550
+ */
551
+ function synthesisBlocked(deps, sessionId, entry, turn) {
552
+ const tally = synthesisTallyOf(deps, sessionId);
553
+ const current = tally !== undefined && sameTurn(tally.turn, turn) ? tally : undefined;
554
+ if (current !== undefined && current.callIds.has(entry.callId))
555
+ return true;
556
+ const budget = sessionBudget(deps, sessionId);
557
+ if (budget === undefined)
558
+ return false;
559
+ let spent;
560
+ try {
561
+ spent = budget.count();
562
+ }
563
+ catch {
564
+ return false;
565
+ }
566
+ if (!Number.isFinite(spent) || spent <= 0)
567
+ return false;
568
+ return (current?.count ?? 0) >= spent;
569
+ }
570
+ /**
571
+ * The rule order as pure, synchronous decision logic.
572
+ *
573
+ * Nothing here writes a receipt or takes a step: every check completes before
574
+ * the first effect. `post-execute` already took the budget at the decision
575
+ * point (obligation 2), so this function never touches the budget.
576
+ */
577
+ function resolveStreamPlan(deps, options) {
578
+ const sessionId = sessionIdOf(options);
579
+ // The selector guard is the first rule and lives in `streamHook`, which
580
+ // returns `next()` before this function runs: a selector request must not
581
+ // even be observed, so it cannot become a plan.
582
+ if (receiptsStopped(deps)) {
583
+ // Fail-closed: the decision cannot be recorded, so it will never be
584
+ // synthesized. Empty the queue and settle the decision-time mark even when
585
+ // the queue entry is already gone (the dispatch side may have consumed it);
586
+ // otherwise the mark would settle a later real request as a substitution.
587
+ return passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false }, true);
588
+ }
589
+ if (sessionId === undefined)
590
+ return { kind: 'pass', sessionId };
591
+ if (!visibleSession(deps, sessionId)) {
592
+ return passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false });
593
+ }
594
+ const entry = peekPending(deps, sessionId);
595
+ if (entry === undefined)
596
+ return { kind: 'pass', sessionId };
597
+ const turn = clockTurnOf(deps, sessionId);
598
+ if (turn === undefined || !sameTurn(entry.turn, turn)) {
599
+ return {
600
+ kind: 'pass',
601
+ sessionId,
602
+ abandon: { entry, clearQueue: true, clearAnchors: false },
603
+ };
604
+ }
605
+ // A blank call id cannot be dispatched and must not be "repaired" here: the
606
+ // execute-side tamper check would compare a different id and reject silently.
607
+ if (typeof entry.callId !== 'string' || entry.callId.trim().length === 0) {
608
+ return {
609
+ kind: 'pass',
610
+ sessionId,
611
+ abandon: { entry, clearQueue: true, clearAnchors: false },
612
+ };
613
+ }
614
+ const anchors = anchorsOf(deps, sessionId);
615
+ const reset = anchorResetOf(anchors, options?.messages, anchorProbe(deps));
616
+ if (reset !== undefined) {
617
+ return {
618
+ kind: 'pass',
619
+ sessionId,
620
+ abandon: {
621
+ entry,
622
+ clearQueue: true,
623
+ clearAnchors: true,
624
+ reset: {
625
+ code: reset,
626
+ stepId: typeof anchors?.stepId === 'string' ? anchors.stepId : 'root',
627
+ turn: turn,
628
+ },
629
+ },
630
+ };
631
+ }
632
+ // Re-check the step immediately before synthesizing. The turn/step checks
633
+ // above validate identity, not spend: a retried or re-enqueued request in the
634
+ // same turn would otherwise emit a second substitute receipt with the same
635
+ // call id, bypassing the per-turn budget the decision already consumed. The
636
+ // entry is dropped through the ordinary abandon path so its usage mark is
637
+ // settled as discarded rather than left to a later real request.
638
+ if (synthesisBlocked(deps, sessionId, entry, turn)) {
639
+ return {
640
+ kind: 'pass',
641
+ sessionId,
642
+ abandon: { entry, clearQueue: true, clearAnchors: true },
643
+ };
644
+ }
645
+ return { kind: 'synthesize', sessionId, entry };
646
+ }
647
+ /**
648
+ * A pass plan that abandons the session's pending entry, when one exists.
649
+ *
650
+ * `discardMark` makes the plan settle the usage mark even when no entry is
651
+ * left; the stopped-store branch needs that because the dispatch side may
652
+ * already have consumed the entry.
653
+ */
654
+ function passPlan(deps, sessionId, abandons, discardMark = false) {
655
+ if (sessionId === undefined)
656
+ return { kind: 'pass', sessionId };
657
+ const entry = peekPending(deps, sessionId);
658
+ if (entry === undefined)
659
+ return { kind: 'pass', sessionId, ...(discardMark ? { discardMark } : {}) };
660
+ return {
661
+ kind: 'pass',
662
+ sessionId,
663
+ abandon: { entry, ...abandons },
664
+ ...(discardMark ? { discardMark } : {}),
665
+ };
666
+ }
667
+ // ---------------------------------------------------------------------------
668
+ // Effects
669
+ // ---------------------------------------------------------------------------
670
+ /**
671
+ * Consume the session's usage mark without reporting a saving.
672
+ *
673
+ * `markSubstituted` has no unmark: a mark left behind by an abandoned entry
674
+ * would make the next real request settle a substitution that never ran
675
+ * (obligation 5). `settle()` here is the discard, not a measurement. The parked
676
+ * plan evidence goes with the mark: nothing will ever write its receipt.
677
+ */
678
+ export function settleDiscarded(deps, sessionId) {
679
+ try {
680
+ sessionUsage(deps, sessionId)?.settle();
681
+ }
682
+ catch {
683
+ // A foreign ledger can only cost a measurement.
684
+ }
685
+ forgetEvidence(deps, sessionId);
686
+ }
687
+ /**
688
+ * Plan/guards evidence parked between synthesis and settlement.
689
+ *
690
+ * The settled receipt is written at the first real request after the
691
+ * synthesized turn, when the queue entry is already gone; the synth-time
692
+ * receipt has it from the entry, this park hands it to the settle. Keyed by
693
+ * `HookDeps` first so two plugin instances in one process cannot read each
694
+ * other's session, and a `WeakMap` lets the whole map die with the assembly.
695
+ */
696
+ const PENDING_EVIDENCE = new WeakMap();
697
+ /** Park the evidence for the session's next settlement, replacing any earlier. */
698
+ function rememberEvidence(deps, sessionId, evidence) {
699
+ let bySession = PENDING_EVIDENCE.get(deps);
700
+ if (bySession === undefined) {
701
+ bySession = new Map();
702
+ PENDING_EVIDENCE.set(deps, bySession);
703
+ }
704
+ bySession.set(sessionId, evidence);
705
+ }
706
+ /** Take (and forget) the evidence one settlement consumes. */
707
+ function takeEvidence(deps, sessionId) {
708
+ const bySession = PENDING_EVIDENCE.get(deps);
709
+ const evidence = bySession?.get(sessionId);
710
+ bySession?.delete(sessionId);
711
+ return evidence;
712
+ }
713
+ /** Drop evidence that no settlement will ever consume. */
714
+ function forgetEvidence(deps, sessionId) {
715
+ PENDING_EVIDENCE.get(deps)?.delete(sessionId);
716
+ }
717
+ /** Record the synthesis mark for the session's pairing. */
718
+ function markSubstitutedFor(deps, sessionId, candidateId) {
719
+ try {
720
+ sessionUsage(deps, sessionId)?.markSubstituted(candidateId);
721
+ }
722
+ catch {
723
+ // A ledger miss costs a measurement, never this turn.
724
+ }
725
+ }
726
+ /** The synth-time receipt: the event, before any measurement exists. */
727
+ async function appendSubstituteReceipt(deps, sessionId, entry) {
728
+ const evidence = entry.evidence;
729
+ await appendReceipt(deps, {
730
+ version: 1,
731
+ ts: new Date().toISOString(),
732
+ sessionId,
733
+ turn: turnNumberOf(entry.turn),
734
+ stepId: 'root',
735
+ kind: 'substitute',
736
+ code: 'substituted',
737
+ tool: entry.name,
738
+ callId: entry.callId,
739
+ candidateId: entry.candidateId,
740
+ // G2: the plan the decision came from and the guards that qualified the
741
+ // candidate, capped by `substitutionEvidence` before they reach the line.
742
+ ...(evidence === undefined ? {} : evidence),
743
+ // The synthesized call has no tool result yet; its name and bound args are
744
+ // the evidence for why this turn asked for it.
745
+ args: entry.args,
746
+ preview: callPreview(entry.name, entry.args),
747
+ // Measured only after the next real request; `'unknown'` never counts.
748
+ saved_input_tokens: 'unknown',
749
+ cache_hit_delta: null,
750
+ output_tokens: 'unknown',
751
+ });
752
+ }
753
+ /** Settle a pending mark at the first after-mark request and report it. */
754
+ async function settlePendingMark(deps, sessionId) {
755
+ const ledger = sessionUsage(deps, sessionId);
756
+ if (ledger === undefined)
757
+ return;
758
+ let candidateId;
759
+ let settled;
760
+ try {
761
+ const pending = ledger.pendingCandidateId();
762
+ if (typeof pending !== 'string' || pending.length === 0)
763
+ return;
764
+ candidateId = pending;
765
+ settled = ledger.settle();
766
+ }
767
+ catch {
768
+ return;
769
+ }
770
+ await appendReceipt(deps, {
771
+ version: 1,
772
+ ts: new Date().toISOString(),
773
+ sessionId,
774
+ turn: clockTurnOf(deps, sessionId) ?? 0,
775
+ stepId: 'root',
776
+ kind: 'substitute-settled',
777
+ code: 'substitute-settled',
778
+ candidateId,
779
+ // G2 applies to the settled line too: the goal and guards are the same
780
+ // evidence the synth-time line carried, parked when that line was written.
781
+ ...(takeEvidence(deps, sessionId) ?? {}),
782
+ saved_input_tokens: settled.saved_input_tokens,
783
+ cache_hit_delta: settled.cache_hit_delta,
784
+ output_tokens: settled.output_tokens,
785
+ });
786
+ }
787
+ /** Map one `usage` chunk onto the ledger's count names (appendix §7). */
788
+ function recordUsage(deps, sessionId, usage) {
789
+ if (usage === undefined || usage === null)
790
+ return;
791
+ const ledger = sessionUsage(deps, sessionId);
792
+ if (ledger === undefined)
793
+ return;
794
+ try {
795
+ ledger.request({
796
+ input: usage.inputTokens,
797
+ cacheRead: usage.cacheReadTokens ?? 0,
798
+ output: usage.outputTokens,
799
+ });
800
+ }
801
+ catch {
802
+ // A foreign ledger can only cost a measurement.
803
+ }
804
+ }
805
+ /**
806
+ * Store the plan a real response carried, or drop the old one when it carried
807
+ * none.
808
+ *
809
+ * The protocol tells the model to omit the block when unsure, so a response
810
+ * that does not contain a valid plan is also the model withdrawing the previous
811
+ * one. Keeping the old plan would let it fire against a much later receipt the
812
+ * model never wrote it for. A malformed block is likewise not a plan.
813
+ */
814
+ function rememberPlan(deps, sessionId, text) {
815
+ if (sessionId === undefined)
816
+ return;
817
+ try {
818
+ const plans = deps.plans;
819
+ if (plans == null || typeof plans.set !== 'function')
820
+ return;
821
+ const parsed = text.length === 0 ? { error: 'no-plan' } : parsePlan(text);
822
+ if ('plan' in parsed)
823
+ plans.set(sessionId, parsed.plan);
824
+ else
825
+ plans.delete(sessionId);
826
+ }
827
+ catch {
828
+ // A plan that cannot be stored only costs a later decision.
829
+ }
830
+ }
831
+ /**
832
+ * Abandon the pending entry: settle the mark, drop what the decision owned and
833
+ * write the reset receipt that explains it.
834
+ */
835
+ async function applyAbandon(deps, sessionId, abandon) {
836
+ settleDiscarded(deps, sessionId);
837
+ if (abandon.clearQueue)
838
+ clearPending(deps, sessionId);
839
+ if (abandon.clearAnchors)
840
+ clearAnchors(deps, sessionId);
841
+ // A plan that produced this abandoned decision must not survive to drive a
842
+ // later receipt, for either reset kind (and for the non-reset abandons too).
843
+ clearPlan(deps, sessionId);
844
+ if (abandon.reset === undefined)
845
+ return;
846
+ await appendReceipt(deps, {
847
+ version: 1,
848
+ ts: new Date().toISOString(),
849
+ sessionId,
850
+ turn: abandon.reset.turn,
851
+ stepId: abandon.reset.stepId,
852
+ kind: 'reset',
853
+ code: abandon.reset.code,
854
+ tool: abandon.entry.name,
855
+ callId: abandon.entry.callId,
856
+ candidateId: abandon.entry.candidateId,
857
+ });
858
+ }
859
+ /**
860
+ * The ordinary turn: observe the real stream.
861
+ *
862
+ * `next()` has already been called by the hook body, so the upstream iterable
863
+ * exists before the generator starts. Usage is mapped and a pending mark is
864
+ * settled at the `usage` chunk (which the host emits before `finish`); text is
865
+ * accumulated for `parsePlan`. Settlement also runs in `finally`: an upstream
866
+ * that throws before the `usage` chunk (a provider 500 mid-stream) or a
867
+ * consumer that cancels the stream still ends the request, and a mark left
868
+ * pending there would pair with the next, unrelated request and report that
869
+ * request's tokens as a saving. An errored stream has no usable sample, so
870
+ * `settle()` reports `'unknown'`. The plan store is still reached only on
871
+ * normal completion, so a partial response never becomes a plan.
872
+ */
873
+ async function* observeBranch(deps, sessionId, upstream) {
874
+ let text = '';
875
+ try {
876
+ for await (const chunk of upstream) {
877
+ if (chunk?.type === 'text-delta' && typeof chunk.text === 'string')
878
+ text += chunk.text;
879
+ if (chunk?.type === 'usage' && sessionId !== undefined) {
880
+ recordUsage(deps, sessionId, chunk.usage);
881
+ await settlePendingMark(deps, sessionId);
882
+ }
883
+ yield chunk;
884
+ }
885
+ }
886
+ finally {
887
+ // The host emits `usage` before `finish`, so this is normally a no-op; a
888
+ // route that omits the chunk still ends the request, and the mark must be
889
+ // consumed there rather than attributed to a later request (`'unknown'`,
890
+ // which status does not count).
891
+ if (sessionId !== undefined)
892
+ await settlePendingMark(deps, sessionId);
893
+ }
894
+ rememberPlan(deps, sessionId, text);
895
+ }
896
+ /**
897
+ * The synthesized turn.
898
+ *
899
+ * The plugin answers instead of the model, so `upstream` is only a fallback:
900
+ * the hook body resolved it synchronously at the waterfall point, before this
901
+ * generator runs, and it stays untouched when the entry is still live. The
902
+ * entry is re-read with `peek` (never `take`) so it survives to
903
+ * `tools/execute`; if it vanished between the synchronous decision and the
904
+ * first generator step, the mark is discarded and the real model answers,
905
+ * because a substitution that cannot be dispatched must not be faked.
906
+ *
907
+ * `upstream` is absent only when the host's `next()` itself threw while the
908
+ * hook body was resolving it; a host that cannot produce an upstream has no
909
+ * fallback to offer, so the vanished entry ends with an empty stream rather
910
+ * than a synthesized call no dispatch can check.
911
+ */
912
+ async function* synthesizeBranch(deps, sessionId, entry, upstream) {
913
+ const current = peekPending(deps, sessionId);
914
+ if (current === undefined || current.callId !== entry.callId) {
915
+ settleDiscarded(deps, sessionId);
916
+ if (upstream !== undefined)
917
+ yield* observeBranch(deps, sessionId, upstream);
918
+ return;
919
+ }
920
+ markSubstitutedFor(deps, sessionId, current.candidateId);
921
+ // Park the plan evidence for the settled line, which runs at the next real
922
+ // request after this entry has left the queue.
923
+ const evidence = current.evidence;
924
+ if (evidence !== undefined)
925
+ rememberEvidence(deps, sessionId, evidence);
926
+ await appendSubstituteReceipt(deps, sessionId, current);
927
+ yield* synthesizeTurn(current);
928
+ }
929
+ // ---------------------------------------------------------------------------
930
+ // The exported hook and session-end cleanup
931
+ // ---------------------------------------------------------------------------
932
+ /**
933
+ * Answer a pass decision: abandon what the decision owned, then observe the
934
+ * real stream.
935
+ *
936
+ * `upstream` is resolved by the hook body at the waterfall point; the generator
937
+ * only delays effects and consumption.
938
+ */
939
+ function observedPass(deps, plan, upstream) {
940
+ return (async function* () {
941
+ if (plan.sessionId !== undefined) {
942
+ // Order matters only for evidence: the discard drops the parked
943
+ // plan/guards, and `applyAbandon` then clears the rest. Both settle
944
+ // calls are idempotent.
945
+ if (plan.discardMark === true)
946
+ settleDiscarded(deps, plan.sessionId);
947
+ if (plan.abandon !== undefined)
948
+ await applyAbandon(deps, plan.sessionId, plan.abandon);
949
+ }
950
+ yield* observeBranch(deps, plan.sessionId, upstream);
951
+ })();
952
+ }
953
+ /**
954
+ * Build the `llm/stream` listener.
955
+ *
956
+ * Returns a **synchronous** function returning an `AsyncIterable`; see the
957
+ * module header for why an `async` function here breaks every request. Any
958
+ * `purpose`-tagged call (selector, compaction, session-title) returns `next()`
959
+ * untouched: never observed, never substituted. Every real request is decided
960
+ * synchronously by {@link resolveStreamPlan} and then answered by a generator.
961
+ *
962
+ * The upstream iterator is resolved **at the waterfall point on every path**,
963
+ * before any generator body runs. The host's terminal is a lazy async iterable
964
+ * (starting it is what calls the model), so resolving it on the synthesis path
965
+ * costs nothing; it is only consumed if the pending entry vanished and the real
966
+ * model has to answer. Resolving it lazily inside the generator would resume a
967
+ * waterfall the host may already have moved past.
968
+ */
969
+ export function streamHook(deps) {
970
+ return (options, next) => {
971
+ // Any purpose-tagged request is auxiliary (appendix §1): the selector, the
972
+ // compaction summarizer, the session-title model. They share the session
973
+ // id but are not conversation steps, so they pass through raw: no
974
+ // substitution, no usage observation, no settlement, no plan rollover.
975
+ if (options?.purpose !== undefined)
976
+ return next();
977
+ const sessionId = sessionIdOf(options);
978
+ if (sessionId !== undefined) {
979
+ const turn = clockTurnOf(deps, sessionId);
980
+ if (turn !== undefined) {
981
+ let rolledOver = false;
982
+ try {
983
+ rolledOver = deps.sessions?.notePlanTurn(sessionId, turn) === true;
984
+ }
985
+ catch {
986
+ rolledOver = false;
987
+ }
988
+ if (rolledOver)
989
+ clearPlan(deps, sessionId);
990
+ }
991
+ }
992
+ let plan;
993
+ try {
994
+ plan = resolveStreamPlan(deps, options);
995
+ }
996
+ catch {
997
+ // A bug in our own decision logic must not take the model request down,
998
+ // but it must still take the ordinary pass path: the decision-time mark
999
+ // has to be discarded here or this real request would settle a
1000
+ // substitution that never ran. Clearing the queue is the same fail-closed
1001
+ // answer — no decision was made.
1002
+ try {
1003
+ plan = passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false }, true);
1004
+ }
1005
+ catch {
1006
+ plan = { kind: 'pass', sessionId, discardMark: true };
1007
+ }
1008
+ }
1009
+ // Resolve the upstream iterator before any branch. The real host's terminal
1010
+ // is an async generator, so this starts no model call; it only fixes which
1011
+ // request the fallbacks observe. A host whose `next()` throws was already
1012
+ // failing on the pass path, so that throw is preserved there; the synthesis
1013
+ // path proceeds without a fallback instead.
1014
+ // Count a synthesis decision before the generator runs: an unconsumed
1015
+ // stream or a vanished entry must still not let the same step be
1016
+ // synthesized twice. This runs before `next()` too, so a host whose
1017
+ // terminal throws cannot reopen the same step.
1018
+ if (plan.kind === 'synthesize') {
1019
+ const turn = clockTurnOf(deps, plan.sessionId) ?? turnNumberOf(plan.entry.turn);
1020
+ recordSynthesis(deps, plan.sessionId, turn, plan.entry.callId);
1021
+ }
1022
+ let upstream;
1023
+ try {
1024
+ upstream = next();
1025
+ }
1026
+ catch (error) {
1027
+ if (plan.kind !== 'synthesize')
1028
+ throw error;
1029
+ return synthesizeBranch(deps, plan.sessionId, plan.entry, undefined);
1030
+ }
1031
+ if (plan.kind === 'synthesize') {
1032
+ return synthesizeBranch(deps, plan.sessionId, plan.entry, upstream);
1033
+ }
1034
+ return observedPass(deps, plan, upstream);
1035
+ };
1036
+ }
1037
+ /**
1038
+ * Drop every per-session trace the plugin keeps for `sessionId`.
1039
+ *
1040
+ * This is the session-end cleanup `src/index.ts` calls from its
1041
+ * `session/disposed` listener: the receipt/dispatch store ships its own
1042
+ * `clear`, but it does not own the queue, the anchors, the plan map or the
1043
+ * per-session runtime, so the caller would otherwise have to know four separate
1044
+ * clears. A pending usage mark is settled first so a mark cannot outlive the
1045
+ * session it belongs to, and the shared-instance loans this session holds are
1046
+ * released so a disposed owner does not refuse every later session forever.
1047
+ */
1048
+ export function clearSession(deps, sessionId) {
1049
+ settleDiscarded(deps, sessionId);
1050
+ clearPending(deps, sessionId);
1051
+ clearAnchors(deps, sessionId);
1052
+ clearPlan(deps, sessionId);
1053
+ forgetSynthesis(deps, sessionId);
1054
+ try {
1055
+ // Projection locators are session-scoped evidence: a disposed session must
1056
+ // not leave its spill paths behind for the next session id to inherit.
1057
+ deps.retrievals?.clear(sessionId);
1058
+ }
1059
+ catch {
1060
+ // Same: each clear is independent.
1061
+ }
1062
+ try {
1063
+ deps.sessionState?.clear(sessionId);
1064
+ }
1065
+ catch {
1066
+ // Same: each clear is independent.
1067
+ }
1068
+ try {
1069
+ deps.sessions?.clear(sessionId);
1070
+ }
1071
+ catch {
1072
+ // Same.
1073
+ }
1074
+ releaseSharedLoans(deps, sessionId);
1075
+ // The rollover path mirrors an accepted dispatch so a late tool result can
1076
+ // still settle a substitution that ran. A disposed session has no late
1077
+ // result coming, so the mirror would otherwise sit in the per-deps map for
1078
+ // the plugin's lifetime — one entry per disposed session.
1079
+ try {
1080
+ deps.clearAcceptedDispatch?.(sessionId);
1081
+ }
1082
+ catch {
1083
+ // A disposal hook that throws must not abort the rest of the teardown.
1084
+ }
1085
+ }
1086
+ //# sourceMappingURL=llm-stream.js.map