dsh-context-compression-improved 0.9.3 → 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.
Files changed (35) hide show
  1. package/package.json +1 -1
  2. package/packages/selector/dsh.plugin.json +1 -1
  3. package/packages/selector/lib/client.d.ts +1 -0
  4. package/packages/selector/lib/client.js +63 -10
  5. package/packages/selector/lib/config.js +71 -7
  6. package/packages/selector/lib/index.js +120 -20
  7. package/packages/selector/lib/pruner.d.ts +158 -107
  8. package/packages/selector/lib/pruner.js +331 -20
  9. package/packages/selector/package.json +1 -1
  10. package/packages/selector/src/client/index.ts +29 -2
  11. package/packages/selector/src/client/locales/de.ts +1 -0
  12. package/packages/selector/src/client/locales/es.ts +1 -0
  13. package/packages/selector/src/client/locales/fr.ts +1 -0
  14. package/packages/selector/src/client/locales/it.ts +1 -0
  15. package/packages/selector/src/client/locales/ja.ts +1 -0
  16. package/packages/selector/src/client/locales/ko.ts +1 -0
  17. package/packages/selector/src/client/locales/ru.ts +1 -0
  18. package/packages/selector/src/client/locales.ts +2 -0
  19. package/packages/selector/src/client/monitor-fab.ts +19 -4
  20. package/packages/selector/src/preset-overlay.ts +145 -22
  21. package/packages/selector/src/pruner/content.ts +1 -1
  22. package/packages/selector/src/pruner/state.ts +4 -0
  23. package/packages/selector/src/pruner.ts +104 -15
  24. package/packages/selector/src/runtime/config.ts +1 -1
  25. package/packages/selector/src/runtime/reducers.ts +81 -1
  26. package/packages/selector/src/runtime/retrieve.ts +4 -3
  27. package/packages/selector/src/runtime/savings-projection.ts +226 -0
  28. package/packages/selector/src/runtime/savings.ts +83 -3
  29. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  30. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  31. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
  32. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  33. package/packages/selector/tests/runtime/savings.spec.ts +22 -3
  34. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  35. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
@@ -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;
@@ -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. */
@@ -122,6 +122,7 @@ import {
122
122
  flattenPlainText,
123
123
  } from './runtime/tokenpilot/dedup.ts'
124
124
  import { getSavingsLedger } from './runtime/savings.ts'
125
+ import { projectSessionSavings } from './runtime/savings-projection.ts'
125
126
 
126
127
  /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
127
128
  function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
@@ -228,6 +229,39 @@ declare module '@deepseek-ai/cordis' {
228
229
  }
229
230
  }
230
231
 
232
+ /**
233
+ * Cross-generation adaptation (0.2.0): the host `settings` service hands back
234
+ * the WHOLE entry config `{ settings: <subtree> }` instead of the settings
235
+ * subtree directly (older lines surfaced the subtree at the top level). The
236
+ * parser requires `profile`+`custom` at the root, so the wrapped shape threw
237
+ * "missing its complete shape" → the session failed open to `profile:'off'`,
238
+ * silently disabling fresh/aggregate on the desktop. Descend exactly one
239
+ * `{settings:<obj>}` wrapper ONLY when the root has no `profile`; every other
240
+ * shape is passed through untouched so the "exotic Host value must fail open
241
+ * to off" safety contract still holds.
242
+ */
243
+ export function unwrapSettingsEntry(value: unknown): unknown {
244
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
245
+ const record = value as Record<string, unknown>
246
+ if ('profile' in record) return value
247
+ const inner = record.settings
248
+ if (inner !== null && typeof inner === 'object' && !Array.isArray(inner)) return inner
249
+ return value
250
+ }
251
+
252
+ /**
253
+ * Whether a fresh candidate is BELOW the fresh trigger. Uses the real token
254
+ * count when an exact tokenizer is available (DeepSeek routes), and otherwise
255
+ * falls back to the 4.0 chars/token estimate — byte-for-byte the pre-existing
256
+ * behavior on routes without a bundled tokenizer (e.g. local Qwen).
257
+ */
258
+ export function freshBelowTrigger(candidate: SnapshotCandidate, policy: CompressionPolicy): boolean {
259
+ if (candidate.count.kind === 'exact-tokenizer') {
260
+ return candidate.count.tokens <= policy.freshTriggerTokens
261
+ }
262
+ return candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)
263
+ }
264
+
231
265
  /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
232
266
  export class ToolResultPruner extends Service {
233
267
  static inject = ['tokenMeter']
@@ -276,6 +310,8 @@ export class ToolResultPruner extends Service {
276
310
  turnClocks: new WeakMap(),
277
311
  estimatorRemainingTurns: new WeakMap(),
278
312
  advisorChannels: new WeakMap(),
313
+ intentChannels: new WeakMap(),
314
+ projectedSavings: new WeakSet(),
279
315
  pendingIntentFolds: new WeakMap(),
280
316
  intentFoldedSeqs: new WeakMap(),
281
317
  intentBaselines: new WeakMap(),
@@ -371,6 +407,15 @@ export class ToolResultPruner extends Service {
371
407
  this.contextWindowForRequest(agent.session),
372
408
  )
373
409
  } catch { /* 观测失败静默:面板显示陈旧/空态 */ }
410
+ // 仪表口径:把当前 surface 存活 seq 交给账本,离开 surface 的压缩替换
411
+ // 即从“当前生效毛节省”中回落(数字随压缩内容进出而涨落)。
412
+ this.ensureSavingsProjection(agent.session)
413
+ try {
414
+ getSavingsLedger().observeActive(
415
+ String(agent.session.id),
416
+ new Set([...agent.session.surface.nodes].map(Number)),
417
+ )
418
+ } catch { /* 观测失败静默:维持上次口径 */ }
374
419
  // TokenPilot-inspired E1: advisory estimator pass, strictly off the
375
420
  // synchronous chain. Verdicts only feed the next pressure pass.
376
421
  void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
@@ -517,6 +562,7 @@ export class ToolResultPruner extends Service {
517
562
  (d) => String(d.ns) === 'context-compression-improved-bundle',
518
563
  )?.value
519
564
  ?? settingsHost?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)) as ContextCompressionSettings | undefined
565
+ const unwrapped = unwrapSettingsEntry(settings)
520
566
  let resolved: ContextCompressionSettings
521
567
  let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
522
568
  ? 'plugin-config-fallback'
@@ -530,7 +576,7 @@ export class ToolResultPruner extends Service {
530
576
  // Validate the Host value BEFORE cloning: structuredClone normalizes
531
577
  // class/exotic prototypes to Object.prototype and would otherwise
532
578
  // erase the very boundary the parser is responsible for enforcing.
533
- : parseContextCompressionSettings(settings)
579
+ : parseContextCompressionSettings(unwrapped as ContextCompressionSettings)
534
580
  } catch (error: unknown) {
535
581
  // A malformed persisted document must fail open LOSSLESSLY: freezing the
536
582
  // deployment default could silently re-enable lossy compression the
@@ -659,7 +705,7 @@ export class ToolResultPruner extends Service {
659
705
  for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
660
706
  if (samples.length >= 3) break
661
707
  if (candidate.event.data.turn === undefined) continue
662
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) continue
708
+ if (freshBelowTrigger(candidate, policy)) continue
663
709
  const path = toolCallPath(candidate.call.arguments)
664
710
  if (path === undefined) continue
665
711
  if (isSupersededRead(events, candidate.seq, path)) continue
@@ -810,6 +856,21 @@ export class ToolResultPruner extends Service {
810
856
  }
811
857
  }
812
858
 
859
+ /**
860
+ * 重进/重启会话的懒重建:首次观测某会话时,若账本尚无该会话条目,则按会话
861
+ * 日志投影播种(当前生效毛节省 + 每次重读惩罚 + 原文配对键)。只做一次,
862
+ * fail-open;同一进程内的实时增量随后在同一条目集合上继续。
863
+ */
864
+ private ensureSavingsProjection(session: Session): void {
865
+ if (this.state.projectedSavings.has(session)) return
866
+ this.state.projectedSavings.add(session)
867
+ const ledger = getSavingsLedger()
868
+ if (ledger.hasSession(String(session.id))) return
869
+ try {
870
+ ledger.seedProjected(String(session.id), projectSessionSavings(this.ctx, session))
871
+ } catch { /* 投影失败静默:面板显示空态,不影响主流程 */ }
872
+ }
873
+
813
874
  // ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
814
875
 
815
876
  /**
@@ -852,8 +913,25 @@ export class ToolResultPruner extends Service {
852
913
 
853
914
  const settingsPreset = settings.presetOptions
854
915
  if (settingsPreset === undefined) return
855
- if (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
856
- || settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0) {
916
+ // 写手通道复用估计器通道:`host` 走宿主 llm 路由(provider/model 可省),
917
+ // `direct` 才需要显式 OpenAI 兼容端点。此前无条件要求直连端点,导致
918
+ // host 通道下每个回合都以 'no-direct-endpoint' 提前返回,fold 永不落地。
919
+ const estimatorMode = settingsPreset.estimatorMode ?? ''
920
+ if (estimatorMode !== 'host' && estimatorMode !== 'direct') {
921
+ emitCompressionAudit(this.ctx.logger, {
922
+ schemaVersion: 1,
923
+ kind: 'intent-summary-outcome',
924
+ sessionId,
925
+ ok: false,
926
+ reason: 'no-estimator-channel',
927
+ turnIndex: turn,
928
+ latencyMs: Date.now() - started,
929
+ })
930
+ return
931
+ }
932
+ if (estimatorMode === 'direct'
933
+ && (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
934
+ || settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0)) {
857
935
  emitCompressionAudit(this.ctx.logger, {
858
936
  schemaVersion: 1,
859
937
  kind: 'intent-summary-outcome',
@@ -891,14 +969,16 @@ export class ToolResultPruner extends Service {
891
969
 
892
970
  const events = sessionEvents(session)
893
971
  const task = collectTaskSemantics(events)
894
- let channel = this.state.advisorChannels.get(session)
972
+ // 独立通道:写手用 30s 超时,advisor 用其自身超时——两者若共享
973
+ // advisorChannels,先构造者会把 mode/timeout 强加给后者。
974
+ let channel = this.state.intentChannels.get(session)
895
975
  if (channel === undefined) {
896
976
  channel = new SideChannel(this.ctx, settingsPreset, {
897
- mode: 'direct',
977
+ mode: estimatorMode,
898
978
  timeoutMs: 30_000,
899
979
  maxTokens: 512,
900
980
  })
901
- this.state.advisorChannels.set(session, channel)
981
+ this.state.intentChannels.set(session, channel)
902
982
  }
903
983
 
904
984
  const answer = await channel.ask({
@@ -1470,7 +1550,8 @@ export class ToolResultPruner extends Service {
1470
1550
  return emptyResult()
1471
1551
  }
1472
1552
  const decisions = this.decisions(session)
1473
- const candidates = this.snapshot(session, view).filter(candidate =>
1553
+ const snapshot = this.snapshot(session, view)
1554
+ const candidates = snapshot.filter(candidate =>
1474
1555
  typeof candidate.event.surfaceOp !== 'object'
1475
1556
  && candidate.event.data.turn === options.freshTurn
1476
1557
  && candidate.event.data.step === options.freshStep
@@ -1506,8 +1587,14 @@ export class ToolResultPruner extends Service {
1506
1587
  const plans = new Map<number, PlannedReplacement>()
1507
1588
  let freshPlanned = 0
1508
1589
  const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
1509
- const candidateChars = candidates.map(candidate => candidate.characterPressure)
1510
- const maxCandidateChars = candidateChars.length === 0 ? undefined : Math.max(...candidateChars)
1590
+ // Token-basis max, mirroring freshBelowTrigger: exact tokenizer where
1591
+ // available, else the 4.0 char estimate. Drives the 'at-or-below-trigger'
1592
+ // audit reason on the same basis the fresh gate uses.
1593
+ const maxCandidateTokens = candidates.length === 0
1594
+ ? undefined
1595
+ : Math.max(...candidates.map(candidate => candidate.count.kind === 'exact-tokenizer'
1596
+ ? candidate.count.tokens
1597
+ : charsToTokens(candidate.characterPressure)))
1511
1598
  if (policy.freshEnabled) {
1512
1599
  if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
1513
1600
  && candidate.count.kind !== 'exact-tokenizer')) {
@@ -1573,12 +1660,12 @@ export class ToolResultPruner extends Service {
1573
1660
  this.auditComponent(session, policy, 'fresh', 'fresh',
1574
1661
  policy.freshEnabled ? 'skipped' : 'disabled',
1575
1662
  !policy.freshEnabled ? 'profile-policy'
1576
- : (maxCandidateChars ?? 0) <= charsForTokens(policy.freshTriggerTokens) ? 'at-or-below-trigger'
1663
+ : (maxCandidateTokens ?? 0) <= policy.freshTriggerTokens ? 'at-or-below-trigger'
1577
1664
  : freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
1578
1665
  : freshPlanned === 0 ? 'no-valid-reduction'
1579
1666
  : 'recovery-tool-unavailable', {
1580
1667
  measurementKind: 'characters',
1581
- ...(maxCandidateChars === undefined ? {} : { currentTokens: charsToTokens(maxCandidateChars) }),
1668
+ ...(maxCandidateTokens === undefined ? {} : { currentTokens: maxCandidateTokens }),
1582
1669
  triggerTokens: policy.freshTriggerTokens,
1583
1670
  targetTokens: policy.freshTargetTokens,
1584
1671
  })
@@ -1699,7 +1786,7 @@ export class ToolResultPruner extends Service {
1699
1786
  if (typeof candidate.event.surfaceOp === 'object') return null
1700
1787
  const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
1701
1788
  if (text === undefined) return null
1702
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1789
+ if (freshBelowTrigger(candidate, policy)) return null
1703
1790
  let table = this.state.dedupeTables.get(session)
1704
1791
  if (table === undefined) {
1705
1792
  table = new DedupeTable()
@@ -1745,7 +1832,7 @@ export class ToolResultPruner extends Service {
1745
1832
  // being reconsidered after their first request.
1746
1833
  if (typeof candidate.event.surfaceOp === 'object') return null
1747
1834
  const resultView = viewToolResult(candidate.event.data.message)
1748
- if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1835
+ if (freshBelowTrigger(candidate, policy)) return null
1749
1836
  const sourceSeq = candidate.seq
1750
1837
  const sourceRef = sourceRefFn(session, sourceSeq)
1751
1838
  const textBlock = onlyTextBlock(resultView.blocks as ContentBlock[])
@@ -1828,7 +1915,7 @@ export class ToolResultPruner extends Service {
1828
1915
  '[Tool result reduced to satisfy the completed-step aggregate budget]',
1829
1916
  `tool: ${candidate.call.name}`,
1830
1917
  `source: ${sourceRef}`,
1831
- 'Use context_compression_retrieve with this source if the omitted evidence is necessary.',
1918
+ 'Retrieve a narrow slice via context_compression_retrieve if needed.',
1832
1919
  ].join('\n')
1833
1920
  const plan = this.plan(
1834
1921
  candidate,
@@ -2323,6 +2410,7 @@ export class ToolResultPruner extends Service {
2323
2410
  tokensAfter,
2324
2411
  basis: exact ? 'exact-tokenizer' : 'characters',
2325
2412
  sourceSeq: manifestSeq,
2413
+ replacementSeq: Number(replacement.seq),
2326
2414
  originalText: groupText,
2327
2415
  })
2328
2416
  }
@@ -2492,6 +2580,7 @@ export class ToolResultPruner extends Service {
2492
2580
  tokensAfter: plan.tokensAfter,
2493
2581
  basis: plan.measurementBasis,
2494
2582
  sourceSeq: plan.sourceSeq,
2583
+ replacementSeq: Number(replacement.seq),
2495
2584
  ...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
2496
2585
  })
2497
2586
  return {
@@ -677,7 +677,7 @@ export function resolvePolicy(
677
677
  'tokenpilot-inspired': {
678
678
  nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
679
679
  nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
680
- freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
680
+ freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
681
681
  aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
682
682
  historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
683
683
  historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,