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

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