dsh-context-compression-improved 0.9.0 → 0.9.5
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 +56 -0
- package/package.json +2 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +1 -0
- package/packages/selector/lib/client.js +86 -32
- package/packages/selector/lib/config.js +71 -7
- package/packages/selector/lib/index.js +120 -20
- package/packages/selector/lib/pruner.d.ts +158 -107
- package/packages/selector/lib/pruner.js +336 -21
- package/packages/selector/package.json +1 -1
- package/packages/selector/src/client/index.ts +55 -20
- package/packages/selector/src/client/locales/de.ts +1 -0
- package/packages/selector/src/client/locales/es.ts +1 -0
- package/packages/selector/src/client/locales/fr.ts +1 -0
- package/packages/selector/src/client/locales/it.ts +1 -0
- package/packages/selector/src/client/locales/ja.ts +1 -0
- package/packages/selector/src/client/locales/ko.ts +1 -0
- package/packages/selector/src/client/locales/ru.ts +1 -0
- package/packages/selector/src/client/locales.ts +2 -0
- package/packages/selector/src/client/monitor-fab.ts +19 -4
- package/packages/selector/src/preset-overlay.ts +145 -22
- package/packages/selector/src/pruner/content.ts +1 -1
- package/packages/selector/src/pruner/state.ts +4 -0
- package/packages/selector/src/pruner.ts +120 -16
- package/packages/selector/src/runtime/config.ts +1 -1
- package/packages/selector/src/runtime/measurement.ts +14 -1
- package/packages/selector/src/runtime/reducers.ts +81 -1
- package/packages/selector/src/runtime/retrieve.ts +4 -3
- package/packages/selector/src/runtime/savings-projection.ts +226 -0
- package/packages/selector/src/runtime/savings.ts +83 -3
- package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
- package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
- package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
- package/packages/selector/tests/runtime/savings.spec.ts +22 -3
- package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
- package/scripts/cell-browser-e2e.mjs +354 -0
|
@@ -81,7 +81,14 @@ function sameCustomPolicy(
|
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
export function apply(ctx: ClientContext): void {
|
|
84
|
-
|
|
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
|
|
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),
|
|
@@ -314,10 +341,29 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
|
|
|
314
341
|
},
|
|
315
342
|
}
|
|
316
343
|
}
|
|
317
|
-
//
|
|
318
|
-
//
|
|
319
|
-
//
|
|
320
|
-
|
|
344
|
+
// bundle 详情卡的组件适配器:closure 自取 injected() 并把 hooks.compression
|
|
345
|
+
// 手工适配成 useCompression(useSyncExternalStore 包装)。这条渲染链不带
|
|
346
|
+
// hookContext、宿主不会做 hooks 映射(0.1.7 真机实证,见下方 bundle 卡注释)。
|
|
347
|
+
const sectionViaAdapter = (props: { close?: () => void }) => {
|
|
348
|
+
const inj = injected()
|
|
349
|
+
const scope = inj.hooks?.compression
|
|
350
|
+
const useCompression = <T,>(selector: (snapshot: ScopeSnapshot<ContextCompressionSettings>) => T): T => {
|
|
351
|
+
if (!scope) return selector({ status: 'loading', value: undefined, revision: undefined, writable: false, base: undefined, user: undefined, mode: 'memory' })
|
|
352
|
+
return useSyncExternalStore(
|
|
353
|
+
scope.subscribe,
|
|
354
|
+
() => selector(scope.getSnapshot()),
|
|
355
|
+
)
|
|
356
|
+
}
|
|
357
|
+
return createElement(ContextCompressionSettingsSection, { ...inj, ...props, useCompression } as never)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// 设置 → 上下文压缩 直挂分节(2026-10-08 回退定案:本插件不在家族 tab 化
|
|
361
|
+
// 范围内——上下文压缩选择器是独立 insection,0.1.1 契约、0.1.0-0.2.0 单注册
|
|
362
|
+
// 点,恢复 0.9.0 原注册)。只挂这一处:再注册 `settings.plugins.tab` /
|
|
363
|
+
// `settings.plugin.item` 会在设置里同时出现独立分节和插件卡片,重复展示
|
|
364
|
+
// 同一张面板。未声明槽的注册会在激活期抛错,故 try/catch 守卫(同
|
|
365
|
+
// dsh-prime-memory 的双槽冗余)。label 沿用已 eager bind 的 tNav(search-index
|
|
366
|
+
// 0.5.3 family-tab incident 的教训通用:label 在宿主渲染期求值,禁懒取 locale)。
|
|
321
367
|
try {
|
|
322
368
|
ctx.slots.inject('settings.section', () => ctx.slots.register({
|
|
323
369
|
name: 'settings.section',
|
|
@@ -328,7 +374,7 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
|
|
|
328
374
|
inject: injected,
|
|
329
375
|
}, ContextCompressionSettingsSection))
|
|
330
376
|
} catch (error) {
|
|
331
|
-
console.warn('[dsh-context-compression-improved] settings.section 注册失败(
|
|
377
|
+
console.warn('[dsh-context-compression-improved] settings.section 注册失败(宿主无该槽,静默缺席):', error)
|
|
332
378
|
}
|
|
333
379
|
|
|
334
380
|
// 输入栏左座(0.1.5+ 宿主):组件刻意空渲染——注册此座位只为接收宿主的
|
|
@@ -356,25 +402,14 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
|
|
|
356
402
|
// abdicate 成 data-slot-error 死格,且 abdication 本会话粘滞不再重试;
|
|
357
403
|
// ②locale: NS 必须保留 —— 它是宿主标准包 t(localeSeat)的唯一来源;
|
|
358
404
|
// ③组件闭包自取 injected(),并把 hooks.compression 手工适配成 useCompression
|
|
359
|
-
// (useSyncExternalStore 包装)
|
|
405
|
+
// (useSyncExternalStore 包装)——已抽为上方 sectionViaAdapter 共用。
|
|
360
406
|
// 老宿主无该槽 → 激活期抛错由 try/catch 吞掉,静默缺席。
|
|
361
407
|
try {
|
|
362
408
|
ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
|
|
363
409
|
name: 'plugins.bundle.config',
|
|
364
410
|
key: 'dsh-context-compression-improved',
|
|
365
411
|
locale: NS,
|
|
366
|
-
},
|
|
367
|
-
const inj = injected()
|
|
368
|
-
const scope = inj.hooks?.compression
|
|
369
|
-
const useCompression = <T,>(selector: (snapshot: ScopeSnapshot<ContextCompressionSettings>) => T): T => {
|
|
370
|
-
if (!scope) return selector({ status: 'loading', value: undefined, revision: undefined, writable: false, base: undefined, user: undefined, mode: 'memory' })
|
|
371
|
-
return useSyncExternalStore(
|
|
372
|
-
scope.subscribe,
|
|
373
|
-
() => selector(scope.getSnapshot()),
|
|
374
|
-
)
|
|
375
|
-
}
|
|
376
|
-
return createElement(ContextCompressionSettingsSection, { ...inj, ...props, useCompression } as never)
|
|
377
|
-
}))
|
|
412
|
+
}, sectionViaAdapter))
|
|
378
413
|
} catch (error) {
|
|
379
414
|
console.warn('[dsh-context-compression-improved] plugins.bundle.config 注册失败(旧宿主无该槽,静默缺席):', error)
|
|
380
415
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
233
|
-
(panel.querySelector('[data-
|
|
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;
|
|
@@ -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,
|
|
550
|
-
|
|
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(
|
|
650
|
+
installMethod(resolveSnapshot, resolveWrapped)
|
|
554
651
|
|
|
555
652
|
for (const method of ['mount', 'recompose', 'standingKeyFor'] as const) {
|
|
556
|
-
const snapshot =
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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(
|
|
745
|
+
Reflect.deleteProperty(snapshot.home, snapshot.name)
|
|
623
746
|
} else {
|
|
624
|
-
Object.defineProperty(
|
|
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. */
|