dsh-boost 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +476 -0
  4. package/README.md +408 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +276 -0
  43. package/dist/hooks/llm-stream.js +1008 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +247 -0
  49. package/dist/hooks/post-execute.js +1776 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +18 -0
  64. package/dist/host/root.js +43 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +866 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +367 -0
  100. package/dist/tools/boost.js +768 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +113 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"llm-stream.js","sourceRoot":"","sources":["../../src/hooks/llm-stream.ts"],"names":[],"mappings":"AAiKA,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,MAAM,uBAAuB,CAAA;AAEnD,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;AAC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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. 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).\n * 6. Anchors intact. `ReceiptAnchors` has no turn field, so `entry.turn` being\n * current is what makes the anchors current; only then is detection run\n * against `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 * 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** 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, before prompt assembly, 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; only `agent/request` warms the scope\n * judgement.\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 and the runtime entry, all dropped together (obligation 10). No map is\n * 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 } 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 the shared fallback runtime.\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. The first session to arrive keeps the loan; every other session gets\n * `undefined`, which each caller already reads as \"no substitution\" (fail\n * closed), and the warning is emitted once per deps object rather than per call.\n */\nconst fallbackOwner = new WeakMap<object, { sessionId: string; warned: boolean }>()\n\n/** Whether the shared fallback runtime may serve this session. */\nfunction mayBorrowShared(deps: HookDeps, sessionId: string): boolean {\n const held = fallbackOwner.get(deps)\n if (held === undefined) {\n fallbackOwner.set(deps, { sessionId, warned: false })\n return true\n }\n if (held.sessionId === sessionId) return true\n if (!held.warned) {\n held.warned = true\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/**\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, sessionId) ? deps.clock : 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, sessionId) ? deps.budget : 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, sessionId) ? deps.usage : undefined\n}\n\n/** The session's anchors without ever failing the request. */\nfunction anchorsOf(deps: HookDeps, sessionId: string): ReceiptAnchors | undefined {\n try {\n return deps.anchors?.get(sessionId)\n } catch {\n return undefined\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` 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 looksPruned(body) || 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). No anchors at all is vacuously intact: `post-execute` always writes\n * them with a commit, but a missing evidence store must not block substitution\n * forever.\n *\n * An empty anchor cannot be located in any message and is skipped; `invalidate`\n * treats an empty anchor as a real value, but the stream hook has no receipt\n * body to compare it with, and refusing every substitution on one empty tool\n * result would be worse than the uncertainty.\n */\nfunction anchorResetOf(\n anchors: ReceiptAnchors | undefined,\n messages: unknown,\n probe: { head: number; tail: number },\n): ResetCode | undefined {\n if (anchors == null) return undefined\n const record: unknown = anchors.anchors\n if (typeof record !== 'object' || record === null) return undefined\n\n const values = Object.values(record as Record<string, unknown>)\n if (values.length === 0) return undefined\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// ---------------------------------------------------------------------------\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 if (budget === undefined) return false\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 const turn = clockTurnOf(deps, sessionId)\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 // 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 anchors = anchorsOf(deps, sessionId)\n const reset = anchorResetOf(anchors, options?.messages, anchorProbe(deps))\n if (reset !== undefined) {\n return {\n kind: 'pass',\n sessionId,\n abandon: {\n entry,\n clearQueue: true,\n clearAnchors: true,\n reset: {\n code: reset,\n stepId: typeof anchors?.stepId === 'string' ? anchors.stepId : 'root',\n turn: turn,\n },\n },\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 * 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 * Plan/guards evidence parked between synthesis and settlement.\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 synth-time\n * receipt has it from the entry, this park hands it to the settle. Keyed by\n * `HookDeps` first so two plugin instances in one process cannot read each\n * other's session, and a `WeakMap` lets the whole map die with the assembly.\n */\nconst PENDING_EVIDENCE = new WeakMap<HookDeps, Map<string, SubstitutionEvidence>>()\n\n/** Park the evidence for the session's next settlement, replacing any earlier. */\nfunction rememberEvidence(deps: HookDeps, sessionId: string, evidence: SubstitutionEvidence): 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, evidence)\n}\n\n/** Take (and forget) the evidence one settlement consumes. */\nfunction takeEvidence(deps: HookDeps, sessionId: string): SubstitutionEvidence | undefined {\n const bySession = PENDING_EVIDENCE.get(deps)\n const evidence = bySession?.get(sessionId)\n bySession?.delete(sessionId)\n return evidence\n}\n\n/** Drop evidence 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) return\n candidateId = pending\n settled = ledger.settle()\n } catch {\n return\n }\n\n await appendReceipt(deps, {\n version: 1,\n ts: new Date().toISOString(),\n sessionId,\n 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 ...(takeEvidence(deps, sessionId) ?? {}),\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`. A consumer that cancels the stream never reaches\n * the plan store, because the code after the loop only runs on normal\n * completion.\n */\nasync function* observeBranch(\n deps: HookDeps,\n sessionId: string | undefined,\n upstream: AsyncIterable<StreamChunk>,\n): AsyncGenerator<StreamChunk> {\n let text = ''\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 // 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 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 for the settled line, which runs at the next real\n // request after this entry has left the queue.\n const evidence = (current as AuditedPendingEntry).evidence\n if (evidence !== undefined) rememberEvidence(deps, sessionId, 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.\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}\n"]}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * One decided substitution waiting for the model turn that will carry it.
3
+ *
4
+ * `args` is the already-validated argument tree the tool must receive. `turn`
5
+ * and `step` accept number or string because the host carries numeric indexes
6
+ * while receipts often use strings; the JSON array in `callIdFor` normalises
7
+ * both forms of the same value to one identity.
8
+ *
9
+ * Treat an entry as immutable once it is queued. The queue hands out the stored
10
+ * object by reference, and mutating `args` after the decision would make the
11
+ * admission receipt describe arguments different from the ones dispatched.
12
+ */
13
+ export interface PendingEntry {
14
+ /** Id shared by the synthesized tool call and the arriving dispatch. */
15
+ callId: string;
16
+ /** Plan candidate this call was substituted for. */
17
+ candidateId: string;
18
+ /** Tool name to invoke. */
19
+ name: string;
20
+ /** Validated argument object; serialised once by the synthesized turn. */
21
+ args: Record<string, unknown>;
22
+ /** Host turn the decision belongs to (number or already-stringified form). */
23
+ turn: number | string;
24
+ /** Host step within `turn` (number or already-stringified form); part of the call id. */
25
+ step: number | string;
26
+ }
27
+ /**
28
+ * At most one pending substitution per session.
29
+ *
30
+ * `set` overwrites, because a second decision in the same session supersedes
31
+ * the first: the earlier call can no longer arrive (its turn is over), and
32
+ * keeping it would make the tamper check compare against a stale id. `take`
33
+ * removes and returns; `peek` only reads. Clearing an absent session is a
34
+ * no-op, so callers do not need to know whether a decision was parked.
35
+ *
36
+ * **Reference semantics.** `set` stores the caller's object and `peek`/`take`
37
+ * return that same object, never a copy. Own it once queued: T23b builds the
38
+ * entry from the admitted candidate and must not mutate `args` afterwards, or
39
+ * the admission receipt will describe a call different from the one that runs.
40
+ *
41
+ * **Lifetime.** Entries leave only through `take` or `clear`; there is no
42
+ * expiry timer and no session hook here. A session that aborts between
43
+ * `tools/post-execute` and the next `llm/stream` therefore parks its entry for
44
+ * the process lifetime, so the owning hook must `clear` at session end. Failing
45
+ * to clear costs memory and nothing else: the execute hook only intervenes when
46
+ * the arriving call's `callId` equals the entry's, and a call with any other id
47
+ * passes through untouched, so a stale entry can neither reject an ordinary call
48
+ * nor be matched by one. The parked `args` are still a leak.
49
+ */
50
+ export declare class PendingQueue {
51
+ private readonly bySession;
52
+ /** Park `e` as the pending substitution for `sessionId`, replacing any earlier entry. */
53
+ set(sessionId: string, e: PendingEntry): void;
54
+ /** Remove and return the pending entry for `sessionId`, if any. */
55
+ take(sessionId: string): PendingEntry | undefined;
56
+ /** The pending entry for `sessionId`, without removing it. */
57
+ peek(sessionId: string): PendingEntry | undefined;
58
+ /** Drop the pending entry for `sessionId`; an absent session is a no-op. */
59
+ clear(sessionId: string): void;
60
+ /** Number of sessions with a pending entry (not the number of calls ever set). */
61
+ size(): number;
62
+ }
63
+ /**
64
+ * The deterministic id for one candidate at one step of one turn in one session.
65
+ *
66
+ * Exactly the first 16 hex characters of
67
+ * `sha256(JSON.stringify([sessionId, String(turn), String(step), candidateId]))`.
68
+ * Sixteen hex characters is 64 bits, far beyond any collision a session can
69
+ * produce, while keeping the id short enough to read in a receipt.
70
+ *
71
+ * **Encoding.** The four identity components are hashed as a JSON array, not
72
+ * joined with `'/'`. With a join, `('s', '1/2', 0, 'c')` and
73
+ * `('s', '1', 0, '2/c')` would hash identically: a `/` inside a component
74
+ * impersonates the separator.
75
+ * JSON quotes each string and delimits the elements, so no component can spill
76
+ * into another. `turn` and `step` are stringified first, so the host's numeric
77
+ * index and a receipt's string form of the same value name one id — the
78
+ * original `number | string` normalisation is preserved.
79
+ *
80
+ * The array also carries `step`, which the old tuple omitted: the same
81
+ * candidate committed twice in one turn must receive different ids, or the host
82
+ * persists two assistant `tool_use` blocks with one id and Anthropic-style
83
+ * providers reject the request.
84
+ *
85
+ * Stable across processes because the input is fully spelled out and the hash
86
+ * is SHA-256; idempotent for the same inputs; different for a different
87
+ * session, turn, step, or candidate.
88
+ */
89
+ export declare function callIdFor(sessionId: string, turn: string | number, step: string | number, candidateId: string): string;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The pending substitution queue and the deterministic call id.
3
+ *
4
+ * When the plugin decides to answer a model request itself, the decision is
5
+ * made in `tools/post-execute` and the synthesized turn is streamed by the
6
+ * `llm/stream` listener later. The two are separated by one host round trip, so
7
+ * the decision must be parked somewhere between them: that is this queue.
8
+ *
9
+ * The queue holds **one entry per session**, keyed by `sessionId` — never by
10
+ * `callId`. The host dispatches the synthesized tool call only after the stream
11
+ * ends, so the execute-side tamper check looks the entry up by session and then
12
+ * compares `entry.callId` with `exec.callId` itself. Keying by `callId` here
13
+ * would make that lookup return `undefined` for every call and silently disable
14
+ * the guard (appendix §7).
15
+ *
16
+ * `callIdFor` is the only producer of a call id: sixteen hex characters of
17
+ * `sha256(JSON.stringify([sessionId, String(turn), String(step), candidateId]))`.
18
+ * The JSON array is deliberate: a `'/'` join lets one component impersonate a
19
+ * separator (`('s', '1/2', 0, 'c')` and `('s', '1', 0, '2/c')` would hash the
20
+ * same), and a flat tuple cannot carry `step` without that same ambiguity.
21
+ * Step is part of the identity because the host persists every assistant
22
+ * `tool_use` block with its id: the same candidate committed at two steps of
23
+ * one turn must not reuse one id, or the provider rejects the duplicated id.
24
+ * The id is pure and stable across processes, so a receipt written in one
25
+ * process names the same call in the next.
26
+ *
27
+ * Everything here is a plain `Map` and a hash: no persistence, timers, host
28
+ * calls, or I/O.
29
+ *
30
+ * @module dsh-boost/hooks/pending
31
+ */
32
+ import { createHash } from 'node:crypto';
33
+ /**
34
+ * At most one pending substitution per session.
35
+ *
36
+ * `set` overwrites, because a second decision in the same session supersedes
37
+ * the first: the earlier call can no longer arrive (its turn is over), and
38
+ * keeping it would make the tamper check compare against a stale id. `take`
39
+ * removes and returns; `peek` only reads. Clearing an absent session is a
40
+ * no-op, so callers do not need to know whether a decision was parked.
41
+ *
42
+ * **Reference semantics.** `set` stores the caller's object and `peek`/`take`
43
+ * return that same object, never a copy. Own it once queued: T23b builds the
44
+ * entry from the admitted candidate and must not mutate `args` afterwards, or
45
+ * the admission receipt will describe a call different from the one that runs.
46
+ *
47
+ * **Lifetime.** Entries leave only through `take` or `clear`; there is no
48
+ * expiry timer and no session hook here. A session that aborts between
49
+ * `tools/post-execute` and the next `llm/stream` therefore parks its entry for
50
+ * the process lifetime, so the owning hook must `clear` at session end. Failing
51
+ * to clear costs memory and nothing else: the execute hook only intervenes when
52
+ * the arriving call's `callId` equals the entry's, and a call with any other id
53
+ * passes through untouched, so a stale entry can neither reject an ordinary call
54
+ * nor be matched by one. The parked `args` are still a leak.
55
+ */
56
+ export class PendingQueue {
57
+ bySession = new Map();
58
+ /** Park `e` as the pending substitution for `sessionId`, replacing any earlier entry. */
59
+ set(sessionId, e) {
60
+ this.bySession.set(sessionId, e);
61
+ }
62
+ /** Remove and return the pending entry for `sessionId`, if any. */
63
+ take(sessionId) {
64
+ const pending = this.bySession.get(sessionId);
65
+ if (pending === undefined)
66
+ return undefined;
67
+ this.bySession.delete(sessionId);
68
+ return pending;
69
+ }
70
+ /** The pending entry for `sessionId`, without removing it. */
71
+ peek(sessionId) {
72
+ return this.bySession.get(sessionId);
73
+ }
74
+ /** Drop the pending entry for `sessionId`; an absent session is a no-op. */
75
+ clear(sessionId) {
76
+ this.bySession.delete(sessionId);
77
+ }
78
+ /** Number of sessions with a pending entry (not the number of calls ever set). */
79
+ size() {
80
+ return this.bySession.size;
81
+ }
82
+ }
83
+ /**
84
+ * The deterministic id for one candidate at one step of one turn in one session.
85
+ *
86
+ * Exactly the first 16 hex characters of
87
+ * `sha256(JSON.stringify([sessionId, String(turn), String(step), candidateId]))`.
88
+ * Sixteen hex characters is 64 bits, far beyond any collision a session can
89
+ * produce, while keeping the id short enough to read in a receipt.
90
+ *
91
+ * **Encoding.** The four identity components are hashed as a JSON array, not
92
+ * joined with `'/'`. With a join, `('s', '1/2', 0, 'c')` and
93
+ * `('s', '1', 0, '2/c')` would hash identically: a `/` inside a component
94
+ * impersonates the separator.
95
+ * JSON quotes each string and delimits the elements, so no component can spill
96
+ * into another. `turn` and `step` are stringified first, so the host's numeric
97
+ * index and a receipt's string form of the same value name one id — the
98
+ * original `number | string` normalisation is preserved.
99
+ *
100
+ * The array also carries `step`, which the old tuple omitted: the same
101
+ * candidate committed twice in one turn must receive different ids, or the host
102
+ * persists two assistant `tool_use` blocks with one id and Anthropic-style
103
+ * providers reject the request.
104
+ *
105
+ * Stable across processes because the input is fully spelled out and the hash
106
+ * is SHA-256; idempotent for the same inputs; different for a different
107
+ * session, turn, step, or candidate.
108
+ */
109
+ export function callIdFor(sessionId, turn, step, candidateId) {
110
+ return createHash('sha256')
111
+ .update(JSON.stringify([sessionId, String(turn), String(step), candidateId]))
112
+ .digest('hex')
113
+ .slice(0, 16);
114
+ }
115
+ //# sourceMappingURL=pending.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pending.js","sourceRoot":"","sources":["../../src/hooks/pending.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AA6BxC;;;;;;;;;;;;;;;;;;;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\n * When the plugin decides to answer a model request itself, the decision is\n * made in `tools/post-execute` and the synthesized turn is streamed by the\n * `llm/stream` listener later. The two are separated by one host round trip, so\n * the decision must be parked somewhere between them: that is this queue.\n *\n * The queue holds **one entry per session**, keyed by `sessionId` — never by\n * `callId`. The host dispatches the synthesized tool call only after the stream\n * ends, so the execute-side tamper check looks the entry up by session and then\n * compares `entry.callId` with `exec.callId` itself. Keying by `callId` here\n * would make that lookup return `undefined` for every call and silently disable\n * the guard (appendix §7).\n *\n * `callIdFor` is the only producer of a call id: sixteen hex characters of\n * `sha256(JSON.stringify([sessionId, String(turn), String(step), candidateId]))`.\n * The JSON array is deliberate: a `'/'` join lets one component impersonate a\n * separator (`('s', '1/2', 0, 'c')` and `('s', '1', 0, '2/c')` would hash the\n * same), and a flat tuple cannot carry `step` without that same ambiguity.\n * Step is part of the identity because the host persists every assistant\n * `tool_use` block with its id: the same candidate committed at two steps of\n * one turn must not reuse one id, or the provider rejects the duplicated id.\n * The id is pure and stable across processes, so a receipt written in one\n * process names the same call in the next.\n *\n * Everything here is a plain `Map` and a hash: no persistence, timers, host\n * calls, or I/O.\n *\n * @module dsh-boost/hooks/pending\n */\nimport { createHash } from 'node:crypto'\n\n/**\n * One decided substitution waiting for the model turn that will carry it.\n *\n * `args` is the already-validated argument tree the tool must receive. `turn`\n * and `step` accept number or string because the host carries numeric indexes\n * while receipts often use strings; the JSON array in `callIdFor` normalises\n * both forms of the same value to one identity.\n *\n * Treat an entry as immutable once it is queued. The queue hands out the stored\n * object by reference, and mutating `args` after the decision would make the\n * admission receipt describe arguments different from the ones dispatched.\n */\nexport interface PendingEntry {\n /** Id shared by the synthesized tool call and the arriving dispatch. */\n callId: string\n /** Plan candidate this call was substituted for. */\n candidateId: string\n /** Tool name to invoke. */\n name: string\n /** Validated argument object; serialised once by the synthesized turn. */\n args: Record<string, unknown>\n /** Host turn the decision belongs to (number or already-stringified form). */\n turn: number | string\n /** Host step within `turn` (number or already-stringified form); part of the call id. */\n step: number | string\n}\n\n/**\n * At most one pending substitution per session.\n *\n * `set` overwrites, because a second decision in the same session supersedes\n * the first: the earlier call can no longer arrive (its turn is over), and\n * keeping it would make the tamper check compare against a stale id. `take`\n * removes and returns; `peek` only reads. Clearing an absent session is a\n * no-op, so callers do not need to know whether a decision was parked.\n *\n * **Reference semantics.** `set` stores the caller's object and `peek`/`take`\n * return that same object, never a copy. Own it once queued: T23b builds the\n * entry from the admitted candidate and must not mutate `args` afterwards, or\n * the admission receipt will describe a call different from the one that runs.\n *\n * **Lifetime.** Entries leave only through `take` or `clear`; there is no\n * expiry timer and no session hook here. A session that aborts between\n * `tools/post-execute` and the next `llm/stream` therefore parks its entry for\n * the process lifetime, so the owning hook must `clear` at session end. Failing\n * to clear costs memory and nothing else: the execute hook only intervenes when\n * the arriving call's `callId` equals the entry's, and a call with any other id\n * passes through untouched, so a stale entry can neither reject an ordinary call\n * nor be matched by one. The parked `args` are still a leak.\n */\nexport class PendingQueue {\n private readonly bySession = new Map<string, PendingEntry>()\n\n /** Park `e` as the pending substitution for `sessionId`, replacing any earlier entry. */\n set(sessionId: string, e: PendingEntry): void {\n this.bySession.set(sessionId, e)\n }\n\n /** Remove and return the pending entry for `sessionId`, if any. */\n take(sessionId: string): PendingEntry | undefined {\n const pending = this.bySession.get(sessionId)\n if (pending === undefined) return undefined\n this.bySession.delete(sessionId)\n return pending\n }\n\n /** The pending entry for `sessionId`, without removing it. */\n peek(sessionId: string): PendingEntry | undefined {\n return this.bySession.get(sessionId)\n }\n\n /** Drop the pending entry for `sessionId`; an absent session is a no-op. */\n clear(sessionId: string): void {\n this.bySession.delete(sessionId)\n }\n\n /** Number of sessions with a pending entry (not the number of calls ever set). */\n size(): number {\n return this.bySession.size\n }\n}\n\n/**\n * The deterministic id for one candidate at one step of one turn in one session.\n *\n * Exactly the first 16 hex characters of\n * `sha256(JSON.stringify([sessionId, String(turn), String(step), candidateId]))`.\n * Sixteen hex characters is 64 bits, far beyond any collision a session can\n * produce, while keeping the id short enough to read in a receipt.\n *\n * **Encoding.** The four identity components are hashed as a JSON array, not\n * joined with `'/'`. With a join, `('s', '1/2', 0, 'c')` and\n * `('s', '1', 0, '2/c')` would hash identically: a `/` inside a component\n * impersonates the separator.\n * JSON quotes each string and delimits the elements, so no component can spill\n * into another. `turn` and `step` are stringified first, so the host's numeric\n * index and a receipt's string form of the same value name one id — the\n * original `number | string` normalisation is preserved.\n *\n * The array also carries `step`, which the old tuple omitted: the same\n * candidate committed twice in one turn must receive different ids, or the host\n * persists two assistant `tool_use` blocks with one id and Anthropic-style\n * providers reject the request.\n *\n * Stable across processes because the input is fully spelled out and the hash\n * is SHA-256; idempotent for the same inputs; different for a different\n * session, turn, step, or candidate.\n */\nexport function callIdFor(\n sessionId: string,\n turn: string | number,\n step: string | number,\n candidateId: string,\n): string {\n return createHash('sha256')\n .update(JSON.stringify([sessionId, String(turn), String(step), candidateId]))\n .digest('hex')\n .slice(0, 16)\n}\n"]}