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

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