dsh-context-compression-improved 0.10.4 → 0.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/$null +1 -0
  2. package/.agents/plans/improve/checklist.md +32 -0
  3. package/.agents/plans/improve/findings.md +102 -0
  4. package/.agents/plans/improve/spec.md +53 -0
  5. package/.agents/plans/improve/tasks.md +70 -0
  6. package/.gitattributes +2 -0
  7. package/.githooks/pre-push +37 -0
  8. package/.github/workflows/ci.yml +47 -0
  9. package/CHANGELOG.de.md +580 -0
  10. package/CHANGELOG.es.md +588 -0
  11. package/CHANGELOG.fr.md +576 -0
  12. package/CHANGELOG.it.md +577 -0
  13. package/CHANGELOG.ja.md +261 -0
  14. package/CHANGELOG.ko.md +254 -0
  15. package/CHANGELOG.md +549 -0
  16. package/CHANGELOG.ru.md +554 -0
  17. package/CHANGELOG.zh.md +238 -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 +110 -15
  26. package/README.ru.md +96 -0
  27. package/README.zh.md +104 -14
  28. package/SECURITY.md +18 -0
  29. package/THIRD_PARTY_NOTICES.md +7 -25
  30. package/assets/board.png +0 -0
  31. package/assets/context.png +0 -0
  32. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  33. package/docs/assets/context-compression-selector-settings.png +0 -0
  34. package/docs/compat-0.1.5-report.md +77 -0
  35. package/docs/installation.de.md +104 -0
  36. package/docs/installation.es.md +104 -0
  37. package/docs/installation.fr.md +104 -0
  38. package/docs/installation.it.md +104 -0
  39. package/docs/installation.ja.md +78 -0
  40. package/docs/installation.ko.md +78 -0
  41. package/docs/installation.md +103 -0
  42. package/docs/installation.ru.md +104 -0
  43. package/docs/installation.zh.md +100 -0
  44. package/docs/repair-log.md +657 -0
  45. package/eslint.config.js +30 -0
  46. package/package.json +113 -126
  47. package/packages/selector/LICENSE +21 -0
  48. package/packages/selector/README.md +26 -0
  49. package/packages/selector/README.zh.md +24 -0
  50. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  51. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  52. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  53. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  54. package/packages/selector/lib/style.css +350 -0
  55. package/packages/selector/package.json +178 -0
  56. package/packages/selector/screenshots.json +3 -0
  57. package/packages/selector/src/client/CompressionProfileControls.tsx +319 -0
  58. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  59. package/packages/selector/src/client/CompressionProfileSelector.tsx +87 -0
  60. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  61. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  62. package/packages/selector/src/client/bridge-scope.ts +125 -0
  63. package/packages/selector/src/client/decode.ts +64 -0
  64. package/packages/selector/src/client/fab-pos.ts +71 -0
  65. package/packages/selector/src/client/index.ts +434 -0
  66. package/packages/selector/src/client/locales/de.ts +160 -0
  67. package/packages/selector/src/client/locales/es.ts +160 -0
  68. package/packages/selector/src/client/locales/fr.ts +160 -0
  69. package/packages/selector/src/client/locales/it.ts +160 -0
  70. package/packages/selector/src/client/locales/ja.ts +160 -0
  71. package/packages/selector/src/client/locales/ko.ts +160 -0
  72. package/packages/selector/src/client/locales/ru.ts +160 -0
  73. package/packages/selector/src/client/locales.ts +320 -0
  74. package/packages/selector/src/client/monitor-fab.ts +431 -0
  75. package/packages/selector/src/client/preset-options.ts +88 -0
  76. package/packages/selector/src/client/savings-card.tsx +269 -0
  77. package/packages/selector/src/client/scope-face.ts +24 -0
  78. package/packages/selector/src/client/settings-section.tsx +149 -0
  79. package/packages/selector/src/compat/host-generation.ts +96 -0
  80. package/packages/selector/src/compat/llm-messages.ts +50 -0
  81. package/packages/selector/src/compat/settings-lease.ts +108 -0
  82. package/packages/selector/src/compat/tool-result.ts +91 -0
  83. package/packages/selector/src/css-modules.d.ts +6 -0
  84. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  85. package/packages/selector/src/estimator-catalog.ts +104 -0
  86. package/packages/selector/src/index.ts +890 -0
  87. package/packages/selector/src/invariant.ts +113 -0
  88. package/packages/selector/src/preset-overlay.ts +749 -0
  89. package/packages/selector/src/profiles.ts +451 -0
  90. package/packages/selector/src/pruner/content.ts +199 -0
  91. package/packages/selector/src/pruner/session.ts +97 -0
  92. package/packages/selector/src/pruner/state.ts +61 -0
  93. package/packages/selector/src/pruner/tuning.ts +23 -0
  94. package/packages/selector/src/pruner/types.ts +78 -0
  95. package/packages/selector/src/pruner.ts +2916 -0
  96. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  97. package/packages/selector/src/runtime/audit.ts +320 -0
  98. package/packages/selector/src/runtime/config.ts +800 -0
  99. package/packages/selector/src/runtime/custom-policy.ts +300 -0
  100. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  101. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  102. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  103. package/packages/selector/src/runtime/measurement.ts +444 -0
  104. package/packages/selector/src/runtime/monitor.ts +310 -0
  105. package/packages/selector/src/runtime/panel-command.ts +213 -0
  106. package/packages/selector/src/runtime/reducers.ts +1755 -0
  107. package/packages/selector/src/runtime/retrieve.ts +505 -0
  108. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  109. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  110. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  111. package/packages/selector/src/runtime/savings.ts +526 -0
  112. package/packages/selector/src/runtime/session-events.ts +30 -0
  113. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  114. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  115. package/packages/selector/src/runtime/stats-db.ts +492 -0
  116. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  117. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  118. package/packages/selector/src/runtime/summary-command.ts +127 -0
  119. package/packages/selector/src/runtime/tail-trim.ts +177 -0
  120. package/packages/selector/src/runtime/token-count.ts +72 -0
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  134. package/packages/selector/src/runtime/tool-names.ts +36 -0
  135. package/packages/selector/src/runtime/toolclass.ts +103 -0
  136. package/packages/selector/src/runtime/types.ts +368 -0
  137. package/packages/selector/src/runtime/value.ts +48 -0
  138. package/packages/selector/src/settings-bridge.ts +175 -0
  139. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  140. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  141. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  142. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  143. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  144. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  145. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  146. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  147. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  148. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  149. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  150. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  151. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  155. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  156. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  157. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  158. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  159. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  160. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  161. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  162. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  163. package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
  164. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  165. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  166. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  167. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  168. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  169. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  170. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  171. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  172. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  173. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  174. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  175. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  176. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  177. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  178. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  179. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  180. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  181. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  182. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  183. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  184. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  185. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  186. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  187. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  188. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  189. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  190. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  191. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
  192. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  193. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  194. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  195. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  196. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  197. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  198. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  199. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  200. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  201. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  202. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  203. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  204. package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
  205. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  206. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  207. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  208. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  209. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  210. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  211. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  212. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  213. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  214. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  215. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
  216. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  217. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  218. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  219. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  220. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  221. package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
  222. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  223. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  224. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  225. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  226. package/packages/selector/tsconfig.json +11 -0
  227. package/packages/selector/tsdown.client.config.ts +102 -0
  228. package/packages/selector/tsdown.config.ts +20 -0
  229. package/pnpm-workspace.yaml +76 -0
  230. package/screenshots.json +6 -3
  231. package/scripts/capture-profile-baseline.mjs +42 -0
  232. package/scripts/cell-browser-e2e.mjs +354 -0
  233. package/scripts/generate-tokenizer-fixtures.py +81 -0
  234. package/scripts/generate-vision-fixtures.py +208 -0
  235. package/scripts/hosts.mjs +79 -0
  236. package/scripts/packed-components-smoke.mjs +763 -0
  237. package/scripts/packed-install-e2e.mjs +1346 -0
  238. package/scripts/sync-hosts.mjs +174 -0
  239. package/scripts/toolclass-corpus-replay.mjs +281 -0
  240. package/scripts/verify-release.mjs +338 -0
  241. package/tests/TEST_INVENTORY.md +41 -0
  242. package/tsconfig.base.json +18 -0
  243. package/tsconfig.json +7 -0
  244. package/tsconfig.tests.json +15 -0
  245. package/vitest.built.config.ts +9 -0
  246. package/vitest.config.ts +54 -0
  247. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  248. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  249. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  250. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  251. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  252. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  253. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  254. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  255. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  256. /package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +0 -0
  257. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  258. /package/{lib → packages/selector/lib}/client.js +0 -0
  259. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  260. /package/{lib → packages/selector/lib}/index.js +0 -0
  261. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  262. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  263. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  264. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  265. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  266. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  267. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  268. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
@@ -0,0 +1,2916 @@
1
+ /**
2
+ * Replay-safe, model-free context-compression selector for tool results.
3
+ *
4
+ * Standard profiles never rewrite ordinary Assistant prose. The only durable
5
+ * replacements emitted here are content-only `tool/result` rewrites whose
6
+ * full source remains in the append-only Session log.
7
+ *
8
+ * @module dsh-context-compression-improved-runtime
9
+ */
10
+
11
+ import { Service } from '@deepseek-ai/cordis'
12
+ import type { Context } from '@deepseek-ai/cordis'
13
+ import z from '@deepseek-ai/schemastery'
14
+ // dsh-llm 是 optional peer:official-clone profile 的模块图解析不到它,静态
15
+ // value import 在 ESM 链接期直接 ERR_MODULE_NOT_FOUND 拖死整个插件挂载(
16
+ // packed-install e2e seedSettings 实证,2026-10-16)。工厂语义极小且稳定
17
+ // (clone → brand id → deepFreeze),携带本地副本,与 0.9.3 SessionSeq 软取同族。
18
+ import { createUserMessage, freezeMessage } from './compat/llm-messages.ts'
19
+ import type { ContentBlock, ToolCallId, UserMessage } from '@deepseek-ai/dsh-llm'
20
+ // ≤0.1.1 宿主 loader 模块表的 dsh-session 没有 SessionSeq 运行时导出——静态
21
+ // named import 在 ESM 链接期即炸,loader entry(tool-result-pruner)mount 失败
22
+ // 连累整个 standard 预设(会话 resume 全挂,2026-10-08 五格 0.1.0/0.1.1 实证)。
23
+ // namespace 软取(链接零失败)+ 恒等回退:老线 session 事件 seq 本就是裸 number,
24
+ // 身份封印仅是新线防呆。CJS interop 形态(named 挂 default 下)一并兼容。
25
+ import * as dshSessionNamespace from '@deepseek-ai/dsh-session'
26
+ import type { SessionSeq as SessionSeqBrand } from '@deepseek-ai/dsh-session'
27
+ const dshSessionSoft = dshSessionNamespace as unknown as {
28
+ SessionSeq?: (value: number) => SessionSeqBrand
29
+ default?: { SessionSeq?: (value: number) => SessionSeqBrand }
30
+ }
31
+ const SessionSeqImpl =
32
+ dshSessionSoft.SessionSeq ??
33
+ dshSessionSoft.default?.SessionSeq ??
34
+ ((value: number) => value as SessionSeqBrand)
35
+ const SessionSeq = SessionSeqImpl as (value: number) => SessionSeqBrand
36
+
37
+ // 0.1.7-rc.2 removed the shared 'plugin' source kind — each producer declares
38
+ // its own kind in its own module (official pattern: compaction's
39
+ // 'compact-checkpoint' in compaction/src/index.ts).
40
+ declare module '@deepseek-ai/dsh-llm' {
41
+ interface MessageSourceMap {
42
+ 'dsh-context-compression': { readonly kind: 'dsh-context-compression' }
43
+ }
44
+ }
45
+ import type { Session, SessionEvent, ToolResultMessage } from '@deepseek-ai/dsh-session'
46
+ import type {} from '@deepseek-ai/dsh-agent'
47
+ import type {} from '@deepseek-ai/dsh-compaction'
48
+ import type {} from '@deepseek-ai/dsh-settings'
49
+ import type {
50
+ CompactionTokenView,
51
+ ObservedPromptUsage,
52
+ } from './runtime/measurement.ts'
53
+ import { measureForCompaction, officialRequestUsage } from './runtime/measurement.ts'
54
+ import { eventBySeq, sessionEvents } from './runtime/session-events.ts'
55
+ import { countExactCanonicalTextFields } from './runtime/token-count.ts'
56
+ import type {} from '@deepseek-ai/dsh-tools'
57
+ import {
58
+ tailTrimMessage,
59
+ tailTrimRef,
60
+ tailTrimStub,
61
+ } from './runtime/tail-trim.ts'
62
+ import { installContextCompressionRetrieve } from './runtime/retrieve.ts'
63
+ import { RUNTIME_TOOL_NAMES } from './runtime/tool-names.ts'
64
+ import type { PrunerState } from './pruner/state.ts'
65
+ import { countOmittedLines, CAPACITY_PRESSURE_RATIO } from './pruner/tuning.ts'
66
+ import type { ToolCallInfo, SnapshotCandidate, PlannedReplacement, HistoryPlanOutcome } from './pruner/types.ts'
67
+ import {
68
+ onlyTextBlock,
69
+ onlyTextBlocks,
70
+ countToolContent,
71
+ sameProviderMeasurementKey,
72
+ unavailableCount,
73
+ recoveryMarker,
74
+ summarize,
75
+ emptyResult,
76
+ pressureCost,
77
+ nativePruneContent,
78
+ } from './pruner/content.ts'
79
+ import {
80
+ hasOpenTurn,
81
+ rootToolResultSeq,
82
+ sourceRef as sourceRefFn,
83
+ latestCompletedToolStep,
84
+ routeAuditFact,
85
+ tokenizerAuditFact,
86
+ isError,
87
+ historyOutcome,
88
+ } from './pruner/session.ts'
89
+ import { buildLocatorBlock, findCompactionTrace } from './runtime/tokenpilot/locator.ts'
90
+ import { clusterOmittedLines, isSupersededRead, toolCallPath } from './runtime/tokenpilot/read-state.ts'
91
+ import {
92
+ Estimator,
93
+ backoffCooldownMs,
94
+ buildEstimatorSystemPrompt,
95
+ buildEstimatorUserPrompt,
96
+ isCoolingDown,
97
+ parseEstimatorAnswerDetailed,
98
+ type EstimatorFailures,
99
+ type EstimatorSample,
100
+ } from './runtime/tokenpilot/estimator.ts'
101
+ import {
102
+ adviseCandidates,
103
+ DEFAULT_ADVICE_ALPHA,
104
+ DEFAULT_ADVICE_HIGH_IMPACT_TOKENS,
105
+ } from './runtime/tokenpilot/benefit.ts'
106
+ import { SideChannel } from './runtime/tokenpilot/sidechannel.ts'
107
+ import {
108
+ advisorCandidatePreview,
109
+ collectTailText,
110
+ collectTaskSemantics,
111
+ runSessionAdvisorPass,
112
+ } from './runtime/tokenpilot/advisor.ts'
113
+ import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
114
+ import { evaluateIntentGate } from './runtime/tokenpilot/intent-gate.ts'
115
+ import { extractErrorLines, maskCandidateForSummary, type IntentRole } from './runtime/tokenpilot/intent-input-mask.ts'
116
+ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/tokenpilot/intent-range.ts'
117
+ import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
118
+ import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
119
+ import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
120
+ import { observeContextUsage } from './runtime/monitor.ts'
121
+ import { compressionMessageSource, viewToolResult } from './compat/tool-result.ts'
122
+
123
+ import {
124
+ DedupeTable,
125
+ dedupeHash,
126
+ dedupePlaceholder,
127
+ flattenPlainText,
128
+ } from './runtime/tokenpilot/dedup.ts'
129
+ import { getSavingsLedger } from './runtime/savings.ts'
130
+ import { claimFromLand, flushUsageOnDispose, reclaimFromTailTrim, scheduleUsageFlush, setStatsLivePathBusy } from './runtime/stats-sync.ts'
131
+ import { kickStatsBackfillOnDispose } from './runtime/stats-backfill.ts'
132
+ import { sampleIntegralBoundary } from './runtime/savings-integral.ts'
133
+ import { projectSessionSavings } from './runtime/savings-projection.ts'
134
+
135
+ /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
136
+ function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
137
+ return flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
138
+ }
139
+ import {
140
+ charsForTokens,
141
+ charsToTokens,
142
+ codePointLength,
143
+ CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
144
+ ContextCompressionSettingsSchema,
145
+ parseContextCompressionSettings,
146
+ DEFAULTS,
147
+ PRUNE_MARKER,
148
+ resolveConfig,
149
+ resolvePolicy,
150
+ } from './runtime/config.ts'
151
+ import {
152
+ historicalPlaceholder,
153
+ reduceFreshToolResult,
154
+ verifyReduction,
155
+ } from './runtime/reducers.ts'
156
+ import type {
157
+ CompressionPolicy,
158
+ ContextCompressionSettings,
159
+ HistoryMode,
160
+ PrunedEntry,
161
+ PruneResult,
162
+ PruneSessionOptions,
163
+ PruneStage,
164
+ ToolResultPruneConfig,
165
+ } from './runtime/types.ts'
166
+ import { COMPRESSION_PROFILES } from './runtime/types.ts'
167
+ import {
168
+ decideConservativeAdaptive,
169
+ deriveAdaptiveTokenBounds,
170
+ } from './runtime/adaptive-cost.ts'
171
+ import {
172
+ DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
173
+ priceOfficialDeepSeekUsage,
174
+ resolveOfficialDeepSeekPrice,
175
+ } from './runtime/deepseek-official-pricing.ts'
176
+ import { emitCompressionAudit, sanitizeAuditMessage } from './runtime/audit.ts'
177
+ import { assertNever, deepFreeze } from './runtime/value.ts'
178
+ import type {
179
+ CompressionAuditComponent,
180
+ CompressionAuditEvaluationStatus,
181
+ } from './runtime/audit.ts'
182
+
183
+ export {
184
+ codePointLength,
185
+ CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
186
+ ContextCompressionSettingsSchema,
187
+ parseContextCompressionSettings,
188
+ AUTO_COMPACT_THRESHOLD_LIMITS,
189
+ DEFAULTS,
190
+ isCompressionProfile,
191
+ isValidAutoCompactThresholdPercent,
192
+ PRUNE_MARKER,
193
+ resolveConfig,
194
+ resolvePolicy,
195
+ } from './runtime/config.ts'
196
+ export {
197
+ CustomCompressionPolicySchema,
198
+ DEFAULT_CUSTOM_COMPRESSION_POLICY,
199
+ resolveCustomPolicy,
200
+ } from './runtime/custom-policy.ts'
201
+ export type { CustomPolicyResolutionOptions } from './runtime/custom-policy.ts'
202
+ export { historicalPlaceholder, normalizeTerminalText, reduceFreshToolResult, verifyReduction } from './runtime/reducers.ts'
203
+ export { measureForCompaction } from './runtime/measurement.ts'
204
+ export type {
205
+ CompactionTokenView,
206
+ MeasuredTokenSurfaceNode,
207
+ } from './runtime/measurement.ts'
208
+ export type {
209
+ AutoCompactSettings,
210
+ CodeSkeletonSettings,
211
+ CompressionPolicy,
212
+ CompressionProfile,
213
+ CustomCompressionBudget,
214
+ CustomCompressionPolicy,
215
+ CustomCompressionUnit,
216
+ CustomHistoryPolicy,
217
+ CustomPrefixPolicy,
218
+ CustomTailTrimPolicy,
219
+ CustomCompressionPolicyV1,
220
+ CustomCompressionPolicyV2,
221
+ CustomCompressionPolicyV3,
222
+ ContextCompressionSettings,
223
+ HistoryMode,
224
+ PrunedEntry,
225
+ PruneResult,
226
+ PruneSessionOptions,
227
+ PruneStage,
228
+ ToolResultPruneConfig,
229
+ } from './runtime/types.ts'
230
+
231
+ // Re-export the canonical profile list from the type module as a runtime value.
232
+ export { COMPRESSION_PROFILES } from './runtime/types.ts'
233
+
234
+ declare module '@deepseek-ai/cordis' {
235
+ interface Context {
236
+ toolResultPruner: ToolResultPruner
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Cross-generation adaptation (0.2.0): the host `settings` service hands back
242
+ * the WHOLE entry config `{ settings: <subtree> }` instead of the settings
243
+ * subtree directly (older lines surfaced the subtree at the top level). The
244
+ * parser requires `profile`+`custom` at the root, so the wrapped shape threw
245
+ * "missing its complete shape" → the session failed open to `profile:'off'`,
246
+ * silently disabling fresh/aggregate on the desktop. Descend exactly one
247
+ * `{settings:<obj>}` wrapper ONLY when the root has no `profile`; every other
248
+ * shape is passed through untouched so the "exotic Host value must fail open
249
+ * to off" safety contract still holds.
250
+ */
251
+ export function unwrapSettingsEntry(value: unknown): unknown {
252
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
253
+ const record = value as Record<string, unknown>
254
+ if ('profile' in record) return value
255
+ const inner = record.settings
256
+ if (inner !== null && typeof inner === 'object' && !Array.isArray(inner)) return inner
257
+ return value
258
+ }
259
+
260
+ /**
261
+ * Whether a fresh candidate is BELOW the fresh trigger. Uses the real token
262
+ * count when an exact tokenizer is available (DeepSeek routes), and otherwise
263
+ * falls back to the 4.0 chars/token estimate — byte-for-byte the pre-existing
264
+ * behavior on routes without a bundled tokenizer (e.g. local Qwen).
265
+ */
266
+ export function freshBelowTrigger(candidate: SnapshotCandidate, policy: CompressionPolicy): boolean {
267
+ if (candidate.count.kind === 'exact-tokenizer') {
268
+ return candidate.count.tokens <= policy.freshTriggerTokens
269
+ }
270
+ return candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)
271
+ }
272
+
273
+ /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
274
+ export class ToolResultPruner extends Service {
275
+ static inject = ['tokenMeter']
276
+
277
+ static Config: z<ToolResultPruneConfig> = z.object({
278
+ profile: z.union([...COMPRESSION_PROFILES]).default(DEFAULTS.profile),
279
+ headChars: z.number().step(1).min(0).default(DEFAULTS.headChars),
280
+ tailChars: z.number().step(1).min(0).default(DEFAULTS.tailChars),
281
+ nativeTriggerTokens: z.number().step(1).min(1).required(false),
282
+ nativeTargetTokens: z.number().step(1).min(1).required(false),
283
+ freshTriggerTokens: z.number().step(1).min(1).required(false),
284
+ freshTargetTokens: z.number().step(1).min(1).required(false),
285
+ aggregateTriggerTokens: z.number().step(1).min(1).required(false),
286
+ aggregateTargetTokens: z.number().step(1).min(1).required(false),
287
+ historyTriggerTokens: z.number().step(1).min(1).required(false),
288
+ historyKeepRecentToolCalls: z.number().step(1).min(0).required(false),
289
+ historyKeepRecentTokens: z.number().step(1).min(0).required(false),
290
+ historyMinReclaimTokens: z.number().step(1).min(1).required(false),
291
+ autoCompactThresholdPercent: z.number().step(1).min(50).max(90).required(false),
292
+ })
293
+
294
+ /** Consolidated per-session mutable state. */
295
+ readonly state: PrunerState
296
+
297
+ /** 0.1.5-specific: per-session sets of already-audited native summary seqs. */
298
+ private readonly auditedNativeSummaries = new WeakMap<Session, Set<number>>()
299
+
300
+ constructor(ctx: Context, config: ToolResultPruneConfig = {}) {
301
+ super(ctx, 'toolResultPruner')
302
+ ctx.inject(['tools', 'systemPrompt'], recoveryCtx => {
303
+ installContextCompressionRetrieve(recoveryCtx)
304
+ })
305
+ this.state = {
306
+ config: resolveConfig(config),
307
+ sessionSettings: new WeakMap(),
308
+ firstExposure: new WeakMap(),
309
+ recoveryExemptions: new WeakMap(),
310
+ dedupeTables: new WeakMap(),
311
+ estimatorVerdicts: new WeakMap(),
312
+ estimatorFailures: new WeakMap(),
313
+ warnedFailures: new WeakMap(),
314
+ postflightDiagnostics: new WeakMap(),
315
+ activeRequestBoundaries: new WeakMap(),
316
+ tailTrimBoundaryAttempts: new WeakMap(),
317
+ policyResolutionAudits: new WeakMap(),
318
+ turnClocks: new WeakMap(),
319
+ estimatorRemainingTurns: new WeakMap(),
320
+ advisorChannels: new WeakMap(),
321
+ intentChannels: new WeakMap(),
322
+ projectedSavings: new WeakSet(),
323
+ pendingIntentFolds: new WeakMap(),
324
+ intentFoldedSeqs: new WeakMap(),
325
+ intentBaselines: new WeakMap(),
326
+ }
327
+
328
+ // 会话结束汇总(dsh-token-optimizer monitor 模式的同款体验):输出该会话的
329
+ // 净节省/缓存命中率一行账。事件名探测式注册——老代际不发 session/disposed
330
+ // 时监听器静默闲置,不构成任何行为差异。
331
+ try {
332
+ ;(ctx as unknown as { on: (name: string, handler: (session: Session) => void) => unknown }).on(
333
+ 'session/disposed',
334
+ (session) => {
335
+ try {
336
+ // T9:dispose 是 usage 残量出口——取消在途 debounce、立即 flush 并
337
+ // 标 source=live;老代际不发该事件时随写随刷路径不受影响。
338
+ flushUsageOnDispose(session)
339
+ // T21:dispose 后低频回填 kick(调度器内部节流,最多 10 分钟一次)。
340
+ kickStatsBackfillOnDispose()
341
+ const line = getSavingsLedger().sessionSummaryLine(String(session.id))
342
+ if (line.includes('requests=0') === false || line.includes('net=0(exact)/0(est)') === false) {
343
+ ctx.logger.info('context-compression session savings (%s): %s', String(session.id), line)
344
+ }
345
+ } catch {
346
+ /* 汇总失败不影响 dispose */
347
+ }
348
+ },
349
+ )
350
+ } catch {
351
+ /* 宿主不支持该事件名:静默 */
352
+ }
353
+
354
+ ctx.on('session/event', (session, event) => {
355
+ this.scanForSeededNativeSummary(session)
356
+ if (event.type === 'compaction/summary') {
357
+ this.emitNativeSummaryAudit(session, event.seq, event.data)
358
+ return
359
+ }
360
+ if (event.type === 'compaction/end') {
361
+ // TokenPilot-inspired A2: annotate the landed summary checkpoint with
362
+ // an Exact Sources locator block. Strictly after compaction/end so no
363
+ // open-compaction invariant ever observes the rewrite.
364
+ try {
365
+ this.attachSummaryLocator(session, event.data.compactionId)
366
+ } catch (error: unknown) {
367
+ this.auditFailure(session, 'pressure', 'summary-locator', error)
368
+ ctx.logger.warn('context-compression summary locator failed open: %o', error)
369
+ }
370
+ }
371
+ })
372
+
373
+ // This is the true first-exposure boundary available in the Harness:
374
+ // the preceding step's results are already durable, the new step is open,
375
+ // and the next model request has not yet derived its history.
376
+ ctx.on('agent/pre-step', async ({ agent, signal, turn, step }, next) => {
377
+ const boundary = {}
378
+ this.state.activeRequestBoundaries.set(agent.session, boundary)
379
+ try {
380
+ if (!signal.aborted) {
381
+ try {
382
+ // Only the immediately preceding step can contain results that have
383
+ // not yet been exposed. This freezes both REDUCE and KEEP decisions:
384
+ // older original events are never reconsidered after a profile change.
385
+ this.turnClock(agent.session, turn)
386
+ this.runRequestBoundary(agent.session, turn, step - 1, signal)
387
+ } catch (error: unknown) {
388
+ this.auditFailure(agent.session, 'fresh', 'request-boundary', error)
389
+ ctx.logger.warn('context-compression fresh pass failed open: %o', error)
390
+ }
391
+ }
392
+ const outcome = await next()
393
+ // BasicCompactionEngine's own pre-step may have just landed a Native
394
+ // auto-compact summary (possibly through a seed-reopen that never
395
+ // reaches the event firehose): scan once more after the step opens.
396
+ this.scanForSeededNativeSummary(agent.session)
397
+ return outcome
398
+ } finally {
399
+ if (this.state.activeRequestBoundaries.get(agent.session) === boundary) {
400
+ this.state.activeRequestBoundaries.delete(agent.session)
401
+ }
402
+ }
403
+ }, { prepend: true })
404
+
405
+ ctx.on('agent/turn-stopping', ({ agent, turn, signal }) => {
406
+ if (signal.aborted) return
407
+ try {
408
+ const step = latestCompletedToolStep(agent.session, turn)
409
+ if (step !== undefined) this.runRequestBoundary(agent.session, turn, step, signal)
410
+ } catch (error: unknown) {
411
+ this.auditFailure(agent.session, 'fresh', 'terminal-pass', error)
412
+ ctx.logger.warn('context-compression terminal pass failed open: %o', error)
413
+ }
414
+ // 压缩监控观测:每回合无条件记录上下文占用——面板占用条与
415
+ // 灾难性遗忘区建议的数据源,与 intentSummary 门控解耦(门关也可观测)。
416
+ try {
417
+ observeContextUsage(
418
+ String(agent.session.id),
419
+ measureForCompaction(this.ctx, agent.session).totalTokens,
420
+ this.contextWindowForRequest(agent.session),
421
+ )
422
+ } catch { /* 观测失败静默:面板显示陈旧/空态 */ }
423
+ // 仪表口径:把当前 surface 存活 seq 交给账本,离开 surface 的压缩替换
424
+ // 即从“当前生效毛节省”中回落(数字随压缩内容进出而涨落)。
425
+ this.ensureSavingsProjection(agent.session)
426
+ try {
427
+ getSavingsLedger().observeActive(
428
+ String(agent.session.id),
429
+ new Set([...agent.session.surface.nodes].map(Number)),
430
+ )
431
+ } catch { /* 观测失败静默:维持上次口径 */ }
432
+ // TokenPilot-inspired E1: advisory estimator pass, strictly off the
433
+ // synchronous chain. Verdicts only feed the next pressure pass.
434
+ void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
435
+ // Advisory relevance advisor: statistics and suggestions only — its
436
+ // summaries, scores, and decay figure never touch any decision path.
437
+ // Strictly fire-and-forget, with its own backoff state.
438
+ void this.postflightAdvisorPass(agent.session, turn, signal).catch(() => undefined)
439
+ // Turn-tail intent summary: strictly fire-and-forget like the advisor;
440
+ // the growth gate inside decides whether a summary call is even spent.
441
+ void this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => undefined)
442
+ })
443
+ }
444
+
445
+ /**
446
+ * Measure text content in Unicode code points; non-text blocks cost zero.
447
+ * @param blocks - tool-result content to measure.
448
+ * @returns total Unicode code points across text blocks.
449
+ */
450
+ /**
451
+ * Apply the configured native head/middle/tail transform.
452
+ * @param blocks - original tool-result content.
453
+ * @returns reduced content, or `null` when no reduction is required.
454
+ */
455
+ pruneContent(blocks: readonly ContentBlock[]): ContentBlock[] | null {
456
+ return nativePruneContent(
457
+ blocks,
458
+ this.state.config.headChars + codePointLength(PRUNE_MARKER) + this.state.config.tailChars,
459
+ this.state.config.headChars,
460
+ this.state.config.tailChars,
461
+ )
462
+ }
463
+
464
+ /**
465
+ * Run one stable-surface pass. `fresh` is invoked before every request and
466
+ * only reduces original oversized results. `pressure` is called by
467
+ * compaction-basic and may additionally age old results at one high-water.
468
+ * @param session - session whose current tool-result surface may be rewritten.
469
+ * @param options - pass stage and optional completed-step coordinates.
470
+ * @returns landed replacements and aggregate Unicode-code-point savings.
471
+ */
472
+ pruneSession(session: Session, options: PruneSessionOptions = {}): PruneResult {
473
+ this.scanForSeededNativeSummary(session)
474
+ const stage = options.stage ?? 'pressure'
475
+ // External callers (compaction-basic) do not carry routed capacity; the
476
+ // runtime resolves it itself so the frozen Auto Compact linkage and the
477
+ // Custom percentage policy see one consistent context window.
478
+ const contextWindowTokens = options.contextWindowTokens ?? this.contextWindowForRequest(session)
479
+ const policy = this.activePolicy(session, contextWindowTokens, stage)
480
+ if (policy === undefined) return emptyResult()
481
+ const profile = policy.profile
482
+ const view = measureForCompaction(this.ctx, session)
483
+ if (stage === 'fresh') {
484
+ // 前台优先:整个 fresh 压缩窗口置 busy,回填调度器在 chunk 间让路
485
+ setStatsLivePathBusy(true)
486
+ try {
487
+ // 真实 usage 聚合(monitor 口径):官方 TokenMeter 的上一已完成请求,
488
+ // 每 fresh 边界入账一次;pressure pass 读到同一 baseline,不重复计。
489
+ const usage = officialRequestUsage(view)
490
+ if (usage !== undefined) {
491
+ getSavingsLedger().recordUsage(String(session.id), usage)
492
+ }
493
+ // T8:持久 usage 走事件日志 data.usage 按科目入账,一秒 debounce 合并扫描。
494
+ scheduleUsageFlush(session)
495
+ // T15:按 call 积分采样(fresh 边界 = recordUsage 同点)——存量净快照 +
496
+ // 该次 usage 拆分,累计"按 N 次 call"的真节省;前向口径,失败静默不碰请求。
497
+ try {
498
+ const integralSessionId = String(session.id)
499
+ sampleIntegralBoundary({
500
+ sessionId: integralSessionId,
501
+ session,
502
+ net: getSavingsLedger().snapshot(integralSessionId).net,
503
+ usage,
504
+ })
505
+ } catch { /* 采样失败静默:积分口径停更,不阻塞请求 */ }
506
+ return this.decideFreshStep(session, options, policy, view)
507
+ } finally {
508
+ setStatsLivePathBusy(false)
509
+ }
510
+ }
511
+ if (profile === 'off') return emptyResult()
512
+
513
+ const landed: PrunedEntry[] = []
514
+ if (policy.nativeToolResultEnabled) {
515
+ const candidates = this.snapshot(session, view)
516
+ const eligible = candidates.filter(candidate => !this.isRecoveryExempt(session, candidate))
517
+ const exactUnavailable = eligible.some(candidate => candidate.count.kind !== 'exact-tokenizer')
518
+ if (exactUnavailable) {
519
+ this.warnExactUnavailable(session, view, 'native')
520
+ }
521
+ const planned = eligible
522
+ .map(candidate => this.planNative(candidate, session, stage, policy, view))
523
+ .filter((entry): entry is PlannedReplacement => entry !== null)
524
+ landed.push(...this.landAll(session, this.adviseReplacements(session, policy, planned, 'history')))
525
+ if (landed.length === 0) {
526
+ const chars = eligible.map(candidate => candidate.characterPressure)
527
+ this.auditComponent(session, policy, 'native-tool-result', 'pressure', 'skipped',
528
+ chars.length === 0 ? 'no-tool-result-candidates'
529
+ : Math.max(...chars) <= charsForTokens(policy.nativeTriggerTokens) ? 'at-or-below-trigger'
530
+ : planned.length === 0 ? 'no-valid-reduction'
531
+ : 'recovery-tool-unavailable', {
532
+ measurementKind: 'characters',
533
+ ...(chars.length === 0 ? {} : { currentTokens: charsToTokens(Math.max(...chars)) }),
534
+ triggerTokens: policy.nativeTriggerTokens,
535
+ targetTokens: policy.nativeTargetTokens,
536
+ })
537
+ }
538
+ return summarize(landed)
539
+ }
540
+
541
+ let historyOutcome: HistoryPlanOutcome = { kind: 'planned', plans: [] }
542
+ let historyAllowed = false
543
+ if (policy.historyMode === 'adaptive') {
544
+ historyOutcome = this.planHistoricalAging(session, policy, view)
545
+ // Adaptive cost authority is meaningful only after the structural
546
+ // planner has formed a real batch. A planning skip keeps its own reason
547
+ // (for example exact-tokenizer-unavailable) and never becomes a false
548
+ // adaptive-cost-rejected decision merely because it has zero plans.
549
+ if (historyOutcome.kind === 'planned') {
550
+ const capacityPressure = this.capacityPressureActive(session, view, policy)
551
+ historyAllowed = this.adaptiveHistoryAllowed(
552
+ session,
553
+ view,
554
+ historyOutcome.plans,
555
+ capacityPressure,
556
+ )
557
+ if (historyAllowed) {
558
+ landed.push(...this.landAll(session, this.adviseReplacements(session, policy, historyOutcome.plans, 'history')))
559
+ }
560
+ }
561
+ } else {
562
+ historyAllowed = this.historyAllowed(session, policy, view)
563
+ if (historyAllowed) {
564
+ historyOutcome = this.planHistoricalAging(session, policy, view)
565
+ if (historyOutcome.kind === 'planned') {
566
+ landed.push(...this.landAll(session, this.adviseReplacements(session, policy, historyOutcome.plans, 'history')))
567
+ }
568
+ }
569
+ }
570
+ if (!landed.some(entry => entry.stage === 'pressure')) {
571
+ this.auditHistoryEvaluation(session, policy, view, historyAllowed, historyOutcome)
572
+ }
573
+ if (policy.tailTrim?.enabled === true) {
574
+ const tailView = measureForCompaction(this.ctx, session)
575
+ this.landOldestTailTrimGroup(session, policy, tailView)
576
+ } else {
577
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'disabled', 'profile-policy')
578
+ }
579
+ return summarize(landed)
580
+ }
581
+
582
+ private activeSettings(session: Session): ContextCompressionSettings {
583
+ const frozen = this.state.sessionSettings.get(session)
584
+ if (frozen !== undefined) return frozen
585
+ // 0.1.7: the compression document rides the selector row's entry config as a
586
+ // `.volatile()` field — read it through the settings service's describe()
587
+ // mirror (keyed by the profile entry id). The legacy per-namespace get stays
588
+ // as a fallback; both are undefined-safe and the caller handles absence.
589
+ const settingsHost = this.ctx.get('settings') as {
590
+ describe?: () => Array<{ ns: unknown; value?: unknown }>
591
+ get?: (ns: never) => unknown
592
+ } | undefined
593
+ const settings = (settingsHost?.describe?.().find(
594
+ (d) => String(d.ns) === 'context-compression-improved-bundle',
595
+ )?.value
596
+ ?? settingsHost?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)) as ContextCompressionSettings | undefined
597
+ const unwrapped = unwrapSettingsEntry(settings)
598
+ let resolved: ContextCompressionSettings
599
+ let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
600
+ ? 'plugin-config-fallback'
601
+ : 'host-settings'
602
+ let autoCompactThresholdSource: 'generation-config' | 'host-settings' | 'schema-default'
603
+ = settings === undefined ? 'schema-default' : 'host-settings'
604
+ let settingsInvalidFallback: 'lossless-off' | undefined
605
+ try {
606
+ resolved = settings === undefined
607
+ ? ContextCompressionSettingsSchema({ profile: this.state.config.profile } as never)
608
+ // Validate the Host value BEFORE cloning: structuredClone normalizes
609
+ // class/exotic prototypes to Object.prototype and would otherwise
610
+ // erase the very boundary the parser is responsible for enforcing.
611
+ : parseContextCompressionSettings(unwrapped as ContextCompressionSettings)
612
+ } catch (error: unknown) {
613
+ // A malformed persisted document must fail open LOSSLESSLY: freezing the
614
+ // deployment default could silently re-enable lossy compression the
615
+ // user never chose (for example a stored `off` plus an unknown key), so
616
+ // the session freezes effectively off and keeps every original result.
617
+ const reason = error instanceof Error ? error.message : String(error)
618
+ this.auditFailure(session, 'pressure', 'policy-resolution', error)
619
+ this.warnOnce(
620
+ session,
621
+ `settings-invalid:${reason}`,
622
+ 'context-compression froze this session effectively off because the stored settings document is invalid: %s',
623
+ reason,
624
+ )
625
+ resolved = ContextCompressionSettingsSchema({ profile: 'off' } as never)
626
+ settingsSource = 'plugin-config-fallback'
627
+ autoCompactThresholdSource = 'schema-default'
628
+ settingsInvalidFallback = 'lossless-off'
629
+ }
630
+ if (this.state.config.autoCompactThresholdPercent !== undefined) {
631
+ // The preset overlay froze this generation's threshold into the
632
+ // deployment config; it supersedes the live Host setting so Auto
633
+ // Compact and micro compact can never split across two thresholds.
634
+ resolved = {
635
+ ...resolved,
636
+ autoCompact: { thresholdPercent: this.state.config.autoCompactThresholdPercent },
637
+ }
638
+ autoCompactThresholdSource = 'generation-config'
639
+ }
640
+ const snapshot = deepFreeze(structuredClone(resolved))
641
+ this.state.sessionSettings.set(session, snapshot)
642
+ emitCompressionAudit(this.ctx.logger, {
643
+ schemaVersion: 1,
644
+ kind: 'policy-frozen',
645
+ sessionId: String(session.id),
646
+ settingsSource,
647
+ autoCompactThresholdSource,
648
+ ...settingsInvalidFallback === undefined ? {} : { settingsInvalidFallback },
649
+ settings: snapshot,
650
+ deploymentConfig: this.state.config,
651
+ })
652
+ return snapshot
653
+ }
654
+
655
+ /**
656
+ * TokenPilot-inspired A2: replace the compaction summary checkpoint node
657
+ * with the same summary plus an Exact Sources locator block. Fails open:
658
+ * any unresolved shape (no trace, no checkpoint node, already annotated)
659
+ * leaves the summary untouched.
660
+ */
661
+ private attachSummaryLocator(session: Session, compactionId: string): void {
662
+ const policy = this.activePolicy(session)
663
+ if (policy?.presetOptions?.summaryLocator !== true) return
664
+ const events = sessionEvents(session)
665
+ const trace = findCompactionTrace(events, compactionId)
666
+ if (trace === undefined) return
667
+ const located = buildLocatorBlock(events, trace.summaryShadowedRange)
668
+ if (located === null) return
669
+ const block = located.text
670
+ // Locate the summary checkpoint surface node: the user/message replacement
671
+ // carrying this compaction's checkpoint provenance. Newest match wins.
672
+ let checkpointSeq: number | undefined
673
+ for (const seq of [...session.surface.nodes].reverse()) {
674
+ const event = eventBySeq(events, seq)
675
+ if (event === undefined || event.type !== 'user/message') continue
676
+ const source = (event.data as { source?: { compactionId?: unknown } }).source
677
+ if (source === undefined || source === null) continue
678
+ if (source.compactionId !== compactionId) continue
679
+ checkpointSeq = seq
680
+ break
681
+ }
682
+ if (checkpointSeq === undefined) return
683
+ const original = events[checkpointSeq]
684
+ if (original?.type !== 'user/message') return
685
+ const data = original.data as UserMessage & { source?: unknown }
686
+ const content = data.content.map(block => ({ ...block })) as typeof data.content
687
+ const textBlocks = content.filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text')
688
+ const lastText = textBlocks.at(-1)
689
+ const marker = '## Exact Sources (locators)'
690
+ if (lastText === undefined) return
691
+ if (lastText.text.includes(marker)) return
692
+ lastText.text = `${lastText.text}\n\n${block}`
693
+ // Drop the checkpoint provenance: this replacement is a plain plugin-source
694
+ // user/message surface rewrite, not a new compaction checkpoint, and
695
+ // carrying the marker would fail the host's closed-transaction validation.
696
+ const replacement = createUserMessage({
697
+ content,
698
+ // Generation-gated: 0.1.x hosts only accept the shared plugin kind.
699
+ source: compressionMessageSource() as { kind: 'dsh-context-compression' },
700
+ })
701
+ session.append('user/message', replacement, {
702
+ surfaceOp: { op: 'replace', startSeq: SessionSeq(checkpointSeq), endSeq: SessionSeq(checkpointSeq) },
703
+ sourceEventSeqs: [SessionSeq(checkpointSeq)],
704
+ })
705
+ emitCompressionAudit(this.ctx.logger, {
706
+ schemaVersion: 1,
707
+ kind: 'summary-locator',
708
+ sessionId: String(session.id),
709
+ profile: policy.profile,
710
+ checkpointSeq,
711
+ summarySeq: trace.summarySeq,
712
+ locatorChars: codePointLength(located.text),
713
+ spillFiles: located.spillFiles,
714
+ touchedFiles: located.touchedFiles,
715
+ })
716
+ }
717
+
718
+ /**
719
+ * TokenPilot-inspired E1: sample oversized historical reads and ask the
720
+ * auxiliary estimator whether their file state is still likely to be
721
+ * referenced. Fire-and-forget: never awaited on the pruning chain, failures
722
+ * back off exponentially per Session, verdicts only extend the rule-only
723
+ * superseded classification.
724
+ */
725
+ private async postflightEstimatorPass(session: Session, signal: AbortSignal): Promise<void> {
726
+ const policy = this.activePolicy(session)
727
+ const presetOptions = policy?.presetOptions
728
+ if (policy === undefined || presetOptions?.readState !== true) return
729
+ const estimatorMode = presetOptions.estimator?.mode ?? ''
730
+ if (estimatorMode === '') return
731
+ const failures = this.state.estimatorFailures.get(session)
732
+ if (isCoolingDown(failures, Date.now())) return
733
+
734
+ const events = sessionEvents(session)
735
+ const samples: EstimatorSample[] = []
736
+ const now = Date.now()
737
+ for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
738
+ if (samples.length >= 3) break
739
+ if (candidate.event.data.turn === undefined) continue
740
+ if (freshBelowTrigger(candidate, policy)) continue
741
+ const path = toolCallPath(candidate.call.arguments)
742
+ if (path === undefined) continue
743
+ if (isSupersededRead(events, candidate.seq, path)) continue
744
+ if (this.state.estimatorVerdicts.get(session)?.has(candidate.seq) === true) continue
745
+ samples.push({ seq: candidate.seq, path, turn: candidate.event.data.turn })
746
+ }
747
+ if (samples.length === 0) return
748
+
749
+ const estimator = new Estimator(this.ctx, this.activeSettings(session).presetOptions ?? {})
750
+ const answer = await estimator.ask(buildEstimatorSystemPrompt(), buildEstimatorUserPrompt(samples), signal)
751
+ const latencyMs = Date.now() - now
752
+ const ok = answer !== undefined && signal.aborted === false
753
+ let expired = 0
754
+ if (ok && answer !== undefined) {
755
+ let verdicts = this.state.estimatorVerdicts.get(session)
756
+ if (verdicts === undefined) {
757
+ verdicts = new Map()
758
+ this.state.estimatorVerdicts.set(session, verdicts)
759
+ }
760
+ const detailed = parseEstimatorAnswerDetailed(answer)
761
+ // TokenPilot-inspired R4: the optional session-level Ŝ rides on the same
762
+ // answer; it only sharpens the benefit model and is never required.
763
+ if (detailed.expectedRemainingTurns !== undefined) {
764
+ this.state.estimatorRemainingTurns.set(session, detailed.expectedRemainingTurns)
765
+ }
766
+ for (const verdict of detailed.verdicts) {
767
+ if (verdicts.has(verdict.seq)) continue
768
+ verdicts.set(verdict.seq, verdict.expired)
769
+ if (verdict.expired) expired += 1
770
+ }
771
+ } else {
772
+ const next: EstimatorFailures = {
773
+ failures: (failures?.failures ?? 0) + 1,
774
+ cooldownUntil: Date.now() + backoffCooldownMs((failures?.failures ?? 0) + 1),
775
+ }
776
+ this.state.estimatorFailures.set(session, next)
777
+ }
778
+ emitCompressionAudit(this.ctx.logger, {
779
+ schemaVersion: 1,
780
+ kind: 'estimator-outcome',
781
+ sessionId: String(session.id),
782
+ profile: policy.profile,
783
+ channel: estimatorMode === 'host' ? 'host' : 'direct',
784
+ sampled: samples.length,
785
+ expired,
786
+ latencyMs,
787
+ ok,
788
+ })
789
+ }
790
+
791
+ // ─────────── Advisory relevance advisor (statistics & suggestions only) ───────────
792
+
793
+ /**
794
+ * Advisory advisor pass at the turn boundary, strictly fire-and-forget.
795
+ * Produces todolist-bound tail-task summaries, incremental relevance
796
+ * scores, and a prefix-decay figure — all observational. Every short
797
+ * circuit below (mode off, re-entry, cooldown, no task semantics, no
798
+ * direct endpoint) returns without touching any state the pruning chain
799
+ * reads, so the default configuration adds exactly zero behavior.
800
+ */
801
+ private async postflightAdvisorPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
802
+ const policy = this.activePolicy(session)
803
+ const presetOptions = policy?.presetOptions
804
+ const advisor = presetOptions?.advisor
805
+ if (policy === undefined || presetOptions === undefined || advisor === undefined || advisor.mode === '') return
806
+ const advisorState = getAdvisorState(session)
807
+ if (advisorState.inFlight) return
808
+ if (isCoolingDown(advisorState.failures, Date.now())) return
809
+
810
+ const events = sessionEvents(session)
811
+ const task = collectTaskSemantics(events)
812
+ if (task === undefined) return
813
+
814
+ const settings = this.activeSettings(session).presetOptions ?? {}
815
+ if (advisor.mode === 'direct'
816
+ && (settings.estimatorBaseUrl === undefined || settings.estimatorBaseUrl.length === 0
817
+ || settings.estimatorModel === undefined || settings.estimatorModel.length === 0)) {
818
+ // The advisor reuses the estimator's direct endpoint; when it is not
819
+ // configured there is nothing to ask, so record the aligned reason and
820
+ // back off instead of re-emitting the audit at every turn.
821
+ emitCompressionAudit(this.ctx.logger, {
822
+ schemaVersion: 1,
823
+ kind: 'advisor-outcome',
824
+ sessionId: String(session.id),
825
+ phase: 'summary',
826
+ channel: 'direct',
827
+ ok: false,
828
+ turnIndex: turn,
829
+ reason: 'no-direct-endpoint',
830
+ latencyMs: 0,
831
+ })
832
+ advisorState.failures = {
833
+ failures: (advisorState.failures?.failures ?? 0) + 1,
834
+ cooldownUntil: Date.now() + backoffCooldownMs((advisorState.failures?.failures ?? 0) + 1),
835
+ }
836
+ return
837
+ }
838
+
839
+ let channel = this.state.advisorChannels.get(session)
840
+ if (channel === undefined) {
841
+ channel = new SideChannel(this.ctx, settings, {
842
+ mode: advisor.mode,
843
+ timeoutMs: advisor.timeoutMs,
844
+ maxTokens: 512,
845
+ })
846
+ this.state.advisorChannels.set(session, channel)
847
+ }
848
+
849
+ const view = measureForCompaction(this.ctx, session)
850
+ const candidates = this.snapshot(session, view)
851
+ .filter(candidate => !this.isRecoveryExempt(session, candidate))
852
+ .map(candidate => ({
853
+ seq: candidate.seq,
854
+ characterPressure: candidate.characterPressure,
855
+ preview: advisorCandidatePreview(candidate.call.name, viewToolResult(candidate.event.data.message).blocks),
856
+ }))
857
+
858
+ let sawFailure = false
859
+ const outcome = await runSessionAdvisorPass(session, channel, record => {
860
+ if (record.ok === false) sawFailure = true
861
+ emitCompressionAudit(this.ctx.logger, record)
862
+ }, {
863
+ profile: policy.profile,
864
+ sessionId: String(session.id),
865
+ turn,
866
+ candidates,
867
+ task: {
868
+ source: task.source,
869
+ todoVersion: task.todoVersion,
870
+ taskText: task.taskText,
871
+ },
872
+ advisor: {
873
+ refreshTurns: advisor.refreshTurns,
874
+ scoreThreshold: advisor.scoreThreshold,
875
+ sampleLimit: advisor.sampleLimit,
876
+ minTokens: advisor.minTokens,
877
+ },
878
+ tailText: collectTailText(events),
879
+ signal,
880
+ })
881
+ if (outcome === undefined && sawFailure && signal.aborted === false) {
882
+ advisorState.failures = {
883
+ failures: (advisorState.failures?.failures ?? 0) + 1,
884
+ cooldownUntil: Date.now() + backoffCooldownMs((advisorState.failures?.failures ?? 0) + 1),
885
+ }
886
+ } else if (outcome !== undefined) {
887
+ advisorState.failures = undefined
888
+ }
889
+ }
890
+
891
+ /**
892
+ * 重进/重启会话的懒重建:首次观测某会话时,若账本尚无该会话条目,则按会话
893
+ * 日志投影播种(当前生效毛节省 + 每次重读惩罚 + 原文配对键)。只做一次,
894
+ * fail-open;同一进程内的实时增量随后在同一条目集合上继续。
895
+ */
896
+ private ensureSavingsProjection(session: Session): void {
897
+ if (this.state.projectedSavings.has(session)) return
898
+ this.state.projectedSavings.add(session)
899
+ const ledger = getSavingsLedger()
900
+ if (ledger.hasSession(String(session.id))) return
901
+ try {
902
+ ledger.seedProjected(String(session.id), projectSessionSavings(this.ctx, session))
903
+ } catch { /* 投影失败静默:面板显示空态,不影响主流程 */ }
904
+ }
905
+
906
+ // ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
907
+
908
+ /**
909
+ * Fire-and-forget postflight: evaluate the growth gate, and only when it
910
+ * passes, select the consumed increment OUTSIDE the protected working set,
911
+ * mask it to semantic-role records, and spend ONE summary-writer call. The
912
+ * verdict stages as a pending fold that the NEXT pressure round lands via
913
+ * the ordinary plan/apply machinery — the synchronous decision path never
914
+ * waits on an LLM.
915
+ */
916
+ private async postflightIntentFoldPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
917
+ const started = Date.now()
918
+ const sessionId = String(session.id)
919
+ const policy = this.activePolicy(session)
920
+ const settings = this.activeSettings(session)
921
+ const intentEnabled = settings.intentSummary.enabled
922
+ const override = getSummaryOverride(sessionId)
923
+ observeIntentEnabled(sessionId, intentEnabled)
924
+ if (policy === undefined) return
925
+ if (this.state.pendingIntentFolds.has(session)) return
926
+ const advisorState = getAdvisorState(session)
927
+ if (advisorState.inFlight) return
928
+ if (isCoolingDown(advisorState.failures, Date.now())) return
929
+
930
+ const view = measureForCompaction(this.ctx, session)
931
+ // The window is the Auto Compact linkage input: policy.autoCompactTokens
932
+ // == floor(window * threshold/100); invert for the gate floor.
933
+ const thresholdPercent = settings.autoCompact.thresholdPercent
934
+ const contextWindow = policy.autoCompactTokens !== undefined && thresholdPercent > 0
935
+ ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100))
936
+ : undefined
937
+ const gate = evaluateIntentGate({
938
+ enabled: intentEnabled,
939
+ override,
940
+ liveTokens: view.totalTokens,
941
+ contextWindow,
942
+ baselineTokens: this.state.intentBaselines.get(session) ?? 0,
943
+ })
944
+ if (!gate.decision) return
945
+
946
+ const settingsPreset = settings.presetOptions
947
+ if (settingsPreset === undefined) return
948
+ // 写手通道复用估计器通道:`host` 走宿主 llm 路由(provider/model 可省),
949
+ // `direct` 才需要显式 OpenAI 兼容端点。此前无条件要求直连端点,导致
950
+ // host 通道下每个回合都以 'no-direct-endpoint' 提前返回,fold 永不落地。
951
+ const estimatorMode = settingsPreset.estimatorMode ?? ''
952
+ if (estimatorMode !== 'host' && estimatorMode !== 'direct') {
953
+ emitCompressionAudit(this.ctx.logger, {
954
+ schemaVersion: 1,
955
+ kind: 'intent-summary-outcome',
956
+ sessionId,
957
+ ok: false,
958
+ reason: 'no-estimator-channel',
959
+ turnIndex: turn,
960
+ latencyMs: Date.now() - started,
961
+ })
962
+ return
963
+ }
964
+ if (estimatorMode === 'direct'
965
+ && (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
966
+ || settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0)) {
967
+ emitCompressionAudit(this.ctx.logger, {
968
+ schemaVersion: 1,
969
+ kind: 'intent-summary-outcome',
970
+ sessionId,
971
+ ok: false,
972
+ reason: 'no-direct-endpoint',
973
+ turnIndex: turn,
974
+ latencyMs: Date.now() - started,
975
+ })
976
+ return
977
+ }
978
+
979
+ const candidates = this.snapshot(session, view).filter(candidate => !this.isRecoveryExempt(session, candidate))
980
+ const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
981
+ const range = computeIntentRange({
982
+ candidates,
983
+ protectedSeqs,
984
+ foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? new Set<number>(),
985
+ maxCandidates: INTENT_RANGE_MAX_CANDIDATES,
986
+ })
987
+ if (range.seqs.length === 0) return
988
+
989
+ const bySeq = new Map(candidates.map(candidate => [candidate.seq, candidate]))
990
+ const records: { seq: number, role: IntentRole, toolName: string, line: string }[] = []
991
+ const errorLines = new Set<string>()
992
+ for (const seq of range.seqs) {
993
+ const candidate = bySeq.get(seq)
994
+ if (candidate === undefined) continue
995
+ const text = onlyTextBlock(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])?.text ?? ''
996
+ const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text)
997
+ records.push({ seq, role: masked.role, toolName: candidate.call.name, line: masked.record })
998
+ for (const line of extractErrorLines(text)) errorLines.add(line)
999
+ }
1000
+ if (records.length === 0) return
1001
+
1002
+ const events = sessionEvents(session)
1003
+ const task = collectTaskSemantics(events)
1004
+ // 独立通道:写手用 30s 超时,advisor 用其自身超时——两者若共享
1005
+ // advisorChannels,先构造者会把 mode/timeout 强加给后者。
1006
+ let channel = this.state.intentChannels.get(session)
1007
+ if (channel === undefined) {
1008
+ channel = new SideChannel(this.ctx, settingsPreset, {
1009
+ mode: estimatorMode,
1010
+ timeoutMs: 30_000,
1011
+ maxTokens: 512,
1012
+ })
1013
+ this.state.intentChannels.set(session, channel)
1014
+ }
1015
+
1016
+ const answer = await channel.ask({
1017
+ system: buildIntentSummarySystemPrompt(),
1018
+ user: buildIntentSummaryUserPrompt(task?.taskText ?? '(no task semantics yet)', records.map(record => record.line), collectTailText(events)),
1019
+ signal,
1020
+ })
1021
+ const summaryCallChars = answer?.length ?? 0
1022
+ const parsed = answer === undefined ? undefined : parseIntentSummaryAnswer(answer)
1023
+ if (parsed === undefined) {
1024
+ const failures = (advisorState.failures?.failures ?? 0) + 1
1025
+ advisorState.failures = { failures, cooldownUntil: Date.now() + backoffCooldownMs(failures) }
1026
+ emitCompressionAudit(this.ctx.logger, {
1027
+ schemaVersion: 1,
1028
+ kind: 'intent-summary-outcome',
1029
+ sessionId,
1030
+ ok: false,
1031
+ reason: answer === undefined ? 'ask-failed' : 'parse-failed',
1032
+ turnIndex: turn,
1033
+ foldedCount: records.length,
1034
+ summaryCallChars,
1035
+ latencyMs: Date.now() - started,
1036
+ })
1037
+ return
1038
+ }
1039
+ this.state.pendingIntentFolds.set(session, {
1040
+ createdAt: Date.now(),
1041
+ turn,
1042
+ startSeq: range.seqs[0]!,
1043
+ endSeq: range.seqs[range.seqs.length - 1]!,
1044
+ summary: parsed.summary,
1045
+ errorLines: [...errorLines],
1046
+ records,
1047
+ summaryCallChars,
1048
+ })
1049
+ emitCompressionAudit(this.ctx.logger, {
1050
+ schemaVersion: 1,
1051
+ kind: 'intent-summary-outcome',
1052
+ sessionId,
1053
+ ok: true,
1054
+ reason: 'staged',
1055
+ turnIndex: turn,
1056
+ foldedCount: records.length,
1057
+ summaryCallChars,
1058
+ latencyMs: Date.now() - started,
1059
+ })
1060
+ }
1061
+
1062
+ /**
1063
+ * Convert a staged pending fold into per-candidate planned replacements
1064
+ * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
1065
+ * rich-content, or no longer exists keeps its original text. Returns
1066
+ * `undefined` when there is nothing (or no longer anything) to fold.
1067
+ */
1068
+ private applyPendingIntentFold(
1069
+ session: Session,
1070
+ policy: CompressionPolicy,
1071
+ view: CompactionTokenView,
1072
+ eligible: readonly SnapshotCandidate[],
1073
+ ): { plans: PlannedReplacement[], reclaim: number, foldedSeqs: Set<number>, charsBefore: number, charsAfter: number, turn: number, summaryCallChars: number } | undefined {
1074
+ const pending = this.state.pendingIntentFolds.get(session)
1075
+ if (pending === undefined) return undefined
1076
+ const bySeq = new Map(eligible.map(candidate => [candidate.seq, candidate]))
1077
+ const foldable = pending.records
1078
+ .map(record => record.seq)
1079
+ .filter(seq => bySeq.has(seq))
1080
+ .sort((a, b) => a - b)
1081
+ if (foldable.length === 0) {
1082
+ this.state.pendingIntentFolds.delete(session)
1083
+ return undefined
1084
+ }
1085
+ const plans: PlannedReplacement[] = []
1086
+ const foldedSeqs = new Set<number>()
1087
+ let reclaim = 0
1088
+ let charsBefore = 0
1089
+ let charsAfter = 0
1090
+ for (const seq of foldable) {
1091
+ const candidate = bySeq.get(seq)!
1092
+ const block = onlyTextBlock(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
1093
+ if (block === null) continue
1094
+ const text = renderIntentFoldBlock(pending, seq)
1095
+ const plan = this.plan(
1096
+ candidate,
1097
+ [{ ...block, text }],
1098
+ rootToolResultSeq(session, candidate.seq),
1099
+ 'intent-summary',
1100
+ 'pressure',
1101
+ 'history',
1102
+ policy.historyMode,
1103
+ view,
1104
+ )
1105
+ if (plan === null || plan.charsAfter >= plan.charsBefore) continue
1106
+ plans.push(plan)
1107
+ foldedSeqs.add(seq)
1108
+ reclaim += plan.charsBefore - plan.charsAfter
1109
+ charsBefore += plan.charsBefore
1110
+ charsAfter += plan.charsAfter
1111
+ }
1112
+ if (plans.length === 0) return undefined
1113
+ this.state.intentFoldedSeqs.get(session)?.forEach(seq => foldedSeqs.add(seq))
1114
+ return { plans, reclaim, foldedSeqs, charsBefore, charsAfter, turn: pending.turn, summaryCallChars: pending.summaryCallChars }
1115
+ }
1116
+
1117
+ // ─────────── Advisory benefit model (statistics & suggestions only) ───────────
1118
+
1119
+ /**
1120
+ * Monotonic per-session turn clock for advisory records. Bumped by the agent
1121
+ * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
1122
+ * observed value.
1123
+ */
1124
+ private turnClock(session: Session, turn?: number): number {
1125
+ const previous = this.state.turnClocks.get(session) ?? 0
1126
+ const next = typeof turn === 'number' && Number.isSafeInteger(turn) && turn > previous ? turn : previous
1127
+ this.state.turnClocks.set(session, next)
1128
+ return next
1129
+ }
1130
+
1131
+ /**
1132
+ * Advisory benefit-model hook — what the retired human-gated review pipeline
1133
+ * left behind. It is the IDENTITY on the landing path: every plan it is given
1134
+ * comes back unchanged, because a reduction must never block automatic
1135
+ * processing. The model's band is published as a `reduction-advice` audit and
1136
+ * snapshotted onto the advisor state for the read-only report route, so the
1137
+ * cache-accounting insight survives without a gate.
1138
+ */
1139
+ private adviseReplacements(
1140
+ session: Session,
1141
+ policy: CompressionPolicy,
1142
+ plans: readonly PlannedReplacement[],
1143
+ stage: 'fresh' | 'history' = 'history',
1144
+ ): readonly PlannedReplacement[] {
1145
+ if (plans.length === 0) return plans
1146
+ const remainingTurns = this.state.estimatorRemainingTurns.get(session)
1147
+ const advice = adviseCandidates(plans.map(plan => ({
1148
+ sourceSeq: plan.sourceSeq,
1149
+ tokensBefore: plan.tokensBefore,
1150
+ tokensAfter: plan.tokensAfter,
1151
+ })), {
1152
+ alpha: DEFAULT_ADVICE_ALPHA,
1153
+ // One-phase approximation of the tail that a mutation must refill: the
1154
+ // frozen protected recent-token tail (findings.md, 约束与依赖).
1155
+ tailTokens: Math.max(1, policy.historyKeepRecentTokens),
1156
+ highImpactTokens: DEFAULT_ADVICE_HIGH_IMPACT_TOKENS,
1157
+ ...remainingTurns === undefined ? {} : { remainingTurns },
1158
+ // Fresh plans shape content before its first request — it is not in the
1159
+ // KV cache yet, so no cache break occurs and the refill penalty would be
1160
+ // a phantom cost pricing every realistic fresh batch into the
1161
+ // not-worth-it band.
1162
+ stage,
1163
+ })
1164
+ if (advice === undefined) return plans
1165
+ const turn = this.turnClock(session)
1166
+ const itemSeqs = plans.map(plan => plan.sourceSeq)
1167
+ // Observational snapshot only: the advisory-only invariant (K13) holds
1168
+ // because no decision path reads this field.
1169
+ getAdvisorState(session).lastAdvice = {
1170
+ band: advice.band,
1171
+ turn,
1172
+ itemSeqs,
1173
+ recoveredTokens: advice.benefit.recoveredTokens,
1174
+ penaltyTokens: advice.benefit.penaltyTokens,
1175
+ ...advice.benefit.paybackTurns === undefined ? {} : { paybackTurns: advice.benefit.paybackTurns },
1176
+ }
1177
+ emitCompressionAudit(this.ctx.logger, {
1178
+ schemaVersion: 1,
1179
+ kind: 'reduction-advice',
1180
+ sessionId: String(session.id),
1181
+ profile: policy.profile,
1182
+ band: advice.band,
1183
+ stage,
1184
+ itemSeqs,
1185
+ pricedCandidates: advice.priced,
1186
+ maxTokensBefore: advice.maxTokensBefore,
1187
+ tokensBefore: plans.reduce((sum, plan) => sum + plan.tokensBefore, 0),
1188
+ tokensAfter: plans.reduce((sum, plan) => sum + plan.tokensAfter, 0),
1189
+ recoveredTokens: advice.benefit.recoveredTokens,
1190
+ penaltyTokens: advice.benefit.penaltyTokens,
1191
+ ...advice.benefit.paybackTurns === undefined ? {} : { paybackTurns: advice.benefit.paybackTurns },
1192
+ ...advice.benefit.expectedSaving === undefined ? {} : { expectedSaving: advice.benefit.expectedSaving },
1193
+ turnIndex: turn,
1194
+ })
1195
+ return plans
1196
+ }
1197
+
1198
+ private activePolicy(
1199
+ session: Session,
1200
+ contextWindowTokens?: number,
1201
+ stage: PruneStage = 'pressure',
1202
+ ): CompressionPolicy | undefined {
1203
+ const settings = this.activeSettings(session)
1204
+ try {
1205
+ // R4 bridge: the persisted settings document's presetOptions (the
1206
+ // settings-card writes, including the advisor keys) must reach the
1207
+ // policy — before this bridge only the estimator endpoint read them
1208
+ // directly and every policy consumer saw the deployment defaults. User
1209
+ // settings win over deployment config; absent fields inherit via
1210
+ // mergePresetOptions.
1211
+ const policy = resolvePolicy(
1212
+ settings.presetOptions === undefined
1213
+ ? this.state.config
1214
+ : { ...this.state.config, presetOptions: settings.presetOptions },
1215
+ settings.profile,
1216
+ settings.custom,
1217
+ {
1218
+ ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
1219
+ autoCompactThresholdPercent: settings.autoCompact.thresholdPercent,
1220
+ },
1221
+ settings.ptcCustom,
1222
+ )
1223
+ // Route changes must produce a fresh audit record even when the policy
1224
+ // object is unchanged, or the dedupe would hide a mid-session reroute.
1225
+ const route = routeAuditFact(session)
1226
+ const auditKey = JSON.stringify({
1227
+ policy,
1228
+ contextWindowTokens: contextWindowTokens ?? null,
1229
+ route: route ?? null,
1230
+ })
1231
+ // Deduplicate only CONSECUTIVE identical resolutions: a permanent set
1232
+ // would hide an A -> B -> A reroute's third record.
1233
+ if (this.state.policyResolutionAudits.get(session) !== auditKey) {
1234
+ this.state.policyResolutionAudits.set(session, auditKey)
1235
+ // Deployment config overrides win over the Auto Compact linkage, so a
1236
+ // standard profile whose History watermarks were replaced must not
1237
+ // audit itself as purely linkage-derived.
1238
+ const overriddenLinkedFields = ([
1239
+ 'historyTriggerTokens',
1240
+ 'historyKeepRecentTokens',
1241
+ 'historyMinReclaimTokens',
1242
+ ] as const).filter(key => this.state.config[key] !== undefined).length
1243
+ emitCompressionAudit(this.ctx.logger, {
1244
+ schemaVersion: 1,
1245
+ kind: 'policy-resolved',
1246
+ sessionId: String(session.id),
1247
+ policy,
1248
+ ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
1249
+ coordination: {
1250
+ thresholdPercent: settings.autoCompact.thresholdPercent,
1251
+ ...policy.autoCompactTokens === undefined ? {} : { autoCompactTokens: policy.autoCompactTokens },
1252
+ ...policy.microDeadlineTokens === undefined ? {} : { microDeadlineTokens: policy.microDeadlineTokens },
1253
+ paramSource: settings.profile === 'custom'
1254
+ ? 'custom-manual'
1255
+ : overriddenLinkedFields === 3 ? 'deployment-override'
1256
+ : overriddenLinkedFields > 0 ? 'mixed'
1257
+ : policy.microDeadlineTokens === undefined ? 'fixed-preset' : 'auto-compact-linked',
1258
+ },
1259
+ ...route === undefined ? {} : { route },
1260
+ ...route === undefined ? {} : tokenizerAuditFact(route),
1261
+ })
1262
+ }
1263
+ return policy
1264
+ } catch (error: unknown) {
1265
+ const reason = error instanceof Error ? error.message : String(error)
1266
+ this.auditFailure(session, stage, 'policy-resolution', error)
1267
+ this.warnOnce(
1268
+ session,
1269
+ `custom-policy:${settings.profile}:${reason}`,
1270
+ 'context-compression kept original tool results because the Custom policy is not effective: %s',
1271
+ reason,
1272
+ )
1273
+ return undefined
1274
+ }
1275
+ }
1276
+
1277
+ private contextWindowForRequest(
1278
+ session: Session,
1279
+ ): number | undefined {
1280
+ const settings = this.activeSettings(session)
1281
+ // History linkage needs routed capacity for standard profiles, and the
1282
+ // Custom percentage policy needs it for context-percent documents. Off and
1283
+ // Native never link, and token-unit Custom stays manual.
1284
+ if (settings.profile === 'off' || settings.profile === 'native') return undefined
1285
+ if (settings.profile === 'custom' && settings.custom.unit !== 'context-percent') return undefined
1286
+ const config = session.requestHeader()?.config
1287
+ const routed = session.requestContext()
1288
+ if (config === undefined || config.provider.length === 0 || config.model.length === 0 || routed === undefined) {
1289
+ return undefined
1290
+ }
1291
+ if (routed.provider !== config.provider || routed.model !== config.model) {
1292
+ this.warnOnce(
1293
+ session,
1294
+ `custom-context-window-route:${config.provider}\0${config.model}`,
1295
+ 'context-compression kept the context-linked policy inactive because durable route capacity belongs to %s/%s, not %s/%s',
1296
+ routed.provider,
1297
+ routed.model,
1298
+ config.provider,
1299
+ config.model,
1300
+ )
1301
+ return undefined
1302
+ }
1303
+ if (!Number.isSafeInteger(routed.contextWindow) || routed.contextWindow === undefined || routed.contextWindow <= 0) {
1304
+ this.warnOnce(
1305
+ session,
1306
+ `custom-context-window-capacity:${config.provider}\0${config.model}`,
1307
+ 'context-compression kept the context-linked policy inactive because %s/%s has no positive durable context capacity',
1308
+ config.provider,
1309
+ config.model,
1310
+ )
1311
+ return undefined
1312
+ }
1313
+ return routed.contextWindow
1314
+ }
1315
+
1316
+ private runRequestBoundary(
1317
+ session: Session,
1318
+ turn: number,
1319
+ step: number,
1320
+ signal: AbortSignal,
1321
+ ): void {
1322
+ const contextWindowTokens = this.contextWindowForRequest(session)
1323
+ if (signal.aborted) return
1324
+ const policy = this.activePolicy(session, contextWindowTokens, 'fresh')
1325
+ if (policy === undefined) return
1326
+ const capacity = contextWindowTokens === undefined ? {} : { contextWindowTokens }
1327
+ this.pruneSession(session, { stage: 'fresh', freshTurn: turn, freshStep: step, ...capacity })
1328
+ if (policy.historyMode !== 'disabled' || policy.tailTrim?.enabled === true) {
1329
+ this.pruneSession(session, { stage: 'pressure', ...capacity })
1330
+ }
1331
+ }
1332
+
1333
+ /** Resolve historical-aging authority without accepting caller-supplied elevation. */
1334
+ private historyAllowed(session: Session, policy: CompressionPolicy, view: CompactionTokenView): boolean {
1335
+ switch (policy.historyMode) {
1336
+ case 'disabled':
1337
+ return false
1338
+ case 'routine':
1339
+ return true
1340
+ case 'capacity-pressure':
1341
+ return this.capacityPressureActive(session, view, policy)
1342
+ case 'adaptive':
1343
+ return false
1344
+ /* v8 ignore next -- closed-union exhaustiveness guard */
1345
+ default:
1346
+ return assertNever(policy.historyMode, 'history mode')
1347
+ }
1348
+ }
1349
+
1350
+ /**
1351
+ * Match the compaction-basic pressure gate using public durable data. The
1352
+ * frozen Auto Compact deadline `D = floor(A x 0.875)` replaces the legacy
1353
+ * fixed 0.7 ratio once the standard-profile linkage resolved; without
1354
+ * linkage the 0.7 ratio is the documented fallback and reproduces the
1355
+ * previous behavior.
1356
+ */
1357
+ private capacityPressureActive(
1358
+ session: Session,
1359
+ view: CompactionTokenView,
1360
+ policy: CompressionPolicy,
1361
+ ): boolean {
1362
+ const deadline = policy.microDeadlineTokens
1363
+ if (deadline !== undefined) return view.totalTokens >= deadline
1364
+ const header = session.requestHeader()?.config
1365
+ const routed = session.requestContext()
1366
+ const contextWindow = routed?.contextWindow
1367
+ if (header === undefined || routed === undefined
1368
+ || routed.provider !== header.provider
1369
+ || routed.model !== header.model
1370
+ || contextWindow === undefined
1371
+ || !Number.isSafeInteger(contextWindow)
1372
+ || contextWindow <= 0) return false
1373
+ return view.totalTokens >= Math.floor(contextWindow * CAPACITY_PRESSURE_RATIO)
1374
+ }
1375
+
1376
+ /** Emit one bounded, independently correlatable postflight cost diagnostic per completed attempt. */
1377
+ private logAdaptivePostflight(session: Session, usage: ObservedPromptUsage): void {
1378
+ const attemptId = String(usage.attemptId)
1379
+ if (this.state.postflightDiagnostics.get(session) === attemptId) return
1380
+ this.state.postflightDiagnostics.set(session, attemptId)
1381
+
1382
+ const key = usage.key
1383
+ let priceRecord: Readonly<Record<string, unknown>> | undefined
1384
+ let cost: ReturnType<typeof priceOfficialDeepSeekUsage> | { readonly kind: 'unpriced'; readonly reason: string }
1385
+ if (key === undefined) {
1386
+ cost = { kind: 'unpriced', reason: 'measurement key unavailable' }
1387
+ } else if (usage.responseModelId !== key.modelId) {
1388
+ cost = { kind: 'unpriced', reason: 'response model mismatch or unavailable' }
1389
+ } else if (usage.observedOutputTokens === undefined) {
1390
+ cost = { kind: 'unpriced', reason: 'output token count unavailable' }
1391
+ } else if (usage.cacheStatus !== 'complete'
1392
+ || usage.cacheReadTokens === undefined
1393
+ || usage.cacheMissTokens === undefined) {
1394
+ cost = { kind: 'unpriced', reason: 'complete cache split unavailable' }
1395
+ } else {
1396
+ const startedAt = new Date(usage.startedAtMs)
1397
+ const completedAt = new Date(usage.completedAtMs)
1398
+ const resolution = resolveOfficialDeepSeekPrice({
1399
+ provider: key.provider,
1400
+ baseUrlClass: key.baseUrlClass,
1401
+ apiRoute: key.apiRoute,
1402
+ modelId: key.modelId,
1403
+ currency: 'USD',
1404
+ at: startedAt,
1405
+ })
1406
+ if (resolution.kind === 'priced') {
1407
+ priceRecord = {
1408
+ catalogVersion: resolution.record.catalogVersion,
1409
+ checkedAt: resolution.record.checkedAt,
1410
+ sourceUrl: resolution.record.sourceUrl,
1411
+ currency: resolution.record.currency,
1412
+ modelId: resolution.record.modelId,
1413
+ apiRoute: resolution.record.apiRoute,
1414
+ startBand: resolution.record.band,
1415
+ }
1416
+ }
1417
+ cost = priceOfficialDeepSeekUsage({
1418
+ provider: key.provider,
1419
+ baseUrlClass: key.baseUrlClass,
1420
+ apiRoute: key.apiRoute,
1421
+ modelId: key.modelId,
1422
+ currency: 'USD',
1423
+ startedAt,
1424
+ completedAt,
1425
+ usage: {
1426
+ cacheReadTokens: usage.cacheReadTokens,
1427
+ cacheMissTokens: usage.cacheMissTokens,
1428
+ outputTokens: usage.observedOutputTokens,
1429
+ },
1430
+ })
1431
+ }
1432
+
1433
+ this.ctx.logger.debug(`context-compression adaptive postflight ${JSON.stringify({
1434
+ sessionId: String(session.id),
1435
+ providerRequestOrdinal: Number(usage.providerRequestOrdinal),
1436
+ attemptId,
1437
+ startedAtMs: usage.startedAtMs,
1438
+ completedAtMs: usage.completedAtMs,
1439
+ measurementKind: usage.measurement.kind,
1440
+ catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
1441
+ ...(priceRecord === undefined ? {} : { priceRecord }),
1442
+ usage: {
1443
+ promptTokens: usage.observedPromptTokens,
1444
+ ...(usage.observedOutputTokens === undefined ? {} : { outputTokens: usage.observedOutputTokens }),
1445
+ cacheStatus: usage.cacheStatus ?? 'unknown',
1446
+ ...(usage.cacheReadTokens === undefined ? {} : { cacheReadTokens: usage.cacheReadTokens }),
1447
+ ...(usage.cacheMissTokens === undefined ? {} : { cacheMissTokens: usage.cacheMissTokens }),
1448
+ },
1449
+ cost,
1450
+ })}`)
1451
+ }
1452
+
1453
+ /** Decide one already-planned History batch from adjacent request-level facts only. */
1454
+ private adaptiveHistoryAllowed(
1455
+ session: Session,
1456
+ view: CompactionTokenView,
1457
+ plans: readonly PlannedReplacement[],
1458
+ capacityPressure: boolean,
1459
+ ): boolean {
1460
+ const log = (
1461
+ allowHistory: boolean,
1462
+ reason: string,
1463
+ detail: Readonly<Record<string, unknown>> = {},
1464
+ ): boolean => {
1465
+ this.ctx.logger.debug(`context-compression adaptive ${JSON.stringify({
1466
+ sessionId: String(session.id),
1467
+ allowHistory,
1468
+ reason,
1469
+ catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
1470
+ ...detail,
1471
+ })}`)
1472
+ return allowHistory
1473
+ }
1474
+ const usage = view.lastCompletedUsage
1475
+ if (usage !== undefined) this.logAdaptivePostflight(session, usage)
1476
+ if (plans.length === 0) return false
1477
+ if (capacityPressure) return log(true, 'capacity-override')
1478
+
1479
+ const currentKey = view.latestEnvelopeKey
1480
+ if (usage === undefined) return log(false, 'usage-unavailable')
1481
+ if (usage.key === undefined || currentKey === undefined) {
1482
+ return log(false, 'measurement-key-unavailable')
1483
+ }
1484
+ if (!sameProviderMeasurementKey(usage.key, currentKey)) {
1485
+ return log(false, 'measurement-key-mismatch')
1486
+ }
1487
+ if (usage.responseModelId !== usage.key.modelId) {
1488
+ return log(false, 'response-model-mismatch-or-unavailable')
1489
+ }
1490
+ if (usage.cacheStatus !== 'complete'
1491
+ || usage.cacheReadTokens === undefined
1492
+ || usage.cacheMissTokens === undefined) {
1493
+ return log(false, 'cache-split-incomplete')
1494
+ }
1495
+
1496
+ const price = resolveOfficialDeepSeekPrice({
1497
+ provider: usage.key.provider,
1498
+ baseUrlClass: usage.key.baseUrlClass,
1499
+ apiRoute: usage.key.apiRoute,
1500
+ modelId: usage.key.modelId,
1501
+ currency: 'USD',
1502
+ at: new Date(),
1503
+ })
1504
+ if (price.kind === 'unpriced') return log(false, `adaptive-unknown-price:${price.reason}`)
1505
+
1506
+ const exactReclaimedTokens = plans.reduce(
1507
+ (sum, plan) => sum + plan.tokensBefore - plan.tokensAfter,
1508
+ 0,
1509
+ )
1510
+ const earliestChangedSeq = Math.min(...plans.map(plan => plan.candidate.seq))
1511
+ const bounds = deriveAdaptiveTokenBounds({
1512
+ exactReclaimedTokens,
1513
+ earliestChangedSeq,
1514
+ previousPromptTokens: usage.observedPromptTokens,
1515
+ expectedTokenizerRevision: usage.key.tokenizerRevision,
1516
+ previousRequestMeasurement: usage.measurement,
1517
+ measuredNodes: view.measuredNodes,
1518
+ })
1519
+ const decision = decideConservativeAdaptive({
1520
+ capacityPressure: false,
1521
+ bounds,
1522
+ inputCacheHitRate: price.record.inputCacheHit,
1523
+ inputCacheMissRate: price.record.inputCacheMiss,
1524
+ observedCacheReadTokens: usage.cacheReadTokens,
1525
+ })
1526
+ return log(decision.allowHistory, decision.reason, {
1527
+ priceBand: price.record.band,
1528
+ observedPromptTokens: usage.observedPromptTokens,
1529
+ observedCacheReadTokens: usage.cacheReadTokens,
1530
+ bounds,
1531
+ ...'minimumRemovalValue' in decision
1532
+ ? { minimumRemovalValue: decision.minimumRemovalValue }
1533
+ : {},
1534
+ ...'maximumCacheLossPenalty' in decision
1535
+ ? { maximumCacheLossPenalty: decision.maximumCacheLossPenalty }
1536
+ : {},
1537
+ })
1538
+ }
1539
+
1540
+ private decisions(session: Session): Set<number> {
1541
+ let decisions = this.state.firstExposure.get(session)
1542
+ if (decisions === undefined) {
1543
+ decisions = new Set()
1544
+ this.state.firstExposure.set(session, decisions)
1545
+ }
1546
+ return decisions
1547
+ }
1548
+
1549
+ /**
1550
+ * TokenPilot-style skipReduction: recovery tool output is permanently exempt
1551
+ * from every reduction pass so retrieved content can never enter a
1552
+ * compress-restore-oscillation loop. A call-name match covers the built-in
1553
+ * recovery tool; the per-session set admits future recovery paths.
1554
+ */
1555
+ private isRecoveryExempt(session: Session, candidate: SnapshotCandidate): boolean {
1556
+ if (candidate.call.name === RUNTIME_TOOL_NAMES.RETRIEVE) return true
1557
+ return this.state.recoveryExemptions.get(session)?.has(candidate.seq) ?? false
1558
+ }
1559
+
1560
+ /** Register a result seq as permanently exempt from further reduction. */
1561
+ private grantRecoveryExemption(session: Session, seq: number): void {
1562
+ let exemptions = this.state.recoveryExemptions.get(session)
1563
+ if (exemptions === undefined) {
1564
+ exemptions = new Set()
1565
+ this.state.recoveryExemptions.set(session, exemptions)
1566
+ }
1567
+ exemptions.add(seq)
1568
+ }
1569
+
1570
+ private decideFreshStep(
1571
+ session: Session,
1572
+ options: PruneSessionOptions,
1573
+ policy: CompressionPolicy,
1574
+ view: CompactionTokenView,
1575
+ ): PruneResult {
1576
+ if (options.freshTurn === undefined || options.freshStep === undefined) {
1577
+ this.auditComponent(session, policy, 'fresh', 'fresh',
1578
+ policy.freshEnabled ? 'skipped' : 'disabled',
1579
+ policy.freshEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
1580
+ this.auditComponent(session, policy, 'aggregate', 'fresh',
1581
+ policy.aggregateEnabled ? 'skipped' : 'disabled',
1582
+ policy.aggregateEnabled ? 'missing-completed-step-coordinates' : 'profile-policy')
1583
+ return emptyResult()
1584
+ }
1585
+ const decisions = this.decisions(session)
1586
+ const snapshot = this.snapshot(session, view)
1587
+ const candidates = snapshot.filter(candidate =>
1588
+ typeof candidate.event.surfaceOp !== 'object'
1589
+ && candidate.event.data.turn === options.freshTurn
1590
+ && candidate.event.data.step === options.freshStep
1591
+ && !decisions.has(candidate.seq))
1592
+ if (candidates.length === 0) {
1593
+ this.auditComponent(session, policy, 'fresh', 'fresh',
1594
+ policy.freshEnabled ? 'skipped' : 'disabled',
1595
+ policy.freshEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
1596
+ this.auditComponent(session, policy, 'aggregate', 'fresh',
1597
+ policy.aggregateEnabled ? 'skipped' : 'disabled',
1598
+ policy.aggregateEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
1599
+ return emptyResult()
1600
+ }
1601
+ // 节省统计(负节省配对):新全文工具结果按 (session,seq) 一次性过账——
1602
+ // 命中"此前压缩过的原文哈希"即记抵消。挂在压力门控之前:全文重读无论
1603
+ // 本轮是否再次压缩,都使原声称的节省不再成立(先骨架后全文 = 负节省)。
1604
+ const ledger = getSavingsLedger()
1605
+ const sid = String(session.id)
1606
+ for (const candidate of candidates) {
1607
+ const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
1608
+ if (text === undefined) continue
1609
+ ledger.noteFullText({
1610
+ sessionId: sid,
1611
+ seq: candidate.seq,
1612
+ text,
1613
+ measure: () =>
1614
+ candidate.count.kind === 'exact-tokenizer' && typeof candidate.count.tokens === 'number'
1615
+ ? { tokens: candidate.count.tokens, basis: 'exact-tokenizer' }
1616
+ : { tokens: Math.ceil(candidate.characterPressure / 4), basis: 'characters' },
1617
+ })
1618
+ }
1619
+
1620
+ const plans = new Map<number, PlannedReplacement>()
1621
+ let freshPlanned = 0
1622
+ const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
1623
+ // Token-basis max, mirroring freshBelowTrigger: exact tokenizer where
1624
+ // available, else the 4.0 char estimate. Drives the 'at-or-below-trigger'
1625
+ // audit reason on the same basis the fresh gate uses.
1626
+ const maxCandidateTokens = candidates.length === 0
1627
+ ? undefined
1628
+ : Math.max(...candidates.map(candidate => candidate.count.kind === 'exact-tokenizer'
1629
+ ? candidate.count.tokens
1630
+ : charsToTokens(candidate.characterPressure)))
1631
+ if (policy.freshEnabled) {
1632
+ if (candidates.some(candidate => candidate.call.name !== RUNTIME_TOOL_NAMES.RETRIEVE
1633
+ && candidate.count.kind !== 'exact-tokenizer')) {
1634
+ this.warnExactUnavailable(session, view, 'fresh')
1635
+ }
1636
+ for (const candidate of candidates) {
1637
+ if (this.isRecoveryExempt(session, candidate)) continue
1638
+ if (dedupeEnabled) {
1639
+ const dedupePlan = this.planDedupe(candidate, session, policy, view)
1640
+ if (dedupePlan !== null) {
1641
+ plans.set(candidate.seq, dedupePlan)
1642
+ continue
1643
+ }
1644
+ }
1645
+ const plan = this.planFresh(candidate, session, policy, view)
1646
+ if (plan !== null) {
1647
+ plans.set(candidate.seq, plan)
1648
+ freshPlanned += 1
1649
+ }
1650
+ }
1651
+ }
1652
+ let aggregateInputChars: number | undefined
1653
+ let aggregatePlanned = 0
1654
+ if (policy.aggregateEnabled) {
1655
+ let total = candidates.reduce((sum, candidate) => sum
1656
+ + (plans.get(candidate.seq)?.charsAfter ?? candidate.characterPressure), 0)
1657
+ aggregateInputChars = total
1658
+ if (total > charsForTokens(policy.aggregateTriggerTokens)) {
1659
+ const remaining = candidates
1660
+ .filter(candidate => !this.isRecoveryExempt(session, candidate))
1661
+ .sort((a, b) => Number(isError(a)) - Number(isError(b))
1662
+ || (plans.get(b.seq)?.charsAfter ?? b.characterPressure)
1663
+ - (plans.get(a.seq)?.charsAfter ?? a.characterPressure))
1664
+ for (const candidate of remaining) {
1665
+ const previous = plans.get(candidate.seq)
1666
+ const plan = this.planAggregate(candidate, session, view)
1667
+ const previousChars = previous?.charsAfter ?? candidate.characterPressure
1668
+ if (plan === null || plan.charsAfter >= previousChars) continue
1669
+ plans.set(candidate.seq, plan)
1670
+ aggregatePlanned += 1
1671
+ total -= previousChars - plan.charsAfter
1672
+ if (total <= charsForTokens(policy.aggregateTargetTokens)) break
1673
+ }
1674
+ if (total > charsForTokens(policy.aggregateTargetTokens)) {
1675
+ this.ctx.logger.warn(
1676
+ 'context-compression fresh aggregate residual: %d characters exceed target %d',
1677
+ total,
1678
+ charsForTokens(policy.aggregateTargetTokens),
1679
+ )
1680
+ }
1681
+ }
1682
+ }
1683
+
1684
+ const freshCandidates = candidates
1685
+ .map(candidate => plans.get(candidate.seq))
1686
+ .filter((plan): plan is PlannedReplacement => plan !== undefined)
1687
+ const landed = this.landAll(session, this.adviseReplacements(session, policy, freshCandidates, 'fresh'))
1688
+ const freshLanded = landed.some(entry => entry.stage === 'fresh'
1689
+ && plans.get(entry.originalSeq)?.component === 'fresh')
1690
+ const aggregateLanded = landed.some(entry => entry.stage === 'fresh'
1691
+ && plans.get(entry.originalSeq)?.component === 'aggregate')
1692
+ if (!freshLanded) {
1693
+ this.auditComponent(session, policy, 'fresh', 'fresh',
1694
+ policy.freshEnabled ? 'skipped' : 'disabled',
1695
+ !policy.freshEnabled ? 'profile-policy'
1696
+ : (maxCandidateTokens ?? 0) <= policy.freshTriggerTokens ? 'at-or-below-trigger'
1697
+ : freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
1698
+ : freshPlanned === 0 ? 'no-valid-reduction'
1699
+ : 'recovery-tool-unavailable', {
1700
+ measurementKind: 'characters',
1701
+ ...(maxCandidateTokens === undefined ? {} : { currentTokens: maxCandidateTokens }),
1702
+ triggerTokens: policy.freshTriggerTokens,
1703
+ targetTokens: policy.freshTargetTokens,
1704
+ })
1705
+ }
1706
+ if (!aggregateLanded) {
1707
+ this.auditComponent(session, policy, 'aggregate', 'fresh',
1708
+ policy.aggregateEnabled ? 'skipped' : 'disabled',
1709
+ !policy.aggregateEnabled ? 'profile-policy'
1710
+ : (aggregateInputChars ?? 0) <= charsForTokens(policy.aggregateTriggerTokens) ? 'at-or-below-trigger'
1711
+ : aggregatePlanned === 0 ? 'no-valid-reduction'
1712
+ : 'recovery-tool-unavailable', {
1713
+ measurementKind: 'characters',
1714
+ ...(aggregateInputChars === undefined ? {} : { currentTokens: charsToTokens(aggregateInputChars) }),
1715
+ triggerTokens: policy.aggregateTriggerTokens,
1716
+ targetTokens: policy.aggregateTargetTokens,
1717
+ })
1718
+ }
1719
+ for (const candidate of candidates) decisions.add(candidate.seq)
1720
+ return summarize(landed)
1721
+ }
1722
+
1723
+ private snapshot(session: Session, view: CompactionTokenView): SnapshotCandidate[] {
1724
+ const events = sessionEvents(session)
1725
+ const calls = new Map<string, ToolCallInfo>()
1726
+ for (const event of events) {
1727
+ if (event.type === 'tool/call') {
1728
+ calls.set(event.data.callId, { name: event.data.name, arguments: event.data.arguments })
1729
+ }
1730
+ }
1731
+ const candidates: SnapshotCandidate[] = []
1732
+ const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
1733
+ const projectionPrices = new Map(view.nodes.map(node => [node.seq, node.tokens]))
1734
+ for (const seq of [...session.surface.nodes]) {
1735
+ const event = eventBySeq(events, seq)
1736
+ if (event?.type !== 'tool/result') continue
1737
+ const shadowedHeuristicTokenCount = projectionPrices.get(seq)
1738
+ if (shadowedHeuristicTokenCount === undefined) {
1739
+ throw new Error(`surface node ${String(seq)} is absent from the atomic legacy projection`)
1740
+ }
1741
+ // Generation-gated triple view: block set / error flag / call id move
1742
+ // together across the 0.1.x envelope and the flat 0.2.0 message.
1743
+ const resultView = viewToolResult(event.data.message)
1744
+ const content = resultView.blocks as ContentBlock[]
1745
+ candidates.push({
1746
+ seq,
1747
+ event,
1748
+ call: calls.get(resultView.callId ?? '') ?? { name: 'unknown', arguments: '{}' },
1749
+ count: onlyTextBlocks(content) === null
1750
+ ? unavailableCount(`surface node ${String(seq)} contains unsupported rich tool-result content`)
1751
+ : measured.get(seq) ?? unavailableCount(`surface node ${String(seq)} is absent from the atomic token view`),
1752
+ shadowedHeuristicTokenCount,
1753
+ characterPressure: pressureCost(content),
1754
+ })
1755
+ }
1756
+ return candidates
1757
+ }
1758
+
1759
+ private planNative(
1760
+ candidate: SnapshotCandidate,
1761
+ session: Session,
1762
+ stage: PruneStage,
1763
+ policy: CompressionPolicy,
1764
+ view: CompactionTokenView,
1765
+ ): PlannedReplacement | null {
1766
+ if (this.isRecoveryExempt(session, candidate)) return null
1767
+ if (candidate.characterPressure <= charsForTokens(policy.nativeTriggerTokens)) return null
1768
+ const resultContent = viewToolResult(candidate.event.data.message).blocks as ContentBlock[]
1769
+ if (onlyTextBlocks(resultContent) === null) return null
1770
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1771
+ // R9b site: the marker's retrieve hint starts at the event line right
1772
+ // after the retained head, computed inside nativePruneContent.
1773
+ const marker = (startLine: number): string => recoveryMarker(sourceRefFn(session, sourceSeq), 'tool result middle pruned', startLine)
1774
+ let head = this.state.config.headChars
1775
+ let tail = this.state.config.tailChars
1776
+ for (let attempt = 0; attempt < 10; attempt += 1) {
1777
+ const threshold = head + codePointLength(marker(1)) + tail
1778
+ const content = nativePruneContent(resultContent, threshold, head, tail, marker)
1779
+ if (content !== null) {
1780
+ const plan = this.plan(
1781
+ candidate,
1782
+ content,
1783
+ sourceSeq,
1784
+ 'native-head-tail',
1785
+ stage,
1786
+ 'native-tool-result',
1787
+ undefined,
1788
+ view,
1789
+ )
1790
+ if (plan !== null && plan.tokensAfter <= policy.nativeTargetTokens) return plan
1791
+ }
1792
+ if (head === 0 && tail === 0) break
1793
+ head = Math.floor(head / 2)
1794
+ tail = Math.floor(tail / 2)
1795
+ }
1796
+ return this.planAggregate(
1797
+ candidate,
1798
+ session,
1799
+ view,
1800
+ 'native-whole-result',
1801
+ stage,
1802
+ policy.nativeTargetTokens,
1803
+ 'native-tool-result',
1804
+ )
1805
+ }
1806
+
1807
+ /**
1808
+ * TokenPilot-inspired A1: replace a byte-identical repeat of an earlier
1809
+ * oversized tool result with a pointer to its first occurrence. The first
1810
+ * occurrence's hash is always recorded so later repeats can point at the
1811
+ * append-only original event even after the surface copy is reduced.
1812
+ */
1813
+ private planDedupe(
1814
+ candidate: SnapshotCandidate,
1815
+ session: Session,
1816
+ policy: CompressionPolicy,
1817
+ view: CompactionTokenView,
1818
+ ): PlannedReplacement | null {
1819
+ if (typeof candidate.event.surfaceOp === 'object') return null
1820
+ const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
1821
+ if (text === undefined) return null
1822
+ if (freshBelowTrigger(candidate, policy)) return null
1823
+ let table = this.state.dedupeTables.get(session)
1824
+ if (table === undefined) {
1825
+ table = new DedupeTable()
1826
+ this.state.dedupeTables.set(session, table)
1827
+ }
1828
+ const hash = dedupeHash(text, 'trim-eol')
1829
+ const entry = table.get(hash)
1830
+ if (entry !== undefined && entry.seq !== candidate.seq) {
1831
+ const placeholder = dedupePlaceholder(entry, codePointLength(text))
1832
+ const plan = this.plan(
1833
+ candidate,
1834
+ [{ type: 'text', text: placeholder }],
1835
+ entry.seq,
1836
+ 'dedupe-pointer',
1837
+ 'fresh',
1838
+ 'fresh',
1839
+ undefined,
1840
+ view,
1841
+ { noNetSavingsGuard: true },
1842
+ )
1843
+ if (plan !== null) return plan
1844
+ return null
1845
+ }
1846
+ if (entry === undefined) {
1847
+ table.record(hash, {
1848
+ seq: candidate.seq,
1849
+ sourceRef: sourceRefFn(session, candidate.seq),
1850
+ toolName: candidate.call.name,
1851
+ originalChars: codePointLength(text),
1852
+ })
1853
+ }
1854
+ return null
1855
+ }
1856
+
1857
+ private planFresh(
1858
+ candidate: SnapshotCandidate,
1859
+ session: Session,
1860
+ policy: CompressionPolicy,
1861
+ view: CompactionTokenView,
1862
+ ): PlannedReplacement | null {
1863
+ // A replace event already reflects one frozen first-exposure decision. The
1864
+ // pre-step coordinate filter prevents previously-kept originals from ever
1865
+ // being reconsidered after their first request.
1866
+ if (typeof candidate.event.surfaceOp === 'object') return null
1867
+ const resultView = viewToolResult(candidate.event.data.message)
1868
+ if (freshBelowTrigger(candidate, policy)) return null
1869
+ const sourceSeq = candidate.seq
1870
+ const sourceRef = sourceRefFn(session, sourceSeq)
1871
+ const textBlock = onlyTextBlock(resultView.blocks as ContentBlock[])
1872
+ if (textBlock !== null) {
1873
+ let budgetChars = Math.max(1, Math.floor(codePointLength(textBlock.text) * 0.75))
1874
+ const codeSkeleton = this.activeSettings(session).codeSkeleton.enabled
1875
+ for (let attempt = 0; attempt < 10; attempt += 1) {
1876
+ const output = reduceFreshToolResult({
1877
+ toolName: candidate.call.name,
1878
+ argumentsText: candidate.call.arguments,
1879
+ text: textBlock.text,
1880
+ budgetChars,
1881
+ sourceRef,
1882
+ isError: resultView.isError || candidate.event.data.error !== undefined,
1883
+ codeSkeleton,
1884
+ })
1885
+ if (output !== null) {
1886
+ const plan = this.plan(
1887
+ candidate,
1888
+ [{ ...textBlock, text: output.text }],
1889
+ sourceSeq,
1890
+ output.reducer,
1891
+ 'fresh',
1892
+ 'fresh',
1893
+ undefined,
1894
+ view,
1895
+ {
1896
+ noNetSavingsGuard: policy.presetOptions?.noNetSavingsGuard === true,
1897
+ ...(output.elidedLines === undefined ? {} : { elidedLines: output.elidedLines }),
1898
+ },
1899
+ )
1900
+ if (plan !== null && plan.charsAfter <= charsForTokens(policy.freshTargetTokens)) return plan
1901
+ }
1902
+ if (budgetChars === 1) break
1903
+ budgetChars = Math.max(1, Math.floor(budgetChars / 2))
1904
+ }
1905
+ }
1906
+
1907
+ return this.planAggregate(
1908
+ candidate,
1909
+ session,
1910
+ view,
1911
+ 'fresh-whole-result',
1912
+ 'fresh',
1913
+ policy.freshTargetTokens,
1914
+ 'fresh',
1915
+ )
1916
+ }
1917
+
1918
+ private planAggregate(
1919
+ candidate: SnapshotCandidate,
1920
+ session: Session,
1921
+ view: CompactionTokenView,
1922
+ reducer = 'fresh-step-aggregate',
1923
+ stage: PruneStage = 'fresh',
1924
+ targetTokens?: number,
1925
+ component: CompressionAuditComponent = 'aggregate',
1926
+ historyMode?: HistoryMode,
1927
+ ): PlannedReplacement | null {
1928
+ if (isError(candidate)) {
1929
+ return this.planErrorEvidence(
1930
+ candidate,
1931
+ session,
1932
+ view,
1933
+ stage,
1934
+ targetTokens,
1935
+ component,
1936
+ historyMode,
1937
+ )
1938
+ }
1939
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1940
+ const sourceRef = sourceRefFn(session, sourceSeq)
1941
+ // The placeholder below is a single text block, so a rich tool result (for
1942
+ // example one carrying an image) must never reach it. The character basis
1943
+ // no longer inherits the exact-tokenizer precondition that used to reject
1944
+ // this path implicitly, so the guard has to be explicit.
1945
+ const redactedContent = viewToolResult(candidate.event.data.message).blocks as ContentBlock[]
1946
+ if (onlyTextBlocks(redactedContent) === null) return null
1947
+ const text = [
1948
+ '[Tool result reduced to satisfy the completed-step aggregate budget]',
1949
+ `tool: ${candidate.call.name}`,
1950
+ `source: ${sourceRef}`,
1951
+ `Retrieve a narrow slice via ${RUNTIME_TOOL_NAMES.RETRIEVE} if needed.`,
1952
+ ].join('\n')
1953
+ const plan = this.plan(
1954
+ candidate,
1955
+ [{ type: 'text', text }],
1956
+ sourceSeq,
1957
+ reducer,
1958
+ stage,
1959
+ component,
1960
+ historyMode,
1961
+ view,
1962
+ )
1963
+ return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
1964
+ ? plan
1965
+ : null
1966
+ }
1967
+
1968
+ /** Preserve bounded diagnostic evidence whenever an all-text error is reduced. */
1969
+ private planErrorEvidence(
1970
+ candidate: SnapshotCandidate,
1971
+ session: Session,
1972
+ view: CompactionTokenView,
1973
+ stage: PruneStage,
1974
+ targetTokens?: number,
1975
+ component: CompressionAuditComponent = 'aggregate',
1976
+ historyMode?: HistoryMode,
1977
+ ): PlannedReplacement | null {
1978
+ if (!isError(candidate)) return null
1979
+ const blocks = onlyTextBlocks(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
1980
+ if (blocks === null) return null
1981
+ const text = blocks.map(block => block.text).join('\n')
1982
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
1983
+ const sourceRef = sourceRefFn(session, sourceSeq)
1984
+ const output = historicalPlaceholder({
1985
+ toolName: candidate.call.name,
1986
+ sourceRef,
1987
+ charsBefore: codePointLength(text),
1988
+ isError: true,
1989
+ text,
1990
+ compact: false,
1991
+ })
1992
+ const input = {
1993
+ toolName: candidate.call.name,
1994
+ argumentsText: candidate.call.arguments,
1995
+ text,
1996
+ budgetChars: 1_200,
1997
+ sourceRef,
1998
+ isError: true,
1999
+ }
2000
+ if (!verifyReduction(input, output)) return null
2001
+ const plan = this.plan(
2002
+ candidate,
2003
+ [{ type: 'text', text: output.text }],
2004
+ sourceSeq,
2005
+ 'error-evidence-placeholder',
2006
+ stage,
2007
+ component,
2008
+ historyMode,
2009
+ view,
2010
+ )
2011
+ return plan !== null && (targetTokens === undefined || plan.tokensAfter <= targetTokens)
2012
+ ? plan
2013
+ : null
2014
+ }
2015
+
2016
+ private planHistoricalAging(
2017
+ session: Session,
2018
+ policy: CompressionPolicy,
2019
+ view: CompactionTokenView,
2020
+ ): HistoryPlanOutcome {
2021
+ const candidates = this.snapshot(session, view)
2022
+ const events = sessionEvents(session)
2023
+ const chars = candidates.map(candidate => candidate.characterPressure)
2024
+ const total = chars.reduce((sum, charsOfNode) => sum + charsOfNode, 0)
2025
+ const trigger = charsForTokens(policy.historyTriggerTokens)
2026
+ // Full-request last chance: ordinary prose, images, prompts, or schemas can
2027
+ // push the complete request past the Auto Compact deadline before the tool
2028
+ // results alone cross the profile trigger.
2029
+ const deadline = policy.microDeadlineTokens
2030
+ const lastChance = deadline !== undefined && view.totalTokens >= deadline
2031
+ if (total <= trigger && !lastChance) return { kind: 'below-profile-trigger' }
2032
+
2033
+ const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
2034
+ const isUnsafe = (candidate: SnapshotCandidate): boolean => {
2035
+ if (this.isRecoveryExempt(session, candidate)) return true
2036
+ const block = onlyTextBlock(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
2037
+ // Fold-once: an already-folded intent block is never re-candidated.
2038
+ if (block?.text.includes(INTENT_FOLD_MARKER) === true) return true
2039
+ return block?.text.includes('[Old tool result content cleared from active context]') === true
2040
+ }
2041
+ // Distinguish "nothing safe to touch" (recovery tool output or already
2042
+ // cleared) from "everything left is inside the protected working set":
2043
+ // both skip, but they are different operational facts.
2044
+ const safe = candidates.filter(candidate => !isUnsafe(candidate))
2045
+ const eligible: SnapshotCandidate[] = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
2046
+ if (eligible.length === 0) {
2047
+ return safe.length === 0
2048
+ ? { kind: 'no-safe-candidates' }
2049
+ : { kind: 'protected-working-set' }
2050
+ }
2051
+ const planned: PlannedReplacement[] = []
2052
+ let reclaim = 0
2053
+ // Turn-tail intent summary (task_2.5): a fold staged by a previous turn's
2054
+ // postflight lands FIRST, through the same plan pipeline as every other
2055
+ // reducer; its reclaim counts toward the batch target and its seqs are
2056
+ // removed from the ordinary loop (fold-once).
2057
+ const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible)
2058
+ if (intentApplied !== undefined) {
2059
+ planned.push(...intentApplied.plans)
2060
+ reclaim += intentApplied.reclaim
2061
+ this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs)
2062
+ this.state.pendingIntentFolds.delete(session)
2063
+ this.state.intentBaselines.set(session, view.totalTokens)
2064
+ recordIntentFold(String(session.id), {
2065
+ turn: intentApplied.turn,
2066
+ startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
2067
+ endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
2068
+ liveTokensBefore: view.totalTokens,
2069
+ at: Date.now(),
2070
+ })
2071
+ emitCompressionAudit(this.ctx.logger, {
2072
+ schemaVersion: 1,
2073
+ kind: 'intent-summary-outcome',
2074
+ sessionId: String(session.id),
2075
+ ok: true,
2076
+ reason: 'landed',
2077
+ foldedCount: intentApplied.plans.length,
2078
+ ...(intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {}),
2079
+ summaryCallChars: intentApplied.summaryCallChars,
2080
+ })
2081
+ for (let index = eligible.length - 1; index >= 0; index -= 1) {
2082
+ if (intentApplied.foldedSeqs.has(eligible[index]!.seq)) eligible.splice(index, 1)
2083
+ }
2084
+ }
2085
+ // Linked batches must reach the deadline target; unlinked batches keep
2086
+ // the traditional minimum-reclaim commit threshold. All arithmetic runs on
2087
+ // the character basis: token-named thresholds enter via charsForTokens.
2088
+ const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens)
2089
+ const microTarget = deadline === undefined ? undefined : Math.max(0, charsForTokens(deadline) - minReclaimChars)
2090
+ const required = Math.max(
2091
+ minReclaimChars,
2092
+ total - trigger,
2093
+ ...(microTarget === undefined ? [] : [charsForTokens(view.totalTokens) - microTarget]),
2094
+ )
2095
+ const batchTarget = microTarget === undefined
2096
+ ? minReclaimChars
2097
+ : required
2098
+ for (const candidate of eligible) {
2099
+ const resultView = viewToolResult(candidate.event.data.message)
2100
+ const block = onlyTextBlock(resultView.blocks as ContentBlock[])
2101
+ // TokenPilot-inspired R2: a read output whose file was later mutated is
2102
+ // superseded — its text can no longer match the file — so it takes the
2103
+ // small whole-result placeholder before the ordinary reducer runs.
2104
+ if (policy.presetOptions?.readState === true && block !== null) {
2105
+ const readPath = toolCallPath(candidate.call.arguments)
2106
+ const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true
2107
+ if (readPath !== undefined
2108
+ && (isSupersededRead(events, candidate.seq, readPath) || estimatorExpired)) {
2109
+ const plan = this.planAggregate(
2110
+ candidate,
2111
+ session,
2112
+ view,
2113
+ 'superseded-read-whole-result',
2114
+ 'pressure',
2115
+ undefined,
2116
+ 'history',
2117
+ policy.historyMode,
2118
+ )
2119
+ if (plan === null) continue
2120
+ planned.push(plan)
2121
+ reclaim += plan.charsBefore - plan.charsAfter
2122
+ if (reclaim >= required) break
2123
+ continue
2124
+ }
2125
+ }
2126
+ const sourceSeq = rootToolResultSeq(session, candidate.seq)
2127
+ if (block === null) {
2128
+ const plan = this.planAggregate(
2129
+ candidate,
2130
+ session,
2131
+ view,
2132
+ 'historical-rich-whole-result',
2133
+ 'pressure',
2134
+ undefined,
2135
+ 'history',
2136
+ policy.historyMode,
2137
+ )
2138
+ if (plan === null) continue
2139
+ planned.push(plan)
2140
+ reclaim += plan.charsBefore - plan.charsAfter
2141
+ if (reclaim >= required) break
2142
+ continue
2143
+ }
2144
+ const output = historicalPlaceholder({
2145
+ toolName: candidate.call.name,
2146
+ sourceRef: sourceRefFn(session, sourceSeq),
2147
+ charsBefore: codePointLength(block.text),
2148
+ isError: resultView.isError || candidate.event.data.error !== undefined,
2149
+ text: block.text,
2150
+ compact: false,
2151
+ })
2152
+ const verifyInput = {
2153
+ toolName: candidate.call.name,
2154
+ argumentsText: candidate.call.arguments,
2155
+ text: block.text,
2156
+ budgetChars: 1_200,
2157
+ sourceRef: sourceRefFn(session, sourceSeq),
2158
+ isError: resultView.isError || candidate.event.data.error !== undefined,
2159
+ }
2160
+ if (!verifyReduction(verifyInput, output)) continue
2161
+ // TokenPilot-inspired R3: when read-state semantics are on, append an
2162
+ // error/warn/info census of the omitted lines so the model keeps
2163
+ // meta-knowledge about what was dropped.
2164
+ let replacementText = output.text
2165
+ if (policy.presetOptions?.readState === true) {
2166
+ const omitted = countOmittedLines(block.text, output.text)
2167
+ const census = omitted === undefined ? undefined : clusterOmittedLines(block.text, omitted)
2168
+ if (census !== undefined) replacementText = `${output.text}
2169
+ [... ${census} ...]`
2170
+ }
2171
+ const plan = this.plan(
2172
+ candidate,
2173
+ [{ ...block, text: replacementText }],
2174
+ sourceSeq,
2175
+ output.reducer,
2176
+ 'pressure',
2177
+ 'history',
2178
+ policy.historyMode,
2179
+ view,
2180
+ { ...(output.elidedLines === undefined ? {} : { elidedLines: output.elidedLines }) },
2181
+ )
2182
+ if (plan === null) continue
2183
+ planned.push(plan)
2184
+ reclaim += plan.charsBefore - plan.charsAfter
2185
+ if (reclaim >= required) break
2186
+ }
2187
+ // Linked batches must reach the deadline target; unlinked batches keep
2188
+ // the traditional minimum-reclaim commit threshold.
2189
+ if (reclaim >= batchTarget && planned.length > 0) return historyOutcome(planned)
2190
+ return lastChance
2191
+ ? { kind: 'cannot-reach-deadline-target', reclaim, required }
2192
+ : { kind: 'insufficient-reclaim', reclaim, required }
2193
+ }
2194
+
2195
+ private protectedHistoryResultSeqs(
2196
+ session: Session,
2197
+ policy: CompressionPolicy,
2198
+ view: CompactionTokenView,
2199
+ ): Set<number> {
2200
+ const candidates = this.snapshot(session, view)
2201
+ return this.protectedHistoryCandidateSeqs(candidates, policy)
2202
+ }
2203
+
2204
+ /** Select the newest completed tool calls and token tail for History-derived stages. */
2205
+ private protectedHistoryCandidateSeqs(
2206
+ candidates: readonly SnapshotCandidate[],
2207
+ policy: CompressionPolicy,
2208
+ ): Set<number> {
2209
+ const protectedSeqs = new Set<number>()
2210
+ for (let index = candidates.length - 1;
2211
+ index >= 0 && candidates.length - index <= policy.historyKeepRecentToolCalls;
2212
+ index--) {
2213
+ const candidate = candidates[index]
2214
+ if (candidate !== undefined) protectedSeqs.add(candidate.seq)
2215
+ }
2216
+ let recentChars = 0
2217
+ for (let index = candidates.length - 1;
2218
+ index >= 0 && recentChars < charsForTokens(policy.historyKeepRecentTokens);
2219
+ index--) {
2220
+ const candidate = candidates[index]
2221
+ if (candidate === undefined) continue
2222
+ protectedSeqs.add(candidate.seq)
2223
+ recentChars += candidate.characterPressure
2224
+ }
2225
+ return protectedSeqs
2226
+ }
2227
+
2228
+ /** Atomically replace at most one oldest safe completed tool-call group. */
2229
+ private landOldestTailTrimGroup(
2230
+ session: Session,
2231
+ policy: CompressionPolicy,
2232
+ view: CompactionTokenView,
2233
+ ): void {
2234
+ const tailTrim = policy.tailTrim
2235
+ if (tailTrim?.enabled !== true) return
2236
+ const events = sessionEvents(session)
2237
+ if (view.currentSurfaceChars <= charsForTokens(tailTrim.triggerTokens)) {
2238
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2239
+ 'at-or-below-trigger', {
2240
+ measurementKind: 'characters',
2241
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2242
+ triggerTokens: tailTrim.triggerTokens,
2243
+ })
2244
+ return
2245
+ }
2246
+ const surfaceCount = view.currentSurface
2247
+ const exactSurface = surfaceCount.kind === 'exact-tokenizer' ? surfaceCount : undefined
2248
+ if (!this.hasRecoveryTool(session)) {
2249
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2250
+ 'recovery-tool-unavailable', {
2251
+ measurementKind: 'characters',
2252
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2253
+ triggerTokens: tailTrim.triggerTokens,
2254
+ })
2255
+ return
2256
+ }
2257
+ if (!hasOpenTurn(session)) {
2258
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2259
+ 'no-open-turn', {
2260
+ measurementKind: 'characters',
2261
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2262
+ triggerTokens: tailTrim.triggerTokens,
2263
+ })
2264
+ return
2265
+ }
2266
+ const protectedResults = this.protectedHistoryResultSeqs(session, policy, view)
2267
+ const measured = new Map(view.measuredNodes.map(node => [node.seq, node.count]))
2268
+ const nodeChars = new Map(view.measuredNodes.map(node => [node.seq, node.characterPressure]))
2269
+ const heuristic = new Map(view.nodes.map(node => [node.seq, node.tokens]))
2270
+ const completedTurns = new Set<number>()
2271
+ const completedSteps = new Set<string>()
2272
+ for (const event of events) {
2273
+ if (event.type === 'turn/end') completedTurns.add(event.data.turn)
2274
+ else if (event.type === 'step/end') completedSteps.add(`${String(event.data.turn)}:${String(event.data.step)}`)
2275
+ }
2276
+ const firstCompletedSurfaceTurn = session.surface.nodes
2277
+ .map(seq => eventBySeq(events, seq))
2278
+ .filter((event): event is SessionEvent<'assistant/message'> | SessionEvent<'tool/result'> =>
2279
+ (event?.type === 'assistant/message' || event?.type === 'tool/result')
2280
+ && completedTurns.has(event.data.turn))
2281
+ .reduce<number | undefined>(
2282
+ (first, event) => first === undefined ? event.data.turn : Math.min(first, event.data.turn),
2283
+ undefined,
2284
+ )
2285
+ const nodes = [...session.surface.nodes]
2286
+ for (let index = 0; index < nodes.length; index++) {
2287
+ const assistantSeq = nodes[index]
2288
+ if (assistantSeq === undefined) continue
2289
+ const assistant = eventBySeq(events, assistantSeq)
2290
+ if (assistant?.type !== 'assistant/message'
2291
+ || assistant.data.interrupted === true
2292
+ || assistant.data.message.content.length === 0
2293
+ || assistant.data.message.content.some(block => block.type !== 'tool-call')
2294
+ || assistant.data.turn === firstCompletedSurfaceTurn
2295
+ || !completedTurns.has(assistant.data.turn)
2296
+ || !completedSteps.has(`${String(assistant.data.turn)}:${String(assistant.data.step)}`)) continue
2297
+ const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
2298
+ if (calls.some(call => call.name === RUNTIME_TOOL_NAMES.RETRIEVE)) continue
2299
+ const callIds = calls.map(call => String(call.id))
2300
+ if (new Set(callIds).size !== callIds.length) continue
2301
+ const resultSeqs = nodes.slice(index + 1, index + 1 + calls.length)
2302
+ if (resultSeqs.length !== calls.length || resultSeqs.some(seq => protectedResults.has(seq))) continue
2303
+ const results = resultSeqs.map(seq => events[seq])
2304
+ // One generation-gated triple view per result message, shared by the
2305
+ // safety gate below and the call-id pairing.
2306
+ const resultViews = results.map(event =>
2307
+ event?.type === 'tool/result' ? viewToolResult(event.data.message) : undefined)
2308
+ if (results.some((event, resultIndex): boolean => {
2309
+ const view = resultViews[resultIndex]
2310
+ if (event?.type !== 'tool/result' || view === undefined
2311
+ || event.data.turn !== assistant.data.turn || event.data.step !== assistant.data.step
2312
+ || event.data.error !== undefined) return true
2313
+ if (view.isError) return true
2314
+ // Images and other rich inner blocks stay fail-open: a TailTrim stub
2315
+ // would silently delete them from the active context.
2316
+ return (view.blocks as ContentBlock[]).some((contentBlock: ContentBlock) => contentBlock.type !== 'text')
2317
+ })) continue
2318
+ const next = events[nodes[index + 1 + calls.length] ?? -1]
2319
+ if (next?.type === 'tool/result'
2320
+ && next.data.turn === assistant.data.turn
2321
+ && next.data.step === assistant.data.step) continue
2322
+ const resultIds = resultViews.map(view => view === undefined ? '' : String(view.callId))
2323
+ if (new Set(resultIds).size !== resultIds.length
2324
+ || resultIds.some((id, resultIndex) => id !== callIds[resultIndex])) continue
2325
+ const shadowedSeqs = [assistantSeq, ...resultSeqs]
2326
+ const roots = shadowedSeqs.map(seq => this.uniqueAppendRoot(session, seq))
2327
+ if (roots.some(root => root === null)) continue
2328
+ const sourceEventSeqs = roots as number[]
2329
+ if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) continue
2330
+ // Exact tokens stay telemetry-only: they are recorded when every
2331
+ // shadowed node shares the surface tokenizer identity, and derived from
2332
+ // characters otherwise. The skip decisions above and below are all
2333
+ // character-based.
2334
+ let exactTokensBefore: number | undefined
2335
+ if (exactSurface !== undefined) {
2336
+ let sum = 0
2337
+ let allExact = true
2338
+ for (const seq of shadowedSeqs) {
2339
+ const count = measured.get(seq)
2340
+ if (count?.kind !== 'exact-tokenizer'
2341
+ || count.tokenizerId !== exactSurface.tokenizerId
2342
+ || count.tokenizerRevision !== exactSurface.tokenizerRevision) {
2343
+ allExact = false
2344
+ break
2345
+ }
2346
+ sum += count.tokens
2347
+ }
2348
+ if (allExact) exactTokensBefore = sum
2349
+ }
2350
+ const charsBefore = shadowedSeqs.reduce((sum, seq) => sum + (nodeChars.get(seq) ?? 0), 0)
2351
+ const manifestSeq = events.length
2352
+ const ref = tailTrimRef(String(session.id), manifestSeq)
2353
+ const stub = tailTrimStub(ref, calls.map(call => call.name), sourceEventSeqs)
2354
+ if (stub === null) continue
2355
+ const stubChars = codePointLength(stub)
2356
+ if (stubChars <= 0
2357
+ || charsBefore - stubChars < charsForTokens(policy.historyMinReclaimTokens)) continue
2358
+ let exactTokensAfter: number | undefined
2359
+ if (exactTokensBefore !== undefined && exactSurface !== undefined) {
2360
+ const stubCount = countExactCanonicalTextFields(
2361
+ [stub],
2362
+ candidate => view.countCanonicalText(candidate),
2363
+ 'TailTrim group stub',
2364
+ )
2365
+ if (stubCount.kind === 'exact-tokenizer'
2366
+ && stubCount.tokenizerId === exactSurface.tokenizerId
2367
+ && stubCount.tokenizerRevision === exactSurface.tokenizerRevision) {
2368
+ exactTokensAfter = stubCount.tokens
2369
+ }
2370
+ }
2371
+ const exact = exactTokensBefore !== undefined && exactTokensAfter !== undefined
2372
+ const tokensBefore = exactTokensBefore ?? charsToTokens(charsBefore)
2373
+ const tokensAfter = exactTokensAfter ?? charsToTokens(stubChars)
2374
+ const heuristicTokens = shadowedSeqs.reduce((sum, seq) => sum + (heuristic.get(seq) ?? 0), 0)
2375
+ const range = { start: SessionSeq(assistantSeq), end: SessionSeq(resultSeqs.at(-1) ?? assistantSeq) }
2376
+ const surfaceRange = { op: 'replace' as const, startSeq: range.start, endSeq: range.end }
2377
+ if (!this.reserveTailTrimBoundaryAttempt(session)) {
2378
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2379
+ 'already-attempted-at-request-boundary', {
2380
+ measurementKind: 'characters',
2381
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2382
+ triggerTokens: tailTrim.triggerTokens,
2383
+ })
2384
+ return
2385
+ }
2386
+ const manifest = session.append('compaction/prune', {
2387
+ shadowedRange: range,
2388
+ shadowedSeqs,
2389
+ shadowedTokenCount: heuristicTokens,
2390
+ })
2391
+ let replacement: SessionEvent<'user/message'>
2392
+ try {
2393
+ replacement = session.append('user/message', tailTrimMessage(stub), {
2394
+ surfaceOp: surfaceRange,
2395
+ sourceEventSeqs: [manifest.seq, ...shadowedSeqs],
2396
+ })
2397
+ } catch (error) {
2398
+ this.auditPublicationFailure(
2399
+ session,
2400
+ 'pressure',
2401
+ 'tail-trim',
2402
+ manifest.seq,
2403
+ error,
2404
+ )
2405
+ return
2406
+ }
2407
+ emitCompressionAudit(this.ctx.logger, {
2408
+ schemaVersion: 1,
2409
+ kind: 'rewrite',
2410
+ sessionId: String(session.id),
2411
+ profile: policy.profile,
2412
+ component: 'tail-trim',
2413
+ stage: 'pressure',
2414
+ reducer: 'pair-preserving-tail-trim',
2415
+ manifestEventType: 'compaction/prune',
2416
+ manifestSeq: manifest.seq,
2417
+ replacementSeq: replacement.seq,
2418
+ sourceSeqs: sourceEventSeqs,
2419
+ tokensBefore,
2420
+ tokensAfter,
2421
+ tokensRemoved: tokensBefore - tokensAfter,
2422
+ measurementBasis: exact ? 'exact-tokenizer' : 'characters',
2423
+ tokenizerId: exact === true && exactSurface !== undefined
2424
+ ? exactSurface.tokenizerId
2425
+ : 'characters',
2426
+ tokenizerRevision: exact === true && exactSurface !== undefined
2427
+ ? exactSurface.tokenizerRevision
2428
+ : 'chars-per-token-4.0',
2429
+ })
2430
+ // 节省统计:tail-trim 组的原文配对键(纯文本结果才登记,富内容跳过——
2431
+ // 与 land() 同口径:只记已落盘、可配对者)。
2432
+ const groupText = shadowedSeqs
2433
+ .map(seq => sessionEvents(session)[seq])
2434
+ .filter((event): event is SessionEvent<'tool/result'> => event?.type === 'tool/result')
2435
+ .map(event => flattenPlainText(viewToolResult(event.data.message).blocks as ContentBlock[]))
2436
+ .filter((text): text is string => text !== undefined)
2437
+ .join('\n')
2438
+ if (groupText.length > 0) {
2439
+ getSavingsLedger().recordSaving({
2440
+ sessionId: String(session.id),
2441
+ component: 'tail-trim',
2442
+ tokensBefore,
2443
+ tokensAfter,
2444
+ basis: exact ? 'exact-tokenizer' : 'characters',
2445
+ sourceSeq: manifestSeq,
2446
+ replacementSeq: Number(replacement.seq),
2447
+ originalText: groupText,
2448
+ })
2449
+ // T6 接线:tail-trim 组回收的持久 saving claim(与内存账本同点同值)。
2450
+ reclaimFromTailTrim({
2451
+ sessionId: String(session.id),
2452
+ tokensBefore,
2453
+ tokensAfter,
2454
+ basis: exact ? 'exact-tokenizer' : 'characters',
2455
+ replacementSeq: Number(replacement.seq),
2456
+ })
2457
+ }
2458
+ return
2459
+ }
2460
+ this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
2461
+ 'no-safe-eligible-tool-group', {
2462
+ measurementKind: 'characters',
2463
+ currentTokens: charsToTokens(view.currentSurfaceChars),
2464
+ triggerTokens: tailTrim.triggerTokens,
2465
+ })
2466
+ }
2467
+
2468
+ private reserveTailTrimBoundaryAttempt(session: Session): boolean {
2469
+ const boundary = this.state.activeRequestBoundaries.get(session)
2470
+ if (boundary === undefined) return true
2471
+ if (this.state.tailTrimBoundaryAttempts.get(session) === boundary) return false
2472
+ this.state.tailTrimBoundaryAttempts.set(session, boundary)
2473
+ return true
2474
+ }
2475
+
2476
+ private uniqueAppendRoot(session: Session, seq: number): number | null {
2477
+ const events = sessionEvents(session)
2478
+ const pending: Array<{ seq: number; depth: number }> = [{ seq, depth: 0 }]
2479
+ const visited = new Set<number>()
2480
+ const roots = new Set<number>()
2481
+ while (pending.length > 0) {
2482
+ const next = pending.pop()
2483
+ if (next === undefined || next.depth > 64 || visited.has(next.seq)) continue
2484
+ visited.add(next.seq)
2485
+ if (visited.size > 64) return null
2486
+ const event = events[next.seq]
2487
+ if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
2488
+ if (event.surfaceOp === 'append') roots.add(event.seq)
2489
+ else if (typeof event.surfaceOp === 'object') {
2490
+ const sources = event.sourceEventSeqs
2491
+ if (sources === undefined || sources.length === 0) return null
2492
+ for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
2493
+ } else return null
2494
+ if (roots.size > 1) return null
2495
+ }
2496
+ return roots.size === 1 ? [...roots][0] ?? null : null
2497
+ }
2498
+
2499
+ private plan(
2500
+ candidate: SnapshotCandidate,
2501
+ content: ContentBlock[],
2502
+ sourceSeq: number,
2503
+ reducer: string,
2504
+ stage: PruneStage,
2505
+ component: CompressionAuditComponent,
2506
+ historyMode: HistoryMode | undefined,
2507
+ view: CompactionTokenView,
2508
+ options: { readonly noNetSavingsGuard?: boolean, readonly elidedLines?: number } = {},
2509
+ ): PlannedReplacement | null {
2510
+ const charsBefore = candidate.characterPressure
2511
+ const charsAfter = pressureCost(content)
2512
+ // Character proof replaces the exact-tokenizer precondition: a reduction
2513
+ // must shrink the decision surface regardless of the routed model id.
2514
+ if (charsAfter <= 0 || charsAfter >= charsBefore) return null
2515
+ // Tokens are telemetry only: exact when both sides share one bundled
2516
+ // tokenizer identity, otherwise derived from the character measurement.
2517
+ const countBefore = candidate.count
2518
+ const countAfter = countToolContent(content, view)
2519
+ const exact = countBefore.kind === 'exact-tokenizer'
2520
+ && countAfter.kind === 'exact-tokenizer'
2521
+ && countAfter.tokenizerId === countBefore.tokenizerId
2522
+ && countAfter.tokenizerRevision === countBefore.tokenizerRevision
2523
+ const tokensBefore = exact ? countBefore.tokens : charsToTokens(charsBefore)
2524
+ const tokensAfter = exact ? countAfter.tokens : charsToTokens(charsAfter)
2525
+ // TokenPilot-style no-net-savings: even when the exact tokenizer reports a
2526
+ // saving, a replacement whose text is not smaller than its original adds
2527
+ // noise without reclaiming context. Text-level because the placeholder
2528
+ // guidance lines (source refs, retrieval hints) must pay for themselves.
2529
+ if (options.noNetSavingsGuard === true) {
2530
+ const originalBlocks = onlyTextBlocks(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
2531
+ const replacementBlocks = onlyTextBlocks(content)
2532
+ if (originalBlocks !== null && replacementBlocks !== null) {
2533
+ const originalChars = originalBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
2534
+ const replacementChars = replacementBlocks.reduce((sum, block) => sum + codePointLength(block.text), 0)
2535
+ if (replacementChars >= originalChars) return null
2536
+ }
2537
+ }
2538
+ return {
2539
+ candidate,
2540
+ content,
2541
+ sourceSeq,
2542
+ reducer,
2543
+ stage,
2544
+ component,
2545
+ ...historyMode === undefined ? {} : { historyMode },
2546
+ charsBefore,
2547
+ charsAfter,
2548
+ tokensBefore,
2549
+ tokensAfter,
2550
+ measurementBasis: exact ? 'exact-tokenizer' : 'characters',
2551
+ tokenizerId: exact ? countBefore.tokenizerId : 'characters',
2552
+ tokenizerRevision: exact ? countBefore.tokenizerRevision : 'chars-per-token-4.0',
2553
+ ...options.elidedLines === undefined ? {} : { elidedLines: options.elidedLines },
2554
+ }
2555
+ }
2556
+
2557
+ private land(session: Session, plan: PlannedReplacement): PrunedEntry | null {
2558
+ const { candidate } = plan
2559
+ // 0.1.7-rc.2: the tool message's own `content` is the result block set —
2560
+ // no wrapping result block anymore. The triple view still resolves the
2561
+ // call id axis on a legacy envelope.
2562
+ const resultView = viewToolResult(candidate.event.data.message)
2563
+ const message = freezeMessage<ToolResultMessage>({
2564
+ ...candidate.event.data.message,
2565
+ content: plan.content,
2566
+ })
2567
+ const manifest = session.append('compaction/prune', {
2568
+ shadowedRange: { start: SessionSeq(candidate.seq), end: SessionSeq(candidate.seq) },
2569
+ shadowedSeqs: [SessionSeq(candidate.seq)],
2570
+ shadowedTokenCount: candidate.shadowedHeuristicTokenCount,
2571
+ })
2572
+ let replacement: SessionEvent<'tool/result'>
2573
+ try {
2574
+ replacement = session.append('tool/result', {
2575
+ ...candidate.event.data,
2576
+ message,
2577
+ }, {
2578
+ surfaceOp: { op: 'replace', startSeq: SessionSeq(candidate.seq), endSeq: SessionSeq(candidate.seq) },
2579
+ sourceEventSeqs: [SessionSeq(candidate.seq)],
2580
+ })
2581
+ } catch (error) {
2582
+ this.auditPublicationFailure(
2583
+ session,
2584
+ plan.stage,
2585
+ plan.component,
2586
+ manifest.seq,
2587
+ error,
2588
+ )
2589
+ return null
2590
+ }
2591
+ emitCompressionAudit(this.ctx.logger, {
2592
+ schemaVersion: 1,
2593
+ kind: 'rewrite',
2594
+ sessionId: String(session.id),
2595
+ profile: this.activeSettings(session).profile,
2596
+ component: plan.component,
2597
+ stage: plan.stage,
2598
+ reducer: plan.reducer,
2599
+ ...plan.historyMode === undefined ? {} : { historyMode: plan.historyMode },
2600
+ manifestEventType: 'compaction/prune',
2601
+ manifestSeq: manifest.seq,
2602
+ replacementSeq: replacement.seq,
2603
+ sourceSeqs: [plan.sourceSeq],
2604
+ tokensBefore: plan.tokensBefore,
2605
+ tokensAfter: plan.tokensAfter,
2606
+ tokensRemoved: plan.tokensBefore - plan.tokensAfter,
2607
+ measurementBasis: plan.measurementBasis,
2608
+ tokenizerId: plan.tokenizerId,
2609
+ tokenizerRevision: plan.tokenizerRevision,
2610
+ // task_4c/G7 telemetry: original-event lines the reducer elided. Audit
2611
+ // record ONLY — the replacement content is untouched by this field.
2612
+ ...plan.elidedLines === undefined ? {} : { elidedLines: plan.elidedLines },
2613
+ })
2614
+ // 节省统计:已实现的削减才入账(tokensBefore−tokensAfter,审计同源同口径);
2615
+ // 原文哈希登记,供后续全文重读/retrieve 抵消配对。
2616
+ const pairedOriginal = originalTextForSavings(candidate)
2617
+ getSavingsLedger().recordSaving({
2618
+ sessionId: String(session.id),
2619
+ component: plan.component,
2620
+ tokensBefore: plan.tokensBefore,
2621
+ tokensAfter: plan.tokensAfter,
2622
+ basis: plan.measurementBasis,
2623
+ sourceSeq: plan.sourceSeq,
2624
+ replacementSeq: Number(replacement.seq),
2625
+ ...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
2626
+ })
2627
+ // T6 接线:主 land 的持久 saving claim——随写随刷同步小事务,失败仅门闩
2628
+ // warn 不阻断压缩主路径(stats-sync 内部兜异常)。
2629
+ claimFromLand({
2630
+ sessionId: String(session.id),
2631
+ component: plan.component,
2632
+ tokensBefore: plan.tokensBefore,
2633
+ tokensAfter: plan.tokensAfter,
2634
+ basis: plan.measurementBasis,
2635
+ replacementSeq: Number(replacement.seq),
2636
+ })
2637
+ return {
2638
+ originalSeq: candidate.seq,
2639
+ sourceSeq: plan.sourceSeq,
2640
+ replacementSeq: replacement.seq,
2641
+ callId: resultView.callId as ToolCallId,
2642
+ reducer: plan.reducer,
2643
+ stage: plan.stage,
2644
+ charsBefore: plan.charsBefore,
2645
+ charsAfter: plan.charsAfter,
2646
+ tokensBefore: plan.tokensBefore,
2647
+ tokensAfter: plan.tokensAfter,
2648
+ }
2649
+ }
2650
+
2651
+ private landAll(session: Session, plans: readonly PlannedReplacement[]): PrunedEntry[] {
2652
+ if (plans.length === 0) return []
2653
+ if (!this.hasRecoveryTool(session)) {
2654
+ this.warnOnce(
2655
+ session,
2656
+ 'missing-context-retrieve',
2657
+ `context-compression kept original tool results because ${RUNTIME_TOOL_NAMES.RETRIEVE} is unavailable`,
2658
+ )
2659
+ return []
2660
+ }
2661
+ if (!hasOpenTurn(session)) {
2662
+ throw new Error('tool-result pruning cannot append a surface replacement outside any open turn')
2663
+ }
2664
+ const landed: PrunedEntry[] = []
2665
+ for (const plan of plans) {
2666
+ const entry = this.land(session, plan)
2667
+ if (entry === null) break
2668
+ landed.push(entry)
2669
+ }
2670
+ return landed
2671
+ }
2672
+
2673
+ private hasRecoveryTool(session: Session): boolean {
2674
+ const tools = this.ctx.get('tools')
2675
+ if (tools === undefined) return false
2676
+ const agent = this.ctx.get('agents')?.get(session.id)
2677
+ return tools.get(RUNTIME_TOOL_NAMES.RETRIEVE, agent) !== undefined
2678
+ }
2679
+
2680
+ private auditHistoryEvaluation(
2681
+ session: Session,
2682
+ policy: CompressionPolicy,
2683
+ view: CompactionTokenView,
2684
+ allowed: boolean,
2685
+ outcome: HistoryPlanOutcome,
2686
+ ): void {
2687
+ if (policy.historyMode === 'disabled') {
2688
+ this.auditComponent(session, policy, 'history', 'pressure', 'disabled', 'profile-policy', {
2689
+ historyMode: policy.historyMode,
2690
+ })
2691
+ return
2692
+ }
2693
+ if (!allowed && outcome.kind === 'planned') {
2694
+ // The authority gate itself refused: below the frozen micro deadline
2695
+ // (capacity-pressure) or the adaptive cost estimate rejected the batch.
2696
+ const deadlineTrigger = policy.microDeadlineTokens
2697
+ const capacity = deadlineTrigger === undefined ? session.requestContext()?.contextWindow : undefined
2698
+ const capacityTrigger = deadlineTrigger !== undefined
2699
+ ? deadlineTrigger
2700
+ : Number.isSafeInteger(capacity) && capacity !== undefined && capacity > 0
2701
+ ? Math.floor(capacity * CAPACITY_PRESSURE_RATIO)
2702
+ : undefined
2703
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2704
+ policy.historyMode === 'capacity-pressure'
2705
+ ? 'below-micro-deadline' : 'adaptive-cost-rejected', {
2706
+ historyMode: policy.historyMode,
2707
+ measurementKind: 'characters',
2708
+ currentTokens: view.totalTokens,
2709
+ ...(capacityTrigger === undefined ? {} : { triggerTokens: capacityTrigger }),
2710
+ })
2711
+ return
2712
+ }
2713
+ const deadline = policy.microDeadlineTokens
2714
+ const lastChance = deadline !== undefined && view.totalTokens >= deadline
2715
+ const detail = (extra: Readonly<Record<string, number>> = {}): Readonly<{
2716
+ historyMode?: HistoryMode
2717
+ measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
2718
+ currentTokens?: number
2719
+ triggerTokens?: number
2720
+ reclaimTokens?: number
2721
+ requiredTokens?: number
2722
+ }> => ({
2723
+ historyMode: policy.historyMode,
2724
+ measurementKind: 'characters',
2725
+ currentTokens: view.totalTokens,
2726
+ ...(outcome.kind === 'insufficient-reclaim' || outcome.kind === 'cannot-reach-deadline-target'
2727
+ ? { reclaimTokens: outcome.reclaim, requiredTokens: outcome.required }
2728
+ : {}),
2729
+ ...extra,
2730
+ })
2731
+ switch (outcome.kind) {
2732
+ case 'below-profile-trigger':
2733
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2734
+ 'below-profile-trigger', detail({ triggerTokens: policy.historyTriggerTokens }))
2735
+ return
2736
+ case 'no-safe-candidates':
2737
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2738
+ 'no-safe-candidates', detail({ triggerTokens: policy.historyTriggerTokens }))
2739
+ return
2740
+ case 'protected-working-set':
2741
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2742
+ 'protected-working-set', detail({ triggerTokens: policy.historyTriggerTokens }))
2743
+ return
2744
+ case 'insufficient-reclaim':
2745
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2746
+ 'insufficient-reclaim', detail({ triggerTokens: policy.historyTriggerTokens }))
2747
+ return
2748
+ case 'cannot-reach-deadline-target':
2749
+ // Planning engaged through the full-request last-chance gate; the
2750
+ // routine trigger numbers below would misdescribe why nothing landed.
2751
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2752
+ 'cannot-reach-deadline-target', detail(lastChance ? { triggerTokens: deadline } : {}))
2753
+ return
2754
+ case 'planned':
2755
+ // A committed batch that landed nothing means the recovery tool was
2756
+ // unavailable at landing time; a degenerate empty commit reads as an
2757
+ // unreachable target instead.
2758
+ this.auditComponent(session, policy, 'history', 'pressure', 'skipped',
2759
+ outcome.plans.length > 0 ? 'recovery-tool-unavailable' : 'insufficient-reclaim',
2760
+ detail({ triggerTokens: lastChance ? deadline : policy.historyTriggerTokens }))
2761
+ return
2762
+ /* v8 ignore next -- closed-union exhaustiveness guard */
2763
+ default:
2764
+ return assertNever(outcome, 'history plan outcome')
2765
+ }
2766
+ }
2767
+
2768
+ private auditComponent(
2769
+ session: Session,
2770
+ policy: CompressionPolicy,
2771
+ component: CompressionAuditComponent,
2772
+ stage: PruneStage,
2773
+ status: CompressionAuditEvaluationStatus,
2774
+ reason: string,
2775
+ detail: Readonly<{
2776
+ historyMode?: HistoryMode
2777
+ measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
2778
+ currentTokens?: number
2779
+ triggerTokens?: number
2780
+ targetTokens?: number
2781
+ reclaimTokens?: number
2782
+ requiredTokens?: number
2783
+ }> = {},
2784
+ ): void {
2785
+ emitCompressionAudit(this.ctx.logger, {
2786
+ schemaVersion: 1,
2787
+ kind: 'component-evaluation',
2788
+ sessionId: String(session.id),
2789
+ profile: policy.profile,
2790
+ component,
2791
+ stage,
2792
+ status,
2793
+ reason,
2794
+ ...detail,
2795
+ })
2796
+ }
2797
+
2798
+ /** Emit the native-auto-compact audit for one summary manifest, once. */
2799
+ private emitNativeSummaryAudit(
2800
+ session: Session,
2801
+ manifestSeq: number,
2802
+ data: { provider?: unknown, model?: unknown, shadowedTokenCount?: unknown },
2803
+ ): void {
2804
+ let audited = this.auditedNativeSummaries.get(session)
2805
+ if (audited === undefined) {
2806
+ audited = new Set()
2807
+ this.auditedNativeSummaries.set(session, audited)
2808
+ }
2809
+ if (audited.has(manifestSeq)) return
2810
+ audited.add(manifestSeq)
2811
+ emitCompressionAudit(this.ctx.logger, {
2812
+ schemaVersion: 1,
2813
+ kind: 'native-auto-compact',
2814
+ sessionId: String(session.id),
2815
+ manifestEventType: 'compaction/summary',
2816
+ manifestSeq,
2817
+ reducer: 'llm-summary',
2818
+ provider: data.provider === undefined ? 'unknown' : String(data.provider),
2819
+ model: data.model === undefined ? 'unknown' : String(data.model),
2820
+ tokensBefore: typeof data.shadowedTokenCount === 'number' ? data.shadowedTokenCount : null,
2821
+ tokensAfter: null,
2822
+ })
2823
+ }
2824
+
2825
+ /**
2826
+ * 0.1.5 commits Native auto-compact by reopening the Session with a seed
2827
+ * log; seed events never reach the `session/event` firehose, so scan the
2828
+ * snapshot for summary manifests the live listener could not observe.
2829
+ */
2830
+ private scanForSeededNativeSummary(session: Session): void {
2831
+ for (const event of sessionEvents(session)) {
2832
+ if (event.type === 'compaction/summary') {
2833
+ this.emitNativeSummaryAudit(session, event.seq, event.data)
2834
+ }
2835
+ }
2836
+ }
2837
+
2838
+ private auditFailure(
2839
+ session: Session,
2840
+ stage: PruneStage,
2841
+ operation:
2842
+ | 'request-boundary'
2843
+ | 'terminal-pass'
2844
+ | 'policy-resolution'
2845
+ | 'summary-locator'
2846
+ | 'publication',
2847
+ error: unknown,
2848
+ ): void {
2849
+ emitCompressionAudit(this.ctx.logger, {
2850
+ schemaVersion: 1,
2851
+ kind: 'failure',
2852
+ sessionId: String(session.id),
2853
+ stage,
2854
+ operation,
2855
+ errorName: error instanceof Error ? error.name : 'UnknownError',
2856
+ // T33:错误消息是审计面唯一自由文本——首行+截断净化后再进任何记录面。
2857
+ errorMessage: sanitizeAuditMessage(error),
2858
+ })
2859
+ }
2860
+
2861
+ private auditPublicationFailure(
2862
+ session: Session,
2863
+ stage: PruneStage,
2864
+ component: CompressionAuditComponent,
2865
+ manifestSeq: number,
2866
+ error: unknown,
2867
+ ): void {
2868
+ emitCompressionAudit(this.ctx.logger, {
2869
+ schemaVersion: 1,
2870
+ kind: 'failure',
2871
+ sessionId: String(session.id),
2872
+ stage,
2873
+ operation: 'publication',
2874
+ component,
2875
+ manifestSeq,
2876
+ errorName: error instanceof Error ? error.name : 'UnknownError',
2877
+ errorMessage: 'surface replacement append failed after compaction/prune committed',
2878
+ })
2879
+ }
2880
+
2881
+ private warnExactUnavailable(
2882
+ session: Session,
2883
+ view: CompactionTokenView,
2884
+ gate: 'native' | 'fresh' | 'aggregate' | 'history' | 'tailtrim',
2885
+ ): void {
2886
+ const provider = view.providerRoute ?? 'unbound-provider'
2887
+ const model = view.modelId ?? 'unbound-model'
2888
+ this.warnOnce(
2889
+ session,
2890
+ `exact-tokenizer:${gate}:${provider}\0${model}`,
2891
+ 'context-compression %s is measuring on the character basis: exact tokenizer counts are unavailable for %s/%s',
2892
+ gate,
2893
+ provider,
2894
+ model,
2895
+ )
2896
+ }
2897
+
2898
+ private warnOnce(
2899
+ session: Session,
2900
+ key: string,
2901
+ message: string,
2902
+ ...args: unknown[]
2903
+ ): void {
2904
+ let warned = this.state.warnedFailures.get(session)
2905
+ if (warned === undefined) {
2906
+ warned = new Set()
2907
+ this.state.warnedFailures.set(session, warned)
2908
+ }
2909
+ if (warned.has(key)) return
2910
+ warned.add(key)
2911
+ this.ctx.logger.warn(message, ...args)
2912
+ }
2913
+
2914
+ }
2915
+
2916
+ export default ToolResultPruner