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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/eslint.config.js +30 -30
  3. package/package.json +163 -163
  4. package/packages/selector/dsh.plugin.json +16 -16
  5. package/packages/selector/lib/client.d.ts +20 -0
  6. package/packages/selector/lib/client.js +433 -17
  7. package/packages/selector/lib/index.js +213 -2
  8. package/packages/selector/lib/{advisor-state.js → intent-gate.js} +593 -3
  9. package/packages/selector/lib/profiles.d.ts +9 -0
  10. package/packages/selector/lib/pruner.d.ts +59 -0
  11. package/packages/selector/lib/pruner.js +494 -262
  12. package/packages/selector/lib/style.css +42 -0
  13. package/packages/selector/src/client/CompressionProfileControls.tsx +34 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  15. package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
  16. package/packages/selector/src/client/decode.ts +53 -49
  17. package/packages/selector/src/client/index.ts +4 -0
  18. package/packages/selector/src/client/locales/de.ts +20 -0
  19. package/packages/selector/src/client/locales/es.ts +20 -0
  20. package/packages/selector/src/client/locales/fr.ts +20 -0
  21. package/packages/selector/src/client/locales/it.ts +20 -0
  22. package/packages/selector/src/client/locales/ja.ts +20 -0
  23. package/packages/selector/src/client/locales/ko.ts +20 -0
  24. package/packages/selector/src/client/locales/ru.ts +20 -0
  25. package/packages/selector/src/client/locales.ts +236 -196
  26. package/packages/selector/src/client/savings-card.tsx +150 -0
  27. package/packages/selector/src/client/settings-section.tsx +133 -124
  28. package/packages/selector/src/index.ts +554 -411
  29. package/packages/selector/src/profiles.ts +414 -394
  30. package/packages/selector/src/pruner/state.ts +57 -50
  31. package/packages/selector/src/pruner.ts +2745 -2421
  32. package/packages/selector/src/runtime/audit.ts +303 -286
  33. package/packages/selector/src/runtime/config.ts +731 -706
  34. package/packages/selector/src/runtime/retrieve.ts +479 -457
  35. package/packages/selector/src/runtime/savings.ts +337 -0
  36. package/packages/selector/src/runtime/summary-command.ts +127 -0
  37. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  38. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  39. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  43. package/packages/selector/src/runtime/types.ts +358 -346
  44. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  45. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  46. package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
  47. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  48. package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
  49. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  50. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  51. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  52. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  53. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  54. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2734 -2731
  55. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  56. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  57. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  58. package/scripts/packed-install-e2e.mjs +1 -1
  59. package/scripts/verify-release.mjs +2 -1
@@ -1,411 +1,554 @@
1
- /** Host owner of the context-compression preference consumed by the browser selector. */
2
-
3
- import type { Context } from '@deepseek-ai/cordis'
4
- import z from '@deepseek-ai/schemastery'
5
- import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
6
- import type { ContextCompressionSettings } from './profiles.ts'
7
- import {
8
- CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
9
- DEFAULT_CONTEXT_COMPRESSION_SETTINGS,
10
- } from './runtime/config.ts'
11
-
12
- import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
13
-
14
- // The settings namespace literal and the settings schema are owned by the
15
- // runtime config module. Both were once inlined/replaced here to dodge a
16
- // cross-package dependency (ab2175a: the namespace literal was duplicated and
17
- // the schema was downgraded to `z.any()`); the runtime is now part of this
18
- // package, so the real schema is back and the daily Custom defaults are
19
- // published again through settings.register(). The namespace value is
20
- // unchanged ('context-compression').
21
- import {
22
- decorateAgentPresets,
23
- resolveCompressionModulePaths,
24
- } from './preset-overlay.ts'
25
-
26
- // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
27
- // absolute paths are registered (each is its own (kind, path) table entry) and
28
- // one handler serves both prefixes. The bundled client only probes /api.
29
- const ESTIMATOR_CATALOG_ROUTES = [
30
- '/endpoint/dsh-context-compression-improved/estimator-catalog',
31
- '/api/dsh-context-compression-improved/estimator-catalog',
32
- ] as const
33
-
34
- // Advisory advisor: one read-only report route, dual prefixed like the others.
35
- const ADVISOR_REPORT_ROUTES = [
36
- '/endpoint/dsh-context-compression-improved/advisor-report',
37
- '/api/dsh-context-compression-improved/advisor-report',
38
- ] as const
39
-
40
- /** Minimal face of the agents service: session id → agent (carrying the session). */
41
- interface AgentsServiceLike {
42
- get?(id: unknown): { session?: unknown } | undefined
43
- }
44
-
45
- function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
46
- const agents = readService('agents') as AgentsServiceLike | undefined
47
- return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
48
- }
49
-
50
- function jsonResponse(res: unknown, status: number, body: unknown): void {
51
- const resTyped = res as {
52
- writeHead: (code: number, headers?: Record<string, string>) => void
53
- end: (body?: string) => void
54
- }
55
- resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
56
- resTyped.end(JSON.stringify(body))
57
- }
58
-
59
- /**
60
- * Serve the advisory advisor's read-only report route (same registration
61
- * skeleton as the estimator-catalog route):
62
- *
63
- * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
64
- * the todolist-bound task summary, and the score distribution. Content-free
65
- * by construction: task semantics are LLM-derived summaries, never message
66
- * text, and no score reason or candidate preview is ever returned.
67
- * Unknown session → 404; no agents service → 503. A session whose advisor
68
- * never ran reports nulls and empty arrays, not an error.
69
- */
70
- function registerAdvisorReportRoute(ctx: Context): void {
71
- const readService = (name: string): unknown => {
72
- try {
73
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
74
- } catch {
75
- return undefined
76
- }
77
- }
78
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
79
- console[level](message, ...args)
80
- }
81
-
82
- const getHandler = (req: unknown, res: unknown): void => {
83
- const agents = readService('agents') as AgentsServiceLike | undefined
84
- if (typeof agents?.get !== 'function') {
85
- jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
86
- return
87
- }
88
- let sessionId = ''
89
- try {
90
- const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
91
- sessionId = url.searchParams.get('sessionId') ?? ''
92
- } catch {
93
- // Malformed URL: fall through with the empty sessionId already set.
94
- }
95
- if (sessionId === '') {
96
- jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
97
- return
98
- }
99
- const session = sessionFor(readService, sessionId)
100
- if (session === undefined) {
101
- jsonResponse(res, 404, { ok: false, error: 'unknown session' })
102
- return
103
- }
104
- const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
105
- jsonResponse(res, 200, {
106
- ok: true,
107
- sessionId,
108
- advisor: {
109
- summary: state.summary ?? null,
110
- decay: state.lastDecay?.decay ?? null,
111
- weightedChars: state.lastDecay?.weightedChars ?? null,
112
- decayTurn: state.lastDecay?.turn ?? null,
113
- scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
114
- lowRelevanceSeqs: [...state.recertified.keys()],
115
- // The benefit model's label of the last landed batch — advice, never a
116
- // gate: the batch it describes landed regardless of the band.
117
- lastAdvice: state.lastAdvice === undefined
118
- ? null
119
- : {
120
- band: state.lastAdvice.band,
121
- turn: state.lastAdvice.turn,
122
- itemSeqs: state.lastAdvice.itemSeqs,
123
- recoveredTokens: state.lastAdvice.recoveredTokens,
124
- penaltyTokens: state.lastAdvice.penaltyTokens,
125
- paybackTurns: state.lastAdvice.paybackTurns ?? null,
126
- },
127
- },
128
- })
129
- }
130
-
131
- const register = (webServer: WebServerLike): void => {
132
- const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
133
- const disposers = table
134
- .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
135
- .filter((off): off is () => void => typeof off === 'function')
136
- ctx.effect(
137
- () => () => { for (const off of disposers) off() },
138
- 'contextCompressionSelector.advisor report route',
139
- )
140
- log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
141
- }
142
-
143
- const active = asWebServer(readService('webServer'))
144
- if (active !== undefined) {
145
- register(active)
146
- return
147
- }
148
-
149
- ctx.inject(['webServer'], (injected) => {
150
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
151
- if (webServer === undefined) {
152
- log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
153
- return
154
- }
155
- register(webServer)
156
- })
157
-
158
- log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
159
- }
160
-
161
- /**
162
- * The one service the catalog route actually needs. `llm` and
163
- * `agentDefaultModel` are payload enrichment the handler resolves per request,
164
- * never reasons to withhold the route.
165
- */
166
- const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
167
-
168
- /** The minimal face of the DSH `webServer` service this plugin uses. */
169
- interface WebServerLike {
170
- register(route: {
171
- kind: 'exact'
172
- path: string
173
- handler: (req: unknown, res: unknown) => unknown
174
- }): () => void
175
- }
176
-
177
- /** The estimator-side service the catalog handler enriches its response with. */
178
- interface AgentDefaultModelLike {
179
- /** Current host model-group selection, when the service exposes one. */
180
- currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
181
- }
182
-
183
- function asWebServer(value: unknown): WebServerLike | undefined {
184
- if (typeof value !== 'object' || value === null) return undefined
185
- const candidate = value as { register?: unknown }
186
- // Hand back the service itself -- never a wrapper re-exporting `register`.
187
- // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
188
- // so a detached call makes `this` the wrapper and throws "Cannot read
189
- // properties of undefined (reading 'has')" inside the host, after which the
190
- // route is simply absent and the client sees a bare 404. The 0.1.5 branch
191
- // never had that defect; take this implementation, not the 0.1.2 history's.
192
- return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
193
- }
194
-
195
- /**
196
- * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
197
- * settings card's host-route dropdowns (live provider/model groups from the DSH
198
- * `llm` service plus the effective selection). Best effort: without the
199
- * `webServer` service the plugin keeps working, only the HTTP API is missing.
200
- *
201
- * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
202
- * enrich the response and are resolved per request, so listing them here would
203
- * let an estimator-side service the handler never needs keep the route
204
- * unregistered. That failure is silent by construction — an unsatisfied
205
- * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
206
- * every request falls through to the host 404.
207
- *
208
- * Two channels cover the two arrival orders: a direct lookup catches a
209
- * `webServer` that is already active when the plugin loads, and `ctx.inject`
210
- * catches one that activates later. Both funnel into a single guarded
211
- * registration, because a late-arriving service must not re-register a
212
- * `(kind, path)` the host treats as a composition-contract violation.
213
- */
214
- function registerEstimatorCatalogRoute(ctx: Context): void {
215
- const readService = (name: string): unknown => {
216
- try {
217
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
218
- } catch {
219
- return undefined
220
- }
221
- }
222
- // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
223
- // surfaces no plugin output in the `dsh web` terminal at all — a full boot
224
- // produced zero plugin log lines while the process itself stayed chatty — so
225
- // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
226
- // uses `console.warn` for the same message class on the same host.
227
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
228
- console[level](message, ...args)
229
- }
230
-
231
- let registered = false
232
- const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
233
- if (registered) return
234
- const handler = (_req: unknown, res: unknown): void => {
235
- const resTyped = res as {
236
- writeHead: (code: number, headers?: Record<string, string>) => void
237
- end: (body?: string) => void
238
- }
239
- if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
240
- const llm = readService('llm')
241
- const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
242
- const deps: EstimatorCatalogDeps = {
243
- ...(llm === undefined
244
- ? {}
245
- : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
246
- ...(typeof defaults?.currentSelection === 'function'
247
- ? { currentSelection: () => defaults.currentSelection?.() }
248
- : {}),
249
- }
250
- buildEstimatorCatalog(deps).then(
251
- catalog => {
252
- resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
253
- resTyped.end(JSON.stringify({ ok: true, ...catalog }))
254
- },
255
- (error: unknown) => {
256
- resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
257
- resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
258
- },
259
- )
260
- }
261
- try {
262
- const disposers = ESTIMATOR_CATALOG_ROUTES
263
- .map(path => webServer.register({ kind: 'exact', path, handler }))
264
- .filter((off): off is () => void => typeof off === 'function')
265
- registered = true
266
- ctx.effect(
267
- () => () => { for (const off of disposers) off() },
268
- 'contextCompressionSelector.estimator-catalog route',
269
- )
270
- log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
271
- } catch (error) {
272
- log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
273
- }
274
- }
275
-
276
- const active = asWebServer(readService('webServer'))
277
- if (active !== undefined) {
278
- register(active, 'direct')
279
- if (registered) return
280
- }
281
-
282
- ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
283
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
284
- if (webServer === undefined) {
285
- log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
286
- return
287
- }
288
- register(webServer, 'inject')
289
- })
290
-
291
- log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
292
- }
293
-
294
- /**
295
- * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
296
- * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
297
- */
298
- function readVolatileValue<T>(value: T | { get(): T } | undefined): T | undefined {
299
- if (value !== null && typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function') {
300
- return (value as { get(): T }).get()
301
- }
302
- return value as T | undefined
303
- }
304
-
305
- /** The compression settings document carried by this row's composition entry. */
306
- function readCompressionDoc(config: Config | undefined): ContextCompressionSettings | undefined {
307
- return readVolatileValue(config?.settings)
308
- }
309
-
310
- /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
311
- export interface Config {
312
- /** Add the canonical compression stack to every non-Minimal preset. */
313
- presetOverlay?: boolean
314
- /**
315
- * Register the estimator-catalog HTTP route on this row.
316
- *
317
- * The standalone Bundle patch sets this on its own row (which declares
318
- * `inject: [webServer]`), so profiles without a host web server never mount a
319
- * row that could only announce a pending route. The row-level `inject` is
320
- * belt-and-braces: `dsh-host-webserver.register` performs no authorization
321
- * check and `ctx.get(name)` only asks whether the providing fiber is active,
322
- * so the two-channel registration inside this function is what actually
323
- * covers both arrival orders.
324
- */
325
- estimatorCatalogRoute?: boolean
326
- /**
327
- * Register the advisory advisor's read-only HTTP report route (decay
328
- * figure, task summary, score distribution, last benefit-model advice).
329
- * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
330
- * itself stays off until the user turns it on through the
331
- * `presetOptions.advisor*` settings keys.
332
- */
333
- advisorReportRoute?: boolean
334
- /**
335
- * 0.1.7: the compression settings document as ONE `.volatile()` whole-object
336
- * field (the old dedicated namespace has no declarative equivalent). The
337
- * browser selector writes it through `configForms`; the runtime reads the
338
- * dereferenced value. Loose section schemas keep unknown keys — the strict
339
- * validation stays in `decodeSettings` (client) and the runtime resolver.
340
- */
341
- settings?: ContextCompressionSettings
342
- }
343
-
344
- /** Loader validation for the standalone Bundle opt-in. */
345
- export const Config = z.object({
346
- presetOverlay: z.boolean().default(false),
347
- estimatorCatalogRoute: z.boolean().default(false),
348
- advisorReportRoute: z.boolean().default(false),
349
- // The daily Custom defaults ride the field's schema default so every
350
- // composition resolves a complete document without a stored user layer.
351
- settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile(),
352
- }) as unknown as z<Config>
353
-
354
- /** Register the persisted default read by the currently mounted root pruner. */
355
- export function apply(ctx: Context, config: Config = {}): void {
356
- // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
357
- // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
358
- // here is completely invisible and looks exactly like a plugin that loaded
359
- // and quietly did nothing. Report it to a sink the host shows, then re-throw
360
- // unchanged: behaviour is untouched, only observability is restored.
361
- try {
362
- // The settings card's host-route dropdowns read this route; it lives on the
363
- // top-level plugin fiber, not inside the isolated `toolResultPruner`
364
- // service, because the route is host-wide rather than per-pruner-instance.
365
- if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
366
-
367
- // Advisory advisor: read-only decay/score/advice report (opt-in).
368
- if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
369
-
370
- if (config.presetOverlay !== true) return
371
-
372
- ctx.inject(['agentPresets'], (presetsCtx) => {
373
- const installation = decorateAgentPresets(
374
- presetsCtx.agentPresets,
375
- {
376
- modules: resolveCompressionModulePaths(),
377
- excludedPresetIds: ['minimal'],
378
- autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(config, presetsCtx),
379
- },
380
- )
381
- presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
382
- })
383
- } catch (error) {
384
- console.error('context-compression selector apply failed: %o', error)
385
- throw error
386
- }
387
- }
388
-
389
- /**
390
- * Read the current Auto Compact threshold ratio at composition time. Settings
391
- * values are revalidated here, and any unreadable value falls back to the 80%
392
- * default rather than blocking preset composition.
393
- */
394
- function resolveAutoCompactThresholdPercent(config: Config | undefined, presetsCtx?: Context): number {
395
- // 0.1.7: the volatile entry field is authoritative; the legacy per-namespace
396
- // read stays as a fallback so a host that still serves the old service shape
397
- // keeps working (test hosts do exactly that).
398
- const raw = readCompressionDoc(config)
399
- ?? (presetsCtx?.get('settings') as { get?: (ns: never) => unknown } | undefined)
400
- ?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
401
- try {
402
- const record = structuredClone(raw) as Record<string, unknown> | undefined
403
- const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
404
- const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
405
- return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
406
- } catch {
407
- return 80
408
- }
409
- }
410
-
411
-
1
+ /** Host owner of the context-compression preference consumed by the browser selector. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
6
+ import { getSavingsLedger } from './runtime/savings.ts'
7
+ import { priceOfficialDeepSeekUsage } from './runtime/deepseek-official-pricing.ts'
8
+ import type { ContextCompressionSettings } from './profiles.ts'
9
+ import {
10
+ CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
11
+ DEFAULT_CONTEXT_COMPRESSION_SETTINGS,
12
+ } from './runtime/config.ts'
13
+
14
+ import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
15
+ import { registerSummaryCommand } from './runtime/summary-command.ts'
16
+
17
+ // The settings namespace literal and the settings schema are owned by the
18
+ // runtime config module. Both were once inlined/replaced here to dodge a
19
+ // cross-package dependency (ab2175a: the namespace literal was duplicated and
20
+ // the schema was downgraded to `z.any()`); the runtime is now part of this
21
+ // package, so the real schema is back and the daily Custom defaults are
22
+ // published again through settings.register(). The namespace value is
23
+ // unchanged ('context-compression').
24
+ import {
25
+ decorateAgentPresets,
26
+ resolveCompressionModulePaths,
27
+ } from './preset-overlay.ts'
28
+
29
+ // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
30
+ // absolute paths are registered (each is its own (kind, path) table entry) and
31
+ // one handler serves both prefixes. The bundled client only probes /api.
32
+ const ESTIMATOR_CATALOG_ROUTES = [
33
+ '/endpoint/dsh-context-compression-improved/estimator-catalog',
34
+ '/api/dsh-context-compression-improved/estimator-catalog',
35
+ ] as const
36
+
37
+ // Advisory advisor: one read-only report route, dual prefixed like the others.
38
+ const ADVISOR_REPORT_ROUTES = [
39
+ '/endpoint/dsh-context-compression-improved/advisor-report',
40
+ '/api/dsh-context-compression-improved/advisor-report',
41
+ ] as const
42
+
43
+ // Savings stats: one read-only snapshot route, dual prefixed like the others.
44
+ const SAVINGS_ROUTES = [
45
+ '/endpoint/dsh-context-compression-improved/savings',
46
+ '/api/dsh-context-compression-improved/savings',
47
+ ] as const
48
+
49
+ /** Minimal face of the agents service: session id → agent (carrying the session). */
50
+ interface AgentsServiceLike {
51
+ get?(id: unknown): { session?: unknown } | undefined
52
+ }
53
+
54
+ function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
55
+ const agents = readService('agents') as AgentsServiceLike | undefined
56
+ return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
57
+ }
58
+
59
+ function jsonResponse(res: unknown, status: number, body: unknown): void {
60
+ const resTyped = res as {
61
+ writeHead: (code: number, headers?: Record<string, string>) => void
62
+ end: (body?: string) => void
63
+ }
64
+ resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
65
+ resTyped.end(JSON.stringify(body))
66
+ }
67
+
68
+ /**
69
+ * Serve the advisory advisor's read-only report route (same registration
70
+ * skeleton as the estimator-catalog route):
71
+ *
72
+ * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
73
+ * the todolist-bound task summary, and the score distribution. Content-free
74
+ * by construction: task semantics are LLM-derived summaries, never message
75
+ * text, and no score reason or candidate preview is ever returned.
76
+ * Unknown session → 404; no agents service → 503. A session whose advisor
77
+ * never ran reports nulls and empty arrays, not an error.
78
+ */
79
+ function registerAdvisorReportRoute(ctx: Context): void {
80
+ const readService = (name: string): unknown => {
81
+ try {
82
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
83
+ } catch {
84
+ return undefined
85
+ }
86
+ }
87
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
88
+ console[level](message, ...args)
89
+ }
90
+
91
+ const getHandler = (req: unknown, res: unknown): void => {
92
+ const agents = readService('agents') as AgentsServiceLike | undefined
93
+ if (typeof agents?.get !== 'function') {
94
+ jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
95
+ return
96
+ }
97
+ let sessionId = ''
98
+ try {
99
+ const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
100
+ sessionId = url.searchParams.get('sessionId') ?? ''
101
+ } catch {
102
+ // Malformed URL: fall through with the empty sessionId already set.
103
+ }
104
+ if (sessionId === '') {
105
+ jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
106
+ return
107
+ }
108
+ const session = sessionFor(readService, sessionId)
109
+ if (session === undefined) {
110
+ jsonResponse(res, 404, { ok: false, error: 'unknown session' })
111
+ return
112
+ }
113
+ const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
114
+ jsonResponse(res, 200, {
115
+ ok: true,
116
+ sessionId,
117
+ advisor: {
118
+ summary: state.summary ?? null,
119
+ decay: state.lastDecay?.decay ?? null,
120
+ weightedChars: state.lastDecay?.weightedChars ?? null,
121
+ decayTurn: state.lastDecay?.turn ?? null,
122
+ scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
123
+ lowRelevanceSeqs: [...state.recertified.keys()],
124
+ // The benefit model's label of the last landed batch — advice, never a
125
+ // gate: the batch it describes landed regardless of the band.
126
+ lastAdvice: state.lastAdvice === undefined
127
+ ? null
128
+ : {
129
+ band: state.lastAdvice.band,
130
+ turn: state.lastAdvice.turn,
131
+ itemSeqs: state.lastAdvice.itemSeqs,
132
+ recoveredTokens: state.lastAdvice.recoveredTokens,
133
+ penaltyTokens: state.lastAdvice.penaltyTokens,
134
+ paybackTurns: state.lastAdvice.paybackTurns ?? null,
135
+ },
136
+ },
137
+ })
138
+ }
139
+
140
+ const register = (webServer: WebServerLike): void => {
141
+ const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
142
+ const disposers = table
143
+ .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
144
+ .filter((off): off is () => void => typeof off === 'function')
145
+ ctx.effect(
146
+ () => () => { for (const off of disposers) off() },
147
+ 'contextCompressionSelector.advisor report route',
148
+ )
149
+ log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
150
+ }
151
+
152
+ const active = asWebServer(readService('webServer'))
153
+ if (active !== undefined) {
154
+ register(active)
155
+ return
156
+ }
157
+
158
+ ctx.inject(['webServer'], (injected) => {
159
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
160
+ if (webServer === undefined) {
161
+ log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
162
+ return
163
+ }
164
+ register(webServer)
165
+ })
166
+
167
+ log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
168
+ }
169
+
170
+ /**
171
+ * The one service the catalog route actually needs. `llm` and
172
+ * `agentDefaultModel` are payload enrichment the handler resolves per request,
173
+ * never reasons to withhold the route.
174
+ */
175
+ const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
176
+
177
+ /** The minimal face of the DSH `webServer` service this plugin uses. */
178
+ interface WebServerLike {
179
+ register(route: {
180
+ kind: 'exact'
181
+ path: string
182
+ handler: (req: unknown, res: unknown) => unknown
183
+ }): () => void
184
+ }
185
+
186
+ /** The estimator-side service the catalog handler enriches its response with. */
187
+ interface AgentDefaultModelLike {
188
+ /** Current host model-group selection, when the service exposes one. */
189
+ currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
190
+ }
191
+
192
+ function asWebServer(value: unknown): WebServerLike | undefined {
193
+ if (typeof value !== 'object' || value === null) return undefined
194
+ const candidate = value as { register?: unknown }
195
+ // Hand back the service itself -- never a wrapper re-exporting `register`.
196
+ // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
197
+ // so a detached call makes `this` the wrapper and throws "Cannot read
198
+ // properties of undefined (reading 'has')" inside the host, after which the
199
+ // route is simply absent and the client sees a bare 404. The 0.1.5 branch
200
+ // never had that defect; take this implementation, not the 0.1.2 history's.
201
+ return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
202
+ }
203
+
204
+ /**
205
+ * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
206
+ * settings card's host-route dropdowns (live provider/model groups from the DSH
207
+ * `llm` service plus the effective selection). Best effort: without the
208
+ * `webServer` service the plugin keeps working, only the HTTP API is missing.
209
+ *
210
+ * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
211
+ * enrich the response and are resolved per request, so listing them here would
212
+ * let an estimator-side service the handler never needs keep the route
213
+ * unregistered. That failure is silent by construction — an unsatisfied
214
+ * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
215
+ * every request falls through to the host 404.
216
+ *
217
+ * Two channels cover the two arrival orders: a direct lookup catches a
218
+ * `webServer` that is already active when the plugin loads, and `ctx.inject`
219
+ * catches one that activates later. Both funnel into a single guarded
220
+ * registration, because a late-arriving service must not re-register a
221
+ * `(kind, path)` the host treats as a composition-contract violation.
222
+ */
223
+ function registerEstimatorCatalogRoute(ctx: Context): void {
224
+ const readService = (name: string): unknown => {
225
+ try {
226
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
227
+ } catch {
228
+ return undefined
229
+ }
230
+ }
231
+ // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
232
+ // surfaces no plugin output in the `dsh web` terminal at all — a full boot
233
+ // produced zero plugin log lines while the process itself stayed chatty — so
234
+ // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
235
+ // uses `console.warn` for the same message class on the same host.
236
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
237
+ console[level](message, ...args)
238
+ }
239
+
240
+ let registered = false
241
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
242
+ if (registered) return
243
+ const handler = (_req: unknown, res: unknown): void => {
244
+ const resTyped = res as {
245
+ writeHead: (code: number, headers?: Record<string, string>) => void
246
+ end: (body?: string) => void
247
+ }
248
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
249
+ const llm = readService('llm')
250
+ const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
251
+ const deps: EstimatorCatalogDeps = {
252
+ ...(llm === undefined
253
+ ? {}
254
+ : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
255
+ ...(typeof defaults?.currentSelection === 'function'
256
+ ? { currentSelection: () => defaults.currentSelection?.() }
257
+ : {}),
258
+ }
259
+ buildEstimatorCatalog(deps).then(
260
+ catalog => {
261
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
262
+ resTyped.end(JSON.stringify({ ok: true, ...catalog }))
263
+ },
264
+ (error: unknown) => {
265
+ resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
266
+ resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
267
+ },
268
+ )
269
+ }
270
+ try {
271
+ const disposers = ESTIMATOR_CATALOG_ROUTES
272
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
273
+ .filter((off): off is () => void => typeof off === 'function')
274
+ registered = true
275
+ ctx.effect(
276
+ () => () => { for (const off of disposers) off() },
277
+ 'contextCompressionSelector.estimator-catalog route',
278
+ )
279
+ log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
280
+ } catch (error) {
281
+ log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
282
+ }
283
+ }
284
+
285
+ const active = asWebServer(readService('webServer'))
286
+ if (active !== undefined) {
287
+ register(active, 'direct')
288
+ if (registered) return
289
+ }
290
+
291
+ ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
292
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
293
+ if (webServer === undefined) {
294
+ log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
295
+ return
296
+ }
297
+ register(webServer, 'inject')
298
+ })
299
+
300
+ log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
301
+ }
302
+
303
+ /**
304
+ * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
305
+ * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
306
+ * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
307
+ * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
308
+ * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
309
+ */
310
+ function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
311
+ startedAt: string
312
+ net: { exact: number; estimated: number }
313
+ usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
314
+ }): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
315
+ if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
316
+ const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
317
+ const selection = defaults?.currentSelection?.()
318
+ const provider = typeof selection?.provider === 'string' ? selection.provider : ''
319
+ const modelId = typeof selection?.model === 'string' ? selection.model : ''
320
+ if (provider !== 'deepseek-official') return undefined
321
+ const now = new Date()
322
+ const startedAt = new Date(snapshot.startedAt)
323
+ const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
324
+ const base = {
325
+ provider,
326
+ baseUrlClass: 'official-public',
327
+ apiRoute: 'chat-completions',
328
+ modelId,
329
+ currency: 'USD',
330
+ startedAt,
331
+ completedAt,
332
+ } as const
333
+ const actual = priceOfficialDeepSeekUsage({
334
+ ...base,
335
+ usage: {
336
+ cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
337
+ cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
338
+ outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
339
+ },
340
+ })
341
+ const saved = snapshot.net.exact > 0
342
+ ? priceOfficialDeepSeekUsage({
343
+ ...base,
344
+ usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
345
+ })
346
+ : undefined
347
+ const decimalOf = (cost: typeof actual): string | undefined =>
348
+ cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
349
+ if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
350
+ return {
351
+ currency: 'USD',
352
+ ...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
353
+ ...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
359
+ * offsets (negative savings — compressed content later re-read in full), and net,
360
+ * with exact-tokenizer and chars/4 bases reported separately and never merged.
361
+ * Registration mirrors the estimator-catalog route (webServer gate alone, dual
362
+ * channels for both service arrival orders, single guarded registration).
363
+ */
364
+ function registerSavingsRoute(ctx: Context): void {
365
+ const readService = (name: string): unknown => {
366
+ try {
367
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
368
+ } catch {
369
+ return undefined
370
+ }
371
+ }
372
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
373
+ console[level](message, ...args)
374
+ }
375
+
376
+ let registered = false
377
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
378
+ if (registered) return
379
+ const handler = (req: unknown, res: unknown): void => {
380
+ const resTyped = res as {
381
+ writeHead: (code: number, headers?: Record<string, string>) => void
382
+ end: (body?: string) => void
383
+ }
384
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
385
+ let sessionId: string | undefined
386
+ try {
387
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
388
+ const raw = url.searchParams.get('sessionId')
389
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
390
+ } catch {
391
+ /* 无法解析的查询串 = 全会话聚合 */
392
+ }
393
+ const snapshot = getSavingsLedger().snapshot(sessionId)
394
+ const pricing = estimateSavingsPricing(readService, snapshot)
395
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
396
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
397
+ }
398
+ try {
399
+ const disposers = SAVINGS_ROUTES
400
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
401
+ .filter((off): off is () => void => typeof off === 'function')
402
+ registered = true
403
+ ctx.effect(
404
+ () => () => { for (const off of disposers) off() },
405
+ 'contextCompressionSelector.savings route',
406
+ )
407
+ log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
408
+ } catch (error) {
409
+ log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
410
+ }
411
+ }
412
+
413
+ const active = asWebServer(readService('webServer'))
414
+ if (active !== undefined) {
415
+ register(active, 'direct')
416
+ if (registered) return
417
+ }
418
+
419
+ ctx.inject(['webServer'], (injected) => {
420
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
421
+ if (webServer === undefined) {
422
+ log('warn', 'context-compression webServer exposes no register() — savings route not registered')
423
+ return
424
+ }
425
+ register(webServer, 'inject')
426
+ })
427
+ }
428
+
429
+ /**
430
+ * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
431
+ * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
432
+ */
433
+ function readVolatileValue<T>(value: T | { get(): T } | undefined): T | undefined {
434
+ if (value !== null && typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function') {
435
+ return (value as { get(): T }).get()
436
+ }
437
+ return value as T | undefined
438
+ }
439
+
440
+ /** The compression settings document carried by this row's composition entry. */
441
+ function readCompressionDoc(config: Config | undefined): ContextCompressionSettings | undefined {
442
+ return readVolatileValue(config?.settings)
443
+ }
444
+
445
+ /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
446
+ export interface Config {
447
+ /** Add the canonical compression stack to every non-Minimal preset. */
448
+ presetOverlay?: boolean
449
+ /**
450
+ * Register the estimator-catalog HTTP route on this row.
451
+ *
452
+ * The standalone Bundle patch sets this on its own row (which declares
453
+ * `inject: [webServer]`), so profiles without a host web server never mount a
454
+ * row that could only announce a pending route. The row-level `inject` is
455
+ * belt-and-braces: `dsh-host-webserver.register` performs no authorization
456
+ * check and `ctx.get(name)` only asks whether the providing fiber is active,
457
+ * so the two-channel registration inside this function is what actually
458
+ * covers both arrival orders.
459
+ */
460
+ estimatorCatalogRoute?: boolean
461
+ /**
462
+ * Register the advisory advisor's read-only HTTP report route (decay
463
+ * figure, task summary, score distribution, last benefit-model advice).
464
+ * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
465
+ * itself stays off until the user turns it on through the
466
+ * `presetOptions.advisor*` settings keys.
467
+ */
468
+ advisorReportRoute?: boolean
469
+ /**
470
+ * 0.1.7: the compression settings document as ONE `.volatile()` whole-object
471
+ * field (the old dedicated namespace has no declarative equivalent). The
472
+ * browser selector writes it through `configForms`; the runtime reads the
473
+ * dereferenced value. Loose section schemas keep unknown keys — the strict
474
+ * validation stays in `decodeSettings` (client) and the runtime resolver.
475
+ */
476
+ settings?: ContextCompressionSettings
477
+ }
478
+
479
+ /** Loader validation for the standalone Bundle opt-in. */
480
+ export const Config = z.object({
481
+ presetOverlay: z.boolean().default(false),
482
+ estimatorCatalogRoute: z.boolean().default(false),
483
+ advisorReportRoute: z.boolean().default(false),
484
+ // The daily Custom defaults ride the field's schema default so every
485
+ // composition resolves a complete document without a stored user layer.
486
+ settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile(),
487
+ }) as unknown as z<Config>
488
+
489
+ /** Register the persisted default read by the currently mounted root pruner. */
490
+ export function apply(ctx: Context, config: Config = {}): void {
491
+ // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
492
+ // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
493
+ // here is completely invisible and looks exactly like a plugin that loaded
494
+ // and quietly did nothing. Report it to a sink the host shows, then re-throw
495
+ // unchanged: behaviour is untouched, only observability is restored.
496
+ try {
497
+ // The settings card's host-route dropdowns read this route; it lives on the
498
+ // top-level plugin fiber, not inside the isolated `toolResultPruner`
499
+ // service, because the route is host-wide rather than per-pruner-instance.
500
+ if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
501
+ // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
502
+ registerSavingsRoute(ctx)
503
+
504
+ // Advisory advisor: read-only decay/score/advice report (opt-in).
505
+ if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
506
+
507
+ // Turn-tail intent summary: `/ctx-summary off|on|status`. The command is
508
+ // free to register and stays quiet on hosts without the commands
509
+ // registry; the capability itself is gated by the frozen `intentSummary`
510
+ // setting plus the session-scoped override this command controls.
511
+ registerSummaryCommand(ctx)
512
+
513
+ if (config.presetOverlay !== true) return
514
+
515
+ ctx.inject(['agentPresets'], (presetsCtx) => {
516
+ const installation = decorateAgentPresets(
517
+ presetsCtx.agentPresets,
518
+ {
519
+ modules: resolveCompressionModulePaths(),
520
+ excludedPresetIds: ['minimal'],
521
+ autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(config, presetsCtx),
522
+ },
523
+ )
524
+ presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
525
+ })
526
+ } catch (error) {
527
+ console.error('context-compression selector apply failed: %o', error)
528
+ throw error
529
+ }
530
+ }
531
+
532
+ /**
533
+ * Read the current Auto Compact threshold ratio at composition time. Settings
534
+ * values are revalidated here, and any unreadable value falls back to the 80%
535
+ * default rather than blocking preset composition.
536
+ */
537
+ function resolveAutoCompactThresholdPercent(config: Config | undefined, presetsCtx?: Context): number {
538
+ // 0.1.7: the volatile entry field is authoritative; the legacy per-namespace
539
+ // read stays as a fallback so a host that still serves the old service shape
540
+ // keeps working (test hosts do exactly that).
541
+ const raw = readCompressionDoc(config)
542
+ ?? (presetsCtx?.get('settings') as { get?: (ns: never) => unknown } | undefined)
543
+ ?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
544
+ try {
545
+ const record = structuredClone(raw) as Record<string, unknown> | undefined
546
+ const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
547
+ const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
548
+ return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
549
+ } catch {
550
+ return 80
551
+ }
552
+ }
553
+
554
+