dsh-context-compression-improved 0.10.0 → 0.10.2

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 (262) hide show
  1. package/README.md +15 -110
  2. package/README.zh.md +14 -104
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
  5. package/{packages/selector/lib → lib}/client.js +73 -12
  6. package/package.json +129 -116
  7. package/screenshots.json +3 -6
  8. package/.agents/plans/improve/checklist.md +0 -32
  9. package/.agents/plans/improve/findings.md +0 -102
  10. package/.agents/plans/improve/spec.md +0 -53
  11. package/.agents/plans/improve/tasks.md +0 -70
  12. package/.gitattributes +0 -2
  13. package/.githooks/pre-push +0 -37
  14. package/.github/workflows/ci.yml +0 -39
  15. package/CHANGELOG.de.md +0 -580
  16. package/CHANGELOG.es.md +0 -588
  17. package/CHANGELOG.fr.md +0 -576
  18. package/CHANGELOG.it.md +0 -577
  19. package/CHANGELOG.ja.md +0 -261
  20. package/CHANGELOG.ko.md +0 -254
  21. package/CHANGELOG.md +0 -544
  22. package/CHANGELOG.ru.md +0 -554
  23. package/CHANGELOG.zh.md +0 -238
  24. package/CONTRIBUTING.md +0 -22
  25. package/README.de.md +0 -96
  26. package/README.es.md +0 -96
  27. package/README.fr.md +0 -96
  28. package/README.it.md +0 -96
  29. package/README.ja.md +0 -102
  30. package/README.ko.md +0 -102
  31. package/README.ru.md +0 -96
  32. package/SECURITY.md +0 -18
  33. package/assets/board.png +0 -0
  34. package/assets/context.png +0 -0
  35. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  36. package/docs/assets/context-compression-selector-settings.png +0 -0
  37. package/docs/compat-0.1.5-report.md +0 -77
  38. package/docs/installation.de.md +0 -104
  39. package/docs/installation.es.md +0 -104
  40. package/docs/installation.fr.md +0 -104
  41. package/docs/installation.it.md +0 -104
  42. package/docs/installation.ja.md +0 -78
  43. package/docs/installation.ko.md +0 -78
  44. package/docs/installation.md +0 -103
  45. package/docs/installation.ru.md +0 -104
  46. package/docs/installation.zh.md +0 -100
  47. package/docs/repair-log.md +0 -657
  48. package/eslint.config.js +0 -30
  49. package/packages/selector/LICENSE +0 -21
  50. package/packages/selector/README.md +0 -26
  51. package/packages/selector/README.zh.md +0 -24
  52. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  53. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  54. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  55. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  56. package/packages/selector/lib/style.css +0 -350
  57. package/packages/selector/package.json +0 -178
  58. package/packages/selector/screenshots.json +0 -3
  59. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  60. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  61. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  62. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  63. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  64. package/packages/selector/src/client/bridge-scope.ts +0 -125
  65. package/packages/selector/src/client/decode.ts +0 -57
  66. package/packages/selector/src/client/index.ts +0 -424
  67. package/packages/selector/src/client/locales/de.ts +0 -158
  68. package/packages/selector/src/client/locales/es.ts +0 -158
  69. package/packages/selector/src/client/locales/fr.ts +0 -158
  70. package/packages/selector/src/client/locales/it.ts +0 -158
  71. package/packages/selector/src/client/locales/ja.ts +0 -158
  72. package/packages/selector/src/client/locales/ko.ts +0 -158
  73. package/packages/selector/src/client/locales/ru.ts +0 -158
  74. package/packages/selector/src/client/locales.ts +0 -316
  75. package/packages/selector/src/client/monitor-fab.ts +0 -419
  76. package/packages/selector/src/client/preset-options.ts +0 -88
  77. package/packages/selector/src/client/savings-card.tsx +0 -269
  78. package/packages/selector/src/client/scope-face.ts +0 -24
  79. package/packages/selector/src/client/settings-section.tsx +0 -140
  80. package/packages/selector/src/compat/host-generation.ts +0 -96
  81. package/packages/selector/src/compat/llm-messages.ts +0 -50
  82. package/packages/selector/src/compat/settings-lease.ts +0 -108
  83. package/packages/selector/src/compat/tool-result.ts +0 -91
  84. package/packages/selector/src/css-modules.d.ts +0 -6
  85. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  86. package/packages/selector/src/estimator-catalog.ts +0 -104
  87. package/packages/selector/src/index.ts +0 -890
  88. package/packages/selector/src/invariant.ts +0 -113
  89. package/packages/selector/src/preset-overlay.ts +0 -749
  90. package/packages/selector/src/profiles.ts +0 -431
  91. package/packages/selector/src/pruner/content.ts +0 -198
  92. package/packages/selector/src/pruner/session.ts +0 -97
  93. package/packages/selector/src/pruner/state.ts +0 -61
  94. package/packages/selector/src/pruner/tuning.ts +0 -23
  95. package/packages/selector/src/pruner/types.ts +0 -78
  96. package/packages/selector/src/pruner.ts +0 -2914
  97. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  98. package/packages/selector/src/runtime/audit.ts +0 -320
  99. package/packages/selector/src/runtime/config.ts +0 -756
  100. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  101. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  102. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  103. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  104. package/packages/selector/src/runtime/measurement.ts +0 -444
  105. package/packages/selector/src/runtime/monitor.ts +0 -310
  106. package/packages/selector/src/runtime/panel-command.ts +0 -213
  107. package/packages/selector/src/runtime/reducers.ts +0 -1754
  108. package/packages/selector/src/runtime/retrieve.ts +0 -503
  109. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  110. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  111. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  112. package/packages/selector/src/runtime/savings.ts +0 -526
  113. package/packages/selector/src/runtime/session-events.ts +0 -30
  114. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  115. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  116. package/packages/selector/src/runtime/stats-db.ts +0 -492
  117. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  118. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  119. package/packages/selector/src/runtime/summary-command.ts +0 -127
  120. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  121. package/packages/selector/src/runtime/token-count.ts +0 -72
  122. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  123. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  124. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  125. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  126. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  127. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  128. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  129. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  130. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  131. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  132. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  133. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  134. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  135. package/packages/selector/src/runtime/toolclass.ts +0 -103
  136. package/packages/selector/src/runtime/types.ts +0 -365
  137. package/packages/selector/src/runtime/value.ts +0 -48
  138. package/packages/selector/src/settings-bridge.ts +0 -175
  139. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  140. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  141. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  142. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  143. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  144. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  145. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  146. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  147. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  148. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  149. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  150. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  155. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  156. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -220
  157. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  158. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  159. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  160. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  161. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  162. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  163. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  164. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  165. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  166. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  167. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  168. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  169. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  170. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  171. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  172. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  173. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  174. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  175. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  176. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  177. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  178. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  179. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  180. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  181. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  182. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  183. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  184. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  185. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  186. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  187. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  188. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2781
  189. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  190. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  191. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  192. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  193. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  194. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  195. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  196. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  197. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  198. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  199. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  200. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  201. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -348
  202. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  203. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  204. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  205. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  206. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  207. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  208. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  209. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  210. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  211. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  212. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  213. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  214. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  215. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  216. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  217. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  218. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  219. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  220. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  221. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  222. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  223. package/packages/selector/tsconfig.json +0 -11
  224. package/packages/selector/tsdown.client.config.ts +0 -102
  225. package/packages/selector/tsdown.config.ts +0 -20
  226. package/pnpm-workspace.yaml +0 -76
  227. package/scripts/capture-profile-baseline.mjs +0 -42
  228. package/scripts/cell-browser-e2e.mjs +0 -354
  229. package/scripts/generate-tokenizer-fixtures.py +0 -81
  230. package/scripts/generate-vision-fixtures.py +0 -208
  231. package/scripts/hosts.mjs +0 -78
  232. package/scripts/packed-components-smoke.mjs +0 -763
  233. package/scripts/packed-install-e2e.mjs +0 -1346
  234. package/scripts/sync-hosts.mjs +0 -174
  235. package/scripts/toolclass-corpus-replay.mjs +0 -281
  236. package/scripts/verify-release.mjs +0 -338
  237. package/tests/TEST_INVENTORY.md +0 -41
  238. package/tsconfig.base.json +0 -18
  239. package/tsconfig.json +0 -7
  240. package/tsconfig.tests.json +0 -15
  241. package/vitest.built.config.ts +0 -9
  242. package/vitest.config.ts +0 -54
  243. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  244. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  245. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  246. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  247. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  248. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  249. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  250. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  251. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  252. /package/{packages/selector/lib → lib}/client.d.ts +0 -0
  253. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  254. /package/{packages/selector/lib → lib}/index.js +0 -0
  255. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  256. /package/{packages/selector/lib → lib}/invariant.js +0 -0
  257. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
  258. /package/{packages/selector/lib → lib}/pruner.d.ts +0 -0
  259. /package/{packages/selector/lib → lib}/pruner.js +0 -0
  260. /package/{packages/selector/lib → lib}/savings-integral.js +0 -0
  261. /package/{packages/selector/lib → lib}/tail-trim.js +0 -0
  262. /package/{packages/selector/lib → lib}/tool-result.js +0 -0
@@ -1,307 +0,0 @@
1
- /**
2
- * live 写路径薄封装(spec T6/T8/T9):land/offset 随写随刷,usage 秒级节流。
3
- *
4
- * 纪律:
5
- * - 全部经 {@link StatsStore.recordClaims} 同步小事务(BEGIN IMMEDIATE +
6
- * INSERT OR IGNORE)落库;claims 幂等键 (session_id, 绝对 seq, kind,
7
- * component, basis),重放零新增(BC #2671 两教训已进 stats-db T4 断言)。
8
- * - store 缺席(无驱动/未开成) = 空转 —— stats-db 打开失败已 warn 恰一次,
9
- * 本模块不重复播报;内存账本照常工作,面板 persisted:false 可见降级。
10
- * - 写失败 = 进程级门闩 warn 恰一次且**绝不上抛**:统计持久化故障绝不
11
- * 阻塞压缩主路径(BC compaction-guard 失败方向不对称教训)。
12
- * - 不"flush-on-dispose"独走:老代际不发 session/disposed 会静默丢
13
- * (BC guard 教训)——land/offset 随写随刷,dispose 只是残量出口。
14
- * - usage 走事件日志 `assistant/message.data.usage` 按事件绝对 seq 逐科目
15
- * 入账(零 tokenizer),每会话一秒 debounce;sessions.version 水位单调前推,
16
- * 与回填共用同一覆盖范围语义。
17
- *
18
- * 隐私红线:只有计数/seq/组件枚举值/时间戳入表;原文、savingsHash、
19
- * 自由文本绝不落库。offset claim 的 seq 用被召回源事件 seq(findings 定键
20
- * (sessionId, eventSeq)):同一源事件反复召回时首次入账,后续重放幂等去重。
21
- *
22
- * @module dsh-context-compression-improved/runtime/stats-sync
23
- */
24
- import type { Session } from '@deepseek-ai/dsh-session'
25
- import type { SavingsBasis } from './savings.ts'
26
- import { getStatsStore, type StatsClaimRow } from './stats-db.ts'
27
- import { sessionEvents } from './session-events.ts'
28
-
29
- /** usage 逐科目枚举:claims.component 的封闭取值(进主键,禁自由文本)。 */
30
- const USAGE_COMPONENTS: readonly { field: 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'; component: string }[] = [
31
- { field: 'inputTokens', component: 'input' },
32
- { field: 'outputTokens', component: 'output' },
33
- { field: 'cacheReadTokens', component: 'cacheRead' },
34
- { field: 'cacheWriteTokens', component: 'cacheWrite' },
35
- ]
36
-
37
- /** usage flush 的 debounce 窗口(秒级,spec T8)。 */
38
- const USAGE_FLUSH_DEBOUNCE_MS = 1_000
39
-
40
- // 写失败 warn 的进程级门闩:可见但不刷屏(与 stats-db 降级门闩同一纪律)。
41
- let writeFailureWarned = false
42
-
43
- function warnWriteFailureOnce(error: unknown): void {
44
- if (writeFailureWarned) return
45
- writeFailureWarned = true
46
- const message = String((error as Error)?.message ?? error)
47
- console.warn('context-compression stats persistence write failed (claims fall back to in-memory only): %s', message)
48
- }
49
-
50
- // 前台活跃压缩窗口旗标:pruner fresh 段进出各置一次,回填调度器在 chunk 间
51
- // 据此让路——面板/回填绝不与前台压缩抢占(前台优先纪律)。
52
- let livePathBusy = false
53
-
54
- /** 标记前台压缩窗口开/关(pruner fresh 段 try/finally 驱动)。 */
55
- export function setStatsLivePathBusy(busy: boolean): void {
56
- livePathBusy = busy
57
- }
58
-
59
- /** 前台压缩是否进行中(回填让路判据;查询零开销)。 */
60
- export function isStatsLivePathBusy(): boolean {
61
- return livePathBusy
62
- }
63
-
64
- // 「当前会话」运行时指针:每个请求边界(fresh/usage flush)都真实跑在用户正在
65
- // 使用的会话上——比客户端注入可靠(注入只在页面加载发生,切会话不更新)。
66
- let activeRuntimeSessionId: string | undefined
67
-
68
- /** 请求边界处记下活跃会话(pruner/stats-sync 调用;幂等写字符串)。 */
69
- export function noteStatsSessionActive(sessionId: string): void {
70
- activeRuntimeSessionId = sessionId
71
- }
72
-
73
- /** 当前活跃会话指针(浮窗六值的解析基准;无请求活动 = undefined)。 */
74
- export function getStatsActiveSessionId(): string | undefined {
75
- return activeRuntimeSessionId
76
- }
77
-
78
- /** store 在场才执行写体;缺席空转,异常一律门闩 warn,绝不上抛。 */
79
- function withStoreWrite(label: string, fn: (store: NonNullable<ReturnType<typeof getStatsStore>>) => void): void {
80
- const store = getStatsStore()
81
- if (store === null) return
82
- try {
83
- fn(store)
84
- } catch (error) {
85
- warnWriteFailureOnce(`${label}: ${String((error as Error)?.message ?? error)}`)
86
- }
87
- }
88
-
89
- /** 单条 saving claim(land 成功点与内存账本同位同值)。 */
90
- function claimSaving(input: {
91
- sessionId: string
92
- component: string
93
- tokensRemoved: number
94
- basis: SavingsBasis
95
- /** 落盘替换事件的绝对 seq(投影条目的天然幂等键)。 */
96
- replacementSeq: number
97
- }): void {
98
- if (!Number.isFinite(input.tokensRemoved) || input.tokensRemoved <= 0) return
99
- const row: StatsClaimRow = {
100
- seq: Math.trunc(input.replacementSeq),
101
- kind: 'saving',
102
- component: input.component,
103
- basis: input.basis,
104
- tokens: Math.trunc(input.tokensRemoved),
105
- at: Date.now(),
106
- }
107
- withStoreWrite('claim saving', store => {
108
- // 同事务抢 source='live' 标记:isLiveOwned 回填护栏自第一条 saving 起生效,
109
- // 封死「live 已 land 但 sessions 行缺席 → 回填投影另键双计」的竞态窗口(审查 M2)。
110
- store.setSessionWatermark(input.sessionId, row.seq, { source: 'live' })
111
- store.recordClaims(input.sessionId, [row])
112
- })
113
- }
114
-
115
- /** 主 land(pruner land() recordSaving 同点):已落盘削减的 saving claim。 */
116
- export function claimFromLand(input: {
117
- sessionId: string
118
- component: string
119
- tokensBefore: number
120
- tokensAfter: number
121
- basis: SavingsBasis
122
- replacementSeq: number
123
- }): void {
124
- claimSaving({
125
- sessionId: input.sessionId,
126
- component: input.component,
127
- tokensRemoved: input.tokensBefore - input.tokensAfter,
128
- basis: input.basis,
129
- replacementSeq: input.replacementSeq,
130
- })
131
- }
132
-
133
- /** tail-trim 组回收(同 land 纪律,component 固定 'tail-trim')。 */
134
- export function reclaimFromTailTrim(input: {
135
- sessionId: string
136
- tokensBefore: number
137
- tokensAfter: number
138
- basis: SavingsBasis
139
- replacementSeq: number
140
- }): void {
141
- claimSaving({
142
- sessionId: input.sessionId,
143
- component: 'tail-trim',
144
- tokensRemoved: input.tokensBefore - input.tokensAfter,
145
- basis: input.basis,
146
- replacementSeq: input.replacementSeq,
147
- })
148
- }
149
-
150
- /** retrieve 回读抵消的 offset claim;seq = 被召回源事件绝对 seq(定键见头注)。 */
151
- export function claimOffset(input: {
152
- sessionId: string
153
- component: 'retrieve' | 'tailtrim-retrieve'
154
- tokens: number
155
- basis: SavingsBasis
156
- sourceSeq: number
157
- }): void {
158
- if (!Number.isFinite(input.tokens) || input.tokens <= 0) return
159
- const row: StatsClaimRow = {
160
- seq: Math.trunc(input.sourceSeq),
161
- kind: 'offset',
162
- component: input.component,
163
- basis: input.basis,
164
- tokens: Math.trunc(input.tokens),
165
- at: Date.now(),
166
- }
167
- withStoreWrite('claim offset', store => {
168
- // 与 claimSaving 同纪律:offset 也先抢 source='live',护栏不依赖 usage 水位(审查 M2)。
169
- store.setSessionWatermark(input.sessionId, row.seq, { source: 'live' })
170
- store.recordClaims(input.sessionId, [row])
171
- })
172
- }
173
-
174
- /**
175
- * 立即扫描事件日志并把水位之后的 usage 逐科目落库;sessions.version 水位
176
- * 单调前推(source=live,即便本轮零新增也 upsert 会话行——dispose 的
177
- * "标记 source=live" 出口)。无 store 时空转。
178
- */
179
- export function flushUsage(session: Session): void {
180
- withStoreWrite('usage flush', store => {
181
- const sid = String(session.id)
182
- const watermark = store.getSessionWatermark(sid)
183
- const rows: StatsClaimRow[] = []
184
- let covered = watermark
185
- for (const event of sessionEvents(session)) {
186
- const seq = Number(event.seq)
187
- // 事件日志 append-only 且 seq 单调;水位以内(含已消费旧事件)直接跳过。
188
- if (!Number.isFinite(seq) || seq <= watermark) continue
189
- if (seq > covered) covered = seq
190
- if (event.type !== 'assistant/message') continue
191
- const usage = event.data.usage
192
- if (usage === undefined) continue
193
- const at = Number(event.time) || Date.now()
194
- for (const { field, component } of USAGE_COMPONENTS) {
195
- const tokens = usage[field]
196
- if (typeof tokens === 'number' && Number.isFinite(tokens) && tokens > 0) {
197
- rows.push({ seq, kind: 'usage', component, basis: '', tokens: Math.trunc(tokens), at })
198
- }
199
- }
200
- }
201
- if (rows.length > 0) store.recordClaims(sid, rows)
202
- if (covered > 0) store.setSessionWatermark(sid, covered, { source: 'live' })
203
- })
204
- }
205
-
206
- // 每会话一个 debounce 槽位:窗口内的重复 schedule 合并为一次扫描。
207
- const pendingUsageFlushes = new Map<string, { session: Session; timer: ReturnType<typeof setTimeout> }>()
208
-
209
- /** 秒级 debounce 的 usage flush 入口(fresh 边界 recordUsage 同点调度)。 */
210
- export function scheduleUsageFlush(session: Session): void {
211
- const sid = String(session.id)
212
- noteStatsSessionActive(sid)
213
- const existing = pendingUsageFlushes.get(sid)
214
- if (existing !== undefined) {
215
- // 刷新引用即可:flush 运行时刻重新扫描全量事件,后来的 usage 自然被覆盖
216
- existing.session = session
217
- return
218
- }
219
- const timer = setTimeout(() => {
220
- const entry = pendingUsageFlushes.get(sid)
221
- if (entry === undefined) return
222
- pendingUsageFlushes.delete(sid)
223
- flushUsage(entry.session)
224
- }, USAGE_FLUSH_DEBOUNCE_MS)
225
- // 计时器不吊住进程退出(插件热重载/单测环境同等安全)
226
- timer.unref?.()
227
- pendingUsageFlushes.set(sid, { session, timer })
228
- }
229
-
230
- /**
231
- * session/disposed 残量出口(T9):取消在途 debounce、立即 flush 全部未落库
232
- * usage,并 upsert 会话行标记 source=live。老代际不发该事件时本函数只是
233
- * 不被调用——随写随刷路径不受影响(不依赖 dispose 的可靠性)。
234
- */
235
- export function flushUsageOnDispose(session: Session): void {
236
- const sid = String(session.id)
237
- const entry = pendingUsageFlushes.get(sid)
238
- if (entry !== undefined) {
239
- clearTimeout(entry.timer)
240
- entry.timer.unref?.()
241
- pendingUsageFlushes.delete(sid)
242
- }
243
- flushUsage(session)
244
- // 零事件/零 usage 会话也要落 source=live 会话行(面板 live/backfill 归属);
245
- // 水位原值回写——setSessionWatermark 单调不减,同值 upsert 只刷 source。
246
- withStoreWrite('dispose session row', store => {
247
- store.setSessionWatermark(sid, store.getSessionWatermark(sid), { source: 'live' })
248
- })
249
- }
250
-
251
- /**
252
- * 积分器采样落库(spec T15):fresh 边界的存量净快照 + 该次调用 usage 拆分。
253
- * 行形 kind='sample'、basis=''、component ∈ {netExact, netEstimated,
254
- * cachedInput, uncachedInput}(与 StatsStore.sumSamples 的读取面一致),幂等键
255
- * (session_id, boundarySeq, 'sample', component, '')——同一边界重放零新增,
256
- * calls(distinct seq 数)不涨。零值行不写(无信息量);负净额照写(召回后
257
- * 存量转负正是积分回落的语义)。sample 不前推 sessions 水位——覆盖语义归
258
- * flushUsage 的 usage 行。
259
- */
260
- export function recordIntegralSample(input: {
261
- sessionId: string
262
- boundarySeq: number
263
- netExact: number
264
- netEstimated: number
265
- cachedInput: number
266
- uncachedInput: number
267
- }): void {
268
- if (!Number.isFinite(input.boundarySeq) || input.boundarySeq < 0) return
269
- const candidates: readonly [component: 'netExact' | 'netEstimated' | 'cachedInput' | 'uncachedInput', tokens: number][] = [
270
- ['netExact', input.netExact],
271
- ['netEstimated', input.netEstimated],
272
- ['cachedInput', input.cachedInput],
273
- ['uncachedInput', input.uncachedInput],
274
- ]
275
- const rows: StatsClaimRow[] = []
276
- for (const [component, tokens] of candidates) {
277
- if (!Number.isFinite(tokens) || tokens === 0) continue
278
- rows.push({ seq: Math.trunc(input.boundarySeq), kind: 'sample', component, basis: '', tokens: Math.trunc(tokens), at: Date.now() })
279
- }
280
- if (rows.length === 0) return
281
- withStoreWrite('integral sample', store => {
282
- store.recordClaims(input.sessionId, rows)
283
- })
284
- }
285
-
286
- /**
287
- * /ccip `flush` 的抓手(spec T31):立即冲刷全部在途 usage debounce(等价于
288
- * 对每个挂起会话跑一次 dispose 出口,但不 upsert source——活跃会话的归属不变)。
289
- */
290
- export function flushPendingUsageNow(): void {
291
- const entries = [...pendingUsageFlushes.values()]
292
- pendingUsageFlushes.clear()
293
- for (const entry of entries) {
294
- clearTimeout(entry.timer)
295
- entry.timer.unref?.()
296
- }
297
- for (const entry of entries) flushUsage(entry.session)
298
- }
299
-
300
- /** 测试/卸载清理:丢弃全部在途 debounce(已落库数据不回滚)。 */
301
- export function cancelPendingUsageFlushes(): void {
302
- for (const entry of pendingUsageFlushes.values()) {
303
- clearTimeout(entry.timer)
304
- entry.timer.unref?.()
305
- }
306
- pendingUsageFlushes.clear()
307
- }
@@ -1,127 +0,0 @@
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
- }
@@ -1,176 +0,0 @@
1
- /** Plugin-owned TailTrim publication protocol over official Session events. */
2
-
3
- // 本地消息工厂,理由同 pruner.ts 头部注释(optional peer 静态导入会炸 ESM 链接期)。
4
- import { createUserMessage } from '../compat/llm-messages.ts'
5
- import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm'
6
- import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
7
- import { sessionEvents } from './session-events.ts'
8
- import { compressionMessageSource, viewToolResult } from '../compat/tool-result.ts'
9
-
10
- const TAIL_TRIM_REF_PATTERN = /^session:\/\/([^/]+)\/tailtrim\/(\d+)$/
11
- const MAX_ROOTS = 64
12
- const MAX_STUB_CODE_POINTS = 1_024
13
-
14
- /** A standard prune plus adjacent user-message replacement that validates. */
15
- export interface PublishedTailTrim {
16
- readonly manifest: SessionEvent<'compaction/prune'>
17
- readonly replacement: SessionEvent<'user/message'>
18
- readonly roots: readonly (
19
- SessionEvent<'assistant/message'> | SessionEvent<'tool/result'>
20
- )[]
21
- readonly toolNames: readonly string[]
22
- readonly ref: string
23
- readonly stub: string
24
- }
25
-
26
- /** Build a same-session reference keyed by the standard prune event. */
27
- export function tailTrimRef(sessionId: string, manifestSeq: number): string {
28
- return `session://${sessionId}/tailtrim/${String(manifestSeq)}`
29
- }
30
-
31
- /** Parse one exact TailTrim reference. */
32
- export function parseTailTrimRef(ref: string): { sessionId: string; manifestSeq: number } | null {
33
- const match = TAIL_TRIM_REF_PATTERN.exec(ref)
34
- if (match === null) return null
35
- const manifestSeq = Number(match[2])
36
- if (!Number.isSafeInteger(manifestSeq) || manifestSeq < 0) return null
37
- return { sessionId: match[1] ?? '', manifestSeq }
38
- }
39
-
40
- /** Build the fixed bounded model-visible TailTrim stub. */
41
- export function tailTrimStub(
42
- ref: string,
43
- toolNames: readonly string[],
44
- sourceEventSeqs: readonly number[],
45
- ): string | null {
46
- const stub = [
47
- '[TailTrim: completed tool-call group]',
48
- `ref: ${ref}`,
49
- `tools: ${toolNames.join(', ')}`,
50
- `source_event_seqs: ${sourceEventSeqs.join(', ')}`,
51
- 'use context_compression_retrieve with this TailTrim ref if needed',
52
- ].join('\n')
53
- return Array.from(stub).length <= MAX_STUB_CODE_POINTS ? stub : null
54
- }
55
-
56
- /** Wrap a TailTrim stub in the one user message used for range replacement. */
57
- export function tailTrimMessage(stub: string): UserMessage {
58
- return createUserMessage({
59
- content: [{ type: 'text', text: stub }],
60
- // Generation-gated: 0.1.x hosts only accept the shared plugin kind.
61
- source: compressionMessageSource() as { kind: 'dsh-context-compression' },
62
- })
63
- }
64
-
65
- /** Validate the standard prune, adjacent replacement, append roots and stub. */
66
- export function validatePublishedTailTrim(
67
- session: Session,
68
- manifestSeq: number,
69
- ): PublishedTailTrim | null {
70
- const events = sessionEvents(session)
71
- const manifest = events[manifestSeq]
72
- if (manifest?.type !== 'compaction/prune'
73
- || manifest.data.shadowedSeqs.length < 2
74
- || manifest.data.shadowedSeqs.length > MAX_ROOTS
75
- || manifest.data.shadowedSeqs[0] !== Number(manifest.data.shadowedRange.start)
76
- || manifest.data.shadowedSeqs.at(-1) !== Number(manifest.data.shadowedRange.end)
77
- || new Set(manifest.data.shadowedSeqs).size !== manifest.data.shadowedSeqs.length) return null
78
- const replacement = events[manifestSeq + 1]
79
- // The validator checks THIS runtime's own publication (same host, same
80
- // generation), so the expected source kind is the generation-gated one the
81
- // writer used — hardcoding the modern kind made the validator reject its
82
- // own legacy output (measured: legacy testbed classified the host, writer
83
- // emitted {kind:'plugin'}, validator demanded 'dsh-context-compression').
84
- const expectedSource = compressionMessageSource()
85
- if (replacement?.type !== 'user/message'
86
- || replacement.seq !== manifest.seq + 1
87
- || replacement.data.source.kind !== expectedSource.kind
88
- || replacement.surfaceOp === undefined
89
- || replacement.surfaceOp === 'append'
90
- || replacement.surfaceOp.startSeq !== manifest.data.shadowedRange.start
91
- || replacement.surfaceOp.endSeq !== manifest.data.shadowedRange.end
92
- || !sameNumbers(
93
- replacement.sourceEventSeqs,
94
- [manifest.seq, ...manifest.data.shadowedSeqs],
95
- )
96
- || replacement.data.content.length !== 1
97
- || replacement.data.content[0]?.type !== 'text') return null
98
-
99
- const tracedRoots = manifest.data.shadowedSeqs.map(seq => uniqueAppendRoot(session, seq, manifestSeq))
100
- if (tracedRoots.some(root => root === null)) return null
101
- const sourceEventSeqs = tracedRoots as number[]
102
- if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) return null
103
- const roots = sourceEventSeqs.map(seq => events[seq])
104
- if (roots.some((event): event is undefined => event === undefined)) return null
105
- const typedRoots = roots as SessionEvent[]
106
- if (!validRootGroup(typedRoots, manifestSeq)) return null
107
- const assistant = typedRoots[0]
108
- if (assistant?.type !== 'assistant/message') return null
109
- const toolNames = assistant.data.message.content.map((block) => {
110
- if (block.type !== 'tool-call') throw new Error('unreachable')
111
- return block.name
112
- })
113
- const ref = tailTrimRef(String(session.id), manifestSeq)
114
- const stub = tailTrimStub(ref, toolNames, sourceEventSeqs)
115
- if (stub === null || replacement.data.content[0].text !== stub) return null
116
- return {
117
- manifest,
118
- replacement,
119
- roots: typedRoots as PublishedTailTrim['roots'],
120
- toolNames,
121
- ref,
122
- stub,
123
- }
124
- }
125
-
126
- function uniqueAppendRoot(session: Session, seq: number, beforeSeq: number): number | null {
127
- const events = sessionEvents(session)
128
- const pending: Array<{ readonly seq: number; readonly depth: number }> = [{ seq, depth: 0 }]
129
- const visited = new Set<number>()
130
- const roots = new Set<number>()
131
- while (pending.length > 0) {
132
- const next = pending.pop()
133
- if (next === undefined || next.depth > MAX_ROOTS || visited.has(next.seq)) continue
134
- if (!Number.isSafeInteger(next.seq) || next.seq < 0 || next.seq >= beforeSeq) return null
135
- visited.add(next.seq)
136
- if (visited.size > MAX_ROOTS) return null
137
- const event = events[next.seq]
138
- if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
139
- if (event.surfaceOp === 'append') roots.add(event.seq)
140
- else if (typeof event.surfaceOp === 'object') {
141
- const sources = event.sourceEventSeqs
142
- if (sources === undefined || sources.length === 0) return null
143
- for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
144
- } else return null
145
- if (roots.size > 1) return null
146
- }
147
- return roots.size === 1 ? [...roots][0] ?? null : null
148
- }
149
-
150
- function validRootGroup(roots: readonly SessionEvent[], manifestSeq: number): boolean {
151
- const assistant = roots[0]
152
- if (assistant?.type !== 'assistant/message' || assistant.seq >= manifestSeq
153
- || assistant.surfaceOp !== 'append' || assistant.data.interrupted === true
154
- || assistant.data.message.content.length === 0
155
- || assistant.data.message.content.some(block => block.type !== 'tool-call')) return false
156
- const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
157
- const callIds = calls.map(call => call.id)
158
- if (new Set(callIds).size !== callIds.length || roots.length !== callIds.length + 1) return false
159
- for (const [index, root] of roots.slice(1).entries()) {
160
- if (root.type !== 'tool/result' || root.seq >= manifestSeq || root.surfaceOp !== 'append') return false
161
- // Generation-gated triple view: error flag and call id axes relocate
162
- // between the 0.1.x envelope and the flat 0.2.0 message.
163
- const result = viewToolResult(root.data.message)
164
- if (result.isError
165
- || root.data.error !== undefined
166
- || root.data.turn !== assistant.data.turn
167
- || root.data.step !== assistant.data.step
168
- || String(result.callId) !== String(callIds[index])) return false
169
- }
170
- return true
171
- }
172
-
173
- function sameNumbers(left: readonly number[] | undefined, right: readonly number[]): boolean {
174
- return left !== undefined && left.length === right.length
175
- && left.every((value, index) => value === right[index])
176
- }
@@ -1,72 +0,0 @@
1
- /** Token counts owned by the standalone compression runtime. */
2
-
3
- /** Exact count of one canonical value under a pinned tokenizer artifact. */
4
- export interface ExactTokenizerTokenCount {
5
- readonly kind: 'exact-tokenizer'
6
- readonly tokens: number
7
- readonly tokenizerId: string
8
- readonly tokenizerRevision: string
9
- }
10
-
11
- /** A value that the bundled tokenizer cannot safely count. */
12
- export interface UnavailableTokenCount {
13
- readonly kind: 'unavailable'
14
- readonly reason: string
15
- }
16
-
17
- /** Best-effort estimate carrying a conservative upper value when available. */
18
- export interface TokenizerEstimateTokenCount {
19
- readonly kind: 'tokenizer-estimate'
20
- readonly tokens: number
21
- readonly upperBoundTokens: number
22
- readonly estimatorId: string
23
- readonly estimatorRevision: string
24
- readonly calibration?: Readonly<{
25
- readonly sampleCount: number
26
- readonly conservativeMarginTokens: number
27
- }>
28
- }
29
-
30
- /** Exact, conservative request estimate, or an explicit refusal. */
31
- export type TokenCount = ExactTokenizerTokenCount | TokenizerEstimateTokenCount | UnavailableTokenCount
32
-
33
- /** Bound exact text counter for one durable provider/model request target. */
34
- export type CanonicalTextTokenCounter = (text: string) => TokenCount
35
-
36
- /** Build an explicit unavailable result without inventing an estimate. */
37
- export function unavailableTokenCount(reason: string): UnavailableTokenCount {
38
- if (reason.length === 0) throw new TypeError('unavailable token count requires a reason')
39
- return Object.freeze({ kind: 'unavailable', reason })
40
- }
41
-
42
- /** Sum independent canonical fields only when every count has one identity. */
43
- export function countExactCanonicalTextFields(
44
- fields: readonly string[],
45
- counter: CanonicalTextTokenCounter,
46
- subject: string,
47
- ): TokenCount {
48
- if (subject.length === 0) throw new TypeError('canonical text field count requires a subject')
49
- const values = fields.length === 0 ? [''] : fields
50
- let identity: ExactTokenizerTokenCount | undefined
51
- let tokens = 0
52
- for (const value of values) {
53
- const count = counter(value)
54
- if (count.kind !== 'exact-tokenizer') {
55
- return unavailableTokenCount(`${subject}: ${count.kind === 'unavailable'
56
- ? count.reason
57
- : 'canonical content requires an exact tokenizer count'}`)
58
- }
59
- if (identity !== undefined
60
- && (identity.tokenizerId !== count.tokenizerId
61
- || identity.tokenizerRevision !== count.tokenizerRevision)) {
62
- return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
63
- }
64
- identity ??= count
65
- tokens += count.tokens
66
- if (!Number.isSafeInteger(tokens) || tokens < 0) {
67
- return unavailableTokenCount(`${subject}: token sum is outside the safe integer range`)
68
- }
69
- }
70
- if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
71
- return Object.freeze({ ...identity, tokens })
72
- }