dsh-context-compression-improved 0.6.4 → 0.7.0-beta.1

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 (75) hide show
  1. package/CHANGELOG.ja.md +51 -0
  2. package/CHANGELOG.ko.md +47 -0
  3. package/CHANGELOG.md +72 -0
  4. package/CHANGELOG.zh.md +47 -0
  5. package/README.ja.md +2 -2
  6. package/README.ko.md +2 -2
  7. package/README.md +6 -3
  8. package/README.zh.md +3 -2
  9. package/eslint.config.js +76 -30
  10. package/package.json +164 -162
  11. package/packages/selector/dsh.plugin.json +16 -16
  12. package/packages/selector/lib/client.js +16 -4
  13. package/packages/selector/lib/index.js +92 -1
  14. package/packages/selector/lib/{advisor-state.js → intent-gate.js} +91 -3
  15. package/packages/selector/lib/profiles.d.ts +9 -0
  16. package/packages/selector/lib/pruner.d.ts +59 -0
  17. package/packages/selector/lib/pruner.js +410 -8
  18. package/packages/selector/package.json +114 -114
  19. package/packages/selector/src/client/decode.ts +6 -2
  20. package/packages/selector/src/client/index.ts +213 -232
  21. package/packages/selector/src/client/scope-face.ts +24 -24
  22. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  23. package/packages/selector/src/index.ts +418 -412
  24. package/packages/selector/src/preset-overlay.ts +3 -0
  25. package/packages/selector/src/profiles.ts +30 -10
  26. package/packages/selector/src/pruner/content.ts +1 -1
  27. package/packages/selector/src/pruner/state.ts +7 -0
  28. package/packages/selector/src/pruner.ts +253 -10
  29. package/packages/selector/src/runtime/audit.ts +17 -0
  30. package/packages/selector/src/runtime/config.ts +36 -11
  31. package/packages/selector/src/runtime/reducers.ts +1 -1
  32. package/packages/selector/src/runtime/summary-command.ts +133 -0
  33. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  34. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  35. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  36. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  37. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  38. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  39. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  40. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +4 -1
  41. package/packages/selector/src/runtime/types.ts +12 -0
  42. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  43. package/packages/selector/tests/built/client-artifact.spec.ts +2 -0
  44. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  45. package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
  46. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  47. package/packages/selector/tests/helpers/legacy-namespace.ts +8 -4
  48. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  49. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  50. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  51. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  52. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  53. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -206
  54. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  55. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -206
  56. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  57. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  58. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -233
  59. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  60. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  61. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  62. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  63. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  64. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2736 -2727
  65. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  66. package/packages/selector/tests/settings-seat.client.spec.ts +165 -165
  67. package/packages/selector/tests/standing-generation.host.spec.ts +704 -704
  68. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +18 -2
  69. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  70. package/pnpm-workspace.yaml +1 -1
  71. package/scripts/packed-components-smoke.mjs +2 -0
  72. package/scripts/packed-install-e2e.mjs +1275 -1273
  73. package/scripts/verify-release.mjs +318 -317
  74. package/tsconfig.tests.json +3 -1
  75. package/vitest.config.ts +14 -0
@@ -1,412 +1,418 @@
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
- ContextCompressionSettingsSchema,
10
- DEFAULT_CONTEXT_COMPRESSION_SETTINGS,
11
- } from './runtime/config.ts'
12
-
13
- import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
14
-
15
- // The settings namespace literal and the settings schema are owned by the
16
- // runtime config module. Both were once inlined/replaced here to dodge a
17
- // cross-package dependency (ab2175a: the namespace literal was duplicated and
18
- // the schema was downgraded to `z.any()`); the runtime is now part of this
19
- // package, so the real schema is back and the daily Custom defaults are
20
- // published again through settings.register(). The namespace value is
21
- // unchanged ('context-compression').
22
- import {
23
- decorateAgentPresets,
24
- resolveCompressionModulePaths,
25
- } from './preset-overlay.ts'
26
-
27
- // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
28
- // absolute paths are registered (each is its own (kind, path) table entry) and
29
- // one handler serves both prefixes. The bundled client only probes /api.
30
- const ESTIMATOR_CATALOG_ROUTES = [
31
- '/endpoint/dsh-context-compression-improved/estimator-catalog',
32
- '/api/dsh-context-compression-improved/estimator-catalog',
33
- ] as const
34
-
35
- // Advisory advisor: one read-only report route, dual prefixed like the others.
36
- const ADVISOR_REPORT_ROUTES = [
37
- '/endpoint/dsh-context-compression-improved/advisor-report',
38
- '/api/dsh-context-compression-improved/advisor-report',
39
- ] as const
40
-
41
- /** Minimal face of the agents service: session id → agent (carrying the session). */
42
- interface AgentsServiceLike {
43
- get?(id: unknown): { session?: unknown } | undefined
44
- }
45
-
46
- function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
47
- const agents = readService('agents') as AgentsServiceLike | undefined
48
- return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
49
- }
50
-
51
- function jsonResponse(res: unknown, status: number, body: unknown): void {
52
- const resTyped = res as {
53
- writeHead: (code: number, headers?: Record<string, string>) => void
54
- end: (body?: string) => void
55
- }
56
- resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
57
- resTyped.end(JSON.stringify(body))
58
- }
59
-
60
- /**
61
- * Serve the advisory advisor's read-only report route (same registration
62
- * skeleton as the estimator-catalog route):
63
- *
64
- * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
65
- * the todolist-bound task summary, and the score distribution. Content-free
66
- * by construction: task semantics are LLM-derived summaries, never message
67
- * text, and no score reason or candidate preview is ever returned.
68
- * Unknown session → 404; no agents service → 503. A session whose advisor
69
- * never ran reports nulls and empty arrays, not an error.
70
- */
71
- function registerAdvisorReportRoute(ctx: Context): void {
72
- const readService = (name: string): unknown => {
73
- try {
74
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
75
- } catch {
76
- return undefined
77
- }
78
- }
79
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
80
- console[level](message, ...args)
81
- }
82
-
83
- const getHandler = (req: unknown, res: unknown): void => {
84
- const agents = readService('agents') as AgentsServiceLike | undefined
85
- if (typeof agents?.get !== 'function') {
86
- jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
87
- return
88
- }
89
- let sessionId = ''
90
- try {
91
- const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
92
- sessionId = url.searchParams.get('sessionId') ?? ''
93
- } catch {
94
- // Malformed URL: fall through with the empty sessionId already set.
95
- }
96
- if (sessionId === '') {
97
- jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
98
- return
99
- }
100
- const session = sessionFor(readService, sessionId)
101
- if (session === undefined) {
102
- jsonResponse(res, 404, { ok: false, error: 'unknown session' })
103
- return
104
- }
105
- const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
106
- jsonResponse(res, 200, {
107
- ok: true,
108
- sessionId,
109
- advisor: {
110
- summary: state.summary ?? null,
111
- decay: state.lastDecay?.decay ?? null,
112
- weightedChars: state.lastDecay?.weightedChars ?? null,
113
- decayTurn: state.lastDecay?.turn ?? null,
114
- scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
115
- lowRelevanceSeqs: [...state.recertified.keys()],
116
- // The benefit model's label of the last landed batch — advice, never a
117
- // gate: the batch it describes landed regardless of the band.
118
- lastAdvice: state.lastAdvice === undefined
119
- ? null
120
- : {
121
- band: state.lastAdvice.band,
122
- turn: state.lastAdvice.turn,
123
- itemSeqs: state.lastAdvice.itemSeqs,
124
- recoveredTokens: state.lastAdvice.recoveredTokens,
125
- penaltyTokens: state.lastAdvice.penaltyTokens,
126
- paybackTurns: state.lastAdvice.paybackTurns ?? null,
127
- },
128
- },
129
- })
130
- }
131
-
132
- const register = (webServer: WebServerLike): void => {
133
- const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
134
- const disposers = table
135
- .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
136
- .filter((off): off is () => void => typeof off === 'function')
137
- ctx.effect(
138
- () => () => { for (const off of disposers) off() },
139
- 'contextCompressionSelector.advisor report route',
140
- )
141
- log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
142
- }
143
-
144
- const active = asWebServer(readService('webServer'))
145
- if (active !== undefined) {
146
- register(active)
147
- return
148
- }
149
-
150
- ctx.inject(['webServer'], (injected) => {
151
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
152
- if (webServer === undefined) {
153
- log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
154
- return
155
- }
156
- register(webServer)
157
- })
158
-
159
- log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
160
- }
161
-
162
- /**
163
- * The one service the catalog route actually needs. `llm` and
164
- * `agentDefaultModel` are payload enrichment the handler resolves per request,
165
- * never reasons to withhold the route.
166
- */
167
- const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
168
-
169
- /** The minimal face of the DSH `webServer` service this plugin uses. */
170
- interface WebServerLike {
171
- register(route: {
172
- kind: 'exact'
173
- path: string
174
- handler: (req: unknown, res: unknown) => unknown
175
- }): () => void
176
- }
177
-
178
- /** The estimator-side service the catalog handler enriches its response with. */
179
- interface AgentDefaultModelLike {
180
- /** Current host model-group selection, when the service exposes one. */
181
- currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
182
- }
183
-
184
- function asWebServer(value: unknown): WebServerLike | undefined {
185
- if (typeof value !== 'object' || value === null) return undefined
186
- const candidate = value as { register?: unknown }
187
- // Hand back the service itself -- never a wrapper re-exporting `register`.
188
- // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
189
- // so a detached call makes `this` the wrapper and throws "Cannot read
190
- // properties of undefined (reading 'has')" inside the host, after which the
191
- // route is simply absent and the client sees a bare 404. The 0.1.5 branch
192
- // never had that defect; take this implementation, not the 0.1.2 history's.
193
- return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
194
- }
195
-
196
- /**
197
- * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
198
- * settings card's host-route dropdowns (live provider/model groups from the DSH
199
- * `llm` service plus the effective selection). Best effort: without the
200
- * `webServer` service the plugin keeps working, only the HTTP API is missing.
201
- *
202
- * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
203
- * enrich the response and are resolved per request, so listing them here would
204
- * let an estimator-side service the handler never needs keep the route
205
- * unregistered. That failure is silent by construction — an unsatisfied
206
- * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
207
- * every request falls through to the host 404.
208
- *
209
- * Two channels cover the two arrival orders: a direct lookup catches a
210
- * `webServer` that is already active when the plugin loads, and `ctx.inject`
211
- * catches one that activates later. Both funnel into a single guarded
212
- * registration, because a late-arriving service must not re-register a
213
- * `(kind, path)` the host treats as a composition-contract violation.
214
- */
215
- function registerEstimatorCatalogRoute(ctx: Context): void {
216
- const readService = (name: string): unknown => {
217
- try {
218
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
219
- } catch {
220
- return undefined
221
- }
222
- }
223
- // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
224
- // surfaces no plugin output in the `dsh web` terminal at all — a full boot
225
- // produced zero plugin log lines while the process itself stayed chatty — so
226
- // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
227
- // uses `console.warn` for the same message class on the same host.
228
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
229
- console[level](message, ...args)
230
- }
231
-
232
- let registered = false
233
- const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
234
- if (registered) return
235
- const handler = (_req: unknown, res: unknown): void => {
236
- const resTyped = res as {
237
- writeHead: (code: number, headers?: Record<string, string>) => void
238
- end: (body?: string) => void
239
- }
240
- if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
241
- const llm = readService('llm')
242
- const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
243
- const deps: EstimatorCatalogDeps = {
244
- ...(llm === undefined
245
- ? {}
246
- : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
247
- ...(typeof defaults?.currentSelection === 'function'
248
- ? { currentSelection: () => defaults.currentSelection?.() }
249
- : {}),
250
- }
251
- buildEstimatorCatalog(deps).then(
252
- catalog => {
253
- resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
254
- resTyped.end(JSON.stringify({ ok: true, ...catalog }))
255
- },
256
- (error: unknown) => {
257
- resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
258
- resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
259
- },
260
- )
261
- }
262
- try {
263
- const disposers = ESTIMATOR_CATALOG_ROUTES
264
- .map(path => webServer.register({ kind: 'exact', path, handler }))
265
- .filter((off): off is () => void => typeof off === 'function')
266
- registered = true
267
- ctx.effect(
268
- () => () => { for (const off of disposers) off() },
269
- 'contextCompressionSelector.estimator-catalog route',
270
- )
271
- log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
272
- } catch (error) {
273
- log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
274
- }
275
- }
276
-
277
- const active = asWebServer(readService('webServer'))
278
- if (active !== undefined) {
279
- register(active, 'direct')
280
- if (registered) return
281
- }
282
-
283
- ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
284
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
285
- if (webServer === undefined) {
286
- log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
287
- return
288
- }
289
- register(webServer, 'inject')
290
- })
291
-
292
- log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
293
- }
294
-
295
- /**
296
- * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
297
- * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
298
- */
299
- function readVolatileValue<T>(value: T | { get(): T } | undefined): T | undefined {
300
- if (value !== null && typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function') {
301
- return (value as { get(): T }).get()
302
- }
303
- return value as T | undefined
304
- }
305
-
306
- /** The compression settings document carried by this row's composition entry. */
307
- function readCompressionDoc(config: Config | undefined): ContextCompressionSettings | undefined {
308
- return readVolatileValue(config?.settings)
309
- }
310
-
311
- /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
312
- export interface Config {
313
- /** Add the canonical compression stack to every non-Minimal preset. */
314
- presetOverlay?: boolean
315
- /**
316
- * Register the estimator-catalog HTTP route on this row.
317
- *
318
- * The standalone Bundle patch sets this on its own row (which declares
319
- * `inject: [webServer]`), so profiles without a host web server never mount a
320
- * row that could only announce a pending route. The row-level `inject` is
321
- * belt-and-braces: `dsh-host-webserver.register` performs no authorization
322
- * check and `ctx.get(name)` only asks whether the providing fiber is active,
323
- * so the two-channel registration inside this function is what actually
324
- * covers both arrival orders.
325
- */
326
- estimatorCatalogRoute?: boolean
327
- /**
328
- * Register the advisory advisor's read-only HTTP report route (decay
329
- * figure, task summary, score distribution, last benefit-model advice).
330
- * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
331
- * itself stays off until the user turns it on through the
332
- * `presetOptions.advisor*` settings keys.
333
- */
334
- advisorReportRoute?: boolean
335
- /**
336
- * 0.1.7: the compression settings document as ONE `.volatile()` whole-object
337
- * field (the old dedicated namespace has no declarative equivalent). The
338
- * browser selector writes it through `configForms`; the runtime reads the
339
- * dereferenced value. Loose section schemas keep unknown keys — the strict
340
- * validation stays in `decodeSettings` (client) and the runtime resolver.
341
- */
342
- settings?: ContextCompressionSettings
343
- }
344
-
345
- /** Loader validation for the standalone Bundle opt-in. */
346
- export const Config = z.object({
347
- presetOverlay: z.boolean().default(false),
348
- estimatorCatalogRoute: z.boolean().default(false),
349
- advisorReportRoute: z.boolean().default(false),
350
- // The daily Custom defaults ride the field's schema default so every
351
- // composition resolves a complete document without a stored user layer.
352
- settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile(),
353
- }) as unknown as z<Config>
354
-
355
- /** Register the persisted default read by the currently mounted root pruner. */
356
- export function apply(ctx: Context, config: Config = {}): void {
357
- // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
358
- // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
359
- // here is completely invisible and looks exactly like a plugin that loaded
360
- // and quietly did nothing. Report it to a sink the host shows, then re-throw
361
- // unchanged: behaviour is untouched, only observability is restored.
362
- try {
363
- // The settings card's host-route dropdowns read this route; it lives on the
364
- // top-level plugin fiber, not inside the isolated `toolResultPruner`
365
- // service, because the route is host-wide rather than per-pruner-instance.
366
- if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
367
-
368
- // Advisory advisor: read-only decay/score/advice report (opt-in).
369
- if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
370
-
371
- if (config.presetOverlay !== true) return
372
-
373
- ctx.inject(['agentPresets'], (presetsCtx) => {
374
- const installation = decorateAgentPresets(
375
- presetsCtx.agentPresets,
376
- {
377
- modules: resolveCompressionModulePaths(),
378
- excludedPresetIds: ['minimal'],
379
- autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(config, presetsCtx),
380
- },
381
- )
382
- presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
383
- })
384
- } catch (error) {
385
- console.error('context-compression selector apply failed: %o', error)
386
- throw error
387
- }
388
- }
389
-
390
- /**
391
- * Read the current Auto Compact threshold ratio at composition time. Settings
392
- * values are revalidated here, and any unreadable value falls back to the 80%
393
- * default rather than blocking preset composition.
394
- */
395
- function resolveAutoCompactThresholdPercent(config: Config | undefined, presetsCtx?: Context): number {
396
- // 0.1.7: the volatile entry field is authoritative; the legacy per-namespace
397
- // read stays as a fallback so a host that still serves the old service shape
398
- // keeps working (test hosts do exactly that).
399
- const raw = readCompressionDoc(config)
400
- ?? (presetsCtx?.get('settings') as { get?: (ns: never) => unknown } | undefined)
401
- ?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
402
- try {
403
- const record = structuredClone(raw) as Record<string, unknown> | undefined
404
- const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
405
- const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
406
- return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
407
- } catch {
408
- return 80
409
- }
410
- }
411
-
412
-
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
+ import { registerSummaryCommand } from './runtime/summary-command.ts'
14
+
15
+ // The settings namespace literal and the settings schema are owned by the
16
+ // runtime config module. Both were once inlined/replaced here to dodge a
17
+ // cross-package dependency (ab2175a: the namespace literal was duplicated and
18
+ // the schema was downgraded to `z.any()`); the runtime is now part of this
19
+ // package, so the real schema is back and the daily Custom defaults are
20
+ // published again through settings.register(). The namespace value is
21
+ // unchanged ('context-compression').
22
+ import {
23
+ decorateAgentPresets,
24
+ resolveCompressionModulePaths,
25
+ } from './preset-overlay.ts'
26
+
27
+ // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
28
+ // absolute paths are registered (each is its own (kind, path) table entry) and
29
+ // one handler serves both prefixes. The bundled client only probes /api.
30
+ const ESTIMATOR_CATALOG_ROUTES = [
31
+ '/endpoint/dsh-context-compression-improved/estimator-catalog',
32
+ '/api/dsh-context-compression-improved/estimator-catalog',
33
+ ] as const
34
+
35
+ // Advisory advisor: one read-only report route, dual prefixed like the others.
36
+ const ADVISOR_REPORT_ROUTES = [
37
+ '/endpoint/dsh-context-compression-improved/advisor-report',
38
+ '/api/dsh-context-compression-improved/advisor-report',
39
+ ] as const
40
+
41
+ /** Minimal face of the agents service: session id → agent (carrying the session). */
42
+ interface AgentsServiceLike {
43
+ get?(id: unknown): { session?: unknown } | undefined
44
+ }
45
+
46
+ function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
47
+ const agents = readService('agents') as AgentsServiceLike | undefined
48
+ return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
49
+ }
50
+
51
+ function jsonResponse(res: unknown, status: number, body: unknown): void {
52
+ const resTyped = res as {
53
+ writeHead: (code: number, headers?: Record<string, string>) => void
54
+ end: (body?: string) => void
55
+ }
56
+ resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
57
+ resTyped.end(JSON.stringify(body))
58
+ }
59
+
60
+ /**
61
+ * Serve the advisory advisor's read-only report route (same registration
62
+ * skeleton as the estimator-catalog route):
63
+ *
64
+ * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
65
+ * the todolist-bound task summary, and the score distribution. Content-free
66
+ * by construction: task semantics are LLM-derived summaries, never message
67
+ * text, and no score reason or candidate preview is ever returned.
68
+ * Unknown session → 404; no agents service → 503. A session whose advisor
69
+ * never ran reports nulls and empty arrays, not an error.
70
+ */
71
+ function registerAdvisorReportRoute(ctx: Context): void {
72
+ const readService = (name: string): unknown => {
73
+ try {
74
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
75
+ } catch {
76
+ return undefined
77
+ }
78
+ }
79
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
80
+ console[level](message, ...args)
81
+ }
82
+
83
+ const getHandler = (req: unknown, res: unknown): void => {
84
+ const agents = readService('agents') as AgentsServiceLike | undefined
85
+ if (typeof agents?.get !== 'function') {
86
+ jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
87
+ return
88
+ }
89
+ let sessionId = ''
90
+ try {
91
+ const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
92
+ sessionId = url.searchParams.get('sessionId') ?? ''
93
+ } catch {
94
+ // Malformed URL: fall through with the empty sessionId already set.
95
+ }
96
+ if (sessionId === '') {
97
+ jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
98
+ return
99
+ }
100
+ const session = sessionFor(readService, sessionId)
101
+ if (session === undefined) {
102
+ jsonResponse(res, 404, { ok: false, error: 'unknown session' })
103
+ return
104
+ }
105
+ const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
106
+ jsonResponse(res, 200, {
107
+ ok: true,
108
+ sessionId,
109
+ advisor: {
110
+ summary: state.summary ?? null,
111
+ decay: state.lastDecay?.decay ?? null,
112
+ weightedChars: state.lastDecay?.weightedChars ?? null,
113
+ decayTurn: state.lastDecay?.turn ?? null,
114
+ scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
115
+ lowRelevanceSeqs: [...state.recertified.keys()],
116
+ // The benefit model's label of the last landed batch — advice, never a
117
+ // gate: the batch it describes landed regardless of the band.
118
+ lastAdvice: state.lastAdvice === undefined
119
+ ? null
120
+ : {
121
+ band: state.lastAdvice.band,
122
+ turn: state.lastAdvice.turn,
123
+ itemSeqs: state.lastAdvice.itemSeqs,
124
+ recoveredTokens: state.lastAdvice.recoveredTokens,
125
+ penaltyTokens: state.lastAdvice.penaltyTokens,
126
+ paybackTurns: state.lastAdvice.paybackTurns ?? null,
127
+ },
128
+ },
129
+ })
130
+ }
131
+
132
+ const register = (webServer: WebServerLike): void => {
133
+ const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
134
+ const disposers = table
135
+ .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
136
+ .filter((off): off is () => void => typeof off === 'function')
137
+ ctx.effect(
138
+ () => () => { for (const off of disposers) off() },
139
+ 'contextCompressionSelector.advisor report route',
140
+ )
141
+ log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
142
+ }
143
+
144
+ const active = asWebServer(readService('webServer'))
145
+ if (active !== undefined) {
146
+ register(active)
147
+ return
148
+ }
149
+
150
+ ctx.inject(['webServer'], (injected) => {
151
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
152
+ if (webServer === undefined) {
153
+ log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
154
+ return
155
+ }
156
+ register(webServer)
157
+ })
158
+
159
+ log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
160
+ }
161
+
162
+ /**
163
+ * The one service the catalog route actually needs. `llm` and
164
+ * `agentDefaultModel` are payload enrichment the handler resolves per request,
165
+ * never reasons to withhold the route.
166
+ */
167
+ const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
168
+
169
+ /** The minimal face of the DSH `webServer` service this plugin uses. */
170
+ interface WebServerLike {
171
+ register(route: {
172
+ kind: 'exact'
173
+ path: string
174
+ handler: (req: unknown, res: unknown) => unknown
175
+ }): () => void
176
+ }
177
+
178
+ /** The estimator-side service the catalog handler enriches its response with. */
179
+ interface AgentDefaultModelLike {
180
+ /** Current host model-group selection, when the service exposes one. */
181
+ currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
182
+ }
183
+
184
+ function asWebServer(value: unknown): WebServerLike | undefined {
185
+ if (typeof value !== 'object' || value === null) return undefined
186
+ const candidate = value as { register?: unknown }
187
+ // Hand back the service itself -- never a wrapper re-exporting `register`.
188
+ // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
189
+ // so a detached call makes `this` the wrapper and throws "Cannot read
190
+ // properties of undefined (reading 'has')" inside the host, after which the
191
+ // route is simply absent and the client sees a bare 404. The 0.1.5 branch
192
+ // never had that defect; take this implementation, not the 0.1.2 history's.
193
+ return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
194
+ }
195
+
196
+ /**
197
+ * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
198
+ * settings card's host-route dropdowns (live provider/model groups from the DSH
199
+ * `llm` service plus the effective selection). Best effort: without the
200
+ * `webServer` service the plugin keeps working, only the HTTP API is missing.
201
+ *
202
+ * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
203
+ * enrich the response and are resolved per request, so listing them here would
204
+ * let an estimator-side service the handler never needs keep the route
205
+ * unregistered. That failure is silent by construction — an unsatisfied
206
+ * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
207
+ * every request falls through to the host 404.
208
+ *
209
+ * Two channels cover the two arrival orders: a direct lookup catches a
210
+ * `webServer` that is already active when the plugin loads, and `ctx.inject`
211
+ * catches one that activates later. Both funnel into a single guarded
212
+ * registration, because a late-arriving service must not re-register a
213
+ * `(kind, path)` the host treats as a composition-contract violation.
214
+ */
215
+ function registerEstimatorCatalogRoute(ctx: Context): void {
216
+ const readService = (name: string): unknown => {
217
+ try {
218
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
219
+ } catch {
220
+ return undefined
221
+ }
222
+ }
223
+ // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
224
+ // surfaces no plugin output in the `dsh web` terminal at all — a full boot
225
+ // produced zero plugin log lines while the process itself stayed chatty — so
226
+ // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
227
+ // uses `console.warn` for the same message class on the same host.
228
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
229
+ console[level](message, ...args)
230
+ }
231
+
232
+ let registered = false
233
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
234
+ if (registered) return
235
+ const handler = (_req: unknown, res: unknown): void => {
236
+ const resTyped = res as {
237
+ writeHead: (code: number, headers?: Record<string, string>) => void
238
+ end: (body?: string) => void
239
+ }
240
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
241
+ const llm = readService('llm')
242
+ const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
243
+ const deps: EstimatorCatalogDeps = {
244
+ ...(llm === undefined
245
+ ? {}
246
+ : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
247
+ ...(typeof defaults?.currentSelection === 'function'
248
+ ? { currentSelection: () => defaults.currentSelection?.() }
249
+ : {}),
250
+ }
251
+ buildEstimatorCatalog(deps).then(
252
+ catalog => {
253
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
254
+ resTyped.end(JSON.stringify({ ok: true, ...catalog }))
255
+ },
256
+ (error: unknown) => {
257
+ resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
258
+ resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
259
+ },
260
+ )
261
+ }
262
+ try {
263
+ const disposers = ESTIMATOR_CATALOG_ROUTES
264
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
265
+ .filter((off): off is () => void => typeof off === 'function')
266
+ registered = true
267
+ ctx.effect(
268
+ () => () => { for (const off of disposers) off() },
269
+ 'contextCompressionSelector.estimator-catalog route',
270
+ )
271
+ log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
272
+ } catch (error) {
273
+ log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
274
+ }
275
+ }
276
+
277
+ const active = asWebServer(readService('webServer'))
278
+ if (active !== undefined) {
279
+ register(active, 'direct')
280
+ if (registered) return
281
+ }
282
+
283
+ ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
284
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
285
+ if (webServer === undefined) {
286
+ log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
287
+ return
288
+ }
289
+ register(webServer, 'inject')
290
+ })
291
+
292
+ log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
293
+ }
294
+
295
+ /**
296
+ * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
297
+ * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
298
+ */
299
+ function readVolatileValue<T>(value: T | { get(): T } | undefined): T | undefined {
300
+ if (value !== null && typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function') {
301
+ return (value as { get(): T }).get()
302
+ }
303
+ return value as T | undefined
304
+ }
305
+
306
+ /** The compression settings document carried by this row's composition entry. */
307
+ function readCompressionDoc(config: Config | undefined): ContextCompressionSettings | undefined {
308
+ return readVolatileValue(config?.settings)
309
+ }
310
+
311
+ /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
312
+ export interface Config {
313
+ /** Add the canonical compression stack to every non-Minimal preset. */
314
+ presetOverlay?: boolean
315
+ /**
316
+ * Register the estimator-catalog HTTP route on this row.
317
+ *
318
+ * The standalone Bundle patch sets this on its own row (which declares
319
+ * `inject: [webServer]`), so profiles without a host web server never mount a
320
+ * row that could only announce a pending route. The row-level `inject` is
321
+ * belt-and-braces: `dsh-host-webserver.register` performs no authorization
322
+ * check and `ctx.get(name)` only asks whether the providing fiber is active,
323
+ * so the two-channel registration inside this function is what actually
324
+ * covers both arrival orders.
325
+ */
326
+ estimatorCatalogRoute?: boolean
327
+ /**
328
+ * Register the advisory advisor's read-only HTTP report route (decay
329
+ * figure, task summary, score distribution, last benefit-model advice).
330
+ * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
331
+ * itself stays off until the user turns it on through the
332
+ * `presetOptions.advisor*` settings keys.
333
+ */
334
+ advisorReportRoute?: boolean
335
+ /**
336
+ * 0.1.7: the compression settings document as ONE `.volatile()` whole-object
337
+ * field (the old dedicated namespace has no declarative equivalent). The
338
+ * browser selector writes it through `configForms`; the runtime reads the
339
+ * dereferenced value. Loose section schemas keep unknown keys — the strict
340
+ * validation stays in `decodeSettings` (client) and the runtime resolver.
341
+ */
342
+ settings?: ContextCompressionSettings
343
+ }
344
+
345
+ /** Loader validation for the standalone Bundle opt-in. */
346
+ export const Config = z.object({
347
+ presetOverlay: z.boolean().default(false),
348
+ estimatorCatalogRoute: z.boolean().default(false),
349
+ advisorReportRoute: z.boolean().default(false),
350
+ // The daily Custom defaults ride the field's schema default so every
351
+ // composition resolves a complete document without a stored user layer.
352
+ settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile(),
353
+ }) as unknown as z<Config>
354
+
355
+ /** Register the persisted default read by the currently mounted root pruner. */
356
+ export function apply(ctx: Context, config: Config = {}): void {
357
+ // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
358
+ // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
359
+ // here is completely invisible and looks exactly like a plugin that loaded
360
+ // and quietly did nothing. Report it to a sink the host shows, then re-throw
361
+ // unchanged: behaviour is untouched, only observability is restored.
362
+ try {
363
+ // The settings card's host-route dropdowns read this route; it lives on the
364
+ // top-level plugin fiber, not inside the isolated `toolResultPruner`
365
+ // service, because the route is host-wide rather than per-pruner-instance.
366
+ if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
367
+
368
+ // Advisory advisor: read-only decay/score/advice report (opt-in).
369
+ if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
370
+
371
+ // Turn-tail intent summary: `/ctx-summary off|on|status`. The command is
372
+ // free to register and stays quiet on hosts without the commands
373
+ // registry; the capability itself is gated by the frozen `intentSummary`
374
+ // setting plus the session-scoped override this command controls.
375
+ registerSummaryCommand(ctx)
376
+
377
+ if (config.presetOverlay !== true) return
378
+
379
+ ctx.inject(['agentPresets'], (presetsCtx) => {
380
+ const installation = decorateAgentPresets(
381
+ presetsCtx.agentPresets,
382
+ {
383
+ modules: resolveCompressionModulePaths(),
384
+ excludedPresetIds: ['minimal'],
385
+ autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(config, presetsCtx),
386
+ },
387
+ )
388
+ presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
389
+ })
390
+ } catch (error) {
391
+ console.error('context-compression selector apply failed: %o', error)
392
+ throw error
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Read the current Auto Compact threshold ratio at composition time. Settings
398
+ * values are revalidated here, and any unreadable value falls back to the 80%
399
+ * default rather than blocking preset composition.
400
+ */
401
+ function resolveAutoCompactThresholdPercent(config: Config | undefined, presetsCtx?: Context): number {
402
+ // 0.1.7: the volatile entry field is authoritative; the legacy per-namespace
403
+ // read stays as a fallback so a host that still serves the old service shape
404
+ // keeps working (test hosts do exactly that).
405
+ const raw = readCompressionDoc(config)
406
+ ?? (presetsCtx?.get('settings') as { get?: (ns: never) => unknown } | undefined)
407
+ ?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
408
+ try {
409
+ const record = structuredClone(raw) as Record<string, unknown> | undefined
410
+ const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
411
+ const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
412
+ return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
413
+ } catch {
414
+ return 80
415
+ }
416
+ }
417
+
418
+