dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0

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 (83) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +401 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +44 -0
  11. package/packages/selector/lib/client.js +1733 -6
  12. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  13. package/packages/selector/lib/index.d.ts +13 -1
  14. package/packages/selector/lib/index.js +204 -3
  15. package/packages/selector/lib/profiles.d.ts +6 -0
  16. package/packages/selector/lib/pruner.d.ts +6 -0
  17. package/packages/selector/lib/pruner.js +90 -258
  18. package/packages/selector/lib/style.css +88 -46
  19. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  20. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  21. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  22. package/packages/selector/src/client/decode.ts +57 -53
  23. package/packages/selector/src/client/index.ts +307 -213
  24. package/packages/selector/src/client/locales/de.ts +141 -0
  25. package/packages/selector/src/client/locales/es.ts +141 -0
  26. package/packages/selector/src/client/locales/fr.ts +141 -0
  27. package/packages/selector/src/client/locales/it.ts +141 -0
  28. package/packages/selector/src/client/locales/ja.ts +141 -0
  29. package/packages/selector/src/client/locales/ko.ts +141 -0
  30. package/packages/selector/src/client/locales/ru.ts +141 -0
  31. package/packages/selector/src/client/locales.ts +282 -196
  32. package/packages/selector/src/client/monitor-fab.ts +336 -0
  33. package/packages/selector/src/client/savings-card.tsx +150 -0
  34. package/packages/selector/src/client/settings-section.tsx +140 -124
  35. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  36. package/packages/selector/src/index.ts +207 -5
  37. package/packages/selector/src/preset-overlay.ts +629 -629
  38. package/packages/selector/src/profiles.ts +431 -414
  39. package/packages/selector/src/pruner/content.ts +198 -198
  40. package/packages/selector/src/pruner/state.ts +57 -57
  41. package/packages/selector/src/pruner.ts +2759 -2665
  42. package/packages/selector/src/runtime/audit.ts +303 -303
  43. package/packages/selector/src/runtime/config.ts +756 -731
  44. package/packages/selector/src/runtime/monitor.ts +235 -0
  45. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  46. package/packages/selector/src/runtime/retrieve.ts +479 -457
  47. package/packages/selector/src/runtime/savings.ts +337 -0
  48. package/packages/selector/src/runtime/summary-command.ts +133 -133
  49. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  50. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  51. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  52. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  53. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  54. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  55. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  56. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  57. package/packages/selector/src/runtime/types.ts +365 -358
  58. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  59. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  60. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  61. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  62. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  63. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  64. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  65. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  66. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  67. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  69. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  70. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  71. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  72. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  73. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  74. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  75. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  76. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  77. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  78. package/scripts/packed-components-smoke.mjs +734 -734
  79. package/scripts/packed-install-e2e.mjs +1 -1
  80. package/scripts/verify-release.mjs +1 -1
  81. package/tests/TEST_INVENTORY.md +41 -41
  82. package/tsconfig.tests.json +17 -17
  83. package/vitest.config.ts +57 -57
@@ -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,133 +1,133 @@
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
- // Host session ids are strings in practice; String() keeps the legacy
64
- // best-effort coercion for exotic host shapes.
65
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
66
- return String(session.id)
67
- }
68
-
69
- type CommandsServiceLike = {
70
- register: (definition: {
71
- definitionId?: unknown
72
- name: string
73
- description: string
74
- handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: 'success' | 'error', text: string }>
75
- }) => unknown
76
- }
77
-
78
- /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
79
- async function loadCommandDefinitionId(): Promise<((id: string) => unknown) | undefined> {
80
- try {
81
- const mod = (await import('@deepseek-ai/dsh-commands')) as { CommandDefinitionId?: (id: string) => unknown }
82
- return mod.CommandDefinitionId
83
- } catch {
84
- return undefined
85
- }
86
- }
87
-
88
- /**
89
- * Mount `/ctx-summary` for every composed human-command adapter. Never
90
- * throws: the command is a convenience surface, and a host without the
91
- * commands service (or with an incompatible registry shape) simply runs
92
- * without it.
93
- */
94
- export function registerSummaryCommand(ctx: Context): void {
95
- ctx.inject(['commands'], (injected) => {
96
- const commands = (injected as { commands?: unknown }).commands as CommandsServiceLike | undefined
97
- if (commands === undefined || typeof commands.register !== 'function') return
98
- void (async () => {
99
- try {
100
- const definitionId = await loadCommandDefinitionId()
101
- await commands.register({
102
- name: SUMMARY_COMMAND_NAME,
103
- description: 'Turn-tail intent summary: temporarily disable/resume or inspect status',
104
- ...(definitionId === undefined ? {} : { definitionId: definitionId('dsh-context-compression-improved/ctx-summary') }),
105
- // The commands contract expects a promise-returning handler; the
106
- // body is fully synchronous by design (all host reads are sync).
107
- // eslint-disable-next-line @typescript-eslint/require-await
108
- handler: async (invocation) => {
109
- const rawInput = typeof invocation.rawInput === 'string' ? invocation.rawInput : ''
110
- const args = parseSummaryCommandArgs(rawInput)
111
- if (args === undefined) return { kind: 'error' as const, text: USAGE }
112
- const sessionId = sessionIdOf(invocation.agent)
113
- if (args === 'status') {
114
- if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
115
- return { kind: 'success' as const, text: formatSummaryStatus(sessionId) }
116
- }
117
- if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
118
- setSummaryOverride(sessionId, args)
119
- return {
120
- kind: 'success' as const,
121
- text: args === 'off'
122
- ? 'ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)'
123
- : 'ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)',
124
- }
125
- },
126
- })
127
- } catch {
128
- // Registry rejected the definition (shape drift, closed union): the
129
- // plugin keeps working, only the convenience command is absent.
130
- }
131
- })()
132
- })
133
- }
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
+ // Host session ids are strings in practice; String() keeps the legacy
64
+ // best-effort coercion for exotic host shapes.
65
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
66
+ return String(session.id)
67
+ }
68
+
69
+ type CommandsServiceLike = {
70
+ register: (definition: {
71
+ definitionId?: unknown
72
+ name: string
73
+ description: string
74
+ handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: 'success' | 'error', text: string }>
75
+ }) => unknown
76
+ }
77
+
78
+ /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
79
+ async function loadCommandDefinitionId(): Promise<((id: string) => unknown) | undefined> {
80
+ try {
81
+ const mod = (await import('@deepseek-ai/dsh-commands')) as { CommandDefinitionId?: (id: string) => unknown }
82
+ return mod.CommandDefinitionId
83
+ } catch {
84
+ return undefined
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Mount `/ctx-summary` for every composed human-command adapter. Never
90
+ * throws: the command is a convenience surface, and a host without the
91
+ * commands service (or with an incompatible registry shape) simply runs
92
+ * without it.
93
+ */
94
+ export function registerSummaryCommand(ctx: Context): void {
95
+ ctx.inject(['commands'], (injected) => {
96
+ const commands = (injected as { commands?: unknown }).commands as CommandsServiceLike | undefined
97
+ if (commands === undefined || typeof commands.register !== 'function') return
98
+ void (async () => {
99
+ try {
100
+ const definitionId = await loadCommandDefinitionId()
101
+ await commands.register({
102
+ name: SUMMARY_COMMAND_NAME,
103
+ description: 'Turn-tail intent summary: temporarily disable/resume or inspect status',
104
+ ...(definitionId === undefined ? {} : { definitionId: definitionId('dsh-context-compression-improved/ctx-summary') }),
105
+ // The commands contract expects a promise-returning handler; the
106
+ // body is fully synchronous by design (all host reads are sync).
107
+ // eslint-disable-next-line @typescript-eslint/require-await
108
+ handler: async (invocation) => {
109
+ const rawInput = typeof invocation.rawInput === 'string' ? invocation.rawInput : ''
110
+ const args = parseSummaryCommandArgs(rawInput)
111
+ if (args === undefined) return { kind: 'error' as const, text: USAGE }
112
+ const sessionId = sessionIdOf(invocation.agent)
113
+ if (args === 'status') {
114
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
115
+ return { kind: 'success' as const, text: formatSummaryStatus(sessionId) }
116
+ }
117
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
118
+ setSummaryOverride(sessionId, args)
119
+ return {
120
+ kind: 'success' as const,
121
+ text: args === 'off'
122
+ ? 'ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)'
123
+ : 'ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)',
124
+ }
125
+ },
126
+ })
127
+ } catch {
128
+ // Registry rejected the definition (shape drift, closed union): the
129
+ // plugin keeps working, only the convenience command is absent.
130
+ }
131
+ })()
132
+ })
133
+ }