dsh-context-compression-improved 0.9.3 → 0.9.7

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 (66) hide show
  1. package/README.de.md +3 -3
  2. package/README.es.md +3 -3
  3. package/README.fr.md +3 -3
  4. package/README.it.md +3 -3
  5. package/README.ja.md +16 -3
  6. package/README.ko.md +16 -3
  7. package/README.md +16 -3
  8. package/README.ru.md +3 -3
  9. package/README.zh.md +16 -3
  10. package/assets/board.png +0 -0
  11. package/assets/context.png +0 -0
  12. package/docs/installation.de.md +2 -2
  13. package/docs/installation.es.md +2 -2
  14. package/docs/installation.fr.md +2 -2
  15. package/docs/installation.it.md +2 -2
  16. package/docs/installation.ja.md +2 -2
  17. package/docs/installation.ko.md +2 -2
  18. package/docs/installation.md +2 -2
  19. package/docs/installation.ru.md +2 -2
  20. package/docs/installation.zh.md +2 -2
  21. package/package.json +7 -6
  22. package/packages/selector/dsh.plugin.json +2 -2
  23. package/packages/selector/lib/client.d.ts +1 -0
  24. package/packages/selector/lib/client.js +63 -10
  25. package/packages/selector/lib/config.js +71 -7
  26. package/packages/selector/lib/index.js +145 -20
  27. package/packages/selector/lib/pruner.d.ts +158 -107
  28. package/packages/selector/lib/pruner.js +332 -22
  29. package/packages/selector/lib/tail-trim.js +25 -2
  30. package/packages/selector/package.json +22 -21
  31. package/packages/selector/src/client/index.ts +29 -2
  32. package/packages/selector/src/client/locales/de.ts +1 -0
  33. package/packages/selector/src/client/locales/es.ts +1 -0
  34. package/packages/selector/src/client/locales/fr.ts +1 -0
  35. package/packages/selector/src/client/locales/it.ts +1 -0
  36. package/packages/selector/src/client/locales/ja.ts +1 -0
  37. package/packages/selector/src/client/locales/ko.ts +1 -0
  38. package/packages/selector/src/client/locales/ru.ts +1 -0
  39. package/packages/selector/src/client/locales.ts +2 -0
  40. package/packages/selector/src/client/monitor-fab.ts +19 -4
  41. package/packages/selector/src/compat/llm-messages.ts +50 -0
  42. package/packages/selector/src/index.ts +27 -0
  43. package/packages/selector/src/preset-overlay.ts +145 -22
  44. package/packages/selector/src/pruner/content.ts +1 -1
  45. package/packages/selector/src/pruner/state.ts +4 -0
  46. package/packages/selector/src/pruner.ts +109 -16
  47. package/packages/selector/src/runtime/config.ts +1 -1
  48. package/packages/selector/src/runtime/reducers.ts +81 -1
  49. package/packages/selector/src/runtime/retrieve.ts +4 -3
  50. package/packages/selector/src/runtime/savings-projection.ts +226 -0
  51. package/packages/selector/src/runtime/savings.ts +83 -3
  52. package/packages/selector/src/runtime/tail-trim.ts +2 -1
  53. package/packages/selector/tests/public/package-contract.client.spec.ts +4 -4
  54. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  55. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  56. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
  57. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  58. package/packages/selector/tests/runtime/savings.spec.ts +22 -3
  59. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  60. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
  61. package/pnpm-workspace.yaml +6 -0
  62. package/screenshots.json +6 -0
  63. package/scripts/hosts.mjs +5 -2
  64. package/scripts/packed-install-e2e.mjs +19 -3
  65. package/scripts/sync-hosts.mjs +2 -2
  66. package/scripts/verify-release.mjs +6 -6
@@ -81,7 +81,14 @@ function sameCustomPolicy(
81
81
  }
82
82
 
83
83
  export function apply(ctx: ClientContext): void {
84
- ctx.locale.register(NS, { zh, en })
84
+ // 幂等:本插件可被两行同 name 挂载(bundle 行 + estimator-catalog 行,宿主侧靠
85
+ // 引用计数去重压缩栈),客户端 apply 会被调用多次。首注册必须容错,否则第二次
86
+ // 抛 'locale namespace ... already has locale "zh"' 会使整个客户端同步失败。
87
+ try {
88
+ ctx.locale.register(NS, { zh, en })
89
+ } catch (error) {
90
+ console.warn('[dsh-context-compression-improved] locale 默认包(zh/en) 已注册,跳过:', error)
91
+ }
85
92
  // de/es/fr/it/ja/ko/ru are not host built-ins (`BuiltInLocaleId` is zh|en), so
86
93
  // their dictionaries ride the single-locale untyped register overload, and each
87
94
  // needs an `addLanguage` definition to become selectable — the catalog owns
@@ -125,6 +132,8 @@ let configFormsHandle: ConfigFormsHandle | undefined
125
132
 
126
133
  /** Last monitorPanel.enabled seen through whichever scope is current (FAB 读数缓存). */
127
134
  let monitorPanelEnabledCache = false
135
+ /** configForms 臂是否已经成功读过一次文档(FAB 读数是否可信)。 */
136
+ let nativeMonitorReady = false
128
137
 
129
138
  /** 浮动监控面板(FAB): body 级幂等单例。enabled 读数走双臂 scope 的投影缓存。 */
130
139
  let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
@@ -161,7 +170,9 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
161
170
  bridgeScope.refresh()
162
171
  const bridgeReadEnabled = (): boolean =>
163
172
  decodeSettings(bridgeScope.getSnapshot().value)?.monitorPanel?.enabled ?? false
164
- readMonitorPanelEnabled = (): boolean => (configFormsHandle === undefined ? bridgeReadEnabled() : monitorPanelEnabledCache)
173
+ readMonitorPanelEnabled = (): boolean => (configFormsHandle !== undefined && nativeMonitorReady
174
+ ? monitorPanelEnabledCache
175
+ : bridgeReadEnabled())
165
176
  try {
166
177
  ctx.inject(['configForms'], (configFormsArg) => {
167
178
  // cordis passes the service's OWNER CONTEXT to inject callbacks (the
@@ -175,6 +186,21 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
175
186
  const svc = (configFormsArg as { configForms?: unknown } | undefined)?.configForms
176
187
  const face = (svc !== undefined && svc !== null ? svc : configFormsArg) as unknown as ConfigFormsHandle
177
188
  configFormsHandle = typeof face?.get === 'function' ? face : undefined
189
+ // 预热 FAB 读数:不看设置面板也要能读到 monitorPanel.enabled。此前缓存只
190
+ // 在设置分节渲染时刷新,导致浮动监控球必须先打开设置才出现。
191
+ if (configFormsHandle !== undefined) {
192
+ try {
193
+ const form = configFormsHandle.get(ENTRY_ID)
194
+ const refresh = (): void => {
195
+ monitorPanelEnabledCache = decodeSettings(form.getSnapshot().value?.settings)?.monitorPanel?.enabled ?? false
196
+ nativeMonitorReady = true
197
+ }
198
+ refresh()
199
+ form.subscribe(() => { try { refresh() } catch { /* ignore */ } })
200
+ } catch (error) {
201
+ console.warn('[dsh-context-compression-improved] FAB 读数预热失败(沿用桥面):', error)
202
+ }
203
+ }
178
204
  })
179
205
  } catch (error) {
180
206
  console.warn('[dsh-context-compression-improved] configForms 臂挂载失败(桥面继续服务):', error)
@@ -212,6 +238,7 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
212
238
  }
213
239
  }
214
240
  monitorPanelEnabledCache = projected.value?.monitorPanel?.enabled ?? false
241
+ nativeMonitorReady = true
215
242
  return projected
216
243
  },
217
244
  subscribe: (listener) => form.subscribe(listener),
@@ -80,6 +80,7 @@ export const de = {
80
80
  'monitor.panel.cost': 'Kosten (ist / gespart gesch.)',
81
81
  'monitor.panel.intent': 'Intent-Zusammenfassung',
82
82
  'monitor.panel.overrideHint': 'Sitzungs-Übersteuerung',
83
+ 'monitor.panel.overridePrefix': 'Sitzungs-Übersteuerung',
83
84
  'monitor.panel.resume': 'Fortsetzen',
84
85
  'monitor.panel.disable': 'Deaktivieren',
85
86
  'monitor.panel.stateOn': 'ein',
@@ -80,6 +80,7 @@ export const es = {
80
80
  'monitor.panel.cost': 'Coste (real / ahorro est.)',
81
81
  'monitor.panel.intent': 'Resumen de intención',
82
82
  'monitor.panel.overrideHint': 'Invalidación de sesión',
83
+ 'monitor.panel.overridePrefix': 'Invalidación de sesión',
83
84
  'monitor.panel.resume': 'Reanudar',
84
85
  'monitor.panel.disable': 'Desactivar',
85
86
  'monitor.panel.stateOn': 'sí',
@@ -80,6 +80,7 @@ export const fr = {
80
80
  'monitor.panel.cost': 'Coût (réel / écon. est.)',
81
81
  'monitor.panel.intent': 'Résumé d\'intention',
82
82
  'monitor.panel.overrideHint': 'Priorité de session',
83
+ 'monitor.panel.overridePrefix': 'Priorité de session',
83
84
  'monitor.panel.resume': 'Reprendre',
84
85
  'monitor.panel.disable': 'Désactiver',
85
86
  'monitor.panel.stateOn': 'activé',
@@ -80,6 +80,7 @@ export const it = {
80
80
  'monitor.panel.cost': 'Costo (effettivo / stimo)',
81
81
  'monitor.panel.intent': 'Riepilogo di intento',
82
82
  'monitor.panel.overrideHint': 'Override di sessione',
83
+ 'monitor.panel.overridePrefix': 'Override di sessione',
83
84
  'monitor.panel.resume': 'Riprendi',
84
85
  'monitor.panel.disable': 'Disattiva',
85
86
  'monitor.panel.stateOn': 'on',
@@ -80,6 +80,7 @@ export const ja = {
80
80
  'monitor.panel.cost': 'コスト(実績 / 節約概算)',
81
81
  'monitor.panel.intent': 'インテント要約',
82
82
  'monitor.panel.overrideHint': 'セッション上書き',
83
+ 'monitor.panel.overridePrefix': 'セッション上書き',
83
84
  'monitor.panel.resume': '再開',
84
85
  'monitor.panel.disable': '停止',
85
86
  'monitor.panel.stateOn': 'オン',
@@ -80,6 +80,7 @@ export const ko = {
80
80
  'monitor.panel.cost': '비용 (실제 / 절감 추정)',
81
81
  'monitor.panel.intent': '인텐트 요약',
82
82
  'monitor.panel.overrideHint': '세션 재정의',
83
+ 'monitor.panel.overridePrefix': '세션 재정의',
83
84
  'monitor.panel.resume': '재개',
84
85
  'monitor.panel.disable': '중지',
85
86
  'monitor.panel.stateOn': '켬',
@@ -80,6 +80,7 @@ export const ru = {
80
80
  'monitor.panel.cost': 'Стоимость (факт / эконом. оценка)',
81
81
  'monitor.panel.intent': 'Итог намерения',
82
82
  'monitor.panel.overrideHint': 'Приоритет сессии',
83
+ 'monitor.panel.overridePrefix': 'Приоритет сессии',
83
84
  'monitor.panel.resume': 'Возобновить',
84
85
  'monitor.panel.disable': 'Отключить',
85
86
  'monitor.panel.stateOn': 'вкл',
@@ -78,6 +78,7 @@ export const zh = {
78
78
  'monitor.panel.cost': '成本(实际 / 省估)',
79
79
  'monitor.panel.intent': '意图摘要',
80
80
  'monitor.panel.overrideHint': '会话覆盖',
81
+ 'monitor.panel.overridePrefix': '会话覆盖',
81
82
  'monitor.panel.resume': '恢复',
82
83
  'monitor.panel.disable': '停用',
83
84
  'monitor.panel.stateOn': '开',
@@ -222,6 +223,7 @@ export const en = {
222
223
  'monitor.panel.cost': 'Cost (actual / saved est.)',
223
224
  'monitor.panel.intent': 'Intent summary',
224
225
  'monitor.panel.overrideHint': 'Session override',
226
+ 'monitor.panel.overridePrefix': 'Session override',
225
227
  'monitor.panel.resume': 'Resume',
226
228
  'monitor.panel.disable': 'Disable',
227
229
  'monitor.panel.stateOn': 'on',
@@ -156,15 +156,19 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
156
156
  let active = false;
157
157
  let moved = false;
158
158
  let origin = { x: 0, y: 0 };
159
+ let startPos = { x: 0, y: 0 };
159
160
  el.addEventListener('pointerdown', (e) => {
160
161
  active = true;
161
162
  moved = false;
162
163
  origin = { x: e.clientX, y: e.clientY };
164
+ startPos = { x: pos.x, y: pos.y };
163
165
  el.setPointerCapture(e.pointerId);
164
166
  });
165
167
  el.addEventListener('pointermove', (e) => {
166
168
  if (!active) return;
167
- const next = clamp({ x: pos.x + e.clientX - origin.x, y: pos.y + e.clientY - origin.y });
169
+ // 以「按下时的位置」为基准 + 指针相对按下点的总位移。若把每帧更新后的 pos
170
+ // 再当基准叠加总位移,位移会被重复累加,浮窗一路被甩到边缘(只能贴边)。
171
+ const next = clamp({ x: startPos.x + (e.clientX - origin.x), y: startPos.y + (e.clientY - origin.y) });
168
172
  if (Math.abs(next.x - pos.x) > 2 || Math.abs(next.y - pos.y) > 2) moved = true;
169
173
  pos = key === 'fab' ? next : pos;
170
174
  if (key === 'fab') place();
@@ -212,10 +216,19 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
212
216
 
213
217
  const fmtTokens = (n: unknown): string => num(n).toLocaleString('en-US');
214
218
 
219
+ // 面板主数字口径:优先精确 tokenizer(exact);exact 为 0(如无内置 tokenizer 的
220
+ // Qwen 路由)时退回估算(chars/4)并标 "est"。两口径绝不合并成一个数。
221
+ const lead = (exact: unknown, estimated: unknown): { v: number; est: boolean } => {
222
+ const ex = num(exact);
223
+ const es = num(estimated);
224
+ return ex !== 0 ? { v: ex, est: false } : { v: es, est: es !== 0 };
225
+ };
226
+
215
227
  const render = (snap: MonitorSnapshotPayload): void => {
216
228
  const net = num(snap.net?.exact) + num(snap.net?.estimated);
217
229
  const netEl = panel.querySelector('[data-net]') as HTMLElement;
218
- netEl.textContent = `${fmtTokens(snap.net?.exact)}${num(snap.net?.estimated) > 0 ? ` (+${fmtTokens(snap.net?.estimated)} est)` : ''}`;
230
+ const netLead = lead(snap.net?.exact, snap.net?.estimated);
231
+ netEl.textContent = netLead.est ? `${fmtTokens(netLead.v)} est` : fmtTokens(netLead.v);
219
232
  netEl.classList.toggle('neg', net < 0);
220
233
  const suggest = snap.suggestion?.suggest === true;
221
234
  fab.classList.toggle('lit', suggest || net < 0);
@@ -229,8 +242,10 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
229
242
  } else {
230
243
  hint.classList.remove('show');
231
244
  }
232
- (panel.querySelector('[data-gross]') as HTMLElement).textContent = fmtTokens(snap.gross?.exact);
233
- (panel.querySelector('[data-offsets]') as HTMLElement).textContent = `-${fmtTokens(snap.offsets?.exact)}`;
245
+ const grossLead = lead(snap.gross?.exact, snap.gross?.estimated);
246
+ (panel.querySelector('[data-gross]') as HTMLElement).textContent = grossLead.est ? `${fmtTokens(grossLead.v)} est` : fmtTokens(grossLead.v);
247
+ const offLead = lead(snap.offsets?.exact, snap.offsets?.estimated);
248
+ (panel.querySelector('[data-offsets]') as HTMLElement).textContent = offLead.est ? `-${fmtTokens(offLead.v)} est` : `-${fmtTokens(offLead.v)}`;
234
249
  const ctxBar = panel.querySelector('[data-ctxbar]') as HTMLElement;
235
250
  const ctxPct = panel.querySelector('[data-ctxpct]') as HTMLElement;
236
251
  const ctxPctNum = typeof snap.context?.pct === 'number' ? snap.context.pct : null;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Local stand-ins for the two `@deepseek-ai/dsh-llm` message factories the
3
+ * pruner and TailTrim hot paths need. The package is an OPTIONAL peer — the
4
+ * official-clone profile in the packed-install e2e (and any host line that
5
+ * stops shipping it into a plugin's module graph) does not resolve it, and a
6
+ * static value import then crashes the whole plugin at module-load time with
7
+ * ERR_MODULE_NOT_FOUND. This mirrors the 0.9.3 pruner soft-import decision:
8
+ * the semantics are deliberately tiny and stable (deep clone → brand a fresh
9
+ * id → deep freeze), so the plugin carries its own copy instead of importing
10
+ * the host's.
11
+ */
12
+ import type { UserMessage } from '@deepseek-ai/dsh-llm'
13
+
14
+ /** Recursive `Object.freeze` over own enumerable properties (arrays included). */
15
+ function deepFreeze<T>(value: T): T {
16
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
17
+ Object.freeze(value)
18
+ for (const nested of Object.values(value as Record<string, unknown>)) {
19
+ deepFreeze(nested)
20
+ }
21
+ }
22
+ return value
23
+ }
24
+
25
+ /**
26
+ * Detach and deep-freeze a message whose identity already exists — the host
27
+ * factory is `deepFreeze(structuredClone(message))`, byte-for-byte.
28
+ */
29
+ export function freezeMessage<T>(message: T): T {
30
+ return deepFreeze(structuredClone(message))
31
+ }
32
+
33
+ /**
34
+ * Create one identified user-role message and freeze it before publication —
35
+ * the host factory spreads the input, stamps `role: 'user'` and a fresh UUID
36
+ * id, clones and freezes. The signature mirrors the host's generic form so
37
+ * call sites keep their excess-property discipline; `id`/`role` stay
38
+ * unconstructible via the `never` guards, exactly like the host's d.ts.
39
+ */
40
+ type NewUserMessage = Omit<UserMessage, 'id' | 'role'>
41
+
42
+ export function createUserMessage<T extends NewUserMessage>(
43
+ input: T & { readonly id?: never, readonly role?: never },
44
+ ): UserMessage {
45
+ return deepFreeze(structuredClone({
46
+ ...input,
47
+ role: 'user' as const,
48
+ id: crypto.randomUUID(),
49
+ })) as unknown as UserMessage
50
+ }
@@ -208,6 +208,18 @@ function asWebServer(value: unknown): WebServerLike | undefined {
208
208
  return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
209
209
  }
210
210
 
211
+ /**
212
+ * `webServer.register` throws `duplicate exact route` when the same lib is
213
+ * mounted twice by the host (two plugin ids resolving to one module: the
214
+ * package-root manifest and the nested selector manifest). The other mount
215
+ * already owns every path in the batch, so the collision is a success from
216
+ * the plugin's point of view — without this, the losing arm logs a stack-
217
+ * heavy warn pair on every boot (observed 0.9.5 on 0.2.0-rc.2, savings and
218
+ * monitor).
219
+ */
220
+ const isDuplicateRouteError = (error: unknown): boolean =>
221
+ String((error as Error)?.message ?? error).includes('duplicate exact route')
222
+
211
223
  /**
212
224
  * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
213
225
  * settings card's host-route dropdowns (live provider/model groups from the DSH
@@ -285,6 +297,11 @@ function registerEstimatorCatalogRoute(ctx: Context): void {
285
297
  )
286
298
  log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
287
299
  } catch (error) {
300
+ if (isDuplicateRouteError(error)) {
301
+ registered = true
302
+ log('info', 'context-compression estimator catalog route already registered by another mount (%s)', channel)
303
+ return
304
+ }
288
305
  log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
289
306
  }
290
307
  }
@@ -359,6 +376,11 @@ function registerSavingsRoute(ctx: Context): void {
359
376
  )
360
377
  log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
361
378
  } catch (error) {
379
+ if (isDuplicateRouteError(error)) {
380
+ registered = true
381
+ log('info', 'context-compression savings route already registered by another mount (%s)', channel)
382
+ return
383
+ }
362
384
  log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
363
385
  }
364
386
  }
@@ -472,6 +494,11 @@ export function registerMonitorRoute(ctx: Context): void {
472
494
  )
473
495
  log('info', 'context-compression monitor route registered (%s): %s', channel, MONITOR_ROUTES.join(', '))
474
496
  } catch (error) {
497
+ if (isDuplicateRouteError(error)) {
498
+ registered = true
499
+ log('info', 'context-compression monitor route already registered by another mount (%s)', channel)
500
+ return
501
+ }
475
502
  log('warn', 'context-compression monitor route registration failed (%s): %o', channel, error)
476
503
  }
477
504
  }
@@ -11,6 +11,19 @@ import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
11
11
  import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
12
12
  import { dump, load } from 'js-yaml'
13
13
 
14
+ /** Cordis 把未被代理的原始 service 暴露在该 symbol 下(见 cordis createTraceable 的 get 陷阱)。 */
15
+ const CORDIS_ORIGINAL = Symbol.for('cordis.original')
16
+
17
+ /**
18
+ * 取得 Cordis traceable 代理背后的原始 service。原始对象是宿主内部调用
19
+ * (`this.resolveMountable → this.resolve`) 时的接收者;只有装饰它,压缩栈补丁才能
20
+ * 真正注入(实证:装饰代理/原型代理均失败)。
21
+ */
22
+ function rawService(presets: object): object {
23
+ const raw = (presets as Record<symbol, unknown>)[CORDIS_ORIGINAL]
24
+ return raw !== null && typeof raw === 'object' ? raw : presets
25
+ }
26
+
14
27
  /** Absolute runtime entry points used by the generated compression stack. */
15
28
  export interface CompressionModulePaths {
16
29
  /** Exact aggregate/history compaction implementation shipped with the Bundle. */
@@ -31,6 +44,8 @@ export interface OverlayableAgentPresets {
31
44
  recompose(agentCtx: unknown, id: string): Promise<AgentPreset>
32
45
  /** Ensure a standing preset composition for cold readers. */
33
46
  standingKeyFor(id?: string): Promise<unknown>
47
+ /** Register a preset definition; the 0.2.0 registry pre-composes it here. Optional: older host lines lack it. */
48
+ register?(definition: unknown): Promise<unknown>
34
49
  }
35
50
 
36
51
  /** Configuration for one reversible decoration. */
@@ -425,12 +440,92 @@ function renderPatchWarning(message: string, args: readonly unknown[]): string {
425
440
  return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`
426
441
  }
427
442
 
443
+ /** Read a definition's preset id when the shape is a plain object. */
444
+ function readDefinitionId(definition: unknown): string | undefined {
445
+ if (typeof definition !== 'object' || definition === null) return undefined
446
+ const id = (definition as { id?: unknown }).id
447
+ return typeof id === 'string' ? id : undefined
448
+ }
449
+
450
+ /**
451
+ * Inject the canonical compression stack into one preset definition's rows.
452
+ *
453
+ * The 0.2.0 `dsh-agent-preset-registry` PRE-BUILDS a generation per definition
454
+ * (`activate` → `mountPreset(ctx, id, definition.plugins)`) and `mount` only
455
+ * `retain`s it; the composition never calls `resolve`. So the stack must land in
456
+ * the definition's own `plugins` before activation, not in a resolved preset
457
+ * file. Best-effort: a failed injection leaves the original rows untouched.
458
+ */
459
+ function injectCompressionRows(
460
+ definition: unknown,
461
+ options: PresetOverlayOptions,
462
+ excluded: ReadonlySet<string>,
463
+ ): void {
464
+ const id = readDefinitionId(definition)
465
+ if (id === undefined || excluded.has(id)) return
466
+ const plugins = (definition as { plugins?: unknown }).plugins
467
+ if (!Array.isArray(plugins)) return
468
+ try {
469
+ const thresholdPercent = options.autoCompactThresholdPercent?.()
470
+ const next = applyEntryPatches(
471
+ stripCompressionRows(plugins as EntryOptions[]),
472
+ [{ insert: compressionRowsBySpecifier(thresholdPercent) }],
473
+ (message: string, ...args: unknown[]) => {
474
+ throw new Error(renderPatchWarning(message, args))
475
+ },
476
+ )
477
+ ;(definition as { plugins: EntryOptions[] }).plugins = next
478
+ } catch {
479
+ // 保留原 rows:注入失败不影响定义注册主流程
480
+ }
481
+ }
482
+
483
+ /**
484
+ * The canonical compression stack addressed by BARE SPECIFIERS. The 0.2.0
485
+ * `dsh-agent-preset-registry` preset files declare this exact group by package
486
+ * name, and its loader resolves bare specifiers (`@deepseek-ai/...`,
487
+ * `dsh-context-compression-improved/pruner`) — absolute filesystem paths from
488
+ * {@link resolveCompressionModulePaths} are NOT accepted there (empirically:
489
+ * every injected row reports "never started").
490
+ */
491
+ function compressionRowsBySpecifier(thresholdPercent?: number): EntryOptions[] {
492
+ return [
493
+ {
494
+ id: 'compaction',
495
+ name: 'cordis:group',
496
+ group: true,
497
+ isolate: { compaction: true, toolResultPruner: true },
498
+ config: [
499
+ {
500
+ id: 'compaction-basic',
501
+ name: '@deepseek-ai/dsh-compaction-basic',
502
+ ...(thresholdPercent === undefined ? {} : {
503
+ config: { thresholdRatio: thresholdPercent / 100, retainRatio: 0.16 },
504
+ }),
505
+ },
506
+ { id: 'command-compact', name: '@deepseek-ai/dsh-command-compact' },
507
+ {
508
+ id: 'tool-result-pruner',
509
+ name: 'dsh-context-compression-improved/pruner',
510
+ config: {
511
+ headChars: 4096,
512
+ tailChars: 1024,
513
+ ...(thresholdPercent === undefined ? {} : { autoCompactThresholdPercent: thresholdPercent }),
514
+ },
515
+ },
516
+ ],
517
+ },
518
+ ]
519
+ }
520
+
428
521
  /** Method names whose native execution is allowed to resolve an overlay. */
429
- type CompositionMethod = 'mount' | 'recompose' | 'standingKeyFor'
522
+ type CompositionMethod = 'mount' | 'recompose' | 'standingKeyFor' | 'register'
430
523
 
431
524
  /** Restore one method to exactly the own/prototype state it had before decoration. */
432
525
  interface MethodSnapshot {
433
526
  readonly name: 'resolve' | CompositionMethod
527
+ /** Object whose OWN property holds the original (the raw service target). */
528
+ readonly home: object
434
529
  readonly own: PropertyDescriptor | undefined
435
530
  readonly original: (...args: never[]) => unknown
436
531
  wrapped?: (...args: never[]) => unknown
@@ -542,23 +637,37 @@ function installAgentPresetsDecoration(
542
637
  const excluded = new Set(options.excludedPresetIds ?? ['minimal'])
543
638
  const operations = new AsyncLocalStorage<CompositionOperation>()
544
639
  const store = new PresetOverlayStore(options)
640
+ const raw = rawService(presets)
545
641
  const snapshots = snapshotMethods(presets)
546
642
  const resolveSnapshot = snapshotFor(snapshots, 'resolve')
547
643
 
548
644
  const resolveWrapped = async (id?: string): Promise<AgentPreset> => {
549
- const preset = await Reflect.apply(resolveSnapshot.original, presets, [id]) as AgentPreset
550
- if (operations.getStore()?.composing !== true || excluded.has(preset.id)) return preset
645
+ const preset = await Reflect.apply(resolveSnapshot.original, raw, [id]) as AgentPreset
646
+ const composing = operations.getStore()?.composing === true
647
+ if (!composing || excluded.has(preset.id)) return preset
551
648
  return await store.overlay(preset)
552
649
  }
553
- installMethod(presets, resolveSnapshot, resolveWrapped)
650
+ installMethod(resolveSnapshot, resolveWrapped)
554
651
 
555
652
  for (const method of ['mount', 'recompose', 'standingKeyFor'] as const) {
556
- const snapshot = snapshotFor(snapshots, method)
557
- const wrapped = (...args: unknown[]): unknown => operations.run(
558
- { composing: true },
559
- (): unknown => Reflect.apply(snapshot.original, presets, args) as unknown,
560
- )
561
- installMethod(presets, snapshot, wrapped)
653
+ const snapshot = snapshots.find(candidate => candidate.name === method)
654
+ if (snapshot === undefined) continue
655
+ const wrapped = (...args: unknown[]): unknown => {
656
+ return operations.run(
657
+ { composing: true },
658
+ (): unknown => Reflect.apply(snapshot.original, raw, args) as unknown,
659
+ )
660
+ }
661
+ installMethod(snapshot, wrapped)
662
+ }
663
+
664
+ const registerSnapshot = snapshots.find(candidate => candidate.name === 'register')
665
+ if (registerSnapshot !== undefined) {
666
+ const registerWrapped = async (definition: unknown): Promise<unknown> => {
667
+ injectCompressionRows(definition, options, excluded)
668
+ return await Reflect.apply(registerSnapshot.original, raw, [definition]) as unknown
669
+ }
670
+ installMethod(registerSnapshot, registerWrapped)
562
671
  }
563
672
 
564
673
  let disposed = false
@@ -566,7 +675,7 @@ function installAgentPresetsDecoration(
566
675
  async dispose(): Promise<void> {
567
676
  if (disposed) return
568
677
  disposed = true
569
- for (const snapshot of [...snapshots].reverse()) restoreMethod(presets, snapshot)
678
+ for (const snapshot of [...snapshots].reverse()) restoreMethod(snapshot)
570
679
  await store.dispose()
571
680
  },
572
681
  }
@@ -574,17 +683,32 @@ function installAgentPresetsDecoration(
574
683
 
575
684
  /** Capture callable methods and whether each was inherited or owned. */
576
685
  function snapshotMethods(presets: OverlayableAgentPresets): MethodSnapshot[] {
577
- return (['resolve', 'mount', 'recompose', 'standingKeyFor'] as const).map((name) => {
686
+ const methods: MethodSnapshot[] = []
687
+ for (const name of ['resolve', 'mount', 'recompose', 'standingKeyFor', 'register'] as const) {
578
688
  const original = presets[name]
579
689
  if (typeof original !== 'function') {
580
- throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
690
+ // `resolve` 是 overlay 自身的重写器,必须有。其余生命周期方法(mount/
691
+ // recompose/standingKeyFor)仅需被 AsyncLocalStorage 作用域包裹:宿主线
692
+ // 缺其中一个(0.1.7-rc.2 无 `standingKeyFor`)不得让整个 overlay 失败,
693
+ // 跳过它即可——否则压缩栈永远注入不了(实证:overlay:err)。
694
+ if (name === 'resolve') {
695
+ throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
696
+ }
697
+ continue
581
698
  }
582
- return {
699
+ // Cordis 的 traceable 代理每次读取都会重绑方法,且把**未代理的原始 target**
700
+ // 暴露在 `Symbol.for('cordis.original')` 下。因此装饰代理或"原型代理"都对
701
+ // target 内部的 `this.resolve(...)` 无效(实证:overlay:composition{mount} 触发、
702
+ // 却无嵌套 overlay:resolve)。装饰**原始 target 自身**方能同时命中两种接收者。
703
+ const home = rawService(presets)
704
+ methods.push({
583
705
  name,
584
- own: Object.getOwnPropertyDescriptor(presets, name),
706
+ home,
707
+ own: Object.getOwnPropertyDescriptor(home, name),
585
708
  original,
586
- }
587
- })
709
+ })
710
+ }
711
+ return methods
588
712
  }
589
713
 
590
714
  /** Return the captured method or fail loudly if the snapshot set is corrupt. */
@@ -601,12 +725,11 @@ function snapshotFor(
601
725
 
602
726
  /** Install one own method while retaining its identity for safe disposal. */
603
727
  function installMethod(
604
- presets: OverlayableAgentPresets,
605
728
  snapshot: MethodSnapshot,
606
729
  wrapped: (...args: never[]) => unknown,
607
730
  ): void {
608
731
  snapshot.wrapped = wrapped
609
- Object.defineProperty(presets, snapshot.name, {
732
+ Object.defineProperty(snapshot.home, snapshot.name, {
610
733
  configurable: true,
611
734
  writable: true,
612
735
  value: wrapped,
@@ -614,13 +737,13 @@ function installMethod(
614
737
  }
615
738
 
616
739
  /** Restore the captured own/prototype state after the final shared lease. */
617
- function restoreMethod(presets: OverlayableAgentPresets, snapshot: MethodSnapshot): void {
740
+ function restoreMethod(snapshot: MethodSnapshot): void {
618
741
  // Cordis' traceable service proxy rebinds a method on every read, so function
619
742
  // identity cannot prove ownership here. The shared reference count is the
620
743
  // ownership guard: this path runs only after the final decorator lease ends.
621
744
  if (snapshot.own === undefined) {
622
- Reflect.deleteProperty(presets, snapshot.name)
745
+ Reflect.deleteProperty(snapshot.home, snapshot.name)
623
746
  } else {
624
- Object.defineProperty(presets, snapshot.name, snapshot.own)
747
+ Object.defineProperty(snapshot.home, snapshot.name, snapshot.own)
625
748
  }
626
749
  }
@@ -72,7 +72,7 @@ function unavailableCount(reason: string): TokenCount {
72
72
 
73
73
  function recoveryMarker(sourceRef: string, label: string, startLine?: number): string {
74
74
  const hint = startLine === undefined
75
- ? 'use context_compression_retrieve if needed'
75
+ ? 'use context_compression_retrieve with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)'
76
76
  : `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
77
77
  return `\n\n[... ${label}; source=${sourceRef}; ${hint} ...]\n\n`
78
78
  }
@@ -48,6 +48,10 @@ export interface PrunerState {
48
48
  readonly estimatorRemainingTurns: WeakMap<Session, number>
49
49
  /** Per-session advisor side channel, constructed once with the advisor overrides. */
50
50
  readonly advisorChannels: WeakMap<Session, SideChannel>
51
+ /** Per-session intent-summary writer channel, constructed once with the estimator channel mode. */
52
+ readonly intentChannels: WeakMap<Session, SideChannel>
53
+ /** Sessions whose savings ledger has been seeded from the session-log projection. */
54
+ readonly projectedSavings: WeakSet<Session>
51
55
  /** Staged intent fold awaiting the next pressure round (at most one per session). */
52
56
  readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>
53
57
  /** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */