dsh-context-compression-improved 0.2.4 → 0.2.5

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