dsh-context-compression-improved 0.5.7 → 0.5.8

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 (61) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/package.json +16 -17
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +59 -0
  5. package/packages/selector/lib/client.js +1012 -17
  6. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +295 -3
  9. package/packages/selector/lib/pruner.d.ts +65 -0
  10. package/packages/selector/lib/pruner.js +497 -262
  11. package/packages/selector/lib/style.css +42 -0
  12. package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
  13. package/packages/selector/src/client/CompressionProfileSelector.module.css +29 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  15. package/packages/selector/src/client/decode.ts +10 -2
  16. package/packages/selector/src/client/index.ts +62 -0
  17. package/packages/selector/src/client/locales/de.ts +43 -0
  18. package/packages/selector/src/client/locales/es.ts +43 -0
  19. package/packages/selector/src/client/locales/fr.ts +43 -0
  20. package/packages/selector/src/client/locales/it.ts +43 -0
  21. package/packages/selector/src/client/locales/ja.ts +43 -0
  22. package/packages/selector/src/client/locales/ko.ts +43 -0
  23. package/packages/selector/src/client/locales/ru.ts +43 -0
  24. package/packages/selector/src/client/locales.ts +86 -0
  25. package/packages/selector/src/client/monitor-fab.ts +336 -0
  26. package/packages/selector/src/client/savings-card.tsx +150 -0
  27. package/packages/selector/src/client/settings-section.tsx +18 -2
  28. package/packages/selector/src/index.ts +215 -5
  29. package/packages/selector/src/profiles.ts +37 -0
  30. package/packages/selector/src/pruner/state.ts +7 -0
  31. package/packages/selector/src/pruner.ts +337 -3
  32. package/packages/selector/src/runtime/audit.ts +17 -0
  33. package/packages/selector/src/runtime/config.ts +52 -2
  34. package/packages/selector/src/runtime/monitor.ts +235 -0
  35. package/packages/selector/src/runtime/retrieve.ts +24 -2
  36. package/packages/selector/src/runtime/savings.ts +337 -0
  37. package/packages/selector/src/runtime/summary-command.ts +127 -0
  38. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  39. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  43. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  44. package/packages/selector/src/runtime/types.ts +19 -0
  45. package/packages/selector/tests/auto-compact.client.spec.tsx +2 -1
  46. package/packages/selector/tests/code-skeleton.client.spec.ts +3 -2
  47. package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
  48. package/packages/selector/tests/estimator-channel.client.spec.tsx +1 -0
  49. package/packages/selector/tests/estimator-route-registration.host.spec.ts +10 -4
  50. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  51. package/packages/selector/tests/preset-options-write.client.spec.ts +1 -0
  52. package/packages/selector/tests/profiles.client.spec.tsx +4 -2
  53. package/packages/selector/tests/runtime/audit.spec.ts +1 -0
  54. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  55. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  56. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  57. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  58. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  59. package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
  60. package/scripts/packed-install-e2e.mjs +1 -1
  61. package/scripts/verify-release.mjs +2 -1
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Compression monitor surface for the floating panel (FAB, task: cci-monitor-fab).
3
+ *
4
+ * Three pieces, one module:
5
+ * - `buildMonitorSnapshot`: the savings snapshot (reused verbatim from the
6
+ * ledger — no second accounting) plus the turn-tail intent-summary block
7
+ * (override / observed flag / gate constants / last fold);
8
+ * - `applySessionOverride`: the `/ctx-summary` override state machine,
9
+ * addressed by session id — the panel buttons drive the same state the
10
+ * command drives, never a second one;
11
+ * - `estimateSavingsPricing`: moved here from the entry (the savings route
12
+ * and the monitor route share it; keeping it next to the monitor payload
13
+ * avoids a runtime → entry import cycle).
14
+ *
15
+ * The monitor route itself stays in the entry (`registerMonitorRoute`),
16
+ * mirroring the savings/estimator registrars: all webServer wiring lives in
17
+ * one place, the data plane lives here.
18
+ *
19
+ * Contract discipline: the published `/savings` route contract is frozen
20
+ * (estimator-route spec encodes it) — the monitor aggregates but never
21
+ * reshapes it; new fields attach under `intent` / `sessionScope`.
22
+ */
23
+
24
+ /** Current host model-group selection, when the service exposes one. */
25
+ export interface AgentDefaultModelLike {
26
+ currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
27
+ }
28
+
29
+ import { priceOfficialDeepSeekUsage } from './deepseek-official-pricing.ts'
30
+ import { getSavingsLedger, type SavingsLedger, type SavingsSnapshot } from './savings.ts'
31
+ import {
32
+ getLastIntentFold,
33
+ getObservedIntentEnabled,
34
+ getSummaryOverride,
35
+ setSummaryOverride,
36
+ type IntentFoldRecord,
37
+ } from './tokenpilot/advisor-state.ts'
38
+ import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
39
+
40
+ /**
41
+ * 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
42
+ * 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
43
+ * (默认 80%)——提前一档给出人工干预窗口。
44
+ */
45
+ export const MONITOR_SUGGEST_PCT = 0.7
46
+
47
+ export interface MonitorIntentBlock {
48
+ /** Session-scoped override; absent = settings-driven. */
49
+ override: 'on' | 'off' | undefined
50
+ /** Settings flag as last observed by the gate; absent = gate not evaluated yet. */
51
+ observedEnabled: boolean | undefined
52
+ gate: { floorFraction: number, growthTokens: number }
53
+ lastFold: IntentFoldRecord | undefined
54
+ }
55
+
56
+ export interface MonitorContextBlock {
57
+ liveTokens: number
58
+ contextWindow: number | undefined
59
+ /** liveTokens / contextWindow, rounded to 3 decimals; null when the window is unknown. */
60
+ pct: number | null
61
+ sessionId: string
62
+ }
63
+
64
+ export interface MonitorSuggestionBlock {
65
+ /** 占用达到建议阈值——客户端点亮悬浮球并展示提示行。 */
66
+ suggest: boolean
67
+ thresholdPct: number
68
+ occupancyPct: number | null
69
+ }
70
+
71
+ export type MonitorSnapshot = SavingsSnapshot & {
72
+ intent: MonitorIntentBlock
73
+ /** Latest observed context occupancy; undefined until the pruner observes a turn. */
74
+ context?: MonitorContextBlock
75
+ /** 灾难性遗忘区建议;未观测前 absent。 */
76
+ suggestion?: MonitorSuggestionBlock
77
+ /** The session the snapshot was filtered to; `null` = all-sessions aggregate. */
78
+ sessionScope: string | null
79
+ }
80
+
81
+ /**
82
+ * Savings snapshot plus the intent-summary control block. Ledger is
83
+ * injectable so tests seed a private instance instead of the process
84
+ * singleton.
85
+ */
86
+ export function buildMonitorSnapshot(
87
+ sessionId?: string,
88
+ ledger: SavingsLedger = getSavingsLedger(),
89
+ ): MonitorSnapshot {
90
+ const scopeKey = sessionId ?? ''
91
+ const override = getSummaryOverride(scopeKey)
92
+ const observedContext = scopeKey.length > 0
93
+ ? getContextUsage(scopeKey)
94
+ : latestObservedContextUsage()
95
+ const contextBlock = observedContext === undefined
96
+ ? undefined
97
+ : {
98
+ liveTokens: observedContext.liveTokens,
99
+ contextWindow: observedContext.contextWindow,
100
+ pct: observedContext.contextWindow !== undefined && observedContext.contextWindow > 0
101
+ ? Math.round((observedContext.liveTokens / observedContext.contextWindow) * 1000) / 1000
102
+ : null,
103
+ sessionId: observedContext.sessionId,
104
+ }
105
+ const suggestion = contextBlock === undefined || contextBlock.pct === null
106
+ ? undefined
107
+ : {
108
+ suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
109
+ thresholdPct: MONITOR_SUGGEST_PCT,
110
+ occupancyPct: contextBlock.pct,
111
+ }
112
+ return {
113
+ ...ledger.snapshot(sessionId),
114
+ ...(contextBlock === undefined ? {} : { context: contextBlock }),
115
+ ...(suggestion === undefined ? {} : { suggestion }),
116
+ intent: {
117
+ override,
118
+ observedEnabled: getObservedIntentEnabled(scopeKey),
119
+ gate: { floorFraction: INTENT_GATE_FLOOR_FRACTION, growthTokens: INTENT_GATE_GROWTH_TOKENS },
120
+ lastFold: getLastIntentFold(scopeKey),
121
+ },
122
+ sessionScope: sessionId ?? null,
123
+ }
124
+ }
125
+
126
+ export interface ContextUsageObservation {
127
+ liveTokens: number
128
+ contextWindow: number | undefined
129
+ }
130
+
131
+ /** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
132
+ const contextUsageBySession = new Map<string, ContextUsageObservation & { at: number; seq: number }>()
133
+ const CONTEXT_USAGE_CAP = 64
134
+
135
+ /**
136
+ * 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
137
+ * contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
138
+ */
139
+ export function observeContextUsage(sessionId: string, liveTokens: number, contextWindow: number | undefined): void {
140
+ if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return
141
+ if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
142
+ const oldest = contextUsageBySession.keys().next().value
143
+ if (oldest !== undefined) contextUsageBySession.delete(oldest)
144
+ }
145
+ contextUsageBySession.set(sessionId, { liveTokens, contextWindow, at: Date.now(), seq: ++observeSeq })
146
+ }
147
+
148
+ export function getContextUsage(sessionId: string): (ContextUsageObservation & { sessionId: string }) | undefined {
149
+ const entry = contextUsageBySession.get(sessionId)
150
+ return entry === undefined ? undefined : { liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, sessionId }
151
+ }
152
+
153
+ let observeSeq = 0
154
+
155
+ function latestObservedContextUsage(): (ContextUsageObservation & { sessionId: string }) | undefined {
156
+ let latest: (ContextUsageObservation & { sessionId: string; seq: number }) | undefined
157
+ for (const [sessionId, entry] of contextUsageBySession) {
158
+ if (latest === undefined || entry.seq > latest.seq) latest = { sessionId, liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, seq: entry.seq }
159
+ }
160
+ return latest
161
+ }
162
+
163
+ export type SessionOverrideAction = 'on' | 'off' | 'clear'
164
+
165
+ export function isSessionOverrideAction(value: unknown): value is SessionOverrideAction {
166
+ return value === 'on' || value === 'off' || value === 'clear'
167
+ }
168
+
169
+ /**
170
+ * Drive the `/ctx-summary` override state machine: `on`/`off` pin the
171
+ * session, `clear` returns it to settings-driven. The resulting override is
172
+ * handed back so the route can echo the post-action truth.
173
+ */
174
+ export function applySessionOverride(
175
+ sessionId: string,
176
+ action: SessionOverrideAction,
177
+ ): { override: 'on' | 'off' | undefined } {
178
+ setSummaryOverride(sessionId, action === 'clear' ? undefined : action)
179
+ return { override: getSummaryOverride(sessionId) }
180
+ }
181
+
182
+ /**
183
+ * 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
184
+ * - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
185
+ * - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
186
+ * 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
187
+ * 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
188
+ * (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
189
+ */
190
+ export function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
191
+ startedAt: string
192
+ net: { exact: number; estimated: number }
193
+ usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
194
+ }): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
195
+ if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
196
+ const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
197
+ const selection = defaults?.currentSelection?.()
198
+ const provider = typeof selection?.provider === 'string' ? selection.provider : ''
199
+ const modelId = typeof selection?.model === 'string' ? selection.model : ''
200
+ if (provider !== 'deepseek-official') return undefined
201
+ const now = new Date()
202
+ const startedAt = new Date(snapshot.startedAt)
203
+ const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
204
+ const base = {
205
+ provider,
206
+ baseUrlClass: 'official-public',
207
+ apiRoute: 'chat-completions',
208
+ modelId,
209
+ currency: 'USD',
210
+ startedAt,
211
+ completedAt,
212
+ } as const
213
+ const actual = priceOfficialDeepSeekUsage({
214
+ ...base,
215
+ usage: {
216
+ cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
217
+ cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
218
+ outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
219
+ },
220
+ })
221
+ const saved = snapshot.net.exact > 0
222
+ ? priceOfficialDeepSeekUsage({
223
+ ...base,
224
+ usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
225
+ })
226
+ : undefined
227
+ const decimalOf = (cost: typeof actual): string | undefined =>
228
+ cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
229
+ if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
230
+ return {
231
+ currency: 'USD',
232
+ ...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
233
+ ...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
234
+ }
235
+ }
@@ -19,6 +19,7 @@ import {
19
19
  type PublishedTailTrim,
20
20
  } from './tail-trim.ts'
21
21
  import { sessionEvents } from './session-events.ts'
22
+ import { getSavingsLedger } from './savings.ts'
22
23
 
23
24
  export const name = 'context-compression-retrieve'
24
25
  export const inject = ['tools', 'systemPrompt']
@@ -94,6 +95,7 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
94
95
  throw new Error('context_compression_retrieve: a compression reference may only read the caller\'s current session')
95
96
  }
96
97
  if (tailTrimRef !== null) {
98
+ const sessionId = String(exec.agent.id)
97
99
  return Promise.resolve(recoverTailTrim(
98
100
  exec.agent.session,
99
101
  args.ref,
@@ -102,7 +104,18 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
102
104
  args.start_line,
103
105
  args.max_lines,
104
106
  { maxChars, maxScanChars, maxQueryChars },
105
- ))
107
+ )).then((text: string) => {
108
+ // 节省统计:回读内容重新进入上下文 = 对该组原声称节省的抵消
109
+ // (chars/4 估算口径;retrieve 不持有精确 counter 身份,分列不混算)。
110
+ getSavingsLedger().recordOffset({
111
+ sessionId,
112
+ component: 'tailtrim-retrieve',
113
+ tokens: Math.ceil(codePointLength(text) / 4),
114
+ basis: 'characters',
115
+ note: `tailtrim/${tailTrimRef.manifestSeq} 回读`,
116
+ })
117
+ return text
118
+ })
106
119
  }
107
120
  const seq = Number(match?.[2])
108
121
  const event = sessionEvents(exec.agent.session)[seq]
@@ -140,7 +153,16 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
140
153
  '--- original tool result ---',
141
154
  ].filter(Boolean).join('\n')
142
155
  const output = `${header}\n${selected.text}`
143
- return Promise.resolve(boundCodePoints(output, maxChars))
156
+ const bounded = boundCodePoints(output, maxChars)
157
+ // 节省统计:retrieve 产物重新进入上下文 = 抵消(chars/4 估算口径)。
158
+ getSavingsLedger().recordOffset({
159
+ sessionId: String(exec.agent.id),
160
+ component: 'retrieve',
161
+ tokens: Math.ceil(codePointLength(bounded) / 4),
162
+ basis: 'characters',
163
+ note: `event/${String(seq)} 回读`,
164
+ })
165
+ return Promise.resolve(bounded)
144
166
  },
145
167
  }))
146
168
  }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * 节省统计账本(诚实口径)。
3
+ *
4
+ * 原则(与 dsh-token-optimizer 类功能对齐的需求口径):
5
+ * 1. **只记已实现**:抵扣来自真实落盘的 rewrite(published replacement)的
6
+ * tokensBefore − tokensAfter,不按"本可以压多少"的最大值计;
7
+ * 2. **负节省(配对抵消)**:同一份原文先被压缩(代码骨架/历史老化/去重指针/
8
+ * 尾裁引用)后,模型又请求了全文——原声称的节省被抵消:全文读取本身
9
+ * 记为负项。净额因此可以为负(骨架 S + 全文 O,对比从未压缩的基线 O,
10
+ * 净 −S),这正是"先骨架再全文 = 负节省"的诚实口径;
11
+ * 3. **口径分列,不混算**:精确 tokenizer 与 chars/4 估算两个 basis 各自独立
12
+ * 汇总,永不合并成一个数。
13
+ *
14
+ * 存储:进程内 per-session 账本(条目环形缓冲 + hash 注册表)。不落盘——
15
+ * 节省统计是运行期面板数据,重启归零是可接受语义(审计日志里已有全量原始记录)。
16
+ *
17
+ * @module dsh-context-compression-improved/runtime/savings
18
+ */
19
+ import { createHash } from 'node:crypto'
20
+
21
+ export type SavingsBasis = 'exact-tokenizer' | 'characters'
22
+
23
+ export interface SavingsEntry {
24
+ kind: 'saving' | 'offset'
25
+ /** 保存组件(fresh/aggregate/history/tail-trim/dedupe)或抵消原因(full-read/retrieve)。 */
26
+ component: string
27
+ tokens: number
28
+ basis: SavingsBasis
29
+ at: number
30
+ note?: string
31
+ }
32
+
33
+ interface RegistryItem {
34
+ sessionId: string
35
+ component: string
36
+ /** 压缩时声称省下的 token 数(抵消时按此科目回冲)。 */
37
+ claimedTokens: number
38
+ basis: SavingsBasis
39
+ sourceSeq: number
40
+ consumed: boolean
41
+ }
42
+
43
+ const MAX_ENTRIES_PER_SESSION = 400
44
+ const MAX_REGISTRY = 2048
45
+
46
+ export class SavingsLedger {
47
+ private readonly entries = new Map<string, SavingsEntry[]>()
48
+ private readonly registry = new Map<string, RegistryItem>()
49
+ private readonly seenFullText = new Set<string>()
50
+ private readonly usage = new Map<string, SessionUsageTotals>()
51
+ private startedAt = Date.now()
52
+
53
+ /**
54
+ * 累计一次官方 usage(request-boundary 读取上一已完成请求;末次请求在
55
+ * dispose 汇总前未入账属可接受低估)。usage 字段缺省按 0 计。
56
+ */
57
+ recordUsage(sessionId: string, usage: {
58
+ inputTokens?: number
59
+ outputTokens?: number
60
+ cacheReadTokens?: number
61
+ cacheWriteTokens?: number
62
+ }): void {
63
+ let total = this.usage.get(sessionId)
64
+ if (total === undefined) {
65
+ total = { requests: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
66
+ this.usage.set(sessionId, total)
67
+ }
68
+ total.requests += 1
69
+ total.inputTokens += positiveOrZero(usage.inputTokens)
70
+ total.outputTokens += positiveOrZero(usage.outputTokens)
71
+ total.cacheReadTokens += positiveOrZero(usage.cacheReadTokens)
72
+ total.cacheWriteTokens += positiveOrZero(usage.cacheWriteTokens)
73
+ }
74
+
75
+ private totalsFor(scope: readonly string[]): SessionUsageTotals {
76
+ const sum: SessionUsageTotals = { requests: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
77
+ for (const sid of scope) {
78
+ const t = this.usage.get(sid)
79
+ if (t === undefined) continue
80
+ sum.requests += t.requests
81
+ sum.inputTokens += t.inputTokens
82
+ sum.outputTokens += t.outputTokens
83
+ sum.cacheReadTokens += t.cacheReadTokens
84
+ sum.cacheWriteTokens += t.cacheWriteTokens
85
+ }
86
+ return sum
87
+ }
88
+
89
+ /** 单行会话汇总(session/disposed 日志用)。 */
90
+ sessionSummaryLine(sessionId: string): string {
91
+ const snap = this.snapshot(sessionId)
92
+ const hit = snap.usage.cacheHitRate
93
+ return `net=${snap.net.exact}(exact)/${snap.net.estimated}(est) ` +
94
+ `gross=${snap.gross.exact}/${snap.gross.estimated} offsets=${snap.offsets.exact}/${snap.offsets.estimated} ` +
95
+ `requests=${snap.usage.requests} cacheHit=${hit === null ? '–' : `${Math.round(hit * 100)}%`}`
96
+ }
97
+
98
+ /** 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。 */
99
+ recordSaving(input: {
100
+ sessionId: string
101
+ component: string
102
+ tokensBefore: number
103
+ tokensAfter: number
104
+ basis: SavingsBasis
105
+ sourceSeq: number
106
+ /** 原文全文(配对键;哈希后不存原文)。 */
107
+ originalText?: string
108
+ }): void {
109
+ const removed = input.tokensBefore - input.tokensAfter
110
+ if (!Number.isFinite(removed) || removed <= 0) return
111
+ this.push(input.sessionId, {
112
+ kind: 'saving',
113
+ component: input.component,
114
+ tokens: removed,
115
+ basis: input.basis,
116
+ at: Date.now(),
117
+ })
118
+ if (typeof input.originalText === 'string' && input.originalText.length > 0) {
119
+ const hash = savingsHash(input.originalText)
120
+ if (this.registry.size >= MAX_REGISTRY && !this.registry.has(hash)) {
121
+ const oldest = this.registry.keys().next().value
122
+ if (oldest !== undefined) this.registry.delete(oldest)
123
+ }
124
+ this.registry.set(hash, {
125
+ sessionId: input.sessionId,
126
+ component: input.component,
127
+ claimedTokens: removed,
128
+ basis: input.basis,
129
+ sourceSeq: input.sourceSeq,
130
+ consumed: false,
131
+ })
132
+ }
133
+ }
134
+
135
+ /**
136
+ * 新的全文工具结果进入上下文(每个 (session, seq) 只看一次):若其原文哈希
137
+ * 命中之前压缩过的条目且未消费过抵消 → 记负项并消费。
138
+ * @param measure 返回 {tokens, basis}——全文按当前可用口径计量。
139
+ */
140
+ noteFullText(input: {
141
+ sessionId: string
142
+ seq: number
143
+ text: string
144
+ measure: (text: string) => { tokens: number; basis: SavingsBasis }
145
+ }): void {
146
+ if (typeof input.text !== 'string' || input.text.length === 0) return
147
+ const seenKey = `${input.sessionId}:${input.seq}`
148
+ if (this.seenFullText.has(seenKey)) return
149
+ this.seenFullText.add(seenKey)
150
+ if (this.seenFullText.size > MAX_REGISTRY * 4) {
151
+ // 粗放防胀:超过容量上限时整体清空(成员只是防重哨兵,漏一次重复探测无害)
152
+ this.seenFullText.clear()
153
+ this.seenFullText.add(seenKey)
154
+ }
155
+ const hit = this.registry.get(savingsHash(input.text))
156
+ if (hit === undefined || hit.consumed || hit.sessionId !== input.sessionId) return
157
+ hit.consumed = true
158
+ const { tokens, basis } = input.measure(input.text)
159
+ if (tokens <= 0) return
160
+ this.push(input.sessionId, {
161
+ kind: 'offset',
162
+ component: 'full-read',
163
+ tokens,
164
+ basis,
165
+ at: Date.now(),
166
+ note: `#${hit.sourceSeq} ${hit.component} 的原文被全文重读(原声称 −${hit.claimedTokens})`,
167
+ })
168
+ }
169
+
170
+ /** retrieve 回读(部分或全部)重新进入上下文:按返回内容计量记负项。 */
171
+ recordOffset(input: {
172
+ sessionId: string
173
+ component: 'retrieve' | 'tailtrim-retrieve'
174
+ tokens: number
175
+ basis: SavingsBasis
176
+ note?: string
177
+ }): void {
178
+ if (!Number.isFinite(input.tokens) || input.tokens <= 0) return
179
+ this.push(input.sessionId, {
180
+ kind: 'offset',
181
+ component: input.component,
182
+ tokens: input.tokens,
183
+ basis: input.basis,
184
+ at: Date.now(),
185
+ ...(input.note === undefined ? {} : { note: input.note }),
186
+ })
187
+ }
188
+
189
+ private sourceSeqOf(item: RegistryItem): number {
190
+ return item.sourceSeq
191
+ }
192
+
193
+ private push(sessionId: string, entry: SavingsEntry): void {
194
+ let list = this.entries.get(sessionId)
195
+ if (list === undefined) {
196
+ list = []
197
+ this.entries.set(sessionId, list)
198
+ }
199
+ list.push(entry)
200
+ if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION)
201
+ }
202
+
203
+ /** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
204
+ snapshot(sessionId?: string): SavingsSnapshot {
205
+ const scope = sessionId === undefined ? [...this.entries.keys()] : [sessionId]
206
+ const totals = { grossExact: 0, grossEstimated: 0, offsetExact: 0, offsetEstimated: 0 }
207
+ const perComponent = new Map<string, { component: string; tokens: number; basis: SavingsBasis; kind: 'saving' | 'offset' }>()
208
+ const recentOffsets: SavingsEntry[] = []
209
+ for (const sid of scope) {
210
+ for (const entry of this.entries.get(sid) ?? []) {
211
+ const exact = entry.basis === 'exact-tokenizer'
212
+ if (entry.kind === 'saving') {
213
+ if (exact) totals.grossExact += entry.tokens
214
+ else totals.grossEstimated += entry.tokens
215
+ } else {
216
+ if (exact) totals.offsetExact += entry.tokens
217
+ else totals.offsetEstimated += entry.tokens
218
+ recentOffsets.push(entry)
219
+ }
220
+ const key = `${entry.kind}:${entry.component}:${entry.basis}`
221
+ const agg = perComponent.get(key)
222
+ if (agg === undefined) {
223
+ perComponent.set(key, { component: entry.component, tokens: entry.tokens, basis: entry.basis, kind: entry.kind })
224
+ } else {
225
+ agg.tokens += entry.tokens
226
+ }
227
+ }
228
+ }
229
+ recentOffsets.sort((a, b) => b.at - a.at)
230
+ const usageTotals = this.totalsFor(scope)
231
+ // 按会话分桶(monitor 口径):净额精确口径降序,前 8
232
+ const perSession = sessionId === undefined
233
+ ? [...new Set([...this.entries.keys(), ...this.usage.keys()])]
234
+ .map(sid => {
235
+ const s = this.snapshot(sid)
236
+ return {
237
+ sessionId: sid,
238
+ gross: s.gross,
239
+ offsets: s.offsets,
240
+ net: s.net,
241
+ requests: s.usage.requests,
242
+ cacheHitRate: s.usage.cacheHitRate,
243
+ }
244
+ })
245
+ .sort((a, b) => (b.net.exact - a.net.exact) || (b.net.estimated - a.net.estimated))
246
+ .slice(0, 8)
247
+ : []
248
+ return {
249
+ startedAt: new Date(this.startedAt).toISOString(),
250
+ sessions: sessionId === undefined ? this.entries.size : this.entries.has(sessionId) ? 1 : 0,
251
+ gross: { exact: totals.grossExact, estimated: totals.grossEstimated },
252
+ offsets: { exact: totals.offsetExact, estimated: totals.offsetEstimated },
253
+ net: {
254
+ exact: totals.grossExact - totals.offsetExact,
255
+ estimated: totals.grossEstimated - totals.offsetEstimated,
256
+ },
257
+ perComponent: [...perComponent.values()].sort((a, b) => b.tokens - a.tokens),
258
+ recentOffsets: recentOffsets.slice(0, 8).map((e) => ({
259
+ component: e.component,
260
+ tokens: e.tokens,
261
+ basis: e.basis,
262
+ at: new Date(e.at).toISOString(),
263
+ ...(e.note === undefined ? {} : { note: e.note }),
264
+ })),
265
+ usage: { ...usageTotals, cacheHitRate: cacheHitRateOf(usageTotals) },
266
+ perSession,
267
+ }
268
+ }
269
+
270
+ /** 测试与停机清理。 */
271
+ clear(): void {
272
+ this.entries.clear()
273
+ this.registry.clear()
274
+ this.seenFullText.clear()
275
+ this.usage.clear()
276
+ this.startedAt = Date.now()
277
+ }
278
+ }
279
+
280
+ export interface SavingsSnapshot {
281
+ startedAt: string
282
+ sessions: number
283
+ gross: { exact: number; estimated: number }
284
+ offsets: { exact: number; estimated: number }
285
+ net: { exact: number; estimated: number }
286
+ perComponent: Array<{ component: string; tokens: number; basis: SavingsBasis; kind: 'saving' | 'offset' }>
287
+ recentOffsets: Array<{ component: string; tokens: number; basis: SavingsBasis; at: string; note?: string }>
288
+ /** 真实 usage 聚合(monitor 模块学到的口径:官方 usage 而非估算)。 */
289
+ usage: SessionUsageTotals & { cacheHitRate: number | null }
290
+ /** 按会话分桶(仅全会话聚合时;按净额精确口径降序,前 8)。 */
291
+ perSession: Array<{
292
+ sessionId: string
293
+ gross: { exact: number; estimated: number }
294
+ offsets: { exact: number; estimated: number }
295
+ net: { exact: number; estimated: number }
296
+ requests: number
297
+ cacheHitRate: number | null
298
+ }>
299
+ }
300
+
301
+ /** 单会话真实 usage 累计(官方 TokenMeter 口径)。 */
302
+ export interface SessionUsageTotals {
303
+ requests: number
304
+ inputTokens: number
305
+ outputTokens: number
306
+ cacheReadTokens: number
307
+ cacheWriteTokens: number
308
+ }
309
+
310
+ function cacheHitRateOf(t: { inputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }): number | null {
311
+ const denom = t.inputTokens + t.cacheReadTokens + t.cacheWriteTokens
312
+ return denom <= 0 ? null : Math.round((t.cacheReadTokens / denom) * 1000) / 1000
313
+ }
314
+
315
+ /** 原文配对哈希(规整行尾与首尾空白——同一文件两次读取的 innocuous 差异不配错)。 */
316
+ export function savingsHash(text: string): string {
317
+ return createHash('sha256')
318
+ .update(
319
+ text
320
+ .replace(/\r\n?/g, '\n')
321
+ .replace(/[ \t]+\n/g, '\n')
322
+ .replace(/(^\s+)|(\s+$)/g, ''),
323
+ 'utf8',
324
+ )
325
+ .digest('hex')
326
+ }
327
+
328
+ function positiveOrZero(v: unknown): number {
329
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.round(v) : 0
330
+ }
331
+
332
+ const singleton = new SavingsLedger()
333
+
334
+ /** 模块级单例:pruner 与 retrieve 分处两文件,共享同一本账。 */
335
+ export function getSavingsLedger(): SavingsLedger {
336
+ return singleton
337
+ }