dsh-context-compression-improved 0.9.8 → 0.9.9

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 (68) hide show
  1. package/.agents/plans/improve/checklist.md +32 -0
  2. package/.agents/plans/improve/findings.md +102 -0
  3. package/.agents/plans/improve/spec.md +53 -0
  4. package/.agents/plans/improve/tasks.md +70 -0
  5. package/CHANGELOG.md +4 -0
  6. package/README.md +14 -2
  7. package/README.zh.md +14 -2
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +16 -0
  11. package/packages/selector/lib/client.js +396 -117
  12. package/packages/selector/lib/index.js +829 -10
  13. package/packages/selector/lib/invariant.js +2 -1
  14. package/packages/selector/lib/pruner.d.ts +1 -1
  15. package/packages/selector/lib/pruner.js +77 -983
  16. package/packages/selector/lib/savings-integral.js +4515 -0
  17. package/packages/selector/lib/tail-trim.js +2 -90
  18. package/packages/selector/lib/tool-result.js +150 -0
  19. package/packages/selector/package.json +8 -4
  20. package/packages/selector/src/client/index.ts +15 -12
  21. package/packages/selector/src/client/locales/de.ts +20 -4
  22. package/packages/selector/src/client/locales/es.ts +20 -4
  23. package/packages/selector/src/client/locales/fr.ts +20 -4
  24. package/packages/selector/src/client/locales/it.ts +20 -4
  25. package/packages/selector/src/client/locales/ja.ts +20 -4
  26. package/packages/selector/src/client/locales/ko.ts +20 -4
  27. package/packages/selector/src/client/locales/ru.ts +20 -4
  28. package/packages/selector/src/client/locales.ts +40 -8
  29. package/packages/selector/src/client/monitor-fab.ts +80 -10
  30. package/packages/selector/src/client/savings-card.tsx +159 -40
  31. package/packages/selector/src/index.ts +236 -1
  32. package/packages/selector/src/pruner.ts +54 -8
  33. package/packages/selector/src/runtime/audit.ts +17 -0
  34. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  35. package/packages/selector/src/runtime/monitor.ts +75 -0
  36. package/packages/selector/src/runtime/panel-command.ts +213 -0
  37. package/packages/selector/src/runtime/retrieve.ts +31 -12
  38. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  39. package/packages/selector/src/runtime/savings-projection.ts +3 -0
  40. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  41. package/packages/selector/src/runtime/savings.ts +122 -13
  42. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  43. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  44. package/packages/selector/src/runtime/stats-db.ts +492 -0
  45. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  46. package/packages/selector/src/runtime/stats-sync.ts +302 -0
  47. package/packages/selector/tests/estimator-route-registration.host.spec.ts +7 -4
  48. package/packages/selector/tests/monitor-fab.client.spec.ts +83 -1
  49. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  50. package/packages/selector/tests/runtime/monitor.spec.ts +53 -0
  51. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  52. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -1
  53. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  54. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  55. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  56. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  57. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  58. package/packages/selector/tests/runtime/stats-backfill.spec.ts +327 -0
  59. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  60. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  61. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  62. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  63. package/packages/selector/tests/settings-seat.client.spec.ts +15 -15
  64. package/pnpm-workspace.yaml +4 -0
  65. package/scripts/verify-release.mjs +5 -2
  66. package/vitest.config.ts +8 -0
  67. package/packages/selector/lib/config.js +0 -1777
  68. package/packages/selector/lib/host-generation.js +0 -62
@@ -7,10 +7,13 @@ import { getSavingsLedger } from './runtime/savings.ts'
7
7
  import {
8
8
  applySessionOverride,
9
9
  buildMonitorSnapshot,
10
+ drsTotalsFragment,
10
11
  estimateSavingsPricing,
11
12
  isSessionOverrideAction,
13
+ mergeCompositionByComponent,
12
14
  type AgentDefaultModelLike,
13
15
  } from './runtime/monitor.ts'
16
+ import { readDrsSessionIndex } from './runtime/savings-verify.ts'
14
17
  import type { ContextCompressionSettings } from './profiles.ts'
15
18
  import {
16
19
  CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
@@ -20,6 +23,13 @@ import {
20
23
  import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
21
24
  import { registerSummaryCommand } from './runtime/summary-command.ts'
22
25
  import { wireSettingsBridge } from './settings-bridge.ts'
26
+ import { closeStatsStore, ensureStatsStore, getStatsStore, statsPersistenceState } from './runtime/stats-db.ts'
27
+ import { cancelPendingUsageFlushes, getStatsActiveSessionId } from './runtime/stats-sync.ts'
28
+ import { configureStatsBackfillTrigger, kickStatsBackfillOnRouteHit } from './runtime/stats-backfill.ts'
29
+ import { getDisplayPrefs } from './runtime/display-prefs.ts'
30
+ import { estimateIntegralMoney } from './runtime/savings-integral.ts'
31
+ import { registerPanelCommand } from './runtime/panel-command.ts'
32
+ import { resolveOfficialDeepSeekPrice, type OfficialDeepSeekPriceRecord } from './runtime/deepseek-official-pricing.ts'
23
33
 
24
34
  // The settings namespace literal and the settings schema are owned by the
25
35
  // runtime config module. Both were once inlined/replaced here to dodge a
@@ -58,6 +68,12 @@ const MONITOR_ROUTES = [
58
68
  '/api/dsh-context-compression-improved/monitor',
59
69
  ] as const
60
70
 
71
+ // Per-session savings ledger (T24): paginated store view ⊕ live residual.
72
+ const SAVINGS_SESSIONS_ROUTES = [
73
+ '/endpoint/dsh-context-compression-improved/savings/sessions',
74
+ '/api/dsh-context-compression-improved/savings/sessions',
75
+ ] as const
76
+
61
77
  /** Minimal face of the agents service: session id → agent (carrying the session). */
62
78
  interface AgentsServiceLike {
63
79
  get?(id: unknown): { session?: unknown } | undefined
@@ -352,6 +368,8 @@ function registerSavingsRoute(ctx: Context): void {
352
368
  end: (body?: string) => void
353
369
  }
354
370
  if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
371
+ // T21:面板首命中最先发生的读路由——回填调度器的一次性 kick(内部闸幂等)。
372
+ kickStatsBackfillOnRouteHit()
355
373
  let sessionId: string | undefined
356
374
  try {
357
375
  const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
@@ -401,6 +419,195 @@ function registerSavingsRoute(ctx: Context): void {
401
419
  })
402
420
  }
403
421
 
422
+ /**
423
+ * Per-session savings ledger route (`GET .../savings/sessions?offset=&limit=&sessionId=…`)
424
+ * — spec T24: paginated store aggregates ⊕ live residual merge + per-session
425
+ * integral (Σ samples: "累计按 N 次 call") + cache-weighted money estimate +
426
+ * persistence state and display prefs (T30) for `/ccip`'s real-time toggles.
427
+ * The frozen `/savings` and `/monitor` contracts are untouched; everything new
428
+ * lives on this endpoint only.
429
+ */
430
+ function registerSavingsSessionsRoute(ctx: Context): void {
431
+ const readService = (name: string): unknown => {
432
+ try {
433
+ return (ctx as unknown as { get: (service: string) => unknown }).get(name)
434
+ } catch {
435
+ return undefined
436
+ }
437
+ }
438
+ const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
439
+ console[level](message, ...args)
440
+ }
441
+
442
+ let registered = false
443
+ const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
444
+ if (registered) return
445
+ const handler = (req: unknown, res: unknown): void => {
446
+ const resTyped = res as {
447
+ writeHead: (code: number, headers?: Record<string, string>) => void
448
+ end: (body?: string) => void
449
+ }
450
+ if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
451
+ kickStatsBackfillOnRouteHit()
452
+ let offset = 0
453
+ let limit = 20
454
+ let sessionId: string | undefined
455
+ try {
456
+ const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
457
+ const rawOffset = Number(url.searchParams.get('offset') ?? '0')
458
+ if (Number.isFinite(rawOffset) && rawOffset >= 0) offset = Math.trunc(rawOffset)
459
+ const rawLimit = Number(url.searchParams.get('limit') ?? '20')
460
+ if (Number.isFinite(rawLimit)) limit = Math.min(100, Math.max(1, Math.trunc(rawLimit)))
461
+ const raw = url.searchParams.get('sessionId')
462
+ if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
463
+ } catch {
464
+ /* 无法解析的查询串 = 默认第一页 */
465
+ }
466
+ const store = getStatsStore()
467
+ const ledger = getSavingsLedger()
468
+ const priceRecord = resolvePanelPriceRecord(readService)
469
+ const buildRow = (agg: { sessionId: string; gross: { exact: number; estimated: number }; offsets: { exact: number; estimated: number }; net: { exact: number; estimated: number } }) => {
470
+ const integral = store === null
471
+ ? { netExact: 0, netEstimated: 0, cachedInput: 0, uncachedInput: 0, calls: 0 }
472
+ : store.sumSamples(agg.sessionId)
473
+ const money = priceRecord === undefined || integral.calls === 0
474
+ ? undefined
475
+ : estimateIntegralMoney({ cachedInput: integral.cachedInput, uncachedInput: integral.uncachedInput, record: priceRecord })
476
+ const liveSnapshot = ledger.snapshot(agg.sessionId)
477
+ return {
478
+ sessionId: agg.sessionId,
479
+ gross: agg.gross,
480
+ offsets: agg.offsets,
481
+ net: agg.net,
482
+ source: store?.getSessionRecord(agg.sessionId)?.source ?? 'live',
483
+ integral,
484
+ ...(money === undefined ? {} : { money }),
485
+ // 当前存量(observeActive 收敛口径)——该会话在本进程内存账本中才非空
486
+ liveStock: liveSnapshot.sessions === 1 ? liveSnapshot.net : undefined,
487
+ }
488
+ }
489
+ let total = 0
490
+ const sessions: ReturnType<typeof buildRow>[] = []
491
+ if (store !== null) {
492
+ const all = store.perSessionAggregates()
493
+ const filtered = sessionId === undefined ? all : all.filter(agg => agg.sessionId === sessionId)
494
+ total = filtered.length
495
+ for (const agg of filtered.slice(offset, offset + limit)) sessions.push(buildRow(agg))
496
+ }
497
+ // 全会话积分总行("累计(按 N 次 call)")+ 省钱加权
498
+ const integralTotal = store === null
499
+ ? { netExact: 0, netEstimated: 0, cachedInput: 0, uncachedInput: 0, calls: 0 }
500
+ : store.sumSamplesAll()
501
+ const integralMoney = priceRecord === undefined || integralTotal.calls === 0
502
+ ? undefined
503
+ : estimateIntegralMoney({ cachedInput: integralTotal.cachedInput, uncachedInput: integralTotal.uncachedInput, record: priceRecord })
504
+ // live-only 补充:内存账本 top-8 中不在 store 分页里的会话(降级态/未落库
505
+ // /store 缺席),只带存量与 usage 口径,不占分页 total。
506
+ const known = new Set(sessions.map(row => row.sessionId))
507
+ const liveOnly = ledger.snapshot(undefined).perSession
508
+ .filter(row => !known.has(row.sessionId) && (sessionId === undefined || row.sessionId === sessionId))
509
+ .map(row => ({ sessionId: row.sessionId, net: row.net, requests: row.requests, cacheHitRate: row.cacheHitRate }))
510
+ resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
511
+ resTyped.end(JSON.stringify({
512
+ ok: true,
513
+ persisted: statsPersistenceState(),
514
+ displayPrefs: getDisplayPrefs(),
515
+ total,
516
+ offset,
517
+ limit,
518
+ integralTotal,
519
+ ...(integralMoney === undefined ? {} : { integralMoney }),
520
+ sessions,
521
+ liveOnly,
522
+ }))
523
+ }
524
+ try {
525
+ const disposers = SAVINGS_SESSIONS_ROUTES
526
+ .map(path => webServer.register({ kind: 'exact', path, handler }))
527
+ .filter((off): off is () => void => typeof off === 'function')
528
+ registered = true
529
+ ctx.effect(
530
+ () => () => { for (const off of disposers) off() },
531
+ 'contextCompressionSelector.savings sessions route',
532
+ )
533
+ log('info', 'context-compression savings sessions route registered (%s): %s', channel, SAVINGS_SESSIONS_ROUTES.join(', '))
534
+ } catch (error) {
535
+ if (isDuplicateRouteError(error)) {
536
+ registered = true
537
+ log('info', 'context-compression savings sessions route already registered by another mount (%s)', channel)
538
+ return
539
+ }
540
+ log('warn', 'context-compression savings sessions route registration failed (%s): %o', channel, error)
541
+ }
542
+ }
543
+
544
+ const active = asWebServer(readService('webServer'))
545
+ if (active !== undefined) {
546
+ register(active, 'direct')
547
+ if (registered) return
548
+ }
549
+
550
+ ctx.inject(['webServer'], (injected) => {
551
+ const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
552
+ if (webServer === undefined) {
553
+ log('warn', 'context-compression webServer exposes no register() — savings sessions route not registered')
554
+ return
555
+ }
556
+ register(webServer, 'inject')
557
+ })
558
+ }
559
+
560
+ /** 官方 deepseek-official 路由的现行定价记录(/ccip 面板省钱加权用);fail-closed。 */
561
+ function resolvePanelPriceRecord(readService: (name: string) => unknown): OfficialDeepSeekPriceRecord | undefined {
562
+ const defaults = readService('agentDefaultModel') as { currentSelection?: () => { provider?: unknown; model?: unknown } } | undefined
563
+ const selection = defaults?.currentSelection?.()
564
+ const provider = typeof selection?.provider === 'string' ? selection.provider : ''
565
+ const modelId = typeof selection?.model === 'string' ? selection.model : ''
566
+ if (provider !== 'deepseek-official') return undefined
567
+ const resolution = resolveOfficialDeepSeekPrice({
568
+ provider,
569
+ baseUrlClass: 'official-public',
570
+ apiRoute: 'chat-completions',
571
+ modelId,
572
+ currency: 'USD',
573
+ at: new Date(),
574
+ })
575
+ return resolution.kind === 'priced' ? resolution.record : undefined
576
+ }
577
+
578
+ /**
579
+ * 浮窗统计块(/monitor 载荷附加字段,既有字段零改动):只带最近压缩会话口径——
580
+ * 宿主不给"正在查看的会话"(输入栏注入只在页面加载时发生,切会话不重注入,
581
+ * 实测陈旧),所以服务端按 claims.at 最大者解析最近压缩会话并显式回带 id。
582
+ * 全部会话/生命周期的聚合刻意不上浮窗(设置页账本负责)。
583
+ * store 缺席 = 只剩 persisted,快照主结构不受影响。
584
+ */
585
+ function monitorStatsBlock(viewSessionId?: string): Record<string, unknown> {
586
+ const store = getStatsStore()
587
+ if (store === null) return { persisted: statsPersistenceState() }
588
+ // 当前会话解析优先级:客户端「页面所在会话」(session 作用域槽响应式下发)
589
+ // > 运行时活跃指针(请求边界) > store 最近压缩会话。
590
+ const currentSessionId = viewSessionId ?? getStatsActiveSessionId() ?? store.latestActiveSessionId()
591
+ const composition = currentSessionId === undefined ? [] : mergeCompositionByComponent(store.sessionComponents(currentSessionId))
592
+ // 会话三值(毛/抵消/净,持久口径 = jsonl 公式产物):最近压缩会话的 claims 聚合,
593
+ // 浮窗 Δ 三行据此填充(内存残量由客户端回退兜底)。
594
+ // 单一来源(用户定标):长度只认 DRS 投影,每次从替换对全量重导(毛=Σ(a−b)
595
+ // 仅压缩对,不含回吐;抵消=Σb 仅召回对;净=毛−抵消)。投影缺席/未同步该会话
596
+ // = 不下发三值(浮窗显示「–」),绝不以 claims/live 账本冒充第二来源;长度
597
+ // 新鲜度由 DRS 的 interval 同步负责(DRS 自己保证尽量跟上 jsonl)。
598
+ const drsIndex = currentSessionId === undefined ? undefined : readDrsSessionIndex({ sessionId: currentSessionId })
599
+ const drsFragment = drsIndex === undefined ? undefined : drsTotalsFragment(drsIndex)
600
+ const sessionTotals = drsFragment?.sessionTotals
601
+ const lastDelta = drsFragment?.lastDelta
602
+ const hasLastDelta = lastDelta !== undefined && (lastDelta.saving !== undefined || lastDelta.offset !== undefined)
603
+ return {
604
+ persisted: statsPersistenceState(),
605
+ ...(sessionTotals === undefined ? {} : { sessionTotals: { gross: sessionTotals.gross, offsets: sessionTotals.offsets, net: sessionTotals.net } }),
606
+ ...(hasLastDelta ? { lastDelta } : {}),
607
+ ...(composition.length > 0 ? { composition, compositionSession: currentSessionId } : {}),
608
+ }
609
+ }
610
+
404
611
  /**
405
612
  * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
406
613
  * - GET → the monitor snapshot (savings aggregate + intent control block +
@@ -433,6 +640,8 @@ export function registerMonitorRoute(ctx: Context): void {
433
640
  end: (body?: string) => void
434
641
  }
435
642
  if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
643
+ // T21:悬浮球轮询的 /monitor 与 /savings 同为首次命中触发源(闸幂等)。
644
+ kickStatsBackfillOnRouteHit()
436
645
  let sessionId: string | undefined
437
646
  try {
438
647
  const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
@@ -481,7 +690,7 @@ export function registerMonitorRoute(ctx: Context): void {
481
690
  const snapshot = buildMonitorSnapshot(sessionId)
482
691
  const pricing = estimateSavingsPricing(readService, snapshot)
483
692
  resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
484
- resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
693
+ resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }), ...monitorStatsBlock(sessionId) }))
485
694
  }
486
695
  try {
487
696
  const disposers = MONITOR_ROUTES
@@ -594,6 +803,32 @@ export function apply(ctx: Context, config: Config = {}): void {
594
803
  // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
595
804
  registerSavingsRoute(ctx)
596
805
  registerMonitorRoute(ctx)
806
+ // T24:per-session 分页面板数据面;/ccip(T29)实时控制命令。
807
+ registerSavingsSessionsRoute(ctx)
808
+ registerPanelCommand(ctx)
809
+
810
+ // 持久层主干生命周期(spec T5):open 后台 arm 不阻塞 apply(WAL 半事务
811
+ // 由 SQLite 在 open 时自动恢复,故 recover 并入 open);close 挂 ctx.effect
812
+ // 同缝清理,热重载/卸载不泄 fd。无驱动/拒开/损坏 → stats-db 内部 warn 恰
813
+ // 一次 + statsPersistenceState() 导出 persisted:false,绝不向宿主抛错。
814
+ ctx.effect(() => () => { cancelPendingUsageFlushes(); closeStatsStore() }, 'contextCompressionSelector.stats db')
815
+ void ensureStatsStore().catch(() => { /* ensureStatsStore 内部已吞错并降级为可见状态;此 catch 仅兜意外拒绝 */ })
816
+ // T21:回填触发源装配——sessionQuery 服务惰性解析(缺服务/老线宿主返回
817
+ // undefined,调度器自动走后端 B);路由 kick 在 savings/monitor 处理器内。
818
+ configureStatsBackfillTrigger({
819
+ sessionQuery: () => {
820
+ try {
821
+ const face = (ctx as unknown as { get: (service: string) => unknown }).get('sessionQuery') as
822
+ | { listSessions?: unknown; readSession?: unknown }
823
+ | undefined
824
+ return typeof face?.listSessions === 'function' && typeof face?.readSession === 'function'
825
+ ? face as unknown as import('./runtime/stats-backfill.ts').BackfillSessionQueryFace
826
+ : undefined
827
+ } catch {
828
+ return undefined
829
+ }
830
+ },
831
+ })
597
832
 
598
833
  // compat-legacy 单版本:legacy 宿主(0.1.0–0.1.5,settings.register 仍在)
599
834
  // 上租约注册压缩命名空间 + 全线挂 settings 桥路由(旧线 client 的唯一数据面;
@@ -126,6 +126,9 @@ import {
126
126
  flattenPlainText,
127
127
  } from './runtime/tokenpilot/dedup.ts'
128
128
  import { getSavingsLedger } from './runtime/savings.ts'
129
+ import { claimFromLand, flushUsageOnDispose, reclaimFromTailTrim, scheduleUsageFlush, setStatsLivePathBusy } from './runtime/stats-sync.ts'
130
+ import { kickStatsBackfillOnDispose } from './runtime/stats-backfill.ts'
131
+ import { sampleIntegralBoundary } from './runtime/savings-integral.ts'
129
132
  import { projectSessionSavings } from './runtime/savings-projection.ts'
130
133
 
131
134
  /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
@@ -169,7 +172,7 @@ import {
169
172
  priceOfficialDeepSeekUsage,
170
173
  resolveOfficialDeepSeekPrice,
171
174
  } from './runtime/deepseek-official-pricing.ts'
172
- import { emitCompressionAudit } from './runtime/audit.ts'
175
+ import { emitCompressionAudit, sanitizeAuditMessage } from './runtime/audit.ts'
173
176
  import { assertNever, deepFreeze } from './runtime/value.ts'
174
177
  import type {
175
178
  CompressionAuditComponent,
@@ -329,6 +332,11 @@ export class ToolResultPruner extends Service {
329
332
  'session/disposed',
330
333
  (session) => {
331
334
  try {
335
+ // T9:dispose 是 usage 残量出口——取消在途 debounce、立即 flush 并
336
+ // 标 source=live;老代际不发该事件时随写随刷路径不受影响。
337
+ flushUsageOnDispose(session)
338
+ // T21:dispose 后低频回填 kick(调度器内部节流,最多 10 分钟一次)。
339
+ kickStatsBackfillOnDispose()
332
340
  const line = getSavingsLedger().sessionSummaryLine(String(session.id))
333
341
  if (line.includes('requests=0') === false || line.includes('net=0(exact)/0(est)') === false) {
334
342
  ctx.logger.info('context-compression session savings (%s): %s', String(session.id), line)
@@ -472,13 +480,32 @@ export class ToolResultPruner extends Service {
472
480
  const profile = policy.profile
473
481
  const view = measureForCompaction(this.ctx, session)
474
482
  if (stage === 'fresh') {
475
- // 真实 usage 聚合(monitor 口径):官方 TokenMeter 的上一已完成请求,
476
- // 每 fresh 边界入账一次;pressure pass 读到同一 baseline,不重复计。
477
- const usage = officialRequestUsage(view)
478
- if (usage !== undefined) {
479
- getSavingsLedger().recordUsage(String(session.id), usage)
483
+ // 前台优先:整个 fresh 压缩窗口置 busy,回填调度器在 chunk 间让路
484
+ setStatsLivePathBusy(true)
485
+ try {
486
+ // 真实 usage 聚合(monitor 口径):官方 TokenMeter 的上一已完成请求,
487
+ // 每 fresh 边界入账一次;pressure pass 读到同一 baseline,不重复计。
488
+ const usage = officialRequestUsage(view)
489
+ if (usage !== undefined) {
490
+ getSavingsLedger().recordUsage(String(session.id), usage)
491
+ }
492
+ // T8:持久 usage 走事件日志 data.usage 按科目入账,一秒 debounce 合并扫描。
493
+ scheduleUsageFlush(session)
494
+ // T15:按 call 积分采样(fresh 边界 = recordUsage 同点)——存量净快照 +
495
+ // 该次 usage 拆分,累计"按 N 次 call"的真节省;前向口径,失败静默不碰请求。
496
+ try {
497
+ const integralSessionId = String(session.id)
498
+ sampleIntegralBoundary({
499
+ sessionId: integralSessionId,
500
+ session,
501
+ net: getSavingsLedger().snapshot(integralSessionId).net,
502
+ usage,
503
+ })
504
+ } catch { /* 采样失败静默:积分口径停更,不阻塞请求 */ }
505
+ return this.decideFreshStep(session, options, policy, view)
506
+ } finally {
507
+ setStatsLivePathBusy(false)
480
508
  }
481
- return this.decideFreshStep(session, options, policy, view)
482
509
  }
483
510
  if (profile === 'off') return emptyResult()
484
511
 
@@ -2417,6 +2444,14 @@ export class ToolResultPruner extends Service {
2417
2444
  replacementSeq: Number(replacement.seq),
2418
2445
  originalText: groupText,
2419
2446
  })
2447
+ // T6 接线:tail-trim 组回收的持久 saving claim(与内存账本同点同值)。
2448
+ reclaimFromTailTrim({
2449
+ sessionId: String(session.id),
2450
+ tokensBefore,
2451
+ tokensAfter,
2452
+ basis: exact ? 'exact-tokenizer' : 'characters',
2453
+ replacementSeq: Number(replacement.seq),
2454
+ })
2420
2455
  }
2421
2456
  return
2422
2457
  }
@@ -2587,6 +2622,16 @@ export class ToolResultPruner extends Service {
2587
2622
  replacementSeq: Number(replacement.seq),
2588
2623
  ...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
2589
2624
  })
2625
+ // T6 接线:主 land 的持久 saving claim——随写随刷同步小事务,失败仅门闩
2626
+ // warn 不阻断压缩主路径(stats-sync 内部兜异常)。
2627
+ claimFromLand({
2628
+ sessionId: String(session.id),
2629
+ component: plan.component,
2630
+ tokensBefore: plan.tokensBefore,
2631
+ tokensAfter: plan.tokensAfter,
2632
+ basis: plan.measurementBasis,
2633
+ replacementSeq: Number(replacement.seq),
2634
+ })
2590
2635
  return {
2591
2636
  originalSeq: candidate.seq,
2592
2637
  sourceSeq: plan.sourceSeq,
@@ -2806,7 +2851,8 @@ export class ToolResultPruner extends Service {
2806
2851
  stage,
2807
2852
  operation,
2808
2853
  errorName: error instanceof Error ? error.name : 'UnknownError',
2809
- errorMessage: error instanceof Error ? error.message : String(error),
2854
+ // T33:错误消息是审计面唯一自由文本——首行+截断净化后再进任何记录面。
2855
+ errorMessage: sanitizeAuditMessage(error),
2810
2856
  })
2811
2857
  }
2812
2858
 
@@ -301,3 +301,20 @@ export function emitCompressionAudit(
301
301
  // Swallow logger failures: audit publication must not roll back a committed rewrite.
302
302
  }
303
303
  }
304
+
305
+ /**
306
+ * errorMessage 审计净化(spec T33):首行 + 控制字符折叠 + 定长截断。
307
+ *
308
+ * 错误消息是审计面唯一的自由文本通道——审计经宿主 logger 落盘,而统计持久层
309
+ * 的隐私红线是"自由文本绝不入表"。本净化让这条通道从源头受限:多行堆栈、
310
+ * 控制字符、超长消息(可能夹带内容碎片)在进入任何记录面前先被压平。
311
+ * errorName 保持结构化(Error.name / UnknownError),不经过本净化。
312
+ */
313
+ export const AUDIT_MESSAGE_MAX_CHARS = 200
314
+
315
+ export function sanitizeAuditMessage(error: unknown): string {
316
+ const raw = error instanceof Error ? error.message : String(error)
317
+ const firstLine = raw.split(/\r?\n/u, 1)[0] ?? ''
318
+ const collapsed = firstLine.replace(/[\p{Cc}]/gu, ' ').trim()
319
+ return collapsed.length > AUDIT_MESSAGE_MAX_CHARS ? collapsed.slice(0, AUDIT_MESSAGE_MAX_CHARS) : collapsed
320
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 面板显示偏好(spec T30)——`/ccip` 命令与 `/savings/sessions` 载荷共享的
3
+ * 进程级状态,meta 表持久(跨重启恢复)。
4
+ *
5
+ * 设计:
6
+ * - 运行时单份内存状态,首次读取时从 stats meta 延迟加载(store 缺席 = 纯
7
+ * 内存默认值,可见降级语义下偏好只是不持久,功能不受损);
8
+ * - 写入走校验器(行开关布尔、mode 枚举、focusSessionId ≤512 或 null),
9
+ * 非法输入静默忽略该字段——显示偏好绝不抛错打扰命令面;
10
+ * - session 级设置是冻结语义(savings.ts 惯例),面板偏好是进程级运行时
11
+ * 状态(summary-command.ts 同款理由:实时开关无法走冻结设置)。
12
+ *
13
+ * @module dsh-context-compression-improved/runtime/display-prefs
14
+ */
15
+ import { getStatsStore } from './stats-db.ts'
16
+
17
+ const META_KEY = 'displayPrefs'
18
+
19
+ export interface PanelDisplayPrefs {
20
+ rows: { stock: boolean; total: boolean; money: boolean }
21
+ mode: 'full' | 'compact'
22
+ /** 面板聚焦会话;null = 不聚焦。`/ccip session <id|latest|off>` 的落点。 */
23
+ focusSessionId: string | null
24
+ }
25
+
26
+ const DEFAULTS: PanelDisplayPrefs = {
27
+ rows: { stock: true, total: true, money: true },
28
+ mode: 'full',
29
+ focusSessionId: null,
30
+ }
31
+
32
+ let current: PanelDisplayPrefs | undefined
33
+
34
+ function cloneDefaults(): PanelDisplayPrefs {
35
+ return { rows: { ...DEFAULTS.rows }, mode: DEFAULTS.mode, focusSessionId: DEFAULTS.focusSessionId }
36
+ }
37
+
38
+ function parsePrefs(raw: string | undefined): PanelDisplayPrefs {
39
+ if (typeof raw !== 'string' || raw === '') return cloneDefaults()
40
+ try {
41
+ const parsed = JSON.parse(raw) as Partial<PanelDisplayPrefs> | null
42
+ if (parsed === null || typeof parsed !== 'object') return cloneDefaults()
43
+ const prefs = cloneDefaults()
44
+ if (parsed.rows !== undefined && typeof parsed.rows === 'object' && parsed.rows !== null) {
45
+ for (const key of ['stock', 'total', 'money'] as const) {
46
+ const value = (parsed.rows as Record<string, unknown>)[key]
47
+ if (typeof value === 'boolean') prefs.rows[key] = value
48
+ }
49
+ }
50
+ if (parsed.mode === 'full' || parsed.mode === 'compact') prefs.mode = parsed.mode
51
+ if (parsed.focusSessionId === null) prefs.focusSessionId = null
52
+ else if (typeof parsed.focusSessionId === 'string' && parsed.focusSessionId.length > 0 && parsed.focusSessionId.length <= 512) {
53
+ prefs.focusSessionId = parsed.focusSessionId
54
+ }
55
+ return prefs
56
+ } catch {
57
+ return cloneDefaults()
58
+ }
59
+ }
60
+
61
+ /** 当前偏好(首次调用从 meta 延迟加载;store 缺席 = 默认值)。 */
62
+ export function getDisplayPrefs(): PanelDisplayPrefs {
63
+ if (current === undefined) {
64
+ current = parsePrefs(getStatsStore()?.getMeta(META_KEY))
65
+ }
66
+ return current
67
+ }
68
+
69
+ /** 打补丁式更新:仅接受字段的合法值;成功即写 meta(store 缺席只改内存)。 */
70
+ export function setDisplayPrefs(patch: {
71
+ rows?: { stock?: boolean; total?: boolean; money?: boolean }
72
+ mode?: 'full' | 'compact'
73
+ focusSessionId?: string | null
74
+ }): PanelDisplayPrefs {
75
+ const prefs = getDisplayPrefs()
76
+ if (patch.rows !== undefined && typeof patch.rows === 'object' && patch.rows !== null) {
77
+ for (const key of ['stock', 'total', 'money'] as const) {
78
+ const value = patch.rows[key]
79
+ if (typeof value === 'boolean') prefs.rows[key] = value
80
+ }
81
+ }
82
+ if (patch.mode === 'full' || patch.mode === 'compact') prefs.mode = patch.mode
83
+ if (patch.focusSessionId === null) prefs.focusSessionId = null
84
+ else if (typeof patch.focusSessionId === 'string' && patch.focusSessionId.length > 0 && patch.focusSessionId.length <= 512) {
85
+ prefs.focusSessionId = patch.focusSessionId
86
+ }
87
+ try {
88
+ getStatsStore()?.setMeta(META_KEY, JSON.stringify(prefs))
89
+ } catch {
90
+ /* 持久失败不抛:偏好保持内存态(下一次读取回退默认——可见降级口径) */
91
+ }
92
+ return prefs
93
+ }
94
+
95
+ /** 测试隔离:丢弃内存态(下次读取重新从 meta 加载)。 */
96
+ export function resetDisplayPrefsCache(): void {
97
+ current = undefined
98
+ }
@@ -28,6 +28,7 @@ export interface AgentDefaultModelLike {
28
28
 
29
29
  import { priceOfficialDeepSeekUsage } from './deepseek-official-pricing.ts'
30
30
  import { getSavingsLedger, type SavingsLedger, type SavingsSnapshot } from './savings.ts'
31
+ import type { DrsSessionIndex } from './savings-verify.ts'
31
32
  import {
32
33
  getLastIntentFold,
33
34
  getObservedIntentEnabled,
@@ -132,6 +133,32 @@ export interface ContextUsageObservation {
132
133
  const contextUsageBySession = new Map<string, ContextUsageObservation & { at: number; seq: number }>()
133
134
  const CONTEXT_USAGE_CAP = 64
134
135
 
136
+ /** 「怎么省的」组成行(浮窗)。 */
137
+ export interface CompositionRow {
138
+ component: string
139
+ basis: string
140
+ tokens: number
141
+ events: number
142
+ }
143
+
144
+ /**
145
+ * 组成按压缩路径去重合并:同路径跨口径(mixed = 精确+估算混合)一行,
146
+ * tokens 降序。重复行是口径拆分的产物,不是两条不同路径。
147
+ */
148
+ export function mergeCompositionByComponent(rows: readonly CompositionRow[]): CompositionRow[] {
149
+ const byComponent = new Map<string, CompositionRow>()
150
+ for (const row of rows) {
151
+ const found = byComponent.get(row.component)
152
+ if (found === undefined) byComponent.set(row.component, { ...row })
153
+ else {
154
+ found.tokens += row.tokens
155
+ found.events += row.events
156
+ if (found.basis !== row.basis) found.basis = 'mixed'
157
+ }
158
+ }
159
+ return [...byComponent.values()].sort((a, b) => b.tokens - a.tokens)
160
+ }
161
+
135
162
  /**
136
163
  * 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
137
164
  * contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
@@ -233,3 +260,51 @@ export function estimateSavingsPricing(readService: (name: string) => unknown, s
233
260
  ...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
234
261
  }
235
262
  }
263
+
264
+ /** DRS 主源的浮窗三值块:sessionTotals(exact/estimated 按 basis 归臂)+ 每类目最后 Δ。 */
265
+ export interface DrsTotalsFragment {
266
+ sessionTotals: {
267
+ gross: { exact: number; estimated: number }
268
+ offsets: { exact: number; estimated: number }
269
+ net: { exact: number; estimated: number }
270
+ }
271
+ lastDelta?: {
272
+ saving?: { tokens: number; seq: number }
273
+ offset?: { tokens: number; seq: number }
274
+ }
275
+ }
276
+
277
+ /**
278
+ * 「每次从头开始计算」(用户定标):三值与最后 Δ 全量重导自 DRS 投影替换对——
279
+ * 毛 = Σ(a−b) 仅压缩对(不含回吐);抵消 = Σb 仅召回对;净 = 毛 − 抵消(含回吐,
280
+ * 有召回时净必异于毛)。basis=ds-token 落 exact 臂;chars/4 落 estimated 臂
281
+ * (浮窗 est 标注如实)。同会话同对子,输出确定——单一来源,不再与 claims 残账分裂。
282
+ */
283
+ export function drsTotalsFragment(index: DrsSessionIndex): DrsTotalsFragment {
284
+ let gross = 0
285
+ let recall = 0
286
+ let saving: { tokens: number; seq: number } | undefined
287
+ let offset: { tokens: number; seq: number } | undefined
288
+ for (const pair of index.pairs) {
289
+ if (pair.kind === 'compress') {
290
+ gross += pair.aTokens - pair.bTokens
291
+ if (saving === undefined || pair.seq > saving.seq) saving = { tokens: pair.aTokens - pair.bTokens, seq: pair.seq }
292
+ } else {
293
+ recall += pair.bTokens
294
+ if (offset === undefined || pair.seq > offset.seq) offset = { tokens: pair.bTokens, seq: pair.seq }
295
+ }
296
+ }
297
+ const exact = index.basis === 'ds-token'
298
+ const arm = (value: number): { exact: number; estimated: number } =>
299
+ exact ? { exact: value, estimated: 0 } : { exact: 0, estimated: value }
300
+ const lastDelta = saving === undefined && offset === undefined
301
+ ? undefined
302
+ : {
303
+ ...(saving === undefined ? {} : { saving }),
304
+ ...(offset === undefined ? {} : { offset }),
305
+ }
306
+ return {
307
+ sessionTotals: { gross: arm(gross), offsets: arm(recall), net: arm(gross - recall) },
308
+ ...(lastDelta === undefined ? {} : { lastDelta }),
309
+ }
310
+ }