dsh-context-compression-improved 0.5.5 → 0.5.7

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 (162) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +314 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -85
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +164 -160
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -21
  26. package/packages/selector/README.zh.md +24 -19
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.js +733 -0
  34. package/packages/selector/lib/style.css +46 -46
  35. package/packages/selector/package.json +114 -114
  36. package/packages/selector/screenshots.json +3 -3
  37. package/packages/selector/src/client/CompressionProfileControls.tsx +226 -226
  38. package/packages/selector/src/client/CompressionProfileSelector.module.css +170 -170
  39. package/packages/selector/src/client/CompressionProfileSelector.tsx +83 -83
  40. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  41. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  42. package/packages/selector/src/client/decode.ts +49 -49
  43. package/packages/selector/src/client/index.ts +178 -149
  44. package/packages/selector/src/client/locales/de.ts +98 -0
  45. package/packages/selector/src/client/locales/es.ts +98 -0
  46. package/packages/selector/src/client/locales/fr.ts +98 -0
  47. package/packages/selector/src/client/locales/it.ts +98 -0
  48. package/packages/selector/src/client/locales/ja.ts +98 -0
  49. package/packages/selector/src/client/locales/ko.ts +98 -0
  50. package/packages/selector/src/client/locales/ru.ts +98 -0
  51. package/packages/selector/src/client/locales.ts +196 -196
  52. package/packages/selector/src/client/preset-options.ts +88 -88
  53. package/packages/selector/src/client/settings-section.tsx +124 -124
  54. package/packages/selector/src/css-modules.d.ts +6 -6
  55. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  56. package/packages/selector/src/estimator-catalog.ts +104 -104
  57. package/packages/selector/src/index.ts +463 -463
  58. package/packages/selector/src/invariant.ts +113 -113
  59. package/packages/selector/src/preset-overlay.ts +626 -626
  60. package/packages/selector/src/profiles.ts +394 -394
  61. package/packages/selector/src/pruner/content.ts +201 -201
  62. package/packages/selector/src/pruner/session.ts +94 -94
  63. package/packages/selector/src/pruner/state.ts +50 -50
  64. package/packages/selector/src/pruner/tuning.ts +23 -23
  65. package/packages/selector/src/pruner/types.ts +78 -78
  66. package/packages/selector/src/pruner.ts +2402 -2402
  67. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  68. package/packages/selector/src/runtime/audit.ts +286 -286
  69. package/packages/selector/src/runtime/config.ts +706 -706
  70. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  71. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  72. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  73. package/packages/selector/src/runtime/measurement.ts +436 -436
  74. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  75. package/packages/selector/src/runtime/retrieve.ts +457 -457
  76. package/packages/selector/src/runtime/session-events.ts +30 -30
  77. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  78. package/packages/selector/src/runtime/token-count.ts +72 -72
  79. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  80. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  81. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  82. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  83. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  84. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  85. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  86. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  87. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  88. package/packages/selector/src/runtime/toolclass.ts +103 -103
  89. package/packages/selector/src/runtime/types.ts +346 -346
  90. package/packages/selector/src/runtime/value.ts +48 -48
  91. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  92. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -213
  93. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  94. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +90 -90
  96. package/packages/selector/tests/custom-contract.client.spec.ts +204 -204
  97. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  98. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  99. package/packages/selector/tests/estimator-route-registration.host.spec.ts +188 -188
  100. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +206 -206
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  104. package/packages/selector/tests/profiles.client.spec.tsx +434 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  110. package/packages/selector/tests/runtime/audit.spec.ts +274 -274
  111. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  112. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  113. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  114. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  115. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  116. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  117. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  118. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  119. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  120. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  121. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  122. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  123. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  124. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  125. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  126. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  127. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  128. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  129. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  130. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  131. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  132. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  133. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  134. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  135. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  136. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  137. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  138. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  139. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  140. package/packages/selector/tests/settings-seat.client.spec.ts +118 -118
  141. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  142. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  143. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  144. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  145. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  146. package/packages/selector/tsconfig.json +11 -11
  147. package/packages/selector/tsdown.client.config.ts +102 -102
  148. package/packages/selector/tsdown.config.ts +20 -20
  149. package/pnpm-workspace.yaml +66 -66
  150. package/scripts/capture-profile-baseline.mjs +42 -42
  151. package/scripts/generate-tokenizer-fixtures.py +81 -81
  152. package/scripts/generate-vision-fixtures.py +208 -208
  153. package/scripts/packed-components-smoke.mjs +732 -732
  154. package/scripts/packed-install-e2e.mjs +1273 -1273
  155. package/scripts/toolclass-corpus-replay.mjs +281 -281
  156. package/scripts/verify-release.mjs +317 -317
  157. package/tests/TEST_INVENTORY.md +41 -41
  158. package/tsconfig.base.json +18 -18
  159. package/tsconfig.json +7 -7
  160. package/tsconfig.tests.json +15 -15
  161. package/vitest.built.config.ts +9 -9
  162. package/vitest.config.ts +43 -43
@@ -1,706 +1,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
- 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
- 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
+ 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
+ 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
+ }