dsh-context-compression-improved 0.11.0 → 0.11.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 (310) 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}/index.js +101 -0
  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 -47
  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 -557
  22. package/CHANGELOG.ru.md +0 -554
  23. package/CHANGELOG.zh.md +0 -247
  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/docs/shallow-teaching-preset-template.md +0 -46
  49. package/eslint.config.js +0 -30
  50. package/packages/selector/LICENSE +0 -21
  51. package/packages/selector/README.md +0 -26
  52. package/packages/selector/README.zh.md +0 -24
  53. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  54. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  55. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  56. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  57. package/packages/selector/lib/style.css +0 -350
  58. package/packages/selector/package.json +0 -178
  59. package/packages/selector/screenshots.json +0 -3
  60. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -352
  61. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  62. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -89
  63. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  64. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  65. package/packages/selector/src/client/bridge-scope.ts +0 -125
  66. package/packages/selector/src/client/decode.ts +0 -68
  67. package/packages/selector/src/client/fab-pos.ts +0 -71
  68. package/packages/selector/src/client/index.ts +0 -438
  69. package/packages/selector/src/client/locales/de.ts +0 -167
  70. package/packages/selector/src/client/locales/es.ts +0 -167
  71. package/packages/selector/src/client/locales/fr.ts +0 -167
  72. package/packages/selector/src/client/locales/it.ts +0 -167
  73. package/packages/selector/src/client/locales/ja.ts +0 -167
  74. package/packages/selector/src/client/locales/ko.ts +0 -167
  75. package/packages/selector/src/client/locales/ru.ts +0 -167
  76. package/packages/selector/src/client/locales.ts +0 -334
  77. package/packages/selector/src/client/monitor-fab.ts +0 -445
  78. package/packages/selector/src/client/preset-options.ts +0 -88
  79. package/packages/selector/src/client/savings-card.tsx +0 -269
  80. package/packages/selector/src/client/scope-face.ts +0 -24
  81. package/packages/selector/src/client/settings-section.tsx +0 -156
  82. package/packages/selector/src/compat/host-generation.ts +0 -96
  83. package/packages/selector/src/compat/llm-messages.ts +0 -50
  84. package/packages/selector/src/compat/settings-lease.ts +0 -108
  85. package/packages/selector/src/compat/tool-result.ts +0 -91
  86. package/packages/selector/src/css-modules.d.ts +0 -6
  87. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  88. package/packages/selector/src/estimator-catalog.ts +0 -104
  89. package/packages/selector/src/index.ts +0 -890
  90. package/packages/selector/src/invariant.ts +0 -113
  91. package/packages/selector/src/preset-overlay.ts +0 -749
  92. package/packages/selector/src/profiles.ts +0 -554
  93. package/packages/selector/src/pruner/content.ts +0 -199
  94. package/packages/selector/src/pruner/session.ts +0 -97
  95. package/packages/selector/src/pruner/state.ts +0 -61
  96. package/packages/selector/src/pruner/tuning.ts +0 -23
  97. package/packages/selector/src/pruner/types.ts +0 -78
  98. package/packages/selector/src/pruner.ts +0 -3222
  99. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  100. package/packages/selector/src/runtime/audit.ts +0 -321
  101. package/packages/selector/src/runtime/config.ts +0 -887
  102. package/packages/selector/src/runtime/custom-policy.ts +0 -300
  103. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  104. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  105. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  106. package/packages/selector/src/runtime/fold-router.ts +0 -143
  107. package/packages/selector/src/runtime/measurement.ts +0 -444
  108. package/packages/selector/src/runtime/monitor.ts +0 -341
  109. package/packages/selector/src/runtime/panel-command.ts +0 -213
  110. package/packages/selector/src/runtime/reducers.ts +0 -1755
  111. package/packages/selector/src/runtime/retrieve.ts +0 -505
  112. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  113. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  114. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  115. package/packages/selector/src/runtime/savings.ts +0 -526
  116. package/packages/selector/src/runtime/sediment-card.ts +0 -126
  117. package/packages/selector/src/runtime/sediment-clock.ts +0 -87
  118. package/packages/selector/src/runtime/sediment-guard.ts +0 -136
  119. package/packages/selector/src/runtime/sediment-publish.ts +0 -144
  120. package/packages/selector/src/runtime/sediment-span.ts +0 -170
  121. package/packages/selector/src/runtime/sediment.ts +0 -209
  122. package/packages/selector/src/runtime/session-events.ts +0 -30
  123. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  124. package/packages/selector/src/runtime/shallow-tools.ts +0 -342
  125. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  126. package/packages/selector/src/runtime/stats-db.ts +0 -492
  127. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  128. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  129. package/packages/selector/src/runtime/summary-command.ts +0 -127
  130. package/packages/selector/src/runtime/tail-trim.ts +0 -177
  131. package/packages/selector/src/runtime/token-count.ts +0 -72
  132. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  133. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  134. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  135. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  136. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -82
  137. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  138. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  139. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  140. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  141. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  142. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -129
  143. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  144. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  145. package/packages/selector/src/runtime/tool-names.ts +0 -42
  146. package/packages/selector/src/runtime/toolclass.ts +0 -103
  147. package/packages/selector/src/runtime/triage/masks.ts +0 -128
  148. package/packages/selector/src/runtime/triage/shallow.ts +0 -132
  149. package/packages/selector/src/runtime/triage/signals.ts +0 -167
  150. package/packages/selector/src/runtime/triage/types.ts +0 -125
  151. package/packages/selector/src/runtime/types.ts +0 -396
  152. package/packages/selector/src/runtime/value.ts +0 -48
  153. package/packages/selector/src/settings-bridge.ts +0 -175
  154. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  155. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  156. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  157. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  158. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  159. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  160. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  161. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  162. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  163. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  164. package/packages/selector/tests/fab-pos.client.spec.ts +0 -47
  165. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +0 -231
  166. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +0 -236
  167. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +0 -220
  168. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +0 -140
  169. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +0 -117
  170. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +0 -67
  171. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +0 -119
  172. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +0 -119
  173. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +0 -131
  174. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +0 -196
  175. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +0 -71
  176. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +0 -126
  177. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +0 -86
  178. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +0 -50
  179. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +0 -102
  180. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  181. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  182. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  183. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  184. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  185. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  186. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  187. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -240
  188. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  189. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  190. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  191. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  192. package/packages/selector/tests/ptc-custom-write.client.spec.ts +0 -86
  193. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -89
  194. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  195. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  196. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  197. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  198. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  199. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  200. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  201. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  202. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  203. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  204. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  205. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  206. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  207. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  208. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  209. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  210. package/packages/selector/tests/runtime/fold-router.spec.ts +0 -140
  211. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  212. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  213. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  214. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  215. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  216. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  217. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  218. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  219. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  220. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  221. package/packages/selector/tests/runtime/ptc-profile.spec.ts +0 -133
  222. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2795
  223. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  224. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  225. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  226. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  227. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  228. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  229. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  230. package/packages/selector/tests/runtime/sediment-card.spec.ts +0 -111
  231. package/packages/selector/tests/runtime/sediment-config.spec.ts +0 -56
  232. package/packages/selector/tests/runtime/sediment-guard.spec.ts +0 -71
  233. package/packages/selector/tests/runtime/sediment-masks.spec.ts +0 -95
  234. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +0 -166
  235. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +0 -65
  236. package/packages/selector/tests/runtime/sediment-publish.spec.ts +0 -142
  237. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +0 -158
  238. package/packages/selector/tests/runtime/sediment-settings.spec.ts +0 -73
  239. package/packages/selector/tests/runtime/sediment-signals.spec.ts +0 -124
  240. package/packages/selector/tests/runtime/sediment-span.spec.ts +0 -92
  241. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  242. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  243. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  244. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +0 -135
  245. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  246. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  247. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -350
  248. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  249. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  250. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  251. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  252. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  253. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  254. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  255. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  256. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  257. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  258. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -121
  259. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  260. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  261. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  262. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  263. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  264. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  265. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  266. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  267. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  268. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  269. package/packages/selector/tsconfig.json +0 -11
  270. package/packages/selector/tsdown.client.config.ts +0 -102
  271. package/packages/selector/tsdown.config.ts +0 -20
  272. package/pnpm-workspace.yaml +0 -76
  273. package/scripts/capture-profile-baseline.mjs +0 -42
  274. package/scripts/cell-browser-e2e.mjs +0 -354
  275. package/scripts/generate-tokenizer-fixtures.py +0 -81
  276. package/scripts/generate-vision-fixtures.py +0 -208
  277. package/scripts/hosts.d.mts +0 -3
  278. package/scripts/hosts.mjs +0 -79
  279. package/scripts/packed-components-smoke.mjs +0 -763
  280. package/scripts/packed-install-e2e.mjs +0 -1346
  281. package/scripts/sediment-latency-report.mjs +0 -63
  282. package/scripts/sync-hosts.mjs +0 -174
  283. package/scripts/toolclass-corpus-replay.mjs +0 -281
  284. package/scripts/verify-release.mjs +0 -343
  285. package/tests/TEST_INVENTORY.md +0 -41
  286. package/tsconfig.base.json +0 -18
  287. package/tsconfig.json +0 -7
  288. package/tsconfig.tests.json +0 -15
  289. package/vitest.built.config.ts +0 -9
  290. package/vitest.config.ts +0 -54
  291. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  292. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  293. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  294. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  295. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  296. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  297. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  298. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  299. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  300. /package/{packages/selector/lib → lib}/client.d.ts +0 -0
  301. /package/{packages/selector/lib → lib}/client.js +0 -0
  302. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  303. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  304. /package/{packages/selector/lib → lib}/invariant.js +0 -0
  305. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
  306. /package/{packages/selector/lib → lib}/pruner.d.ts +0 -0
  307. /package/{packages/selector/lib → lib}/pruner.js +0 -0
  308. /package/{packages/selector/lib → lib}/savings-integral.js +0 -0
  309. /package/{packages/selector/lib → lib}/tail-trim.js +0 -0
  310. /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,177 +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
- import { RUNTIME_TOOL_NAMES } from './tool-names.ts'
10
-
11
- const TAIL_TRIM_REF_PATTERN = /^session:\/\/([^/]+)\/tailtrim\/(\d+)$/
12
- const MAX_ROOTS = 64
13
- const MAX_STUB_CODE_POINTS = 1_024
14
-
15
- /** A standard prune plus adjacent user-message replacement that validates. */
16
- export interface PublishedTailTrim {
17
- readonly manifest: SessionEvent<'compaction/prune'>
18
- readonly replacement: SessionEvent<'user/message'>
19
- readonly roots: readonly (
20
- SessionEvent<'assistant/message'> | SessionEvent<'tool/result'>
21
- )[]
22
- readonly toolNames: readonly string[]
23
- readonly ref: string
24
- readonly stub: string
25
- }
26
-
27
- /** Build a same-session reference keyed by the standard prune event. */
28
- export function tailTrimRef(sessionId: string, manifestSeq: number): string {
29
- return `session://${sessionId}/tailtrim/${String(manifestSeq)}`
30
- }
31
-
32
- /** Parse one exact TailTrim reference. */
33
- export function parseTailTrimRef(ref: string): { sessionId: string; manifestSeq: number } | null {
34
- const match = TAIL_TRIM_REF_PATTERN.exec(ref)
35
- if (match === null) return null
36
- const manifestSeq = Number(match[2])
37
- if (!Number.isSafeInteger(manifestSeq) || manifestSeq < 0) return null
38
- return { sessionId: match[1] ?? '', manifestSeq }
39
- }
40
-
41
- /** Build the fixed bounded model-visible TailTrim stub. */
42
- export function tailTrimStub(
43
- ref: string,
44
- toolNames: readonly string[],
45
- sourceEventSeqs: readonly number[],
46
- ): string | null {
47
- const stub = [
48
- '[TailTrim: completed tool-call group]',
49
- `ref: ${ref}`,
50
- `tools: ${toolNames.join(', ')}`,
51
- `source_event_seqs: ${sourceEventSeqs.join(', ')}`,
52
- `use ${RUNTIME_TOOL_NAMES.RETRIEVE} with this TailTrim ref if needed`,
53
- ].join('\n')
54
- return Array.from(stub).length <= MAX_STUB_CODE_POINTS ? stub : null
55
- }
56
-
57
- /** Wrap a TailTrim stub in the one user message used for range replacement. */
58
- export function tailTrimMessage(stub: string): UserMessage {
59
- return createUserMessage({
60
- content: [{ type: 'text', text: stub }],
61
- // Generation-gated: 0.1.x hosts only accept the shared plugin kind.
62
- source: compressionMessageSource() as { kind: 'dsh-context-compression' },
63
- })
64
- }
65
-
66
- /** Validate the standard prune, adjacent replacement, append roots and stub. */
67
- export function validatePublishedTailTrim(
68
- session: Session,
69
- manifestSeq: number,
70
- ): PublishedTailTrim | null {
71
- const events = sessionEvents(session)
72
- const manifest = events[manifestSeq]
73
- if (manifest?.type !== 'compaction/prune'
74
- || manifest.data.shadowedSeqs.length < 2
75
- || manifest.data.shadowedSeqs.length > MAX_ROOTS
76
- || manifest.data.shadowedSeqs[0] !== Number(manifest.data.shadowedRange.start)
77
- || manifest.data.shadowedSeqs.at(-1) !== Number(manifest.data.shadowedRange.end)
78
- || new Set(manifest.data.shadowedSeqs).size !== manifest.data.shadowedSeqs.length) return null
79
- const replacement = events[manifestSeq + 1]
80
- // The validator checks THIS runtime's own publication (same host, same
81
- // generation), so the expected source kind is the generation-gated one the
82
- // writer used — hardcoding the modern kind made the validator reject its
83
- // own legacy output (measured: legacy testbed classified the host, writer
84
- // emitted {kind:'plugin'}, validator demanded 'dsh-context-compression').
85
- const expectedSource = compressionMessageSource()
86
- if (replacement?.type !== 'user/message'
87
- || replacement.seq !== manifest.seq + 1
88
- || replacement.data.source.kind !== expectedSource.kind
89
- || replacement.surfaceOp === undefined
90
- || replacement.surfaceOp === 'append'
91
- || replacement.surfaceOp.startSeq !== manifest.data.shadowedRange.start
92
- || replacement.surfaceOp.endSeq !== manifest.data.shadowedRange.end
93
- || !sameNumbers(
94
- replacement.sourceEventSeqs,
95
- [manifest.seq, ...manifest.data.shadowedSeqs],
96
- )
97
- || replacement.data.content.length !== 1
98
- || replacement.data.content[0]?.type !== 'text') return null
99
-
100
- const tracedRoots = manifest.data.shadowedSeqs.map(seq => uniqueAppendRoot(session, seq, manifestSeq))
101
- if (tracedRoots.some(root => root === null)) return null
102
- const sourceEventSeqs = tracedRoots as number[]
103
- if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) return null
104
- const roots = sourceEventSeqs.map(seq => events[seq])
105
- if (roots.some((event): event is undefined => event === undefined)) return null
106
- const typedRoots = roots as SessionEvent[]
107
- if (!validRootGroup(typedRoots, manifestSeq)) return null
108
- const assistant = typedRoots[0]
109
- if (assistant?.type !== 'assistant/message') return null
110
- const toolNames = assistant.data.message.content.map((block) => {
111
- if (block.type !== 'tool-call') throw new Error('unreachable')
112
- return block.name
113
- })
114
- const ref = tailTrimRef(String(session.id), manifestSeq)
115
- const stub = tailTrimStub(ref, toolNames, sourceEventSeqs)
116
- if (stub === null || replacement.data.content[0].text !== stub) return null
117
- return {
118
- manifest,
119
- replacement,
120
- roots: typedRoots as PublishedTailTrim['roots'],
121
- toolNames,
122
- ref,
123
- stub,
124
- }
125
- }
126
-
127
- function uniqueAppendRoot(session: Session, seq: number, beforeSeq: number): number | null {
128
- const events = sessionEvents(session)
129
- const pending: Array<{ readonly seq: number; readonly depth: number }> = [{ seq, depth: 0 }]
130
- const visited = new Set<number>()
131
- const roots = new Set<number>()
132
- while (pending.length > 0) {
133
- const next = pending.pop()
134
- if (next === undefined || next.depth > MAX_ROOTS || visited.has(next.seq)) continue
135
- if (!Number.isSafeInteger(next.seq) || next.seq < 0 || next.seq >= beforeSeq) return null
136
- visited.add(next.seq)
137
- if (visited.size > MAX_ROOTS) return null
138
- const event = events[next.seq]
139
- if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
140
- if (event.surfaceOp === 'append') roots.add(event.seq)
141
- else if (typeof event.surfaceOp === 'object') {
142
- const sources = event.sourceEventSeqs
143
- if (sources === undefined || sources.length === 0) return null
144
- for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
145
- } else return null
146
- if (roots.size > 1) return null
147
- }
148
- return roots.size === 1 ? [...roots][0] ?? null : null
149
- }
150
-
151
- function validRootGroup(roots: readonly SessionEvent[], manifestSeq: number): boolean {
152
- const assistant = roots[0]
153
- if (assistant?.type !== 'assistant/message' || assistant.seq >= manifestSeq
154
- || assistant.surfaceOp !== 'append' || assistant.data.interrupted === true
155
- || assistant.data.message.content.length === 0
156
- || assistant.data.message.content.some(block => block.type !== 'tool-call')) return false
157
- const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
158
- const callIds = calls.map(call => call.id)
159
- if (new Set(callIds).size !== callIds.length || roots.length !== callIds.length + 1) return false
160
- for (const [index, root] of roots.slice(1).entries()) {
161
- if (root.type !== 'tool/result' || root.seq >= manifestSeq || root.surfaceOp !== 'append') return false
162
- // Generation-gated triple view: error flag and call id axes relocate
163
- // between the 0.1.x envelope and the flat 0.2.0 message.
164
- const result = viewToolResult(root.data.message)
165
- if (result.isError
166
- || root.data.error !== undefined
167
- || root.data.turn !== assistant.data.turn
168
- || root.data.step !== assistant.data.step
169
- || String(result.callId) !== String(callIds[index])) return false
170
- }
171
- return true
172
- }
173
-
174
- function sameNumbers(left: readonly number[] | undefined, right: readonly number[]): boolean {
175
- return left !== undefined && left.length === right.length
176
- && left.every((value, index) => value === right[index])
177
- }
@@ -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
- }