dsh-context-compression-improved 0.8.0-beta.3 → 0.8.0-beta.4

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