dsh-context-compression-improved 0.2.3 → 0.2.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 (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -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
+ }
@@ -1,17 +1,30 @@
1
- /** Public Session event-log compatibility across Harness 0.1.x releases. */
2
-
3
- import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
4
-
5
- /**
6
- * Read one immutable Session event snapshot.
7
- *
8
- * Harness rc.2 exposed `events`; Alpha 5 replaced it with the public
9
- * `snapshotEvents()` method. Prefer the new API when present and retain the
10
- * old accessor as the compatibility fallback for already-supported hosts.
11
- */
12
- export function sessionEvents(session: Session): readonly SessionEvent[] {
13
- const snapshot = (session as unknown as {
14
- snapshotEvents?: () => readonly SessionEvent[]
15
- }).snapshotEvents
16
- return typeof snapshot === 'function' ? snapshot.call(session) : session.events
17
- }
1
+ /** Public Session event-log compatibility across Harness 0.1.x releases. */
2
+
3
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
4
+
5
+ /**
6
+ * Read one immutable Session event snapshot.
7
+ *
8
+ * Harness rc.2 exposed `events`; Alpha 5 replaced it with the public
9
+ * `snapshotEvents()` method. Prefer the new API when present and retain the
10
+ * old accessor as the compatibility fallback for already-supported hosts.
11
+ */
12
+ export function sessionEvents(session: Session): readonly SessionEvent[] {
13
+ const snapshot = (session as unknown as {
14
+ snapshotEvents?: () => readonly SessionEvent[]
15
+ }).snapshotEvents
16
+ if (typeof snapshot === 'function') return snapshot.call(session)
17
+ return (session as unknown as { events?: readonly SessionEvent[] }).events ?? []
18
+ }
19
+
20
+ /**
21
+ * Resolve one surface-node seq to its event. 0.1.5 surface nodes are
22
+ * positional and may replace earlier ranges, so a node's seq is not
23
+ * guaranteed to equal the snapshot array index: always resolve by seq.
24
+ */
25
+ export function eventBySeq(
26
+ events: readonly SessionEvent[],
27
+ seq: number | bigint | { valueOf(): number },
28
+ ): SessionEvent | undefined {
29
+ return events[Number(seq)]
30
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `/ctx-summary off|on|status` — in-session temporary override for the
3
+ * turn-tail intent-summary gate.
4
+ *
5
+ * The override is session-scoped by design: settings are session-frozen
6
+ * (changes only affect newly observed sessions), so "temporarily disable and
7
+ * resume" can only be expressed as runtime state. Overrides die with the
8
+ * process and never leak across sessions. `off` wins over the settings gate;
9
+ * `on` never bypasses the numeric growth gates — it only lifts the
10
+ * settings/override veto.
11
+ *
12
+ * Registration mirrors the host's own `/compact` command: optional
13
+ * `commands`-service injection (a host without the registry simply never
14
+ * mounts the command), dynamic `CommandDefinitionId` brand import with a
15
+ * plain fallback so a stripped host cannot break plugin load.
16
+ */
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import {
19
+ getLastIntentFold,
20
+ getObservedIntentEnabled,
21
+ getSummaryOverride,
22
+ setSummaryOverride,
23
+ } from './tokenpilot/advisor-state.ts'
24
+ import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
25
+
26
+ export const SUMMARY_COMMAND_NAME = 'ctx-summary'
27
+
28
+ const USAGE = 'Usage: /ctx-summary off|on|status'
29
+
30
+ export type SummaryCommandArgs = 'off' | 'on' | 'status'
31
+
32
+ /** Parse the raw argument string; `undefined` = unrecognized (usage error). */
33
+ export function parseSummaryCommandArgs(rawInput: string): SummaryCommandArgs | undefined {
34
+ const token = rawInput.trim().toLowerCase()
35
+ if (token === 'off' || token === 'on' || token === 'status') return token
36
+ return undefined
37
+ }
38
+
39
+ function describeFold(sessionId: string): string {
40
+ const fold = getLastIntentFold(sessionId)
41
+ if (fold === undefined) return 'none'
42
+ return `turn ${fold.turn}, seq ${fold.startSeq}..${fold.endSeq}`
43
+ }
44
+
45
+ /** Human-facing status line; observability only, never a decision input. */
46
+ export function formatSummaryStatus(sessionId: string): string {
47
+ const override = getSummaryOverride(sessionId)
48
+ const enabled = getObservedIntentEnabled(sessionId)
49
+ const enabledText = enabled === undefined ? 'unknown (gate not evaluated yet)' : enabled ? 'yes' : 'no'
50
+ return [
51
+ `ctx-summary status:`,
52
+ ` override: ${override ?? 'default (settings-driven)'}`,
53
+ ` intentSummary enabled (settings): ${enabledText}`,
54
+ ` gate: floor >${Math.round(INTENT_GATE_FLOOR_FRACTION * 100)}% of window AND growth >${INTENT_GATE_GROWTH_TOKENS} tokens since last fold`,
55
+ ` last fold: ${describeFold(sessionId)}`,
56
+ ].join('\n')
57
+ }
58
+
59
+ /** Resolve the invoking agent's session id (`''` when the host exposes none). */
60
+ function sessionIdOf(agent: unknown): string {
61
+ const session = (agent as { session?: { id?: unknown } } | undefined)?.session
62
+ if (session === undefined || session.id === undefined || session.id === null) return ''
63
+ return String(session.id)
64
+ }
65
+
66
+ type CommandsServiceLike = {
67
+ register: (definition: {
68
+ definitionId?: unknown
69
+ name: string
70
+ description: string
71
+ handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: 'success' | 'error', text: string }>
72
+ }) => unknown
73
+ }
74
+
75
+ /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
76
+ async function loadCommandDefinitionId(): Promise<((id: string) => unknown) | undefined> {
77
+ try {
78
+ const mod = (await import('@deepseek-ai/dsh-commands')) as { CommandDefinitionId?: (id: string) => unknown }
79
+ return mod.CommandDefinitionId
80
+ } catch {
81
+ return undefined
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Mount `/ctx-summary` for every composed human-command adapter. Never
87
+ * throws: the command is a convenience surface, and a host without the
88
+ * commands service (or with an incompatible registry shape) simply runs
89
+ * without it.
90
+ */
91
+ export function registerSummaryCommand(ctx: Context): void {
92
+ ctx.inject(['commands'], (injected) => {
93
+ const commands = (injected as { commands?: unknown }).commands as CommandsServiceLike | undefined
94
+ if (commands === undefined || typeof commands.register !== 'function') return
95
+ void (async () => {
96
+ try {
97
+ const definitionId = await loadCommandDefinitionId()
98
+ await commands.register({
99
+ name: SUMMARY_COMMAND_NAME,
100
+ description: 'Turn-tail intent summary: temporarily disable/resume or inspect status',
101
+ ...(definitionId === undefined ? {} : { definitionId: definitionId('dsh-context-compression-improved/ctx-summary') }),
102
+ handler: async (invocation) => {
103
+ const rawInput = typeof invocation.rawInput === 'string' ? invocation.rawInput : ''
104
+ const args = parseSummaryCommandArgs(rawInput)
105
+ if (args === undefined) return { kind: 'error' as const, text: USAGE }
106
+ const sessionId = sessionIdOf(invocation.agent)
107
+ if (args === 'status') {
108
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
109
+ return { kind: 'success' as const, text: formatSummaryStatus(sessionId) }
110
+ }
111
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
112
+ setSummaryOverride(sessionId, args)
113
+ return {
114
+ kind: 'success' as const,
115
+ text: args === 'off'
116
+ ? 'ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)'
117
+ : 'ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)',
118
+ }
119
+ },
120
+ })
121
+ } catch {
122
+ // Registry rejected the definition (shape drift, closed union): the
123
+ // plugin keeps working, only the convenience command is absent.
124
+ }
125
+ })()
126
+ })
127
+ }