dsh-context-compression-improved 0.9.9-beta.0 → 0.9.9

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