dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +401 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +44 -0
  11. package/packages/selector/lib/client.js +1733 -6
  12. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  13. package/packages/selector/lib/index.d.ts +13 -1
  14. package/packages/selector/lib/index.js +204 -3
  15. package/packages/selector/lib/profiles.d.ts +6 -0
  16. package/packages/selector/lib/pruner.d.ts +6 -0
  17. package/packages/selector/lib/pruner.js +90 -258
  18. package/packages/selector/lib/style.css +88 -46
  19. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  20. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  21. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  22. package/packages/selector/src/client/decode.ts +57 -53
  23. package/packages/selector/src/client/index.ts +307 -213
  24. package/packages/selector/src/client/locales/de.ts +141 -0
  25. package/packages/selector/src/client/locales/es.ts +141 -0
  26. package/packages/selector/src/client/locales/fr.ts +141 -0
  27. package/packages/selector/src/client/locales/it.ts +141 -0
  28. package/packages/selector/src/client/locales/ja.ts +141 -0
  29. package/packages/selector/src/client/locales/ko.ts +141 -0
  30. package/packages/selector/src/client/locales/ru.ts +141 -0
  31. package/packages/selector/src/client/locales.ts +282 -196
  32. package/packages/selector/src/client/monitor-fab.ts +336 -0
  33. package/packages/selector/src/client/savings-card.tsx +150 -0
  34. package/packages/selector/src/client/settings-section.tsx +140 -124
  35. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  36. package/packages/selector/src/index.ts +207 -5
  37. package/packages/selector/src/preset-overlay.ts +629 -629
  38. package/packages/selector/src/profiles.ts +431 -414
  39. package/packages/selector/src/pruner/content.ts +198 -198
  40. package/packages/selector/src/pruner/state.ts +57 -57
  41. package/packages/selector/src/pruner.ts +2759 -2665
  42. package/packages/selector/src/runtime/audit.ts +303 -303
  43. package/packages/selector/src/runtime/config.ts +756 -731
  44. package/packages/selector/src/runtime/monitor.ts +235 -0
  45. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  46. package/packages/selector/src/runtime/retrieve.ts +479 -457
  47. package/packages/selector/src/runtime/savings.ts +337 -0
  48. package/packages/selector/src/runtime/summary-command.ts +133 -133
  49. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  50. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  51. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  52. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  53. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  54. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  55. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  56. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  57. package/packages/selector/src/runtime/types.ts +365 -358
  58. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  59. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  60. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  61. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  62. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  63. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  64. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  65. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  66. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  67. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  69. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  70. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  71. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  72. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  73. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  74. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  75. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  76. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  77. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  78. package/scripts/packed-components-smoke.mjs +734 -734
  79. package/scripts/packed-install-e2e.mjs +1 -1
  80. package/scripts/verify-release.mjs +1 -1
  81. package/tests/TEST_INVENTORY.md +41 -41
  82. package/tsconfig.tests.json +17 -17
  83. package/vitest.config.ts +57 -57
@@ -1,731 +1,756 @@
1
- /** Configuration resolution for the mixed deterministic context-compression selector. */
2
-
3
- import z from '@deepseek-ai/schemastery'
4
- import type {
5
- AutoCompactSettings,
6
- CodeSkeletonSettings,
7
- CompressionPolicy,
8
- IntentSummarySettings,
9
- CompressionProfile,
10
- CustomCompressionPolicy,
11
- PresetOptions,
12
- PresetOptionsSettings,
13
- ContextCompressionSettings,
14
- ResolvedConfig,
15
- ToolResultPruneConfig,
16
- } from './types.ts'
17
- import { COMPRESSION_PROFILES } from './types.ts'
18
- import {
19
- CustomCompressionPolicySchema,
20
- DEFAULT_CUSTOM_COMPRESSION_POLICY,
21
- resolveCustomPolicy,
22
- type CustomPolicyResolutionOptions,
23
- } from './custom-policy.ts'
24
- import { deepFreeze } from './value.ts'
25
-
26
- /** Settings namespace shared by the Host service and browser selector. */
27
- export const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = 'context-compression'
28
-
29
- /** Fixed native fallback marker. */
30
- export const PRUNE_MARKER = '\n\n[... tool result middle pruned ...]\n\n'
31
-
32
- /**
33
- * The one Auto Compact threshold contract shared by the settings UI, the
34
- * persisted settings schema, and the runtime resolver. Every integer in the
35
- * range is valid and entered directly in the UI.
36
- */
37
- export const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
38
- min: 50,
39
- max: 90,
40
- step: 1,
41
- default: 80,
42
- } as const)
43
-
44
- /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
45
- export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
46
- return typeof value === 'number'
47
- && Number.isSafeInteger(value)
48
- && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
49
- && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
50
- }
51
-
52
- const AUTO_COMPACT_DEFAULT: AutoCompactSettings = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default })
53
-
54
- /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
55
- function isPlainRecord(value: unknown): value is Record<string, unknown> {
56
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
57
- const prototype = Object.getPrototypeOf(value) as object | null
58
- return prototype === Object.prototype || prototype === null
59
- }
60
-
61
- /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
62
- function assertPlainDataTree(value: unknown, seen: WeakSet<object> = new WeakSet()): void {
63
- if (value === null || typeof value !== 'object') return
64
- if (seen.has(value)) return
65
- seen.add(value)
66
- if (Array.isArray(value)) {
67
- for (const entry of value) assertPlainDataTree(entry, seen)
68
- return
69
- }
70
- if (!isPlainRecord(value)) {
71
- throw new TypeError('Context-compression settings must contain only plain objects')
72
- }
73
- for (const entry of Object.values(value)) assertPlainDataTree(entry, seen)
74
- }
75
-
76
- /**
77
- * Strictly parse the persisted autoCompact section. Schemastery object
78
- * defaults silently absorb null, empty, and extra-key sections, so this stays
79
- * hand-validated beside the top-level unknown-key check.
80
- */
81
- function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
82
- if (value === undefined) return AUTO_COMPACT_DEFAULT
83
- if (!isPlainRecord(value)) {
84
- throw new TypeError('Context-compression autoCompact must be a plain object')
85
- }
86
- const keys = Object.keys(value)
87
- if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
88
- throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
89
- }
90
- const thresholdPercent = (value).thresholdPercent
91
- if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
92
- 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)}`)
93
- }
94
- return { thresholdPercent }
95
- }
96
-
97
- /**
98
- * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
99
- * to every profile: absent inherits the lossless `false` default, while a
100
- * present-but-invalid section is an explicitly invalid document.
101
- */
102
- function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
103
- if (value === undefined) return { enabled: false }
104
- if (!isPlainRecord(value)) {
105
- throw new TypeError('Context-compression codeSkeleton must be a plain object')
106
- }
107
- const keys = Object.keys(value)
108
- if (keys.length !== 1 || keys[0] !== 'enabled') {
109
- throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
110
- }
111
- const enabled = (value).enabled
112
- if (typeof enabled !== 'boolean') {
113
- throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
114
- }
115
- return { enabled }
116
- }
117
-
118
- /**
119
- * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
120
- * section semantics: absent inherits the lossless `false` default, while a
121
- * present-but-invalid section is an explicitly invalid document.
122
- */
123
- function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
124
- if (value === undefined) return { enabled: false }
125
- if (!isPlainRecord(value)) {
126
- throw new TypeError('Context-compression intentSummary must be a plain object')
127
- }
128
- const keys = Object.keys(value)
129
- if (keys.length !== 1 || keys[0] !== 'enabled') {
130
- throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
131
- }
132
- const enabled = (value).enabled
133
- if (typeof enabled !== 'boolean') {
134
- throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
135
- }
136
- return { enabled }
137
- }
138
-
139
- /**
140
- * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
141
- * inherits the preset defaults; present-but-invalid is rejected, mirroring the
142
- * codeSkeleton section semantics.
143
- */
144
- export function parsePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
145
- if (value === undefined) return undefined
146
- if (!isPlainRecord(value)) {
147
- throw new TypeError('Context-compression presetOptions must be a plain object')
148
- }
149
- const allowed = new Set([
150
- 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
151
- 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
152
- // Legacy keys of the retired human-gated review pipeline. They stay in the
153
- // ACCEPTED set on purpose: the keys are persisted in existing settings
154
- // documents, and rejecting them would make this plugin fail to load on an
155
- // upgrade. They are read by nothing — the gate they configured no longer
156
- // exists, and a reduction never blocks automatic processing.
157
- 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
158
- 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
159
- 'advisorMinTokens',
160
- ])
161
- const unknown = Object.keys(value).find(key => !allowed.has(key))
162
- if (unknown !== undefined) {
163
- throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`)
164
- }
165
- const booleans = ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const
166
- for (const key of booleans) {
167
- const entry = value[key]
168
- if (entry !== undefined && typeof entry !== 'boolean') {
169
- throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`)
170
- }
171
- }
172
- const estimatorMode = value.estimatorMode
173
- if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
174
- throw new TypeError('Context-compression presetOptions.estimatorMode must be "", "host", or "direct"')
175
- }
176
- const advisorMode = value.advisorMode
177
- if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
178
- throw new TypeError('Context-compression presetOptions.advisorMode must be "", "host", or "direct"')
179
- }
180
- const advisorTimeoutMs = value.advisorTimeoutMs
181
- if (advisorTimeoutMs !== undefined
182
- && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
183
- || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
184
- throw new TypeError('Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000')
185
- }
186
- const advisorRefreshTurns = value.advisorRefreshTurns
187
- if (advisorRefreshTurns !== undefined
188
- && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
189
- || advisorRefreshTurns < 1)) {
190
- throw new TypeError('Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1')
191
- }
192
- const advisorScoreThreshold = value.advisorScoreThreshold
193
- if (advisorScoreThreshold !== undefined
194
- && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
195
- || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
196
- throw new TypeError('Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1')
197
- }
198
- const advisorSampleLimit = value.advisorSampleLimit
199
- if (advisorSampleLimit !== undefined
200
- && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
201
- || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
202
- throw new TypeError('Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64')
203
- }
204
- const advisorMinTokens = value.advisorMinTokens
205
- if (advisorMinTokens !== undefined
206
- && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
207
- throw new TypeError('Context-compression presetOptions.advisorMinTokens must be a positive integer')
208
- }
209
- const estimatorTimeoutMs = value.estimatorTimeoutMs
210
- if (estimatorTimeoutMs !== undefined
211
- && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
212
- || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
213
- throw new TypeError('Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000')
214
- }
215
- for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
216
- const entry = value[key]
217
- if (entry !== undefined && typeof entry !== 'string') {
218
- throw new TypeError(`Context-compression presetOptions.${key} must be a string`)
219
- }
220
- }
221
- const result: {
222
- -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
223
- } = {}
224
- if (value.dedupeToolResults !== undefined) result.dedupeToolResults = value.dedupeToolResults as boolean
225
- if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
226
- if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
227
- if (value.readState !== undefined) result.readState = value.readState as boolean
228
- if (estimatorMode !== undefined) result.estimatorMode = estimatorMode
229
- if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
230
- if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
231
- if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
232
- if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
233
- if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs
234
- if (advisorMode !== undefined) result.advisorMode = advisorMode
235
- if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs
236
- if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns
237
- if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold
238
- if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit
239
- if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens
240
- return result
241
- }
242
-
243
- /** Settings schema used by the user-facing profile selector. */
244
- const contextCompressionSettingsInputSchema = z.object({
245
- profile: z.union([...COMPRESSION_PROFILES]).default('balanced'),
246
- custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY),
247
- })
248
-
249
- /**
250
- * Reject a section that is PRESENT but not a usable value. Schemastery
251
- * `.default(...)` silently substitutes null and undefined, which would turn a
252
- * hand-corrupted store into the (lossy) default policy; only genuinely absent
253
- * keys may inherit defaults, and that distinction must be made before any
254
- * default can fire.
255
- */
256
- function assertPresentSection(
257
- candidate: Record<string, unknown>,
258
- key: 'profile' | 'custom',
259
- valid: (value: unknown) => boolean,
260
- ): void {
261
- if (!Object.hasOwn(candidate, key)) return
262
- if (!valid(candidate[key])) {
263
- throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`)
264
- }
265
- }
266
-
267
- const isSupportedProfile = (value: unknown): boolean =>
268
- typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
269
-
270
- const isUsableCustomDocument = (value: unknown): boolean =>
271
- isPlainRecord(value)
272
-
273
- export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
274
- profile: 'balanced',
275
- custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
276
- autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
277
- codeSkeleton: { enabled: false },
278
- intentSummary: { enabled: false },
279
- }
280
-
281
- /**
282
- * Parse one settings document with the persisted-section semantics: `undefined`
283
- * inherits the defaults (an absent section), while `null` is an explicitly
284
- * invalid document and must never silently become the default policy.
285
- */
286
- export function parseContextCompressionSettings(value: unknown): ContextCompressionSettings {
287
- if (!isPlainRecord(value)) {
288
- throw new TypeError('Context-compression settings must be a plain object')
289
- }
290
- const keys = Object.keys(value)
291
- // Documents surfaced by the settings service are always schema-resolved and
292
- // complete; anything thinner is a hand-edited store and must not silently
293
- // become a default (possibly lossy) policy.
294
- if (keys.length === 0 || !keys.includes('profile') || !keys.includes('custom')) {
295
- throw new TypeError('Context-compression settings document is missing its complete shape')
296
- }
297
- return ContextCompressionSettingsSchema(value as never)
298
- }
299
-
300
- /** Settings schema used by the user-facing profile selector. */
301
- export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z.transform(
302
- z.any().required(),
303
- (value: unknown): ContextCompressionSettings => {
304
- if (!isPlainRecord(value)) {
305
- throw new TypeError('Context-compression settings must be a plain object')
306
- }
307
- // Validate prototypes before cloning, then parse a detached mutable copy:
308
- // SettingsProvider returns frozen records, while structuredClone would
309
- // otherwise erase exotic prototypes before this boundary can reject them.
310
- assertPlainDataTree(value)
311
- const candidate = structuredClone(value)
312
- // Settings stored before the autoCompact or codeSkeleton sections existed
313
- // remain valid and inherit their defaults; the sections themselves stay
314
- // strictly shaped.
315
- const unknown = Object.keys(candidate).find(key =>
316
- key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')
317
- if (unknown !== undefined) {
318
- throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
319
- }
320
- // Present-but-invalid sections must never fall through to the Schemastery
321
- // defaults below: `profile: null` silently becoming the lossy `balanced`
322
- // default is exactly the corruption the lossless-off fallback exists for.
323
- // Only genuinely absent sections (internal partial fallbacks) may inherit.
324
- assertPresentSection(candidate, 'profile', isSupportedProfile)
325
- assertPresentSection(candidate, 'custom', isUsableCustomDocument)
326
- const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
327
- const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
328
- const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
329
- const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
330
- return {
331
- ...contextCompressionSettingsInputSchema(candidate),
332
- autoCompact,
333
- codeSkeleton,
334
- intentSummary,
335
- ...presetOptions === undefined ? {} : { presetOptions },
336
- }
337
- },
338
- ).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS) as z<ContextCompressionSettings>
339
-
340
- /** Low-friction defaults; token budgets live in resolved profile policy. */
341
- export const DEFAULTS: ResolvedConfig = deepFreeze({
342
- profile: 'balanced',
343
- headChars: 4096,
344
- tailChars: 1024,
345
- })
346
-
347
- const CONFIG_KEYS: ReadonlySet<string> = new Set([
348
- 'profile',
349
- 'headChars',
350
- 'tailChars',
351
- 'nativeTriggerTokens',
352
- 'nativeTargetTokens',
353
- 'freshTriggerTokens',
354
- 'freshTargetTokens',
355
- 'aggregateTriggerTokens',
356
- 'aggregateTargetTokens',
357
- 'historyTriggerTokens',
358
- 'historyKeepRecentToolCalls',
359
- 'historyKeepRecentTokens',
360
- 'historyMinReclaimTokens',
361
- 'readInputCapChars',
362
- 'autoCompactThresholdPercent',
363
- 'presetOptions',
364
- ])
365
-
366
- const LEGACY_GATE_REPLACEMENTS: Readonly<Record<string, string>> = Object.freeze({
367
- thresholdChars: 'nativeTriggerTokens',
368
- freshThresholdChars: 'freshTriggerTokens',
369
- freshTargetChars: 'freshTargetTokens',
370
- freshBatchTriggerChars: 'aggregateTriggerTokens',
371
- freshBatchTargetChars: 'aggregateTargetTokens',
372
- historyTriggerChars: 'historyTriggerTokens',
373
- historyKeepRecentChars: 'historyKeepRecentTokens',
374
- historyMinReclaimChars: 'historyMinReclaimTokens',
375
- historyKeepRecentTurns: 'historyKeepRecentToolCalls',
376
- })
377
-
378
- /**
379
- * Count Unicode code points without splitting surrogate pairs.
380
- * @param text - text whose code points are counted.
381
- * @returns the number of Unicode code points.
382
- */
383
- export function codePointLength(text: string): number {
384
- let length = 0
385
- for (const _point of text) length++
386
- return length
387
- }
388
-
389
- /**
390
- * Conservative upper bound on characters per token. Same convention the
391
- * readInputCapChars invariant already uses (see resolvePolicy): English
392
- * code runs approximately four characters per token at the upper bound.
393
- */
394
- export const CHARS_PER_TOKEN = 4.0
395
-
396
- /** Express one token-named policy gate on the character basis. */
397
- export function charsForTokens(tokens: number): number {
398
- return tokens * CHARS_PER_TOKEN
399
- }
400
-
401
- /** Derive the telemetry-only token figure from a character measurement. */
402
- export function charsToTokens(chars: number): number {
403
- if (!Number.isFinite(chars) || chars <= 0) return 0
404
- return Math.max(1, Math.round(chars / CHARS_PER_TOKEN))
405
- }
406
-
407
- /**
408
- * Test whether a settings value names a supported compression profile.
409
- * @param value - untrusted settings value.
410
- * @returns whether the value is a supported compression profile.
411
- */
412
- export function isCompressionProfile(value: unknown): value is CompressionProfile {
413
- return typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
414
- }
415
-
416
- /**
417
- * Resolve and validate plugin configuration.
418
- * @param config - optional composition overrides.
419
- * @returns a detached, deeply immutable configuration snapshot.
420
- */
421
- export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfig {
422
- for (const key of Object.keys(config)) {
423
- const replacement = LEGACY_GATE_REPLACEMENTS[key]
424
- if (replacement !== undefined) {
425
- throw new Error(
426
- `ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; `
427
- + `choose "${replacement}" manually in tokens (no character conversion is applied)`,
428
- )
429
- }
430
- if (!CONFIG_KEYS.has(key)) {
431
- throw new Error(`ToolResultPruneConfig: unknown key "${key}"`)
432
- }
433
- }
434
- const resolved: ResolvedConfig = {
435
- profile: config.profile ?? DEFAULTS.profile,
436
- headChars: config.headChars ?? DEFAULTS.headChars,
437
- tailChars: config.tailChars ?? DEFAULTS.tailChars,
438
- ...config.nativeTriggerTokens === undefined ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
439
- ...config.nativeTargetTokens === undefined ? {} : { nativeTargetTokens: config.nativeTargetTokens },
440
- ...config.freshTriggerTokens === undefined ? {} : { freshTriggerTokens: config.freshTriggerTokens },
441
- ...config.freshTargetTokens === undefined ? {} : { freshTargetTokens: config.freshTargetTokens },
442
- ...config.aggregateTriggerTokens === undefined ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
443
- ...config.aggregateTargetTokens === undefined ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
444
- ...config.historyTriggerTokens === undefined ? {} : { historyTriggerTokens: config.historyTriggerTokens },
445
- ...config.historyKeepRecentToolCalls === undefined ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
446
- ...config.historyKeepRecentTokens === undefined ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
447
- ...config.historyMinReclaimTokens === undefined ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
448
- ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
449
- ...config.autoCompactThresholdPercent === undefined ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
450
- ...config.presetOptions === undefined ? {} : { presetOptions: config.presetOptions },
451
- }
452
- if (!isCompressionProfile(resolved.profile)) {
453
- throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`)
454
- }
455
- assertNonNegativeInteger('headChars', resolved.headChars)
456
- assertNonNegativeInteger('tailChars', resolved.tailChars)
457
- for (const key of [
458
- 'nativeTriggerTokens', 'nativeTargetTokens', 'freshTriggerTokens', 'freshTargetTokens',
459
- 'aggregateTriggerTokens', 'aggregateTargetTokens', 'historyTriggerTokens',
460
- 'historyMinReclaimTokens', 'readInputCapChars',
461
- ] as const) {
462
- const value = resolved[key]
463
- if (value !== undefined) assertPositiveInteger(key, value)
464
- }
465
- if (resolved.historyKeepRecentToolCalls !== undefined) {
466
- assertNonNegativeInteger('historyKeepRecentToolCalls', resolved.historyKeepRecentToolCalls)
467
- }
468
- if (resolved.historyKeepRecentTokens !== undefined) {
469
- assertNonNegativeInteger('historyKeepRecentTokens', resolved.historyKeepRecentTokens)
470
- }
471
- if (resolved.autoCompactThresholdPercent !== undefined
472
- && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) {
473
- 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)}`)
474
- }
475
- assertTargetBelowTrigger('native', resolved.nativeTargetTokens, resolved.nativeTriggerTokens)
476
- assertTargetBelowTrigger('fresh', resolved.freshTargetTokens, resolved.freshTriggerTokens)
477
- assertTargetBelowTrigger('aggregate', resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens)
478
- return deepFreeze(structuredClone(resolved))
479
- }
480
-
481
- /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
482
- const AUTO_COMPACT_HISTORY_RATIOS: Readonly<Record<string, Readonly<{
483
- trigger: number
484
- minReclaim: number
485
- keepRecentTokens: number
486
- }>>> = Object.freeze({
487
- balanced: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
488
- savings: Object.freeze({ trigger: 0.50, minReclaim: 0.16, keepRecentTokens: 0.08 }),
489
- 'cache-strict': Object.freeze({ trigger: 0.75, minReclaim: 0.16, keepRecentTokens: 0.08 }),
490
- adaptive: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
491
- 'tokenpilot-inspired': Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
492
- })
493
-
494
- /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
495
- const MICRO_DEADLINE_RATIO = 0.875
496
-
497
- /**
498
- * TokenPilot-inspired sub-capability defaults. Every capability is on except
499
- * the estimator, which requires an explicit endpoint channel (host or direct)
500
- * before any consumer may leave its rule-only fallback.
501
- */
502
- const PRESET_OPTION_DEFAULTS: PresetOptions = deepFreeze({
503
- noNetSavingsGuard: true,
504
- skipReductionRecovery: true,
505
- dedupeToolResults: true,
506
- summaryLocator: true,
507
- prefixStabilizer: true,
508
- readState: true,
509
- estimator: { mode: '' },
510
- // Advisory advisor ships off: statistics and suggestions only, never a gate.
511
- advisor: {
512
- mode: '',
513
- timeoutMs: 8_000,
514
- refreshTurns: 8,
515
- scoreThreshold: 0.35,
516
- sampleLimit: 16,
517
- minTokens: 250,
518
- },
519
- })
520
-
521
- /**
522
- * Merge persisted presetOptions overrides over the tokenpilot-inspired
523
- * defaults. Persisted booleans are three-state (undefined = inherit); the
524
- * estimator channel overrides the default empty mode wholesale.
525
- */
526
- function mergePresetOptions(overrides: PresetOptionsSettings | undefined): PresetOptions {
527
- if (overrides === undefined) return PRESET_OPTION_DEFAULTS
528
- return deepFreeze({
529
- noNetSavingsGuard: true,
530
- skipReductionRecovery: true,
531
- dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
532
- summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
533
- prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
534
- readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
535
- estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
536
- advisor: {
537
- mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
538
- timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
539
- refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
540
- scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
541
- sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
542
- minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens,
543
- },
544
- })
545
- }
546
-
547
- /**
548
- * Resolve the Auto-Compact-linked History watermarks for one standard profile.
549
- *
550
- * `A = floor(C × a)` is the Auto Compact token watermark for the routed
551
- * context window `C` and the user threshold `a = p / 100`; the History
552
- * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
553
- * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
554
- * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
555
- * preset numbers exactly. Custom stays manual and Off/Native run no History,
556
- * so none of them link.
557
- */
558
- function resolveAutoCompactLinkage(
559
- profile: CompressionProfile,
560
- options: CustomPolicyResolutionOptions,
561
- ): { autoCompactTokens: number, microDeadlineTokens: number, historyTriggerTokens: number,
562
- historyMinReclaimTokens: number, historyKeepRecentTokens: number } | undefined {
563
- const ratios = profile === 'custom' ? undefined : AUTO_COMPACT_HISTORY_RATIOS[profile]
564
- const contextWindow = options.contextWindowTokens
565
- const threshold = options.autoCompactThresholdPercent
566
- if (ratios === undefined) return undefined
567
- if (!isValidAutoCompactThresholdPercent(threshold)) return undefined
568
- if (!Number.isSafeInteger(contextWindow) || contextWindow === undefined || contextWindow <= 0) return undefined
569
- // Mirror compaction-basic's evaluation order exactly: it multiplies by the
570
- // generated ratio float (p / 100), and integer-first division differs by
571
- // one token on some window/percent pairs (200k x 57).
572
- const autoCompactTokens = Math.floor(contextWindow * (threshold / 100))
573
- if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return undefined
574
- const linked = {
575
- autoCompactTokens,
576
- microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
577
- historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
578
- historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
579
- historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens),
580
- }
581
- for (const value of Object.values(linked)) {
582
- if (!Number.isSafeInteger(value) || value <= 0) return undefined
583
- }
584
- return linked
585
- }
586
-
587
- /**
588
- * Resolve one public profile into a complete mixed-strategy policy.
589
- * @param config - validated composition configuration.
590
- * @param profile - profile frozen for the target Session.
591
- * @param custom - versioned Custom document used only by the `custom` profile.
592
- * @param options - routed capacity and the frozen Auto Compact threshold used
593
- * to resolve context-percent Custom values and standard-profile linkage.
594
- * @returns the effective deterministic compression policy.
595
- */
596
- export function resolvePolicy(
597
- config: ResolvedConfig,
598
- profile: CompressionProfile,
599
- custom: CustomCompressionPolicy = DEFAULT_CUSTOM_COMPRESSION_POLICY,
600
- options: CustomPolicyResolutionOptions = {},
601
- ): CompressionPolicy {
602
- if (profile === 'custom') return resolveCustomPolicy(custom, options)
603
- const presets: Record<Exclude<CompressionProfile, 'custom'>, Omit<CompressionPolicy, 'profile'>> = {
604
- off: {
605
- nativeToolResultEnabled: false, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
606
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
607
- freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
608
- aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
609
- historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
610
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
611
- },
612
- native: {
613
- nativeToolResultEnabled: true, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
614
- nativeTriggerTokens: 4_096, nativeTargetTokens: 2_048,
615
- freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
616
- aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
617
- historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
618
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
619
- },
620
- balanced: {
621
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
622
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
623
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
624
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
625
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
626
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
627
- },
628
- 'cache-strict': {
629
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'capacity-pressure',
630
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
631
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
632
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
633
- historyTriggerTokens: 600_000, historyKeepRecentToolCalls: 10,
634
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
635
- },
636
- savings: {
637
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
638
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
639
- freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
640
- aggregateTriggerTokens: 16_384, aggregateTargetTokens: 4_096,
641
- historyTriggerTokens: 400_000, historyKeepRecentToolCalls: 10,
642
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
643
- },
644
- adaptive: {
645
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'adaptive',
646
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
647
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
648
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
649
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
650
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
651
- },
652
- 'tokenpilot-inspired': {
653
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
654
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
655
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
656
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
657
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
658
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
659
- },
660
- }
661
- const preset = presets[profile]
662
- const linkage = resolveAutoCompactLinkage(profile, options)
663
- const policy: CompressionPolicy = {
664
- profile,
665
- ...preset,
666
- nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
667
- nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
668
- freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
669
- freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
670
- aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
671
- aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
672
- historyTriggerTokens: config.historyTriggerTokens
673
- ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
674
- historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
675
- historyKeepRecentTokens: config.historyKeepRecentTokens
676
- ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
677
- historyMinReclaimTokens: config.historyMinReclaimTokens
678
- ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
679
- ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
680
- ...linkage === undefined ? {} : {
681
- autoCompactTokens: linkage.autoCompactTokens,
682
- microDeadlineTokens: linkage.microDeadlineTokens,
683
- },
684
- ...profile === 'tokenpilot-inspired' ? {
685
- presetOptions: mergePresetOptions(config.presetOptions),
686
- } : {},
687
- }
688
- if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === 'native') {
689
- throw new Error('context compression policy: native target must be below trigger')
690
- }
691
- if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
692
- throw new Error('context compression policy: fresh target must be below trigger')
693
- }
694
- if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) {
695
- throw new Error('context compression policy: aggregate target must be below trigger')
696
- }
697
- // G2 invariant: the fresh trigger is in TOKENS while a read input cap is in
698
- // CHARACTERS. English code runs ≈4.0 chars/token at the conservative upper
699
- // bound, so a cap at or below `freshTriggerTokens × 4.0` would truncate every
700
- // read result below the trigger and silently silence the fresh path.
701
- if (policy.readInputCapChars !== undefined
702
- && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
703
- throw new Error('context compression policy: read input cap would silence the fresh path')
704
- }
705
- return deepFreeze(policy)
706
- }
707
-
708
- function assertTargetBelowTrigger(
709
- label: string,
710
- target: number | undefined,
711
- trigger: number | undefined,
712
- ): void {
713
- if ((target === undefined) !== (trigger === undefined)) {
714
- throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`)
715
- }
716
- if (target !== undefined && trigger !== undefined && target >= trigger) {
717
- throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`)
718
- }
719
- }
720
-
721
- function assertPositiveInteger(name: string, value: number): void {
722
- if (!Number.isSafeInteger(value) || value <= 0) {
723
- throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`)
724
- }
725
- }
726
-
727
- function assertNonNegativeInteger(name: string, value: number): void {
728
- if (!Number.isSafeInteger(value) || value < 0) {
729
- throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`)
730
- }
731
- }
1
+ /** Configuration resolution for the mixed deterministic context-compression selector. */
2
+
3
+ import z from '@deepseek-ai/schemastery'
4
+ import type {
5
+ AutoCompactSettings,
6
+ CodeSkeletonSettings,
7
+ CompressionPolicy,
8
+ IntentSummarySettings,
9
+ MonitorPanelSettings,
10
+ CompressionProfile,
11
+ CustomCompressionPolicy,
12
+ PresetOptions,
13
+ PresetOptionsSettings,
14
+ ContextCompressionSettings,
15
+ ResolvedConfig,
16
+ ToolResultPruneConfig,
17
+ } from './types.ts'
18
+ import { COMPRESSION_PROFILES } from './types.ts'
19
+ import {
20
+ CustomCompressionPolicySchema,
21
+ DEFAULT_CUSTOM_COMPRESSION_POLICY,
22
+ resolveCustomPolicy,
23
+ type CustomPolicyResolutionOptions,
24
+ } from './custom-policy.ts'
25
+ import { deepFreeze } from './value.ts'
26
+
27
+ /** Settings namespace shared by the Host service and browser selector. */
28
+ export const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = 'context-compression'
29
+
30
+ /** Fixed native fallback marker. */
31
+ export const PRUNE_MARKER = '\n\n[... tool result middle pruned ...]\n\n'
32
+
33
+ /**
34
+ * The one Auto Compact threshold contract shared by the settings UI, the
35
+ * persisted settings schema, and the runtime resolver. Every integer in the
36
+ * range is valid and entered directly in the UI.
37
+ */
38
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
39
+ min: 50,
40
+ max: 90,
41
+ step: 1,
42
+ default: 80,
43
+ } as const)
44
+
45
+ /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
46
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
47
+ return typeof value === 'number'
48
+ && Number.isSafeInteger(value)
49
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
50
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
51
+ }
52
+
53
+ const AUTO_COMPACT_DEFAULT: AutoCompactSettings = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default })
54
+
55
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
56
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
57
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
58
+ const prototype = Object.getPrototypeOf(value) as object | null
59
+ return prototype === Object.prototype || prototype === null
60
+ }
61
+
62
+ /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
63
+ function assertPlainDataTree(value: unknown, seen: WeakSet<object> = new WeakSet()): void {
64
+ if (value === null || typeof value !== 'object') return
65
+ if (seen.has(value)) return
66
+ seen.add(value)
67
+ if (Array.isArray(value)) {
68
+ for (const entry of value) assertPlainDataTree(entry, seen)
69
+ return
70
+ }
71
+ if (!isPlainRecord(value)) {
72
+ throw new TypeError('Context-compression settings must contain only plain objects')
73
+ }
74
+ for (const entry of Object.values(value)) assertPlainDataTree(entry, seen)
75
+ }
76
+
77
+ /**
78
+ * Strictly parse the persisted autoCompact section. Schemastery object
79
+ * defaults silently absorb null, empty, and extra-key sections, so this stays
80
+ * hand-validated beside the top-level unknown-key check.
81
+ */
82
+ function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
83
+ if (value === undefined) return AUTO_COMPACT_DEFAULT
84
+ if (!isPlainRecord(value)) {
85
+ throw new TypeError('Context-compression autoCompact must be a plain object')
86
+ }
87
+ const keys = Object.keys(value)
88
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
89
+ throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
90
+ }
91
+ const thresholdPercent = (value).thresholdPercent
92
+ if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
93
+ 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)}`)
94
+ }
95
+ return { thresholdPercent }
96
+ }
97
+
98
+ /**
99
+ * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
100
+ * to every profile: absent inherits the lossless `false` default, while a
101
+ * present-but-invalid section is an explicitly invalid document.
102
+ */
103
+ function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
104
+ if (value === undefined) return { enabled: false }
105
+ if (!isPlainRecord(value)) {
106
+ throw new TypeError('Context-compression codeSkeleton must be a plain object')
107
+ }
108
+ const keys = Object.keys(value)
109
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
110
+ throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
111
+ }
112
+ const enabled = (value).enabled
113
+ if (typeof enabled !== 'boolean') {
114
+ throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
115
+ }
116
+ return { enabled }
117
+ }
118
+
119
+ /**
120
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
121
+ * section semantics: absent inherits the lossless `false` default, while a
122
+ * present-but-invalid section is an explicitly invalid document.
123
+ */
124
+ function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
125
+ if (value === undefined) return { enabled: false }
126
+ if (!isPlainRecord(value)) {
127
+ throw new TypeError('Context-compression intentSummary must be a plain object')
128
+ }
129
+ const keys = Object.keys(value)
130
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
131
+ throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
132
+ }
133
+ const enabled = (value).enabled
134
+ if (typeof enabled !== 'boolean') {
135
+ throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
136
+ }
137
+ return { enabled }
138
+ }
139
+
140
+ /**
141
+ * Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
142
+ * section semantics: absent inherits the hidden default, while a
143
+ * present-but-invalid section is an explicitly invalid document.
144
+ */
145
+ function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
146
+ if (value === undefined) return { enabled: false }
147
+ if (!isPlainRecord(value)) {
148
+ throw new TypeError('Context-compression monitorPanel must be a plain object')
149
+ }
150
+ const keys = Object.keys(value)
151
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
152
+ throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join('", "')}"`)
153
+ }
154
+ const enabled = (value as Record<string, unknown>).enabled
155
+ if (typeof enabled !== 'boolean') {
156
+ throw new TypeError('Context-compression monitorPanel.enabled must be a boolean')
157
+ }
158
+ return { enabled }
159
+ }
160
+
161
+ /**
162
+ * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
163
+ * inherits the preset defaults; present-but-invalid is rejected, mirroring the
164
+ * codeSkeleton section semantics.
165
+ */
166
+ export function parsePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
167
+ if (value === undefined) return undefined
168
+ if (!isPlainRecord(value)) {
169
+ throw new TypeError('Context-compression presetOptions must be a plain object')
170
+ }
171
+ const allowed = new Set([
172
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
173
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
174
+ // Legacy keys of the retired human-gated review pipeline. They stay in the
175
+ // ACCEPTED set on purpose: the keys are persisted in existing settings
176
+ // documents, and rejecting them would make this plugin fail to load on an
177
+ // upgrade. They are read by nothing — the gate they configured no longer
178
+ // exists, and a reduction never blocks automatic processing.
179
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
180
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
181
+ 'advisorMinTokens',
182
+ ])
183
+ const unknown = Object.keys(value).find(key => !allowed.has(key))
184
+ if (unknown !== undefined) {
185
+ throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`)
186
+ }
187
+ const booleans = ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const
188
+ for (const key of booleans) {
189
+ const entry = value[key]
190
+ if (entry !== undefined && typeof entry !== 'boolean') {
191
+ throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`)
192
+ }
193
+ }
194
+ const estimatorMode = value.estimatorMode
195
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
196
+ throw new TypeError('Context-compression presetOptions.estimatorMode must be "", "host", or "direct"')
197
+ }
198
+ const advisorMode = value.advisorMode
199
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
200
+ throw new TypeError('Context-compression presetOptions.advisorMode must be "", "host", or "direct"')
201
+ }
202
+ const advisorTimeoutMs = value.advisorTimeoutMs
203
+ if (advisorTimeoutMs !== undefined
204
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
205
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
206
+ throw new TypeError('Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000')
207
+ }
208
+ const advisorRefreshTurns = value.advisorRefreshTurns
209
+ if (advisorRefreshTurns !== undefined
210
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
211
+ || advisorRefreshTurns < 1)) {
212
+ throw new TypeError('Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1')
213
+ }
214
+ const advisorScoreThreshold = value.advisorScoreThreshold
215
+ if (advisorScoreThreshold !== undefined
216
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
217
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
218
+ throw new TypeError('Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1')
219
+ }
220
+ const advisorSampleLimit = value.advisorSampleLimit
221
+ if (advisorSampleLimit !== undefined
222
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
223
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
224
+ throw new TypeError('Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64')
225
+ }
226
+ const advisorMinTokens = value.advisorMinTokens
227
+ if (advisorMinTokens !== undefined
228
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
229
+ throw new TypeError('Context-compression presetOptions.advisorMinTokens must be a positive integer')
230
+ }
231
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
232
+ if (estimatorTimeoutMs !== undefined
233
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
234
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
235
+ throw new TypeError('Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000')
236
+ }
237
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
238
+ const entry = value[key]
239
+ if (entry !== undefined && typeof entry !== 'string') {
240
+ throw new TypeError(`Context-compression presetOptions.${key} must be a string`)
241
+ }
242
+ }
243
+ const result: {
244
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
245
+ } = {}
246
+ if (value.dedupeToolResults !== undefined) result.dedupeToolResults = value.dedupeToolResults as boolean
247
+ if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
248
+ if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
249
+ if (value.readState !== undefined) result.readState = value.readState as boolean
250
+ if (estimatorMode !== undefined) result.estimatorMode = estimatorMode
251
+ if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
252
+ if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
253
+ if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
254
+ if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
255
+ if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs
256
+ if (advisorMode !== undefined) result.advisorMode = advisorMode
257
+ if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs
258
+ if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns
259
+ if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold
260
+ if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit
261
+ if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens
262
+ return result
263
+ }
264
+
265
+ /** Settings schema used by the user-facing profile selector. */
266
+ const contextCompressionSettingsInputSchema = z.object({
267
+ profile: z.union([...COMPRESSION_PROFILES]).default('balanced'),
268
+ custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY),
269
+ })
270
+
271
+ /**
272
+ * Reject a section that is PRESENT but not a usable value. Schemastery
273
+ * `.default(...)` silently substitutes null and undefined, which would turn a
274
+ * hand-corrupted store into the (lossy) default policy; only genuinely absent
275
+ * keys may inherit defaults, and that distinction must be made before any
276
+ * default can fire.
277
+ */
278
+ function assertPresentSection(
279
+ candidate: Record<string, unknown>,
280
+ key: 'profile' | 'custom',
281
+ valid: (value: unknown) => boolean,
282
+ ): void {
283
+ if (!Object.hasOwn(candidate, key)) return
284
+ if (!valid(candidate[key])) {
285
+ throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`)
286
+ }
287
+ }
288
+
289
+ const isSupportedProfile = (value: unknown): boolean =>
290
+ typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
291
+
292
+ const isUsableCustomDocument = (value: unknown): boolean =>
293
+ isPlainRecord(value)
294
+
295
+ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
296
+ profile: 'balanced',
297
+ custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
298
+ autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
299
+ codeSkeleton: { enabled: false },
300
+ intentSummary: { enabled: false },
301
+ monitorPanel: { enabled: false },
302
+ }
303
+
304
+ /**
305
+ * Parse one settings document with the persisted-section semantics: `undefined`
306
+ * inherits the defaults (an absent section), while `null` is an explicitly
307
+ * invalid document and must never silently become the default policy.
308
+ */
309
+ export function parseContextCompressionSettings(value: unknown): ContextCompressionSettings {
310
+ if (!isPlainRecord(value)) {
311
+ throw new TypeError('Context-compression settings must be a plain object')
312
+ }
313
+ const keys = Object.keys(value)
314
+ // Documents surfaced by the settings service are always schema-resolved and
315
+ // complete; anything thinner is a hand-edited store and must not silently
316
+ // become a default (possibly lossy) policy.
317
+ if (keys.length === 0 || !keys.includes('profile') || !keys.includes('custom')) {
318
+ throw new TypeError('Context-compression settings document is missing its complete shape')
319
+ }
320
+ return ContextCompressionSettingsSchema(value as never)
321
+ }
322
+
323
+ /** Settings schema used by the user-facing profile selector. */
324
+ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z.transform(
325
+ z.any().required(),
326
+ (value: unknown): ContextCompressionSettings => {
327
+ if (!isPlainRecord(value)) {
328
+ throw new TypeError('Context-compression settings must be a plain object')
329
+ }
330
+ // Validate prototypes before cloning, then parse a detached mutable copy:
331
+ // SettingsProvider returns frozen records, while structuredClone would
332
+ // otherwise erase exotic prototypes before this boundary can reject them.
333
+ assertPlainDataTree(value)
334
+ const candidate = structuredClone(value)
335
+ // Settings stored before the autoCompact or codeSkeleton sections existed
336
+ // remain valid and inherit their defaults; the sections themselves stay
337
+ // strictly shaped.
338
+ const unknown = Object.keys(candidate).find(key =>
339
+ key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
340
+ if (unknown !== undefined) {
341
+ throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
342
+ }
343
+ // Present-but-invalid sections must never fall through to the Schemastery
344
+ // defaults below: `profile: null` silently becoming the lossy `balanced`
345
+ // default is exactly the corruption the lossless-off fallback exists for.
346
+ // Only genuinely absent sections (internal partial fallbacks) may inherit.
347
+ assertPresentSection(candidate, 'profile', isSupportedProfile)
348
+ assertPresentSection(candidate, 'custom', isUsableCustomDocument)
349
+ const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
350
+ const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
351
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
352
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
353
+ const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
354
+ return {
355
+ ...contextCompressionSettingsInputSchema(candidate),
356
+ autoCompact,
357
+ codeSkeleton,
358
+ intentSummary,
359
+ monitorPanel,
360
+ ...presetOptions === undefined ? {} : { presetOptions },
361
+ }
362
+ },
363
+ ).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS) as z<ContextCompressionSettings>
364
+
365
+ /** Low-friction defaults; token budgets live in resolved profile policy. */
366
+ export const DEFAULTS: ResolvedConfig = deepFreeze({
367
+ profile: 'balanced',
368
+ headChars: 4096,
369
+ tailChars: 1024,
370
+ })
371
+
372
+ const CONFIG_KEYS: ReadonlySet<string> = new Set([
373
+ 'profile',
374
+ 'headChars',
375
+ 'tailChars',
376
+ 'nativeTriggerTokens',
377
+ 'nativeTargetTokens',
378
+ 'freshTriggerTokens',
379
+ 'freshTargetTokens',
380
+ 'aggregateTriggerTokens',
381
+ 'aggregateTargetTokens',
382
+ 'historyTriggerTokens',
383
+ 'historyKeepRecentToolCalls',
384
+ 'historyKeepRecentTokens',
385
+ 'historyMinReclaimTokens',
386
+ 'readInputCapChars',
387
+ 'autoCompactThresholdPercent',
388
+ 'presetOptions',
389
+ ])
390
+
391
+ const LEGACY_GATE_REPLACEMENTS: Readonly<Record<string, string>> = Object.freeze({
392
+ thresholdChars: 'nativeTriggerTokens',
393
+ freshThresholdChars: 'freshTriggerTokens',
394
+ freshTargetChars: 'freshTargetTokens',
395
+ freshBatchTriggerChars: 'aggregateTriggerTokens',
396
+ freshBatchTargetChars: 'aggregateTargetTokens',
397
+ historyTriggerChars: 'historyTriggerTokens',
398
+ historyKeepRecentChars: 'historyKeepRecentTokens',
399
+ historyMinReclaimChars: 'historyMinReclaimTokens',
400
+ historyKeepRecentTurns: 'historyKeepRecentToolCalls',
401
+ })
402
+
403
+ /**
404
+ * Count Unicode code points without splitting surrogate pairs.
405
+ * @param text - text whose code points are counted.
406
+ * @returns the number of Unicode code points.
407
+ */
408
+ export function codePointLength(text: string): number {
409
+ let length = 0
410
+ for (const _point of text) length++
411
+ return length
412
+ }
413
+
414
+ /**
415
+ * Conservative upper bound on characters per token. Same convention the
416
+ * readInputCapChars invariant already uses (see resolvePolicy): English
417
+ * code runs approximately four characters per token at the upper bound.
418
+ */
419
+ export const CHARS_PER_TOKEN = 4.0
420
+
421
+ /** Express one token-named policy gate on the character basis. */
422
+ export function charsForTokens(tokens: number): number {
423
+ return tokens * CHARS_PER_TOKEN
424
+ }
425
+
426
+ /** Derive the telemetry-only token figure from a character measurement. */
427
+ export function charsToTokens(chars: number): number {
428
+ if (!Number.isFinite(chars) || chars <= 0) return 0
429
+ return Math.max(1, Math.round(chars / CHARS_PER_TOKEN))
430
+ }
431
+
432
+ /**
433
+ * Test whether a settings value names a supported compression profile.
434
+ * @param value - untrusted settings value.
435
+ * @returns whether the value is a supported compression profile.
436
+ */
437
+ export function isCompressionProfile(value: unknown): value is CompressionProfile {
438
+ return typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
439
+ }
440
+
441
+ /**
442
+ * Resolve and validate plugin configuration.
443
+ * @param config - optional composition overrides.
444
+ * @returns a detached, deeply immutable configuration snapshot.
445
+ */
446
+ export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfig {
447
+ for (const key of Object.keys(config)) {
448
+ const replacement = LEGACY_GATE_REPLACEMENTS[key]
449
+ if (replacement !== undefined) {
450
+ throw new Error(
451
+ `ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; `
452
+ + `choose "${replacement}" manually in tokens (no character conversion is applied)`,
453
+ )
454
+ }
455
+ if (!CONFIG_KEYS.has(key)) {
456
+ throw new Error(`ToolResultPruneConfig: unknown key "${key}"`)
457
+ }
458
+ }
459
+ const resolved: ResolvedConfig = {
460
+ profile: config.profile ?? DEFAULTS.profile,
461
+ headChars: config.headChars ?? DEFAULTS.headChars,
462
+ tailChars: config.tailChars ?? DEFAULTS.tailChars,
463
+ ...config.nativeTriggerTokens === undefined ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
464
+ ...config.nativeTargetTokens === undefined ? {} : { nativeTargetTokens: config.nativeTargetTokens },
465
+ ...config.freshTriggerTokens === undefined ? {} : { freshTriggerTokens: config.freshTriggerTokens },
466
+ ...config.freshTargetTokens === undefined ? {} : { freshTargetTokens: config.freshTargetTokens },
467
+ ...config.aggregateTriggerTokens === undefined ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
468
+ ...config.aggregateTargetTokens === undefined ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
469
+ ...config.historyTriggerTokens === undefined ? {} : { historyTriggerTokens: config.historyTriggerTokens },
470
+ ...config.historyKeepRecentToolCalls === undefined ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
471
+ ...config.historyKeepRecentTokens === undefined ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
472
+ ...config.historyMinReclaimTokens === undefined ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
473
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
474
+ ...config.autoCompactThresholdPercent === undefined ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
475
+ ...config.presetOptions === undefined ? {} : { presetOptions: config.presetOptions },
476
+ }
477
+ if (!isCompressionProfile(resolved.profile)) {
478
+ throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`)
479
+ }
480
+ assertNonNegativeInteger('headChars', resolved.headChars)
481
+ assertNonNegativeInteger('tailChars', resolved.tailChars)
482
+ for (const key of [
483
+ 'nativeTriggerTokens', 'nativeTargetTokens', 'freshTriggerTokens', 'freshTargetTokens',
484
+ 'aggregateTriggerTokens', 'aggregateTargetTokens', 'historyTriggerTokens',
485
+ 'historyMinReclaimTokens', 'readInputCapChars',
486
+ ] as const) {
487
+ const value = resolved[key]
488
+ if (value !== undefined) assertPositiveInteger(key, value)
489
+ }
490
+ if (resolved.historyKeepRecentToolCalls !== undefined) {
491
+ assertNonNegativeInteger('historyKeepRecentToolCalls', resolved.historyKeepRecentToolCalls)
492
+ }
493
+ if (resolved.historyKeepRecentTokens !== undefined) {
494
+ assertNonNegativeInteger('historyKeepRecentTokens', resolved.historyKeepRecentTokens)
495
+ }
496
+ if (resolved.autoCompactThresholdPercent !== undefined
497
+ && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) {
498
+ 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)}`)
499
+ }
500
+ assertTargetBelowTrigger('native', resolved.nativeTargetTokens, resolved.nativeTriggerTokens)
501
+ assertTargetBelowTrigger('fresh', resolved.freshTargetTokens, resolved.freshTriggerTokens)
502
+ assertTargetBelowTrigger('aggregate', resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens)
503
+ return deepFreeze(structuredClone(resolved))
504
+ }
505
+
506
+ /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
507
+ const AUTO_COMPACT_HISTORY_RATIOS: Readonly<Record<string, Readonly<{
508
+ trigger: number
509
+ minReclaim: number
510
+ keepRecentTokens: number
511
+ }>>> = Object.freeze({
512
+ balanced: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
513
+ savings: Object.freeze({ trigger: 0.50, minReclaim: 0.16, keepRecentTokens: 0.08 }),
514
+ 'cache-strict': Object.freeze({ trigger: 0.75, minReclaim: 0.16, keepRecentTokens: 0.08 }),
515
+ adaptive: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
516
+ 'tokenpilot-inspired': Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
517
+ })
518
+
519
+ /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
520
+ const MICRO_DEADLINE_RATIO = 0.875
521
+
522
+ /**
523
+ * TokenPilot-inspired sub-capability defaults. Every capability is on except
524
+ * the estimator, which requires an explicit endpoint channel (host or direct)
525
+ * before any consumer may leave its rule-only fallback.
526
+ */
527
+ const PRESET_OPTION_DEFAULTS: PresetOptions = deepFreeze({
528
+ noNetSavingsGuard: true,
529
+ skipReductionRecovery: true,
530
+ dedupeToolResults: true,
531
+ summaryLocator: true,
532
+ prefixStabilizer: true,
533
+ readState: true,
534
+ estimator: { mode: '' },
535
+ // Advisory advisor ships off: statistics and suggestions only, never a gate.
536
+ advisor: {
537
+ mode: '',
538
+ timeoutMs: 8_000,
539
+ refreshTurns: 8,
540
+ scoreThreshold: 0.35,
541
+ sampleLimit: 16,
542
+ minTokens: 250,
543
+ },
544
+ })
545
+
546
+ /**
547
+ * Merge persisted presetOptions overrides over the tokenpilot-inspired
548
+ * defaults. Persisted booleans are three-state (undefined = inherit); the
549
+ * estimator channel overrides the default empty mode wholesale.
550
+ */
551
+ function mergePresetOptions(overrides: PresetOptionsSettings | undefined): PresetOptions {
552
+ if (overrides === undefined) return PRESET_OPTION_DEFAULTS
553
+ return deepFreeze({
554
+ noNetSavingsGuard: true,
555
+ skipReductionRecovery: true,
556
+ dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
557
+ summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
558
+ prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
559
+ readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
560
+ estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
561
+ advisor: {
562
+ mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
563
+ timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
564
+ refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
565
+ scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
566
+ sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
567
+ minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens,
568
+ },
569
+ })
570
+ }
571
+
572
+ /**
573
+ * Resolve the Auto-Compact-linked History watermarks for one standard profile.
574
+ *
575
+ * `A = floor(C × a)` is the Auto Compact token watermark for the routed
576
+ * context window `C` and the user threshold `a = p / 100`; the History
577
+ * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
578
+ * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
579
+ * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
580
+ * preset numbers exactly. Custom stays manual and Off/Native run no History,
581
+ * so none of them link.
582
+ */
583
+ function resolveAutoCompactLinkage(
584
+ profile: CompressionProfile,
585
+ options: CustomPolicyResolutionOptions,
586
+ ): { autoCompactTokens: number, microDeadlineTokens: number, historyTriggerTokens: number,
587
+ historyMinReclaimTokens: number, historyKeepRecentTokens: number } | undefined {
588
+ const ratios = profile === 'custom' ? undefined : AUTO_COMPACT_HISTORY_RATIOS[profile]
589
+ const contextWindow = options.contextWindowTokens
590
+ const threshold = options.autoCompactThresholdPercent
591
+ if (ratios === undefined) return undefined
592
+ if (!isValidAutoCompactThresholdPercent(threshold)) return undefined
593
+ if (!Number.isSafeInteger(contextWindow) || contextWindow === undefined || contextWindow <= 0) return undefined
594
+ // Mirror compaction-basic's evaluation order exactly: it multiplies by the
595
+ // generated ratio float (p / 100), and integer-first division differs by
596
+ // one token on some window/percent pairs (200k x 57).
597
+ const autoCompactTokens = Math.floor(contextWindow * (threshold / 100))
598
+ if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return undefined
599
+ const linked = {
600
+ autoCompactTokens,
601
+ microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
602
+ historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
603
+ historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
604
+ historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens),
605
+ }
606
+ for (const value of Object.values(linked)) {
607
+ if (!Number.isSafeInteger(value) || value <= 0) return undefined
608
+ }
609
+ return linked
610
+ }
611
+
612
+ /**
613
+ * Resolve one public profile into a complete mixed-strategy policy.
614
+ * @param config - validated composition configuration.
615
+ * @param profile - profile frozen for the target Session.
616
+ * @param custom - versioned Custom document used only by the `custom` profile.
617
+ * @param options - routed capacity and the frozen Auto Compact threshold used
618
+ * to resolve context-percent Custom values and standard-profile linkage.
619
+ * @returns the effective deterministic compression policy.
620
+ */
621
+ export function resolvePolicy(
622
+ config: ResolvedConfig,
623
+ profile: CompressionProfile,
624
+ custom: CustomCompressionPolicy = DEFAULT_CUSTOM_COMPRESSION_POLICY,
625
+ options: CustomPolicyResolutionOptions = {},
626
+ ): CompressionPolicy {
627
+ if (profile === 'custom') return resolveCustomPolicy(custom, options)
628
+ const presets: Record<Exclude<CompressionProfile, 'custom'>, Omit<CompressionPolicy, 'profile'>> = {
629
+ off: {
630
+ nativeToolResultEnabled: false, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
631
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
632
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
633
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
634
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
635
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
636
+ },
637
+ native: {
638
+ nativeToolResultEnabled: true, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
639
+ nativeTriggerTokens: 4_096, nativeTargetTokens: 2_048,
640
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
641
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
642
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
643
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
644
+ },
645
+ balanced: {
646
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
647
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
648
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
649
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
650
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
651
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
652
+ },
653
+ 'cache-strict': {
654
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'capacity-pressure',
655
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
656
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
657
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
658
+ historyTriggerTokens: 600_000, historyKeepRecentToolCalls: 10,
659
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
660
+ },
661
+ savings: {
662
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
663
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
664
+ freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
665
+ aggregateTriggerTokens: 16_384, aggregateTargetTokens: 4_096,
666
+ historyTriggerTokens: 400_000, historyKeepRecentToolCalls: 10,
667
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
668
+ },
669
+ adaptive: {
670
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'adaptive',
671
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
672
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
673
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
674
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
675
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
676
+ },
677
+ 'tokenpilot-inspired': {
678
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
679
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
680
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
681
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
682
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
683
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
684
+ },
685
+ }
686
+ const preset = presets[profile]
687
+ const linkage = resolveAutoCompactLinkage(profile, options)
688
+ const policy: CompressionPolicy = {
689
+ profile,
690
+ ...preset,
691
+ nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
692
+ nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
693
+ freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
694
+ freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
695
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
696
+ aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
697
+ historyTriggerTokens: config.historyTriggerTokens
698
+ ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
699
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
700
+ historyKeepRecentTokens: config.historyKeepRecentTokens
701
+ ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
702
+ historyMinReclaimTokens: config.historyMinReclaimTokens
703
+ ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
704
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
705
+ ...linkage === undefined ? {} : {
706
+ autoCompactTokens: linkage.autoCompactTokens,
707
+ microDeadlineTokens: linkage.microDeadlineTokens,
708
+ },
709
+ ...profile === 'tokenpilot-inspired' ? {
710
+ presetOptions: mergePresetOptions(config.presetOptions),
711
+ } : {},
712
+ }
713
+ if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === 'native') {
714
+ throw new Error('context compression policy: native target must be below trigger')
715
+ }
716
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
717
+ throw new Error('context compression policy: fresh target must be below trigger')
718
+ }
719
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) {
720
+ throw new Error('context compression policy: aggregate target must be below trigger')
721
+ }
722
+ // G2 invariant: the fresh trigger is in TOKENS while a read input cap is in
723
+ // CHARACTERS. English code runs ≈4.0 chars/token at the conservative upper
724
+ // bound, so a cap at or below `freshTriggerTokens × 4.0` would truncate every
725
+ // read result below the trigger and silently silence the fresh path.
726
+ if (policy.readInputCapChars !== undefined
727
+ && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
728
+ throw new Error('context compression policy: read input cap would silence the fresh path')
729
+ }
730
+ return deepFreeze(policy)
731
+ }
732
+
733
+ function assertTargetBelowTrigger(
734
+ label: string,
735
+ target: number | undefined,
736
+ trigger: number | undefined,
737
+ ): void {
738
+ if ((target === undefined) !== (trigger === undefined)) {
739
+ throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`)
740
+ }
741
+ if (target !== undefined && trigger !== undefined && target >= trigger) {
742
+ throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`)
743
+ }
744
+ }
745
+
746
+ function assertPositiveInteger(name: string, value: number): void {
747
+ if (!Number.isSafeInteger(value) || value <= 0) {
748
+ throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`)
749
+ }
750
+ }
751
+
752
+ function assertNonNegativeInteger(name: string, value: number): void {
753
+ if (!Number.isSafeInteger(value) || value < 0) {
754
+ throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`)
755
+ }
756
+ }