dsh-context-compression-improved 0.8.0-beta.2 → 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.
- package/CHANGELOG.md +9 -0
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/advisor-state.js +503 -1
- package/packages/selector/lib/client.d.ts +14 -0
- package/packages/selector/lib/client.js +327 -10
- package/packages/selector/lib/index.js +122 -2
- package/packages/selector/lib/pruner.js +87 -258
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/locales/de.ts +15 -0
- package/packages/selector/src/client/locales/es.ts +15 -0
- package/packages/selector/src/client/locales/fr.ts +15 -0
- package/packages/selector/src/client/locales/it.ts +15 -0
- package/packages/selector/src/client/locales/ja.ts +15 -0
- package/packages/selector/src/client/locales/ko.ts +15 -0
- package/packages/selector/src/client/locales/ru.ts +15 -0
- package/packages/selector/src/client/locales.ts +226 -196
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +126 -124
- package/packages/selector/src/index.ts +547 -411
- package/packages/selector/src/pruner.ts +2505 -2421
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
|
@@ -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
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
// package
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
*
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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
|
+
|