dsh-boost 0.1.2 → 0.1.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"llm-stream.js","sourceRoot":"","sources":["../../src/hooks/llm-stream.ts"],"names":[],"mappings":"AA2KA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAA;AAEjE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAGhD,OAAO,EACL,aAAa,EACb,WAAW,EACX,YAAY,EACZ,SAAS,EACT,YAAY,EACZ,WAAW,EACX,WAAW,GACZ,MAAM,oBAAoB,CAAA;AAK3B,uEAAuE;AACvE,MAAM,kBAAkB,GAAG,EAAE,CAAA;AAkB7B;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,cAAc;IACR,SAAS,GAAG,IAAI,GAAG,EAAwB,CAAA;IAC3C,YAAY,CAAQ;IAErC,YAAY,eAAuB,cAAc,CAAC,YAAY;QAC5D,kEAAkE;QAClE,sEAAsE;QACtE,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;YAC/C,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,cAAc,CAAC,YAAY,CAAA;IACjC,CAAC;IAED,iDAAiD;IACjD,QAAQ,CAAC,SAAiB;QACxB,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,KAAK,CAAA;IACpC,CAAC;IAED,uDAAuD;IACvD,SAAS,CAAC,SAAiB;QACzB,OAA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CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAChC,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC7B,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC7B,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC1B,eAAe,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAChC,IAAI,CAAC;QACH,2EAA2E;QAC3E,uEAAuE;QACvE,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,CAAA;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,mCAAmC;IACrC,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,SAAS,CAAC,CAAA;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,mCAAmC;IACrC,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAA;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,QAAQ;IACV,CAAC;IACD,kBAAkB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACnC,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,0DAA0D;IAC1D,IAAI,CAAC;QACH,IAAI,CAAC,qBAAqB,EAAE,CAAC,SAAS,CAAC,CAAA;IACzC,CAAC;IAAC,MAAM,CAAC;QACP,uEAAuE;IACzE,CAAC;AACH,CAAC","sourcesContent":["/**\n * The `llm/stream` hook body: the point where the plugin answers a model\n * request itself instead of calling the provider.\n *\n * ## The synchronous contract\n *\n * The host treats `llm/stream` as a **synchronous waterfall**: `next()` returns\n * an `AsyncIterable<StreamChunk>` and the host does `for await` over whatever\n * the listener returns. An `async` listener would hand the host a\n * `Promise<AsyncIterable>`, every request would fail with a `TypeError`, and the\n * plugin would break the product rather than degrade it (appendix §7). The\n * exported function therefore returns a **generator object synchronously**;\n * every `await` lives inside the generator.\n *\n * ## Rule order (fixed, checks before any side effect)\n *\n * 1. `purpose` set -> raw `next()`. The appendix sets `purpose` **only** for\n * auxiliary calls, and the host issues several on the same session id: the\n * plugin's selector (`boost-selector`), `dsh-compaction-basic`\n * (`compaction`) and the session-title model (`session-title`). None is a\n * conversation step, so all pass through untouched: never substituted,\n * never observed into `usage.request()`, never settling a mark. Observing\n * one would pair a substitution with the summarizer's usage and corrupt\n * `saved_input_tokens` (obligation 7); synthesizing into one would break\n * compaction and write a substitute receipt for a call that never ran.\n * 2. `receipts.stopped()` -> pass through, fail-closed. A store that cannot\n * record evidence cannot justify a substitution.\n * 3. Visibility. `resolveSession(sessionId)` returning `undefined` means the\n * session is not substitutable: pass through and clear that session's queue\n * (the decision cannot be honoured any more).\n * 4. No pending entry -> pass through. This is the ordinary turn.\n * 5. Anchors readable and intact. A decision whose anchors were never written\n * (the commit's `set` failed), whose store holds no record, or whose store\n * throws cannot be verified at all; all three fail closed through the reset\n * path (row 28). With a record present, detection runs against\n * `options.messages` (obligation 6). A pruned carrier yields\n * `pruned-reset`, a receipt that is no longer present yields\n * `compaction-reset`; either clears queue + anchors and passes through. A\n * body that only shares the anchor's head and tail is **not** a carrier: it\n * must also carry the pruner marker or our projection's head line, or a\n * middle edit would pass for the original text.\n * 6. Turn validity. The queue is cleared on the **new turn's first\n * `post-execute`**, which happens after the new turn's first `llm/stream`.\n * An entry whose `turn` differs from the session clock's turn belongs to a\n * previous turn: synthesizing it would answer the new turn with an old\n * decision, and its `callId` would even match at dispatch and be accepted.\n * Compare, clear and pass through (obligation 4). This runs after the anchor\n * read: an entry that is dead by identity but also lost its evidence still\n * reports the reset, while one with intact anchors is dropped silently.\n * 7. Step still payable. `post-execute` already took the entry's step, but the\n * same decision can be replayed (a retried request, a re-enqueue at one\n * step). The per-turn synthesis tally and the budget's paid-step count are\n * re-checked immediately before synthesizing; an entry whose step can no\n * longer be honoured is dropped through the abandon path (settling its mark\n * as discarded) instead of emitting a duplicate `callId`.\n * 8. Synthesize: `markSubstituted` -> `{kind:'substitute'}` receipt ->\n * `peek` (never `take`, obligation 3) -> `yield* synthesizeTurn(entry)`.\n * The upstream iterator is resolved synchronously at the waterfall point on\n * every path, but the synthesis branch does not consume it. The entry must\n * survive to `tools/execute`, which is the consumer that enforces the\n * tamper check.\n *\n * The hook never calls `budget.take()`: Task 23b already took the step at\n * `tools/post-execute`, and a second take would charge 2 of 8 per substitution\n * (obligation 2). It only reads `count()` to verify that a paid step backs the\n * synthesis.\n *\n * ## Per-session state (obligation 1)\n *\n * `HookDeps` also carries single `clock`/`budget`/`usage` instances, and a\n * shared instance is cross-session contamination: another session's\n * `agent/request` sets this session's `callId` turn/step, a shared\n * `StepBudget(1)` starves one session, and a shared usage ledger pairs one\n * session's substitution with another session's request. `SessionRuntime`\n * (exported here) keys all three by `sessionId`; `HookDeps.sessions` accepts it,\n * and when present it is authoritative for both this hook and Task 23b's\n * helpers. The shipped wiring lives in `wireSessionEvents` (`src/index.ts`)\n * and is deliberately **two** clock listeners, not one:\n *\n * ```ts\n * const sessions = new SessionRuntime(cfg.stepsPerTurn)\n * registerHooks(ctx, { ...deps, sessions })\n *\n * // agent/pre-step: the non-deprecated clock seam. It fires once per proposed\n * // step AFTER prompt assembly (the host assembles at\n * // `@deepseek-ai/dsh-agent-loop/lib/index.js:692`, then dispatches pre-step\n * // at `:695`), and copies the host turn/step.\n * ctx.on('agent/pre-step', (payload, next) => {\n * sessions.onModelRequest(sessionId, payload.turn, payload.step)\n * horizon.observe(sessionId, payload.turn, payload.step)\n * return next()\n * })\n *\n * // agent/request: deprecated, kept for what the request waterfall alone\n * // yields: the resolved provider/model the selector inherits (after next()),\n * // the async visibility warm, and a clock fallback.\n * ctx.on('agent/request', async (payload, next) => {\n * sessions.onModelRequest(sessionId, payload.turn, payload.step)\n * await warmVisibility(scope, registry, payload.agent, sessionId, workspaces)\n * const config = await next()\n * rememberRoute(routes, sessionId, config)\n * return config\n * })\n *\n * ctx.on('session/disposed', (session) => clearSession(deps, sessionId))\n * ```\n *\n * The split is intentional: `agent/pre-step` is the seam the host documents for\n * turn/step, while the selector's effective route is only available from the\n * request waterfall's resolved config. Both listeners copy the clock so a host\n * that drops the deprecated event still advances turns. Both record the route:\n * `agent/pre-step` from the captured `modelSelection` (the primary source since\n * row 37), and `agent/request` from the resolved config as the fallback for\n * hosts that only populate it there. The visibility warm is owned by the\n * `system-prompt/assemble` listener (also in `wireSessionEvents`), which the\n * host runs **before** `agent/pre-step`; `agent/request`'s call is only a\n * fallback. This hook sees a warm judgement only because of that assemble\n * listener — a cold-cache read here would reintroduce the D4 prompt\n * invalidation, so do not move the warm back onto the pre-step seam.\n *\n * `onModelRequest` copies the host turn/step (never a plugin count) and resets\n * that session's budget only when its turn changes. `notePlanTurn` is the\n * matching rollover for the plan store: the first real request of a new turn\n * drops the previous turn's plan before a new one can be parsed, so a stale\n * plan cannot drive a substitution in the new turn. `clearSession(deps, id)`\n * is the session-end cleanup: queue, anchors, plans, receipt state, the usage\n * mark, the runtime entry and any shared-instance loan it holds, all dropped\n * together (obligation 10). No map is ever handed out.\n *\n * ## Settlement (obligation 11)\n *\n * The first real request after a synthesized turn carries a `usage` chunk. The\n * pass-through branch maps it to `UsageLedger.request()` and, if a mark is\n * pending, calls `settle()` and appends `{kind:'substitute-settled'}` with the\n * measured counts (`'unknown'` stays `'unknown'`; it is never interpolated).\n * When a marked entry is abandoned (turn rollover, reset, stopped receipts,\n * lost visibility, an unpayable or already-synthesized step, a vanished queue\n * entry) the mark is settled and discarded **without** a settlement receipt: no\n * substitution ran, so no saving exists to report (obligation 5).\n *\n * ## Anchor detection and our own projection\n *\n * The host pruner rewrites an oversized receipt in place to\n * `head + PRUNE_MARKER + tail`, and apply-mode projection composes\n * `head line + head + spill footer + tail`. Both preserve the receipt's head\n * and tail, so \"the anchor text is not present verbatim\" alone would classify\n * our own projection as compaction and disable substitution whenever projection\n * is on. `carriesAnchor` therefore accepts the exact text, or a body holding\n * the anchor's head *and* tail probes **plus** one of the two rewrites' own\n * evidence: the prune marker (which then decides `pruned-reset`) or the\n * projection head line, whose `output N chars; showing first H and last T`\n * counts must name this anchor's length and windows. A full receipt with the\n * same probes but a different middle — a file edited and re-read — carries\n * neither, so it is a lost anchor (`compaction-reset`) rather than a\n * substitution against content the model no longer holds.\n *\n * Probes are measured in code points (a UTF-16 slice can split a surrogate\n * pair) and clamped to the smallest configured projection window, because\n * `resolveConfig` accepts `headChars`/`tailChars` below the probe length and a\n * window shorter than the probe would make our own projection look like\n * compaction.\n *\n * Everything here is contained: a foreign store, queue, ledger, clock or\n * resolver can degrade the decision, never throw out of the model request.\n * `resolveStreamPlan` is synchronous and writes no receipt; its only state is\n * the per-turn synthesis tally, and every receipt/queue effect (writes, clears,\n * settlement) happens inside a generator after the decision.\n *\n * @module dsh-boost/hooks/llm-stream\n */\nimport type { GenerateOptions, StreamChunk, TokenUsage } from '@deepseek-ai/dsh-llm'\nimport { StepBudget } from '../admission/ledger.js'\nimport { UsageLedger } from '../admission/usage.js'\nimport { DEFAULT_CONFIG } from '../config.js'\nimport { looksPruned, PRUNE_MARKER } from '../gate/invalidate.js'\nimport type { ReceiptAnchors } from '../gate/invalidate.js'\nimport { parsePlan } from '../gate/plan.js'\nimport { TurnClock } from './clock.js'\nimport { synthesizeTurn } from './synthesize.js'\nimport type { PendingEntry } from './pending.js'\nimport type { AuditedPendingEntry, HookDeps, SubstitutionEvidence } from './post-execute.js'\nimport {\n appendReceipt,\n callPreview,\n clearAnchors,\n clearPlan,\n clearPending,\n clockTurnOf,\n peekPending,\n} from './session-state.js'\n\n/** Which external rewrite invalidated a decision. */\ntype ResetCode = 'pruned-reset' | 'compaction-reset'\n\n/** Default head/tail probe length for a receipt rewritten in place. */\nconst ANCHOR_PROBE_CHARS = 32\n\n// ---------------------------------------------------------------------------\n// Per-session runtime (obligation 1)\n// ---------------------------------------------------------------------------\n\n/** The three per-session pieces that must never be shared across sessions. */\ninterface SessionEntry {\n /** Host turn/step for this session. */\n clock: TurnClock\n /** This session's per-turn substitution budget. */\n budget: StepBudget\n /** This session's request pairing. */\n usage: UsageLedger\n /** The host turn whose plan store this session has been reconciled with. */\n planTurn?: number\n}\n\n/**\n * Per-session clock, budget and usage ledger.\n *\n * The host numbers turns and steps per session; a single instance therefore\n * lets one session's `agent/request` stamp another session's derived `callId`,\n * lets one session's `StepBudget(1)` starve the next, and pairs one session's\n * substitution with another session's request. The runtime keys all three by\n * `sessionId` and is the only place a per-session primitive is created.\n *\n * The map is private: callers get the objects, never the map, and\n * {@link SessionRuntime.clear} is the only way an entry leaves. `onModelRequest`\n * is driven by Task 23c-2 from the host's `agent/request` payload; this module\n * cannot see that event itself. A new turn resets that session's budget (the\n * budget is per-turn, not per-lifetime); a non-finite or backwards turn is\n * ignored by `TurnClock` and therefore resets nothing.\n */\nexport class SessionRuntime {\n private readonly bySession = new Map<string, SessionEntry>()\n private readonly stepsPerTurn: number\n\n constructor(stepsPerTurn: number = DEFAULT_CONFIG.stepsPerTurn) {\n // `StepBudget` already treats a non-positive max as empty; only a\n // non-finite value (which no resolved config can produce) falls back.\n this.stepsPerTurn = Number.isFinite(stepsPerTurn)\n ? stepsPerTurn\n : DEFAULT_CONFIG.stepsPerTurn\n }\n\n /** The session's clock, created on first use. */\n clockFor(sessionId: string): TurnClock {\n return this.entry(sessionId).clock\n }\n\n /** The session's turn budget, created on first use. */\n budgetFor(sessionId: string): StepBudget {\n return this.entry(sessionId).budget\n }\n\n /** The session's usage ledger, created on first use. */\n usageFor(sessionId: string): UsageLedger {\n return this.entry(sessionId).usage\n }\n\n /**\n * Record one host request for a session.\n *\n * `turn`/`step` are the host's numbers, copied through `TurnClock` (which\n * ignores non-finite and backwards turns). A turn change is the only thing\n * that resets the budget: a second request in one turn must keep the spend.\n */\n onModelRequest(sessionId: string, turn: number, step?: number): void {\n const entry = this.entry(sessionId)\n const before = entry.clock.turn()\n entry.clock.onModelRequest(turn, step)\n if (entry.clock.turn() !== before) entry.budget.reset()\n }\n\n /**\n * Reconcile this session's plan store with `turn`; `true` on a turn change.\n *\n * The plan lives in `HookDeps.plans` and is keyed by session only, so\n * without this note a turn that emits no new plan keeps the previous turn's\n * one, and its remaining steps can still drive a substitution. The stream\n * hook calls this once per **real** request (never for an auxiliary\n * `purpose`, which is not a conversation step) and clears the plan map when\n * it returns true, before that request's response could write a new plan.\n * The first call reports true so a seeded map cannot outlive its first\n * request; `clearSession` drops the note with the rest of the entry.\n */\n notePlanTurn(sessionId: string, turn: number): boolean {\n const entry = this.entry(sessionId)\n if (entry.planTurn === turn) return false\n entry.planTurn = turn\n return true\n }\n\n /** Drop everything this runtime holds for one session. */\n clear(sessionId: string): void {\n this.bySession.delete(sessionId)\n }\n\n /** Number of sessions with state (not the number ever seen). */\n size(): number {\n return this.bySession.size\n }\n\n private entry(sessionId: string): SessionEntry {\n const existing = this.bySession.get(sessionId)\n if (existing !== undefined) return existing\n const entry: SessionEntry = {\n clock: new TurnClock(),\n budget: new StepBudget(this.stepsPerTurn),\n usage: new UsageLedger(),\n }\n this.bySession.set(sessionId, entry)\n return entry\n }\n}\n\n// ---------------------------------------------------------------------------\n// Defensive readers: every foreign call is wrapped\n// ---------------------------------------------------------------------------\n\n/** The request's session id, or `undefined` when the host supplied none. */\nfunction sessionIdOf(options: GenerateOptions | undefined): string | undefined {\n const id = options?.sessionId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n}\n\n/**\n * Which session has been lent each shared fallback instance.\n *\n * `apply` always passes `sessions`, so this exists for embedders and tests that\n * hand in one `clock`/`budget`/`usage` instead. Those three carry per-session\n * state — a turn's step counter, a pending usage mark — so lending one to a\n * second session attributes B's tokens to A's candidate. That surfaces as a\n * saving that never happened, which is the one error this plugin must not\n * produce. Ownership is keyed by the **instance**, not by the deps object: two\n * assemblies that share the same three objects (the pattern the fallback exists\n * for) must agree on the one session they serve, or each claims its own loan\n * and both borrow. The first session to arrive keeps the loan; every other\n * session gets `undefined`, which each caller already reads as \"no\n * substitution\" (fail closed), and the warning is emitted once per deps object\n * rather than per call. `clearSession` drops the loans its session holds, so a\n * disposed owner does not lock the instance for the rest of the process.\n */\nconst fallbackLoans = new WeakMap<object, { sessionId: string }>()\n\n/** Deps objects already warned about a refused loan (once each, not per call). */\nconst fallbackWarned = new WeakSet<object>()\n\n/** Whether the shared fallback instance may serve this session. */\nfunction mayBorrowShared(instance: object, deps: HookDeps, sessionId: string): boolean {\n const held = fallbackLoans.get(instance)\n if (held === undefined) {\n fallbackLoans.set(instance, { sessionId })\n return true\n }\n if (held.sessionId === sessionId) return true\n if (!fallbackWarned.has(deps)) {\n fallbackWarned.add(deps)\n try {\n deps.logger?.warn(\n `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`,\n )\n } catch {\n // A logger that throws must not turn a measurement guard into a failure.\n }\n }\n return false\n}\n\n/** Release the shared-instance loans the disposing session holds. */\nfunction releaseSharedLoans(deps: HookDeps, sessionId: string): void {\n for (const instance of [deps.clock, deps.budget, deps.usage]) {\n if (instance === undefined) continue\n if (fallbackLoans.get(instance)?.sessionId === sessionId) fallbackLoans.delete(instance)\n }\n}\n\n/**\n * The session's clock: the per-session runtime when wired, the shared instance\n * otherwise — but only for the one session that instance belongs to.\n *\n * Exported because `tools/post-execute` must resolve the *same* clock for the\n * turn/step it stamps into a `callId`; two copies of this precedence rule could\n * drift and let the decision and the stream hook disagree about one session.\n */\nexport function sessionClock(deps: HookDeps, sessionId: string): TurnClock | undefined {\n try {\n const owned = deps.sessions?.clockFor(sessionId)\n if (owned !== undefined) return owned\n } catch {\n // Fall through to the shared instance, subject to the ownership rule.\n }\n return deps.clock !== undefined && mayBorrowShared(deps.clock, deps, sessionId)\n ? deps.clock\n : undefined\n}\n\n/** The session's turn budget; the same precedence as {@link sessionClock}. */\nexport function sessionBudget(deps: HookDeps, sessionId: string): StepBudget | undefined {\n try {\n const owned = deps.sessions?.budgetFor(sessionId)\n if (owned !== undefined) return owned\n } catch {\n // Fall through to the shared instance, subject to the ownership rule.\n }\n return deps.budget !== undefined && mayBorrowShared(deps.budget, deps, sessionId)\n ? deps.budget\n : undefined\n}\n\n/**\n * Whether a substitution budget is wired at all.\n *\n * `undefined` from {@link sessionBudget} has two meanings and callers must not\n * conflate them (row 21): with neither `deps.budget` nor a per-session runtime,\n * the embedder never asked for a cap, so the substitution is unconstrained; a\n * wired budget that this session may not borrow is the opposite — the shared\n * instance belongs to another session and the step cannot be paid. Treating the\n * refusal as \"no cap\" let an unbudgeted substitution through without ever\n * incrementing the live budget.\n */\nexport function budgetWired(deps: HookDeps): boolean {\n return deps.budget !== undefined || deps.sessions !== undefined\n}\n\n/** The session's usage ledger; the same precedence as {@link sessionClock}. */\nexport function sessionUsage(deps: HookDeps, sessionId: string): UsageLedger | undefined {\n try {\n const owned = deps.sessions?.usageFor(sessionId)\n if (owned !== undefined) return owned\n } catch {\n // Fall through to the shared instance, subject to the ownership rule.\n }\n return deps.usage !== undefined && mayBorrowShared(deps.usage, deps, sessionId)\n ? deps.usage\n : undefined\n}\n\n/** What the session's anchor store answered. */\ntype AnchorRead =\n | { kind: 'record'; anchors: ReceiptAnchors }\n /** The store answered, but holds no record for a session with a live decision. */\n | { kind: 'cold' }\n /** The store is absent or its read threw: nothing can be verified. */\n | { kind: 'unreadable' }\n\n/**\n * The session's anchors, distinguishing a record from a cold store.\n *\n * A substitution is only legitimate against the receipt the model still holds,\n * so every missing answer is a lost anchor (row 28). `post-execute` writes\n * anchors with every commit, so a live queue entry with no record means that\n * write failed; synthesizing then would skip the only verification the design\n * has. A throwing read is equally unverifiable. Both fail closed through the\n * ordinary reset path instead of substituting on unseen evidence.\n */\nfunction anchorsOf(deps: HookDeps, sessionId: string): AnchorRead {\n const store = deps.anchors\n if (store == null || typeof store.get !== 'function') return { kind: 'unreadable' }\n try {\n const anchors = store.get(sessionId)\n return anchors == null ? { kind: 'cold' } : { kind: 'record', anchors }\n } catch {\n return { kind: 'unreadable' }\n }\n}\n\n/**\n * Whether the receipt store has stopped writing, fail-closed.\n *\n * A missing `stopped` (a partial store in a test or an older host) is \"not\n * stopped\", so the ordinary path is unchanged. A store that *throws* cannot\n * record evidence, which is exactly what stopped means.\n */\nexport function receiptsStopped(deps: HookDeps): boolean {\n try {\n const store = deps.receipts\n if (store == null || typeof store.stopped !== 'function') return false\n return store.stopped() === true\n } catch {\n return true\n }\n}\n\n/**\n * Whether the session resolves to a workspace.\n *\n * The stream hook's rule only needs the resolver: a session that does not\n * resolve has no substitute-able workspace, so the decision cannot be honoured.\n * The live scope-document check lives in `tools/post-execute`, which owns the\n * async document read; `resolveSession` is synchronous by contract.\n */\nfunction visibleSession(deps: HookDeps, sessionId: string): boolean {\n try {\n const resolve = deps.resolveSession\n if (typeof resolve !== 'function') return false\n return typeof resolve(sessionId) === 'string'\n } catch {\n return false\n }\n}\n\n/** The host turn and the entry's turn are the same, number or stringified number. */\nfunction sameTurn(entryTurn: number | string, clockTurn: number): boolean {\n return String(entryTurn) === String(clockTurn)\n}\n\n/** A receipt's `turn` field is a number; entry turns may already be strings. */\nfunction turnNumberOf(turn: number | string): number {\n if (typeof turn === 'number' && Number.isFinite(turn)) return turn\n const parsed = Number(turn)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\n// ---------------------------------------------------------------------------\n// Anchor detection against the outgoing messages (obligation 6)\n// ---------------------------------------------------------------------------\n\n/**\n * Every text-block body the model will see in this request.\n *\n * `RequestMessage.content` is an array of blocks; only `text` blocks carry\n * receipt bodies. Blocks are kept separate so a mixed message cannot make two\n * unrelated texts look like one receipt. A malformed message is skipped, never\n * a throw: `options.messages` is host-shaped data.\n */\nfunction messageTexts(messages: unknown): string[] {\n if (!Array.isArray(messages)) return []\n const bodies: string[] = []\n for (const message of messages) {\n const content = (message as { content?: unknown } | null | undefined)?.content\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (typeof block !== 'object' || block === null) continue\n const { type, text } = block as { type?: unknown; text?: unknown }\n if (type === 'text' && typeof text === 'string') bodies.push(text)\n }\n }\n return bodies\n}\n\n/**\n * The head/tail probe windows, clamped to the projection's own windows.\n *\n * Our projection keeps `headChars`/`tailChars` code points of the receipt, so\n * a probe longer than a configured window can never match a projected body and\n * would report `compaction-reset`. `resolveConfig` accepts any finite value\n * (including 0), so the window is the smallest one any family configures,\n * capped at {@link ANCHOR_PROBE_CHARS}; a 0 window drops that side of the\n * probe and leaves only the other. With the design defaults this is 32/32.\n */\nfunction anchorProbe(deps: HookDeps): { head: number; tail: number } {\n let head = ANCHOR_PROBE_CHARS\n let tail = ANCHOR_PROBE_CHARS\n try {\n const projection: unknown = deps.config?.projection\n if (typeof projection !== 'object' || projection === null) return { head, tail }\n for (const raw of Object.values(projection)) {\n const params = raw as { headChars?: unknown; tailChars?: unknown } | null\n if (typeof params?.headChars === 'number' && Number.isFinite(params.headChars)) {\n head = Math.min(head, Math.max(0, params.headChars))\n }\n if (typeof params?.tailChars === 'number' && Number.isFinite(params.tailChars)) {\n tail = Math.min(tail, Math.max(0, params.tailChars))\n }\n }\n } catch {\n return { head: ANCHOR_PROBE_CHARS, tail: ANCHOR_PROBE_CHARS }\n }\n return { head, tail }\n}\n\n/**\n * The head line our own projection writes: `[output N chars; showing first H\n * and last T]`. The counts use `toLocaleString('en-US')`, hence the commas.\n */\nconst PROJECTION_HEADER = /^\\[output ([\\d,]+) chars; showing first ([\\d,]+) and last ([\\d,]+)\\]$/\n\n/** One `en-US`-formatted count from a projection head line. */\nfunction headerCount(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined\n const value = Number(raw.replaceAll(',', ''))\n return Number.isSafeInteger(value) ? value : undefined\n}\n\n/**\n * Whether `body` is our own projection of `anchor`.\n *\n * A projected receipt is `head line + head + spill footer + tail`. The head\n * line names the anchor's total code points and both window sizes, and the two\n * windows are the anchor's own first/last code points. A full receipt that\n * merely shares the anchor's head and tail cannot produce that line, so this\n * closes the probe collision without reading the middle (which the projection\n * removed) and without a new stored field. Old anchors that cannot be verified\n * this way simply do not match, which fails closed.\n */\nfunction ownProjectionCarries(body: string, anchor: string): boolean {\n const newline = body.indexOf('\\n')\n if (newline === -1) return false\n const match = PROJECTION_HEADER.exec(body.slice(0, newline))\n if (match === null) return false\n const output = headerCount(match[1])\n const headLen = headerCount(match[2])\n const tailLen = headerCount(match[3])\n if (output === undefined || headLen === undefined || tailLen === undefined) return false\n if (headLen <= 0 && tailLen <= 0) return false\n const points = Array.from(anchor)\n if (output !== points.length) return false\n if (headLen + tailLen >= points.length) return false\n const head = headLen > 0 ? points.slice(0, headLen).join('') : ''\n const tail = tailLen > 0 ? points.slice(-tailLen).join('') : ''\n return body.startsWith(`${match[0]}\\n${head}`) && (tailLen === 0 || body.endsWith(tail))\n}\n\n/**\n * Whether `body` is the anchor rewritten **by the host pruner**, and nothing\n * else.\n *\n * `looksPruned` alone is not identity: any body that embeds the anchor's pruned\n * text — a `read` of a session log, the case `invalidate` documents as\n * occurring — carries the marker too, so a receipt that was compacted away\n * could be declared \"still carried\" and a decision would survive on evidence\n * the model no longer holds.\n *\n * The pruner replaces the middle with a single marker and keeps a head and a\n * tail, so a genuine carrier is `head + marker + tail` with nothing before the\n * head and nothing after the tail. Requiring the carrier to *start* with the\n * anchor's first `head` code points and *end* with its last `tail` ones — the\n * same windows `ownProjectionCarries` derives for our own rewrite — rejects the\n * wrapper: its head is the wrapper's opening line, not the anchor's.\n */\nfunction prunedCarries(body: string, anchor: string): boolean {\n const marker = body.indexOf(PRUNE_MARKER)\n if (marker === -1) return false\n // Exactly one marker: two would mean this is not one pruned receipt.\n if (body.indexOf(PRUNE_MARKER, marker + PRUNE_MARKER.length) !== -1) return false\n const head = body.slice(0, marker)\n const tail = body.slice(marker + PRUNE_MARKER.length)\n if (head.length === 0 || tail.length === 0) return false\n const points = Array.from(anchor)\n const headPoints = Array.from(head)\n const tailPoints = Array.from(tail)\n if (headPoints.length + tailPoints.length >= points.length) return false\n return (\n points.slice(0, headPoints.length).join('') === head &&\n points.slice(-tailPoints.length).join('') === tail\n )\n}\n\n/**\n * Whether `body` still carries `anchor`, verbatim or as a verified in-place\n * rewrite.\n *\n * The host pruner replaces the middle of an oversized receipt with\n * `PRUNE_MARKER` while preserving a head and a tail; apply-mode projection\n * composes head line + head + spill footer + tail. Both keep the anchor's\n * beginning and end, so a body holding both probes *and* the rewrite's own\n * evidence is the same receipt rewritten in place.\n *\n * Sharing the two probes alone is not identity: a file edited in the middle and\n * re-read produces a full receipt with the same 32-character head and tail but\n * a different body. Accepting it would substitute against content the model no\n * longer holds, so a probe match must be accompanied by the pruner marker or\n * our projection's head line. Anything else is a lost anchor (fail closed).\n *\n * Probes are sliced by **code point**, exactly like `truncate`: a UTF-16 slice\n * can end on half a surrogate pair, and a lone surrogate is not a substring a\n * correctly projected body has to contain. Short anchors whose two windows\n * would cover the whole text get no probe treatment: at that size the exact\n * text either is present or the receipt is gone.\n */\nfunction carriesAnchor(\n body: string,\n anchor: string,\n probe: { head: number; tail: number },\n): boolean {\n if (body.includes(anchor)) return true\n const points = Array.from(anchor)\n const headLen = Math.min(probe.head, points.length)\n const tailLen = Math.min(probe.tail, points.length)\n if (headLen === 0 && tailLen === 0) return false\n if (points.length <= headLen + tailLen) return false\n const head = headLen > 0 ? points.slice(0, headLen).join('') : ''\n const tail = tailLen > 0 ? points.slice(-tailLen).join('') : ''\n const start = headLen > 0 ? body.indexOf(head) : 0\n if (headLen > 0 && start === -1) return false\n if (tailLen > 0 && body.indexOf(tail, start + headLen) === -1) return false\n return prunedCarries(body, anchor) || ownProjectionCarries(body, anchor)\n}\n\n/**\n * Why the decision's anchored receipts are no longer trustworthy, if they are.\n *\n * Marker precedence matches `invalidate`: any carried body that contains the\n * pruner literal means `pruned-reset`, because the pruner is the common case\n * and it leaves the receipt in place. Only when no anchor was pruned does a\n * missing carrier mean `compaction-reset` (the history was replaced by a\n * summary).\n *\n * A missing record, a record with no entries and a record whose shape cannot be\n * read are all unverifiable and therefore `compaction-reset` (row 28): the\n * commit that parked the decision writes anchors, so their absence is a failed\n * write, not a reason to substitute with zero verification. An empty anchor\n * string is a real value the check skips; `invalidate` treats an empty anchor\n * as a real value, and the stream hook has no receipt body to compare it with.\n */\nfunction anchorResetOf(\n anchors: ReceiptAnchors | undefined,\n messages: unknown,\n probe: { head: number; tail: number },\n): ResetCode | undefined {\n if (anchors == null) return 'compaction-reset'\n let record: unknown\n try {\n record = anchors.anchors\n } catch {\n return 'compaction-reset'\n }\n if (typeof record !== 'object' || record === null) return 'compaction-reset'\n\n const values = Object.values(record as Record<string, unknown>)\n if (values.length === 0) return 'compaction-reset'\n const texts = values.filter((text): text is string => typeof text === 'string' && text.length > 0)\n if (texts.length === 0) {\n // An empty anchor is a real value the check skips (it cannot be located in\n // any message). Any other unverifiable shape — an object from an older or\n // foreign anchor store — must fail closed instead: treating it as \"no\n // anchors\" would substitute on evidence this code cannot read.\n return values.every((value) => value === '') ? undefined : 'compaction-reset'\n }\n\n const bodies = messageTexts(messages)\n let compacted = false\n for (const anchor of texts) {\n if (looksPruned(anchor)) return 'pruned-reset'\n const carriers = bodies.filter((body) => carriesAnchor(body, anchor, probe))\n if (carriers.length === 0) {\n compacted = true\n continue\n }\n if (carriers.some((body) => looksPruned(body))) return 'pruned-reset'\n }\n return compacted ? 'compaction-reset' : undefined\n}\n\n/** The anchored step id a reset receipt names, never throwing on a foreign shape. */\nfunction anchorStepIdOf(anchors: ReceiptAnchors): string {\n try {\n return typeof anchors.stepId === 'string' ? anchors.stepId : 'root'\n } catch {\n return 'root'\n }\n}\n\n// ---------------------------------------------------------------------------\n// The synchronous decision\n// ---------------------------------------------------------------------------\n\n/** A decision to refuse the pending entry before it is synthesized. */\ninterface AbandonPlan {\n /** The entry this request refuses to synthesize. */\n entry: PendingEntry\n /** Drop the session's queue entry (turn rollover, reset, invisible scope). */\n clearQueue: boolean\n /** Drop the session's anchors (only a reset invalidates the evidence). */\n clearAnchors: boolean\n /** Reset receipt to write, when the anchored evidence was invalidated. */\n reset?: { code: ResetCode; stepId: string; turn: number }\n}\n\n/** What one request is going to do, decided synchronously. */\ntype StreamPlan =\n | {\n kind: 'pass'\n sessionId: string | undefined\n abandon?: AbandonPlan\n /**\n * Discard the session's decision-time usage mark even when no queue entry\n * is left to abandon. A stopped store passes every request through, so\n * the decision will never be synthesized and its mark must not settle a\n * later real request as if it had run.\n */\n discardMark?: boolean\n }\n | { kind: 'synthesize'; sessionId: string; entry: PendingEntry }\n\n/**\n * How many synthesized turns this session has already emitted in one turn.\n *\n * `post-execute` takes exactly one step per queue entry, so the budget's\n * `count()` is the number of steps paid for in the turn; this tally is how many\n * of them have been spent on synthesis. A second synthesis of one entry would\n * spend a step the budget never granted. The call ids are kept too: the\n * deterministic `callIdFor` makes a re-enqueued decision at the same\n * turn/step/candidate reuse one id, and the host would persist two `tool_use`\n * blocks with it.\n */\ninterface SynthesisTally {\n /** Host turn this tally belongs to. */\n turn: number\n /** Synthesized turns emitted in `turn`. */\n count: number\n /** Call ids already synthesized in `turn`. */\n callIds: Set<string>\n}\n\n/**\n * Per-session synthesis history, keyed by `HookDeps` first so two plugin\n * instances in one process cannot read each other's session. It holds one turn\n * per session and dies with the assembly; `clearSession` drops the session.\n */\nconst SYNTHESIS_TALLY = new WeakMap<HookDeps, Map<string, SynthesisTally>>()\n\n/** The session's synthesis tally, if this turn has one. */\nfunction synthesisTallyOf(deps: HookDeps, sessionId: string): SynthesisTally | undefined {\n try {\n return SYNTHESIS_TALLY.get(deps)?.get(sessionId)\n } catch {\n return undefined\n }\n}\n\n/** Count one synthesized turn, starting a new tally when the turn changed. */\nfunction recordSynthesis(deps: HookDeps, sessionId: string, turn: number, callId: string): void {\n try {\n let bySession = SYNTHESIS_TALLY.get(deps)\n if (bySession === undefined) {\n bySession = new Map()\n SYNTHESIS_TALLY.set(deps, bySession)\n }\n let tally = bySession.get(sessionId)\n if (tally === undefined || tally.turn !== turn) {\n tally = { turn, count: 0, callIds: new Set() }\n bySession.set(sessionId, tally)\n }\n tally.count += 1\n tally.callIds.add(callId)\n } catch {\n // A tally miss costs a duplicate guard, never this request.\n }\n}\n\n/** Drop one session's synthesis history at session end. */\nfunction forgetSynthesis(deps: HookDeps, sessionId: string): void {\n try {\n SYNTHESIS_TALLY.get(deps)?.delete(sessionId)\n } catch {\n // Same: the tally is a guard, not a precondition.\n }\n}\n\n/**\n * Whether the entry's step can no longer be honoured.\n *\n * Two independent facts make a still-live entry unhonourable: its deterministic\n * call id was already synthesized in this turn (a retry or a re-enqueue at one\n * step), or the turn's paid steps are already used up by earlier syntheses.\n * A budget that reports no spend at all is a fixture/legacy shape rather than\n * proof of a step; the call-id half still applies there.\n */\nfunction synthesisBlocked(\n deps: HookDeps,\n sessionId: string,\n entry: PendingEntry,\n turn: number,\n): boolean {\n const tally = synthesisTallyOf(deps, sessionId)\n const current = tally !== undefined && sameTurn(tally.turn, turn) ? tally : undefined\n if (current !== undefined && current.callIds.has(entry.callId)) return true\n const budget = sessionBudget(deps, sessionId)\n // Row 21: a wired budget that was not lent to this session is unpayable, not\n // \"no cap\". Only a completely unwired budget leaves the step unconstrained.\n if (budget === undefined) return budgetWired(deps)\n let spent: number\n try {\n spent = budget.count()\n } catch {\n return false\n }\n if (!Number.isFinite(spent) || spent <= 0) return false\n return (current?.count ?? 0) >= spent\n}\n\n/**\n * The rule order as pure, synchronous decision logic.\n *\n * Nothing here writes a receipt or takes a step: every check completes before\n * the first effect. `post-execute` already took the budget at the decision\n * point (obligation 2), so this function never touches the budget.\n */\nfunction resolveStreamPlan(\n deps: HookDeps,\n options: GenerateOptions | undefined,\n): StreamPlan {\n const sessionId = sessionIdOf(options)\n\n // The selector guard is the first rule and lives in `streamHook`, which\n // returns `next()` before this function runs: a selector request must not\n // even be observed, so it cannot become a plan.\n\n if (receiptsStopped(deps)) {\n // Fail-closed: the decision cannot be recorded, so it will never be\n // synthesized. Empty the queue and settle the decision-time mark even when\n // the queue entry is already gone (the dispatch side may have consumed it);\n // otherwise the mark would settle a later real request as a substitution.\n return passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false }, true)\n }\n\n if (sessionId === undefined) return { kind: 'pass', sessionId }\n\n if (!visibleSession(deps, sessionId)) {\n return passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false })\n }\n\n const entry = peekPending(deps, sessionId)\n if (entry === undefined) return { kind: 'pass', sessionId }\n\n // A blank call id cannot be dispatched and must not be \"repaired\" here: the\n // execute-side tamper check would compare a different id and reject silently.\n if (typeof entry.callId !== 'string' || entry.callId.trim().length === 0) {\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, clearQueue: true, clearAnchors: false },\n }\n }\n\n const turn = clockTurnOf(deps, sessionId)\n // The reset receipt pairs with the entry's own turn when the clock cannot\n // name a real one; a turn-0 commit still wrote (or failed to write) anchors.\n const resetTurn = turn ?? turnNumberOf(entry.turn)\n\n // Row 28: anchor evidence is checked before turn validity. A decision whose\n // anchors were never written (the commit's `set` failed), a store that holds\n // no record for a live entry, and a throwing read are all unverifiable;\n // dropping them as an ordinary stale entry would hide the lost evidence.\n // Intact anchors on a stale turn still take the silent abandon below: there\n // the decision is dead by identity, not because its evidence vanished.\n const anchorRead = anchorsOf(deps, sessionId)\n if (anchorRead.kind !== 'record') {\n return resetPlan(sessionId, entry, 'compaction-reset', 'root', resetTurn)\n }\n const reset = anchorResetOf(anchorRead.anchors, options?.messages, anchorProbe(deps))\n if (reset !== undefined) {\n return resetPlan(\n sessionId,\n entry,\n reset,\n anchorStepIdOf(anchorRead.anchors),\n resetTurn,\n )\n }\n\n if (turn === undefined || !sameTurn(entry.turn, turn)) {\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, clearQueue: true, clearAnchors: false },\n }\n }\n\n // Re-check the step immediately before synthesizing. The turn/step checks\n // above validate identity, not spend: a retried or re-enqueued request in the\n // same turn would otherwise emit a second substitute receipt with the same\n // call id, bypassing the per-turn budget the decision already consumed. The\n // entry is dropped through the ordinary abandon path so its usage mark is\n // settled as discarded rather than left to a later real request.\n if (synthesisBlocked(deps, sessionId, entry, turn)) {\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, clearQueue: true, clearAnchors: true },\n }\n }\n\n return { kind: 'synthesize', sessionId, entry }\n}\n\n/**\n * Abandon a decision whose anchored evidence cannot be verified.\n *\n * The reset receipt explains the lost anchor; the queue and anchors go with it,\n * and the usage mark is settled as discarded by `applyAbandon`.\n */\nfunction resetPlan(\n sessionId: string,\n entry: PendingEntry,\n code: ResetCode,\n stepId: string,\n turn: number,\n): StreamPlan {\n return {\n kind: 'pass',\n sessionId,\n abandon: {\n entry,\n clearQueue: true,\n clearAnchors: true,\n reset: { code, stepId, turn },\n },\n }\n}\n\n/**\n * A pass plan that abandons the session's pending entry, when one exists.\n *\n * `discardMark` makes the plan settle the usage mark even when no entry is\n * left; the stopped-store branch needs that because the dispatch side may\n * already have consumed the entry.\n */\nfunction passPlan(\n deps: HookDeps,\n sessionId: string | undefined,\n abandons: { clearQueue: boolean; clearAnchors: boolean },\n discardMark = false,\n): StreamPlan {\n if (sessionId === undefined) return { kind: 'pass', sessionId }\n const entry = peekPending(deps, sessionId)\n if (entry === undefined) return { kind: 'pass', sessionId, ...(discardMark ? { discardMark } : {}) }\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, ...abandons },\n ...(discardMark ? { discardMark } : {}),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Effects\n// ---------------------------------------------------------------------------\n\n/**\n * Consume the session's usage mark without reporting a saving.\n *\n * `markSubstituted` has no unmark: a mark left behind by an abandoned entry\n * would make the next real request settle a substitution that never ran\n * (obligation 5). `settle()` here is the discard, not a measurement. The parked\n * plan evidence goes with the mark: nothing will ever write its receipt.\n */\nexport function settleDiscarded(deps: HookDeps, sessionId: string): void {\n try {\n sessionUsage(deps, sessionId)?.settle()\n } catch {\n // A foreign ledger can only cost a measurement.\n }\n forgetEvidence(deps, sessionId)\n}\n\n/**\n * The facts of a synthesized turn that its later settlement needs.\n *\n * The settled receipt is written at the first real request after the\n * synthesized turn, when the queue entry is already gone. The evidence (plan,\n * guards) must survive until then, and so must the turn: the settled line pairs\n * with the synthesis turn, not with whichever request happened to settle it\n * (row 26).\n */\ninterface SynthesisFact {\n /** Host turn the synthesized turn answered. */\n turn: number\n /** Plan/guards evidence for the settled receipt, when the entry carried it. */\n evidence?: SubstitutionEvidence\n}\n\n/**\n * Plan/guards evidence parked between synthesis and settlement.\n *\n * Keyed by `HookDeps` first so two plugin instances in one process cannot read\n * each other's session, and a `WeakMap` lets the whole map die with the\n * assembly.\n */\nconst PENDING_EVIDENCE = new WeakMap<HookDeps, Map<string, SynthesisFact>>()\n\n/** Park the fact for the session's next settlement, replacing any earlier. */\nfunction rememberEvidence(deps: HookDeps, sessionId: string, fact: SynthesisFact): void {\n let bySession = PENDING_EVIDENCE.get(deps)\n if (bySession === undefined) {\n bySession = new Map()\n PENDING_EVIDENCE.set(deps, bySession)\n }\n bySession.set(sessionId, fact)\n}\n\n/** Take (and forget) the fact one settlement consumes. */\nfunction takeEvidence(deps: HookDeps, sessionId: string): SynthesisFact | undefined {\n const bySession = PENDING_EVIDENCE.get(deps)\n const fact = bySession?.get(sessionId)\n bySession?.delete(sessionId)\n return fact\n}\n\n/** Drop a fact that no settlement will ever consume. */\nfunction forgetEvidence(deps: HookDeps, sessionId: string): void {\n PENDING_EVIDENCE.get(deps)?.delete(sessionId)\n}\n\n/** Record the synthesis mark for the session's pairing. */\nfunction markSubstitutedFor(deps: HookDeps, sessionId: string, candidateId: string): void {\n try {\n sessionUsage(deps, sessionId)?.markSubstituted(candidateId)\n } catch {\n // A ledger miss costs a measurement, never this turn.\n }\n}\n\n/** The synth-time receipt: the event, before any measurement exists. */\nasync function appendSubstituteReceipt(\n deps: HookDeps,\n sessionId: string,\n entry: PendingEntry,\n): Promise<void> {\n const evidence = (entry as AuditedPendingEntry).evidence\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: turnNumberOf(entry.turn),\n stepId: 'root',\n kind: 'substitute',\n code: 'substituted',\n tool: entry.name,\n callId: entry.callId,\n candidateId: entry.candidateId,\n // G2: the plan the decision came from and the guards that qualified the\n // candidate, capped by `substitutionEvidence` before they reach the line.\n ...(evidence === undefined ? {} : evidence),\n // The synthesized call has no tool result yet; its name and bound args are\n // the evidence for why this turn asked for it.\n args: entry.args,\n preview: callPreview(entry.name, entry.args),\n // Measured only after the next real request; `'unknown'` never counts.\n saved_input_tokens: 'unknown',\n cache_hit_delta: null,\n output_tokens: 'unknown',\n })\n}\n\n/** Settle a pending mark at the first after-mark request and report it. */\nasync function settlePendingMark(deps: HookDeps, sessionId: string): Promise<void> {\n const ledger = sessionUsage(deps, sessionId)\n if (ledger === undefined) return\n\n let candidateId: string | undefined\n let settled: ReturnType<UsageLedger['settle']>\n try {\n const pending = ledger.pendingCandidateId()\n if (typeof pending !== 'string' || pending.length === 0) {\n // A parked fact without a mark can never be settled; drop it rather than\n // let a later, unrelated mark pick up this turn's evidence.\n forgetEvidence(deps, sessionId)\n return\n }\n candidateId = pending\n settled = ledger.settle()\n } catch {\n forgetEvidence(deps, sessionId)\n return\n }\n\n const fact = takeEvidence(deps, sessionId)\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n // Row 26: the synthesized turn is the substitution's turn; the request that\n // happens to settle it may already be the next one.\n turn: fact?.turn ?? clockTurnOf(deps, sessionId) ?? 0,\n stepId: 'root',\n kind: 'substitute-settled',\n code: 'substitute-settled',\n candidateId,\n // G2 applies to the settled line too: the goal and guards are the same\n // evidence the synth-time line carried, parked when that line was written.\n ...(fact?.evidence ?? {}),\n saved_input_tokens: settled.saved_input_tokens,\n cache_hit_delta: settled.cache_hit_delta,\n output_tokens: settled.output_tokens,\n })\n}\n\n/** Map one `usage` chunk onto the ledger's count names (appendix §7). */\nfunction recordUsage(deps: HookDeps, sessionId: string, usage: TokenUsage | undefined): void {\n if (usage === undefined || usage === null) return\n const ledger = sessionUsage(deps, sessionId)\n if (ledger === undefined) return\n try {\n ledger.request({\n input: usage.inputTokens,\n cacheRead: usage.cacheReadTokens ?? 0,\n output: usage.outputTokens,\n })\n } catch {\n // A foreign ledger can only cost a measurement.\n }\n}\n\n/**\n * Store the plan a real response carried, or drop the old one when it carried\n * none.\n *\n * The protocol tells the model to omit the block when unsure, so a response\n * that does not contain a valid plan is also the model withdrawing the previous\n * one. Keeping the old plan would let it fire against a much later receipt the\n * model never wrote it for. A malformed block is likewise not a plan.\n */\nfunction rememberPlan(deps: HookDeps, sessionId: string | undefined, text: string): void {\n if (sessionId === undefined) return\n try {\n const plans = deps.plans\n if (plans == null || typeof plans.set !== 'function') return\n const parsed = text.length === 0 ? { error: 'no-plan' as const } : parsePlan(text)\n if ('plan' in parsed) plans.set(sessionId, parsed.plan)\n else plans.delete(sessionId)\n } catch {\n // A plan that cannot be stored only costs a later decision.\n }\n}\n\n/**\n * Abandon the pending entry: settle the mark, drop what the decision owned and\n * write the reset receipt that explains it.\n */\nasync function applyAbandon(\n deps: HookDeps,\n sessionId: string,\n abandon: AbandonPlan,\n): Promise<void> {\n settleDiscarded(deps, sessionId)\n if (abandon.clearQueue) clearPending(deps, sessionId)\n if (abandon.clearAnchors) clearAnchors(deps, sessionId)\n // A plan that produced this abandoned decision must not survive to drive a\n // later receipt, for either reset kind (and for the non-reset abandons too).\n clearPlan(deps, sessionId)\n if (abandon.reset === undefined) return\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: abandon.reset.turn,\n stepId: abandon.reset.stepId,\n kind: 'reset',\n code: abandon.reset.code,\n tool: abandon.entry.name,\n callId: abandon.entry.callId,\n candidateId: abandon.entry.candidateId,\n })\n}\n\n/**\n * The ordinary turn: observe the real stream.\n *\n * `next()` has already been called by the hook body, so the upstream iterable\n * exists before the generator starts. Usage is mapped and a pending mark is\n * settled at the `usage` chunk (which the host emits before `finish`); text is\n * accumulated for `parsePlan`. Settlement also runs in `finally`: an upstream\n * that throws before the `usage` chunk (a provider 500 mid-stream) or a\n * consumer that cancels the stream still ends the request, and a mark left\n * pending there would pair with the next, unrelated request and report that\n * request's tokens as a saving. An errored stream has no usable sample, so\n * `settle()` reports `'unknown'`. The plan store is still reached only on\n * normal completion, so a partial response never becomes a plan.\n */\nasync function* observeBranch(\n deps: HookDeps,\n sessionId: string | undefined,\n upstream: AsyncIterable<StreamChunk>,\n): AsyncGenerator<StreamChunk> {\n let text = ''\n try {\n for await (const chunk of upstream) {\n if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text\n if (chunk?.type === 'usage' && sessionId !== undefined) {\n recordUsage(deps, sessionId, chunk.usage)\n await settlePendingMark(deps, sessionId)\n }\n yield chunk\n }\n } finally {\n // The host emits `usage` before `finish`, so this is normally a no-op; a\n // route that omits the chunk still ends the request, and the mark must be\n // consumed there rather than attributed to a later request (`'unknown'`,\n // which status does not count).\n if (sessionId !== undefined) await settlePendingMark(deps, sessionId)\n }\n rememberPlan(deps, sessionId, text)\n}\n\n/**\n * The synthesized turn.\n *\n * The plugin answers instead of the model, so `upstream` is only a fallback:\n * the hook body resolved it synchronously at the waterfall point, before this\n * generator runs, and it stays untouched when the entry is still live. The\n * entry is re-read with `peek` (never `take`) so it survives to\n * `tools/execute`; if it vanished between the synchronous decision and the\n * first generator step, the mark is discarded and the real model answers,\n * because a substitution that cannot be dispatched must not be faked.\n *\n * `upstream` is absent only when the host's `next()` itself threw while the\n * hook body was resolving it; a host that cannot produce an upstream has no\n * fallback to offer, so the vanished entry ends with an empty stream rather\n * than a synthesized call no dispatch can check.\n */\nasync function* synthesizeBranch(\n deps: HookDeps,\n sessionId: string,\n entry: PendingEntry,\n upstream: AsyncIterable<StreamChunk> | undefined,\n): AsyncGenerator<StreamChunk> {\n const current = peekPending(deps, sessionId)\n if (current === undefined || current.callId !== entry.callId) {\n settleDiscarded(deps, sessionId)\n if (upstream !== undefined) yield* observeBranch(deps, sessionId, upstream)\n return\n }\n\n markSubstitutedFor(deps, sessionId, current.candidateId)\n // Park the plan evidence and the synthesis turn for the settled line, which\n // runs at the next real request after this entry has left the queue.\n const evidence = (current as AuditedPendingEntry).evidence\n const turn = turnNumberOf(current.turn)\n rememberEvidence(deps, sessionId, {\n turn,\n ...(evidence === undefined ? {} : { evidence }),\n })\n // Row 27: mirror the synthesis fact now, not when `tools/execute` accepts the\n // dispatch. A call denied by `tools/pre-execute` never reaches that hook, and\n // a rollover must still report the model round this turn skipped. The mirror\n // only feeds the settle path; it never claims a measured saving.\n deps.noteSynthesis?.(sessionId, turn, current.candidateId, evidence)\n await appendSubstituteReceipt(deps, sessionId, current)\n yield* synthesizeTurn(current)\n}\n\n// ---------------------------------------------------------------------------\n// The exported hook and session-end cleanup\n// ---------------------------------------------------------------------------\n\n/**\n * Answer a pass decision: abandon what the decision owned, then observe the\n * real stream.\n *\n * `upstream` is resolved by the hook body at the waterfall point; the generator\n * only delays effects and consumption.\n */\nfunction observedPass(\n deps: HookDeps,\n plan: Extract<StreamPlan, { kind: 'pass' }>,\n upstream: AsyncIterable<StreamChunk>,\n): AsyncIterable<StreamChunk> {\n return (async function* (): AsyncGenerator<StreamChunk> {\n if (plan.sessionId !== undefined) {\n // Order matters only for evidence: the discard drops the parked\n // plan/guards, and `applyAbandon` then clears the rest. Both settle\n // calls are idempotent.\n if (plan.discardMark === true) settleDiscarded(deps, plan.sessionId)\n if (plan.abandon !== undefined) await applyAbandon(deps, plan.sessionId, plan.abandon)\n }\n yield* observeBranch(deps, plan.sessionId, upstream)\n })()\n}\n\n/**\n * Build the `llm/stream` listener.\n *\n * Returns a **synchronous** function returning an `AsyncIterable`; see the\n * module header for why an `async` function here breaks every request. Any\n * `purpose`-tagged call (selector, compaction, session-title) returns `next()`\n * untouched: never observed, never substituted. Every real request is decided\n * synchronously by {@link resolveStreamPlan} and then answered by a generator.\n *\n * The upstream iterator is resolved **at the waterfall point on every path**,\n * before any generator body runs. The host's terminal is a lazy async iterable\n * (starting it is what calls the model), so resolving it on the synthesis path\n * costs nothing; it is only consumed if the pending entry vanished and the real\n * model has to answer. Resolving it lazily inside the generator would resume a\n * waterfall the host may already have moved past.\n */\nexport function streamHook(\n deps: HookDeps,\n): (options: GenerateOptions, next: () => AsyncIterable<StreamChunk>) => AsyncIterable<StreamChunk> {\n return (options, next) => {\n // Any purpose-tagged request is auxiliary (appendix §1): the selector, the\n // compaction summarizer, the session-title model. They share the session\n // id but are not conversation steps, so they pass through raw: no\n // substitution, no usage observation, no settlement, no plan rollover.\n if (options?.purpose !== undefined) return next()\n\n const sessionId = sessionIdOf(options)\n if (sessionId !== undefined) {\n const turn = clockTurnOf(deps, sessionId)\n if (turn !== undefined) {\n let rolledOver = false\n try {\n rolledOver = deps.sessions?.notePlanTurn(sessionId, turn) === true\n } catch {\n rolledOver = false\n }\n if (rolledOver) clearPlan(deps, sessionId)\n }\n }\n\n let plan: StreamPlan\n try {\n plan = resolveStreamPlan(deps, options)\n } catch {\n // A bug in our own decision logic must not take the model request down,\n // but it must still take the ordinary pass path: the decision-time mark\n // has to be discarded here or this real request would settle a\n // substitution that never ran. Clearing the queue is the same fail-closed\n // answer — no decision was made.\n try {\n plan = passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false }, true)\n } catch {\n plan = { kind: 'pass', sessionId, discardMark: true }\n }\n }\n\n // Resolve the upstream iterator before any branch. The real host's terminal\n // is an async generator, so this starts no model call; it only fixes which\n // request the fallbacks observe. A host whose `next()` throws was already\n // failing on the pass path, so that throw is preserved there; the synthesis\n // path proceeds without a fallback instead.\n // Count a synthesis decision before the generator runs: an unconsumed\n // stream or a vanished entry must still not let the same step be\n // synthesized twice. This runs before `next()` too, so a host whose\n // terminal throws cannot reopen the same step.\n if (plan.kind === 'synthesize') {\n const turn = clockTurnOf(deps, plan.sessionId) ?? turnNumberOf(plan.entry.turn)\n recordSynthesis(deps, plan.sessionId, turn, plan.entry.callId)\n }\n\n let upstream: AsyncIterable<StreamChunk> | undefined\n try {\n upstream = next()\n } catch (error) {\n if (plan.kind !== 'synthesize') throw error\n return synthesizeBranch(deps, plan.sessionId, plan.entry, undefined)\n }\n\n if (plan.kind === 'synthesize') {\n return synthesizeBranch(deps, plan.sessionId, plan.entry, upstream)\n }\n\n return observedPass(deps, plan, upstream)\n }\n}\n\n/**\n * Drop every per-session trace the plugin keeps for `sessionId`.\n *\n * This is the session-end cleanup `src/index.ts` calls from its\n * `session/disposed` listener: the receipt/dispatch store ships its own\n * `clear`, but it does not own the queue, the anchors, the plan map or the\n * per-session runtime, so the caller would otherwise have to know four separate\n * clears. A pending usage mark is settled first so a mark cannot outlive the\n * session it belongs to, and the shared-instance loans this session holds are\n * released so a disposed owner does not refuse every later session forever.\n */\nexport function clearSession(deps: HookDeps, sessionId: string): void {\n settleDiscarded(deps, sessionId)\n clearPending(deps, sessionId)\n clearAnchors(deps, sessionId)\n clearPlan(deps, sessionId)\n forgetSynthesis(deps, sessionId)\n try {\n // Projection locators are session-scoped evidence: a disposed session must\n // not leave its spill paths behind for the next session id to inherit.\n deps.retrievals?.clear(sessionId)\n } catch {\n // Same: each clear is independent.\n }\n try {\n deps.sessionState?.clear(sessionId)\n } catch {\n // Same: each clear is independent.\n }\n try {\n deps.sessions?.clear(sessionId)\n } catch {\n // Same.\n }\n releaseSharedLoans(deps, sessionId)\n // The rollover path mirrors an accepted dispatch so a late tool result can\n // still settle a substitution that ran. A disposed session has no late\n // result coming, so the mirror would otherwise sit in the per-deps map for\n // the plugin's lifetime — one entry per disposed session.\n try {\n deps.clearAcceptedDispatch?.(sessionId)\n } catch {\n // A disposal hook that throws must not abort the rest of the teardown.\n }\n}\n"]}
1
+ {"version":3,"file":"llm-stream.js","sourceRoot":"","sources":["../../src/hooks/llm-stream.ts"],"names":[],"mappings":"AAsLA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAA;AAEjE,OAAO,EAAE,SAAS,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ChC,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC7B,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC7B,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC1B,eAAe,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAChC,IAAI,CAAC;QACH,2EAA2E;QAC3E,uEAAuE;QACvE,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,CAAA;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,mCAAmC;IACrC,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,SAAS,CAAC,CAAA;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,mCAAmC;IACrC,CAAC;IACD,IAAI,CAAC;QACH,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAA;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,QAAQ;IACV,CAAC;IACD,kBAAkB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACnC,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,0DAA0D;IAC1D,IAAI,CAAC;QACH,IAAI,CAAC,qBAAqB,EAAE,CAAC,SAAS,CAAC,CAAA;IACzC,CAAC;IAAC,MAAM,CAAC;QACP,uEAAuE;IACzE,CAAC;AACH,CAAC","sourcesContent":["/**\n * The `llm/stream` hook body: the point where the plugin answers a model\n * request itself instead of calling the provider.\n *\n * ## The synchronous contract\n *\n * The host treats `llm/stream` as a **synchronous waterfall**: `next()` returns\n * an `AsyncIterable<StreamChunk>` and the host does `for await` over whatever\n * the listener returns. An `async` listener would hand the host a\n * `Promise<AsyncIterable>`, every request would fail with a `TypeError`, and the\n * plugin would break the product rather than degrade it (appendix §7). The\n * exported function therefore returns a **generator object synchronously**;\n * every `await` lives inside the generator.\n *\n * ## Rule order (fixed, checks before any side effect)\n *\n * 1. `purpose` set -> raw `next()`. The appendix sets `purpose` **only** for\n * auxiliary calls, and the host issues several on the same session id: the\n * plugin's selector (`boost-selector`), `dsh-compaction-basic`\n * (`compaction`) and the session-title model (`session-title`). None is a\n * conversation step, so all pass through untouched: never substituted,\n * never observed into `usage.request()`, never settling a mark. Observing\n * one would pair a substitution with the summarizer's usage and corrupt\n * `saved_input_tokens` (obligation 7); synthesizing into one would break\n * compaction and write a substitute receipt for a call that never ran.\n * 2. `receipts.stopped()` -> pass through, fail-closed. A store that cannot\n * record evidence cannot justify a substitution.\n * 3. Visibility. `resolveSession(sessionId)` returning `undefined` means the\n * session is not substitutable: pass through and clear that session's queue\n * (the decision cannot be honoured any more).\n * 4. No pending entry -> pass through. This is the ordinary turn.\n * 5. Anchors readable and intact. A decision whose anchors were never written\n * (the commit's `set` failed), whose store holds no record, or whose store\n * throws cannot be verified at all; all three fail closed through the reset\n * path (row 28). With a record present, detection runs against\n * `options.messages` (obligation 6). A pruned carrier yields\n * `pruned-reset`, a receipt that is no longer present yields\n * `compaction-reset`; either clears queue + anchors and passes through. A\n * body that only shares the anchor's head and tail is **not** a carrier: it\n * must also carry the pruner marker or our projection's head line, or a\n * middle edit would pass for the original text.\n * 6. Turn validity. The queue is cleared on the **new turn's first\n * `post-execute`**, which happens after the new turn's first `llm/stream`.\n * An entry whose `turn` differs from the session clock's turn belongs to a\n * previous turn: synthesizing it would answer the new turn with an old\n * decision, and its `callId` would even match at dispatch and be accepted.\n * Compare, clear and pass through (obligation 4). This runs after the anchor\n * read: an entry that is dead by identity but also lost its evidence still\n * reports the reset, while one with intact anchors is dropped silently.\n * 7. Step still payable. `post-execute` already took the entry's step, but the\n * same decision can be replayed (a retried request, a re-enqueue at one\n * step). The per-turn synthesis tally and the budget's paid-step count are\n * re-checked immediately before synthesizing; an entry whose step can no\n * longer be honoured is dropped through the abandon path (settling its mark\n * as discarded) instead of emitting a duplicate `callId`.\n * 8. Synthesize: `markSubstituted` -> `{kind:'substitute'}` receipt ->\n * `peek` (never `take`, obligation 3) -> `yield* synthesizeTurn(entry)`.\n * The upstream iterator is resolved synchronously at the waterfall point on\n * every path, but the synthesis branch does not consume it. The entry must\n * survive to `tools/execute`, which is the consumer that enforces the\n * tamper check.\n *\n * The hook never calls `budget.take()`: Task 23b already took the step at\n * `tools/post-execute`, and a second take would charge 2 of 8 per substitution\n * (obligation 2). It only reads `count()` to verify that a paid step backs the\n * synthesis.\n *\n * ## Per-session state (obligation 1)\n *\n * `HookDeps` also carries single `clock`/`budget`/`usage` instances, and a\n * shared instance is cross-session contamination: another session's\n * `agent/request` sets this session's `callId` turn/step, a shared\n * `StepBudget(1)` starves one session, and a shared usage ledger pairs one\n * session's substitution with another session's request. `SessionRuntime`\n * (exported here) keys all three by `sessionId`; `HookDeps.sessions` accepts it,\n * and when present it is authoritative for both this hook and Task 23b's\n * helpers. The shipped wiring lives in `wireSessionEvents` (`src/index.ts`)\n * and is deliberately **two** clock listeners, not one:\n *\n * ```ts\n * const sessions = new SessionRuntime(cfg.stepsPerTurn)\n * registerHooks(ctx, { ...deps, sessions })\n *\n * // agent/pre-step: the non-deprecated clock seam. It fires once per proposed\n * // step AFTER prompt assembly (the host assembles at\n * // `@deepseek-ai/dsh-agent-loop/lib/index.js:692`, then dispatches pre-step\n * // at `:695`), and copies the host turn/step.\n * ctx.on('agent/pre-step', (payload, next) => {\n * sessions.onModelRequest(sessionId, payload.turn, payload.step)\n * horizon.observe(sessionId, payload.turn, payload.step)\n * return next()\n * })\n *\n * // agent/request: deprecated, kept for what the request waterfall alone\n * // yields: the resolved provider/model the selector inherits (after next()),\n * // the async visibility warm, and a clock fallback.\n * ctx.on('agent/request', async (payload, next) => {\n * sessions.onModelRequest(sessionId, payload.turn, payload.step)\n * await warmVisibility(scope, registry, payload.agent, sessionId, workspaces)\n * const config = await next()\n * rememberRoute(routes, sessionId, config)\n * return config\n * })\n *\n * ctx.on('session/disposed', (session) => clearSession(deps, sessionId))\n * ```\n *\n * The split is intentional: `agent/pre-step` is the seam the host documents for\n * turn/step, while the selector's effective route is only available from the\n * request waterfall's resolved config. Both listeners copy the clock so a host\n * that drops the deprecated event still advances turns. Both record the route:\n * `agent/pre-step` from the captured `modelSelection` (the primary source since\n * row 37), and `agent/request` from the resolved config as the fallback for\n * hosts that only populate it there. The visibility warm is owned by the\n * `system-prompt/assemble` listener (also in `wireSessionEvents`), which the\n * host runs **before** `agent/pre-step`; `agent/request`'s call is only a\n * fallback. This hook sees a warm judgement only because of that assemble\n * listener — a cold-cache read here would reintroduce the D4 prompt\n * invalidation, so do not move the warm back onto the pre-step seam.\n *\n * `onModelRequest` copies the host turn/step (never a plugin count) and resets\n * that session's budget only when its turn changes. `notePlanTurn` is the\n * matching rollover for the plan store: the first real request of a new turn\n * drops the previous turn's plan before a new one can be parsed, so a stale\n * plan cannot drive a substitution in the new turn. `clearSession(deps, id)`\n * is the session-end cleanup: queue, anchors, plans, receipt state, the usage\n * mark, the runtime entry and any shared-instance loan it holds, all dropped\n * together (obligation 10). No map is ever handed out.\n *\n * ## Settlement (obligation 11)\n *\n * The first real request after a synthesized turn carries a `usage` chunk. The\n * pass-through branch maps it to `UsageLedger.request()` and, if a mark is\n * pending, calls `settle()` and appends `{kind:'substitute-settled'}` with the\n * measured counts (`'unknown'` stays `'unknown'`; it is never interpolated).\n * When a marked entry is abandoned (turn rollover, reset, stopped receipts,\n * lost visibility, an unpayable or already-synthesized step, a vanished queue\n * entry) the mark is settled and discarded **without** a settlement receipt: no\n * substitution ran, so no saving exists to report (obligation 5).\n *\n * ## Anchor detection and our own projection\n *\n * The host pruner rewrites an oversized receipt in place to\n * `head + PRUNE_MARKER + tail`, and apply-mode projection composes\n * `head line + head + spill footer + tail`. Both preserve the receipt's head\n * and tail, so \"the anchor text is not present verbatim\" alone would classify\n * our own projection as compaction and disable substitution whenever projection\n * is on. Two *outer* shapers also rewrite a receipt: `dsh-spill-policy` for\n * non-`read` tools and `dsh-tool-fs-search` for `glob`/`grep`. The spill policy\n * keeps a head and a tail and appends its footer after the tail; fs-search\n * keeps the head of an over-cap page and appends its footer after it. Either\n * way a rewrite can end in a notice instead of in the anchor's last code\n * points.\n *\n * `carriesAnchor` therefore accepts the exact text, or a body holding the\n * anchor's head *and* tail probes **plus** rewrite evidence: the prune marker\n * (which then decides `pruned-reset`), the projection head line, whose\n * `output N chars; showing first H and last T` counts must name this anchor's\n * length and windows, or a spill-style footer from an outer shaper, with the\n * anchor's head at the very start and its tail at the very end of the rewritten\n * body (or before that trailing footer). A shaper that drops the tail — an\n * over-cap fs-search page — is not a carrier: the model no longer holds the\n * anchor's end, so the decision is refused. A full receipt with the same probes\n * but a different middle — a file edited and re-read — carries none of that\n * evidence, so it is a lost anchor (`compaction-reset`) rather than a\n * substitution against content the model no longer holds.\n *\n * Probes are measured in code points (a UTF-16 slice can split a surrogate\n * pair) and clamped to the smallest configured projection window, because\n * `resolveConfig` accepts `headChars`/`tailChars` below the probe length and a\n * window shorter than the probe would make our own projection look like\n * compaction.\n *\n * Everything here is contained: a foreign store, queue, ledger, clock or\n * resolver can degrade the decision, never throw out of the model request.\n * `resolveStreamPlan` is synchronous and writes no receipt; its only state is\n * the per-turn synthesis tally, and every receipt/queue effect (writes, clears,\n * settlement) happens inside a generator after the decision.\n *\n * @module dsh-boost/hooks/llm-stream\n */\nimport type { GenerateOptions, StreamChunk, TokenUsage } from '@deepseek-ai/dsh-llm'\nimport { StepBudget } from '../admission/ledger.js'\nimport { UsageLedger } from '../admission/usage.js'\nimport { DEFAULT_CONFIG } from '../config.js'\nimport { looksPruned, PRUNE_MARKER } from '../gate/invalidate.js'\nimport type { ReceiptAnchors } from '../gate/invalidate.js'\nimport { parsePlan } from '../gate/plan.js'\nimport { TurnClock } from './clock.js'\nimport { synthesizeTurn } from './synthesize.js'\nimport type { PendingEntry } from './pending.js'\nimport type { AuditedPendingEntry, HookDeps, SubstitutionEvidence } from './post-execute.js'\nimport {\n appendReceipt,\n callPreview,\n clearAnchors,\n clearPlan,\n clearPending,\n clockTurnOf,\n peekPending,\n} from './session-state.js'\n\n/** Which external rewrite invalidated a decision. */\ntype ResetCode = 'pruned-reset' | 'compaction-reset'\n\n/** Default head/tail probe length for a receipt rewritten in place. */\nconst ANCHOR_PROBE_CHARS = 32\n\n// ---------------------------------------------------------------------------\n// Per-session runtime (obligation 1)\n// ---------------------------------------------------------------------------\n\n/** The three per-session pieces that must never be shared across sessions. */\ninterface SessionEntry {\n /** Host turn/step for this session. */\n clock: TurnClock\n /** This session's per-turn substitution budget. */\n budget: StepBudget\n /** This session's request pairing. */\n usage: UsageLedger\n /** The host turn whose plan store this session has been reconciled with. */\n planTurn?: number\n}\n\n/**\n * Per-session clock, budget and usage ledger.\n *\n * The host numbers turns and steps per session; a single instance therefore\n * lets one session's `agent/request` stamp another session's derived `callId`,\n * lets one session's `StepBudget(1)` starve the next, and pairs one session's\n * substitution with another session's request. The runtime keys all three by\n * `sessionId` and is the only place a per-session primitive is created.\n *\n * The map is private: callers get the objects, never the map, and\n * {@link SessionRuntime.clear} is the only way an entry leaves. `onModelRequest`\n * is driven by Task 23c-2 from the host's `agent/request` payload; this module\n * cannot see that event itself. A new turn resets that session's budget (the\n * budget is per-turn, not per-lifetime); a non-finite or backwards turn is\n * ignored by `TurnClock` and therefore resets nothing.\n */\nexport class SessionRuntime {\n private readonly bySession = new Map<string, SessionEntry>()\n private readonly stepsPerTurn: number\n\n constructor(stepsPerTurn: number = DEFAULT_CONFIG.stepsPerTurn) {\n // `StepBudget` already treats a non-positive max as empty; only a\n // non-finite value (which no resolved config can produce) falls back.\n this.stepsPerTurn = Number.isFinite(stepsPerTurn)\n ? stepsPerTurn\n : DEFAULT_CONFIG.stepsPerTurn\n }\n\n /** The session's clock, created on first use. */\n clockFor(sessionId: string): TurnClock {\n return this.entry(sessionId).clock\n }\n\n /** The session's turn budget, created on first use. */\n budgetFor(sessionId: string): StepBudget {\n return this.entry(sessionId).budget\n }\n\n /** The session's usage ledger, created on first use. */\n usageFor(sessionId: string): UsageLedger {\n return this.entry(sessionId).usage\n }\n\n /**\n * Record one host request for a session.\n *\n * `turn`/`step` are the host's numbers, copied through `TurnClock` (which\n * ignores non-finite and backwards turns). A turn change is the only thing\n * that resets the budget: a second request in one turn must keep the spend.\n */\n onModelRequest(sessionId: string, turn: number, step?: number): void {\n const entry = this.entry(sessionId)\n const before = entry.clock.turn()\n entry.clock.onModelRequest(turn, step)\n if (entry.clock.turn() !== before) entry.budget.reset()\n }\n\n /**\n * Reconcile this session's plan store with `turn`; `true` on a turn change.\n *\n * The plan lives in `HookDeps.plans` and is keyed by session only, so\n * without this note a turn that emits no new plan keeps the previous turn's\n * one, and its remaining steps can still drive a substitution. The stream\n * hook calls this once per **real** request (never for an auxiliary\n * `purpose`, which is not a conversation step) and clears the plan map when\n * it returns true, before that request's response could write a new plan.\n * The first call reports true so a seeded map cannot outlive its first\n * request; `clearSession` drops the note with the rest of the entry.\n */\n notePlanTurn(sessionId: string, turn: number): boolean {\n const entry = this.entry(sessionId)\n if (entry.planTurn === turn) return false\n entry.planTurn = turn\n return true\n }\n\n /** Drop everything this runtime holds for one session. */\n clear(sessionId: string): void {\n this.bySession.delete(sessionId)\n }\n\n /** Number of sessions with state (not the number ever seen). */\n size(): number {\n return this.bySession.size\n }\n\n private entry(sessionId: string): SessionEntry {\n const existing = this.bySession.get(sessionId)\n if (existing !== undefined) return existing\n const entry: SessionEntry = {\n clock: new TurnClock(),\n budget: new StepBudget(this.stepsPerTurn),\n usage: new UsageLedger(),\n }\n this.bySession.set(sessionId, entry)\n return entry\n }\n}\n\n// ---------------------------------------------------------------------------\n// Defensive readers: every foreign call is wrapped\n// ---------------------------------------------------------------------------\n\n/** The request's session id, or `undefined` when the host supplied none. */\nfunction sessionIdOf(options: GenerateOptions | undefined): string | undefined {\n const id = options?.sessionId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n}\n\n/**\n * Which session has been lent each shared fallback instance.\n *\n * `apply` always passes `sessions`, so this exists for embedders and tests that\n * hand in one `clock`/`budget`/`usage` instead. Those three carry per-session\n * state — a turn's step counter, a pending usage mark — so lending one to a\n * second session attributes B's tokens to A's candidate. That surfaces as a\n * saving that never happened, which is the one error this plugin must not\n * produce. Ownership is keyed by the **instance**, not by the deps object: two\n * assemblies that share the same three objects (the pattern the fallback exists\n * for) must agree on the one session they serve, or each claims its own loan\n * and both borrow. The first session to arrive keeps the loan; every other\n * session gets `undefined`, which each caller already reads as \"no\n * substitution\" (fail closed), and the warning is emitted once per deps object\n * rather than per call. `clearSession` drops the loans its session holds, so a\n * disposed owner does not lock the instance for the rest of the process.\n */\nconst fallbackLoans = new WeakMap<object, { sessionId: string }>()\n\n/** Deps objects already warned about a refused loan (once each, not per call). */\nconst fallbackWarned = new WeakSet<object>()\n\n/** Whether the shared fallback instance may serve this session. */\nfunction mayBorrowShared(instance: object, deps: HookDeps, sessionId: string): boolean {\n const held = fallbackLoans.get(instance)\n if (held === undefined) {\n fallbackLoans.set(instance, { sessionId })\n return true\n }\n if (held.sessionId === sessionId) return true\n if (!fallbackWarned.has(deps)) {\n fallbackWarned.add(deps)\n try {\n deps.logger?.warn(\n `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`,\n )\n } catch {\n // A logger that throws must not turn a measurement guard into a failure.\n }\n }\n return false\n}\n\n/** Release the shared-instance loans the disposing session holds. */\nfunction releaseSharedLoans(deps: HookDeps, sessionId: string): void {\n for (const instance of [deps.clock, deps.budget, deps.usage]) {\n if (instance === undefined) continue\n if (fallbackLoans.get(instance)?.sessionId === sessionId) fallbackLoans.delete(instance)\n }\n}\n\n/**\n * The session's clock: the per-session runtime when wired, the shared instance\n * otherwise — but only for the one session that instance belongs to.\n *\n * Exported because `tools/post-execute` must resolve the *same* clock for the\n * turn/step it stamps into a `callId`; two copies of this precedence rule could\n * drift and let the decision and the stream hook disagree about one session.\n */\nexport function sessionClock(deps: HookDeps, sessionId: string): TurnClock | undefined {\n try {\n const owned = deps.sessions?.clockFor(sessionId)\n if (owned !== undefined) return owned\n } catch {\n // Fall through to the shared instance, subject to the ownership rule.\n }\n return deps.clock !== undefined && mayBorrowShared(deps.clock, deps, sessionId)\n ? deps.clock\n : undefined\n}\n\n/** The session's turn budget; the same precedence as {@link sessionClock}. */\nexport function sessionBudget(deps: HookDeps, sessionId: string): StepBudget | undefined {\n try {\n const owned = deps.sessions?.budgetFor(sessionId)\n if (owned !== undefined) return owned\n } catch {\n // Fall through to the shared instance, subject to the ownership rule.\n }\n return deps.budget !== undefined && mayBorrowShared(deps.budget, deps, sessionId)\n ? deps.budget\n : undefined\n}\n\n/**\n * Whether a substitution budget is wired at all.\n *\n * `undefined` from {@link sessionBudget} has two meanings and callers must not\n * conflate them (row 21): with neither `deps.budget` nor a per-session runtime,\n * the embedder never asked for a cap, so the substitution is unconstrained; a\n * wired budget that this session may not borrow is the opposite — the shared\n * instance belongs to another session and the step cannot be paid. Treating the\n * refusal as \"no cap\" let an unbudgeted substitution through without ever\n * incrementing the live budget.\n */\nexport function budgetWired(deps: HookDeps): boolean {\n return deps.budget !== undefined || deps.sessions !== undefined\n}\n\n/** The session's usage ledger; the same precedence as {@link sessionClock}. */\nexport function sessionUsage(deps: HookDeps, sessionId: string): UsageLedger | undefined {\n try {\n const owned = deps.sessions?.usageFor(sessionId)\n if (owned !== undefined) return owned\n } catch {\n // Fall through to the shared instance, subject to the ownership rule.\n }\n return deps.usage !== undefined && mayBorrowShared(deps.usage, deps, sessionId)\n ? deps.usage\n : undefined\n}\n\n/** What the session's anchor store answered. */\ntype AnchorRead =\n | { kind: 'record'; anchors: ReceiptAnchors }\n /** The store answered, but holds no record for a session with a live decision. */\n | { kind: 'cold' }\n /** The store is absent or its read threw: nothing can be verified. */\n | { kind: 'unreadable' }\n\n/**\n * The session's anchors, distinguishing a record from a cold store.\n *\n * A substitution is only legitimate against the receipt the model still holds,\n * so every missing answer is a lost anchor (row 28). `post-execute` writes\n * anchors with every commit, so a live queue entry with no record means that\n * write failed; synthesizing then would skip the only verification the design\n * has. A throwing read is equally unverifiable. Both fail closed through the\n * ordinary reset path instead of substituting on unseen evidence.\n */\nfunction anchorsOf(deps: HookDeps, sessionId: string): AnchorRead {\n const store = deps.anchors\n if (store == null || typeof store.get !== 'function') return { kind: 'unreadable' }\n try {\n const anchors = store.get(sessionId)\n return anchors == null ? { kind: 'cold' } : { kind: 'record', anchors }\n } catch {\n return { kind: 'unreadable' }\n }\n}\n\n/**\n * Whether the receipt store has stopped writing, fail-closed.\n *\n * A missing `stopped` (a partial store in a test or an older host) is \"not\n * stopped\", so the ordinary path is unchanged. A store that *throws* cannot\n * record evidence, which is exactly what stopped means.\n */\nexport function receiptsStopped(deps: HookDeps): boolean {\n try {\n const store = deps.receipts\n if (store == null || typeof store.stopped !== 'function') return false\n return store.stopped() === true\n } catch {\n return true\n }\n}\n\n/**\n * Whether the session resolves to a workspace.\n *\n * The stream hook's rule only needs the resolver: a session that does not\n * resolve has no substitute-able workspace, so the decision cannot be honoured.\n * The live scope-document check lives in `tools/post-execute`, which owns the\n * async document read; `resolveSession` is synchronous by contract.\n */\nfunction visibleSession(deps: HookDeps, sessionId: string): boolean {\n try {\n const resolve = deps.resolveSession\n if (typeof resolve !== 'function') return false\n return typeof resolve(sessionId) === 'string'\n } catch {\n return false\n }\n}\n\n/** The host turn and the entry's turn are the same, number or stringified number. */\nfunction sameTurn(entryTurn: number | string, clockTurn: number): boolean {\n return String(entryTurn) === String(clockTurn)\n}\n\n/** A receipt's `turn` field is a number; entry turns may already be strings. */\nfunction turnNumberOf(turn: number | string): number {\n if (typeof turn === 'number' && Number.isFinite(turn)) return turn\n const parsed = Number(turn)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\n// ---------------------------------------------------------------------------\n// Anchor detection against the outgoing messages (obligation 6)\n// ---------------------------------------------------------------------------\n\n/**\n * Every text-block body the model will see in this request.\n *\n * `RequestMessage.content` is an array of blocks; only `text` blocks carry\n * receipt bodies. Blocks are kept separate so a mixed message cannot make two\n * unrelated texts look like one receipt. A malformed message is skipped, never\n * a throw: `options.messages` is host-shaped data.\n */\nfunction messageTexts(messages: unknown): string[] {\n if (!Array.isArray(messages)) return []\n const bodies: string[] = []\n for (const message of messages) {\n const content = (message as { content?: unknown } | null | undefined)?.content\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (typeof block !== 'object' || block === null) continue\n const { type, text } = block as { type?: unknown; text?: unknown }\n if (type === 'text' && typeof text === 'string') bodies.push(text)\n }\n }\n return bodies\n}\n\n/**\n * The head/tail probe windows, clamped to the projection's own windows.\n *\n * Our projection keeps `headChars`/`tailChars` code points of the receipt, so\n * a probe longer than a configured window can never match a projected body and\n * would report `compaction-reset`. `resolveConfig` accepts any finite value\n * (including 0), so the window is the smallest one any family configures,\n * capped at {@link ANCHOR_PROBE_CHARS}; a 0 window drops that side of the\n * probe and leaves only the other. With the design defaults this is 32/32.\n */\nfunction anchorProbe(deps: HookDeps): { head: number; tail: number } {\n let head = ANCHOR_PROBE_CHARS\n let tail = ANCHOR_PROBE_CHARS\n try {\n const projection: unknown = deps.config?.projection\n if (typeof projection !== 'object' || projection === null) return { head, tail }\n for (const raw of Object.values(projection)) {\n const params = raw as { headChars?: unknown; tailChars?: unknown } | null\n if (typeof params?.headChars === 'number' && Number.isFinite(params.headChars)) {\n head = Math.min(head, Math.max(0, params.headChars))\n }\n if (typeof params?.tailChars === 'number' && Number.isFinite(params.tailChars)) {\n tail = Math.min(tail, Math.max(0, params.tailChars))\n }\n }\n } catch {\n return { head: ANCHOR_PROBE_CHARS, tail: ANCHOR_PROBE_CHARS }\n }\n return { head, tail }\n}\n\n/**\n * The head line our own projection writes: `[output N chars; showing first H\n * and last T]`. The counts use `toLocaleString('en-US')`, hence the commas.\n */\nconst PROJECTION_HEADER = /^\\[output ([\\d,]+) chars; showing first ([\\d,]+) and last ([\\d,]+)\\]$/\n\n/** One `en-US`-formatted count from a projection head line. */\nfunction headerCount(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined\n const value = Number(raw.replaceAll(',', ''))\n return Number.isSafeInteger(value) ? value : undefined\n}\n\n/**\n * Whether `body` is our own projection of `anchor`.\n *\n * A projected receipt is `head line + head + spill footer + tail`. The head\n * line names the anchor's total code points and both window sizes, and the two\n * windows are the anchor's own first/last code points. A full receipt that\n * merely shares the anchor's head and tail cannot produce that line, so this\n * closes the probe collision without reading the middle (which the projection\n * removed) and without a new stored field. Old anchors that cannot be verified\n * this way simply do not match, which fails closed.\n */\nfunction ownProjectionCarries(body: string, anchor: string): boolean {\n const newline = body.indexOf('\\n')\n if (newline === -1) return false\n const match = PROJECTION_HEADER.exec(body.slice(0, newline))\n if (match === null) return false\n const output = headerCount(match[1])\n const headLen = headerCount(match[2])\n const tailLen = headerCount(match[3])\n if (output === undefined || headLen === undefined || tailLen === undefined) return false\n if (headLen <= 0 && tailLen <= 0) return false\n const points = Array.from(anchor)\n if (output !== points.length) return false\n if (headLen + tailLen >= points.length) return false\n const head = headLen > 0 ? points.slice(0, headLen).join('') : ''\n const tail = tailLen > 0 ? points.slice(-tailLen).join('') : ''\n if (!body.startsWith(`${match[0]}\\n${head}`)) return false\n if (tailLen === 0) return true\n // Our own replacement may append rescued marker lines after the tail (design\n // §5.4-4), so the body does not have to *end* with the tail — it has to\n // contain it at the position the header implies, followed by nothing but\n // those markers. A rewritten middle still fails, because the tail must sit\n // where the two windows put it.\n const tailAt = body.indexOf(`\\n${tail}`)\n if (tailAt === -1) return false\n const rest = body.slice(tailAt + 1 + tail.length)\n if (rest === '') return true\n return rest.startsWith('\\n') && PRESERVED_SIGNAL_LINE.test(rest)\n}\n\n/** One rescued marker line, or several of them, each on its own line. */\nconst PRESERVED_SIGNAL_LINE = /^\\n(?:\\[exit code: -?\\d+\\]|exit_code\\s*[:=]\\s*-?\\d+|is_error\\s*[:=]\\s*(?:true|false))(?:\\n(?:\\[exit code: -?\\d+\\]|exit_code\\s*[:=]\\s*-?\\d+|is_error\\s*[:=]\\s*(?:true|false)))*$/i\n\n/**\n * Whether `body` is the anchor rewritten **by the host pruner**, and nothing\n * else.\n *\n * `looksPruned` alone is not identity: any body that embeds the anchor's pruned\n * text — a `read` of a session log, the case `invalidate` documents as\n * occurring — carries the marker too, so a receipt that was compacted away\n * could be declared \"still carried\" and a decision would survive on evidence\n * the model no longer holds.\n *\n * The pruner replaces the middle with a single marker and keeps a head and a\n * tail, so a genuine carrier is `head + marker + tail` with nothing before the\n * head and nothing after the tail. Requiring the carrier to *start* with the\n * anchor's first `head` code points and *end* with its last `tail` ones — the\n * same windows `ownProjectionCarries` derives for our own rewrite — rejects the\n * wrapper: its head is the wrapper's opening line, not the anchor's.\n */\nfunction prunedCarries(body: string, anchor: string): boolean {\n const marker = body.indexOf(PRUNE_MARKER)\n if (marker === -1) return false\n // Exactly one marker: two would mean this is not one pruned receipt.\n if (body.indexOf(PRUNE_MARKER, marker + PRUNE_MARKER.length) !== -1) return false\n const head = body.slice(0, marker)\n const tail = body.slice(marker + PRUNE_MARKER.length)\n if (head.length === 0 || tail.length === 0) return false\n const points = Array.from(anchor)\n const headPoints = Array.from(head)\n const tailPoints = Array.from(tail)\n if (headPoints.length + tailPoints.length >= points.length) return false\n return (\n points.slice(0, headPoints.length).join('') === head &&\n points.slice(-tailPoints.length).join('') === tail\n )\n}\n\n/**\n * The locator phrase every host spill notice carries.\n *\n * Both outer shapers end a rewrite with a parenthesised notice naming where the\n * complete result lives: `dsh-spill-policy` renders `(Omitted N bytes. Full\n * formatted result stored at: …)` and `dsh-tool-fs-search` renders `(Showing N\n * of M paths. Full sorted result stored at: …)`. The counts and the sentence\n * around them differ by shaper and result kind; the locator phrase is the part\n * both always include.\n */\nconst SPILL_LOCATION = ' stored at: '\n\n/**\n * Where a trailing host-shape spill footer starts, or `-1` when the body does\n * not end in one.\n *\n * The footer is a final parenthesised block introduced by a blank line, and the\n * locator phrase separates it from an ordinary parenthetical. This is a shape\n * check, not authentication: the identity evidence remains the anchor's own\n * head and tail, which the caller requires at the two ends of the rewritten\n * body.\n */\nfunction trailingSpillFooterStart(body: string): number {\n if (!body.endsWith(')')) return -1\n const start = body.lastIndexOf('\\n\\n(')\n if (start === -1) return -1\n const notice = body.slice(start + 2)\n if (!notice.includes(SPILL_LOCATION)) return -1\n // The notice must also name how much was dropped. A footer carrying only a\n // locator is not evidence that a shaper rewrote this receipt, and without a\n // count the only remaining identity check would be \"shares the first and last\n // window\" — the edited-then-re-read collision `prunedCarries` rejects.\n return OMITTED_BYTES.test(notice) ? start : -1\n}\n\n/** An omitted-byte notice: the only in-body evidence a shaper rewrote the middle. */\nconst OMITTED_BYTES = /\\([^)]*\\d[\\d,]*\\s*(?:bytes|characters)[^)]*\\)/i\n\n/**\n * Whether `core` is `anchor` rewritten by a foreign shaper.\n *\n * The anchor's head must sit at the very start and its tail at the very end of\n * the rewritten body, and a spill footer must be the rewrite's evidence: either\n * the trailing notice the caller stripped (`strippedFooter`), or one sitting\n * between the two windows. A full receipt that merely shares the two probes —\n * the edited-then-re-read collision `prunedCarries` exists to reject — has no\n * footer, and a wrapper that embeds the anchor does not start with its head, so\n * neither qualifies. The length guard rejects a body that is only the two\n * windows with nothing rewritten between them.\n */\nfunction foreignShaperCarries(\n core: string,\n anchor: string,\n head: string,\n tail: string,\n strippedFooter: boolean,\n): boolean {\n if (core === anchor) return false\n if (head.length > 0 && !core.startsWith(head)) return false\n if (tail.length > 0 && !core.endsWith(tail)) return false\n if (core.length <= head.length + tail.length) return false\n if (strippedFooter) return true\n const middle = core.slice(head.length, core.length - tail.length)\n const footerStart = middle.indexOf('\\n\\n(')\n if (footerStart === -1) return false\n const footerEnd = middle.indexOf(')', footerStart)\n return footerEnd !== -1 && middle.slice(footerStart, footerEnd + 1).includes(SPILL_LOCATION)\n}\n\n/**\n * Whether `body` still carries `anchor`, verbatim or as a verified in-place\n * rewrite.\n *\n * The host pruner replaces the middle of an oversized receipt with\n * `PRUNE_MARKER` while preserving a head and a tail; apply-mode projection\n * composes head line + head + spill footer + tail. Both keep the anchor's\n * beginning and end, so a body holding both probes *and* the rewrite's own\n * evidence is the same receipt rewritten in place.\n *\n * An outer shaper (`dsh-spill-policy` for non-`read`, `dsh-tool-fs-search` for\n * `glob`/`grep`) also keeps the head and tail but appends its footer after the\n * tail, so the model-visible body ends with the notice. That case is checked\n * twice: the trailing notice is stripped and our own projection is verified on\n * the remaining body, then the remaining body is accepted as a foreign rewrite\n * only when it still starts with the anchor's head and ends with its tail.\n *\n * Sharing the two probes alone is not identity: a file edited in the middle and\n * re-read produces a full receipt with the same 32-character head and tail but\n * a different body.\n *\n * Residual, accepted: for a foreign shaper's rewrite the middle cannot be\n * verified from the model-visible body — we keep neither the anchor's byte\n * length nor a digest of it, and the shaper's own window (120 code points) need\n * not equal our probe window. What is checked is the shape (head at index 0,\n * tail at the end, a spill notice naming both a location and an omitted-byte\n * count) and that the body is longer than the two windows. A re-spilled receipt\n * that happens to share both probes would be accepted; rejecting every foreign\n * rewrite instead would discard every spilled receipt, which is the common\n * case. Fail closed only where the shape does not hold. Accepting it would substitute against content the model no\n * longer holds, so a probe match must be accompanied by the pruner marker, our\n * projection's head line, or a spill footer. Anything else is a lost anchor\n * (fail closed).\n *\n * Probes are sliced by **code point**, exactly like `truncate`: a UTF-16 slice\n * can end on half a surrogate pair, and a lone surrogate is not a substring a\n * correctly projected body has to contain. Short anchors whose two windows\n * would cover the whole text get no probe treatment: at that size the exact\n * text either is present or the receipt is gone.\n */\nfunction carriesAnchor(\n body: string,\n anchor: string,\n probe: { head: number; tail: number },\n): boolean {\n if (body.includes(anchor)) return true\n const points = Array.from(anchor)\n const headLen = Math.min(probe.head, points.length)\n const tailLen = Math.min(probe.tail, points.length)\n if (headLen === 0 && tailLen === 0) return false\n if (points.length <= headLen + tailLen) return false\n const head = headLen > 0 ? points.slice(0, headLen).join('') : ''\n const tail = tailLen > 0 ? points.slice(-tailLen).join('') : ''\n const start = headLen > 0 ? body.indexOf(head) : 0\n if (headLen > 0 && start === -1) return false\n if (tailLen > 0 && body.indexOf(tail, start + headLen) === -1) return false\n if (prunedCarries(body, anchor) || ownProjectionCarries(body, anchor)) return true\n\n // An outer shaper's footer follows the rewrite, so the model-visible body\n // ends with the notice rather than with the anchor's tail. Verify the same\n // body with that notice removed; without one, the in-middle footer shape is\n // checked instead.\n const footerStart = trailingSpillFooterStart(body)\n const core = footerStart === -1 ? body : body.slice(0, footerStart)\n if (footerStart !== -1 && ownProjectionCarries(core, anchor)) return true\n return foreignShaperCarries(core, anchor, head, tail, footerStart !== -1)\n}\n\n/**\n * Why the decision's anchored receipts are no longer trustworthy, if they are.\n *\n * Marker precedence matches `invalidate`: any carried body that contains the\n * pruner literal means `pruned-reset`, because the pruner is the common case\n * and it leaves the receipt in place. Only when no anchor was pruned does a\n * missing carrier mean `compaction-reset` (the history was replaced by a\n * summary).\n *\n * A missing record, a record with no entries and a record whose shape cannot be\n * read are all unverifiable and therefore `compaction-reset` (row 28): the\n * commit that parked the decision writes anchors, so their absence is a failed\n * write, not a reason to substitute with zero verification. An empty anchor\n * string is a real value the check skips; `invalidate` treats an empty anchor\n * as a real value, and the stream hook has no receipt body to compare it with.\n */\nfunction anchorResetOf(\n anchors: ReceiptAnchors | undefined,\n messages: unknown,\n probe: { head: number; tail: number },\n): ResetCode | undefined {\n if (anchors == null) return 'compaction-reset'\n let record: unknown\n try {\n record = anchors.anchors\n } catch {\n return 'compaction-reset'\n }\n if (typeof record !== 'object' || record === null) return 'compaction-reset'\n\n const values = Object.values(record as Record<string, unknown>)\n if (values.length === 0) return 'compaction-reset'\n const texts = values.filter((text): text is string => typeof text === 'string' && text.length > 0)\n if (texts.length === 0) {\n // An empty anchor is a real value the check skips (it cannot be located in\n // any message). Any other unverifiable shape — an object from an older or\n // foreign anchor store — must fail closed instead: treating it as \"no\n // anchors\" would substitute on evidence this code cannot read.\n return values.every((value) => value === '') ? undefined : 'compaction-reset'\n }\n\n const bodies = messageTexts(messages)\n let compacted = false\n for (const anchor of texts) {\n if (looksPruned(anchor)) return 'pruned-reset'\n const carriers = bodies.filter((body) => carriesAnchor(body, anchor, probe))\n if (carriers.length === 0) {\n compacted = true\n continue\n }\n if (carriers.some((body) => looksPruned(body))) return 'pruned-reset'\n }\n return compacted ? 'compaction-reset' : undefined\n}\n\n/** The anchored step id a reset receipt names, never throwing on a foreign shape. */\nfunction anchorStepIdOf(anchors: ReceiptAnchors): string {\n try {\n return typeof anchors.stepId === 'string' ? anchors.stepId : 'root'\n } catch {\n return 'root'\n }\n}\n\n// ---------------------------------------------------------------------------\n// The synchronous decision\n// ---------------------------------------------------------------------------\n\n/** A decision to refuse the pending entry before it is synthesized. */\ninterface AbandonPlan {\n /** The entry this request refuses to synthesize. */\n entry: PendingEntry\n /** Drop the session's queue entry (turn rollover, reset, invisible scope). */\n clearQueue: boolean\n /** Drop the session's anchors (only a reset invalidates the evidence). */\n clearAnchors: boolean\n /** Reset receipt to write, when the anchored evidence was invalidated. */\n reset?: { code: ResetCode; stepId: string; turn: number }\n}\n\n/** What one request is going to do, decided synchronously. */\ntype StreamPlan =\n | {\n kind: 'pass'\n sessionId: string | undefined\n abandon?: AbandonPlan\n /**\n * Discard the session's decision-time usage mark even when no queue entry\n * is left to abandon. A stopped store passes every request through, so\n * the decision will never be synthesized and its mark must not settle a\n * later real request as if it had run.\n */\n discardMark?: boolean\n }\n | { kind: 'synthesize'; sessionId: string; entry: PendingEntry }\n\n/**\n * How many synthesized turns this session has already emitted in one turn.\n *\n * `post-execute` takes exactly one step per queue entry, so the budget's\n * `count()` is the number of steps paid for in the turn; this tally is how many\n * of them have been spent on synthesis. A second synthesis of one entry would\n * spend a step the budget never granted. The call ids are kept too: the\n * deterministic `callIdFor` makes a re-enqueued decision at the same\n * turn/step/candidate reuse one id, and the host would persist two `tool_use`\n * blocks with it.\n */\ninterface SynthesisTally {\n /** Host turn this tally belongs to. */\n turn: number\n /** Synthesized turns emitted in `turn`. */\n count: number\n /** Call ids already synthesized in `turn`. */\n callIds: Set<string>\n}\n\n/**\n * Per-session synthesis history, keyed by `HookDeps` first so two plugin\n * instances in one process cannot read each other's session. It holds one turn\n * per session and dies with the assembly; `clearSession` drops the session.\n */\nconst SYNTHESIS_TALLY = new WeakMap<HookDeps, Map<string, SynthesisTally>>()\n\n/** The session's synthesis tally, if this turn has one. */\nfunction synthesisTallyOf(deps: HookDeps, sessionId: string): SynthesisTally | undefined {\n try {\n return SYNTHESIS_TALLY.get(deps)?.get(sessionId)\n } catch {\n return undefined\n }\n}\n\n/** Count one synthesized turn, starting a new tally when the turn changed. */\nfunction recordSynthesis(deps: HookDeps, sessionId: string, turn: number, callId: string): void {\n try {\n let bySession = SYNTHESIS_TALLY.get(deps)\n if (bySession === undefined) {\n bySession = new Map()\n SYNTHESIS_TALLY.set(deps, bySession)\n }\n let tally = bySession.get(sessionId)\n if (tally === undefined || tally.turn !== turn) {\n tally = { turn, count: 0, callIds: new Set() }\n bySession.set(sessionId, tally)\n }\n tally.count += 1\n tally.callIds.add(callId)\n } catch {\n // A tally miss costs a duplicate guard, never this request.\n }\n}\n\n/** Drop one session's synthesis history at session end. */\nfunction forgetSynthesis(deps: HookDeps, sessionId: string): void {\n try {\n SYNTHESIS_TALLY.get(deps)?.delete(sessionId)\n } catch {\n // Same: the tally is a guard, not a precondition.\n }\n}\n\n/**\n * Whether the entry's step can no longer be honoured.\n *\n * Two independent facts make a still-live entry unhonourable: its deterministic\n * call id was already synthesized in this turn (a retry or a re-enqueue at one\n * step), or the turn's paid steps are already used up by earlier syntheses.\n * A budget that reports no spend at all is a fixture/legacy shape rather than\n * proof of a step; the call-id half still applies there.\n */\nfunction synthesisBlocked(\n deps: HookDeps,\n sessionId: string,\n entry: PendingEntry,\n turn: number,\n): boolean {\n const tally = synthesisTallyOf(deps, sessionId)\n const current = tally !== undefined && sameTurn(tally.turn, turn) ? tally : undefined\n if (current !== undefined && current.callIds.has(entry.callId)) return true\n const budget = sessionBudget(deps, sessionId)\n // Row 21: a wired budget that was not lent to this session is unpayable, not\n // \"no cap\". Only a completely unwired budget leaves the step unconstrained.\n if (budget === undefined) return budgetWired(deps)\n let spent: number\n try {\n spent = budget.count()\n } catch {\n return false\n }\n if (!Number.isFinite(spent) || spent <= 0) return false\n return (current?.count ?? 0) >= spent\n}\n\n/**\n * The rule order as pure, synchronous decision logic.\n *\n * Nothing here writes a receipt or takes a step: every check completes before\n * the first effect. `post-execute` already took the budget at the decision\n * point (obligation 2), so this function never touches the budget.\n */\nfunction resolveStreamPlan(\n deps: HookDeps,\n options: GenerateOptions | undefined,\n): StreamPlan {\n const sessionId = sessionIdOf(options)\n\n // The selector guard is the first rule and lives in `streamHook`, which\n // returns `next()` before this function runs: a selector request must not\n // even be observed, so it cannot become a plan.\n\n if (receiptsStopped(deps)) {\n // Fail-closed: the decision cannot be recorded, so it will never be\n // synthesized. Empty the queue and settle the decision-time mark even when\n // the queue entry is already gone (the dispatch side may have consumed it);\n // otherwise the mark would settle a later real request as a substitution.\n return passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false }, true)\n }\n\n if (sessionId === undefined) return { kind: 'pass', sessionId }\n\n if (!visibleSession(deps, sessionId)) {\n return passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false })\n }\n\n const entry = peekPending(deps, sessionId)\n if (entry === undefined) return { kind: 'pass', sessionId }\n\n // A blank call id cannot be dispatched and must not be \"repaired\" here: the\n // execute-side tamper check would compare a different id and reject silently.\n if (typeof entry.callId !== 'string' || entry.callId.trim().length === 0) {\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, clearQueue: true, clearAnchors: false },\n }\n }\n\n const turn = clockTurnOf(deps, sessionId)\n // The reset receipt pairs with the entry's own turn when the clock cannot\n // name a real one; a turn-0 commit still wrote (or failed to write) anchors.\n const resetTurn = turn ?? turnNumberOf(entry.turn)\n\n // Row 28: anchor evidence is checked before turn validity. A decision whose\n // anchors were never written (the commit's `set` failed), a store that holds\n // no record for a live entry, and a throwing read are all unverifiable;\n // dropping them as an ordinary stale entry would hide the lost evidence.\n // Intact anchors on a stale turn still take the silent abandon below: there\n // the decision is dead by identity, not because its evidence vanished.\n const anchorRead = anchorsOf(deps, sessionId)\n if (anchorRead.kind !== 'record') {\n return resetPlan(sessionId, entry, 'compaction-reset', 'root', resetTurn)\n }\n const reset = anchorResetOf(anchorRead.anchors, options?.messages, anchorProbe(deps))\n if (reset !== undefined) {\n return resetPlan(\n sessionId,\n entry,\n reset,\n anchorStepIdOf(anchorRead.anchors),\n resetTurn,\n )\n }\n\n if (turn === undefined || !sameTurn(entry.turn, turn)) {\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, clearQueue: true, clearAnchors: false },\n }\n }\n\n // Re-check the step immediately before synthesizing. The turn/step checks\n // above validate identity, not spend: a retried or re-enqueued request in the\n // same turn would otherwise emit a second substitute receipt with the same\n // call id, bypassing the per-turn budget the decision already consumed. The\n // entry is dropped through the ordinary abandon path so its usage mark is\n // settled as discarded rather than left to a later real request.\n if (synthesisBlocked(deps, sessionId, entry, turn)) {\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, clearQueue: true, clearAnchors: true },\n }\n }\n\n return { kind: 'synthesize', sessionId, entry }\n}\n\n/**\n * Abandon a decision whose anchored evidence cannot be verified.\n *\n * The reset receipt explains the lost anchor; the queue and anchors go with it,\n * and the usage mark is settled as discarded by `applyAbandon`.\n */\nfunction resetPlan(\n sessionId: string,\n entry: PendingEntry,\n code: ResetCode,\n stepId: string,\n turn: number,\n): StreamPlan {\n return {\n kind: 'pass',\n sessionId,\n abandon: {\n entry,\n clearQueue: true,\n clearAnchors: true,\n reset: { code, stepId, turn },\n },\n }\n}\n\n/**\n * A pass plan that abandons the session's pending entry, when one exists.\n *\n * `discardMark` makes the plan settle the usage mark even when no entry is\n * left; the stopped-store branch needs that because the dispatch side may\n * already have consumed the entry.\n */\nfunction passPlan(\n deps: HookDeps,\n sessionId: string | undefined,\n abandons: { clearQueue: boolean; clearAnchors: boolean },\n discardMark = false,\n): StreamPlan {\n if (sessionId === undefined) return { kind: 'pass', sessionId }\n const entry = peekPending(deps, sessionId)\n if (entry === undefined) return { kind: 'pass', sessionId, ...(discardMark ? { discardMark } : {}) }\n return {\n kind: 'pass',\n sessionId,\n abandon: { entry, ...abandons },\n ...(discardMark ? { discardMark } : {}),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Effects\n// ---------------------------------------------------------------------------\n\n/**\n * Consume the session's usage mark without reporting a saving.\n *\n * `markSubstituted` has no unmark: a mark left behind by an abandoned entry\n * would make the next real request settle a substitution that never ran\n * (obligation 5). `settle()` here is the discard, not a measurement. The parked\n * plan evidence goes with the mark: nothing will ever write its receipt.\n */\nexport function settleDiscarded(deps: HookDeps, sessionId: string): void {\n try {\n sessionUsage(deps, sessionId)?.settle()\n } catch {\n // A foreign ledger can only cost a measurement.\n }\n forgetEvidence(deps, sessionId)\n}\n\n/**\n * The facts of a synthesized turn that its later settlement needs.\n *\n * The settled receipt is written at the first real request after the\n * synthesized turn, when the queue entry is already gone. The evidence (plan,\n * guards) must survive until then, and so must the turn: the settled line pairs\n * with the synthesis turn, not with whichever request happened to settle it\n * (row 26).\n */\ninterface SynthesisFact {\n /** Host turn the synthesized turn answered. */\n turn: number\n /** Plan/guards evidence for the settled receipt, when the entry carried it. */\n evidence?: SubstitutionEvidence\n}\n\n/**\n * Plan/guards evidence parked between synthesis and settlement.\n *\n * Keyed by `HookDeps` first so two plugin instances in one process cannot read\n * each other's session, and a `WeakMap` lets the whole map die with the\n * assembly.\n */\nconst PENDING_EVIDENCE = new WeakMap<HookDeps, Map<string, SynthesisFact>>()\n\n/** Park the fact for the session's next settlement, replacing any earlier. */\nfunction rememberEvidence(deps: HookDeps, sessionId: string, fact: SynthesisFact): void {\n let bySession = PENDING_EVIDENCE.get(deps)\n if (bySession === undefined) {\n bySession = new Map()\n PENDING_EVIDENCE.set(deps, bySession)\n }\n bySession.set(sessionId, fact)\n}\n\n/** Take (and forget) the fact one settlement consumes. */\nfunction takeEvidence(deps: HookDeps, sessionId: string): SynthesisFact | undefined {\n const bySession = PENDING_EVIDENCE.get(deps)\n const fact = bySession?.get(sessionId)\n bySession?.delete(sessionId)\n return fact\n}\n\n/** Drop a fact that no settlement will ever consume. */\nfunction forgetEvidence(deps: HookDeps, sessionId: string): void {\n PENDING_EVIDENCE.get(deps)?.delete(sessionId)\n}\n\n/** Record the synthesis mark for the session's pairing. */\nfunction markSubstitutedFor(deps: HookDeps, sessionId: string, candidateId: string): void {\n try {\n sessionUsage(deps, sessionId)?.markSubstituted(candidateId)\n } catch {\n // A ledger miss costs a measurement, never this turn.\n }\n}\n\n/** The synth-time receipt: the event, before any measurement exists. */\nasync function appendSubstituteReceipt(\n deps: HookDeps,\n sessionId: string,\n entry: PendingEntry,\n): Promise<void> {\n const evidence = (entry as AuditedPendingEntry).evidence\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: turnNumberOf(entry.turn),\n stepId: 'root',\n kind: 'substitute',\n code: 'substituted',\n tool: entry.name,\n callId: entry.callId,\n candidateId: entry.candidateId,\n // G2: the plan the decision came from and the guards that qualified the\n // candidate, capped by `substitutionEvidence` before they reach the line.\n ...(evidence === undefined ? {} : evidence),\n // The synthesized call has no tool result yet; its name and bound args are\n // the evidence for why this turn asked for it.\n args: entry.args,\n preview: callPreview(entry.name, entry.args),\n // Measured only after the next real request; `'unknown'` never counts.\n saved_input_tokens: 'unknown',\n cache_hit_delta: null,\n output_tokens: 'unknown',\n })\n}\n\n/** Settle a pending mark at the first after-mark request and report it. */\nasync function settlePendingMark(deps: HookDeps, sessionId: string): Promise<void> {\n const ledger = sessionUsage(deps, sessionId)\n if (ledger === undefined) return\n\n let candidateId: string | undefined\n let settled: ReturnType<UsageLedger['settle']>\n try {\n const pending = ledger.pendingCandidateId()\n if (typeof pending !== 'string' || pending.length === 0) {\n // A parked fact without a mark can never be settled; drop it rather than\n // let a later, unrelated mark pick up this turn's evidence.\n forgetEvidence(deps, sessionId)\n return\n }\n candidateId = pending\n settled = ledger.settle()\n } catch {\n forgetEvidence(deps, sessionId)\n return\n }\n\n const fact = takeEvidence(deps, sessionId)\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n // Row 26: the synthesized turn is the substitution's turn; the request that\n // happens to settle it may already be the next one.\n turn: fact?.turn ?? clockTurnOf(deps, sessionId) ?? 0,\n stepId: 'root',\n kind: 'substitute-settled',\n code: 'substitute-settled',\n candidateId,\n // G2 applies to the settled line too: the goal and guards are the same\n // evidence the synth-time line carried, parked when that line was written.\n ...(fact?.evidence ?? {}),\n saved_input_tokens: settled.saved_input_tokens,\n // Row 7: the settled line carries both estimates — the upper input figure\n // and the lower whole-request figure from the plan's own request.\n avoided_total_tokens: settled.avoided_total_tokens,\n cache_hit_delta: settled.cache_hit_delta,\n output_tokens: settled.output_tokens,\n })\n}\n\n/** Map one `usage` chunk onto the ledger's count names (appendix §7). */\nfunction recordUsage(deps: HookDeps, sessionId: string, usage: TokenUsage | undefined): void {\n if (usage === undefined || usage === null) return\n const ledger = sessionUsage(deps, sessionId)\n if (ledger === undefined) return\n try {\n ledger.request({\n input: usage.inputTokens,\n cacheRead: usage.cacheReadTokens ?? 0,\n output: usage.outputTokens,\n })\n } catch {\n // A foreign ledger can only cost a measurement.\n }\n}\n\n/**\n * Store the plan a real response carried, or drop the old one when it carried\n * none.\n *\n * The protocol tells the model to omit the block when unsure, so a response\n * that does not contain a valid plan is also the model withdrawing the previous\n * one. Keeping the old plan would let it fire against a much later receipt the\n * model never wrote it for. A malformed block is likewise not a plan.\n */\nfunction rememberPlan(deps: HookDeps, sessionId: string | undefined, text: string): void {\n if (sessionId === undefined) return\n try {\n const plans = deps.plans\n if (plans == null || typeof plans.set !== 'function') return\n const parsed = text.length === 0 ? { error: 'no-plan' as const } : parsePlan(text)\n if ('plan' in parsed) plans.set(sessionId, parsed.plan)\n else plans.delete(sessionId)\n } catch {\n // A plan that cannot be stored only costs a later decision.\n }\n}\n\n/**\n * Abandon the pending entry: settle the mark, drop what the decision owned and\n * write the reset receipt that explains it.\n */\nasync function applyAbandon(\n deps: HookDeps,\n sessionId: string,\n abandon: AbandonPlan,\n): Promise<void> {\n settleDiscarded(deps, sessionId)\n if (abandon.clearQueue) clearPending(deps, sessionId)\n if (abandon.clearAnchors) clearAnchors(deps, sessionId)\n // A plan that produced this abandoned decision must not survive to drive a\n // later receipt, for either reset kind (and for the non-reset abandons too).\n clearPlan(deps, sessionId)\n if (abandon.reset === undefined) return\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n turn: abandon.reset.turn,\n stepId: abandon.reset.stepId,\n kind: 'reset',\n code: abandon.reset.code,\n tool: abandon.entry.name,\n callId: abandon.entry.callId,\n candidateId: abandon.entry.candidateId,\n })\n}\n\n/**\n * The ordinary turn: observe the real stream.\n *\n * `next()` has already been called by the hook body, so the upstream iterable\n * exists before the generator starts. Usage is mapped and a pending mark is\n * settled at the `usage` chunk (which the host emits before `finish`); text is\n * accumulated for `parsePlan`. Settlement also runs in `finally`: an upstream\n * that throws before the `usage` chunk (a provider 500 mid-stream) or a\n * consumer that cancels the stream still ends the request, and a mark left\n * pending there would pair with the next, unrelated request and report that\n * request's tokens as a saving. An errored stream has no usable sample, so\n * `settle()` reports `'unknown'`. The plan store is still reached only on\n * normal completion, so a partial response never becomes a plan.\n */\nasync function* observeBranch(\n deps: HookDeps,\n sessionId: string | undefined,\n upstream: AsyncIterable<StreamChunk>,\n): AsyncGenerator<StreamChunk> {\n let text = ''\n try {\n for await (const chunk of upstream) {\n if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text\n if (chunk?.type === 'usage' && sessionId !== undefined) {\n recordUsage(deps, sessionId, chunk.usage)\n await settlePendingMark(deps, sessionId)\n }\n yield chunk\n }\n } finally {\n // The host emits `usage` before `finish`, so this is normally a no-op; a\n // route that omits the chunk still ends the request, and the mark must be\n // consumed there rather than attributed to a later request (`'unknown'`,\n // which status does not count).\n if (sessionId !== undefined) await settlePendingMark(deps, sessionId)\n }\n rememberPlan(deps, sessionId, text)\n}\n\n/**\n * The synthesized turn.\n *\n * The plugin answers instead of the model, so `upstream` is only a fallback:\n * the hook body resolved it synchronously at the waterfall point, before this\n * generator runs, and it stays untouched when the entry is still live. The\n * entry is re-read with `peek` (never `take`) so it survives to\n * `tools/execute`; if it vanished between the synchronous decision and the\n * first generator step, the mark is discarded and the real model answers,\n * because a substitution that cannot be dispatched must not be faked.\n *\n * `upstream` is absent only when the host's `next()` itself threw while the\n * hook body was resolving it; a host that cannot produce an upstream has no\n * fallback to offer, so the vanished entry ends with an empty stream rather\n * than a synthesized call no dispatch can check.\n */\nasync function* synthesizeBranch(\n deps: HookDeps,\n sessionId: string,\n entry: PendingEntry,\n upstream: AsyncIterable<StreamChunk> | undefined,\n): AsyncGenerator<StreamChunk> {\n const current = peekPending(deps, sessionId)\n if (current === undefined || current.callId !== entry.callId) {\n settleDiscarded(deps, sessionId)\n if (upstream !== undefined) yield* observeBranch(deps, sessionId, upstream)\n return\n }\n\n markSubstitutedFor(deps, sessionId, current.candidateId)\n // Park the plan evidence and the synthesis turn for the settled line, which\n // runs at the next real request after this entry has left the queue.\n const evidence = (current as AuditedPendingEntry).evidence\n const turn = turnNumberOf(current.turn)\n rememberEvidence(deps, sessionId, {\n turn,\n ...(evidence === undefined ? {} : { evidence }),\n })\n // Row 27: mirror the synthesis fact now, not when `tools/execute` accepts the\n // dispatch. A call denied by `tools/pre-execute` never reaches that hook, and\n // a rollover must still report the model round this turn skipped. The mirror\n // only feeds the settle path; it never claims a measured saving.\n deps.noteSynthesis?.(sessionId, turn, current.candidateId, evidence)\n await appendSubstituteReceipt(deps, sessionId, current)\n yield* synthesizeTurn(current)\n}\n\n// ---------------------------------------------------------------------------\n// The exported hook and session-end cleanup\n// ---------------------------------------------------------------------------\n\n/**\n * Answer a pass decision: abandon what the decision owned, then observe the\n * real stream.\n *\n * `upstream` is resolved by the hook body at the waterfall point; the generator\n * only delays effects and consumption.\n */\nfunction observedPass(\n deps: HookDeps,\n plan: Extract<StreamPlan, { kind: 'pass' }>,\n upstream: AsyncIterable<StreamChunk>,\n): AsyncIterable<StreamChunk> {\n return (async function* (): AsyncGenerator<StreamChunk> {\n if (plan.sessionId !== undefined) {\n // Order matters only for evidence: the discard drops the parked\n // plan/guards, and `applyAbandon` then clears the rest. Both settle\n // calls are idempotent.\n if (plan.discardMark === true) settleDiscarded(deps, plan.sessionId)\n if (plan.abandon !== undefined) await applyAbandon(deps, plan.sessionId, plan.abandon)\n }\n yield* observeBranch(deps, plan.sessionId, upstream)\n })()\n}\n\n/**\n * Build the `llm/stream` listener.\n *\n * Returns a **synchronous** function returning an `AsyncIterable`; see the\n * module header for why an `async` function here breaks every request. Any\n * `purpose`-tagged call (selector, compaction, session-title) returns `next()`\n * untouched: never observed, never substituted. Every real request is decided\n * synchronously by {@link resolveStreamPlan} and then answered by a generator.\n *\n * The upstream iterator is resolved **at the waterfall point on every path**,\n * before any generator body runs. The host's terminal is a lazy async iterable\n * (starting it is what calls the model), so resolving it on the synthesis path\n * costs nothing; it is only consumed if the pending entry vanished and the real\n * model has to answer. Resolving it lazily inside the generator would resume a\n * waterfall the host may already have moved past.\n */\nexport function streamHook(\n deps: HookDeps,\n): (options: GenerateOptions, next: () => AsyncIterable<StreamChunk>) => AsyncIterable<StreamChunk> {\n return (options, next) => {\n // Any purpose-tagged request is auxiliary (appendix §1): the selector, the\n // compaction summarizer, the session-title model. They share the session\n // id but are not conversation steps, so they pass through raw: no\n // substitution, no usage observation, no settlement, no plan rollover.\n if (options?.purpose !== undefined) return next()\n\n const sessionId = sessionIdOf(options)\n if (sessionId !== undefined) {\n const turn = clockTurnOf(deps, sessionId)\n if (turn !== undefined) {\n let rolledOver = false\n try {\n rolledOver = deps.sessions?.notePlanTurn(sessionId, turn) === true\n } catch {\n rolledOver = false\n }\n if (rolledOver) clearPlan(deps, sessionId)\n }\n }\n\n let plan: StreamPlan\n try {\n plan = resolveStreamPlan(deps, options)\n } catch {\n // A bug in our own decision logic must not take the model request down,\n // but it must still take the ordinary pass path: the decision-time mark\n // has to be discarded here or this real request would settle a\n // substitution that never ran. Clearing the queue is the same fail-closed\n // answer — no decision was made.\n try {\n plan = passPlan(deps, sessionId, { clearQueue: true, clearAnchors: false }, true)\n } catch {\n plan = { kind: 'pass', sessionId, discardMark: true }\n }\n }\n\n // Resolve the upstream iterator before any branch. The real host's terminal\n // is an async generator, so this starts no model call; it only fixes which\n // request the fallbacks observe. A host whose `next()` throws was already\n // failing on the pass path, so that throw is preserved there; the synthesis\n // path proceeds without a fallback instead.\n // Count a synthesis decision before the generator runs: an unconsumed\n // stream or a vanished entry must still not let the same step be\n // synthesized twice. This runs before `next()` too, so a host whose\n // terminal throws cannot reopen the same step.\n if (plan.kind === 'synthesize') {\n const turn = clockTurnOf(deps, plan.sessionId) ?? turnNumberOf(plan.entry.turn)\n recordSynthesis(deps, plan.sessionId, turn, plan.entry.callId)\n }\n\n let upstream: AsyncIterable<StreamChunk> | undefined\n try {\n upstream = next()\n } catch (error) {\n if (plan.kind !== 'synthesize') throw error\n return synthesizeBranch(deps, plan.sessionId, plan.entry, undefined)\n }\n\n if (plan.kind === 'synthesize') {\n return synthesizeBranch(deps, plan.sessionId, plan.entry, upstream)\n }\n\n return observedPass(deps, plan, upstream)\n }\n}\n\n/**\n * Drop every per-session trace the plugin keeps for `sessionId`.\n *\n * This is the session-end cleanup `src/index.ts` calls from its\n * `session/disposed` listener: the receipt/dispatch store ships its own\n * `clear`, but it does not own the queue, the anchors, the plan map or the\n * per-session runtime, so the caller would otherwise have to know four separate\n * clears. A pending usage mark is settled first so a mark cannot outlive the\n * session it belongs to, and the shared-instance loans this session holds are\n * released so a disposed owner does not refuse every later session forever.\n */\nexport function clearSession(deps: HookDeps, sessionId: string): void {\n settleDiscarded(deps, sessionId)\n clearPending(deps, sessionId)\n clearAnchors(deps, sessionId)\n clearPlan(deps, sessionId)\n forgetSynthesis(deps, sessionId)\n try {\n // Projection locators are session-scoped evidence: a disposed session must\n // not leave its spill paths behind for the next session id to inherit.\n deps.retrievals?.clear(sessionId)\n } catch {\n // Same: each clear is independent.\n }\n try {\n deps.sessionState?.clear(sessionId)\n } catch {\n // Same: each clear is independent.\n }\n try {\n deps.sessions?.clear(sessionId)\n } catch {\n // Same.\n }\n releaseSharedLoans(deps, sessionId)\n // The rollover path mirrors an accepted dispatch so a late tool result can\n // still settle a substitution that ran. A disposed session has no late\n // result coming, so the mirror would otherwise sit in the per-deps map for\n // the plugin's lifetime — one entry per disposed session.\n try {\n deps.clearAcceptedDispatch?.(sessionId)\n } catch {\n // A disposal hook that throws must not abort the rest of the teardown.\n }\n}\n"]}