dsh-context-compression-improved 0.2.3 → 0.2.5

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 (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,684 +1,904 @@
1
- import z from "@deepseek-ai/schemastery";
2
- import { Context, Service } from "@deepseek-ai/cordis";
3
- import { CallId, ContentBlock } from "@deepseek-ai/dsh-llm";
4
- import { Session } from "@deepseek-ai/dsh-session";
5
- import { TokenMeasurement } from "@deepseek-ai/dsh-token-meter";
6
- //#region src/runtime/tokenpilot/dedup.d.ts
7
- /** Entry stored per first-seen content hash. */
8
- interface DedupeTableEntry {
9
- /** First surface seq carrying this canonical content. */
10
- readonly seq: number;
11
- /** Session source reference of the first occurrence. */
12
- readonly sourceRef: string;
13
- /** Tool name of the first occurrence. */
14
- readonly toolName: string;
15
- /** Original full-text code points of the first occurrence. */
16
- readonly originalChars: number;
17
- }
18
- /** Per-session dedup index with insertion-order eviction. */
19
- declare class DedupeTable {
20
- private readonly maxEntries;
21
- private readonly entries;
22
- constructor(maxEntries?: number);
23
- /** Look up the first occurrence for one canonical hash, if any. */
24
- get(hash: string): DedupeTableEntry | undefined;
25
- /** Record a first occurrence; existing hashes only refresh insertion order. */
26
- record(hash: string, entry: DedupeTableEntry): void;
27
- }
28
- //#endregion
29
- //#region src/runtime/types.d.ts
30
- /** User-facing mixed strategy profile. */
31
- declare const COMPRESSION_PROFILES: readonly ["off", "native", "balanced", "cache-strict", "savings", "adaptive", "tokenpilot-inspired", "custom"];
32
- /** Public compression strategy selected for one Session. */
33
- type CompressionProfile = typeof COMPRESSION_PROFILES[number];
34
- /** When historical tool results may be aged for one Session policy. */
35
- type HistoryMode = 'disabled' | 'routine' | 'capacity-pressure' | 'adaptive';
36
- /** Canonical unit stored by one versioned Custom policy. */
37
- type CustomCompressionUnit = 'tokens' | 'context-percent';
38
- /** Whether routine History may rewrite a previously sent Harness prefix. */
39
- type CustomPrefixPolicy = 'preserve' | 'pressure-break';
40
- /** One independently selectable Custom Fresh or Aggregate stage. */
41
- interface CustomCompressionBudget {
42
- enabled: boolean;
43
- trigger: number;
44
- target: number;
45
- }
46
- /** Legacy Custom History gate and turn/token working-set protection. */
47
- interface LegacyCustomHistoryPolicy {
48
- enabled: boolean;
49
- trigger: number;
50
- keepRecentTurns: number;
51
- keepRecent: number;
52
- minReclaim: number;
53
- }
54
- /** Custom History gate and recent tool-call/token working-set protection. */
55
- interface CustomHistoryPolicy {
56
- enabled: boolean;
57
- trigger: number;
58
- keepRecentToolCalls: number;
59
- keepRecentTokens: number;
60
- minReclaim: number;
61
- }
62
- /** Custom-only experimental TailTrim gate. */
63
- interface CustomTailTrimPolicy {
64
- enabled: boolean;
65
- trigger: number;
66
- }
67
- /** TokenPilot-inspired preset sub-capability switches (only injected for `tokenpilot-inspired`). */
68
- interface PresetOptions {
69
- /** Reject replacements whose text is not smaller than the original (G1). */
70
- readonly noNetSavingsGuard: boolean;
71
- /** Permanently exempt recovery content from further reduction (G2). */
72
- readonly skipReductionRecovery: boolean;
73
- /** Replace byte-identical repeated tool results with first-occurrence pointers (A1). */
74
- readonly dedupeToolResults: boolean;
75
- /** Append Exact Sources locator blocks after Auto Compact completes (A2). */
76
- readonly summaryLocator: boolean;
77
- /** Volatile-line demotion, deterministic tool ordering, and prefix fingerprint audit (S1/S2). */
78
- readonly prefixStabilizer: boolean;
79
- /** Fresh/superseded read-state classification with clustered omission markers (R2/R3). */
80
- readonly readState: boolean;
81
- /** Optional estimator channel; `''` keeps every estimator consumer on rule-only fallbacks (E1/E2). */
82
- readonly estimator: {
83
- readonly mode: '' | 'host' | 'direct';
84
- };
85
- }
86
- /** Common user-authored Custom stages shared by persisted policy versions. */
87
- interface CustomCompressionPolicyFields<HistoryPolicy> {
88
- unit: CustomCompressionUnit;
89
- fresh: CustomCompressionBudget;
90
- aggregate: CustomCompressionBudget;
91
- history: HistoryPolicy;
92
- prefixPolicy: CustomPrefixPolicy;
93
- }
94
- /** Legacy R4 Custom policy, accepted without migration. */
95
- interface CustomCompressionPolicyV1 extends CustomCompressionPolicyFields<LegacyCustomHistoryPolicy> {
96
- version: 1;
97
- }
98
- /** R5 Custom policy with an explicit default-off TailTrim stage. */
99
- interface CustomCompressionPolicyV2 extends CustomCompressionPolicyFields<LegacyCustomHistoryPolicy> {
100
- version: 2;
101
- tailTrim: CustomTailTrimPolicy;
102
- }
103
- /** Custom policy with tool-call working-set protection. */
104
- interface CustomCompressionPolicyV3 extends CustomCompressionPolicyFields<CustomHistoryPolicy> {
105
- version: 3;
106
- tailTrim: CustomTailTrimPolicy;
107
- }
108
- /** Strict persisted Custom policy union. */
109
- type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3;
110
- /** User-tunable Auto Compact coordination preferences. */
111
- interface AutoCompactSettings {
112
- /** Routed-context percentage that triggers model-driven Auto Compact. */
113
- thresholdPercent: number;
114
- }
115
- /**
116
- * Orthogonal evidence-based code-skeleton reducer gate. Independent of every
117
- * profile: when enabled, fresh oversized source-code results may take the
118
- * `hypa-code-skeleton` reducer before the head/tail fallbacks.
119
- */
120
- interface CodeSkeletonSettings {
121
- enabled: boolean;
122
- }
123
- /**
124
- * Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
125
- * Absent fields inherit the preset defaults; the section is only meaningful
126
- * while the resolved profile is `tokenpilot-inspired`.
127
- */
128
- interface PresetOptionsSettings {
129
- readonly dedupeToolResults?: boolean;
130
- readonly summaryLocator?: boolean;
131
- readonly prefixStabilizer?: boolean;
132
- readonly readState?: boolean;
133
- readonly estimatorMode?: '' | 'host' | 'direct';
134
- /**
135
- * Estimator endpoint fields. Persisted-settings only: they never enter the
136
- * frozen CompressionPolicy, which is emitted verbatim by policy-resolved
137
- * audits, so the API key cannot leak into logs.
138
- */
139
- readonly estimatorProvider?: string;
140
- readonly estimatorModel?: string;
141
- readonly estimatorBaseUrl?: string;
142
- readonly estimatorApiKey?: string;
143
- readonly estimatorTimeoutMs?: number;
144
- }
145
- /** Durable global preference exposed through `ctx.settings`. */
146
- interface ContextCompressionSettings {
147
- /** Default strategy snapped when a Session first reaches the pruner. */
148
- profile: CompressionProfile;
149
- /** Versioned Custom policy snapped with `profile` for a newly observed Session. */
150
- custom: CustomCompressionPolicy;
151
- /** Auto Compact trigger preference snapped with `profile` for a newly observed Session. */
152
- autoCompact: AutoCompactSettings;
153
- /** Code-skeleton reducer gate snapped independently of `profile`. */
154
- codeSkeleton: CodeSkeletonSettings;
155
- /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
156
- presetOptions?: PresetOptionsSettings;
157
- }
158
- /** Token-gated policy with character fields limited to reducer candidate shape. */
159
- interface ToolResultPruneConfig {
160
- /** Composition fallback when Host settings are unavailable. Defaults to `balanced`. */
161
- profile?: CompressionProfile;
162
- /** Native fallback leading Unicode code points. Defaults to `4096`. */
163
- headChars?: number;
164
- /** Native fallback trailing Unicode code points. Defaults to `1024`. */
165
- tailChars?: number;
166
- /** Native original-content token trigger. Profile default when omitted. */
167
- nativeTriggerTokens?: number;
168
- /** Native replacement token target. Profile default when omitted. */
169
- nativeTargetTokens?: number;
170
- /** Fresh-result exact-token trigger. Profile default when omitted. */
171
- freshTriggerTokens?: number;
172
- /** Maximum fresh-result exact-token replacement size. Profile default when omitted. */
173
- freshTargetTokens?: number;
174
- /** Combined completed-step token pressure that starts aggregate reduction. */
175
- aggregateTriggerTokens?: number;
176
- /** Aggregate token target after completed-step pressure exceeds its trigger. */
177
- aggregateTargetTokens?: number;
178
- /** Total live tool-result tokens that permit historical aging. Profile default when omitted. */
179
- historyTriggerTokens?: number;
180
- /** Recent completed agent tool calls protected from historical aging. Profile default when omitted. */
181
- historyKeepRecentToolCalls?: number;
182
- /** Recent tool-result token tail protected in addition to tool calls. Profile default when omitted. */
183
- historyKeepRecentTokens?: number;
184
- /** Minimum reclaim required before historical aging is worth a cache break. Profile default when omitted. */
185
- historyMinReclaimTokens?: number;
186
- /**
187
- * Auto Compact threshold percent frozen into this deployment by the preset
188
- * overlay generation (50–90 integer). When present it supersedes the live
189
- * Host setting so one generation never splits Auto Compact and micro
190
- * compact across two thresholds.
191
- */
192
- autoCompactThresholdPercent?: number;
193
- /** Optional tokenpilot-inspired sub-capability overrides (deploy-level). */
194
- presetOptions?: PresetOptionsSettings;
195
- }
196
- /** Resolved per-profile behavior. */
197
- interface CompressionPolicy {
198
- readonly profile: CompressionProfile;
199
- /** Whether this Session may use the selector's native-style head/middle/tail reducer. */
200
- readonly nativeToolResultEnabled: boolean;
201
- readonly freshEnabled: boolean;
202
- readonly aggregateEnabled: boolean;
203
- readonly historyMode: HistoryMode;
204
- readonly nativeTriggerTokens: number;
205
- readonly nativeTargetTokens: number;
206
- readonly freshTriggerTokens: number;
207
- readonly freshTargetTokens: number;
208
- readonly aggregateTriggerTokens: number;
209
- readonly aggregateTargetTokens: number;
210
- readonly historyTriggerTokens: number;
211
- readonly historyKeepRecentToolCalls: number;
212
- readonly historyKeepRecentTokens: number;
213
- readonly historyMinReclaimTokens: number;
214
- /**
215
- * Auto Compact token watermark `A = floor(C × a)` when the standard-profile
216
- * History linkage resolved for this Session; absent for Custom, Off, Native,
217
- * or unresolved routed capacity.
218
- */
219
- readonly autoCompactTokens?: number;
220
- /**
221
- * Micro-compact last-chance watermark `D = floor(A × 0.875)`. Absent when
222
- * {@link autoCompactTokens} is absent; capacity-pressure gates fall back to
223
- * the fixed 0.7 routed-context ratio in that case.
224
- */
225
- readonly microDeadlineTokens?: number;
226
- /** Present for Custom v3; standard profiles and legacy Custom policies carry no TailTrim policy. */
227
- readonly tailTrim?: {
228
- readonly enabled: boolean;
229
- readonly triggerTokens: number;
230
- };
231
- /**
232
- * TokenPilot-inspired sub-capability switches. Present only for the
233
- * `tokenpilot-inspired` preset; every other profile stays byte-identical.
234
- */
235
- readonly presetOptions?: PresetOptions;
236
- }
237
- /** Validated, detached, deeply immutable configuration. */
238
- interface ResolvedConfig {
239
- readonly profile: CompressionProfile;
240
- readonly headChars: number;
241
- readonly tailChars: number;
242
- readonly nativeTriggerTokens?: number;
243
- readonly nativeTargetTokens?: number;
244
- readonly freshTriggerTokens?: number;
245
- readonly freshTargetTokens?: number;
246
- readonly aggregateTriggerTokens?: number;
247
- readonly aggregateTargetTokens?: number;
248
- readonly historyTriggerTokens?: number;
249
- readonly historyKeepRecentToolCalls?: number;
250
- readonly historyKeepRecentTokens?: number;
251
- readonly historyMinReclaimTokens?: number;
252
- /**
253
- * Auto Compact threshold percent frozen into this deployment by the preset
254
- * overlay generation (50-90 integer). Supersedes the live Host setting.
255
- */
256
- readonly autoCompactThresholdPercent?: number;
257
- /** Optional tokenpilot-inspired sub-capability overrides resolved from the deployment config. */
258
- readonly presetOptions?: PresetOptionsSettings;
259
- }
260
- /** Why a pruning pass runs. */
261
- type PruneStage = 'fresh' | 'pressure';
262
- /** Optional control over one pruning pass. */
263
- interface PruneSessionOptions {
264
- /** `fresh` only reduces never-before-seen oversized results; `pressure` may age older results too. */
265
- stage?: PruneStage;
266
- /** Routed model context capacity used only to resolve a context-percent Custom snapshot. */
267
- contextWindowTokens?: number;
268
- /** Proposed turn at the pre-step boundary. Used with `freshStep` to freeze keep/reduce decisions. */
269
- freshTurn?: number;
270
- /** The immediately preceding completed step whose tool results have not yet entered a model request. */
271
- freshStep?: number;
272
- }
273
- /** Cited source event and size accounting for one landed surface replacement. */
274
- interface PrunedEntry {
275
- /** Current surface event shadowed by this replacement. */
276
- readonly originalSeq: number;
277
- /** Root full-fidelity source event used in the recovery reference. */
278
- readonly sourceSeq: number;
279
- /** Newly appended compressed tool-result event. */
280
- readonly replacementSeq: number;
281
- /** Tool call shared by the original and replacement. */
282
- readonly callId: CallId;
283
- /** Reducer or aging strategy that produced the replacement. */
284
- readonly reducer: string;
285
- /** Pass stage that landed the replacement. */
286
- readonly stage: PruneStage;
287
- /** Original deterministic pressure cost. */
288
- readonly charsBefore: number;
289
- /** Replacement deterministic pressure cost. */
290
- readonly charsAfter: number;
291
- /** Authoritative exact canonical content tokens before replacement. */
292
- readonly tokensBefore: number;
293
- /** Authoritative exact canonical content tokens after replacement. */
294
- readonly tokensAfter: number;
295
- }
296
- /** Aggregate outcome of one stable-surface pruning pass. */
297
- interface PruneResult {
298
- /** Replacements in landing order. */
299
- readonly pruned: readonly PrunedEntry[];
300
- /** Total deterministic pressure cost removed across replacements. */
301
- readonly charsRemoved: number;
302
- /** Authoritative exact canonical content tokens removed. */
303
- readonly tokensRemoved: number;
304
- }
305
- //#endregion
306
- //#region src/runtime/tokenpilot/estimator.d.ts
307
- /** Per-session estimator failure bookkeeping for exponential backoff. */
308
- interface EstimatorFailures {
309
- failures: number;
310
- cooldownUntil: number;
311
- }
312
- //#endregion
313
- //#region src/pruner/state.d.ts
314
- /** Mutable per-session state bag used inside {@link ToolResultPruner}. */
315
- interface PrunerState {
316
- /** Resolved immutable deployment configuration. */
317
- readonly config: ResolvedConfig;
318
- /** Complete canonical setting document frozen when each Session first reaches this root service. */
319
- readonly sessionSettings: WeakMap<Session, ContextCompressionSettings>;
320
- /** Original result seqs whose first-exposure KEEP/REDUCE decision has committed. */
321
- readonly firstExposure: WeakMap<Session, Set<number>>;
322
- /** Result seqs permanently exempt from further reduction (recovery outputs and registered equivalents). */
323
- readonly recoveryExemptions: WeakMap<Session, Set<number>>;
324
- /** Per-session canonical-content hash index backing tokenpilot-inspired dedupe. */
325
- readonly dedupeTables: WeakMap<Session, DedupeTable>;
326
- /** Advisory estimator verdicts consumed by the read-state classification. */
327
- readonly estimatorVerdicts: WeakMap<Session, Map<number, boolean>>;
328
- /** Per-session estimator failure backoff state. */
329
- readonly estimatorFailures: WeakMap<Session, EstimatorFailures>;
330
- /** Runtime prerequisite warnings deduplicated per Session and failure key. */
331
- readonly warnedFailures: WeakMap<Session, Set<string>>;
332
- /** Last Adaptive postflight attempt emitted per Session; keeps diagnostics bounded and independent. */
333
- readonly postflightDiagnostics: WeakMap<Session, string>;
334
- /** Current pre-step chain identity, shared by this producer and downstream compaction-basic. */
335
- readonly activeRequestBoundaries: WeakMap<Session, object>;
336
- /** Boundary identity that already attempted one fully preflighted TailTrim publication. */
337
- readonly tailTrimBoundaryAttempts: WeakMap<Session, object>;
338
- /** Last effective policy audit key emitted for each Session. */
339
- readonly policyResolutionAudits: WeakMap<Session, string>;
340
- }
341
- //#endregion
342
- //#region src/runtime/custom-policy.d.ts
343
- /** Canonical Custom document accepted by Host settings and the runtime resolver. */
344
- declare const CustomCompressionPolicySchema: z<CustomCompressionPolicy>;
345
- /** Balanced-equivalent Custom policy stored as one token-canonical document. */
346
- declare const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3;
347
- /** Routed model facts needed only by context-percent Custom documents. */
348
- interface CustomPolicyResolutionOptions {
349
- /** Positive resolved shared model context capacity. */
350
- readonly contextWindowTokens?: number;
351
- /**
352
- * Frozen Auto Compact threshold percent. Standard profiles use it to link
353
- * History watermarks to the Auto Compact level; Custom resolution ignores it
354
- * because Custom stays explicit-token manual.
355
- */
356
- readonly autoCompactThresholdPercent?: number;
357
- }
358
- /**
359
- * Resolve one validated Custom document to the same token policy used by public presets.
360
- * @param value - untrusted or typed Custom settings value.
361
- * @param options - routed model capacity for context-percent documents.
362
- * @returns a detached deeply immutable effective token policy.
363
- */
364
- declare function resolveCustomPolicy(value: CustomCompressionPolicy, options?: CustomPolicyResolutionOptions): CompressionPolicy;
365
- //#endregion
366
- //#region src/runtime/config.d.ts
367
- /** Settings namespace shared by the Host service and browser selector. */
368
- declare const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = "context-compression";
369
- /** Fixed native fallback marker. */
370
- declare const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
371
- /**
372
- * The one Auto Compact threshold contract shared by the settings UI, the
373
- * persisted settings schema, and the runtime resolver. Every integer in the
374
- * range is valid and entered directly in the UI.
375
- */
376
- declare const AUTO_COMPACT_THRESHOLD_LIMITS: {
377
- readonly min: 50;
378
- readonly max: 90;
379
- readonly step: 1;
380
- readonly default: 80;
381
- };
382
- /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
383
- declare function isValidAutoCompactThresholdPercent(value: unknown): value is number;
384
- /**
385
- * Parse one settings document with the persisted-section semantics: `undefined`
386
- * inherits the defaults (an absent section), while `null` is an explicitly
387
- * invalid document and must never silently become the default policy.
388
- */
389
- declare function parseContextCompressionSettings(value: unknown): ContextCompressionSettings;
390
- /** Settings schema used by the user-facing profile selector. */
391
- declare const ContextCompressionSettingsSchema: z<ContextCompressionSettings>;
392
- /** Low-friction defaults; token budgets live in resolved profile policy. */
393
- declare const DEFAULTS: ResolvedConfig;
394
- /**
395
- * Count Unicode code points without splitting surrogate pairs.
396
- * @param text - text whose code points are counted.
397
- * @returns the number of Unicode code points.
398
- */
399
- declare function codePointLength(text: string): number;
400
- /**
401
- * Test whether a settings value names a supported compression profile.
402
- * @param value - untrusted settings value.
403
- * @returns whether the value is a supported compression profile.
404
- */
405
- declare function isCompressionProfile(value: unknown): value is CompressionProfile;
406
- /**
407
- * Resolve and validate plugin configuration.
408
- * @param config - optional composition overrides.
409
- * @returns a detached, deeply immutable configuration snapshot.
410
- */
411
- declare function resolveConfig(config?: ToolResultPruneConfig): ResolvedConfig;
412
- /**
413
- * Resolve one public profile into a complete mixed-strategy policy.
414
- * @param config - validated composition configuration.
415
- * @param profile - profile frozen for the target Session.
416
- * @param custom - versioned Custom document used only by the `custom` profile.
417
- * @param options - routed capacity and the frozen Auto Compact threshold used
418
- * to resolve context-percent Custom values and standard-profile linkage.
419
- * @returns the effective deterministic compression policy.
420
- */
421
- declare function resolvePolicy(config: ResolvedConfig, profile: CompressionProfile, custom?: CustomCompressionPolicy, options?: CustomPolicyResolutionOptions): CompressionPolicy;
422
- //#endregion
423
- //#region src/runtime/reducers.d.ts
424
- /** Deterministic, evidence-backed reducers for fresh tool results. */
425
- /** Input shared by every fresh-result reducer. */
426
- interface ReducerInput {
427
- readonly toolName: string;
428
- readonly argumentsText: string;
429
- readonly text: string;
430
- readonly budgetChars: number;
431
- readonly sourceRef: string;
432
- readonly isError: boolean;
433
- /**
434
- * Orthogonal user gate for the `hypa-code-skeleton` candidate. Absent or
435
- * false keeps source-code content on its existing head/tail reducers.
436
- */
437
- readonly codeSkeleton?: boolean;
438
- }
439
- /** One verified reducer candidate. */
440
- interface ReducerOutput {
441
- readonly text: string;
442
- readonly reducer: string;
443
- readonly lossy: boolean;
444
- }
445
- /**
446
- * Select a reducer from verified tool, command, and content evidence.
447
- * @param input - original result text, recovery source, and output budget.
448
- * @returns a verified candidate, or `null` when every reducer fails open.
449
- */
450
- declare function reduceFreshToolResult(input: ReducerInput): ReducerOutput | null;
451
- /**
452
- * Build a recoverable placeholder for an old tool result.
453
- * @param input - tool identity, source reference, size, status, and retained evidence.
454
- * @returns a lossy placeholder that cites the immutable source event.
455
- */
456
- declare function historicalPlaceholder(input: {
457
- readonly toolName: string;
458
- readonly sourceRef: string;
459
- readonly charsBefore: number;
460
- readonly isError: boolean;
461
- readonly text: string;
462
- readonly compact?: boolean;
463
- }): ReducerOutput;
464
- /**
465
- * Validate shrinkage, budget, recovery, and error retention.
466
- * @param input - original reducer input and its safety requirements.
467
- * @param output - candidate reduced text and reducer metadata.
468
- * @returns whether the candidate is safe to land.
469
- */
470
- declare function verifyReduction(input: ReducerInput, output: ReducerOutput): boolean;
471
- /**
472
- * Strip ANSI, collapse carriage-return progress redraws, and fold exact repeats.
473
- * @param text - raw terminal output.
474
- * @returns normalized terminal text.
475
- */
476
- declare function normalizeTerminalText(text: string): string;
477
- //#endregion
478
- //#region src/runtime/token-count.d.ts
479
- /** Token counts owned by the standalone compression runtime. */
480
- /** Exact count of one canonical value under a pinned tokenizer artifact. */
481
- interface ExactTokenizerTokenCount {
482
- readonly kind: 'exact-tokenizer';
483
- readonly tokens: number;
484
- readonly tokenizerId: string;
485
- readonly tokenizerRevision: string;
486
- }
487
- /** A value that the bundled tokenizer cannot safely count. */
488
- interface UnavailableTokenCount {
489
- readonly kind: 'unavailable';
490
- readonly reason: string;
491
- }
492
- /** Best-effort estimate carrying a conservative upper value when available. */
493
- interface TokenizerEstimateTokenCount {
494
- readonly kind: 'tokenizer-estimate';
495
- readonly tokens: number;
496
- readonly upperBoundTokens: number;
497
- readonly estimatorId: string;
498
- readonly estimatorRevision: string;
499
- readonly calibration?: Readonly<{
500
- readonly sampleCount: number;
501
- readonly conservativeMarginTokens: number;
502
- }>;
503
- }
504
- /** Exact, conservative request estimate, or an explicit refusal. */
505
- type TokenCount = ExactTokenizerTokenCount | TokenizerEstimateTokenCount | UnavailableTokenCount;
506
- //#endregion
507
- //#region src/runtime/measurement.d.ts
508
- /** Request identity retained only when every dimension is publicly known. */
509
- interface ProviderMeasurementKey {
510
- readonly provider: string;
511
- readonly baseUrlClass: string;
512
- readonly apiRoute: string;
513
- readonly modelId: string;
514
- readonly requestTemplateRevision: string;
515
- readonly tokenizerRevision: string;
516
- readonly modality: string;
517
- }
518
- /** Rich request observation used by Adaptive when a future public API supplies it. */
519
- interface ObservedPromptUsage {
520
- readonly attemptId: string;
521
- readonly providerRequestOrdinal: number;
522
- readonly startedAtMs: number;
523
- readonly completedAtMs: number;
524
- readonly measurement: TokenCount;
525
- readonly observedPromptTokens: number;
526
- readonly observedOutputTokens?: number;
527
- readonly responseModelId?: string;
528
- readonly cacheStatus?: 'complete' | 'unknown';
529
- readonly cacheReadTokens?: number;
530
- readonly cacheMissTokens?: number;
531
- readonly key?: ProviderMeasurementKey;
532
- }
533
- /**
534
- * Intrinsic-grid diagnostic attached to nodes whose count estimates images.
535
- * It reports ONLY the official block
536
- * arithmetic evaluated on the attachment's intrinsic dimensions at the two
537
- * alignment-padding extremes (compress-pad 0 and 3). It is NOT a request-token
538
- * bound: the adapter may still re-project the image (per-route pixel-budget
539
- * or image-detail overrides, byte-cap reprojection), which can move the real
540
- * count below the diagnostic minimum. It never participates in exact gates,
541
- * rewrite proofs, or any lossy decision.
542
- */
543
- interface IntrinsicImageBlockDiagnostic {
544
- readonly paddingMinimumTokens: number;
545
- readonly paddingMaximumTokens: number;
546
- }
547
- /** One same-revision surface node with exact, estimated, or unavailable count. */
548
- interface MeasuredTokenSurfaceNode {
549
- readonly seq: number;
550
- readonly count: TokenCount;
551
- /** Intrinsic-grid diagnostic when usable image dimensions were available. */
552
- readonly intrinsicImageBlockEstimate?: IntrinsicImageBlockDiagnostic;
553
- }
554
- /** Compression view derived only from published Session and TokenMeter methods. */
555
- interface CompactionTokenView extends TokenMeasurement {
556
- readonly providerRoute?: string;
557
- readonly modelId?: string;
558
- readonly measuredNodes: readonly MeasuredTokenSurfaceNode[];
559
- readonly currentSurface: TokenCount;
560
- /** Sum of per-node intrinsic padding minima; a diagnostic, not a token bound. */
561
- readonly intrinsicImageBlockEstimateTokens: number;
562
- readonly latestEnvelopeKey?: ProviderMeasurementKey;
563
- readonly lastCompletedUsage?: ObservedPromptUsage;
564
- countCanonicalText(text: string): TokenCount;
565
- }
566
- /**
567
- * Capture one route-bound view without calling patched Harness methods.
568
- * Official `measure()` remains authoritative for request pressure; the bundled
569
- * tokenizer supplies exact canonical content counts used by safe rewrites.
570
- */
571
- declare function measureForCompaction(ctx: Context, session: Session): CompactionTokenView;
572
- //#endregion
573
- //#region src/pruner.d.ts
574
- declare module '@deepseek-ai/cordis' {
575
- interface Context {
576
- toolResultPruner: ToolResultPruner;
577
- }
578
- }
579
- /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
580
- declare class ToolResultPruner extends Service {
581
- static inject: string[];
582
- static Config: z<ToolResultPruneConfig>;
583
- /** Consolidated per-session mutable state. */
584
- readonly state: PrunerState;
585
- constructor(ctx: Context, config?: ToolResultPruneConfig);
586
- /**
587
- * Measure text content in Unicode code points; non-text blocks cost zero.
588
- * @param blocks - tool-result content to measure.
589
- * @returns total Unicode code points across text blocks.
590
- */
591
- measureContent(blocks: readonly ContentBlock[]): number;
592
- /**
593
- * Apply the configured native head/middle/tail transform.
594
- * @param blocks - original tool-result content.
595
- * @returns reduced content, or `null` when no reduction is required.
596
- */
597
- pruneContent(blocks: readonly ContentBlock[]): ContentBlock[] | null;
598
- /**
599
- * Run one stable-surface pass. `fresh` is invoked before every request and
600
- * only reduces original oversized results. `pressure` is called by
601
- * compaction-basic and may additionally age old results at one high-water.
602
- * @param session - session whose current tool-result surface may be rewritten.
603
- * @param options - pass stage and optional completed-step coordinates.
604
- * @returns landed replacements and aggregate Unicode-code-point savings.
605
- */
606
- pruneSession(session: Session, options?: PruneSessionOptions): PruneResult;
607
- private activeSettings;
608
- /**
609
- * TokenPilot-inspired A2: replace the compaction summary checkpoint node
610
- * with the same summary plus an Exact Sources locator block. Fails open:
611
- * any unresolved shape (no trace, no checkpoint node, already annotated)
612
- * leaves the summary untouched.
613
- */
614
- private attachSummaryLocator;
615
- /**
616
- * TokenPilot-inspired E1: sample oversized historical reads and ask the
617
- * auxiliary estimator whether their file state is still likely to be
618
- * referenced. Fire-and-forget: never awaited on the pruning chain, failures
619
- * back off exponentially per Session, verdicts only extend the rule-only
620
- * superseded classification.
621
- */
622
- private postflightEstimatorPass;
623
- private activePolicy;
624
- private contextWindowForRequest;
625
- private runRequestBoundary;
626
- /** Resolve historical-aging authority without accepting caller-supplied elevation. */
627
- private historyAllowed;
628
- /**
629
- * Match the compaction-basic pressure gate using public durable data. The
630
- * frozen Auto Compact deadline `D = floor(A x 0.875)` replaces the legacy
631
- * fixed 0.7 ratio once the standard-profile linkage resolved; without
632
- * linkage the 0.7 ratio is the documented fallback and reproduces the
633
- * previous behavior.
634
- */
635
- private capacityPressureActive;
636
- /** Emit one bounded, independently correlatable postflight cost diagnostic per completed attempt. */
637
- private logAdaptivePostflight;
638
- /** Decide one already-planned History batch from adjacent request-level facts only. */
639
- private adaptiveHistoryAllowed;
640
- private decisions;
641
- /**
642
- * TokenPilot-style skipReduction: recovery tool output is permanently exempt
643
- * from every reduction pass so retrieved content can never enter a
644
- * compress-restore-oscillation loop. A call-name match covers the built-in
645
- * recovery tool; the per-session set admits future recovery paths.
646
- */
647
- private isRecoveryExempt;
648
- /** Register a result seq as permanently exempt from further reduction. */
649
- private grantRecoveryExemption;
650
- private decideFreshStep;
651
- private snapshot;
652
- private planNative;
653
- /**
654
- * TokenPilot-inspired A1: replace a byte-identical repeat of an earlier
655
- * oversized tool result with a pointer to its first occurrence. The first
656
- * occurrence's hash is always recorded so later repeats can point at the
657
- * append-only original event even after the surface copy is reduced.
658
- */
659
- private planDedupe;
660
- private planFresh;
661
- private planAggregate;
662
- /** Preserve bounded diagnostic evidence whenever an all-text error is reduced. */
663
- private planErrorEvidence;
664
- private planHistoricalAging;
665
- private protectedHistoryResultSeqs;
666
- /** Select the newest completed tool calls and token tail for History-derived stages. */
667
- private protectedHistoryCandidateSeqs;
668
- /** Atomically replace at most one oldest safe completed tool-call group. */
669
- private landOldestTailTrimGroup;
670
- private reserveTailTrimBoundaryAttempt;
671
- private uniqueAppendRoot;
672
- private plan;
673
- private land;
674
- private landAll;
675
- private hasRecoveryTool;
676
- private auditHistoryEvaluation;
677
- private auditComponent;
678
- private auditFailure;
679
- private auditPublicationFailure;
680
- private warnExactUnavailable;
681
- private warnOnce;
682
- }
683
- //#endregion
684
- export { AUTO_COMPACT_THRESHOLD_LIMITS, type AutoCompactSettings, COMPRESSION_PROFILES, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, type CodeSkeletonSettings, type CompactionTokenView, type CompressionPolicy, type CompressionProfile, type ContextCompressionSettings, ContextCompressionSettingsSchema, type CustomCompressionBudget, type CustomCompressionPolicy, CustomCompressionPolicySchema, type CustomCompressionPolicyV1, type CustomCompressionPolicyV2, type CustomCompressionPolicyV3, type CustomCompressionUnit, type CustomHistoryPolicy, type CustomPolicyResolutionOptions, type CustomPrefixPolicy, type CustomTailTrimPolicy, DEFAULTS, DEFAULT_CUSTOM_COMPRESSION_POLICY, type HistoryMode, type MeasuredTokenSurfaceNode, PRUNE_MARKER, type PruneResult, type PruneSessionOptions, type PruneStage, type PrunedEntry, type ResolvedConfig, type ToolResultPruneConfig, ToolResultPruner, ToolResultPruner as default, codePointLength, historicalPlaceholder, isCompressionProfile, isValidAutoCompactThresholdPercent, measureForCompaction, normalizeTerminalText, parseContextCompressionSettings, reduceFreshToolResult, resolveConfig, resolveCustomPolicy, resolvePolicy, verifyReduction };
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { Context, Service } from "@deepseek-ai/cordis";
3
+ import { ContentBlock, ToolCallId } from "@deepseek-ai/dsh-llm";
4
+ import { Session } from "@deepseek-ai/dsh-session";
5
+ import { TokenMeasurement } from "@deepseek-ai/dsh-token-meter";
6
+ //#region src/runtime/tokenpilot/dedup.d.ts
7
+ /** Entry stored per first-seen content hash. */
8
+ interface DedupeTableEntry {
9
+ /** First surface seq carrying this canonical content. */
10
+ readonly seq: number;
11
+ /** Session source reference of the first occurrence. */
12
+ readonly sourceRef: string;
13
+ /** Tool name of the first occurrence. */
14
+ readonly toolName: string;
15
+ /** Original full-text code points of the first occurrence. */
16
+ readonly originalChars: number;
17
+ }
18
+ /** Per-session dedup index with insertion-order eviction. */
19
+ declare class DedupeTable {
20
+ private readonly maxEntries;
21
+ private readonly entries;
22
+ constructor(maxEntries?: number);
23
+ /** Look up the first occurrence for one canonical hash, if any. */
24
+ get(hash: string): DedupeTableEntry | undefined;
25
+ /** Record a first occurrence; existing hashes only refresh insertion order. */
26
+ record(hash: string, entry: DedupeTableEntry): void;
27
+ }
28
+ //#endregion
29
+ //#region src/runtime/types.d.ts
30
+ /** User-facing mixed strategy profile. */
31
+ declare const COMPRESSION_PROFILES: readonly ["off", "native", "balanced", "cache-strict", "savings", "adaptive", "tokenpilot-inspired", "custom"];
32
+ /** Public compression strategy selected for one Session. */
33
+ type CompressionProfile = typeof COMPRESSION_PROFILES[number];
34
+ /** When historical tool results may be aged for one Session policy. */
35
+ type HistoryMode = 'disabled' | 'routine' | 'capacity-pressure' | 'adaptive';
36
+ /** Canonical unit stored by one versioned Custom policy. */
37
+ type CustomCompressionUnit = 'tokens' | 'context-percent';
38
+ /** Whether routine History may rewrite a previously sent Harness prefix. */
39
+ type CustomPrefixPolicy = 'preserve' | 'pressure-break';
40
+ /** One independently selectable Custom Fresh or Aggregate stage. */
41
+ interface CustomCompressionBudget {
42
+ enabled: boolean;
43
+ trigger: number;
44
+ target: number;
45
+ }
46
+ /** Legacy Custom History gate and turn/token working-set protection. */
47
+ interface LegacyCustomHistoryPolicy {
48
+ enabled: boolean;
49
+ trigger: number;
50
+ keepRecentTurns: number;
51
+ keepRecent: number;
52
+ minReclaim: number;
53
+ }
54
+ /** Custom History gate and recent tool-call/token working-set protection. */
55
+ interface CustomHistoryPolicy {
56
+ enabled: boolean;
57
+ trigger: number;
58
+ keepRecentToolCalls: number;
59
+ keepRecentTokens: number;
60
+ minReclaim: number;
61
+ }
62
+ /** Custom-only experimental TailTrim gate. */
63
+ interface CustomTailTrimPolicy {
64
+ enabled: boolean;
65
+ trigger: number;
66
+ }
67
+ /** TokenPilot-inspired preset sub-capability switches (only injected for `tokenpilot-inspired`). */
68
+ interface PresetOptions {
69
+ /** Reject replacements whose text is not smaller than the original (G1). */
70
+ readonly noNetSavingsGuard: boolean;
71
+ /** Permanently exempt recovery content from further reduction (G2). */
72
+ readonly skipReductionRecovery: boolean;
73
+ /** Replace byte-identical repeated tool results with first-occurrence pointers (A1). */
74
+ readonly dedupeToolResults: boolean;
75
+ /** Append Exact Sources locator blocks after Auto Compact completes (A2). */
76
+ readonly summaryLocator: boolean;
77
+ /** Volatile-line demotion, deterministic tool ordering, and prefix fingerprint audit (S1/S2). */
78
+ readonly prefixStabilizer: boolean;
79
+ /** Fresh/superseded read-state classification with clustered omission markers (R2/R3). */
80
+ readonly readState: boolean;
81
+ /** Optional estimator channel; `''` keeps every estimator consumer on rule-only fallbacks (E1/E2). */
82
+ readonly estimator: {
83
+ readonly mode: '' | 'host' | 'direct';
84
+ };
85
+ /**
86
+ * Advisory relevance advisor: statistics and suggestions only — every output
87
+ * (summaries, scores, decay, recertification) is observational and must never
88
+ * suppress, delay, or rewrite any reduction that would land. `''` (the
89
+ * default) keeps the advisor fully off.
90
+ */
91
+ readonly advisor: {
92
+ readonly mode: '' | 'host' | 'direct';
93
+ readonly timeoutMs: number;
94
+ readonly refreshTurns: number;
95
+ readonly scoreThreshold: number;
96
+ readonly sampleLimit: number;
97
+ readonly minTokens: number;
98
+ };
99
+ }
100
+ /** Common user-authored Custom stages shared by persisted policy versions. */
101
+ interface CustomCompressionPolicyFields<HistoryPolicy> {
102
+ unit: CustomCompressionUnit;
103
+ fresh: CustomCompressionBudget;
104
+ aggregate: CustomCompressionBudget;
105
+ history: HistoryPolicy;
106
+ prefixPolicy: CustomPrefixPolicy;
107
+ }
108
+ /** Legacy R4 Custom policy, accepted without migration. */
109
+ interface CustomCompressionPolicyV1 extends CustomCompressionPolicyFields<LegacyCustomHistoryPolicy> {
110
+ version: 1;
111
+ }
112
+ /** R5 Custom policy with an explicit default-off TailTrim stage. */
113
+ interface CustomCompressionPolicyV2 extends CustomCompressionPolicyFields<LegacyCustomHistoryPolicy> {
114
+ version: 2;
115
+ tailTrim: CustomTailTrimPolicy;
116
+ }
117
+ /** Custom policy with tool-call working-set protection. */
118
+ interface CustomCompressionPolicyV3 extends CustomCompressionPolicyFields<CustomHistoryPolicy> {
119
+ version: 3;
120
+ tailTrim: CustomTailTrimPolicy;
121
+ }
122
+ /** Strict persisted Custom policy union. */
123
+ type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3;
124
+ /** User-tunable Auto Compact coordination preferences. */
125
+ interface AutoCompactSettings {
126
+ /** Routed-context percentage that triggers model-driven Auto Compact. */
127
+ thresholdPercent: number;
128
+ }
129
+ /**
130
+ * Orthogonal evidence-based code-skeleton reducer gate. Independent of every
131
+ * profile: when enabled, fresh oversized source-code results may take the
132
+ * `hypa-code-skeleton` reducer before the head/tail fallbacks.
133
+ */
134
+ interface CodeSkeletonSettings {
135
+ enabled: boolean;
136
+ }
137
+ /**
138
+ * Orthogonal turn-tail intent-summary gate. Independent of every profile:
139
+ * when enabled, the turn-boundary growth gate may fold consumed-increment
140
+ * tool results into an LLM-written intent block (skeleton + verbatim error
141
+ * lines are kept; the model only ever writes the summary segment).
142
+ */
143
+ interface IntentSummarySettings {
144
+ enabled: boolean;
145
+ }
146
+ /** Floating compression-monitor panel (FAB); visibility switch. */
147
+ interface MonitorPanelSettings {
148
+ enabled: boolean;
149
+ }
150
+ /**
151
+ * Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
152
+ * Absent fields inherit the preset defaults; the section is only meaningful
153
+ * while the resolved profile is `tokenpilot-inspired`.
154
+ */
155
+ interface PresetOptionsSettings {
156
+ readonly dedupeToolResults?: boolean;
157
+ readonly summaryLocator?: boolean;
158
+ readonly prefixStabilizer?: boolean;
159
+ readonly readState?: boolean;
160
+ readonly estimatorMode?: '' | 'host' | 'direct';
161
+ /**
162
+ * Estimator endpoint fields. Persisted-settings only: they never enter the
163
+ * frozen CompressionPolicy, which is emitted verbatim by policy-resolved
164
+ * audits, so the API key cannot leak into logs.
165
+ */
166
+ readonly estimatorProvider?: string;
167
+ readonly estimatorModel?: string;
168
+ readonly estimatorBaseUrl?: string;
169
+ readonly estimatorApiKey?: string;
170
+ readonly estimatorTimeoutMs?: number;
171
+ /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
172
+ readonly advisorMode?: '' | 'host' | 'direct';
173
+ readonly advisorTimeoutMs?: number;
174
+ readonly advisorRefreshTurns?: number;
175
+ readonly advisorScoreThreshold?: number;
176
+ readonly advisorSampleLimit?: number;
177
+ readonly advisorMinTokens?: number;
178
+ }
179
+ /** Durable global preference exposed through `ctx.settings`. */
180
+ interface ContextCompressionSettings {
181
+ /** Default strategy snapped when a Session first reaches the pruner. */
182
+ profile: CompressionProfile;
183
+ /** Versioned Custom policy snapped with `profile` for a newly observed Session. */
184
+ custom: CustomCompressionPolicy;
185
+ /** Auto Compact trigger preference snapped with `profile` for a newly observed Session. */
186
+ autoCompact: AutoCompactSettings;
187
+ /** Code-skeleton reducer gate snapped independently of `profile`. */
188
+ codeSkeleton: CodeSkeletonSettings;
189
+ /** Turn-tail intent-summary gate snapped independently of `profile`. */
190
+ intentSummary: IntentSummarySettings;
191
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
192
+ monitorPanel?: MonitorPanelSettings;
193
+ /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
194
+ presetOptions?: PresetOptionsSettings;
195
+ }
196
+ /** Token-gated policy with character fields limited to reducer candidate shape. */
197
+ interface ToolResultPruneConfig {
198
+ /** Composition fallback when Host settings are unavailable. Defaults to `balanced`. */
199
+ profile?: CompressionProfile;
200
+ /** Native fallback leading Unicode code points. Defaults to `4096`. */
201
+ headChars?: number;
202
+ /** Native fallback trailing Unicode code points. Defaults to `1024`. */
203
+ tailChars?: number;
204
+ /** Native original-content token trigger. Profile default when omitted. */
205
+ nativeTriggerTokens?: number;
206
+ /** Native replacement token target. Profile default when omitted. */
207
+ nativeTargetTokens?: number;
208
+ /** Fresh-result exact-token trigger. Profile default when omitted. */
209
+ freshTriggerTokens?: number;
210
+ /** Maximum fresh-result exact-token replacement size. Profile default when omitted. */
211
+ freshTargetTokens?: number;
212
+ /** Combined completed-step token pressure that starts aggregate reduction. */
213
+ aggregateTriggerTokens?: number;
214
+ /** Aggregate token target after completed-step pressure exceeds its trigger. */
215
+ aggregateTargetTokens?: number;
216
+ /** Total live tool-result tokens that permit historical aging. Profile default when omitted. */
217
+ historyTriggerTokens?: number;
218
+ /** Recent completed agent tool calls protected from historical aging. Profile default when omitted. */
219
+ historyKeepRecentToolCalls?: number;
220
+ /** Recent tool-result token tail protected in addition to tool calls. Profile default when omitted. */
221
+ historyKeepRecentTokens?: number;
222
+ /** Minimum reclaim required before historical aging is worth a cache break. Profile default when omitted. */
223
+ historyMinReclaimTokens?: number;
224
+ /**
225
+ * Read-class input cap in characters. Invariant (startup-asserted in
226
+ * `resolvePolicy`): when set it must exceed `freshTriggerTokens × 4.0` —
227
+ * the conservative chars/token upper bound — otherwise the cap sits below
228
+ * the fresh trigger and silently silences the fresh path for every read
229
+ * result. Unset profiles (host cap 50k–59.5k chars observed) stay untouched.
230
+ */
231
+ readInputCapChars?: number;
232
+ /**
233
+ * Auto Compact threshold percent frozen into this deployment by the preset
234
+ * overlay generation (50–90 integer). When present it supersedes the live
235
+ * Host setting so one generation never splits Auto Compact and micro
236
+ * compact across two thresholds.
237
+ */
238
+ autoCompactThresholdPercent?: number;
239
+ /** Optional tokenpilot-inspired sub-capability overrides (deploy-level). */
240
+ presetOptions?: PresetOptionsSettings;
241
+ }
242
+ /** Resolved per-profile behavior. */
243
+ interface CompressionPolicy {
244
+ readonly profile: CompressionProfile;
245
+ /** Whether this Session may use the selector's native-style head/middle/tail reducer. */
246
+ readonly nativeToolResultEnabled: boolean;
247
+ readonly freshEnabled: boolean;
248
+ readonly aggregateEnabled: boolean;
249
+ readonly historyMode: HistoryMode;
250
+ readonly nativeTriggerTokens: number;
251
+ readonly nativeTargetTokens: number;
252
+ readonly freshTriggerTokens: number;
253
+ readonly freshTargetTokens: number;
254
+ readonly aggregateTriggerTokens: number;
255
+ readonly aggregateTargetTokens: number;
256
+ readonly historyTriggerTokens: number;
257
+ readonly historyKeepRecentToolCalls: number;
258
+ readonly historyKeepRecentTokens: number;
259
+ readonly historyMinReclaimTokens: number;
260
+ /**
261
+ * Read-class input cap in characters when configured; absent otherwise.
262
+ * Startup-asserted to exceed `freshTriggerTokens × 4.0` so it can never
263
+ * silently silence the fresh path (G2 invariant).
264
+ */
265
+ readonly readInputCapChars?: number;
266
+ /**
267
+ * Auto Compact token watermark `A = floor(C × a)` when the standard-profile
268
+ * History linkage resolved for this Session; absent for Custom, Off, Native,
269
+ * or unresolved routed capacity.
270
+ */
271
+ readonly autoCompactTokens?: number;
272
+ /**
273
+ * Micro-compact last-chance watermark `D = floor(A × 0.875)`. Absent when
274
+ * {@link autoCompactTokens} is absent; capacity-pressure gates fall back to
275
+ * the fixed 0.7 routed-context ratio in that case.
276
+ */
277
+ readonly microDeadlineTokens?: number;
278
+ /** Present for Custom v3; standard profiles and legacy Custom policies carry no TailTrim policy. */
279
+ readonly tailTrim?: {
280
+ readonly enabled: boolean;
281
+ readonly triggerTokens: number;
282
+ };
283
+ /**
284
+ * TokenPilot-inspired sub-capability switches. Present only for the
285
+ * `tokenpilot-inspired` preset; every other profile stays byte-identical.
286
+ */
287
+ readonly presetOptions?: PresetOptions;
288
+ }
289
+ /** Validated, detached, deeply immutable configuration. */
290
+ interface ResolvedConfig {
291
+ readonly profile: CompressionProfile;
292
+ readonly headChars: number;
293
+ readonly tailChars: number;
294
+ readonly nativeTriggerTokens?: number;
295
+ readonly nativeTargetTokens?: number;
296
+ readonly freshTriggerTokens?: number;
297
+ readonly freshTargetTokens?: number;
298
+ readonly aggregateTriggerTokens?: number;
299
+ readonly aggregateTargetTokens?: number;
300
+ readonly historyTriggerTokens?: number;
301
+ readonly historyKeepRecentToolCalls?: number;
302
+ readonly historyKeepRecentTokens?: number;
303
+ readonly historyMinReclaimTokens?: number;
304
+ /** Read-class input cap in characters when configured; absent otherwise. */
305
+ readonly readInputCapChars?: number;
306
+ /**
307
+ * Auto Compact threshold percent frozen into this deployment by the preset
308
+ * overlay generation (50-90 integer). Supersedes the live Host setting.
309
+ */
310
+ readonly autoCompactThresholdPercent?: number;
311
+ /** Optional tokenpilot-inspired sub-capability overrides resolved from the deployment config. */
312
+ readonly presetOptions?: PresetOptionsSettings;
313
+ }
314
+ /** Why a pruning pass runs. */
315
+ type PruneStage = 'fresh' | 'pressure';
316
+ /** Optional control over one pruning pass. */
317
+ interface PruneSessionOptions {
318
+ /** `fresh` only reduces never-before-seen oversized results; `pressure` may age older results too. */
319
+ stage?: PruneStage;
320
+ /** Routed model context capacity used only to resolve a context-percent Custom snapshot. */
321
+ contextWindowTokens?: number;
322
+ /** Proposed turn at the pre-step boundary. Used with `freshStep` to freeze keep/reduce decisions. */
323
+ freshTurn?: number;
324
+ /** The immediately preceding completed step whose tool results have not yet entered a model request. */
325
+ freshStep?: number;
326
+ }
327
+ /** Cited source event and size accounting for one landed surface replacement. */
328
+ interface PrunedEntry {
329
+ /** Current surface event shadowed by this replacement. */
330
+ readonly originalSeq: number;
331
+ /** Root full-fidelity source event used in the recovery reference. */
332
+ readonly sourceSeq: number;
333
+ /** Newly appended compressed tool-result event. */
334
+ readonly replacementSeq: number;
335
+ /** Tool call shared by the original and replacement. */
336
+ readonly callId: ToolCallId;
337
+ /** Reducer or aging strategy that produced the replacement. */
338
+ readonly reducer: string;
339
+ /** Pass stage that landed the replacement. */
340
+ readonly stage: PruneStage;
341
+ /** Original deterministic pressure cost. */
342
+ readonly charsBefore: number;
343
+ /** Replacement deterministic pressure cost. */
344
+ readonly charsAfter: number;
345
+ /** Authoritative exact canonical content tokens before replacement. */
346
+ readonly tokensBefore: number;
347
+ /** Authoritative exact canonical content tokens after replacement. */
348
+ readonly tokensAfter: number;
349
+ }
350
+ /** Aggregate outcome of one stable-surface pruning pass. */
351
+ interface PruneResult {
352
+ /** Replacements in landing order. */
353
+ readonly pruned: readonly PrunedEntry[];
354
+ /** Total deterministic pressure cost removed across replacements. */
355
+ readonly charsRemoved: number;
356
+ /** Authoritative exact canonical content tokens removed. */
357
+ readonly tokensRemoved: number;
358
+ }
359
+ //#endregion
360
+ //#region src/runtime/tokenpilot/sidechannel.d.ts
361
+ /** Audit record of one side-channel call (Phase 13). All fields optional-safe. */
362
+ interface SideChannelAudit {
363
+ readonly ok: boolean;
364
+ readonly latencyMs: number;
365
+ /** host|direct plus the resolved provider/model identity. */
366
+ readonly channel?: string;
367
+ /** L2 coverage: content shown N of node content total M. */
368
+ readonly coverage?: {
369
+ readonly shown: number;
370
+ readonly total: number;
371
+ };
372
+ readonly reason?: string;
373
+ }
374
+ interface SideChannelRequest {
375
+ readonly system: string;
376
+ readonly user: string;
377
+ readonly signal: AbortSignal;
378
+ }
379
+ /** One bound side channel. `ask` resolves `undefined` on ANY failure. */
380
+ declare class SideChannel {
381
+ private readonly ctx;
382
+ private readonly options;
383
+ private readonly overrides?;
384
+ /**
385
+ * @param overrides - per-consumer overrides of the estimator-named options.
386
+ * The estimator itself never passes them (byte-identical behavior); the
387
+ * advisory advisor passes its own mode/timeout/output budget so both
388
+ * consumers share one transport without sharing one configuration.
389
+ */
390
+ constructor(ctx: Context, options: PresetOptionsSettings, overrides?: {
391
+ readonly mode?: "" | "host" | "direct";
392
+ readonly timeoutMs?: number;
393
+ readonly maxTokens?: number;
394
+ } | undefined);
395
+ private get mode();
396
+ get enabled(): boolean;
397
+ ask(request: SideChannelRequest): Promise<string | undefined>;
398
+ /** Failure-open wrapper that also records one audit record per call. */
399
+ askAudited(request: SideChannelRequest): Promise<{
400
+ text?: string;
401
+ audit: SideChannelAudit;
402
+ }>;
403
+ identity(): string | undefined;
404
+ /** Same host-route resolution as the estimator: explicit, then host default. */
405
+ private resolveHostRoute;
406
+ private askHost;
407
+ private askDirect;
408
+ }
409
+ //#endregion
410
+ //#region src/runtime/tokenpilot/estimator.d.ts
411
+ /** Per-session estimator failure bookkeeping for exponential backoff. */
412
+ interface EstimatorFailures {
413
+ failures: number;
414
+ cooldownUntil: number;
415
+ }
416
+ //#endregion
417
+ //#region src/runtime/tokenpilot/intent-input-mask.d.ts
418
+ type IntentRole = 'read-mask' | 'write-keep' | 'conservative';
419
+ //#endregion
420
+ //#region src/runtime/tokenpilot/intent-fold.d.ts
421
+ /** One staged fold awaiting the next pressure round. */
422
+ interface PendingIntentFold {
423
+ readonly createdAt: number;
424
+ readonly turn: number;
425
+ /** Inclusive seq span of the folded candidates. */
426
+ readonly startSeq: number;
427
+ readonly endSeq: number;
428
+ /** LLM-written summary segment (fail-open parsed, char-capped). */
429
+ readonly summary: string;
430
+ /** Verbatim error lines collected across the batch (never LLM-revoiced). */
431
+ readonly errorLines: readonly string[];
432
+ /** Per-candidate faces: read-mask single lines ride the block, keep-class lines prompt-only. */
433
+ readonly records: ReadonlyArray<{
434
+ readonly seq: number;
435
+ readonly role: IntentRole;
436
+ readonly toolName: string;
437
+ readonly line: string;
438
+ }>;
439
+ /** Characters consumed by the summary-writer call (credit accounting). */
440
+ readonly summaryCallChars: number;
441
+ }
442
+ //#endregion
443
+ //#region src/pruner/state.d.ts
444
+ /** Mutable per-session state bag used inside {@link ToolResultPruner}. */
445
+ interface PrunerState {
446
+ /** Resolved immutable deployment configuration. */
447
+ readonly config: ResolvedConfig;
448
+ /** Complete canonical setting document frozen when each Session first reaches this root service. */
449
+ readonly sessionSettings: WeakMap<Session, ContextCompressionSettings>;
450
+ /** Original result seqs whose first-exposure KEEP/REDUCE decision has committed. */
451
+ readonly firstExposure: WeakMap<Session, Set<number>>;
452
+ /** Result seqs permanently exempt from further reduction (recovery outputs and registered equivalents). */
453
+ readonly recoveryExemptions: WeakMap<Session, Set<number>>;
454
+ /** Per-session canonical-content hash index backing tokenpilot-inspired dedupe. */
455
+ readonly dedupeTables: WeakMap<Session, DedupeTable>;
456
+ /** Advisory estimator verdicts consumed by the read-state classification. */
457
+ readonly estimatorVerdicts: WeakMap<Session, Map<number, boolean>>;
458
+ /** Per-session estimator failure backoff state. */
459
+ readonly estimatorFailures: WeakMap<Session, EstimatorFailures>;
460
+ /** Runtime prerequisite warnings deduplicated per Session and failure key. */
461
+ readonly warnedFailures: WeakMap<Session, Set<string>>;
462
+ /** Last Adaptive postflight attempt emitted per Session; keeps diagnostics bounded and independent. */
463
+ readonly postflightDiagnostics: WeakMap<Session, string>;
464
+ /** Current pre-step chain identity, shared by this producer and downstream compaction-basic. */
465
+ readonly activeRequestBoundaries: WeakMap<Session, object>;
466
+ /** Boundary identity that already attempted one fully preflighted TailTrim publication. */
467
+ readonly tailTrimBoundaryAttempts: WeakMap<Session, object>;
468
+ /** Last effective policy audit key emitted for each Session. */
469
+ readonly policyResolutionAudits: WeakMap<Session, string>;
470
+ /** Last observed turn index per Session: the monotonic clock for advisory records. */
471
+ readonly turnClocks: WeakMap<Session, number>;
472
+ /** Estimator-reported remaining turns Ŝ per Session; advisory only. */
473
+ readonly estimatorRemainingTurns: WeakMap<Session, number>;
474
+ /** Per-session advisor side channel, constructed once with the advisor overrides. */
475
+ readonly advisorChannels: WeakMap<Session, SideChannel>;
476
+ /** Staged intent fold awaiting the next pressure round (at most one per session). */
477
+ readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>;
478
+ /** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
479
+ readonly intentFoldedSeqs: WeakMap<Session, Set<number>>;
480
+ /** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
481
+ readonly intentBaselines: WeakMap<Session, number>;
482
+ }
483
+ //#endregion
484
+ //#region src/runtime/custom-policy.d.ts
485
+ /** Canonical Custom document accepted by Host settings and the runtime resolver. */
486
+ declare const CustomCompressionPolicySchema: z<CustomCompressionPolicy>;
487
+ /** Balanced-equivalent Custom policy stored as one token-canonical document. */
488
+ declare const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3;
489
+ /** Routed model facts needed only by context-percent Custom documents. */
490
+ interface CustomPolicyResolutionOptions {
491
+ /** Positive resolved shared model context capacity. */
492
+ readonly contextWindowTokens?: number;
493
+ /**
494
+ * Frozen Auto Compact threshold percent. Standard profiles use it to link
495
+ * History watermarks to the Auto Compact level; Custom resolution ignores it
496
+ * because Custom stays explicit-token manual.
497
+ */
498
+ readonly autoCompactThresholdPercent?: number;
499
+ }
500
+ /**
501
+ * Resolve one validated Custom document to the same token policy used by public presets.
502
+ * @param value - untrusted or typed Custom settings value.
503
+ * @param options - routed model capacity for context-percent documents.
504
+ * @returns a detached deeply immutable effective token policy.
505
+ */
506
+ declare function resolveCustomPolicy(value: CustomCompressionPolicy, options?: CustomPolicyResolutionOptions): CompressionPolicy;
507
+ //#endregion
508
+ //#region src/runtime/config.d.ts
509
+ /** Settings namespace shared by the Host service and browser selector. */
510
+ declare const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = "context-compression";
511
+ /** Fixed native fallback marker. */
512
+ declare const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
513
+ /**
514
+ * The one Auto Compact threshold contract shared by the settings UI, the
515
+ * persisted settings schema, and the runtime resolver. Every integer in the
516
+ * range is valid and entered directly in the UI.
517
+ */
518
+ declare const AUTO_COMPACT_THRESHOLD_LIMITS: {
519
+ readonly min: 50;
520
+ readonly max: 90;
521
+ readonly step: 1;
522
+ readonly default: 80;
523
+ };
524
+ /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
525
+ declare function isValidAutoCompactThresholdPercent(value: unknown): value is number;
526
+ /**
527
+ * Parse one settings document with the persisted-section semantics: `undefined`
528
+ * inherits the defaults (an absent section), while `null` is an explicitly
529
+ * invalid document and must never silently become the default policy.
530
+ */
531
+ declare function parseContextCompressionSettings(value: unknown): ContextCompressionSettings;
532
+ /** Settings schema used by the user-facing profile selector. */
533
+ declare const ContextCompressionSettingsSchema: z<ContextCompressionSettings>;
534
+ /** Low-friction defaults; token budgets live in resolved profile policy. */
535
+ declare const DEFAULTS: ResolvedConfig;
536
+ /**
537
+ * Count Unicode code points without splitting surrogate pairs.
538
+ * @param text - text whose code points are counted.
539
+ * @returns the number of Unicode code points.
540
+ */
541
+ declare function codePointLength(text: string): number;
542
+ /**
543
+ * Test whether a settings value names a supported compression profile.
544
+ * @param value - untrusted settings value.
545
+ * @returns whether the value is a supported compression profile.
546
+ */
547
+ declare function isCompressionProfile(value: unknown): value is CompressionProfile;
548
+ /**
549
+ * Resolve and validate plugin configuration.
550
+ * @param config - optional composition overrides.
551
+ * @returns a detached, deeply immutable configuration snapshot.
552
+ */
553
+ declare function resolveConfig(config?: ToolResultPruneConfig): ResolvedConfig;
554
+ /**
555
+ * Resolve one public profile into a complete mixed-strategy policy.
556
+ * @param config - validated composition configuration.
557
+ * @param profile - profile frozen for the target Session.
558
+ * @param custom - versioned Custom document used only by the `custom` profile.
559
+ * @param options - routed capacity and the frozen Auto Compact threshold used
560
+ * to resolve context-percent Custom values and standard-profile linkage.
561
+ * @returns the effective deterministic compression policy.
562
+ */
563
+ declare function resolvePolicy(config: ResolvedConfig, profile: CompressionProfile, custom?: CustomCompressionPolicy, options?: CustomPolicyResolutionOptions): CompressionPolicy;
564
+ //#endregion
565
+ //#region src/runtime/reducers.d.ts
566
+ /** Deterministic, evidence-backed reducers for fresh tool results. */
567
+ /** Input shared by every fresh-result reducer. */
568
+ interface ReducerInput {
569
+ readonly toolName: string;
570
+ readonly argumentsText: string;
571
+ readonly text: string;
572
+ readonly budgetChars: number;
573
+ readonly sourceRef: string;
574
+ readonly isError: boolean;
575
+ /**
576
+ * Orthogonal user gate for the `hypa-code-skeleton` candidate. Absent or
577
+ * false keeps source-code content on its existing head/tail reducers.
578
+ */
579
+ readonly codeSkeleton?: boolean;
580
+ }
581
+ /** One verified reducer candidate. */
582
+ interface ReducerOutput {
583
+ readonly text: string;
584
+ readonly reducer: string;
585
+ readonly lossy: boolean;
586
+ /**
587
+ * Structured telemetry (task_4c/G7): how many ORIGINAL-event lines the
588
+ * reducer elided, when the reducer knows it. Never printed into `text` —
589
+ * host-side logging is what turns this into the compress→retrieve M/N ratio.
590
+ */
591
+ readonly elidedLines?: number;
592
+ }
593
+ /**
594
+ * Optional side-channel ranking (S1a/S1b) handed to the form-dispatched
595
+ * reducers. Selection and order ONLY — the mechanical fold stays the sole
596
+ * content authority, and `undefined` reproduces the mechanical output
597
+ * byte-for-byte. The ranking itself always comes from outside the reducers:
598
+ * the mechanical layer never calls a model.
599
+ */
600
+ interface ReductionRanking {
601
+ /** Search file paths, most relevant first (S1a). Unknown paths are ignored. */
602
+ readonly files?: readonly string[];
603
+ /** Document section heading texts, most relevant first (S1b). */
604
+ readonly sections?: readonly string[];
605
+ }
606
+ /**
607
+ * Select a reducer from verified tool, command, and content evidence.
608
+ * @param input - original result text, recovery source, and output budget.
609
+ * @returns a verified candidate, or `null` when every reducer fails open.
610
+ */
611
+ declare function reduceFreshToolResult(input: ReducerInput, ranking?: ReductionRanking): ReducerOutput | null;
612
+ /**
613
+ * Build a recoverable placeholder for an old tool result.
614
+ * @param input - tool identity, source reference, size, status, and retained evidence.
615
+ * @returns a lossy placeholder that cites the immutable source event.
616
+ */
617
+ declare function historicalPlaceholder(input: {
618
+ readonly toolName: string;
619
+ readonly sourceRef: string;
620
+ readonly charsBefore: number;
621
+ readonly isError: boolean;
622
+ readonly text: string;
623
+ readonly compact?: boolean;
624
+ }): ReducerOutput;
625
+ /**
626
+ * Validate shrinkage, budget, recovery, and error retention.
627
+ * @param input - original reducer input and its safety requirements.
628
+ * @param output - candidate reduced text and reducer metadata.
629
+ * @returns whether the candidate is safe to land.
630
+ */
631
+ declare function verifyReduction(input: ReducerInput, output: ReducerOutput): boolean;
632
+ /**
633
+ * Strip ANSI, collapse carriage-return progress redraws, and fold exact repeats.
634
+ * @param text - raw terminal output.
635
+ * @returns normalized terminal text.
636
+ */
637
+ declare function normalizeTerminalText(text: string): string;
638
+ //#endregion
639
+ //#region src/runtime/token-count.d.ts
640
+ /** Token counts owned by the standalone compression runtime. */
641
+ /** Exact count of one canonical value under a pinned tokenizer artifact. */
642
+ interface ExactTokenizerTokenCount {
643
+ readonly kind: 'exact-tokenizer';
644
+ readonly tokens: number;
645
+ readonly tokenizerId: string;
646
+ readonly tokenizerRevision: string;
647
+ }
648
+ /** A value that the bundled tokenizer cannot safely count. */
649
+ interface UnavailableTokenCount {
650
+ readonly kind: 'unavailable';
651
+ readonly reason: string;
652
+ }
653
+ /** Best-effort estimate carrying a conservative upper value when available. */
654
+ interface TokenizerEstimateTokenCount {
655
+ readonly kind: 'tokenizer-estimate';
656
+ readonly tokens: number;
657
+ readonly upperBoundTokens: number;
658
+ readonly estimatorId: string;
659
+ readonly estimatorRevision: string;
660
+ readonly calibration?: Readonly<{
661
+ readonly sampleCount: number;
662
+ readonly conservativeMarginTokens: number;
663
+ }>;
664
+ }
665
+ /** Exact, conservative request estimate, or an explicit refusal. */
666
+ type TokenCount = ExactTokenizerTokenCount | TokenizerEstimateTokenCount | UnavailableTokenCount;
667
+ //#endregion
668
+ //#region src/runtime/measurement.d.ts
669
+ /** Request identity retained only when every dimension is publicly known. */
670
+ interface ProviderMeasurementKey {
671
+ readonly provider: string;
672
+ readonly baseUrlClass: string;
673
+ readonly apiRoute: string;
674
+ readonly modelId: string;
675
+ readonly requestTemplateRevision: string;
676
+ readonly tokenizerRevision: string;
677
+ readonly modality: string;
678
+ }
679
+ /** Rich request observation used by Adaptive when a future public API supplies it. */
680
+ interface ObservedPromptUsage {
681
+ readonly attemptId: string;
682
+ readonly providerRequestOrdinal: number;
683
+ readonly startedAtMs: number;
684
+ readonly completedAtMs: number;
685
+ readonly measurement: TokenCount;
686
+ readonly observedPromptTokens: number;
687
+ readonly observedOutputTokens?: number;
688
+ readonly responseModelId?: string;
689
+ readonly cacheStatus?: 'complete' | 'unknown';
690
+ readonly cacheReadTokens?: number;
691
+ readonly cacheMissTokens?: number;
692
+ readonly key?: ProviderMeasurementKey;
693
+ }
694
+ /**
695
+ * Intrinsic-grid diagnostic attached to nodes whose count estimates images.
696
+ * It reports ONLY the official block
697
+ * arithmetic evaluated on the attachment's intrinsic dimensions at the two
698
+ * alignment-padding extremes (compress-pad 0 and 3). It is NOT a request-token
699
+ * bound: the adapter may still re-project the image (per-route pixel-budget
700
+ * or image-detail overrides, byte-cap reprojection), which can move the real
701
+ * count below the diagnostic minimum. It never participates in exact gates,
702
+ * rewrite proofs, or any lossy decision.
703
+ */
704
+ interface IntrinsicImageBlockDiagnostic {
705
+ readonly paddingMinimumTokens: number;
706
+ readonly paddingMaximumTokens: number;
707
+ }
708
+ /** One same-revision surface node with exact, estimated, or unavailable count. */
709
+ interface MeasuredTokenSurfaceNode {
710
+ readonly seq: number;
711
+ readonly count: TokenCount;
712
+ /**
713
+ * Authoritative decision metric for this node: character pressure in
714
+ * Unicode code points (same convention as SnapshotCandidate.characterPressure).
715
+ */
716
+ readonly characterPressure: number;
717
+ /** Intrinsic-grid diagnostic when usable image dimensions were available. */
718
+ readonly intrinsicImageBlockEstimate?: IntrinsicImageBlockDiagnostic;
719
+ }
720
+ /** Compression view derived only from published Session and TokenMeter methods. */
721
+ interface CompactionTokenView extends TokenMeasurement {
722
+ readonly providerRoute?: string;
723
+ readonly modelId?: string;
724
+ readonly measuredNodes: readonly MeasuredTokenSurfaceNode[];
725
+ readonly currentSurface: TokenCount;
726
+ /**
727
+ * Exact character analogue of `currentSurface`: sum of per-node
728
+ * `characterPressure` over the same nodes `currentSurface` covers.
729
+ */
730
+ readonly currentSurfaceChars: number;
731
+ /** Sum of per-node intrinsic padding minima; a diagnostic, not a token bound. */
732
+ readonly intrinsicImageBlockEstimateTokens: number;
733
+ readonly latestEnvelopeKey?: ProviderMeasurementKey;
734
+ readonly lastCompletedUsage?: ObservedPromptUsage;
735
+ countCanonicalText(text: string): TokenCount;
736
+ }
737
+ /**
738
+ * Capture one route-bound view without calling patched Harness methods.
739
+ * Official `measure()` remains authoritative for request pressure; the bundled
740
+ * tokenizer supplies exact canonical content counts used by safe rewrites.
741
+ */
742
+ declare function measureForCompaction(ctx: Context, session: Session): CompactionTokenView;
743
+ //#endregion
744
+ //#region src/pruner.d.ts
745
+ declare module '@deepseek-ai/cordis' {
746
+ interface Context {
747
+ toolResultPruner: ToolResultPruner;
748
+ }
749
+ }
750
+ /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
751
+ declare class ToolResultPruner extends Service {
752
+ static inject: string[];
753
+ static Config: z<ToolResultPruneConfig>;
754
+ /** Consolidated per-session mutable state. */
755
+ readonly state: PrunerState;
756
+ /** 0.1.5-specific: per-session sets of already-audited native summary seqs. */
757
+ private readonly auditedNativeSummaries;
758
+ constructor(ctx: Context, config?: ToolResultPruneConfig);
759
+ /**
760
+ * Measure text content in Unicode code points; non-text blocks cost zero.
761
+ * @param blocks - tool-result content to measure.
762
+ * @returns total Unicode code points across text blocks.
763
+ */
764
+ /**
765
+ * Apply the configured native head/middle/tail transform.
766
+ * @param blocks - original tool-result content.
767
+ * @returns reduced content, or `null` when no reduction is required.
768
+ */
769
+ pruneContent(blocks: readonly ContentBlock[]): ContentBlock[] | null;
770
+ /**
771
+ * Run one stable-surface pass. `fresh` is invoked before every request and
772
+ * only reduces original oversized results. `pressure` is called by
773
+ * compaction-basic and may additionally age old results at one high-water.
774
+ * @param session - session whose current tool-result surface may be rewritten.
775
+ * @param options - pass stage and optional completed-step coordinates.
776
+ * @returns landed replacements and aggregate Unicode-code-point savings.
777
+ */
778
+ pruneSession(session: Session, options?: PruneSessionOptions): PruneResult;
779
+ private activeSettings;
780
+ /**
781
+ * TokenPilot-inspired A2: replace the compaction summary checkpoint node
782
+ * with the same summary plus an Exact Sources locator block. Fails open:
783
+ * any unresolved shape (no trace, no checkpoint node, already annotated)
784
+ * leaves the summary untouched.
785
+ */
786
+ private attachSummaryLocator;
787
+ /**
788
+ * TokenPilot-inspired E1: sample oversized historical reads and ask the
789
+ * auxiliary estimator whether their file state is still likely to be
790
+ * referenced. Fire-and-forget: never awaited on the pruning chain, failures
791
+ * back off exponentially per Session, verdicts only extend the rule-only
792
+ * superseded classification.
793
+ */
794
+ private postflightEstimatorPass;
795
+ /**
796
+ * Advisory advisor pass at the turn boundary, strictly fire-and-forget.
797
+ * Produces todolist-bound tail-task summaries, incremental relevance
798
+ * scores, and a prefix-decay figure — all observational. Every short
799
+ * circuit below (mode off, re-entry, cooldown, no task semantics, no
800
+ * direct endpoint) returns without touching any state the pruning chain
801
+ * reads, so the default configuration adds exactly zero behavior.
802
+ */
803
+ private postflightAdvisorPass;
804
+ /**
805
+ * Fire-and-forget postflight: evaluate the growth gate, and only when it
806
+ * passes, select the consumed increment OUTSIDE the protected working set,
807
+ * mask it to semantic-role records, and spend ONE summary-writer call. The
808
+ * verdict stages as a pending fold that the NEXT pressure round lands via
809
+ * the ordinary plan/apply machinery — the synchronous decision path never
810
+ * waits on an LLM.
811
+ */
812
+ private postflightIntentFoldPass;
813
+ /**
814
+ * Convert a staged pending fold into per-candidate planned replacements
815
+ * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
816
+ * rich-content, or no longer exists keeps its original text. Returns
817
+ * `undefined` when there is nothing (or no longer anything) to fold.
818
+ */
819
+ private applyPendingIntentFold;
820
+ /**
821
+ * Monotonic per-session turn clock for advisory records. Bumped by the agent
822
+ * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
823
+ * observed value.
824
+ */
825
+ private turnClock;
826
+ /**
827
+ * Advisory benefit-model hook — what the retired human-gated review pipeline
828
+ * left behind. It is the IDENTITY on the landing path: every plan it is given
829
+ * comes back unchanged, because a reduction must never block automatic
830
+ * processing. The model's band is published as a `reduction-advice` audit and
831
+ * snapshotted onto the advisor state for the read-only report route, so the
832
+ * cache-accounting insight survives without a gate.
833
+ */
834
+ private adviseReplacements;
835
+ private activePolicy;
836
+ private contextWindowForRequest;
837
+ private runRequestBoundary;
838
+ /** Resolve historical-aging authority without accepting caller-supplied elevation. */
839
+ private historyAllowed;
840
+ /**
841
+ * Match the compaction-basic pressure gate using public durable data. The
842
+ * frozen Auto Compact deadline `D = floor(A x 0.875)` replaces the legacy
843
+ * fixed 0.7 ratio once the standard-profile linkage resolved; without
844
+ * linkage the 0.7 ratio is the documented fallback and reproduces the
845
+ * previous behavior.
846
+ */
847
+ private capacityPressureActive;
848
+ /** Emit one bounded, independently correlatable postflight cost diagnostic per completed attempt. */
849
+ private logAdaptivePostflight;
850
+ /** Decide one already-planned History batch from adjacent request-level facts only. */
851
+ private adaptiveHistoryAllowed;
852
+ private decisions;
853
+ /**
854
+ * TokenPilot-style skipReduction: recovery tool output is permanently exempt
855
+ * from every reduction pass so retrieved content can never enter a
856
+ * compress-restore-oscillation loop. A call-name match covers the built-in
857
+ * recovery tool; the per-session set admits future recovery paths.
858
+ */
859
+ private isRecoveryExempt;
860
+ /** Register a result seq as permanently exempt from further reduction. */
861
+ private grantRecoveryExemption;
862
+ private decideFreshStep;
863
+ private snapshot;
864
+ private planNative;
865
+ /**
866
+ * TokenPilot-inspired A1: replace a byte-identical repeat of an earlier
867
+ * oversized tool result with a pointer to its first occurrence. The first
868
+ * occurrence's hash is always recorded so later repeats can point at the
869
+ * append-only original event even after the surface copy is reduced.
870
+ */
871
+ private planDedupe;
872
+ private planFresh;
873
+ private planAggregate;
874
+ /** Preserve bounded diagnostic evidence whenever an all-text error is reduced. */
875
+ private planErrorEvidence;
876
+ private planHistoricalAging;
877
+ private protectedHistoryResultSeqs;
878
+ /** Select the newest completed tool calls and token tail for History-derived stages. */
879
+ private protectedHistoryCandidateSeqs;
880
+ /** Atomically replace at most one oldest safe completed tool-call group. */
881
+ private landOldestTailTrimGroup;
882
+ private reserveTailTrimBoundaryAttempt;
883
+ private uniqueAppendRoot;
884
+ private plan;
885
+ private land;
886
+ private landAll;
887
+ private hasRecoveryTool;
888
+ private auditHistoryEvaluation;
889
+ private auditComponent;
890
+ /** Emit the native-auto-compact audit for one summary manifest, once. */
891
+ private emitNativeSummaryAudit;
892
+ /**
893
+ * 0.1.5 commits Native auto-compact by reopening the Session with a seed
894
+ * log; seed events never reach the `session/event` firehose, so scan the
895
+ * snapshot for summary manifests the live listener could not observe.
896
+ */
897
+ private scanForSeededNativeSummary;
898
+ private auditFailure;
899
+ private auditPublicationFailure;
900
+ private warnExactUnavailable;
901
+ private warnOnce;
902
+ }
903
+ //#endregion
904
+ export { AUTO_COMPACT_THRESHOLD_LIMITS, type AutoCompactSettings, COMPRESSION_PROFILES, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, type CodeSkeletonSettings, type CompactionTokenView, type CompressionPolicy, type CompressionProfile, type ContextCompressionSettings, ContextCompressionSettingsSchema, type CustomCompressionBudget, type CustomCompressionPolicy, CustomCompressionPolicySchema, type CustomCompressionPolicyV1, type CustomCompressionPolicyV2, type CustomCompressionPolicyV3, type CustomCompressionUnit, type CustomHistoryPolicy, type CustomPolicyResolutionOptions, type CustomPrefixPolicy, type CustomTailTrimPolicy, DEFAULTS, DEFAULT_CUSTOM_COMPRESSION_POLICY, type HistoryMode, type MeasuredTokenSurfaceNode, PRUNE_MARKER, type PruneResult, type PruneSessionOptions, type PruneStage, type PrunedEntry, type ToolResultPruneConfig, ToolResultPruner, ToolResultPruner as default, codePointLength, historicalPlaceholder, isCompressionProfile, isValidAutoCompactThresholdPercent, measureForCompaction, normalizeTerminalText, parseContextCompressionSettings, reduceFreshToolResult, resolveConfig, resolveCustomPolicy, resolvePolicy, verifyReduction };