dsh-context-compression-improved 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,342 +1,431 @@
1
- /** Public context-compression choices shared by the Host schema and browser selector. */
2
- export const COMPRESSION_PROFILES = [
3
- 'off',
4
- 'native',
5
- 'balanced',
6
- 'cache-strict',
7
- 'savings',
8
- 'adaptive',
9
- 'tokenpilot-inspired',
10
- 'custom',
11
- ] as const
12
-
13
- /** One supported context-compression profile. */
14
- export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
15
-
16
- /** Single canonical unit stored by a version-1 browser Custom document. */
17
- export type CustomCompressionUnit = 'tokens' | 'context-percent'
18
-
19
- /** Whether Custom History may routinely rewrite an already-sent prefix. */
20
- export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
21
-
22
- /** Browser representation of one independently enabled Fresh or Aggregate budget. */
23
- export interface CustomCompressionBudget {
24
- enabled: boolean
25
- trigger: number
26
- target: number
27
- }
28
-
29
- /** Legacy browser representation of the Custom History working set. */
30
- export interface LegacyCustomHistoryPolicy {
31
- enabled: boolean
32
- trigger: number
33
- keepRecentTurns: number
34
- keepRecent: number
35
- minReclaim: number
36
- }
37
-
38
- /** Browser representation of Custom History tool-call and token-tail protection. */
39
- export interface CustomHistoryPolicy {
40
- enabled: boolean
41
- trigger: number
42
- keepRecentToolCalls: number
43
- keepRecentTokens: number
44
- minReclaim: number
45
- }
46
-
47
- /** Browser representation of the Custom-only Experimental TailTrim gate. */
48
- export interface CustomTailTrimPolicy {
49
- enabled: boolean
50
- trigger: number
51
- }
52
-
53
- interface CustomCompressionPolicyCommon<HistoryPolicy> {
54
- unit: CustomCompressionUnit
55
- fresh: CustomCompressionBudget
56
- aggregate: CustomCompressionBudget
57
- history: HistoryPolicy
58
- prefixPolicy: CustomPrefixPolicy
59
- }
60
-
61
- /** Legacy public Custom document; accepted and normalized before editing. */
62
- export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
63
- version: 1
64
- }
65
-
66
- /** Legacy Custom document with a default-disabled TailTrim stage. */
67
- export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
68
- version: 2
69
- tailTrim: CustomTailTrimPolicy
70
- }
71
-
72
- /** Public Custom document with tool-call working-set protection. */
73
- export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
74
- version: 3
75
- tailTrim: CustomTailTrimPolicy
76
- }
77
-
78
- /** Exact public Custom document accepted by the Host and browser boundary. */
79
- export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
80
-
81
- /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
82
- export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
83
- version: 3,
84
- unit: 'tokens',
85
- fresh: { enabled: true, trigger: 8_192, target: 3_072 },
86
- aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
87
- history: {
88
- enabled: true,
89
- trigger: 500_000,
90
- keepRecentToolCalls: 10,
91
- keepRecentTokens: 64_000,
92
- minReclaim: 96_000,
93
- },
94
- prefixPolicy: 'pressure-break',
95
- tailTrim: { enabled: false, trigger: 700_000 },
96
- }
97
-
98
- /** User-tunable Auto Compact coordination preferences. */
99
- export interface AutoCompactSettings {
100
- thresholdPercent: number
101
- }
102
-
103
- /**
104
- * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
105
- * runtime: independent of every profile, default off.
106
- */
107
- export interface CodeSkeletonSettings {
108
- enabled: boolean
109
- }
110
-
111
- /**
112
- * Decode the persisted codeSkeleton section with exactly the runtime schema's
113
- * strictness: absent means the lossless off default; present values must be a
114
- * plain object carrying only a boolean `enabled`. Anything else is invalid,
115
- * never silently coerced.
116
- */
117
- export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
118
- if (value === undefined) return { enabled: false }
119
- if (!isPlainRecord(value)) return undefined
120
- const keys = Object.keys(value)
121
- if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
122
- const enabled = (value as Record<string, unknown>).enabled
123
- return typeof enabled === 'boolean' ? { enabled } : undefined
124
- }
125
-
126
- /** Browser-safe mirror of the runtime presetOptions section. */
127
- export interface PresetOptionsSettings {
128
- readonly dedupeToolResults?: boolean
129
- readonly summaryLocator?: boolean
130
- readonly prefixStabilizer?: boolean
131
- readonly readState?: boolean
132
- readonly estimatorMode?: '' | 'host' | 'direct'
133
- readonly estimatorProvider?: string
134
- readonly estimatorModel?: string
135
- readonly estimatorBaseUrl?: string
136
- readonly estimatorApiKey?: string
137
- readonly estimatorTimeoutMs?: number
138
- }
139
-
140
- /**
141
- * Browser mirror of the runtime presetOptions section: absent inherits the
142
- * preset defaults (decodes to `undefined`); present values must be a plain
143
- * object carrying only the known keys with valid types.
144
- */
145
- export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
146
- if (value === undefined) return undefined
147
- if (!isPlainRecord(value)) return undefined
148
- const allowed = new Set([
149
- 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
150
- 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
151
- ])
152
- if (Object.keys(value).some(key => !allowed.has(key))) return undefined
153
- for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
154
- const entry = value[key]
155
- if (entry !== undefined && typeof entry !== 'boolean') return undefined
156
- }
157
- const estimatorMode = value.estimatorMode
158
- if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
159
- return undefined
160
- }
161
- for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
162
- const entry = value[key]
163
- if (entry !== undefined && typeof entry !== 'string') return undefined
164
- }
165
- const estimatorTimeoutMs = value.estimatorTimeoutMs
166
- if (estimatorTimeoutMs !== undefined
167
- && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
168
- || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
169
- return undefined
170
- }
171
- const decoded: {
172
- -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
173
- } = {}
174
- if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
175
- if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
176
- if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
177
- if (value.readState !== undefined) decoded.readState = value.readState as boolean
178
- if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
179
- if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
180
- if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
181
- if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
182
- if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
183
- if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
184
- return decoded
185
- }
186
-
187
- /**
188
- * The one threshold contract shared by the UI, the persisted settings, and the
189
- * runtime resolver; mirrored browser-safe from the runtime package.
190
- */
191
- export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
192
- min: 50,
193
- max: 90,
194
- step: 1,
195
- default: 80,
196
- } as const)
197
-
198
- /** Narrow one unknown value to a valid Auto Compact threshold percent. */
199
- export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
200
- return typeof value === 'number'
201
- && Number.isSafeInteger(value)
202
- && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
203
- && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
204
- }
205
-
206
- /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
207
- export function isPlainRecord(value: unknown): value is Record<string, unknown> {
208
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
209
- const prototype = Object.getPrototypeOf(value) as object | null
210
- return prototype === Object.prototype || prototype === null
211
- }
212
-
213
- /**
214
- * Decode the persisted autoCompact section with exactly the runtime schema's
215
- * strictness: absent means the 80% default; present values must be a plain
216
- * object carrying only a valid `thresholdPercent`. Anything else is invalid,
217
- * never silently coerced.
218
- */
219
- export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
220
- if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
221
- if (!isPlainRecord(value)) return undefined
222
- const keys = Object.keys(value)
223
- if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
224
- const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
225
- return isValidAutoCompactThresholdPercent(thresholdPercent)
226
- ? { thresholdPercent }
227
- : undefined
228
- }
229
-
230
- /** Durable settings section owned by this package. */
231
- export interface ContextCompressionSettings {
232
- /** Default profile captured when each Session first reaches the pruner. */
233
- profile: CompressionProfile
234
- /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
235
- custom: CustomCompressionPolicy
236
- /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
237
- autoCompact: AutoCompactSettings
238
- /** Code-skeleton reducer gate captured independently of `profile`. */
239
- codeSkeleton: CodeSkeletonSettings
240
- /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
241
- presetOptions?: PresetOptionsSettings
242
- }
243
-
244
- /**
245
- * Narrow an unknown settings value to a complete supported Custom policy.
246
- * @param value - Candidate settings value received from the Host or edited locally.
247
- * @returns Whether the value is a relation-valid Custom policy.
248
- */
249
- export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
250
- if (!hasExactKeys(
251
- value,
252
- value !== null && typeof value === 'object' && 'version' in value && value.version === 1
253
- ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
254
- : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
255
- )) return false
256
- if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
257
- || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
258
- if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
259
- if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
260
- const modernHistory = value.version === 3
261
- if (!hasExactKeys(
262
- value.history,
263
- modernHistory
264
- ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
265
- : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
266
- )) return false
267
- if (typeof value.history.enabled !== 'boolean'
268
- || typeof value.history.trigger !== 'number'
269
- || typeof value.history.minReclaim !== 'number') return false
270
- const recent = modernHistory
271
- ? value.history.keepRecentTokens
272
- : value.history.keepRecent
273
- const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
274
- if (typeof recent !== 'number'
275
- || typeof calls !== 'number'
276
- || !Number.isSafeInteger(calls)
277
- || calls < 0) return false
278
- let tailTrimTrigger: number | undefined
279
- if (value.version !== 1) {
280
- const tailTrim = value.tailTrim
281
- if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
282
- || typeof tailTrim.enabled !== 'boolean'
283
- || typeof tailTrim.trigger !== 'number') return false
284
- tailTrimTrigger = tailTrim.trigger
285
- }
286
- const measured = [
287
- value.fresh.trigger, value.fresh.target,
288
- value.aggregate.trigger, value.aggregate.target,
289
- value.history.trigger, recent, value.history.minReclaim,
290
- ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
291
- ]
292
- if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
293
- if (value.fresh.trigger <= 0 || value.fresh.target <= 0
294
- || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
295
- || value.history.trigger <= 0 || recent < 0
296
- || value.history.minReclaim <= 0
297
- || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
298
- if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
299
- if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
300
- return value.fresh.target < value.fresh.trigger
301
- && value.aggregate.target < value.aggregate.trigger
302
- && value.history.minReclaim <= value.history.trigger
303
- }
304
-
305
- function isBudget(value: unknown): value is CustomCompressionBudget {
306
- return hasExactKeys(value, ['enabled', 'trigger', 'target'])
307
- && typeof value.enabled === 'boolean'
308
- && typeof value.trigger === 'number'
309
- && typeof value.target === 'number'
310
- }
311
-
312
- /**
313
- * Canonicalize one validated Custom document to version 3, mirroring the
314
- * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
315
- * boundaries hand the SAME complete document to the UI and the policy
316
- * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
317
- * and a v1 document gains the default-disabled TailTrim stage.
318
- */
319
- export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
320
- if (policy.version === 3) return structuredClone(policy)
321
- return {
322
- version: 3,
323
- unit: policy.unit,
324
- fresh: structuredClone(policy.fresh),
325
- aggregate: structuredClone(policy.aggregate),
326
- history: {
327
- enabled: policy.history.enabled,
328
- trigger: policy.history.trigger,
329
- keepRecentToolCalls: 10,
330
- keepRecentTokens: policy.history.keepRecent,
331
- minReclaim: policy.history.minReclaim,
332
- },
333
- prefixPolicy: policy.prefixPolicy,
334
- tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
335
- }
336
- }
337
-
338
- function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
339
- if (!isPlainRecord(value)) return false
340
- const keys = Object.keys(value)
341
- return keys.length === expected.length && keys.every(key => expected.includes(key))
342
- }
1
+ /** Public context-compression choices shared by the Host schema and browser selector. */
2
+ export const COMPRESSION_PROFILES = [
3
+ 'off',
4
+ 'native',
5
+ 'balanced',
6
+ 'cache-strict',
7
+ 'savings',
8
+ 'adaptive',
9
+ 'tokenpilot-inspired',
10
+ 'custom',
11
+ ] as const
12
+
13
+ /** One supported context-compression profile. */
14
+ export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
15
+
16
+ /** Single canonical unit stored by a version-1 browser Custom document. */
17
+ export type CustomCompressionUnit = 'tokens' | 'context-percent'
18
+
19
+ /** Whether Custom History may routinely rewrite an already-sent prefix. */
20
+ export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
21
+
22
+ /** Browser representation of one independently enabled Fresh or Aggregate budget. */
23
+ export interface CustomCompressionBudget {
24
+ enabled: boolean
25
+ trigger: number
26
+ target: number
27
+ }
28
+
29
+ /** Legacy browser representation of the Custom History working set. */
30
+ export interface LegacyCustomHistoryPolicy {
31
+ enabled: boolean
32
+ trigger: number
33
+ keepRecentTurns: number
34
+ keepRecent: number
35
+ minReclaim: number
36
+ }
37
+
38
+ /** Browser representation of Custom History tool-call and token-tail protection. */
39
+ export interface CustomHistoryPolicy {
40
+ enabled: boolean
41
+ trigger: number
42
+ keepRecentToolCalls: number
43
+ keepRecentTokens: number
44
+ minReclaim: number
45
+ }
46
+
47
+ /** Browser representation of the Custom-only Experimental TailTrim gate. */
48
+ export interface CustomTailTrimPolicy {
49
+ enabled: boolean
50
+ trigger: number
51
+ }
52
+
53
+ interface CustomCompressionPolicyCommon<HistoryPolicy> {
54
+ unit: CustomCompressionUnit
55
+ fresh: CustomCompressionBudget
56
+ aggregate: CustomCompressionBudget
57
+ history: HistoryPolicy
58
+ prefixPolicy: CustomPrefixPolicy
59
+ }
60
+
61
+ /** Legacy public Custom document; accepted and normalized before editing. */
62
+ export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
63
+ version: 1
64
+ }
65
+
66
+ /** Legacy Custom document with a default-disabled TailTrim stage. */
67
+ export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
68
+ version: 2
69
+ tailTrim: CustomTailTrimPolicy
70
+ }
71
+
72
+ /** Public Custom document with tool-call working-set protection. */
73
+ export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
74
+ version: 3
75
+ tailTrim: CustomTailTrimPolicy
76
+ }
77
+
78
+ /** Exact public Custom document accepted by the Host and browser boundary. */
79
+ export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
80
+
81
+ /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
82
+ export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
83
+ version: 3,
84
+ unit: 'tokens',
85
+ fresh: { enabled: true, trigger: 8_192, target: 3_072 },
86
+ aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
87
+ history: {
88
+ enabled: true,
89
+ trigger: 500_000,
90
+ keepRecentToolCalls: 10,
91
+ keepRecentTokens: 64_000,
92
+ minReclaim: 96_000,
93
+ },
94
+ prefixPolicy: 'pressure-break',
95
+ tailTrim: { enabled: false, trigger: 700_000 },
96
+ }
97
+
98
+ /** User-tunable Auto Compact coordination preferences. */
99
+ export interface AutoCompactSettings {
100
+ thresholdPercent: number
101
+ }
102
+
103
+ /**
104
+ * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
105
+ * runtime: independent of every profile, default off.
106
+ */
107
+ export interface CodeSkeletonSettings {
108
+ enabled: boolean
109
+ }
110
+
111
+ /**
112
+ * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
113
+ * runtime: independent of every profile, default off.
114
+ */
115
+ export interface IntentSummarySettings {
116
+ enabled: boolean
117
+ }
118
+
119
+ /** Floating compression-monitor panel (FAB); visibility switch. */
120
+ export interface MonitorPanelSettings {
121
+ enabled: boolean
122
+ }
123
+
124
+ /**
125
+ * Decode the persisted codeSkeleton section with exactly the runtime schema's
126
+ * strictness: absent means the lossless off default; present values must be a
127
+ * plain object carrying only a boolean `enabled`. Anything else is invalid,
128
+ * never silently coerced.
129
+ */
130
+ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
131
+ if (value === undefined) return { enabled: false }
132
+ if (!isPlainRecord(value)) return undefined
133
+ const keys = Object.keys(value)
134
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
135
+ const enabled = (value as Record<string, unknown>).enabled
136
+ return typeof enabled === 'boolean' ? { enabled } : undefined
137
+ }
138
+
139
+ /** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
140
+ export function decodeIntentSummarySettings(value: unknown): IntentSummarySettings | undefined {
141
+ if (value === undefined) return { enabled: false }
142
+ if (!isPlainRecord(value)) return undefined
143
+ const keys = Object.keys(value)
144
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
145
+ const enabled = (value as Record<string, unknown>).enabled
146
+ return typeof enabled === 'boolean' ? { enabled } : undefined
147
+ }
148
+
149
+ /** Browser-safe mirror of the runtime monitorPanel section (absent inherits hidden). */
150
+ export function decodeMonitorPanelSettings(value: unknown): MonitorPanelSettings | undefined {
151
+ if (value === undefined) return { enabled: false }
152
+ if (!isPlainRecord(value)) return undefined
153
+ const keys = Object.keys(value)
154
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
155
+ const enabled = (value as Record<string, unknown>).enabled
156
+ return typeof enabled === 'boolean' ? { enabled } : undefined
157
+ }
158
+
159
+ /** Browser-safe mirror of the runtime presetOptions section. */
160
+ export interface PresetOptionsSettings {
161
+ readonly dedupeToolResults?: boolean
162
+ readonly summaryLocator?: boolean
163
+ readonly prefixStabilizer?: boolean
164
+ readonly readState?: boolean
165
+ readonly estimatorMode?: '' | 'host' | 'direct'
166
+ readonly estimatorProvider?: string
167
+ readonly estimatorModel?: string
168
+ readonly estimatorBaseUrl?: string
169
+ readonly estimatorApiKey?: string
170
+ readonly estimatorTimeoutMs?: number
171
+ /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
172
+ readonly advisorMode?: '' | 'host' | 'direct'
173
+ readonly advisorTimeoutMs?: number
174
+ readonly advisorRefreshTurns?: number
175
+ readonly advisorScoreThreshold?: number
176
+ readonly advisorSampleLimit?: number
177
+ readonly advisorMinTokens?: number
178
+ }
179
+
180
+ /**
181
+ * Browser mirror of the runtime presetOptions section: absent inherits the
182
+ * preset defaults (decodes to `undefined`); present values must be a plain
183
+ * object carrying only the known keys with valid types.
184
+ */
185
+ export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
186
+ if (value === undefined) return undefined
187
+ if (!isPlainRecord(value)) return undefined
188
+ const allowed = new Set([
189
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
190
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
191
+ // Legacy keys of the retired review gate: still ACCEPTED so an existing
192
+ // settings document keeps decoding (rejecting them would report the whole
193
+ // card unreadable), and ignored — nothing reads them any more.
194
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
195
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
196
+ 'advisorMinTokens',
197
+ ])
198
+ if (Object.keys(value).some(key => !allowed.has(key))) return undefined
199
+ for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
200
+ const entry = value[key]
201
+ if (entry !== undefined && typeof entry !== 'boolean') return undefined
202
+ }
203
+ const estimatorMode = value.estimatorMode
204
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
205
+ return undefined
206
+ }
207
+ const advisorMode = value.advisorMode
208
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
209
+ return undefined
210
+ }
211
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
212
+ const entry = value[key]
213
+ if (entry !== undefined && typeof entry !== 'string') return undefined
214
+ }
215
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
216
+ if (estimatorTimeoutMs !== undefined
217
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
218
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
219
+ return undefined
220
+ }
221
+ const advisorTimeoutMs = value.advisorTimeoutMs
222
+ if (advisorTimeoutMs !== undefined
223
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
224
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
225
+ return undefined
226
+ }
227
+ const advisorRefreshTurns = value.advisorRefreshTurns
228
+ if (advisorRefreshTurns !== undefined
229
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
230
+ || advisorRefreshTurns < 1)) {
231
+ return undefined
232
+ }
233
+ const advisorScoreThreshold = value.advisorScoreThreshold
234
+ if (advisorScoreThreshold !== undefined
235
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
236
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
237
+ return undefined
238
+ }
239
+ const advisorSampleLimit = value.advisorSampleLimit
240
+ if (advisorSampleLimit !== undefined
241
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
242
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
243
+ return undefined
244
+ }
245
+ const advisorMinTokens = value.advisorMinTokens
246
+ if (advisorMinTokens !== undefined
247
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
248
+ return undefined
249
+ }
250
+ const decoded: {
251
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
252
+ } = {}
253
+ if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
254
+ if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
255
+ if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
256
+ if (value.readState !== undefined) decoded.readState = value.readState as boolean
257
+ if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
258
+ if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
259
+ if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
260
+ if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
261
+ if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
262
+ if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
263
+ if (advisorMode !== undefined) decoded.advisorMode = advisorMode as '' | 'host' | 'direct'
264
+ if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs as number
265
+ if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns as number
266
+ if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold as number
267
+ if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit as number
268
+ if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens as number
269
+ return decoded
270
+ }
271
+
272
+ /**
273
+ * The one threshold contract shared by the UI, the persisted settings, and the
274
+ * runtime resolver; mirrored browser-safe from the runtime package.
275
+ */
276
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
277
+ min: 50,
278
+ max: 90,
279
+ step: 1,
280
+ default: 80,
281
+ } as const)
282
+
283
+ /** Narrow one unknown value to a valid Auto Compact threshold percent. */
284
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
285
+ return typeof value === 'number'
286
+ && Number.isSafeInteger(value)
287
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
288
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
289
+ }
290
+
291
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
292
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
293
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
294
+ const prototype = Object.getPrototypeOf(value) as object | null
295
+ return prototype === Object.prototype || prototype === null
296
+ }
297
+
298
+ /**
299
+ * Decode the persisted autoCompact section with exactly the runtime schema's
300
+ * strictness: absent means the 80% default; present values must be a plain
301
+ * object carrying only a valid `thresholdPercent`. Anything else is invalid,
302
+ * never silently coerced.
303
+ */
304
+ export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
305
+ if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
306
+ if (!isPlainRecord(value)) return undefined
307
+ const keys = Object.keys(value)
308
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
309
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
310
+ return isValidAutoCompactThresholdPercent(thresholdPercent)
311
+ ? { thresholdPercent }
312
+ : undefined
313
+ }
314
+
315
+ /** Durable settings section owned by this package. */
316
+ export interface ContextCompressionSettings {
317
+ /** Default profile captured when each Session first reaches the pruner. */
318
+ profile: CompressionProfile
319
+ /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
320
+ custom: CustomCompressionPolicy
321
+ /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
322
+ autoCompact: AutoCompactSettings
323
+ /** Code-skeleton reducer gate captured independently of `profile`. */
324
+ codeSkeleton: CodeSkeletonSettings
325
+ /** Turn-tail intent-summary gate captured independently of `profile`. */
326
+ intentSummary: IntentSummarySettings
327
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
328
+ monitorPanel?: MonitorPanelSettings
329
+ /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
330
+ presetOptions?: PresetOptionsSettings
331
+ }
332
+
333
+ /**
334
+ * Narrow an unknown settings value to a complete supported Custom policy.
335
+ * @param value - Candidate settings value received from the Host or edited locally.
336
+ * @returns Whether the value is a relation-valid Custom policy.
337
+ */
338
+ export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
339
+ if (!hasExactKeys(
340
+ value,
341
+ value !== null && typeof value === 'object' && 'version' in value && value.version === 1
342
+ ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
343
+ : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
344
+ )) return false
345
+ if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
346
+ || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
347
+ if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
348
+ if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
349
+ const modernHistory = value.version === 3
350
+ if (!hasExactKeys(
351
+ value.history,
352
+ modernHistory
353
+ ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
354
+ : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
355
+ )) return false
356
+ if (typeof value.history.enabled !== 'boolean'
357
+ || typeof value.history.trigger !== 'number'
358
+ || typeof value.history.minReclaim !== 'number') return false
359
+ const recent = modernHistory
360
+ ? value.history.keepRecentTokens
361
+ : value.history.keepRecent
362
+ const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
363
+ if (typeof recent !== 'number'
364
+ || typeof calls !== 'number'
365
+ || !Number.isSafeInteger(calls)
366
+ || calls < 0) return false
367
+ let tailTrimTrigger: number | undefined
368
+ if (value.version !== 1) {
369
+ const tailTrim = value.tailTrim
370
+ if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
371
+ || typeof tailTrim.enabled !== 'boolean'
372
+ || typeof tailTrim.trigger !== 'number') return false
373
+ tailTrimTrigger = tailTrim.trigger
374
+ }
375
+ const measured = [
376
+ value.fresh.trigger, value.fresh.target,
377
+ value.aggregate.trigger, value.aggregate.target,
378
+ value.history.trigger, recent, value.history.minReclaim,
379
+ ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
380
+ ]
381
+ if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
382
+ if (value.fresh.trigger <= 0 || value.fresh.target <= 0
383
+ || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
384
+ || value.history.trigger <= 0 || recent < 0
385
+ || value.history.minReclaim <= 0
386
+ || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
387
+ if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
388
+ if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
389
+ return value.fresh.target < value.fresh.trigger
390
+ && value.aggregate.target < value.aggregate.trigger
391
+ && value.history.minReclaim <= value.history.trigger
392
+ }
393
+
394
+ function isBudget(value: unknown): value is CustomCompressionBudget {
395
+ return hasExactKeys(value, ['enabled', 'trigger', 'target'])
396
+ && typeof value.enabled === 'boolean'
397
+ && typeof value.trigger === 'number'
398
+ && typeof value.target === 'number'
399
+ }
400
+
401
+ /**
402
+ * Canonicalize one validated Custom document to version 3, mirroring the
403
+ * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
404
+ * boundaries hand the SAME complete document to the UI and the policy
405
+ * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
406
+ * and a v1 document gains the default-disabled TailTrim stage.
407
+ */
408
+ export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
409
+ if (policy.version === 3) return structuredClone(policy)
410
+ return {
411
+ version: 3,
412
+ unit: policy.unit,
413
+ fresh: structuredClone(policy.fresh),
414
+ aggregate: structuredClone(policy.aggregate),
415
+ history: {
416
+ enabled: policy.history.enabled,
417
+ trigger: policy.history.trigger,
418
+ keepRecentToolCalls: 10,
419
+ keepRecentTokens: policy.history.keepRecent,
420
+ minReclaim: policy.history.minReclaim,
421
+ },
422
+ prefixPolicy: policy.prefixPolicy,
423
+ tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
424
+ }
425
+ }
426
+
427
+ function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
428
+ if (!isPlainRecord(value)) return false
429
+ const keys = Object.keys(value)
430
+ return keys.length === expected.length && keys.every(key => expected.includes(key))
431
+ }