dsh-context-compression-improved 0.12.0 → 0.13.1

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 (334) hide show
  1. package/.agents/plans/improve/checklist.md +32 -0
  2. package/.agents/plans/improve/findings.md +102 -0
  3. package/.agents/plans/improve/spec.md +53 -0
  4. package/.agents/plans/improve/tasks.md +70 -0
  5. package/.gitattributes +2 -0
  6. package/.githooks/pre-push +37 -0
  7. package/.github/workflows/ci.yml +47 -0
  8. package/CHANGELOG.de.md +580 -0
  9. package/CHANGELOG.es.md +588 -0
  10. package/CHANGELOG.fr.md +576 -0
  11. package/CHANGELOG.it.md +577 -0
  12. package/CHANGELOG.ja.md +261 -0
  13. package/CHANGELOG.ko.md +254 -0
  14. package/CHANGELOG.md +582 -0
  15. package/CHANGELOG.pt.md +167 -0
  16. package/CHANGELOG.ru.md +554 -0
  17. package/CHANGELOG.zh.md +247 -0
  18. package/CONTRIBUTING.md +22 -0
  19. package/README.de.md +96 -0
  20. package/README.es.md +96 -0
  21. package/README.fr.md +96 -0
  22. package/README.it.md +96 -0
  23. package/README.ja.md +102 -0
  24. package/README.ko.md +102 -0
  25. package/README.md +128 -22
  26. package/README.pt.md +96 -0
  27. package/README.ru.md +96 -0
  28. package/README.zh.md +114 -24
  29. package/SECURITY.md +18 -0
  30. package/THIRD_PARTY_NOTICES.md +7 -25
  31. package/assets/board.png +0 -0
  32. package/assets/context.png +0 -0
  33. package/assets/dshfind-card.svg +33 -0
  34. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  35. package/docs/assets/context-compression-selector-settings.png +0 -0
  36. package/docs/compat-0.1.5-report.md +77 -0
  37. package/docs/installation.de.md +104 -0
  38. package/docs/installation.es.md +104 -0
  39. package/docs/installation.fr.md +104 -0
  40. package/docs/installation.it.md +104 -0
  41. package/docs/installation.ja.md +78 -0
  42. package/docs/installation.ko.md +78 -0
  43. package/docs/installation.md +103 -0
  44. package/docs/installation.ru.md +104 -0
  45. package/docs/installation.zh.md +100 -0
  46. package/docs/repair-log.md +657 -0
  47. package/docs/shallow-teaching-preset-template.md +46 -0
  48. package/eslint.config.js +30 -0
  49. package/package.json +112 -127
  50. package/packages/selector/LICENSE +21 -0
  51. package/packages/selector/README.md +26 -0
  52. package/packages/selector/README.zh.md +24 -0
  53. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  54. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  55. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  56. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  57. package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +1 -1
  58. package/{lib → packages/selector/lib}/client.js +18 -10
  59. package/{lib → packages/selector/lib}/profiles.d.ts +6 -0
  60. package/packages/selector/lib/style.css +350 -0
  61. package/packages/selector/package.json +180 -0
  62. package/packages/selector/screenshots.json +3 -0
  63. package/packages/selector/src/client/CompressionProfileControls.tsx +352 -0
  64. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  65. package/packages/selector/src/client/CompressionProfileSelector.tsx +89 -0
  66. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  67. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  68. package/packages/selector/src/client/bridge-scope.ts +125 -0
  69. package/packages/selector/src/client/decode.ts +68 -0
  70. package/packages/selector/src/client/fab-pos.ts +71 -0
  71. package/packages/selector/src/client/guide-steps.ts +50 -0
  72. package/packages/selector/src/client/guide.tsx +368 -0
  73. package/packages/selector/src/client/index.ts +456 -0
  74. package/packages/selector/src/client/locales/de.ts +167 -0
  75. package/packages/selector/src/client/locales/es.ts +167 -0
  76. package/packages/selector/src/client/locales/fr.ts +167 -0
  77. package/packages/selector/src/client/locales/it.ts +167 -0
  78. package/packages/selector/src/client/locales/ja.ts +167 -0
  79. package/packages/selector/src/client/locales/ko.ts +167 -0
  80. package/packages/selector/src/client/locales/pt.ts +167 -0
  81. package/packages/selector/src/client/locales/ru.ts +167 -0
  82. package/packages/selector/src/client/locales.ts +334 -0
  83. package/packages/selector/src/client/monitor-fab.ts +445 -0
  84. package/packages/selector/src/client/preset-options.ts +88 -0
  85. package/packages/selector/src/client/savings-card.tsx +269 -0
  86. package/packages/selector/src/client/scope-face.ts +24 -0
  87. package/packages/selector/src/client/settings-section.tsx +171 -0
  88. package/packages/selector/src/compat/host-generation.ts +96 -0
  89. package/packages/selector/src/compat/llm-messages.ts +50 -0
  90. package/packages/selector/src/compat/settings-lease.ts +108 -0
  91. package/packages/selector/src/compat/tool-result.ts +91 -0
  92. package/packages/selector/src/css-modules.d.ts +6 -0
  93. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  94. package/packages/selector/src/estimator-catalog.ts +104 -0
  95. package/packages/selector/src/index.ts +909 -0
  96. package/packages/selector/src/invariant.ts +113 -0
  97. package/packages/selector/src/preset-overlay.ts +749 -0
  98. package/packages/selector/src/profiles.ts +560 -0
  99. package/packages/selector/src/pruner/content.ts +199 -0
  100. package/packages/selector/src/pruner/session.ts +97 -0
  101. package/packages/selector/src/pruner/state.ts +61 -0
  102. package/packages/selector/src/pruner/tuning.ts +23 -0
  103. package/packages/selector/src/pruner/types.ts +78 -0
  104. package/packages/selector/src/pruner.ts +3222 -0
  105. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  106. package/packages/selector/src/runtime/audit.ts +321 -0
  107. package/packages/selector/src/runtime/config.ts +887 -0
  108. package/packages/selector/src/runtime/custom-policy.ts +300 -0
  109. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  110. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  111. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  112. package/packages/selector/src/runtime/fold-router.ts +143 -0
  113. package/packages/selector/src/runtime/injected-kinds.ts +62 -0
  114. package/packages/selector/src/runtime/measurement.ts +444 -0
  115. package/packages/selector/src/runtime/monitor.ts +341 -0
  116. package/packages/selector/src/runtime/netgain.ts +48 -0
  117. package/packages/selector/src/runtime/panel-command.ts +213 -0
  118. package/packages/selector/src/runtime/reducers.ts +1755 -0
  119. package/packages/selector/src/runtime/retrieve.ts +505 -0
  120. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  121. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  122. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  123. package/packages/selector/src/runtime/savings.ts +526 -0
  124. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  125. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  126. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  127. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  128. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  129. package/packages/selector/src/runtime/sediment.ts +209 -0
  130. package/packages/selector/src/runtime/session-events.ts +30 -0
  131. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  132. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  133. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  134. package/packages/selector/src/runtime/stats-db.ts +492 -0
  135. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  136. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  137. package/packages/selector/src/runtime/summary-command.ts +127 -0
  138. package/packages/selector/src/runtime/tail-trim.ts +177 -0
  139. package/packages/selector/src/runtime/token-count.ts +72 -0
  140. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  141. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  142. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  143. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  144. package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
  145. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  146. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  147. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  148. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  149. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  150. package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
  151. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  152. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  153. package/packages/selector/src/runtime/tool-names.ts +42 -0
  154. package/packages/selector/src/runtime/toolclass.ts +103 -0
  155. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  156. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  157. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  158. package/packages/selector/src/runtime/triage/types.ts +125 -0
  159. package/packages/selector/src/runtime/types.ts +396 -0
  160. package/packages/selector/src/runtime/value.ts +48 -0
  161. package/packages/selector/src/settings-bridge.ts +175 -0
  162. package/packages/selector/src/tui-command.ts +99 -0
  163. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  164. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  165. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  166. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  167. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  168. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  169. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  170. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  171. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  172. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  173. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  174. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  175. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  176. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  177. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  178. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  179. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  180. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  181. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  182. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  183. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  184. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  185. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  186. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  187. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  188. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  189. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  190. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  191. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  192. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  193. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  194. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  195. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  196. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  197. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  198. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  199. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  200. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  201. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  202. package/packages/selector/tests/public/package-contract.client.spec.ts +91 -0
  203. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  204. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  205. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  206. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  207. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  208. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  209. package/packages/selector/tests/runtime/behavior-lock-profiles.spec.ts +128 -0
  210. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  211. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  212. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  213. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  214. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  215. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  216. package/packages/selector/tests/runtime/fallback-diversity.spec.ts +75 -0
  217. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  218. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  219. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  220. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  221. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  222. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  223. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  224. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  225. package/packages/selector/tests/runtime/injected-kinds.spec.ts +86 -0
  226. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  227. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  228. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  229. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  230. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  231. package/packages/selector/tests/runtime/netgain.spec.ts +61 -0
  232. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  233. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  234. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  235. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
  236. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  237. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  238. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  239. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  240. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  241. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  242. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  243. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  244. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  245. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  246. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  247. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  248. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  249. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  250. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  251. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  252. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  253. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  254. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  255. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  256. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  257. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  258. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  259. package/packages/selector/tests/runtime/source-kind-audit.spec.ts +79 -0
  260. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  261. package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
  262. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  263. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  264. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  265. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  266. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  267. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  268. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  269. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  270. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  271. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  272. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
  273. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  274. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  275. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  276. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  277. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  278. package/packages/selector/tests/standing-generation.host.spec.ts +729 -0
  279. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  280. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  281. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  282. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  283. package/packages/selector/tsconfig.json +11 -0
  284. package/packages/selector/tsdown.client.config.ts +102 -0
  285. package/packages/selector/tsdown.config.ts +20 -0
  286. package/pnpm-workspace.yaml +76 -0
  287. package/screenshots.json +6 -3
  288. package/scripts/capture-profile-baseline.mjs +42 -0
  289. package/scripts/cell-browser-e2e.mjs +354 -0
  290. package/scripts/generate-tokenizer-fixtures.py +81 -0
  291. package/scripts/generate-vision-fixtures.py +208 -0
  292. package/scripts/hosts.d.mts +3 -0
  293. package/scripts/hosts.mjs +81 -0
  294. package/scripts/packed-components-smoke.mjs +763 -0
  295. package/scripts/packed-install-e2e.mjs +1346 -0
  296. package/scripts/sediment-latency-report.mjs +63 -0
  297. package/scripts/sync-hosts.mjs +176 -0
  298. package/scripts/toolclass-corpus-replay.mjs +281 -0
  299. package/scripts/verify-release.mjs +342 -0
  300. package/tests/TEST_INVENTORY.md +41 -0
  301. package/tsconfig.base.json +18 -0
  302. package/tsconfig.json +7 -0
  303. package/tsconfig.tests.json +15 -0
  304. package/vitest.built.config.ts +9 -0
  305. package/vitest.config.ts +54 -0
  306. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  307. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  308. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  309. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  310. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  311. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  312. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  313. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  314. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  315. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  316. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  317. /package/{lib → packages/selector/lib}/index.js +0 -0
  318. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  319. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  320. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  321. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  322. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  323. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  324. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
  325. /package/{locale → packages/selector/locale}/de.json +0 -0
  326. /package/{locale → packages/selector/locale}/en.json +0 -0
  327. /package/{locale → packages/selector/locale}/es.json +0 -0
  328. /package/{locale → packages/selector/locale}/fr.json +0 -0
  329. /package/{locale → packages/selector/locale}/it.json +0 -0
  330. /package/{locale → packages/selector/locale}/ja.json +0 -0
  331. /package/{locale → packages/selector/locale}/ko.json +0 -0
  332. /package/{locale → packages/selector/locale}/pt.json +0 -0
  333. /package/{locale → packages/selector/locale}/ru.json +0 -0
  334. /package/{locale → packages/selector/locale}/zh.json +0 -0
@@ -0,0 +1,307 @@
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
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `/ctx-summary off|on|status` — in-session temporary override for the
3
+ * turn-tail intent-summary gate.
4
+ *
5
+ * The override is session-scoped by design: settings are session-frozen
6
+ * (changes only affect newly observed sessions), so "temporarily disable and
7
+ * resume" can only be expressed as runtime state. Overrides die with the
8
+ * process and never leak across sessions. `off` wins over the settings gate;
9
+ * `on` never bypasses the numeric growth gates — it only lifts the
10
+ * settings/override veto.
11
+ *
12
+ * Registration mirrors the host's own `/compact` command: optional
13
+ * `commands`-service injection (a host without the registry simply never
14
+ * mounts the command), dynamic `CommandDefinitionId` brand import with a
15
+ * plain fallback so a stripped host cannot break plugin load.
16
+ */
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import {
19
+ getLastIntentFold,
20
+ getObservedIntentEnabled,
21
+ getSummaryOverride,
22
+ setSummaryOverride,
23
+ } from './tokenpilot/advisor-state.ts'
24
+ import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
25
+
26
+ export const SUMMARY_COMMAND_NAME = 'ctx-summary'
27
+
28
+ const USAGE = 'Usage: /ctx-summary off|on|status'
29
+
30
+ export type SummaryCommandArgs = 'off' | 'on' | 'status'
31
+
32
+ /** Parse the raw argument string; `undefined` = unrecognized (usage error). */
33
+ export function parseSummaryCommandArgs(rawInput: string): SummaryCommandArgs | undefined {
34
+ const token = rawInput.trim().toLowerCase()
35
+ if (token === 'off' || token === 'on' || token === 'status') return token
36
+ return undefined
37
+ }
38
+
39
+ function describeFold(sessionId: string): string {
40
+ const fold = getLastIntentFold(sessionId)
41
+ if (fold === undefined) return 'none'
42
+ return `turn ${fold.turn}, seq ${fold.startSeq}..${fold.endSeq}`
43
+ }
44
+
45
+ /** Human-facing status line; observability only, never a decision input. */
46
+ export function formatSummaryStatus(sessionId: string): string {
47
+ const override = getSummaryOverride(sessionId)
48
+ const enabled = getObservedIntentEnabled(sessionId)
49
+ const enabledText = enabled === undefined ? 'unknown (gate not evaluated yet)' : enabled ? 'yes' : 'no'
50
+ return [
51
+ `ctx-summary status:`,
52
+ ` override: ${override ?? 'default (settings-driven)'}`,
53
+ ` intentSummary enabled (settings): ${enabledText}`,
54
+ ` gate: floor >${Math.round(INTENT_GATE_FLOOR_FRACTION * 100)}% of window AND growth >${INTENT_GATE_GROWTH_TOKENS} tokens since last fold`,
55
+ ` last fold: ${describeFold(sessionId)}`,
56
+ ].join('\n')
57
+ }
58
+
59
+ /** Resolve the invoking agent's session id (`''` when the host exposes none). */
60
+ function sessionIdOf(agent: unknown): string {
61
+ const session = (agent as { session?: { id?: unknown } } | undefined)?.session
62
+ if (session === undefined || session.id === undefined || session.id === null) return ''
63
+ return String(session.id)
64
+ }
65
+
66
+ type CommandsServiceLike = {
67
+ register: (definition: {
68
+ definitionId?: unknown
69
+ name: string
70
+ description: string
71
+ handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: 'success' | 'error', text: string }>
72
+ }) => unknown
73
+ }
74
+
75
+ /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
76
+ async function loadCommandDefinitionId(): Promise<((id: string) => unknown) | undefined> {
77
+ try {
78
+ const mod = (await import('@deepseek-ai/dsh-commands')) as { CommandDefinitionId?: (id: string) => unknown }
79
+ return mod.CommandDefinitionId
80
+ } catch {
81
+ return undefined
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Mount `/ctx-summary` for every composed human-command adapter. Never
87
+ * throws: the command is a convenience surface, and a host without the
88
+ * commands service (or with an incompatible registry shape) simply runs
89
+ * without it.
90
+ */
91
+ export function registerSummaryCommand(ctx: Context): void {
92
+ ctx.inject(['commands'], (injected) => {
93
+ const commands = (injected as { commands?: unknown }).commands as CommandsServiceLike | undefined
94
+ if (commands === undefined || typeof commands.register !== 'function') return
95
+ void (async () => {
96
+ try {
97
+ const definitionId = await loadCommandDefinitionId()
98
+ await commands.register({
99
+ name: SUMMARY_COMMAND_NAME,
100
+ description: 'Turn-tail intent summary: temporarily disable/resume or inspect status',
101
+ ...(definitionId === undefined ? {} : { definitionId: definitionId('dsh-context-compression-improved/ctx-summary') }),
102
+ handler: async (invocation) => {
103
+ const rawInput = typeof invocation.rawInput === 'string' ? invocation.rawInput : ''
104
+ const args = parseSummaryCommandArgs(rawInput)
105
+ if (args === undefined) return { kind: 'error' as const, text: USAGE }
106
+ const sessionId = sessionIdOf(invocation.agent)
107
+ if (args === 'status') {
108
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
109
+ return { kind: 'success' as const, text: formatSummaryStatus(sessionId) }
110
+ }
111
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
112
+ setSummaryOverride(sessionId, args)
113
+ return {
114
+ kind: 'success' as const,
115
+ text: args === 'off'
116
+ ? 'ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)'
117
+ : 'ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)',
118
+ }
119
+ },
120
+ })
121
+ } catch {
122
+ // Registry rejected the definition (shape drift, closed union): the
123
+ // plugin keeps working, only the convenience command is absent.
124
+ }
125
+ })()
126
+ })
127
+ }
@@ -0,0 +1,177 @@
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
+ }
@@ -0,0 +1,72 @@
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
+ }