dsh-boost 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +526 -0
  4. package/README.md +444 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +283 -0
  43. package/dist/hooks/llm-stream.js +1086 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +257 -0
  49. package/dist/hooks/post-execute.js +1950 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +25 -0
  64. package/dist/host/root.js +64 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +984 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +380 -0
  100. package/dist/tools/boost.js +801 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +130 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Admission arithmetic: is a substitution worth its overhead, and how many
3
+ * steps may the current turn still take?
4
+ *
5
+ * Both are pure arithmetic. This module performs no I/O, reads no config and
6
+ * keeps no time window; callers pass the resolved `BoostConfig` values in
7
+ * (design §5.3). The mutable state is `StepBudget` (per session/turn, hence
8
+ * `reset()` at every turn start) and `RuntimeStepHorizon` (per-session turn
9
+ * history, cleared on session disposal). The assembly feeds the latter from
10
+ * the host's `agent/pre-step` and reads it at status time, which is what makes
11
+ * `historyTurns` a production input rather than an unused config key.
12
+ *
13
+ * @module dsh-boost/admission/ledger
14
+ */
15
+ /**
16
+ * Conservative bound on the steps left in this turn (design §5.3).
17
+ *
18
+ * Fewer than `historyTurns` sizes in `stepsSoFar` means there is no usable
19
+ * mean: the horizon is returned verbatim, never an estimate from a short
20
+ * history. Otherwise this is
21
+ * `Math.min(horizonSteps, Math.round(mean(last historyTurns)))`.
22
+ *
23
+ * Degenerate inputs are defined and never NaN:
24
+ * - `historyTurns` is floored once, and that same N gates both the short-
25
+ * history check and the window, so `2.5` with two entries averages them.
26
+ * A floored `historyTurns <= 0` has no window to average, so it takes the
27
+ * horizon path; the literal mean branch would divide by zero.
28
+ * - a non-finite `horizonSteps` (`NaN` or `Infinity`) degrades to `0`
29
+ * (fail-closed).
30
+ * - a non-finite mean (a `NaN` or `Infinity` in the window) falls back to the
31
+ * horizon.
32
+ *
33
+ * The return is a raw estimate, not a sanitised count: a finite `horizonSteps`
34
+ * is passed through unclamped, so a fractional (`20.5`) or negative (`-1`)
35
+ * horizon — and a negative mean — reach the caller as-is. Callers must not
36
+ * assume a non-negative integer; `0` means zero remaining steps.
37
+ */
38
+ export declare function remainingSteps(input: {
39
+ stepsSoFar: number[];
40
+ horizonSteps: number;
41
+ historyTurns: number;
42
+ }): number;
43
+ /**
44
+ * Per-session history of completed-turn step counts.
45
+ *
46
+ * Design §5.3 asks runtime admission to bound the remaining steps by
47
+ * `min(horizonSteps, mean of the last historyTurns turns)` instead of trusting
48
+ * the fixed horizon, so the plugin never overstates a projection's replay
49
+ * saving. The host reports `(turn, step)` on every model request; this class
50
+ * folds a turn's highest host step into history when the next turn starts. A
51
+ * retried step cannot inflate the count (the maximum is kept), a backwards
52
+ * turn is ignored, and malformed observations create no entry.
53
+ *
54
+ * The state is per session and cleared on `session/disposed` by the assembly;
55
+ * `remaining()` is the conservative aggregate status reports: the minimum over
56
+ * every live session, or the configured horizon when no session has enough
57
+ * completed turns yet.
58
+ */
59
+ export declare class RuntimeStepHorizon {
60
+ private readonly horizonSteps;
61
+ private readonly historyTurns;
62
+ private readonly bySession;
63
+ constructor(horizonSteps: number, historyTurns: number);
64
+ /** Record one proposed model request for `sessionId` at host `(turn, step)`. */
65
+ observe(sessionId: string, turn: number, step: number): void;
66
+ /** This session's conservative remaining-step estimate. */
67
+ remainingFor(sessionId: string): number;
68
+ /** The conservative minimum across live sessions, or the horizon when none has history. */
69
+ remaining(): number;
70
+ /** Drop one session's history on disposal. */
71
+ clear(sessionId: string): void;
72
+ /** Number of sessions with retained history (diagnostics/tests). */
73
+ size(): number;
74
+ }
75
+ /**
76
+ * Admission gate for one candidate (design §5.3).
77
+ *
78
+ * A deterministic single candidate has no selector call and no plan to pay
79
+ * for, so it skips the threshold entirely. Everything else must clear the
80
+ * threshold strictly: breaking even is not a win.
81
+ */
82
+ export declare function worthSubstituting(input: {
83
+ savedTokens: number;
84
+ overheadTokens: number;
85
+ thresholdTokens: number;
86
+ deterministicSingle: boolean;
87
+ }): boolean;
88
+ /**
89
+ * Per-turn substitution budget (default 8, design §5.2-6).
90
+ *
91
+ * The plugin owns one instance for its whole lifetime, so calling `reset()` at
92
+ * turn start is mandatory: without it the budget would be spent once and then
93
+ * silently disable substitution for the rest of the process.
94
+ *
95
+ * A non-positive `max` is an empty budget — `take()` always returns `false`
96
+ * and `exhausted()` is already `true`. A fractional max floors, so `count()`
97
+ * can never exceed it. A non-finite max — including `Infinity`, whose literal
98
+ * reading would be "unlimited" — is also an empty budget: fail-closed, and
99
+ * unreachable through `resolveConfig`, which keeps only finite numbers.
100
+ */
101
+ export declare class StepBudget {
102
+ private readonly max;
103
+ private taken;
104
+ constructor(max: number);
105
+ /** Claim one step; false without incrementing once the budget is spent. */
106
+ take(): boolean;
107
+ /** Start a new turn: the budget is per-turn, not per-plugin-lifetime. */
108
+ reset(): void;
109
+ /** True when no further `take()` can succeed. */
110
+ exhausted(): boolean;
111
+ /** Steps taken since construction or the last `reset()`. */
112
+ count(): number;
113
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Admission arithmetic: is a substitution worth its overhead, and how many
3
+ * steps may the current turn still take?
4
+ *
5
+ * Both are pure arithmetic. This module performs no I/O, reads no config and
6
+ * keeps no time window; callers pass the resolved `BoostConfig` values in
7
+ * (design §5.3). The mutable state is `StepBudget` (per session/turn, hence
8
+ * `reset()` at every turn start) and `RuntimeStepHorizon` (per-session turn
9
+ * history, cleared on session disposal). The assembly feeds the latter from
10
+ * the host's `agent/pre-step` and reads it at status time, which is what makes
11
+ * `historyTurns` a production input rather than an unused config key.
12
+ *
13
+ * @module dsh-boost/admission/ledger
14
+ */
15
+ /**
16
+ * Conservative bound on the steps left in this turn (design §5.3).
17
+ *
18
+ * Fewer than `historyTurns` sizes in `stepsSoFar` means there is no usable
19
+ * mean: the horizon is returned verbatim, never an estimate from a short
20
+ * history. Otherwise this is
21
+ * `Math.min(horizonSteps, Math.round(mean(last historyTurns)))`.
22
+ *
23
+ * Degenerate inputs are defined and never NaN:
24
+ * - `historyTurns` is floored once, and that same N gates both the short-
25
+ * history check and the window, so `2.5` with two entries averages them.
26
+ * A floored `historyTurns <= 0` has no window to average, so it takes the
27
+ * horizon path; the literal mean branch would divide by zero.
28
+ * - a non-finite `horizonSteps` (`NaN` or `Infinity`) degrades to `0`
29
+ * (fail-closed).
30
+ * - a non-finite mean (a `NaN` or `Infinity` in the window) falls back to the
31
+ * horizon.
32
+ *
33
+ * The return is a raw estimate, not a sanitised count: a finite `horizonSteps`
34
+ * is passed through unclamped, so a fractional (`20.5`) or negative (`-1`)
35
+ * horizon — and a negative mean — reach the caller as-is. Callers must not
36
+ * assume a non-negative integer; `0` means zero remaining steps.
37
+ */
38
+ export function remainingSteps(input) {
39
+ const { stepsSoFar, horizonSteps, historyTurns } = input;
40
+ const horizon = Number.isFinite(horizonSteps) ? horizonSteps : 0;
41
+ const turns = Number.isFinite(historyTurns) ? Math.floor(historyTurns) : 0;
42
+ if (turns <= 0 || stepsSoFar.length < turns)
43
+ return horizon;
44
+ const window = stepsSoFar.slice(-turns);
45
+ const mean = window.reduce((sum, n) => sum + n, 0) / window.length;
46
+ return Number.isFinite(mean) ? Math.min(horizon, Math.round(mean)) : horizon;
47
+ }
48
+ /**
49
+ * Per-session history of completed-turn step counts.
50
+ *
51
+ * Design §5.3 asks runtime admission to bound the remaining steps by
52
+ * `min(horizonSteps, mean of the last historyTurns turns)` instead of trusting
53
+ * the fixed horizon, so the plugin never overstates a projection's replay
54
+ * saving. The host reports `(turn, step)` on every model request; this class
55
+ * folds a turn's highest host step into history when the next turn starts. A
56
+ * retried step cannot inflate the count (the maximum is kept), a backwards
57
+ * turn is ignored, and malformed observations create no entry.
58
+ *
59
+ * The state is per session and cleared on `session/disposed` by the assembly;
60
+ * `remaining()` is the conservative aggregate status reports: the minimum over
61
+ * every live session, or the configured horizon when no session has enough
62
+ * completed turns yet.
63
+ */
64
+ export class RuntimeStepHorizon {
65
+ horizonSteps;
66
+ historyTurns;
67
+ bySession = new Map();
68
+ constructor(horizonSteps, historyTurns) {
69
+ this.horizonSteps = Number.isFinite(horizonSteps) && horizonSteps >= 0 ? Math.floor(horizonSteps) : 0;
70
+ this.historyTurns = Number.isFinite(historyTurns) && historyTurns >= 1 ? Math.floor(historyTurns) : 1;
71
+ }
72
+ /** Record one proposed model request for `sessionId` at host `(turn, step)`. */
73
+ observe(sessionId, turn, step) {
74
+ if (typeof sessionId !== 'string' || sessionId.length === 0)
75
+ return;
76
+ if (!Number.isFinite(turn) || !Number.isFinite(step))
77
+ return;
78
+ const hostTurn = Math.floor(turn);
79
+ const hostStep = Math.floor(step);
80
+ if (hostTurn < 1 || hostStep < 1)
81
+ return;
82
+ const existing = this.bySession.get(sessionId);
83
+ if (existing === undefined) {
84
+ this.bySession.set(sessionId, { turn: hostTurn, maxStep: hostStep, completed: [] });
85
+ return;
86
+ }
87
+ if (hostTurn < existing.turn)
88
+ return;
89
+ if (hostTurn === existing.turn) {
90
+ if (hostStep > existing.maxStep)
91
+ existing.maxStep = hostStep;
92
+ return;
93
+ }
94
+ // A new turn proves the previous one is complete.
95
+ existing.completed.push(existing.maxStep);
96
+ if (existing.completed.length > this.historyTurns)
97
+ existing.completed.shift();
98
+ existing.turn = hostTurn;
99
+ existing.maxStep = hostStep;
100
+ }
101
+ /** This session's conservative remaining-step estimate. */
102
+ remainingFor(sessionId) {
103
+ const entry = this.bySession.get(sessionId);
104
+ return remainingSteps({
105
+ stepsSoFar: entry?.completed ?? [],
106
+ horizonSteps: this.horizonSteps,
107
+ historyTurns: this.historyTurns,
108
+ });
109
+ }
110
+ /** The conservative minimum across live sessions, or the horizon when none has history. */
111
+ remaining() {
112
+ let value = this.horizonSteps;
113
+ for (const sessionId of this.bySession.keys())
114
+ value = Math.min(value, this.remainingFor(sessionId));
115
+ return value;
116
+ }
117
+ /** Drop one session's history on disposal. */
118
+ clear(sessionId) {
119
+ this.bySession.delete(sessionId);
120
+ }
121
+ /** Number of sessions with retained history (diagnostics/tests). */
122
+ size() {
123
+ return this.bySession.size;
124
+ }
125
+ }
126
+ /**
127
+ * Admission gate for one candidate (design §5.3).
128
+ *
129
+ * A deterministic single candidate has no selector call and no plan to pay
130
+ * for, so it skips the threshold entirely. Everything else must clear the
131
+ * threshold strictly: breaking even is not a win.
132
+ */
133
+ export function worthSubstituting(input) {
134
+ const { savedTokens, overheadTokens, thresholdTokens, deterministicSingle } = input;
135
+ return deterministicSingle || savedTokens - overheadTokens > thresholdTokens;
136
+ }
137
+ /**
138
+ * Per-turn substitution budget (default 8, design §5.2-6).
139
+ *
140
+ * The plugin owns one instance for its whole lifetime, so calling `reset()` at
141
+ * turn start is mandatory: without it the budget would be spent once and then
142
+ * silently disable substitution for the rest of the process.
143
+ *
144
+ * A non-positive `max` is an empty budget — `take()` always returns `false`
145
+ * and `exhausted()` is already `true`. A fractional max floors, so `count()`
146
+ * can never exceed it. A non-finite max — including `Infinity`, whose literal
147
+ * reading would be "unlimited" — is also an empty budget: fail-closed, and
148
+ * unreachable through `resolveConfig`, which keeps only finite numbers.
149
+ */
150
+ export class StepBudget {
151
+ max;
152
+ taken = 0;
153
+ constructor(max) {
154
+ this.max = Number.isFinite(max) && max > 0 ? Math.floor(max) : 0;
155
+ }
156
+ /** Claim one step; false without incrementing once the budget is spent. */
157
+ take() {
158
+ if (this.taken >= this.max)
159
+ return false;
160
+ this.taken += 1;
161
+ return true;
162
+ }
163
+ /** Start a new turn: the budget is per-turn, not per-plugin-lifetime. */
164
+ reset() {
165
+ this.taken = 0;
166
+ }
167
+ /** True when no further `take()` can succeed. */
168
+ exhausted() {
169
+ return this.taken >= this.max;
170
+ }
171
+ /** Steps taken since construction or the last `reset()`. */
172
+ count() {
173
+ return this.taken;
174
+ }
175
+ }
176
+ //# sourceMappingURL=ledger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../src/admission/ledger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,cAAc,CAAC,KAI9B;IACC,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,GAAG,KAAK,CAAA;IACxD,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;IAChE,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAC1E,IAAI,KAAK,IAAI,CAAC,IAAI,UAAU,CAAC,MAAM,GAAG,KAAK;QAAE,OAAO,OAAO,CAAA;IAE3D,MAAM,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAA;IACvC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,CAAA;IAClE,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,C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rB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IAClC,CAAC;IAED,oEAAoE;IACpE,IAAI;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAA;IAC5B,CAAC;CACF;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAKjC;IACC,MAAM,EAAE,WAAW,EAAE,cAAc,EAAE,eAAe,EAAE,mBAAmB,EAAE,GAAG,KAAK,CAAA;IACnF,OAAO,mBAAmB,IAAI,WAAW,GAAG,cAAc,GAAG,eAAe,CAAA;AAC9E,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,UAAU;IACJ,GAAG,CAAQ;IACpB,KAAK,GAAG,CAAC,CAAA;IAEjB,YAAY,GAAW;QACrB,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;IAED,2EAA2E;IAC3E,IAAI;QACF,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG;YAAE,OAAO,KAAK,CAAA;QACxC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAA;QACf,OAAO,IAAI,CAAA;IACb,CAAC;IAED,yEAAyE;IACzE,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;IAChB,CAAC;IAED,iDAAiD;IACjD,SAAS;QACP,OAAO,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,CAAA;IAC/B,CAAC;IAED,4DAA4D;IAC5D,KAAK;QACH,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;CACF","sourcesContent":["/**\n * Admission arithmetic: is a substitution worth its overhead, and how many\n * steps may the current turn still take?\n *\n * Both are pure arithmetic. This module performs no I/O, reads no config and\n * keeps no time window; callers pass the resolved `BoostConfig` values in\n * (design §5.3). The mutable state is `StepBudget` (per session/turn, hence\n * `reset()` at every turn start) and `RuntimeStepHorizon` (per-session turn\n * history, cleared on session disposal). The assembly feeds the latter from\n * the host's `agent/pre-step` and reads it at status time, which is what makes\n * `historyTurns` a production input rather than an unused config key.\n *\n * @module dsh-boost/admission/ledger\n */\n\n/**\n * Conservative bound on the steps left in this turn (design §5.3).\n *\n * Fewer than `historyTurns` sizes in `stepsSoFar` means there is no usable\n * mean: the horizon is returned verbatim, never an estimate from a short\n * history. Otherwise this is\n * `Math.min(horizonSteps, Math.round(mean(last historyTurns)))`.\n *\n * Degenerate inputs are defined and never NaN:\n * - `historyTurns` is floored once, and that same N gates both the short-\n * history check and the window, so `2.5` with two entries averages them.\n * A floored `historyTurns <= 0` has no window to average, so it takes the\n * horizon path; the literal mean branch would divide by zero.\n * - a non-finite `horizonSteps` (`NaN` or `Infinity`) degrades to `0`\n * (fail-closed).\n * - a non-finite mean (a `NaN` or `Infinity` in the window) falls back to the\n * horizon.\n *\n * The return is a raw estimate, not a sanitised count: a finite `horizonSteps`\n * is passed through unclamped, so a fractional (`20.5`) or negative (`-1`)\n * horizon — and a negative mean — reach the caller as-is. Callers must not\n * assume a non-negative integer; `0` means zero remaining steps.\n */\nexport function remainingSteps(input: {\n stepsSoFar: number[]\n horizonSteps: number\n historyTurns: number\n}): number {\n const { stepsSoFar, horizonSteps, historyTurns } = input\n const horizon = Number.isFinite(horizonSteps) ? horizonSteps : 0\n const turns = Number.isFinite(historyTurns) ? Math.floor(historyTurns) : 0\n if (turns <= 0 || stepsSoFar.length < turns) return horizon\n\n const window = stepsSoFar.slice(-turns)\n const mean = window.reduce((sum, n) => sum + n, 0) / window.length\n return Number.isFinite(mean) ? Math.min(horizon, Math.round(mean)) : horizon\n}\n\n/**\n * Per-session history of completed-turn step counts.\n *\n * Design §5.3 asks runtime admission to bound the remaining steps by\n * `min(horizonSteps, mean of the last historyTurns turns)` instead of trusting\n * the fixed horizon, so the plugin never overstates a projection's replay\n * saving. The host reports `(turn, step)` on every model request; this class\n * folds a turn's highest host step into history when the next turn starts. A\n * retried step cannot inflate the count (the maximum is kept), a backwards\n * turn is ignored, and malformed observations create no entry.\n *\n * The state is per session and cleared on `session/disposed` by the assembly;\n * `remaining()` is the conservative aggregate status reports: the minimum over\n * every live session, or the configured horizon when no session has enough\n * completed turns yet.\n */\nexport class RuntimeStepHorizon {\n private readonly horizonSteps: number\n private readonly historyTurns: number\n private readonly bySession = new Map<\n string,\n { turn: number; maxStep: number; completed: number[] }\n >()\n\n constructor(horizonSteps: number, historyTurns: number) {\n this.horizonSteps = Number.isFinite(horizonSteps) && horizonSteps >= 0 ? Math.floor(horizonSteps) : 0\n this.historyTurns = Number.isFinite(historyTurns) && historyTurns >= 1 ? Math.floor(historyTurns) : 1\n }\n\n /** Record one proposed model request for `sessionId` at host `(turn, step)`. */\n observe(sessionId: string, turn: number, step: number): void {\n if (typeof sessionId !== 'string' || sessionId.length === 0) return\n if (!Number.isFinite(turn) || !Number.isFinite(step)) return\n const hostTurn = Math.floor(turn)\n const hostStep = Math.floor(step)\n if (hostTurn < 1 || hostStep < 1) return\n\n const existing = this.bySession.get(sessionId)\n if (existing === undefined) {\n this.bySession.set(sessionId, { turn: hostTurn, maxStep: hostStep, completed: [] })\n return\n }\n if (hostTurn < existing.turn) return\n if (hostTurn === existing.turn) {\n if (hostStep > existing.maxStep) existing.maxStep = hostStep\n return\n }\n // A new turn proves the previous one is complete.\n existing.completed.push(existing.maxStep)\n if (existing.completed.length > this.historyTurns) existing.completed.shift()\n existing.turn = hostTurn\n existing.maxStep = hostStep\n }\n\n /** This session's conservative remaining-step estimate. */\n remainingFor(sessionId: string): number {\n const entry = this.bySession.get(sessionId)\n return remainingSteps({\n stepsSoFar: entry?.completed ?? [],\n horizonSteps: this.horizonSteps,\n historyTurns: this.historyTurns,\n })\n }\n\n /** The conservative minimum across live sessions, or the horizon when none has history. */\n remaining(): number {\n let value = this.horizonSteps\n for (const sessionId of this.bySession.keys()) value = Math.min(value, this.remainingFor(sessionId))\n return value\n }\n\n /** Drop one session's history on disposal. */\n clear(sessionId: string): void {\n this.bySession.delete(sessionId)\n }\n\n /** Number of sessions with retained history (diagnostics/tests). */\n size(): number {\n return this.bySession.size\n }\n}\n\n/**\n * Admission gate for one candidate (design §5.3).\n *\n * A deterministic single candidate has no selector call and no plan to pay\n * for, so it skips the threshold entirely. Everything else must clear the\n * threshold strictly: breaking even is not a win.\n */\nexport function worthSubstituting(input: {\n savedTokens: number\n overheadTokens: number\n thresholdTokens: number\n deterministicSingle: boolean\n}): boolean {\n const { savedTokens, overheadTokens, thresholdTokens, deterministicSingle } = input\n return deterministicSingle || savedTokens - overheadTokens > thresholdTokens\n}\n\n/**\n * Per-turn substitution budget (default 8, design §5.2-6).\n *\n * The plugin owns one instance for its whole lifetime, so calling `reset()` at\n * turn start is mandatory: without it the budget would be spent once and then\n * silently disable substitution for the rest of the process.\n *\n * A non-positive `max` is an empty budget — `take()` always returns `false`\n * and `exhausted()` is already `true`. A fractional max floors, so `count()`\n * can never exceed it. A non-finite max — including `Infinity`, whose literal\n * reading would be \"unlimited\" — is also an empty budget: fail-closed, and\n * unreachable through `resolveConfig`, which keeps only finite numbers.\n */\nexport class StepBudget {\n private readonly max: number\n private taken = 0\n\n constructor(max: number) {\n this.max = Number.isFinite(max) && max > 0 ? Math.floor(max) : 0\n }\n\n /** Claim one step; false without incrementing once the budget is spent. */\n take(): boolean {\n if (this.taken >= this.max) return false\n this.taken += 1\n return true\n }\n\n /** Start a new turn: the budget is per-turn, not per-plugin-lifetime. */\n reset(): void {\n this.taken = 0\n }\n\n /** True when no further `take()` can succeed. */\n exhausted(): boolean {\n return this.taken >= this.max\n }\n\n /** Steps taken since construction or the last `reset()`. */\n count(): number {\n return this.taken\n }\n}\n"]}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Projection retrieval accounting: the denominator of `projection_net_tokens`.
3
+ *
4
+ * The projection ledger's gross saving is what the plugin removed from the
5
+ * history; the net saving must subtract what the model spent reading the
6
+ * spilled original back. `projection_retrievals` counts those reads (design
7
+ * §5.3), and its producer is the `read`/`grep` call that names one of this
8
+ * session's spill locators. A retrieval that is not counted would make every
9
+ * projection look free, which is why this is a ledger and not a statistic.
10
+ *
11
+ * The matcher is pure — `(params, locators) → boolean` — so the hook can call
12
+ * it against the locators recorded when a receipt was actually spilled. The
13
+ * per-session ledger is deliberately small and bounded: it keeps the most
14
+ * recent {@link MAX_LOCATORS_PER_SESSION} locators, because a long session
15
+ * projects far more artifacts than its model ever reads back and the ledger is
16
+ * an audit aid, not a cache of the spill store.
17
+ *
18
+ * @module dsh-boost/admission/retrieval
19
+ */
20
+ /**
21
+ * Whether a tool call's arguments name one of the given spill locators.
22
+ *
23
+ * Total by construction: malformed, cyclic or hostile arguments return `false`
24
+ * rather than throwing, because this runs inside the host's `post-execute`
25
+ * waterfall where a throw would replace the tool result with an error.
26
+ */
27
+ export declare function recordRetrieval(params: unknown, locators: ReadonlySet<string>): boolean;
28
+ /**
29
+ * The spill locators a session's projected receipts left behind.
30
+ *
31
+ * One instance belongs to the plugin instance; `apply` passes it through
32
+ * `HookDeps` and `clearSession` drops a session's set on `session/disposed`, so
33
+ * a disposed session cannot leak locators into the next one.
34
+ */
35
+ export declare class RetrievalLedger {
36
+ private readonly bySession;
37
+ /** Locators dropped by the cap, across every session; exposed by status. */
38
+ private evictedCount;
39
+ /** Remember one applied projection's locator; `true` when it was new. */
40
+ record(sessionId: string, locator: string): boolean;
41
+ /** The locators currently remembered for `sessionId` (empty when unknown). */
42
+ locatorsOf(sessionId: string): ReadonlySet<string>;
43
+ /**
44
+ * The matched locator for this call, or `undefined` when it is not a retrieval.
45
+ *
46
+ * Goes through the exported {@link recordRetrieval} predicate first, so the
47
+ * production hook and the documented obligation share one decision; the
48
+ * second walk only runs on a hit and is what puts the locator on the receipt.
49
+ */
50
+ locate(sessionId: string, params: unknown): string | undefined;
51
+ /** Whether this call retrieves a spilled artifact. */
52
+ hit(sessionId: string, params: unknown): boolean;
53
+ /** Drop one session's locators (session end). */
54
+ clear(sessionId: string): void;
55
+ /** Number of sessions currently holding locators. */
56
+ size(): number;
57
+ /**
58
+ * Locators the cap has dropped since process start.
59
+ *
60
+ * A silent eviction would make later re-reads uncounted and flatter the net
61
+ * account; status reports this so an operator can see the ledger is lossy
62
+ * rather than assume every retrieval was seen.
63
+ */
64
+ evictions(): number;
65
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Projection retrieval accounting: the denominator of `projection_net_tokens`.
3
+ *
4
+ * The projection ledger's gross saving is what the plugin removed from the
5
+ * history; the net saving must subtract what the model spent reading the
6
+ * spilled original back. `projection_retrievals` counts those reads (design
7
+ * §5.3), and its producer is the `read`/`grep` call that names one of this
8
+ * session's spill locators. A retrieval that is not counted would make every
9
+ * projection look free, which is why this is a ledger and not a statistic.
10
+ *
11
+ * The matcher is pure — `(params, locators) → boolean` — so the hook can call
12
+ * it against the locators recorded when a receipt was actually spilled. The
13
+ * per-session ledger is deliberately small and bounded: it keeps the most
14
+ * recent {@link MAX_LOCATORS_PER_SESSION} locators, because a long session
15
+ * projects far more artifacts than its model ever reads back and the ledger is
16
+ * an audit aid, not a cache of the spill store.
17
+ *
18
+ * @module dsh-boost/admission/retrieval
19
+ */
20
+ /** Deepest argument nesting a retrieval check will walk. */
21
+ const MAX_DEPTH = 32;
22
+ /** Hard bound on visited argument nodes, so hostile params cannot stall a hook. */
23
+ const MAX_NODES = 4096;
24
+ /** Bound on remembered locators per session (oldest evicted first). */
25
+ const MAX_LOCATORS_PER_SESSION = 512;
26
+ /** A shared immutable empty set, so a missed session allocates nothing. */
27
+ const EMPTY_LOCATORS = new Set();
28
+ /**
29
+ * The first string leaf of `params` that equals one of `locators`.
30
+ *
31
+ * Exact equality is intentional: a locator is a complete spill path, and the
32
+ * host's `read`/`grep` tools take the path as one argument. Substring matching
33
+ * would count a read of `/spill/read-1.txt.bak` as a retrieval of the original.
34
+ * The walk is iterative, depth-capped and node-capped because `params` is
35
+ * model-written.
36
+ */
37
+ function matchedLocator(params, locators) {
38
+ if (locators.size === 0)
39
+ return undefined;
40
+ const stack = [{ value: params, depth: 0 }];
41
+ let visited = 0;
42
+ while (stack.length > 0 && visited < MAX_NODES) {
43
+ const frame = stack.pop();
44
+ if (frame === undefined)
45
+ break;
46
+ visited += 1;
47
+ const value = frame.value;
48
+ if (typeof value === 'string') {
49
+ if (locators.has(value))
50
+ return value;
51
+ continue;
52
+ }
53
+ if (value === null || typeof value !== 'object')
54
+ continue;
55
+ if (frame.depth >= MAX_DEPTH)
56
+ continue;
57
+ if (Array.isArray(value)) {
58
+ for (const child of value)
59
+ stack.push({ value: child, depth: frame.depth + 1 });
60
+ continue;
61
+ }
62
+ for (const child of Object.values(value)) {
63
+ stack.push({ value: child, depth: frame.depth + 1 });
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+ /**
69
+ * Whether a tool call's arguments name one of the given spill locators.
70
+ *
71
+ * Total by construction: malformed, cyclic or hostile arguments return `false`
72
+ * rather than throwing, because this runs inside the host's `post-execute`
73
+ * waterfall where a throw would replace the tool result with an error.
74
+ */
75
+ export function recordRetrieval(params, locators) {
76
+ try {
77
+ return matchedLocator(params, locators) !== undefined;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ /**
84
+ * The spill locators a session's projected receipts left behind.
85
+ *
86
+ * One instance belongs to the plugin instance; `apply` passes it through
87
+ * `HookDeps` and `clearSession` drops a session's set on `session/disposed`, so
88
+ * a disposed session cannot leak locators into the next one.
89
+ */
90
+ export class RetrievalLedger {
91
+ bySession = new Map();
92
+ /** Locators dropped by the cap, across every session; exposed by status. */
93
+ evictedCount = 0;
94
+ /** Remember one applied projection's locator; `true` when it was new. */
95
+ record(sessionId, locator) {
96
+ if (typeof sessionId !== 'string' || sessionId === '')
97
+ return false;
98
+ if (typeof locator !== 'string' || locator === '')
99
+ return false;
100
+ let locators = this.bySession.get(sessionId);
101
+ if (locators === undefined) {
102
+ locators = new Set();
103
+ this.bySession.set(sessionId, locators);
104
+ }
105
+ if (locators.has(locator))
106
+ return false;
107
+ if (locators.size >= MAX_LOCATORS_PER_SESSION) {
108
+ const oldest = locators.values().next().value;
109
+ if (oldest !== undefined) {
110
+ locators.delete(oldest);
111
+ this.evictedCount += 1;
112
+ }
113
+ }
114
+ locators.add(locator);
115
+ return true;
116
+ }
117
+ /** The locators currently remembered for `sessionId` (empty when unknown). */
118
+ locatorsOf(sessionId) {
119
+ return this.bySession.get(sessionId) ?? EMPTY_LOCATORS;
120
+ }
121
+ /**
122
+ * The matched locator for this call, or `undefined` when it is not a retrieval.
123
+ *
124
+ * Goes through the exported {@link recordRetrieval} predicate first, so the
125
+ * production hook and the documented obligation share one decision; the
126
+ * second walk only runs on a hit and is what puts the locator on the receipt.
127
+ */
128
+ locate(sessionId, params) {
129
+ try {
130
+ const locators = this.locatorsOf(sessionId);
131
+ if (!recordRetrieval(params, locators))
132
+ return undefined;
133
+ return matchedLocator(params, locators);
134
+ }
135
+ catch {
136
+ return undefined;
137
+ }
138
+ }
139
+ /** Whether this call retrieves a spilled artifact. */
140
+ hit(sessionId, params) {
141
+ return this.locate(sessionId, params) !== undefined;
142
+ }
143
+ /** Drop one session's locators (session end). */
144
+ clear(sessionId) {
145
+ this.bySession.delete(sessionId);
146
+ }
147
+ /** Number of sessions currently holding locators. */
148
+ size() {
149
+ return this.bySession.size;
150
+ }
151
+ /**
152
+ * Locators the cap has dropped since process start.
153
+ *
154
+ * A silent eviction would make later re-reads uncounted and flatter the net
155
+ * account; status reports this so an operator can see the ledger is lossy
156
+ * rather than assume every retrieval was seen.
157
+ */
158
+ evictions() {
159
+ return this.evictedCount;
160
+ }
161
+ }
162
+ //# sourceMappingURL=retrieval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retrieval.js","sourceRoot":"","sources":["../../src/admission/retrieval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,4DAA4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sourcesContent":["/**\n * Projection retrieval accounting: the denominator of `projection_net_tokens`.\n *\n * The projection ledger's gross saving is what the plugin removed from the\n * history; the net saving must subtract what the model spent reading the\n * spilled original back. `projection_retrievals` counts those reads (design\n * §5.3), and its producer is the `read`/`grep` call that names one of this\n * session's spill locators. A retrieval that is not counted would make every\n * projection look free, which is why this is a ledger and not a statistic.\n *\n * The matcher is pure — `(params, locators) → boolean` — so the hook can call\n * it against the locators recorded when a receipt was actually spilled. The\n * per-session ledger is deliberately small and bounded: it keeps the most\n * recent {@link MAX_LOCATORS_PER_SESSION} locators, because a long session\n * projects far more artifacts than its model ever reads back and the ledger is\n * an audit aid, not a cache of the spill store.\n *\n * @module dsh-boost/admission/retrieval\n */\n\n/** Deepest argument nesting a retrieval check will walk. */\nconst MAX_DEPTH = 32\n/** Hard bound on visited argument nodes, so hostile params cannot stall a hook. */\nconst MAX_NODES = 4096\n/** Bound on remembered locators per session (oldest evicted first). */\nconst MAX_LOCATORS_PER_SESSION = 512\n\n/** A shared immutable empty set, so a missed session allocates nothing. */\nconst EMPTY_LOCATORS: ReadonlySet<string> = new Set()\n\n/**\n * The first string leaf of `params` that equals one of `locators`.\n *\n * Exact equality is intentional: a locator is a complete spill path, and the\n * host's `read`/`grep` tools take the path as one argument. Substring matching\n * would count a read of `/spill/read-1.txt.bak` as a retrieval of the original.\n * The walk is iterative, depth-capped and node-capped because `params` is\n * model-written.\n */\nfunction matchedLocator(params: unknown, locators: ReadonlySet<string>): string | undefined {\n if (locators.size === 0) return undefined\n\n const stack: Array<{ value: unknown; depth: number }> = [{ value: params, depth: 0 }]\n let visited = 0\n while (stack.length > 0 && visited < MAX_NODES) {\n const frame = stack.pop()\n if (frame === undefined) break\n visited += 1\n const value = frame.value\n\n if (typeof value === 'string') {\n if (locators.has(value)) return value\n continue\n }\n if (value === null || typeof value !== 'object') continue\n if (frame.depth >= MAX_DEPTH) continue\n\n if (Array.isArray(value)) {\n for (const child of value) stack.push({ value: child, depth: frame.depth + 1 })\n continue\n }\n for (const child of Object.values(value as Record<string, unknown>)) {\n stack.push({ value: child, depth: frame.depth + 1 })\n }\n }\n return undefined\n}\n\n/**\n * Whether a tool call's arguments name one of the given spill locators.\n *\n * Total by construction: malformed, cyclic or hostile arguments return `false`\n * rather than throwing, because this runs inside the host's `post-execute`\n * waterfall where a throw would replace the tool result with an error.\n */\nexport function recordRetrieval(params: unknown, locators: ReadonlySet<string>): boolean {\n try {\n return matchedLocator(params, locators) !== undefined\n } catch {\n return false\n }\n}\n\n/**\n * The spill locators a session's projected receipts left behind.\n *\n * One instance belongs to the plugin instance; `apply` passes it through\n * `HookDeps` and `clearSession` drops a session's set on `session/disposed`, so\n * a disposed session cannot leak locators into the next one.\n */\nexport class RetrievalLedger {\n private readonly bySession = new Map<string, Set<string>>()\n /** Locators dropped by the cap, across every session; exposed by status. */\n private evictedCount = 0\n\n /** Remember one applied projection's locator; `true` when it was new. */\n record(sessionId: string, locator: string): boolean {\n if (typeof sessionId !== 'string' || sessionId === '') return false\n if (typeof locator !== 'string' || locator === '') return false\n let locators = this.bySession.get(sessionId)\n if (locators === undefined) {\n locators = new Set()\n this.bySession.set(sessionId, locators)\n }\n if (locators.has(locator)) return false\n if (locators.size >= MAX_LOCATORS_PER_SESSION) {\n const oldest = locators.values().next().value\n if (oldest !== undefined) {\n locators.delete(oldest)\n this.evictedCount += 1\n }\n }\n locators.add(locator)\n return true\n }\n\n /** The locators currently remembered for `sessionId` (empty when unknown). */\n locatorsOf(sessionId: string): ReadonlySet<string> {\n return this.bySession.get(sessionId) ?? EMPTY_LOCATORS\n }\n\n /**\n * The matched locator for this call, or `undefined` when it is not a retrieval.\n *\n * Goes through the exported {@link recordRetrieval} predicate first, so the\n * production hook and the documented obligation share one decision; the\n * second walk only runs on a hit and is what puts the locator on the receipt.\n */\n locate(sessionId: string, params: unknown): string | undefined {\n try {\n const locators = this.locatorsOf(sessionId)\n if (!recordRetrieval(params, locators)) return undefined\n return matchedLocator(params, locators)\n } catch {\n return undefined\n }\n }\n\n /** Whether this call retrieves a spilled artifact. */\n hit(sessionId: string, params: unknown): boolean {\n return this.locate(sessionId, params) !== undefined\n }\n\n /** Drop one session's locators (session end). */\n clear(sessionId: string): void {\n this.bySession.delete(sessionId)\n }\n\n /** Number of sessions currently holding locators. */\n size(): number {\n return this.bySession.size\n }\n\n /**\n * Locators the cap has dropped since process start.\n *\n * A silent eviction would make later re-reads uncounted and flatter the net\n * account; status reports this so an operator can see the ledger is lossy\n * rather than assume every retrieval was seen.\n */\n evictions(): number {\n return this.evictedCount\n }\n}\n"]}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Usage pairing: turn two consecutive model requests into the measured saving
3
+ * of one substitution (design §5.3).
4
+ *
5
+ * When the plugin substitutes a call, the model is not asked for that step, so
6
+ * the next real request replays a shorter history. The saving is therefore
7
+ * measured as the size of that next request — `input + cacheRead`, because the
8
+ * host reports `inputTokens` excluding cache reads — never estimated. A missing
9
+ * next request is `'unknown'`; an interpolated number would be indistinguishable
10
+ * from a measurement once written to a receipt.
11
+ *
12
+ * The ledger keeps two request slots plus a mark: `latest`, the first request
13
+ * after the mark, and the mark itself — which holds the request that preceded
14
+ * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no
15
+ * timers, no I/O, no host calls.
16
+ *
17
+ * @module dsh-boost/admission/usage
18
+ */
19
+ /** One model request's raw counts, mapped from the `llm/stream` usage chunk. */
20
+ export interface Usage {
21
+ input: number;
22
+ cacheRead: number;
23
+ output: number;
24
+ }
25
+ /**
26
+ * Pairs two consecutive model requests around one substitution.
27
+ *
28
+ * The pairing target is the FIRST request after the mark, never the latest:
29
+ * when a caller forgets to settle, a later unrelated request must not be
30
+ * attributed to the substitution. `settle()` consumes the mark and clears the
31
+ * pairing slots; `last()` is a pure reader and survives it.
32
+ */
33
+ export declare class UsageLedger {
34
+ private latest;
35
+ private hasMark;
36
+ private beforeMark;
37
+ private afterMark;
38
+ private candidateId;
39
+ /**
40
+ * Record one real request. The first request after a mark claims the pairing
41
+ * slot and keeps it; later requests only advance `last()`.
42
+ */
43
+ request(u: Usage): void;
44
+ /** Most recent request, or `undefined` before the first one. Never consumes. */
45
+ last(): Usage | undefined;
46
+ /**
47
+ * Record that a substitution just happened.
48
+ *
49
+ * `candidateId` is kept only so the caller can pair `settle()` with the right
50
+ * substitution receipt (`pendingCandidateId()`); it never changes the
51
+ * arithmetic. A new mark discards any unconsumed pairing and starts over from
52
+ * the current latest request.
53
+ */
54
+ markSubstituted(candidateId: string): void;
55
+ /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */
56
+ pendingCandidateId(): string | undefined;
57
+ /**
58
+ * Consume the mark and report the substitution's measured cost.
59
+ *
60
+ * `saved_input_tokens` is the first after-mark request's `input + cacheRead`;
61
+ * `output_tokens` is that request's `output`, a third count that is never
62
+ * folded into input. Both are `'unknown'` when no usable request arrived after
63
+ * the mark — never a copy of the previous request's numbers. `cache_hit_delta`
64
+ * is the after-mark hit rate minus the pre-mark hit rate, `null` when either
65
+ * side cannot be told (a `null` delta means "cannot tell", not zero).
66
+ *
67
+ * A second `settle()` has nothing left to consume and reports the same
68
+ * `'unknown'` / `null`.
69
+ */
70
+ settle(): {
71
+ saved_input_tokens: number | 'unknown';
72
+ cache_hit_delta: number | null;
73
+ output_tokens: number | 'unknown';
74
+ };
75
+ }