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,842 +1,1713 @@
1
- import z from "@deepseek-ai/schemastery";
2
- //#region src/runtime/types.ts
3
- /** User-facing mixed strategy profile. */
4
- const COMPRESSION_PROFILES = [
5
- "off",
6
- "native",
7
- "balanced",
8
- "cache-strict",
9
- "savings",
10
- "adaptive",
11
- "tokenpilot-inspired",
12
- "custom"
13
- ];
14
- //#endregion
15
- //#region src/runtime/value.ts
16
- /** Version-neutral immutable-value and closed-union helpers for the plugin runtime. */
17
- /**
18
- * Freeze an object graph in place without relying on a Harness utility export.
19
- * Live AbortSignals remain mutable so request cancellation continues to work.
20
- * @param value - Value to freeze recursively.
21
- * @returns The same deeply frozen value.
22
- */
23
- function deepFreeze(value) {
24
- const seen = /* @__PURE__ */ new WeakSet();
25
- const pending = [{
26
- kind: "visit",
27
- node: value
28
- }];
29
- while (pending.length > 0) {
30
- const task = pending.pop();
31
- /* v8 ignore next -- the loop condition guarantees one pending task. */
32
- if (task === void 0) continue;
33
- if (task.kind === "property") {
34
- pending.push({
35
- kind: "visit",
36
- node: task.source[task.key]
37
- });
38
- continue;
39
- }
40
- const node = task.node;
41
- if (node === null || typeof node !== "object" || node instanceof AbortSignal || seen.has(node)) continue;
42
- seen.add(node);
43
- Object.freeze(node);
44
- const keys = Object.keys(node);
45
- for (let index = keys.length - 1; index >= 0; index--) {
46
- const key = keys[index];
47
- /* v8 ignore next -- the loop is bounded by the captured key count. */
48
- if (key === void 0) continue;
49
- pending.push({
50
- kind: "property",
51
- source: node,
52
- key
53
- });
54
- }
55
- }
56
- return value;
57
- }
58
- /**
59
- * Throw for an impossible member of a closed discriminated union.
60
- * @param value - Value that escaped its closed union type.
61
- * @param context - Optional switch-site label.
62
- * @returns Never returns.
63
- */
64
- function assertNever(value, context) {
65
- const rendered = JSON.stringify(value) ?? String(value);
66
- throw new Error(`unreachable variant${context === void 0 ? "" : ` in ${context}`}: ${rendered}`);
67
- }
68
- //#endregion
69
- //#region src/runtime/custom-policy.ts
70
- /** Strict versioned Custom policy parsing and effective-token resolution. */
71
- const budgetSchema = z.object({
72
- enabled: z.boolean().required(),
73
- trigger: z.number().required(),
74
- target: z.number().required()
75
- }).required();
76
- const legacyHistorySchema = z.object({
77
- enabled: z.boolean().required(),
78
- trigger: z.number().required(),
79
- keepRecentTurns: z.number().step(1).min(0).required(),
80
- keepRecent: z.number().required(),
81
- minReclaim: z.number().required()
82
- }).required();
83
- const historySchema = z.object({
84
- enabled: z.boolean().required(),
85
- trigger: z.number().required(),
86
- keepRecentToolCalls: z.number().step(1).min(0).required(),
87
- keepRecentTokens: z.number().required(),
88
- minReclaim: z.number().required()
89
- }).required();
90
- const tailTrimSchema = z.object({
91
- enabled: z.boolean().required(),
92
- trigger: z.number().required()
93
- }).required();
94
- const customCompressionPolicyV1InputSchema = z.object({
95
- version: z.const(1).required(),
96
- unit: z.union(["tokens", "context-percent"]).required(),
97
- fresh: budgetSchema,
98
- aggregate: budgetSchema,
99
- history: legacyHistorySchema,
100
- prefixPolicy: z.union(["preserve", "pressure-break"]).required()
101
- }).required();
102
- const customCompressionPolicyV2InputSchema = z.object({
103
- version: z.const(2).required(),
104
- unit: z.union(["tokens", "context-percent"]).required(),
105
- fresh: budgetSchema,
106
- aggregate: budgetSchema,
107
- history: legacyHistorySchema,
108
- prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
109
- tailTrim: tailTrimSchema
110
- }).required();
111
- const customCompressionPolicyV3InputSchema = z.object({
112
- version: z.const(3).required(),
113
- unit: z.union(["tokens", "context-percent"]).required(),
114
- fresh: budgetSchema,
115
- aggregate: budgetSchema,
116
- history: historySchema,
117
- prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
118
- tailTrim: tailTrimSchema
119
- }).required();
120
- /** Canonical Custom document accepted by Host settings and the runtime resolver. */
121
- const CustomCompressionPolicySchema = z.transform(z.any().required(), (value) => {
122
- assertExactPolicyShape(value);
123
- const canonical = canonicalizeCustomPolicy(value.version === 1 ? customCompressionPolicyV1InputSchema(value) : value.version === 2 ? customCompressionPolicyV2InputSchema(value) : customCompressionPolicyV3InputSchema(value));
124
- assertCanonicalRelations(canonical);
125
- return deepFreeze(structuredClone(canonical));
126
- });
127
- /** Balanced-equivalent Custom policy stored as one token-canonical document. */
128
- const DEFAULT_CUSTOM_COMPRESSION_POLICY = deepFreeze({
129
- version: 3,
130
- unit: "tokens",
131
- fresh: {
132
- enabled: true,
133
- trigger: 8192,
134
- target: 3072
135
- },
136
- aggregate: {
137
- enabled: true,
138
- trigger: 32768,
139
- target: 12288
140
- },
141
- history: {
142
- enabled: true,
143
- trigger: 5e5,
144
- keepRecentToolCalls: 10,
145
- keepRecentTokens: 64e3,
146
- minReclaim: 96e3
147
- },
148
- prefixPolicy: "pressure-break",
149
- tailTrim: {
150
- enabled: false,
151
- trigger: 7e5
152
- }
153
- });
154
- /**
155
- * Resolve one validated Custom document to the same token policy used by public presets.
156
- * @param value - untrusted or typed Custom settings value.
157
- * @param options - routed model capacity for context-percent documents.
158
- * @returns a detached deeply immutable effective token policy.
159
- */
160
- function resolveCustomPolicy(value, options = {}) {
161
- const policy = canonicalizeCustomPolicy(CustomCompressionPolicySchema(value));
162
- const effective = (name, amount) => {
163
- if (policy.unit === "tokens") return amount;
164
- const contextWindow = options.contextWindowTokens;
165
- if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) throw new Error("Custom context-percent policy requires a resolved positive model context window");
166
- const tokens = Math.floor(contextWindow * amount / 100);
167
- if (!Number.isSafeInteger(tokens) || amount > 0 && tokens <= 0) throw new Error(`Custom ${name} has no valid effective token value for this model`);
168
- return tokens;
169
- };
170
- const resolved = {
171
- profile: "custom",
172
- nativeToolResultEnabled: false,
173
- freshEnabled: policy.fresh.enabled,
174
- aggregateEnabled: policy.aggregate.enabled,
175
- historyMode: !policy.history.enabled ? "disabled" : policy.prefixPolicy === "preserve" ? "capacity-pressure" : "routine",
176
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
177
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
178
- freshTriggerTokens: effective("Fresh trigger", policy.fresh.trigger),
179
- freshTargetTokens: effective("Fresh target", policy.fresh.target),
180
- aggregateTriggerTokens: effective("Aggregate trigger", policy.aggregate.trigger),
181
- aggregateTargetTokens: effective("Aggregate target", policy.aggregate.target),
182
- historyTriggerTokens: effective("History trigger", policy.history.trigger),
183
- historyKeepRecentToolCalls: policy.history.keepRecentToolCalls,
184
- historyKeepRecentTokens: effective("History recent token tail", policy.history.keepRecentTokens),
185
- historyMinReclaimTokens: effective("History min-reclaim", policy.history.minReclaim),
186
- tailTrim: {
187
- enabled: policy.tailTrim.enabled,
188
- triggerTokens: effective("TailTrim trigger", policy.tailTrim.trigger)
189
- }
190
- };
191
- assertEffectiveRelations(resolved);
192
- return deepFreeze(resolved);
193
- }
194
- function canonicalizeCustomPolicy(policy) {
195
- if (policy.version === 3) return policy;
196
- return {
197
- version: 3,
198
- unit: policy.unit,
199
- fresh: policy.fresh,
200
- aggregate: policy.aggregate,
201
- history: {
202
- enabled: policy.history.enabled,
203
- trigger: policy.history.trigger,
204
- keepRecentToolCalls: 10,
205
- keepRecentTokens: policy.history.keepRecent,
206
- minReclaim: policy.history.minReclaim
207
- },
208
- prefixPolicy: policy.prefixPolicy,
209
- tailTrim: policy.version === 1 ? {
210
- enabled: false,
211
- trigger: 7e5
212
- } : policy.tailTrim
213
- };
214
- }
215
- function measuredValues(policy) {
216
- return [
217
- policy.fresh.trigger,
218
- policy.fresh.target,
219
- policy.aggregate.trigger,
220
- policy.aggregate.target,
221
- policy.history.trigger,
222
- policy.history.keepRecentTokens,
223
- policy.history.minReclaim,
224
- policy.tailTrim.trigger
225
- ];
226
- }
227
- function validMeasuredValues(policy) {
228
- const values = measuredValues(policy);
229
- if (![
230
- policy.fresh.trigger,
231
- policy.fresh.target,
232
- policy.aggregate.trigger,
233
- policy.aggregate.target,
234
- policy.history.trigger,
235
- policy.history.minReclaim,
236
- policy.tailTrim.trigger
237
- ].every((value) => value > 0) || policy.history.keepRecentTokens < 0 || !Number.isSafeInteger(policy.history.keepRecentToolCalls) || policy.history.keepRecentToolCalls < 0) return false;
238
- return policy.unit === "tokens" ? values.every(Number.isSafeInteger) : values.every((value) => Number.isFinite(value) && value <= 100);
239
- }
240
- function assertCanonicalRelations(policy) {
241
- if (!validMeasuredValues(policy)) throw new TypeError("Custom measured values must use the selected canonical unit");
242
- if (policy.fresh.target >= policy.fresh.trigger) throw new TypeError("Custom Fresh target must be below trigger");
243
- if (policy.aggregate.target >= policy.aggregate.trigger) throw new TypeError("Custom Aggregate target must be below trigger");
244
- if (policy.history.minReclaim > policy.history.trigger) throw new TypeError("Custom History min-reclaim must not exceed its trigger");
245
- }
246
- function assertExactPolicyShape(value) {
247
- if (!isPlainRecord$1(value)) throw new TypeError("Custom must be a plain object");
248
- if (value.version !== 1 && value.version !== 2 && value.version !== 3) throw new TypeError("Custom version must be 1, 2, or 3");
249
- assertExactKeys(value, value.version === 1 ? [
250
- "version",
251
- "unit",
252
- "fresh",
253
- "aggregate",
254
- "history",
255
- "prefixPolicy"
256
- ] : [
257
- "version",
258
- "unit",
259
- "fresh",
260
- "aggregate",
261
- "history",
262
- "prefixPolicy",
263
- "tailTrim"
264
- ], "Custom");
265
- assertExactKeys(value.fresh, [
266
- "enabled",
267
- "trigger",
268
- "target"
269
- ], "Custom Fresh");
270
- assertExactKeys(value.aggregate, [
271
- "enabled",
272
- "trigger",
273
- "target"
274
- ], "Custom Aggregate");
275
- assertExactKeys(value.history, value.version === 3 ? [
276
- "enabled",
277
- "trigger",
278
- "keepRecentToolCalls",
279
- "keepRecentTokens",
280
- "minReclaim"
281
- ] : [
282
- "enabled",
283
- "trigger",
284
- "keepRecentTurns",
285
- "keepRecent",
286
- "minReclaim"
287
- ], "Custom History");
288
- if (value.version !== 1) assertExactKeys(value.tailTrim, ["enabled", "trigger"], "Custom TailTrim");
289
- }
290
- function assertExactKeys(value, allowed, label) {
291
- if (!isPlainRecord$1(value)) throw new TypeError(`${label} must be a plain object`);
292
- const allowedKeys = new Set(allowed);
293
- const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
294
- if (unknown !== void 0) throw new TypeError(`${label}: unknown key "${unknown}"`);
295
- }
296
- function isPlainRecord$1(value) {
297
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
298
- const prototype = Object.getPrototypeOf(value);
299
- return prototype === Object.prototype || prototype === null;
300
- }
301
- function assertEffectiveRelations(policy) {
302
- if (policy.freshTargetTokens >= policy.freshTriggerTokens) throw new Error("Custom effective Fresh target must be below trigger");
303
- if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens) throw new Error("Custom effective Aggregate target must be below trigger");
304
- if (policy.historyMinReclaimTokens > policy.historyTriggerTokens) throw new Error("Custom effective History min-reclaim must not exceed its trigger");
305
- }
306
- //#endregion
307
- //#region src/runtime/config.ts
308
- /** Configuration resolution for the mixed deterministic context-compression selector. */
309
- /** Settings namespace shared by the Host service and browser selector. */
310
- const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = "context-compression";
311
- /** Fixed native fallback marker. */
312
- const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
313
- /**
314
- * The one Auto Compact threshold contract shared by the settings UI, the
315
- * persisted settings schema, and the runtime resolver. Every integer in the
316
- * range is valid and entered directly in the UI.
317
- */
318
- const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
319
- min: 50,
320
- max: 90,
321
- step: 1,
322
- default: 80
323
- });
324
- /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
325
- function isValidAutoCompactThresholdPercent(value) {
326
- return typeof value === "number" && Number.isSafeInteger(value) && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max;
327
- }
328
- const AUTO_COMPACT_DEFAULT = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default });
329
- /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
330
- function isPlainRecord(value) {
331
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
332
- const prototype = Object.getPrototypeOf(value);
333
- return prototype === Object.prototype || prototype === null;
334
- }
335
- /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
336
- function assertPlainDataTree(value, seen = /* @__PURE__ */ new WeakSet()) {
337
- if (value === null || typeof value !== "object") return;
338
- if (seen.has(value)) return;
339
- seen.add(value);
340
- if (Array.isArray(value)) {
341
- for (const entry of value) assertPlainDataTree(entry, seen);
342
- return;
343
- }
344
- if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must contain only plain objects");
345
- for (const entry of Object.values(value)) assertPlainDataTree(entry, seen);
346
- }
347
- /**
348
- * Strictly parse the persisted autoCompact section. Schemastery object
349
- * defaults silently absorb null, empty, and extra-key sections, so this stays
350
- * hand-validated beside the top-level unknown-key check.
351
- */
352
- function parseAutoCompactSettings(value) {
353
- if (value === void 0) return AUTO_COMPACT_DEFAULT;
354
- if (!isPlainRecord(value)) throw new TypeError("Context-compression autoCompact must be a plain object");
355
- const keys = Object.keys(value);
356
- if (keys.length !== 1 || keys[0] !== "thresholdPercent") throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join("\", \"")}"`);
357
- const thresholdPercent = value.thresholdPercent;
358
- if (!isValidAutoCompactThresholdPercent(thresholdPercent)) throw new TypeError(`Context-compression autoCompact.thresholdPercent (${String(thresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`);
359
- return { thresholdPercent };
360
- }
361
- /**
362
- * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
363
- * to every profile: absent inherits the lossless `false` default, while a
364
- * present-but-invalid section is an explicitly invalid document.
365
- */
366
- function parseCodeSkeletonSettings(value) {
367
- if (value === void 0) return { enabled: false };
368
- if (!isPlainRecord(value)) throw new TypeError("Context-compression codeSkeleton must be a plain object");
369
- const keys = Object.keys(value);
370
- if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join("\", \"")}"`);
371
- const enabled = value.enabled;
372
- if (typeof enabled !== "boolean") throw new TypeError("Context-compression codeSkeleton.enabled must be a boolean");
373
- return { enabled };
374
- }
375
- /**
376
- * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
377
- * inherits the preset defaults; present-but-invalid is rejected, mirroring the
378
- * codeSkeleton section semantics.
379
- */
380
- function parsePresetOptionsSettings(value) {
381
- if (value === void 0) return void 0;
382
- if (!isPlainRecord(value)) throw new TypeError("Context-compression presetOptions must be a plain object");
383
- const allowed = /* @__PURE__ */ new Set([
384
- "dedupeToolResults",
385
- "summaryLocator",
386
- "prefixStabilizer",
387
- "readState",
388
- "estimatorMode",
389
- "estimatorProvider",
390
- "estimatorModel",
391
- "estimatorBaseUrl",
392
- "estimatorApiKey",
393
- "estimatorTimeoutMs"
394
- ]);
395
- const unknown = Object.keys(value).find((key) => !allowed.has(key));
396
- if (unknown !== void 0) throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`);
397
- for (const key of [
398
- "dedupeToolResults",
399
- "summaryLocator",
400
- "prefixStabilizer",
401
- "readState"
402
- ]) {
403
- const entry = value[key];
404
- if (entry !== void 0 && typeof entry !== "boolean") throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`);
405
- }
406
- const estimatorMode = value.estimatorMode;
407
- if (estimatorMode !== void 0 && estimatorMode !== "" && estimatorMode !== "host" && estimatorMode !== "direct") throw new TypeError("Context-compression presetOptions.estimatorMode must be \"\", \"host\", or \"direct\"");
408
- const estimatorTimeoutMs = value.estimatorTimeoutMs;
409
- if (estimatorTimeoutMs !== void 0 && (typeof estimatorTimeoutMs !== "number" || !Number.isSafeInteger(estimatorTimeoutMs) || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000");
410
- for (const key of [
411
- "estimatorProvider",
412
- "estimatorModel",
413
- "estimatorBaseUrl",
414
- "estimatorApiKey"
415
- ]) {
416
- const entry = value[key];
417
- if (entry !== void 0 && typeof entry !== "string") throw new TypeError(`Context-compression presetOptions.${key} must be a string`);
418
- }
419
- const result = {};
420
- if (value.dedupeToolResults !== void 0) result.dedupeToolResults = value.dedupeToolResults;
421
- if (value.summaryLocator !== void 0) result.summaryLocator = value.summaryLocator;
422
- if (value.prefixStabilizer !== void 0) result.prefixStabilizer = value.prefixStabilizer;
423
- if (value.readState !== void 0) result.readState = value.readState;
424
- if (estimatorMode !== void 0) result.estimatorMode = estimatorMode;
425
- if (value.estimatorProvider !== void 0) result.estimatorProvider = value.estimatorProvider;
426
- if (value.estimatorModel !== void 0) result.estimatorModel = value.estimatorModel;
427
- if (value.estimatorBaseUrl !== void 0) result.estimatorBaseUrl = value.estimatorBaseUrl;
428
- if (value.estimatorApiKey !== void 0) result.estimatorApiKey = value.estimatorApiKey;
429
- if (estimatorTimeoutMs !== void 0) result.estimatorTimeoutMs = estimatorTimeoutMs;
430
- return result;
431
- }
432
- /** Settings schema used by the user-facing profile selector. */
433
- const contextCompressionSettingsInputSchema = z.object({
434
- profile: z.union([...COMPRESSION_PROFILES]).default("balanced"),
435
- custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY)
436
- });
437
- /**
438
- * Reject a section that is PRESENT but not a usable value. Schemastery
439
- * `.default(...)` silently substitutes null and undefined, which would turn a
440
- * hand-corrupted store into the (lossy) default policy; only genuinely absent
441
- * keys may inherit defaults, and that distinction must be made before any
442
- * default can fire.
443
- */
444
- function assertPresentSection(candidate, key, valid) {
445
- if (!Object.hasOwn(candidate, key)) return;
446
- if (!valid(candidate[key])) throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`);
447
- }
448
- const isSupportedProfile = (value) => typeof value === "string" && COMPRESSION_PROFILES.includes(value);
449
- const isUsableCustomDocument = (value) => isPlainRecord(value);
450
- const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
451
- profile: "balanced",
452
- custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
453
- autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
454
- codeSkeleton: { enabled: false }
455
- };
456
- /**
457
- * Parse one settings document with the persisted-section semantics: `undefined`
458
- * inherits the defaults (an absent section), while `null` is an explicitly
459
- * invalid document and must never silently become the default policy.
460
- */
461
- function parseContextCompressionSettings(value) {
462
- if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
463
- const keys = Object.keys(value);
464
- if (keys.length === 0 || !keys.includes("profile") || !keys.includes("custom")) throw new TypeError("Context-compression settings document is missing its complete shape");
465
- return ContextCompressionSettingsSchema(value);
466
- }
467
- /** Settings schema used by the user-facing profile selector. */
468
- const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value) => {
469
- if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
470
- assertPlainDataTree(value);
471
- const candidate = structuredClone(value);
472
- const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "presetOptions");
473
- if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
474
- assertPresentSection(candidate, "profile", isSupportedProfile);
475
- assertPresentSection(candidate, "custom", isUsableCustomDocument);
476
- const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
477
- const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
478
- const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
479
- return {
480
- ...contextCompressionSettingsInputSchema(candidate),
481
- autoCompact,
482
- codeSkeleton,
483
- ...presetOptions === void 0 ? {} : { presetOptions }
484
- };
485
- }).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
486
- /** Low-friction defaults; token budgets live in resolved profile policy. */
487
- const DEFAULTS = deepFreeze({
488
- profile: "balanced",
489
- headChars: 4096,
490
- tailChars: 1024
491
- });
492
- const CONFIG_KEYS = /* @__PURE__ */ new Set([
493
- "profile",
494
- "headChars",
495
- "tailChars",
496
- "nativeTriggerTokens",
497
- "nativeTargetTokens",
498
- "freshTriggerTokens",
499
- "freshTargetTokens",
500
- "aggregateTriggerTokens",
501
- "aggregateTargetTokens",
502
- "historyTriggerTokens",
503
- "historyKeepRecentToolCalls",
504
- "historyKeepRecentTokens",
505
- "historyMinReclaimTokens",
506
- "autoCompactThresholdPercent",
507
- "presetOptions"
508
- ]);
509
- const LEGACY_GATE_REPLACEMENTS = Object.freeze({
510
- thresholdChars: "nativeTriggerTokens",
511
- freshThresholdChars: "freshTriggerTokens",
512
- freshTargetChars: "freshTargetTokens",
513
- freshBatchTriggerChars: "aggregateTriggerTokens",
514
- freshBatchTargetChars: "aggregateTargetTokens",
515
- historyTriggerChars: "historyTriggerTokens",
516
- historyKeepRecentChars: "historyKeepRecentTokens",
517
- historyMinReclaimChars: "historyMinReclaimTokens",
518
- historyKeepRecentTurns: "historyKeepRecentToolCalls"
519
- });
520
- /**
521
- * Count Unicode code points without splitting surrogate pairs.
522
- * @param text - text whose code points are counted.
523
- * @returns the number of Unicode code points.
524
- */
525
- function codePointLength(text) {
526
- let length = 0;
527
- for (const _point of text) length++;
528
- return length;
529
- }
530
- /**
531
- * Test whether a settings value names a supported compression profile.
532
- * @param value - untrusted settings value.
533
- * @returns whether the value is a supported compression profile.
534
- */
535
- function isCompressionProfile(value) {
536
- return typeof value === "string" && COMPRESSION_PROFILES.includes(value);
537
- }
538
- /**
539
- * Resolve and validate plugin configuration.
540
- * @param config - optional composition overrides.
541
- * @returns a detached, deeply immutable configuration snapshot.
542
- */
543
- function resolveConfig(config = {}) {
544
- for (const key of Object.keys(config)) {
545
- const replacement = LEGACY_GATE_REPLACEMENTS[key];
546
- if (replacement !== void 0) throw new Error(`ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; choose "${replacement}" manually in tokens (no character conversion is applied)`);
547
- if (!CONFIG_KEYS.has(key)) throw new Error(`ToolResultPruneConfig: unknown key "${key}"`);
548
- }
549
- const resolved = {
550
- profile: config.profile ?? DEFAULTS.profile,
551
- headChars: config.headChars ?? DEFAULTS.headChars,
552
- tailChars: config.tailChars ?? DEFAULTS.tailChars,
553
- ...config.nativeTriggerTokens === void 0 ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
554
- ...config.nativeTargetTokens === void 0 ? {} : { nativeTargetTokens: config.nativeTargetTokens },
555
- ...config.freshTriggerTokens === void 0 ? {} : { freshTriggerTokens: config.freshTriggerTokens },
556
- ...config.freshTargetTokens === void 0 ? {} : { freshTargetTokens: config.freshTargetTokens },
557
- ...config.aggregateTriggerTokens === void 0 ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
558
- ...config.aggregateTargetTokens === void 0 ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
559
- ...config.historyTriggerTokens === void 0 ? {} : { historyTriggerTokens: config.historyTriggerTokens },
560
- ...config.historyKeepRecentToolCalls === void 0 ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
561
- ...config.historyKeepRecentTokens === void 0 ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
562
- ...config.historyMinReclaimTokens === void 0 ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
563
- ...config.autoCompactThresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
564
- ...config.presetOptions === void 0 ? {} : { presetOptions: config.presetOptions }
565
- };
566
- if (!isCompressionProfile(resolved.profile)) throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`);
567
- assertNonNegativeInteger("headChars", resolved.headChars);
568
- assertNonNegativeInteger("tailChars", resolved.tailChars);
569
- for (const key of [
570
- "nativeTriggerTokens",
571
- "nativeTargetTokens",
572
- "freshTriggerTokens",
573
- "freshTargetTokens",
574
- "aggregateTriggerTokens",
575
- "aggregateTargetTokens",
576
- "historyTriggerTokens",
577
- "historyMinReclaimTokens"
578
- ]) {
579
- const value = resolved[key];
580
- if (value !== void 0) assertPositiveInteger(key, value);
581
- }
582
- if (resolved.historyKeepRecentToolCalls !== void 0) assertNonNegativeInteger("historyKeepRecentToolCalls", resolved.historyKeepRecentToolCalls);
583
- if (resolved.historyKeepRecentTokens !== void 0) assertNonNegativeInteger("historyKeepRecentTokens", resolved.historyKeepRecentTokens);
584
- if (resolved.autoCompactThresholdPercent !== void 0 && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) throw new Error(`ToolResultPruneConfig: autoCompactThresholdPercent (${String(resolved.autoCompactThresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`);
585
- assertTargetBelowTrigger("native", resolved.nativeTargetTokens, resolved.nativeTriggerTokens);
586
- assertTargetBelowTrigger("fresh", resolved.freshTargetTokens, resolved.freshTriggerTokens);
587
- assertTargetBelowTrigger("aggregate", resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens);
588
- return deepFreeze(structuredClone(resolved));
589
- }
590
- /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
591
- const AUTO_COMPACT_HISTORY_RATIOS = Object.freeze({
592
- balanced: Object.freeze({
593
- trigger: .625,
594
- minReclaim: .12,
595
- keepRecentTokens: .08
596
- }),
597
- savings: Object.freeze({
598
- trigger: .5,
599
- minReclaim: .16,
600
- keepRecentTokens: .08
601
- }),
602
- "cache-strict": Object.freeze({
603
- trigger: .75,
604
- minReclaim: .16,
605
- keepRecentTokens: .08
606
- }),
607
- adaptive: Object.freeze({
608
- trigger: .625,
609
- minReclaim: .12,
610
- keepRecentTokens: .08
611
- }),
612
- "tokenpilot-inspired": Object.freeze({
613
- trigger: .625,
614
- minReclaim: .12,
615
- keepRecentTokens: .08
616
- })
617
- });
618
- /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
619
- const MICRO_DEADLINE_RATIO = .875;
620
- /**
621
- * TokenPilot-inspired sub-capability defaults. Every capability is on except
622
- * the estimator, which requires an explicit endpoint channel (host or direct)
623
- * before any consumer may leave its rule-only fallback.
624
- */
625
- const PRESET_OPTION_DEFAULTS = deepFreeze({
626
- noNetSavingsGuard: true,
627
- skipReductionRecovery: true,
628
- dedupeToolResults: true,
629
- summaryLocator: true,
630
- prefixStabilizer: true,
631
- readState: true,
632
- estimator: { mode: "" }
633
- });
634
- /**
635
- * Merge persisted presetOptions overrides over the tokenpilot-inspired
636
- * defaults. Persisted booleans are three-state (undefined = inherit); the
637
- * estimator channel overrides the default empty mode wholesale.
638
- */
639
- function mergePresetOptions(overrides) {
640
- if (overrides === void 0) return PRESET_OPTION_DEFAULTS;
641
- return deepFreeze({
642
- noNetSavingsGuard: true,
643
- skipReductionRecovery: true,
644
- dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
645
- summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
646
- prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
647
- readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
648
- estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode }
649
- });
650
- }
651
- /**
652
- * Resolve the Auto-Compact-linked History watermarks for one standard profile.
653
- *
654
- * `A = floor(C × a)` is the Auto Compact token watermark for the routed
655
- * context window `C` and the user threshold `a = p / 100`; the History
656
- * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
657
- * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
658
- * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
659
- * preset numbers exactly. Custom stays manual and Off/Native run no History,
660
- * so none of them link.
661
- */
662
- function resolveAutoCompactLinkage(profile, options) {
663
- const ratios = profile === "custom" ? void 0 : AUTO_COMPACT_HISTORY_RATIOS[profile];
664
- const contextWindow = options.contextWindowTokens;
665
- const threshold = options.autoCompactThresholdPercent;
666
- if (ratios === void 0) return void 0;
667
- if (!isValidAutoCompactThresholdPercent(threshold)) return void 0;
668
- if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) return void 0;
669
- const autoCompactTokens = Math.floor(contextWindow * (threshold / 100));
670
- if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return void 0;
671
- const linked = {
672
- autoCompactTokens,
673
- microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
674
- historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
675
- historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
676
- historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens)
677
- };
678
- for (const value of Object.values(linked)) if (!Number.isSafeInteger(value) || value <= 0) return void 0;
679
- return linked;
680
- }
681
- /**
682
- * Resolve one public profile into a complete mixed-strategy policy.
683
- * @param config - validated composition configuration.
684
- * @param profile - profile frozen for the target Session.
685
- * @param custom - versioned Custom document used only by the `custom` profile.
686
- * @param options - routed capacity and the frozen Auto Compact threshold used
687
- * to resolve context-percent Custom values and standard-profile linkage.
688
- * @returns the effective deterministic compression policy.
689
- */
690
- function resolvePolicy(config, profile, custom = DEFAULT_CUSTOM_COMPRESSION_POLICY, options = {}) {
691
- if (profile === "custom") return resolveCustomPolicy(custom, options);
692
- const preset = {
693
- off: {
694
- nativeToolResultEnabled: false,
695
- freshEnabled: false,
696
- aggregateEnabled: false,
697
- historyMode: "disabled",
698
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
699
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
700
- freshTriggerTokens: Number.MAX_SAFE_INTEGER,
701
- freshTargetTokens: Number.MAX_SAFE_INTEGER,
702
- aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
703
- aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
704
- historyTriggerTokens: Number.MAX_SAFE_INTEGER,
705
- historyKeepRecentToolCalls: 10,
706
- historyKeepRecentTokens: 64e3,
707
- historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
708
- },
709
- native: {
710
- nativeToolResultEnabled: true,
711
- freshEnabled: false,
712
- aggregateEnabled: false,
713
- historyMode: "disabled",
714
- nativeTriggerTokens: 4096,
715
- nativeTargetTokens: 2048,
716
- freshTriggerTokens: Number.MAX_SAFE_INTEGER,
717
- freshTargetTokens: Number.MAX_SAFE_INTEGER,
718
- aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
719
- aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
720
- historyTriggerTokens: Number.MAX_SAFE_INTEGER,
721
- historyKeepRecentToolCalls: 10,
722
- historyKeepRecentTokens: 64e3,
723
- historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
724
- },
725
- balanced: {
726
- nativeToolResultEnabled: false,
727
- freshEnabled: true,
728
- aggregateEnabled: true,
729
- historyMode: "routine",
730
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
731
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
732
- freshTriggerTokens: 8192,
733
- freshTargetTokens: 3072,
734
- aggregateTriggerTokens: 32768,
735
- aggregateTargetTokens: 12288,
736
- historyTriggerTokens: 5e5,
737
- historyKeepRecentToolCalls: 10,
738
- historyKeepRecentTokens: 64e3,
739
- historyMinReclaimTokens: 96e3
740
- },
741
- "cache-strict": {
742
- nativeToolResultEnabled: false,
743
- freshEnabled: true,
744
- aggregateEnabled: true,
745
- historyMode: "capacity-pressure",
746
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
747
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
748
- freshTriggerTokens: 8192,
749
- freshTargetTokens: 3072,
750
- aggregateTriggerTokens: 32768,
751
- aggregateTargetTokens: 12288,
752
- historyTriggerTokens: 6e5,
753
- historyKeepRecentToolCalls: 10,
754
- historyKeepRecentTokens: 64e3,
755
- historyMinReclaimTokens: 128e3
756
- },
757
- savings: {
758
- nativeToolResultEnabled: false,
759
- freshEnabled: true,
760
- aggregateEnabled: true,
761
- historyMode: "routine",
762
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
763
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
764
- freshTriggerTokens: 4096,
765
- freshTargetTokens: 1536,
766
- aggregateTriggerTokens: 16384,
767
- aggregateTargetTokens: 4096,
768
- historyTriggerTokens: 4e5,
769
- historyKeepRecentToolCalls: 10,
770
- historyKeepRecentTokens: 64e3,
771
- historyMinReclaimTokens: 128e3
772
- },
773
- adaptive: {
774
- nativeToolResultEnabled: false,
775
- freshEnabled: true,
776
- aggregateEnabled: true,
777
- historyMode: "adaptive",
778
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
779
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
780
- freshTriggerTokens: 8192,
781
- freshTargetTokens: 3072,
782
- aggregateTriggerTokens: 32768,
783
- aggregateTargetTokens: 12288,
784
- historyTriggerTokens: 5e5,
785
- historyKeepRecentToolCalls: 10,
786
- historyKeepRecentTokens: 64e3,
787
- historyMinReclaimTokens: 96e3
788
- },
789
- "tokenpilot-inspired": {
790
- nativeToolResultEnabled: false,
791
- freshEnabled: true,
792
- aggregateEnabled: true,
793
- historyMode: "routine",
794
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
795
- nativeTargetTokens: Number.MAX_SAFE_INTEGER,
796
- freshTriggerTokens: 8192,
797
- freshTargetTokens: 3072,
798
- aggregateTriggerTokens: 32768,
799
- aggregateTargetTokens: 12288,
800
- historyTriggerTokens: 5e5,
801
- historyKeepRecentToolCalls: 10,
802
- historyKeepRecentTokens: 64e3,
803
- historyMinReclaimTokens: 96e3
804
- }
805
- }[profile];
806
- const linkage = resolveAutoCompactLinkage(profile, options);
807
- const policy = {
808
- profile,
809
- ...preset,
810
- nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
811
- nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
812
- freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
813
- freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
814
- aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
815
- aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
816
- historyTriggerTokens: config.historyTriggerTokens ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
817
- historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
818
- historyKeepRecentTokens: config.historyKeepRecentTokens ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
819
- historyMinReclaimTokens: config.historyMinReclaimTokens ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
820
- ...linkage === void 0 ? {} : {
821
- autoCompactTokens: linkage.autoCompactTokens,
822
- microDeadlineTokens: linkage.microDeadlineTokens
823
- },
824
- ...profile === "tokenpilot-inspired" ? { presetOptions: mergePresetOptions(config.presetOptions) } : {}
825
- };
826
- if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === "native") throw new Error("context compression policy: native target must be below trigger");
827
- if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: fresh target must be below trigger");
828
- if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: aggregate target must be below trigger");
829
- return deepFreeze(policy);
830
- }
831
- function assertTargetBelowTrigger(label, target, trigger) {
832
- if (target === void 0 !== (trigger === void 0)) throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`);
833
- if (target !== void 0 && trigger !== void 0 && target >= trigger) throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`);
834
- }
835
- function assertPositiveInteger(name, value) {
836
- if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`);
837
- }
838
- function assertNonNegativeInteger(name, value) {
839
- if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
840
- }
841
- //#endregion
842
- export { COMPRESSION_PROFILES as _, PRUNE_MARKER as a, isValidAutoCompactThresholdPercent as c, resolvePolicy as d, CustomCompressionPolicySchema as f, deepFreeze as g, assertNever as h, DEFAULTS as i, parseContextCompressionSettings as l, resolveCustomPolicy as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, codePointLength as o, DEFAULT_CUSTOM_COMPRESSION_POLICY as p, ContextCompressionSettingsSchema as r, isCompressionProfile as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, resolveConfig as u };
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { createHash } from "node:crypto";
3
+ //#region src/runtime/savings.ts
4
+ /**
5
+ * 节省统计账本(诚实口径)。
6
+ *
7
+ * 原则(与 dsh-token-optimizer 类功能对齐的需求口径):
8
+ * 1. **只记已实现**:抵扣来自真实落盘的 rewrite(published replacement)的
9
+ * tokensBefore − tokensAfter,不按"本可以压多少"的最大值计;
10
+ * 2. **负节省(配对抵消)**:同一份原文先被压缩(代码骨架/历史老化/去重指针/
11
+ * 尾裁引用)后,模型又请求了全文——原声称的节省被抵消:全文读取本身
12
+ * 记为负项。净额因此可以为负(骨架 S + 全文 O,对比从未压缩的基线 O,
13
+ * 净 −S),这正是"先骨架再全文 = 负节省"的诚实口径;
14
+ * 3. **口径分列,不混算**:精确 tokenizer 与 chars/4 估算两个 basis 各自独立
15
+ * 汇总,永不合并成一个数。
16
+ *
17
+ * 存储:进程内 per-session 账本(条目环形缓冲 + hash 注册表)。不落盘——
18
+ * 节省统计是运行期面板数据,重启归零是可接受语义(审计日志里已有全量原始记录)。
19
+ *
20
+ * @module dsh-context-compression-improved/runtime/savings
21
+ */
22
+ const MAX_ENTRIES_PER_SESSION = 400;
23
+ const MAX_REGISTRY = 2048;
24
+ var SavingsLedger = class {
25
+ entries = /* @__PURE__ */ new Map();
26
+ registry = /* @__PURE__ */ new Map();
27
+ seenFullText = /* @__PURE__ */ new Set();
28
+ usage = /* @__PURE__ */ new Map();
29
+ startedAt = Date.now();
30
+ /**
31
+ * 累计一次官方 usage(request-boundary 读取上一已完成请求;末次请求在
32
+ * dispose 汇总前未入账属可接受低估)。usage 字段缺省按 0 计。
33
+ */
34
+ recordUsage(sessionId, usage) {
35
+ let total = this.usage.get(sessionId);
36
+ if (total === void 0) {
37
+ total = {
38
+ requests: 0,
39
+ inputTokens: 0,
40
+ outputTokens: 0,
41
+ cacheReadTokens: 0,
42
+ cacheWriteTokens: 0
43
+ };
44
+ this.usage.set(sessionId, total);
45
+ }
46
+ total.requests += 1;
47
+ total.inputTokens += positiveOrZero(usage.inputTokens);
48
+ total.outputTokens += positiveOrZero(usage.outputTokens);
49
+ total.cacheReadTokens += positiveOrZero(usage.cacheReadTokens);
50
+ total.cacheWriteTokens += positiveOrZero(usage.cacheWriteTokens);
51
+ }
52
+ totalsFor(scope) {
53
+ const sum = {
54
+ requests: 0,
55
+ inputTokens: 0,
56
+ outputTokens: 0,
57
+ cacheReadTokens: 0,
58
+ cacheWriteTokens: 0
59
+ };
60
+ for (const sid of scope) {
61
+ const t = this.usage.get(sid);
62
+ if (t === void 0) continue;
63
+ sum.requests += t.requests;
64
+ sum.inputTokens += t.inputTokens;
65
+ sum.outputTokens += t.outputTokens;
66
+ sum.cacheReadTokens += t.cacheReadTokens;
67
+ sum.cacheWriteTokens += t.cacheWriteTokens;
68
+ }
69
+ return sum;
70
+ }
71
+ /** 单行会话汇总(session/disposed 日志用)。 */
72
+ sessionSummaryLine(sessionId) {
73
+ const snap = this.snapshot(sessionId);
74
+ const hit = snap.usage.cacheHitRate;
75
+ return `net=${snap.net.exact}(exact)/${snap.net.estimated}(est) gross=${snap.gross.exact}/${snap.gross.estimated} offsets=${snap.offsets.exact}/${snap.offsets.estimated} requests=${snap.usage.requests} cacheHit=${hit === null ? "–" : `${Math.round(hit * 100)}%`}`;
76
+ }
77
+ /** 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。 */
78
+ recordSaving(input) {
79
+ const removed = input.tokensBefore - input.tokensAfter;
80
+ if (!Number.isFinite(removed) || removed <= 0) return;
81
+ this.push(input.sessionId, {
82
+ kind: "saving",
83
+ component: input.component,
84
+ tokens: removed,
85
+ basis: input.basis,
86
+ at: Date.now()
87
+ });
88
+ if (typeof input.originalText === "string" && input.originalText.length > 0) {
89
+ const hash = savingsHash(input.originalText);
90
+ if (this.registry.size >= MAX_REGISTRY && !this.registry.has(hash)) {
91
+ const oldest = this.registry.keys().next().value;
92
+ if (oldest !== void 0) this.registry.delete(oldest);
93
+ }
94
+ this.registry.set(hash, {
95
+ sessionId: input.sessionId,
96
+ component: input.component,
97
+ claimedTokens: removed,
98
+ basis: input.basis,
99
+ sourceSeq: input.sourceSeq,
100
+ consumed: false
101
+ });
102
+ }
103
+ }
104
+ /**
105
+ * 新的全文工具结果进入上下文(每个 (session, seq) 只看一次):若其原文哈希
106
+ * 命中之前压缩过的条目且未消费过抵消 → 记负项并消费。
107
+ * @param measure 返回 {tokens, basis}——全文按当前可用口径计量。
108
+ */
109
+ noteFullText(input) {
110
+ if (typeof input.text !== "string" || input.text.length === 0) return;
111
+ const seenKey = `${input.sessionId}:${input.seq}`;
112
+ if (this.seenFullText.has(seenKey)) return;
113
+ this.seenFullText.add(seenKey);
114
+ if (this.seenFullText.size > MAX_REGISTRY * 4) {
115
+ this.seenFullText.clear();
116
+ this.seenFullText.add(seenKey);
117
+ }
118
+ const hit = this.registry.get(savingsHash(input.text));
119
+ if (hit === void 0 || hit.consumed || hit.sessionId !== input.sessionId) return;
120
+ hit.consumed = true;
121
+ const { tokens, basis } = input.measure(input.text);
122
+ if (tokens <= 0) return;
123
+ this.push(input.sessionId, {
124
+ kind: "offset",
125
+ component: "full-read",
126
+ tokens,
127
+ basis,
128
+ at: Date.now(),
129
+ note: `#${hit.sourceSeq} ${hit.component} 的原文被全文重读(原声称 −${hit.claimedTokens})`
130
+ });
131
+ }
132
+ /** retrieve 回读(部分或全部)重新进入上下文:按返回内容计量记负项。 */
133
+ recordOffset(input) {
134
+ if (!Number.isFinite(input.tokens) || input.tokens <= 0) return;
135
+ this.push(input.sessionId, {
136
+ kind: "offset",
137
+ component: input.component,
138
+ tokens: input.tokens,
139
+ basis: input.basis,
140
+ at: Date.now(),
141
+ ...input.note === void 0 ? {} : { note: input.note }
142
+ });
143
+ }
144
+ sourceSeqOf(item) {
145
+ return item.sourceSeq;
146
+ }
147
+ push(sessionId, entry) {
148
+ let list = this.entries.get(sessionId);
149
+ if (list === void 0) {
150
+ list = [];
151
+ this.entries.set(sessionId, list);
152
+ }
153
+ list.push(entry);
154
+ if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION);
155
+ }
156
+ /** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
157
+ snapshot(sessionId) {
158
+ const scope = sessionId === void 0 ? [...this.entries.keys()] : [sessionId];
159
+ const totals = {
160
+ grossExact: 0,
161
+ grossEstimated: 0,
162
+ offsetExact: 0,
163
+ offsetEstimated: 0
164
+ };
165
+ const perComponent = /* @__PURE__ */ new Map();
166
+ const recentOffsets = [];
167
+ for (const sid of scope) for (const entry of this.entries.get(sid) ?? []) {
168
+ const exact = entry.basis === "exact-tokenizer";
169
+ if (entry.kind === "saving") {
170
+ if (exact) totals.grossExact += entry.tokens;
171
+ else totals.grossEstimated += entry.tokens;
172
+ } else {
173
+ if (exact) totals.offsetExact += entry.tokens;
174
+ else totals.offsetEstimated += entry.tokens;
175
+ recentOffsets.push(entry);
176
+ }
177
+ const key = `${entry.kind}:${entry.component}:${entry.basis}`;
178
+ const agg = perComponent.get(key);
179
+ if (agg === void 0) perComponent.set(key, {
180
+ component: entry.component,
181
+ tokens: entry.tokens,
182
+ basis: entry.basis,
183
+ kind: entry.kind
184
+ });
185
+ else agg.tokens += entry.tokens;
186
+ }
187
+ recentOffsets.sort((a, b) => b.at - a.at);
188
+ const usageTotals = this.totalsFor(scope);
189
+ const perSession = sessionId === void 0 ? [.../* @__PURE__ */ new Set([...this.entries.keys(), ...this.usage.keys()])].map((sid) => {
190
+ const s = this.snapshot(sid);
191
+ return {
192
+ sessionId: sid,
193
+ gross: s.gross,
194
+ offsets: s.offsets,
195
+ net: s.net,
196
+ requests: s.usage.requests,
197
+ cacheHitRate: s.usage.cacheHitRate
198
+ };
199
+ }).sort((a, b) => b.net.exact - a.net.exact || b.net.estimated - a.net.estimated).slice(0, 8) : [];
200
+ return {
201
+ startedAt: new Date(this.startedAt).toISOString(),
202
+ sessions: sessionId === void 0 ? this.entries.size : this.entries.has(sessionId) ? 1 : 0,
203
+ gross: {
204
+ exact: totals.grossExact,
205
+ estimated: totals.grossEstimated
206
+ },
207
+ offsets: {
208
+ exact: totals.offsetExact,
209
+ estimated: totals.offsetEstimated
210
+ },
211
+ net: {
212
+ exact: totals.grossExact - totals.offsetExact,
213
+ estimated: totals.grossEstimated - totals.offsetEstimated
214
+ },
215
+ perComponent: [...perComponent.values()].sort((a, b) => b.tokens - a.tokens),
216
+ recentOffsets: recentOffsets.slice(0, 8).map((e) => ({
217
+ component: e.component,
218
+ tokens: e.tokens,
219
+ basis: e.basis,
220
+ at: new Date(e.at).toISOString(),
221
+ ...e.note === void 0 ? {} : { note: e.note }
222
+ })),
223
+ usage: {
224
+ ...usageTotals,
225
+ cacheHitRate: cacheHitRateOf(usageTotals)
226
+ },
227
+ perSession
228
+ };
229
+ }
230
+ /** 测试与停机清理。 */
231
+ clear() {
232
+ this.entries.clear();
233
+ this.registry.clear();
234
+ this.seenFullText.clear();
235
+ this.usage.clear();
236
+ this.startedAt = Date.now();
237
+ }
238
+ };
239
+ function cacheHitRateOf(t) {
240
+ const denom = t.inputTokens + t.cacheReadTokens + t.cacheWriteTokens;
241
+ return denom <= 0 ? null : Math.round(t.cacheReadTokens / denom * 1e3) / 1e3;
242
+ }
243
+ /** 原文配对哈希(规整行尾与首尾空白——同一文件两次读取的 innocuous 差异不配错)。 */
244
+ function savingsHash(text) {
245
+ return createHash("sha256").update(text.replace(/\r\n?/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/(^\s+)|(\s+$)/g, ""), "utf8").digest("hex");
246
+ }
247
+ function positiveOrZero(v) {
248
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : 0;
249
+ }
250
+ const singleton = new SavingsLedger();
251
+ /** 模块级单例:pruner 与 retrieve 分处两文件,共享同一本账。 */
252
+ function getSavingsLedger() {
253
+ return singleton;
254
+ }
255
+ //#endregion
256
+ //#region src/runtime/deepseek-official-pricing.ts
257
+ /** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
258
+ const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
259
+ /** Wall-clock time at which the checked-in official price pages were verified. */
260
+ const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
261
+ const PRICES = Object.freeze({
262
+ "deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
263
+ "0.007",
264
+ "0.22",
265
+ "0.66"
266
+ ], [
267
+ "0.014",
268
+ "0.44",
269
+ "1.32"
270
+ ], [
271
+ "0.05",
272
+ "1.5",
273
+ "4.5"
274
+ ], [
275
+ "0.10",
276
+ "3.0",
277
+ "9.0"
278
+ ]),
279
+ "deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
280
+ "0.022",
281
+ "0.66",
282
+ "1.98"
283
+ ], [
284
+ "0.044",
285
+ "1.32",
286
+ "3.96"
287
+ ], [
288
+ "0.15",
289
+ "4.5",
290
+ "13.5"
291
+ ], [
292
+ "0.30",
293
+ "9.0",
294
+ "27.0"
295
+ ]),
296
+ "deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
297
+ "0.007",
298
+ "0.22",
299
+ "0.66"
300
+ ], [
301
+ "0.014",
302
+ "0.44",
303
+ "1.32"
304
+ ], [
305
+ "0.05",
306
+ "1.5",
307
+ "4.5"
308
+ ], [
309
+ "0.10",
310
+ "3.0",
311
+ "9.0"
312
+ ])
313
+ });
314
+ const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
315
+ const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
316
+ const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
317
+ /**
318
+ * Resolve one immutable official price record; aliases and compatible gateways fail closed.
319
+ * @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
320
+ * @returns An immutable price record or an explicit unpriced reason.
321
+ */
322
+ function resolveOfficialDeepSeekPrice(input) {
323
+ if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
324
+ if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
325
+ if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
326
+ if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
327
+ if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
328
+ const band = priceBandAt(input.at);
329
+ if (band === void 0) return unpriced("invalid price timestamp");
330
+ const model = PRICES[input.modelId];
331
+ const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
332
+ return {
333
+ kind: "priced",
334
+ record: Object.freeze({
335
+ catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
336
+ checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
337
+ provider: "deepseek-official",
338
+ baseUrlClass: "official-public",
339
+ apiRoute: input.apiRoute,
340
+ modelId: input.modelId,
341
+ modelVersion: model.version,
342
+ currency: input.currency,
343
+ unitTokens: 1e6,
344
+ band,
345
+ inputCacheHit,
346
+ inputCacheMiss,
347
+ output,
348
+ sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
349
+ sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
350
+ peakRule: PEAK_RULE
351
+ })
352
+ };
353
+ }
354
+ /**
355
+ * Classify a timestamp under the published Beijing peak schedule.
356
+ * @param at - absolute request time to interpret in Asia/Shanghai.
357
+ * @returns Peak/off-peak, or undefined for an invalid timestamp.
358
+ */
359
+ function priceBandAt(at) {
360
+ if (!Number.isFinite(at.getTime())) return void 0;
361
+ const parts = new Intl.DateTimeFormat("en-US", {
362
+ timeZone: "Asia/Shanghai",
363
+ weekday: "short",
364
+ hour: "2-digit",
365
+ minute: "2-digit",
366
+ second: "2-digit",
367
+ hourCycle: "h23"
368
+ }).formatToParts(at);
369
+ const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
370
+ const weekday = values.weekday;
371
+ const hour = Number(values.hour);
372
+ const minute = Number(values.minute);
373
+ const second = Number(values.second);
374
+ if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
375
+ const workday = weekday !== "Sat" && weekday !== "Sun";
376
+ const seconds = hour * 3600 + minute * 60 + second;
377
+ return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
378
+ }
379
+ /**
380
+ * Price one completed request, returning a range when it spans a published band boundary.
381
+ * @param input - exact applicability, request interval, and complete disjoint usage buckets.
382
+ * @returns Fixed-point exact/range cost or an explicit unpriced reason.
383
+ */
384
+ function priceOfficialDeepSeekUsage(input) {
385
+ for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
386
+ if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
387
+ const start = resolveOfficialDeepSeekPrice({
388
+ ...input,
389
+ at: input.startedAt
390
+ });
391
+ if (start.kind === "unpriced") return start;
392
+ const end = resolveOfficialDeepSeekPrice({
393
+ ...input,
394
+ at: input.completedAt
395
+ });
396
+ if (end.kind === "unpriced") return end;
397
+ const startAmount = amountFor(start.record, input.usage);
398
+ if (startAmount === void 0) return unpriced("invalid decimal price record");
399
+ const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
400
+ if (start.record.band === end.record.band && !crossesBoundary) return {
401
+ kind: "exact",
402
+ currency: start.record.currency,
403
+ band: start.record.band,
404
+ ...startAmount
405
+ };
406
+ const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
407
+ const endAmount = amountFor(comparisonRecord, input.usage);
408
+ if (endAmount === void 0) return unpriced("invalid decimal price record");
409
+ const startFemto = BigInt(startAmount.femtoUnits);
410
+ const endFemto = BigInt(endAmount.femtoUnits);
411
+ return {
412
+ kind: "range",
413
+ currency: start.record.currency,
414
+ bands: [start.record.band, comparisonRecord.band],
415
+ minimum: startFemto <= endFemto ? startAmount : endAmount,
416
+ maximum: startFemto <= endFemto ? endAmount : startAmount
417
+ };
418
+ }
419
+ /** Detect any published UTC band boundary, even when both endpoints share a band. */
420
+ function spansPublishedPriceBoundary(startedAt, completedAt) {
421
+ const start = startedAt.getTime();
422
+ const end = completedAt.getTime();
423
+ if (end <= start) return false;
424
+ const dayMs = 864e5;
425
+ if (end - start >= 7 * dayMs) return true;
426
+ const firstDay = Math.floor(start / dayMs) * dayMs;
427
+ for (let day = firstDay; day <= end; day += dayMs) {
428
+ const weekday = new Date(day).getUTCDay();
429
+ if (weekday === 0 || weekday === 6) continue;
430
+ for (const hour of [
431
+ 1,
432
+ 4,
433
+ 6,
434
+ 10
435
+ ]) {
436
+ const boundary = day + hour * 60 * 60 * 1e3;
437
+ if (boundary > start && boundary <= end) return true;
438
+ }
439
+ }
440
+ return false;
441
+ }
442
+ function priceRecordInBand(record, band) {
443
+ const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
444
+ return Object.freeze({
445
+ ...record,
446
+ band,
447
+ inputCacheHit,
448
+ inputCacheMiss,
449
+ output
450
+ });
451
+ }
452
+ /**
453
+ * Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
454
+ * @param value - canonical non-negative decimal with at most nine fractional digits.
455
+ * @returns Integer nano-units, or undefined when the decimal is invalid.
456
+ */
457
+ function decimalRateNanoUnits(value) {
458
+ const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
459
+ if (match === null) return void 0;
460
+ const whole = match[1] ?? "0";
461
+ const fraction = (match[2] ?? "").padEnd(9, "0");
462
+ return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
463
+ }
464
+ function amountFor(record, usage) {
465
+ const hit = decimalRateNanoUnits(record.inputCacheHit);
466
+ const miss = decimalRateNanoUnits(record.inputCacheMiss);
467
+ const output = decimalRateNanoUnits(record.output);
468
+ if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
469
+ const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
470
+ return {
471
+ femtoUnits: femtoUnits.toString(),
472
+ decimal: formatFemto(femtoUnits)
473
+ };
474
+ }
475
+ function formatFemto(value) {
476
+ const digits = value.toString().padStart(16, "0");
477
+ const whole = digits.slice(0, -15);
478
+ const fraction = digits.slice(-15).replace(/0+$/u, "");
479
+ return fraction.length === 0 ? whole : `${whole}.${fraction}`;
480
+ }
481
+ function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
482
+ return Object.freeze({
483
+ version,
484
+ USD: Object.freeze({
485
+ "off-peak": usdOffPeak,
486
+ peak: usdPeak
487
+ }),
488
+ CNY: Object.freeze({
489
+ "off-peak": cnyOffPeak,
490
+ peak: cnyPeak
491
+ })
492
+ });
493
+ }
494
+ function isOfficialModel(value) {
495
+ return Object.prototype.hasOwnProperty.call(PRICES, value);
496
+ }
497
+ function unpriced(reason) {
498
+ return {
499
+ kind: "unpriced",
500
+ reason
501
+ };
502
+ }
503
+ const advisorStates = /* @__PURE__ */ new WeakMap();
504
+ /**
505
+ * The per-session advisor state, created on first touch.
506
+ * @param session - the session to key the state on (by object identity).
507
+ */
508
+ function getAdvisorState(session) {
509
+ let state = advisorStates.get(session);
510
+ if (state === void 0) {
511
+ state = {
512
+ todoVersion: void 0,
513
+ summary: void 0,
514
+ lastSummaryTurn: -1,
515
+ watermarkSeq: 0,
516
+ scores: /* @__PURE__ */ new Map(),
517
+ recertified: /* @__PURE__ */ new Map(),
518
+ failures: void 0,
519
+ inFlight: false,
520
+ lastDecay: void 0,
521
+ lastAdvice: void 0
522
+ };
523
+ advisorStates.set(session, state);
524
+ }
525
+ return state;
526
+ }
527
+ /**
528
+ * Insert or refresh one score with LRU semantics: a re-touched seq moves to
529
+ * the newest position, and the oldest entry is evicted once the map exceeds
530
+ * {@link ADVISOR_SCORES_LIMIT}.
531
+ */
532
+ function recordScore(state, seq, entry) {
533
+ state.scores.delete(seq);
534
+ state.scores.set(seq, entry);
535
+ if (state.scores.size > 64) {
536
+ const oldest = state.scores.keys().next();
537
+ if (oldest.done !== true) state.scores.delete(oldest.value);
538
+ }
539
+ }
540
+ /**
541
+ * Mark one seq as LLM-recertified low relevance (a suggestion for later
542
+ * history-aggressiveness decisions, consumed by nothing in this round).
543
+ * Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
544
+ */
545
+ function recordRecertified(state, seq, turn) {
546
+ state.recertified.delete(seq);
547
+ state.recertified.set(seq, turn);
548
+ if (state.recertified.size > 64) {
549
+ const oldest = state.recertified.keys().next();
550
+ if (oldest.done !== true) state.recertified.delete(oldest.value);
551
+ }
552
+ }
553
+ /**
554
+ * Drop every cached artifact that depends on the task semantics: a changed
555
+ * todo version invalidates the summary and makes all eligible candidates
556
+ * rescore-worthy (the watermark alone would otherwise hide them).
557
+ */
558
+ function invalidateOnTaskChange(state, todoVersion) {
559
+ if (state.todoVersion === todoVersion) return false;
560
+ state.todoVersion = todoVersion;
561
+ state.summary = void 0;
562
+ state.lastSummaryTurn = -1;
563
+ return true;
564
+ }
565
+ /**
566
+ * `/ctx-summary off|on` overrides, keyed by session id (string). The command
567
+ * handler only sees `invocation.agent.session.id`, not the pruner's Session
568
+ * object, so these are id-keyed rather than WeakMap'd. Entries are two-char
569
+ * strings per session and cleared whenever the override is lifted.
570
+ */
571
+ const summaryOverrides = /* @__PURE__ */ new Map();
572
+ /** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
573
+ function getSummaryOverride(sessionId) {
574
+ return summaryOverrides.get(sessionId);
575
+ }
576
+ /** Set or clear (`undefined`) the session's `/ctx-summary` override. */
577
+ function setSummaryOverride(sessionId, value) {
578
+ if (value === void 0) summaryOverrides.delete(sessionId);
579
+ else summaryOverrides.set(sessionId, value);
580
+ }
581
+ /** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
582
+ const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
583
+ /** Record the gate input the pass last evaluated for this session. */
584
+ function observeIntentEnabled(sessionId, enabled) {
585
+ lastObservedIntentEnabled.set(sessionId, enabled);
586
+ }
587
+ /** The settings-side enabled flag last observed for the session, if any. */
588
+ function getObservedIntentEnabled(sessionId) {
589
+ return lastObservedIntentEnabled.get(sessionId);
590
+ }
591
+ const lastIntentFolds = /* @__PURE__ */ new Map();
592
+ /** Record a landed intent fold for the session (newest wins). */
593
+ function recordIntentFold(sessionId, record) {
594
+ lastIntentFolds.set(sessionId, record);
595
+ }
596
+ /** The most recent landed intent fold for the session, if any. */
597
+ function getLastIntentFold(sessionId) {
598
+ return lastIntentFolds.get(sessionId);
599
+ }
600
+ //#endregion
601
+ //#region src/runtime/tokenpilot/intent-gate.ts
602
+ /**
603
+ * Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
604
+ *
605
+ * Pure decision helper evaluated at the turn-boundary postflight: it decides
606
+ * whether this turn may spend a summary-writer LLM call and stage a fold for
607
+ * the next pressure round. The gate is deliberately conservative — every
608
+ * unresolved input (unknown context window, non-finite counters) fails closed
609
+ * toward "do not run", because a skipped fold is free while a wasted summary
610
+ * call is not. Content safety is unaffected either way: fail-open semantics
611
+ * live in the fold landing path, not here.
612
+ */
613
+ /** Floor: the live surface must exceed this fraction of the context window. */
614
+ const INTENT_GATE_FLOOR_FRACTION = .45;
615
+ /** Growth: the live surface must have grown by more than this since the last landed fold. */
616
+ const INTENT_GATE_GROWTH_TOKENS = 5e4;
617
+ function isUsableNumber(value) {
618
+ return Number.isFinite(value) && value >= 0;
619
+ }
620
+ /** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
621
+ function evaluateIntentGate(input) {
622
+ const snapshot = (decision, reason) => ({
623
+ ...input,
624
+ decision,
625
+ reason
626
+ });
627
+ if (!input.enabled) return snapshot(false, "disabled");
628
+ if (input.override === "off") return snapshot(false, "override-off");
629
+ if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
630
+ if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
631
+ if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
632
+ if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
633
+ if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
634
+ return snapshot(true, "passed");
635
+ }
636
+ //#endregion
637
+ //#region src/runtime/monitor.ts
638
+ /**
639
+ * 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
640
+ * 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
641
+ * (默认 80%)——提前一档给出人工干预窗口。
642
+ */
643
+ const MONITOR_SUGGEST_PCT = .7;
644
+ /**
645
+ * Savings snapshot plus the intent-summary control block. Ledger is
646
+ * injectable so tests seed a private instance instead of the process
647
+ * singleton.
648
+ */
649
+ function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
650
+ const scopeKey = sessionId ?? "";
651
+ const override = getSummaryOverride(scopeKey);
652
+ const observedContext = scopeKey.length > 0 ? getContextUsage(scopeKey) : latestObservedContextUsage();
653
+ const contextBlock = observedContext === void 0 ? void 0 : {
654
+ liveTokens: observedContext.liveTokens,
655
+ contextWindow: observedContext.contextWindow,
656
+ pct: observedContext.contextWindow !== void 0 && observedContext.contextWindow > 0 ? Math.round(observedContext.liveTokens / observedContext.contextWindow * 1e3) / 1e3 : null,
657
+ sessionId: observedContext.sessionId
658
+ };
659
+ const suggestion = contextBlock === void 0 || contextBlock.pct === null ? void 0 : {
660
+ suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
661
+ thresholdPct: MONITOR_SUGGEST_PCT,
662
+ occupancyPct: contextBlock.pct
663
+ };
664
+ return {
665
+ ...ledger.snapshot(sessionId),
666
+ ...contextBlock === void 0 ? {} : { context: contextBlock },
667
+ ...suggestion === void 0 ? {} : { suggestion },
668
+ intent: {
669
+ override,
670
+ observedEnabled: getObservedIntentEnabled(scopeKey),
671
+ gate: {
672
+ floorFraction: INTENT_GATE_FLOOR_FRACTION,
673
+ growthTokens: INTENT_GATE_GROWTH_TOKENS
674
+ },
675
+ lastFold: getLastIntentFold(scopeKey)
676
+ },
677
+ sessionScope: sessionId ?? null
678
+ };
679
+ }
680
+ /** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
681
+ const contextUsageBySession = /* @__PURE__ */ new Map();
682
+ const CONTEXT_USAGE_CAP = 64;
683
+ /**
684
+ * 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
685
+ * contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
686
+ */
687
+ function observeContextUsage(sessionId, liveTokens, contextWindow) {
688
+ if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return;
689
+ if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
690
+ const oldest = contextUsageBySession.keys().next().value;
691
+ if (oldest !== void 0) contextUsageBySession.delete(oldest);
692
+ }
693
+ contextUsageBySession.set(sessionId, {
694
+ liveTokens,
695
+ contextWindow,
696
+ at: Date.now(),
697
+ seq: ++observeSeq
698
+ });
699
+ }
700
+ function getContextUsage(sessionId) {
701
+ const entry = contextUsageBySession.get(sessionId);
702
+ return entry === void 0 ? void 0 : {
703
+ liveTokens: entry.liveTokens,
704
+ contextWindow: entry.contextWindow,
705
+ sessionId
706
+ };
707
+ }
708
+ let observeSeq = 0;
709
+ function latestObservedContextUsage() {
710
+ let latest;
711
+ for (const [sessionId, entry] of contextUsageBySession) if (latest === void 0 || entry.seq > latest.seq) latest = {
712
+ sessionId,
713
+ liveTokens: entry.liveTokens,
714
+ contextWindow: entry.contextWindow,
715
+ seq: entry.seq
716
+ };
717
+ return latest;
718
+ }
719
+ function isSessionOverrideAction(value) {
720
+ return value === "on" || value === "off" || value === "clear";
721
+ }
722
+ /**
723
+ * Drive the `/ctx-summary` override state machine: `on`/`off` pin the
724
+ * session, `clear` returns it to settings-driven. The resulting override is
725
+ * handed back so the route can echo the post-action truth.
726
+ */
727
+ function applySessionOverride(sessionId, action) {
728
+ setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
729
+ return { override: getSummaryOverride(sessionId) };
730
+ }
731
+ /**
732
+ * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
733
+ * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
734
+ * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
735
+ * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
736
+ * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
737
+ * (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
738
+ */
739
+ function estimateSavingsPricing(readService, snapshot) {
740
+ if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
741
+ const selection = readService("agentDefaultModel")?.currentSelection?.();
742
+ const provider = typeof selection?.provider === "string" ? selection.provider : "";
743
+ const modelId = typeof selection?.model === "string" ? selection.model : "";
744
+ if (provider !== "deepseek-official") return void 0;
745
+ const now = /* @__PURE__ */ new Date();
746
+ const startedAt = new Date(snapshot.startedAt);
747
+ const base = {
748
+ provider,
749
+ baseUrlClass: "official-public",
750
+ apiRoute: "chat-completions",
751
+ modelId,
752
+ currency: "USD",
753
+ startedAt,
754
+ completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
755
+ };
756
+ const actual = priceOfficialDeepSeekUsage({
757
+ ...base,
758
+ usage: {
759
+ cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
760
+ cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
761
+ outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
762
+ }
763
+ });
764
+ const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
765
+ ...base,
766
+ usage: {
767
+ cacheReadTokens: 0,
768
+ cacheMissTokens: Math.round(snapshot.net.exact),
769
+ outputTokens: 0
770
+ }
771
+ }) : void 0;
772
+ const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
773
+ if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
774
+ return {
775
+ currency: "USD",
776
+ ...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
777
+ ...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
778
+ };
779
+ }
780
+ //#endregion
781
+ //#region src/runtime/types.ts
782
+ /** User-facing mixed strategy profile. */
783
+ const COMPRESSION_PROFILES = [
784
+ "off",
785
+ "native",
786
+ "balanced",
787
+ "cache-strict",
788
+ "savings",
789
+ "adaptive",
790
+ "tokenpilot-inspired",
791
+ "custom"
792
+ ];
793
+ //#endregion
794
+ //#region src/runtime/value.ts
795
+ /** Version-neutral immutable-value and closed-union helpers for the plugin runtime. */
796
+ /**
797
+ * Freeze an object graph in place without relying on a Harness utility export.
798
+ * Live AbortSignals remain mutable so request cancellation continues to work.
799
+ * @param value - Value to freeze recursively.
800
+ * @returns The same deeply frozen value.
801
+ */
802
+ function deepFreeze(value) {
803
+ const seen = /* @__PURE__ */ new WeakSet();
804
+ const pending = [{
805
+ kind: "visit",
806
+ node: value
807
+ }];
808
+ while (pending.length > 0) {
809
+ const task = pending.pop();
810
+ /* v8 ignore next -- the loop condition guarantees one pending task. */
811
+ if (task === void 0) continue;
812
+ if (task.kind === "property") {
813
+ pending.push({
814
+ kind: "visit",
815
+ node: task.source[task.key]
816
+ });
817
+ continue;
818
+ }
819
+ const node = task.node;
820
+ if (node === null || typeof node !== "object" || node instanceof AbortSignal || seen.has(node)) continue;
821
+ seen.add(node);
822
+ Object.freeze(node);
823
+ const keys = Object.keys(node);
824
+ for (let index = keys.length - 1; index >= 0; index--) {
825
+ const key = keys[index];
826
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
827
+ if (key === void 0) continue;
828
+ pending.push({
829
+ kind: "property",
830
+ source: node,
831
+ key
832
+ });
833
+ }
834
+ }
835
+ return value;
836
+ }
837
+ /**
838
+ * Throw for an impossible member of a closed discriminated union.
839
+ * @param value - Value that escaped its closed union type.
840
+ * @param context - Optional switch-site label.
841
+ * @returns Never returns.
842
+ */
843
+ function assertNever(value, context) {
844
+ const rendered = JSON.stringify(value) ?? String(value);
845
+ throw new Error(`unreachable variant${context === void 0 ? "" : ` in ${context}`}: ${rendered}`);
846
+ }
847
+ //#endregion
848
+ //#region src/runtime/custom-policy.ts
849
+ /** Strict versioned Custom policy parsing and effective-token resolution. */
850
+ const budgetSchema = z.object({
851
+ enabled: z.boolean().required(),
852
+ trigger: z.number().required(),
853
+ target: z.number().required()
854
+ }).required();
855
+ const legacyHistorySchema = z.object({
856
+ enabled: z.boolean().required(),
857
+ trigger: z.number().required(),
858
+ keepRecentTurns: z.number().step(1).min(0).required(),
859
+ keepRecent: z.number().required(),
860
+ minReclaim: z.number().required()
861
+ }).required();
862
+ const historySchema = z.object({
863
+ enabled: z.boolean().required(),
864
+ trigger: z.number().required(),
865
+ keepRecentToolCalls: z.number().step(1).min(0).required(),
866
+ keepRecentTokens: z.number().required(),
867
+ minReclaim: z.number().required()
868
+ }).required();
869
+ const tailTrimSchema = z.object({
870
+ enabled: z.boolean().required(),
871
+ trigger: z.number().required()
872
+ }).required();
873
+ const customCompressionPolicyV1InputSchema = z.object({
874
+ version: z.const(1).required(),
875
+ unit: z.union(["tokens", "context-percent"]).required(),
876
+ fresh: budgetSchema,
877
+ aggregate: budgetSchema,
878
+ history: legacyHistorySchema,
879
+ prefixPolicy: z.union(["preserve", "pressure-break"]).required()
880
+ }).required();
881
+ const customCompressionPolicyV2InputSchema = z.object({
882
+ version: z.const(2).required(),
883
+ unit: z.union(["tokens", "context-percent"]).required(),
884
+ fresh: budgetSchema,
885
+ aggregate: budgetSchema,
886
+ history: legacyHistorySchema,
887
+ prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
888
+ tailTrim: tailTrimSchema
889
+ }).required();
890
+ const customCompressionPolicyV3InputSchema = z.object({
891
+ version: z.const(3).required(),
892
+ unit: z.union(["tokens", "context-percent"]).required(),
893
+ fresh: budgetSchema,
894
+ aggregate: budgetSchema,
895
+ history: historySchema,
896
+ prefixPolicy: z.union(["preserve", "pressure-break"]).required(),
897
+ tailTrim: tailTrimSchema
898
+ }).required();
899
+ /** Canonical Custom document accepted by Host settings and the runtime resolver. */
900
+ const CustomCompressionPolicySchema = z.transform(z.any().required(), (value) => {
901
+ assertExactPolicyShape(value);
902
+ const canonical = canonicalizeCustomPolicy(value.version === 1 ? customCompressionPolicyV1InputSchema(value) : value.version === 2 ? customCompressionPolicyV2InputSchema(value) : customCompressionPolicyV3InputSchema(value));
903
+ assertCanonicalRelations(canonical);
904
+ return deepFreeze(structuredClone(canonical));
905
+ });
906
+ /** Balanced-equivalent Custom policy stored as one token-canonical document. */
907
+ const DEFAULT_CUSTOM_COMPRESSION_POLICY = deepFreeze({
908
+ version: 3,
909
+ unit: "tokens",
910
+ fresh: {
911
+ enabled: true,
912
+ trigger: 8192,
913
+ target: 3072
914
+ },
915
+ aggregate: {
916
+ enabled: true,
917
+ trigger: 32768,
918
+ target: 12288
919
+ },
920
+ history: {
921
+ enabled: true,
922
+ trigger: 5e5,
923
+ keepRecentToolCalls: 10,
924
+ keepRecentTokens: 64e3,
925
+ minReclaim: 96e3
926
+ },
927
+ prefixPolicy: "pressure-break",
928
+ tailTrim: {
929
+ enabled: false,
930
+ trigger: 7e5
931
+ }
932
+ });
933
+ /**
934
+ * Resolve one validated Custom document to the same token policy used by public presets.
935
+ * @param value - untrusted or typed Custom settings value.
936
+ * @param options - routed model capacity for context-percent documents.
937
+ * @returns a detached deeply immutable effective token policy.
938
+ */
939
+ function resolveCustomPolicy(value, options = {}) {
940
+ const policy = canonicalizeCustomPolicy(CustomCompressionPolicySchema(value));
941
+ const effective = (name, amount) => {
942
+ if (policy.unit === "tokens") return amount;
943
+ const contextWindow = options.contextWindowTokens;
944
+ if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) throw new Error("Custom context-percent policy requires a resolved positive model context window");
945
+ const tokens = Math.floor(contextWindow * amount / 100);
946
+ if (!Number.isSafeInteger(tokens) || amount > 0 && tokens <= 0) throw new Error(`Custom ${name} has no valid effective token value for this model`);
947
+ return tokens;
948
+ };
949
+ const resolved = {
950
+ profile: "custom",
951
+ nativeToolResultEnabled: false,
952
+ freshEnabled: policy.fresh.enabled,
953
+ aggregateEnabled: policy.aggregate.enabled,
954
+ historyMode: !policy.history.enabled ? "disabled" : policy.prefixPolicy === "preserve" ? "capacity-pressure" : "routine",
955
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
956
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
957
+ freshTriggerTokens: effective("Fresh trigger", policy.fresh.trigger),
958
+ freshTargetTokens: effective("Fresh target", policy.fresh.target),
959
+ aggregateTriggerTokens: effective("Aggregate trigger", policy.aggregate.trigger),
960
+ aggregateTargetTokens: effective("Aggregate target", policy.aggregate.target),
961
+ historyTriggerTokens: effective("History trigger", policy.history.trigger),
962
+ historyKeepRecentToolCalls: policy.history.keepRecentToolCalls,
963
+ historyKeepRecentTokens: effective("History recent token tail", policy.history.keepRecentTokens),
964
+ historyMinReclaimTokens: effective("History min-reclaim", policy.history.minReclaim),
965
+ tailTrim: {
966
+ enabled: policy.tailTrim.enabled,
967
+ triggerTokens: effective("TailTrim trigger", policy.tailTrim.trigger)
968
+ }
969
+ };
970
+ assertEffectiveRelations(resolved);
971
+ return deepFreeze(resolved);
972
+ }
973
+ function canonicalizeCustomPolicy(policy) {
974
+ if (policy.version === 3) return policy;
975
+ return {
976
+ version: 3,
977
+ unit: policy.unit,
978
+ fresh: policy.fresh,
979
+ aggregate: policy.aggregate,
980
+ history: {
981
+ enabled: policy.history.enabled,
982
+ trigger: policy.history.trigger,
983
+ keepRecentToolCalls: 10,
984
+ keepRecentTokens: policy.history.keepRecent,
985
+ minReclaim: policy.history.minReclaim
986
+ },
987
+ prefixPolicy: policy.prefixPolicy,
988
+ tailTrim: policy.version === 1 ? {
989
+ enabled: false,
990
+ trigger: 7e5
991
+ } : policy.tailTrim
992
+ };
993
+ }
994
+ function measuredValues(policy) {
995
+ return [
996
+ policy.fresh.trigger,
997
+ policy.fresh.target,
998
+ policy.aggregate.trigger,
999
+ policy.aggregate.target,
1000
+ policy.history.trigger,
1001
+ policy.history.keepRecentTokens,
1002
+ policy.history.minReclaim,
1003
+ policy.tailTrim.trigger
1004
+ ];
1005
+ }
1006
+ function validMeasuredValues(policy) {
1007
+ const values = measuredValues(policy);
1008
+ if (![
1009
+ policy.fresh.trigger,
1010
+ policy.fresh.target,
1011
+ policy.aggregate.trigger,
1012
+ policy.aggregate.target,
1013
+ policy.history.trigger,
1014
+ policy.history.minReclaim,
1015
+ policy.tailTrim.trigger
1016
+ ].every((value) => value > 0) || policy.history.keepRecentTokens < 0 || !Number.isSafeInteger(policy.history.keepRecentToolCalls) || policy.history.keepRecentToolCalls < 0) return false;
1017
+ return policy.unit === "tokens" ? values.every(Number.isSafeInteger) : values.every((value) => Number.isFinite(value) && value <= 100);
1018
+ }
1019
+ function assertCanonicalRelations(policy) {
1020
+ if (!validMeasuredValues(policy)) throw new TypeError("Custom measured values must use the selected canonical unit");
1021
+ if (policy.fresh.target >= policy.fresh.trigger) throw new TypeError("Custom Fresh target must be below trigger");
1022
+ if (policy.aggregate.target >= policy.aggregate.trigger) throw new TypeError("Custom Aggregate target must be below trigger");
1023
+ if (policy.history.minReclaim > policy.history.trigger) throw new TypeError("Custom History min-reclaim must not exceed its trigger");
1024
+ }
1025
+ function assertExactPolicyShape(value) {
1026
+ if (!isPlainRecord$1(value)) throw new TypeError("Custom must be a plain object");
1027
+ if (value.version !== 1 && value.version !== 2 && value.version !== 3) throw new TypeError("Custom version must be 1, 2, or 3");
1028
+ assertExactKeys(value, value.version === 1 ? [
1029
+ "version",
1030
+ "unit",
1031
+ "fresh",
1032
+ "aggregate",
1033
+ "history",
1034
+ "prefixPolicy"
1035
+ ] : [
1036
+ "version",
1037
+ "unit",
1038
+ "fresh",
1039
+ "aggregate",
1040
+ "history",
1041
+ "prefixPolicy",
1042
+ "tailTrim"
1043
+ ], "Custom");
1044
+ assertExactKeys(value.fresh, [
1045
+ "enabled",
1046
+ "trigger",
1047
+ "target"
1048
+ ], "Custom Fresh");
1049
+ assertExactKeys(value.aggregate, [
1050
+ "enabled",
1051
+ "trigger",
1052
+ "target"
1053
+ ], "Custom Aggregate");
1054
+ assertExactKeys(value.history, value.version === 3 ? [
1055
+ "enabled",
1056
+ "trigger",
1057
+ "keepRecentToolCalls",
1058
+ "keepRecentTokens",
1059
+ "minReclaim"
1060
+ ] : [
1061
+ "enabled",
1062
+ "trigger",
1063
+ "keepRecentTurns",
1064
+ "keepRecent",
1065
+ "minReclaim"
1066
+ ], "Custom History");
1067
+ if (value.version !== 1) assertExactKeys(value.tailTrim, ["enabled", "trigger"], "Custom TailTrim");
1068
+ }
1069
+ function assertExactKeys(value, allowed, label) {
1070
+ if (!isPlainRecord$1(value)) throw new TypeError(`${label} must be a plain object`);
1071
+ const allowedKeys = new Set(allowed);
1072
+ const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
1073
+ if (unknown !== void 0) throw new TypeError(`${label}: unknown key "${unknown}"`);
1074
+ }
1075
+ function isPlainRecord$1(value) {
1076
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1077
+ const prototype = Object.getPrototypeOf(value);
1078
+ return prototype === Object.prototype || prototype === null;
1079
+ }
1080
+ function assertEffectiveRelations(policy) {
1081
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens) throw new Error("Custom effective Fresh target must be below trigger");
1082
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens) throw new Error("Custom effective Aggregate target must be below trigger");
1083
+ if (policy.historyMinReclaimTokens > policy.historyTriggerTokens) throw new Error("Custom effective History min-reclaim must not exceed its trigger");
1084
+ }
1085
+ //#endregion
1086
+ //#region src/runtime/config.ts
1087
+ /** Configuration resolution for the mixed deterministic context-compression selector. */
1088
+ /** Settings namespace shared by the Host service and browser selector. */
1089
+ const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = "context-compression";
1090
+ /** Fixed native fallback marker. */
1091
+ const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
1092
+ /**
1093
+ * The one Auto Compact threshold contract shared by the settings UI, the
1094
+ * persisted settings schema, and the runtime resolver. Every integer in the
1095
+ * range is valid and entered directly in the UI.
1096
+ */
1097
+ const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
1098
+ min: 50,
1099
+ max: 90,
1100
+ step: 1,
1101
+ default: 80
1102
+ });
1103
+ /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
1104
+ function isValidAutoCompactThresholdPercent(value) {
1105
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max;
1106
+ }
1107
+ const AUTO_COMPACT_DEFAULT = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default });
1108
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
1109
+ function isPlainRecord(value) {
1110
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1111
+ const prototype = Object.getPrototypeOf(value);
1112
+ return prototype === Object.prototype || prototype === null;
1113
+ }
1114
+ /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
1115
+ function assertPlainDataTree(value, seen = /* @__PURE__ */ new WeakSet()) {
1116
+ if (value === null || typeof value !== "object") return;
1117
+ if (seen.has(value)) return;
1118
+ seen.add(value);
1119
+ if (Array.isArray(value)) {
1120
+ for (const entry of value) assertPlainDataTree(entry, seen);
1121
+ return;
1122
+ }
1123
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must contain only plain objects");
1124
+ for (const entry of Object.values(value)) assertPlainDataTree(entry, seen);
1125
+ }
1126
+ /**
1127
+ * Strictly parse the persisted autoCompact section. Schemastery object
1128
+ * defaults silently absorb null, empty, and extra-key sections, so this stays
1129
+ * hand-validated beside the top-level unknown-key check.
1130
+ */
1131
+ function parseAutoCompactSettings(value) {
1132
+ if (value === void 0) return AUTO_COMPACT_DEFAULT;
1133
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression autoCompact must be a plain object");
1134
+ const keys = Object.keys(value);
1135
+ if (keys.length !== 1 || keys[0] !== "thresholdPercent") throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join("\", \"")}"`);
1136
+ const thresholdPercent = value.thresholdPercent;
1137
+ if (!isValidAutoCompactThresholdPercent(thresholdPercent)) throw new TypeError(`Context-compression autoCompact.thresholdPercent (${String(thresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`);
1138
+ return { thresholdPercent };
1139
+ }
1140
+ /**
1141
+ * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
1142
+ * to every profile: absent inherits the lossless `false` default, while a
1143
+ * present-but-invalid section is an explicitly invalid document.
1144
+ */
1145
+ function parseCodeSkeletonSettings(value) {
1146
+ if (value === void 0) return { enabled: false };
1147
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression codeSkeleton must be a plain object");
1148
+ const keys = Object.keys(value);
1149
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join("\", \"")}"`);
1150
+ const enabled = value.enabled;
1151
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression codeSkeleton.enabled must be a boolean");
1152
+ return { enabled };
1153
+ }
1154
+ /**
1155
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
1156
+ * section semantics: absent inherits the lossless `false` default, while a
1157
+ * present-but-invalid section is an explicitly invalid document.
1158
+ */
1159
+ function parseIntentSummarySettings(value) {
1160
+ if (value === void 0) return { enabled: false };
1161
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
1162
+ const keys = Object.keys(value);
1163
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
1164
+ const enabled = value.enabled;
1165
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
1166
+ return { enabled };
1167
+ }
1168
+ /**
1169
+ * Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
1170
+ * section semantics: absent inherits the hidden default, while a
1171
+ * present-but-invalid section is an explicitly invalid document.
1172
+ */
1173
+ function parseMonitorPanelSettings(value) {
1174
+ if (value === void 0) return { enabled: false };
1175
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression monitorPanel must be a plain object");
1176
+ const keys = Object.keys(value);
1177
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join("\", \"")}"`);
1178
+ const enabled = value.enabled;
1179
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression monitorPanel.enabled must be a boolean");
1180
+ return { enabled };
1181
+ }
1182
+ /**
1183
+ * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
1184
+ * inherits the preset defaults; present-but-invalid is rejected, mirroring the
1185
+ * codeSkeleton section semantics.
1186
+ */
1187
+ function parsePresetOptionsSettings(value) {
1188
+ if (value === void 0) return void 0;
1189
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression presetOptions must be a plain object");
1190
+ const allowed = /* @__PURE__ */ new Set([
1191
+ "dedupeToolResults",
1192
+ "summaryLocator",
1193
+ "prefixStabilizer",
1194
+ "readState",
1195
+ "estimatorMode",
1196
+ "estimatorProvider",
1197
+ "estimatorModel",
1198
+ "estimatorBaseUrl",
1199
+ "estimatorApiKey",
1200
+ "estimatorTimeoutMs",
1201
+ "reviewMode",
1202
+ "reviewTimeoutTurns",
1203
+ "cacheHitDiscountAlpha",
1204
+ "reviewHighImpactTokens",
1205
+ "advisorMode",
1206
+ "advisorTimeoutMs",
1207
+ "advisorRefreshTurns",
1208
+ "advisorScoreThreshold",
1209
+ "advisorSampleLimit",
1210
+ "advisorMinTokens"
1211
+ ]);
1212
+ const unknown = Object.keys(value).find((key) => !allowed.has(key));
1213
+ if (unknown !== void 0) throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`);
1214
+ for (const key of [
1215
+ "dedupeToolResults",
1216
+ "summaryLocator",
1217
+ "prefixStabilizer",
1218
+ "readState"
1219
+ ]) {
1220
+ const entry = value[key];
1221
+ if (entry !== void 0 && typeof entry !== "boolean") throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`);
1222
+ }
1223
+ const estimatorMode = value.estimatorMode;
1224
+ if (estimatorMode !== void 0 && estimatorMode !== "" && estimatorMode !== "host" && estimatorMode !== "direct") throw new TypeError("Context-compression presetOptions.estimatorMode must be \"\", \"host\", or \"direct\"");
1225
+ const advisorMode = value.advisorMode;
1226
+ if (advisorMode !== void 0 && advisorMode !== "" && advisorMode !== "host" && advisorMode !== "direct") throw new TypeError("Context-compression presetOptions.advisorMode must be \"\", \"host\", or \"direct\"");
1227
+ const advisorTimeoutMs = value.advisorTimeoutMs;
1228
+ if (advisorTimeoutMs !== void 0 && (typeof advisorTimeoutMs !== "number" || !Number.isSafeInteger(advisorTimeoutMs) || advisorTimeoutMs < 100 || advisorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000");
1229
+ const advisorRefreshTurns = value.advisorRefreshTurns;
1230
+ if (advisorRefreshTurns !== void 0 && (typeof advisorRefreshTurns !== "number" || !Number.isSafeInteger(advisorRefreshTurns) || advisorRefreshTurns < 1)) throw new TypeError("Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1");
1231
+ const advisorScoreThreshold = value.advisorScoreThreshold;
1232
+ if (advisorScoreThreshold !== void 0 && (typeof advisorScoreThreshold !== "number" || !Number.isFinite(advisorScoreThreshold) || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) throw new TypeError("Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1");
1233
+ const advisorSampleLimit = value.advisorSampleLimit;
1234
+ if (advisorSampleLimit !== void 0 && (typeof advisorSampleLimit !== "number" || !Number.isSafeInteger(advisorSampleLimit) || advisorSampleLimit < 1 || advisorSampleLimit > 64)) throw new TypeError("Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64");
1235
+ const advisorMinTokens = value.advisorMinTokens;
1236
+ if (advisorMinTokens !== void 0 && (typeof advisorMinTokens !== "number" || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) throw new TypeError("Context-compression presetOptions.advisorMinTokens must be a positive integer");
1237
+ const estimatorTimeoutMs = value.estimatorTimeoutMs;
1238
+ if (estimatorTimeoutMs !== void 0 && (typeof estimatorTimeoutMs !== "number" || !Number.isSafeInteger(estimatorTimeoutMs) || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 6e4)) throw new TypeError("Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000");
1239
+ for (const key of [
1240
+ "estimatorProvider",
1241
+ "estimatorModel",
1242
+ "estimatorBaseUrl",
1243
+ "estimatorApiKey"
1244
+ ]) {
1245
+ const entry = value[key];
1246
+ if (entry !== void 0 && typeof entry !== "string") throw new TypeError(`Context-compression presetOptions.${key} must be a string`);
1247
+ }
1248
+ const result = {};
1249
+ if (value.dedupeToolResults !== void 0) result.dedupeToolResults = value.dedupeToolResults;
1250
+ if (value.summaryLocator !== void 0) result.summaryLocator = value.summaryLocator;
1251
+ if (value.prefixStabilizer !== void 0) result.prefixStabilizer = value.prefixStabilizer;
1252
+ if (value.readState !== void 0) result.readState = value.readState;
1253
+ if (estimatorMode !== void 0) result.estimatorMode = estimatorMode;
1254
+ if (value.estimatorProvider !== void 0) result.estimatorProvider = value.estimatorProvider;
1255
+ if (value.estimatorModel !== void 0) result.estimatorModel = value.estimatorModel;
1256
+ if (value.estimatorBaseUrl !== void 0) result.estimatorBaseUrl = value.estimatorBaseUrl;
1257
+ if (value.estimatorApiKey !== void 0) result.estimatorApiKey = value.estimatorApiKey;
1258
+ if (estimatorTimeoutMs !== void 0) result.estimatorTimeoutMs = estimatorTimeoutMs;
1259
+ if (advisorMode !== void 0) result.advisorMode = advisorMode;
1260
+ if (advisorTimeoutMs !== void 0) result.advisorTimeoutMs = advisorTimeoutMs;
1261
+ if (advisorRefreshTurns !== void 0) result.advisorRefreshTurns = advisorRefreshTurns;
1262
+ if (advisorScoreThreshold !== void 0) result.advisorScoreThreshold = advisorScoreThreshold;
1263
+ if (advisorSampleLimit !== void 0) result.advisorSampleLimit = advisorSampleLimit;
1264
+ if (advisorMinTokens !== void 0) result.advisorMinTokens = advisorMinTokens;
1265
+ return result;
1266
+ }
1267
+ /** Settings schema used by the user-facing profile selector. */
1268
+ const contextCompressionSettingsInputSchema = z.object({
1269
+ profile: z.union([...COMPRESSION_PROFILES]).default("balanced"),
1270
+ custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY)
1271
+ });
1272
+ /**
1273
+ * Reject a section that is PRESENT but not a usable value. Schemastery
1274
+ * `.default(...)` silently substitutes null and undefined, which would turn a
1275
+ * hand-corrupted store into the (lossy) default policy; only genuinely absent
1276
+ * keys may inherit defaults, and that distinction must be made before any
1277
+ * default can fire.
1278
+ */
1279
+ function assertPresentSection(candidate, key, valid) {
1280
+ if (!Object.hasOwn(candidate, key)) return;
1281
+ if (!valid(candidate[key])) throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`);
1282
+ }
1283
+ const isSupportedProfile = (value) => typeof value === "string" && COMPRESSION_PROFILES.includes(value);
1284
+ const isUsableCustomDocument = (value) => isPlainRecord(value);
1285
+ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
1286
+ profile: "balanced",
1287
+ custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
1288
+ autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
1289
+ codeSkeleton: { enabled: false },
1290
+ intentSummary: { enabled: false },
1291
+ monitorPanel: { enabled: false }
1292
+ };
1293
+ /**
1294
+ * Parse one settings document with the persisted-section semantics: `undefined`
1295
+ * inherits the defaults (an absent section), while `null` is an explicitly
1296
+ * invalid document and must never silently become the default policy.
1297
+ */
1298
+ function parseContextCompressionSettings(value) {
1299
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
1300
+ const keys = Object.keys(value);
1301
+ if (keys.length === 0 || !keys.includes("profile") || !keys.includes("custom")) throw new TypeError("Context-compression settings document is missing its complete shape");
1302
+ return ContextCompressionSettingsSchema(value);
1303
+ }
1304
+ /** Settings schema used by the user-facing profile selector. */
1305
+ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value) => {
1306
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
1307
+ assertPlainDataTree(value);
1308
+ const candidate = structuredClone(value);
1309
+ const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
1310
+ if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
1311
+ assertPresentSection(candidate, "profile", isSupportedProfile);
1312
+ assertPresentSection(candidate, "custom", isUsableCustomDocument);
1313
+ const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
1314
+ const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
1315
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
1316
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
1317
+ const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
1318
+ return {
1319
+ ...contextCompressionSettingsInputSchema(candidate),
1320
+ autoCompact,
1321
+ codeSkeleton,
1322
+ intentSummary,
1323
+ monitorPanel,
1324
+ ...presetOptions === void 0 ? {} : { presetOptions }
1325
+ };
1326
+ }).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
1327
+ /** Low-friction defaults; token budgets live in resolved profile policy. */
1328
+ const DEFAULTS = deepFreeze({
1329
+ profile: "balanced",
1330
+ headChars: 4096,
1331
+ tailChars: 1024
1332
+ });
1333
+ const CONFIG_KEYS = /* @__PURE__ */ new Set([
1334
+ "profile",
1335
+ "headChars",
1336
+ "tailChars",
1337
+ "nativeTriggerTokens",
1338
+ "nativeTargetTokens",
1339
+ "freshTriggerTokens",
1340
+ "freshTargetTokens",
1341
+ "aggregateTriggerTokens",
1342
+ "aggregateTargetTokens",
1343
+ "historyTriggerTokens",
1344
+ "historyKeepRecentToolCalls",
1345
+ "historyKeepRecentTokens",
1346
+ "historyMinReclaimTokens",
1347
+ "readInputCapChars",
1348
+ "autoCompactThresholdPercent",
1349
+ "presetOptions"
1350
+ ]);
1351
+ const LEGACY_GATE_REPLACEMENTS = Object.freeze({
1352
+ thresholdChars: "nativeTriggerTokens",
1353
+ freshThresholdChars: "freshTriggerTokens",
1354
+ freshTargetChars: "freshTargetTokens",
1355
+ freshBatchTriggerChars: "aggregateTriggerTokens",
1356
+ freshBatchTargetChars: "aggregateTargetTokens",
1357
+ historyTriggerChars: "historyTriggerTokens",
1358
+ historyKeepRecentChars: "historyKeepRecentTokens",
1359
+ historyMinReclaimChars: "historyMinReclaimTokens",
1360
+ historyKeepRecentTurns: "historyKeepRecentToolCalls"
1361
+ });
1362
+ /**
1363
+ * Count Unicode code points without splitting surrogate pairs.
1364
+ * @param text - text whose code points are counted.
1365
+ * @returns the number of Unicode code points.
1366
+ */
1367
+ function codePointLength(text) {
1368
+ let length = 0;
1369
+ for (const _point of text) length++;
1370
+ return length;
1371
+ }
1372
+ /** Express one token-named policy gate on the character basis. */
1373
+ function charsForTokens(tokens) {
1374
+ return tokens * 4;
1375
+ }
1376
+ /** Derive the telemetry-only token figure from a character measurement. */
1377
+ function charsToTokens(chars) {
1378
+ if (!Number.isFinite(chars) || chars <= 0) return 0;
1379
+ return Math.max(1, Math.round(chars / 4));
1380
+ }
1381
+ /**
1382
+ * Test whether a settings value names a supported compression profile.
1383
+ * @param value - untrusted settings value.
1384
+ * @returns whether the value is a supported compression profile.
1385
+ */
1386
+ function isCompressionProfile(value) {
1387
+ return typeof value === "string" && COMPRESSION_PROFILES.includes(value);
1388
+ }
1389
+ /**
1390
+ * Resolve and validate plugin configuration.
1391
+ * @param config - optional composition overrides.
1392
+ * @returns a detached, deeply immutable configuration snapshot.
1393
+ */
1394
+ function resolveConfig(config = {}) {
1395
+ for (const key of Object.keys(config)) {
1396
+ const replacement = LEGACY_GATE_REPLACEMENTS[key];
1397
+ if (replacement !== void 0) throw new Error(`ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; choose "${replacement}" manually in tokens (no character conversion is applied)`);
1398
+ if (!CONFIG_KEYS.has(key)) throw new Error(`ToolResultPruneConfig: unknown key "${key}"`);
1399
+ }
1400
+ const resolved = {
1401
+ profile: config.profile ?? DEFAULTS.profile,
1402
+ headChars: config.headChars ?? DEFAULTS.headChars,
1403
+ tailChars: config.tailChars ?? DEFAULTS.tailChars,
1404
+ ...config.nativeTriggerTokens === void 0 ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
1405
+ ...config.nativeTargetTokens === void 0 ? {} : { nativeTargetTokens: config.nativeTargetTokens },
1406
+ ...config.freshTriggerTokens === void 0 ? {} : { freshTriggerTokens: config.freshTriggerTokens },
1407
+ ...config.freshTargetTokens === void 0 ? {} : { freshTargetTokens: config.freshTargetTokens },
1408
+ ...config.aggregateTriggerTokens === void 0 ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
1409
+ ...config.aggregateTargetTokens === void 0 ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
1410
+ ...config.historyTriggerTokens === void 0 ? {} : { historyTriggerTokens: config.historyTriggerTokens },
1411
+ ...config.historyKeepRecentToolCalls === void 0 ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
1412
+ ...config.historyKeepRecentTokens === void 0 ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
1413
+ ...config.historyMinReclaimTokens === void 0 ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
1414
+ ...config.readInputCapChars === void 0 ? {} : { readInputCapChars: config.readInputCapChars },
1415
+ ...config.autoCompactThresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
1416
+ ...config.presetOptions === void 0 ? {} : { presetOptions: config.presetOptions }
1417
+ };
1418
+ if (!isCompressionProfile(resolved.profile)) throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`);
1419
+ assertNonNegativeInteger("headChars", resolved.headChars);
1420
+ assertNonNegativeInteger("tailChars", resolved.tailChars);
1421
+ for (const key of [
1422
+ "nativeTriggerTokens",
1423
+ "nativeTargetTokens",
1424
+ "freshTriggerTokens",
1425
+ "freshTargetTokens",
1426
+ "aggregateTriggerTokens",
1427
+ "aggregateTargetTokens",
1428
+ "historyTriggerTokens",
1429
+ "historyMinReclaimTokens",
1430
+ "readInputCapChars"
1431
+ ]) {
1432
+ const value = resolved[key];
1433
+ if (value !== void 0) assertPositiveInteger(key, value);
1434
+ }
1435
+ if (resolved.historyKeepRecentToolCalls !== void 0) assertNonNegativeInteger("historyKeepRecentToolCalls", resolved.historyKeepRecentToolCalls);
1436
+ if (resolved.historyKeepRecentTokens !== void 0) assertNonNegativeInteger("historyKeepRecentTokens", resolved.historyKeepRecentTokens);
1437
+ if (resolved.autoCompactThresholdPercent !== void 0 && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) throw new Error(`ToolResultPruneConfig: autoCompactThresholdPercent (${String(resolved.autoCompactThresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`);
1438
+ assertTargetBelowTrigger("native", resolved.nativeTargetTokens, resolved.nativeTriggerTokens);
1439
+ assertTargetBelowTrigger("fresh", resolved.freshTargetTokens, resolved.freshTriggerTokens);
1440
+ assertTargetBelowTrigger("aggregate", resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens);
1441
+ return deepFreeze(structuredClone(resolved));
1442
+ }
1443
+ /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
1444
+ const AUTO_COMPACT_HISTORY_RATIOS = Object.freeze({
1445
+ balanced: Object.freeze({
1446
+ trigger: .625,
1447
+ minReclaim: .12,
1448
+ keepRecentTokens: .08
1449
+ }),
1450
+ savings: Object.freeze({
1451
+ trigger: .5,
1452
+ minReclaim: .16,
1453
+ keepRecentTokens: .08
1454
+ }),
1455
+ "cache-strict": Object.freeze({
1456
+ trigger: .75,
1457
+ minReclaim: .16,
1458
+ keepRecentTokens: .08
1459
+ }),
1460
+ adaptive: Object.freeze({
1461
+ trigger: .625,
1462
+ minReclaim: .12,
1463
+ keepRecentTokens: .08
1464
+ }),
1465
+ "tokenpilot-inspired": Object.freeze({
1466
+ trigger: .625,
1467
+ minReclaim: .12,
1468
+ keepRecentTokens: .08
1469
+ })
1470
+ });
1471
+ /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
1472
+ const MICRO_DEADLINE_RATIO = .875;
1473
+ /**
1474
+ * TokenPilot-inspired sub-capability defaults. Every capability is on except
1475
+ * the estimator, which requires an explicit endpoint channel (host or direct)
1476
+ * before any consumer may leave its rule-only fallback.
1477
+ */
1478
+ const PRESET_OPTION_DEFAULTS = deepFreeze({
1479
+ noNetSavingsGuard: true,
1480
+ skipReductionRecovery: true,
1481
+ dedupeToolResults: true,
1482
+ summaryLocator: true,
1483
+ prefixStabilizer: true,
1484
+ readState: true,
1485
+ estimator: { mode: "" },
1486
+ advisor: {
1487
+ mode: "",
1488
+ timeoutMs: 8e3,
1489
+ refreshTurns: 8,
1490
+ scoreThreshold: .35,
1491
+ sampleLimit: 16,
1492
+ minTokens: 250
1493
+ }
1494
+ });
1495
+ /**
1496
+ * Merge persisted presetOptions overrides over the tokenpilot-inspired
1497
+ * defaults. Persisted booleans are three-state (undefined = inherit); the
1498
+ * estimator channel overrides the default empty mode wholesale.
1499
+ */
1500
+ function mergePresetOptions(overrides) {
1501
+ if (overrides === void 0) return PRESET_OPTION_DEFAULTS;
1502
+ return deepFreeze({
1503
+ noNetSavingsGuard: true,
1504
+ skipReductionRecovery: true,
1505
+ dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
1506
+ summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
1507
+ prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
1508
+ readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
1509
+ estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
1510
+ advisor: {
1511
+ mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
1512
+ timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
1513
+ refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
1514
+ scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
1515
+ sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
1516
+ minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens
1517
+ }
1518
+ });
1519
+ }
1520
+ /**
1521
+ * Resolve the Auto-Compact-linked History watermarks for one standard profile.
1522
+ *
1523
+ * `A = floor(C × a)` is the Auto Compact token watermark for the routed
1524
+ * context window `C` and the user threshold `a = p / 100`; the History
1525
+ * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
1526
+ * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
1527
+ * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
1528
+ * preset numbers exactly. Custom stays manual and Off/Native run no History,
1529
+ * so none of them link.
1530
+ */
1531
+ function resolveAutoCompactLinkage(profile, options) {
1532
+ const ratios = profile === "custom" ? void 0 : AUTO_COMPACT_HISTORY_RATIOS[profile];
1533
+ const contextWindow = options.contextWindowTokens;
1534
+ const threshold = options.autoCompactThresholdPercent;
1535
+ if (ratios === void 0) return void 0;
1536
+ if (!isValidAutoCompactThresholdPercent(threshold)) return void 0;
1537
+ if (!Number.isSafeInteger(contextWindow) || contextWindow === void 0 || contextWindow <= 0) return void 0;
1538
+ const autoCompactTokens = Math.floor(contextWindow * (threshold / 100));
1539
+ if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return void 0;
1540
+ const linked = {
1541
+ autoCompactTokens,
1542
+ microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
1543
+ historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
1544
+ historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
1545
+ historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens)
1546
+ };
1547
+ for (const value of Object.values(linked)) if (!Number.isSafeInteger(value) || value <= 0) return void 0;
1548
+ return linked;
1549
+ }
1550
+ /**
1551
+ * Resolve one public profile into a complete mixed-strategy policy.
1552
+ * @param config - validated composition configuration.
1553
+ * @param profile - profile frozen for the target Session.
1554
+ * @param custom - versioned Custom document used only by the `custom` profile.
1555
+ * @param options - routed capacity and the frozen Auto Compact threshold used
1556
+ * to resolve context-percent Custom values and standard-profile linkage.
1557
+ * @returns the effective deterministic compression policy.
1558
+ */
1559
+ function resolvePolicy(config, profile, custom = DEFAULT_CUSTOM_COMPRESSION_POLICY, options = {}) {
1560
+ if (profile === "custom") return resolveCustomPolicy(custom, options);
1561
+ const preset = {
1562
+ off: {
1563
+ nativeToolResultEnabled: false,
1564
+ freshEnabled: false,
1565
+ aggregateEnabled: false,
1566
+ historyMode: "disabled",
1567
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
1568
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
1569
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER,
1570
+ freshTargetTokens: Number.MAX_SAFE_INTEGER,
1571
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
1572
+ aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
1573
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER,
1574
+ historyKeepRecentToolCalls: 10,
1575
+ historyKeepRecentTokens: 64e3,
1576
+ historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
1577
+ },
1578
+ native: {
1579
+ nativeToolResultEnabled: true,
1580
+ freshEnabled: false,
1581
+ aggregateEnabled: false,
1582
+ historyMode: "disabled",
1583
+ nativeTriggerTokens: 4096,
1584
+ nativeTargetTokens: 2048,
1585
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER,
1586
+ freshTargetTokens: Number.MAX_SAFE_INTEGER,
1587
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER,
1588
+ aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
1589
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER,
1590
+ historyKeepRecentToolCalls: 10,
1591
+ historyKeepRecentTokens: 64e3,
1592
+ historyMinReclaimTokens: Number.MAX_SAFE_INTEGER
1593
+ },
1594
+ balanced: {
1595
+ nativeToolResultEnabled: false,
1596
+ freshEnabled: true,
1597
+ aggregateEnabled: true,
1598
+ historyMode: "routine",
1599
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
1600
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
1601
+ freshTriggerTokens: 8192,
1602
+ freshTargetTokens: 3072,
1603
+ aggregateTriggerTokens: 32768,
1604
+ aggregateTargetTokens: 12288,
1605
+ historyTriggerTokens: 5e5,
1606
+ historyKeepRecentToolCalls: 10,
1607
+ historyKeepRecentTokens: 64e3,
1608
+ historyMinReclaimTokens: 96e3
1609
+ },
1610
+ "cache-strict": {
1611
+ nativeToolResultEnabled: false,
1612
+ freshEnabled: true,
1613
+ aggregateEnabled: true,
1614
+ historyMode: "capacity-pressure",
1615
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
1616
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
1617
+ freshTriggerTokens: 8192,
1618
+ freshTargetTokens: 3072,
1619
+ aggregateTriggerTokens: 32768,
1620
+ aggregateTargetTokens: 12288,
1621
+ historyTriggerTokens: 6e5,
1622
+ historyKeepRecentToolCalls: 10,
1623
+ historyKeepRecentTokens: 64e3,
1624
+ historyMinReclaimTokens: 128e3
1625
+ },
1626
+ savings: {
1627
+ nativeToolResultEnabled: false,
1628
+ freshEnabled: true,
1629
+ aggregateEnabled: true,
1630
+ historyMode: "routine",
1631
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
1632
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
1633
+ freshTriggerTokens: 4096,
1634
+ freshTargetTokens: 1536,
1635
+ aggregateTriggerTokens: 16384,
1636
+ aggregateTargetTokens: 4096,
1637
+ historyTriggerTokens: 4e5,
1638
+ historyKeepRecentToolCalls: 10,
1639
+ historyKeepRecentTokens: 64e3,
1640
+ historyMinReclaimTokens: 128e3
1641
+ },
1642
+ adaptive: {
1643
+ nativeToolResultEnabled: false,
1644
+ freshEnabled: true,
1645
+ aggregateEnabled: true,
1646
+ historyMode: "adaptive",
1647
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
1648
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
1649
+ freshTriggerTokens: 8192,
1650
+ freshTargetTokens: 3072,
1651
+ aggregateTriggerTokens: 32768,
1652
+ aggregateTargetTokens: 12288,
1653
+ historyTriggerTokens: 5e5,
1654
+ historyKeepRecentToolCalls: 10,
1655
+ historyKeepRecentTokens: 64e3,
1656
+ historyMinReclaimTokens: 96e3
1657
+ },
1658
+ "tokenpilot-inspired": {
1659
+ nativeToolResultEnabled: false,
1660
+ freshEnabled: true,
1661
+ aggregateEnabled: true,
1662
+ historyMode: "routine",
1663
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER,
1664
+ nativeTargetTokens: Number.MAX_SAFE_INTEGER,
1665
+ freshTriggerTokens: 8192,
1666
+ freshTargetTokens: 3072,
1667
+ aggregateTriggerTokens: 32768,
1668
+ aggregateTargetTokens: 12288,
1669
+ historyTriggerTokens: 5e5,
1670
+ historyKeepRecentToolCalls: 10,
1671
+ historyKeepRecentTokens: 64e3,
1672
+ historyMinReclaimTokens: 96e3
1673
+ }
1674
+ }[profile];
1675
+ const linkage = resolveAutoCompactLinkage(profile, options);
1676
+ const policy = {
1677
+ profile,
1678
+ ...preset,
1679
+ nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
1680
+ nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
1681
+ freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
1682
+ freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
1683
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
1684
+ aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
1685
+ historyTriggerTokens: config.historyTriggerTokens ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
1686
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
1687
+ historyKeepRecentTokens: config.historyKeepRecentTokens ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
1688
+ historyMinReclaimTokens: config.historyMinReclaimTokens ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
1689
+ ...config.readInputCapChars === void 0 ? {} : { readInputCapChars: config.readInputCapChars },
1690
+ ...linkage === void 0 ? {} : {
1691
+ autoCompactTokens: linkage.autoCompactTokens,
1692
+ microDeadlineTokens: linkage.microDeadlineTokens
1693
+ },
1694
+ ...profile === "tokenpilot-inspired" ? { presetOptions: mergePresetOptions(config.presetOptions) } : {}
1695
+ };
1696
+ if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === "native") throw new Error("context compression policy: native target must be below trigger");
1697
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: fresh target must be below trigger");
1698
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) throw new Error("context compression policy: aggregate target must be below trigger");
1699
+ if (policy.readInputCapChars !== void 0 && policy.readInputCapChars <= policy.freshTriggerTokens * 4) throw new Error("context compression policy: read input cap would silence the fresh path");
1700
+ return deepFreeze(policy);
1701
+ }
1702
+ function assertTargetBelowTrigger(label, target, trigger) {
1703
+ if (target === void 0 !== (trigger === void 0)) throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`);
1704
+ if (target !== void 0 && trigger !== void 0 && target >= trigger) throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`);
1705
+ }
1706
+ function assertPositiveInteger(name, value) {
1707
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`);
1708
+ }
1709
+ function assertNonNegativeInteger(name, value) {
1710
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
1711
+ }
1712
+ //#endregion
1713
+ export { getObservedIntentEnabled as A, priceOfficialDeepSeekUsage as B, isSessionOverrideAction as C, evaluateIntentGate as D, INTENT_GATE_GROWTH_TOKENS as E, recordRecertified as F, getSavingsLedger as H, recordScore as I, setSummaryOverride as L, invalidateOnTaskChange as M, observeIntentEnabled as N, getAdvisorState as O, recordIntentFold as P, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as R, estimateSavingsPricing as S, INTENT_GATE_FLOOR_FRACTION as T, resolveOfficialDeepSeekPrice as V, assertNever as _, PRUNE_MARKER as a, applySessionOverride as b, codePointLength as c, parseContextCompressionSettings as d, resolveConfig as f, resolveCustomPolicy as g, DEFAULT_CUSTOM_COMPRESSION_POLICY as h, DEFAULTS as i, getSummaryOverride as j, getLastIntentFold as k, isCompressionProfile as l, CustomCompressionPolicySchema as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, charsForTokens as o, resolvePolicy as p, ContextCompressionSettingsSchema as r, charsToTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isValidAutoCompactThresholdPercent as u, deepFreeze as v, observeContextUsage as w, buildMonitorSnapshot as x, COMPRESSION_PROFILES as y, decimalRateNanoUnits as z };