@sema-agent/core 5.20.0 → 5.21.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 (312) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/agents/agent-definition.d.ts +7 -0
  3. package/dist/agents/agent-transcript-tool.d.ts +30 -0
  4. package/dist/agents/builtin-agents.d.ts +60 -0
  5. package/dist/agents/cascade.d.ts +107 -0
  6. package/dist/agents/cumulative-stats.d.ts +56 -0
  7. package/dist/agents/observer.d.ts +162 -0
  8. package/dist/agents/peer-admission.d.ts +95 -0
  9. package/dist/agents/repair-loop.d.ts +226 -0
  10. package/dist/agents/retain-ledger.d.ts +141 -0
  11. package/dist/agents/roster-store.d.ts +105 -0
  12. package/dist/agents/send-message-tool.d.ts +92 -0
  13. package/dist/agents/session-util.d.ts +5 -0
  14. package/dist/agents/subagent-steps.d.ts +66 -0
  15. package/dist/agents/subagent.d.ts +600 -0
  16. package/dist/agents/suspend-guard.d.ts +29 -0
  17. package/dist/agents/teacher.d.ts +75 -0
  18. package/dist/agents/team.d.ts +120 -1
  19. package/dist/agents/tool-filter.d.ts +34 -0
  20. package/dist/agents/verify.d.ts +198 -0
  21. package/dist/bench/metrics.d.ts +455 -0
  22. package/dist/brain/anthropic.d.ts +30 -0
  23. package/dist/brain/circuit-breaker.d.ts +33 -0
  24. package/dist/brain/context-overflow.d.ts +60 -3
  25. package/dist/brain/degrading.d.ts +67 -0
  26. package/dist/brain/errors.d.ts +42 -0
  27. package/dist/brain/failover.d.ts +15 -0
  28. package/dist/brain/media-degrade.d.ts +39 -0
  29. package/dist/brain/model-presets.d.ts +31 -0
  30. package/dist/brain/open-responses.d.ts +19 -0
  31. package/dist/brain/openai.d.ts +46 -0
  32. package/dist/brain/reasoning.d.ts +106 -1
  33. package/dist/brain/repetition.d.ts +83 -0
  34. package/dist/brain/request-params.d.ts +56 -0
  35. package/dist/brain/retry.d.ts +46 -0
  36. package/dist/brain/routing.d.ts +12 -0
  37. package/dist/brain/status-sink.d.ts +30 -1
  38. package/dist/brain/stream-engine.d.ts +147 -0
  39. package/dist/brain/stream-shared.d.ts +34 -0
  40. package/dist/brain/terminal-cause.d.ts +31 -0
  41. package/dist/brain/timeout.d.ts +107 -0
  42. package/dist/brain/tool-call-id.d.ts +20 -0
  43. package/dist/brain/tool-call-repair.d.ts +13 -0
  44. package/dist/config/catalog.d.ts +47 -0
  45. package/dist/config/defaults.d.ts +33 -0
  46. package/dist/core/a2a-task-state.d.ts +53 -0
  47. package/dist/core/a2a.d.ts +51 -0
  48. package/dist/core/arg-summary.d.ts +62 -0
  49. package/dist/core/ask-question.d.ts +272 -2
  50. package/dist/core/auto-compaction.d.ts +467 -0
  51. package/dist/core/auto-compaction.js +20 -6
  52. package/dist/core/auto-mode-prompt-assets.d.ts +8 -0
  53. package/dist/core/auto-mode-prompt.d.ts +27 -0
  54. package/dist/core/auto-mode.d.ts +54 -3
  55. package/dist/core/auto-promote.d.ts +100 -0
  56. package/dist/core/background-agent-store.d.ts +292 -0
  57. package/dist/core/background-shell.d.ts +110 -0
  58. package/dist/core/cache-break-detector.d.ts +34 -0
  59. package/dist/core/canonical-json.d.ts +57 -0
  60. package/dist/core/checkpoint-store.d.ts +1574 -16
  61. package/dist/core/compliance.d.ts +30 -0
  62. package/dist/core/consolidate-scope.d.ts +75 -0
  63. package/dist/core/context-edit.d.ts +99 -0
  64. package/dist/core/context-guard.d.ts +46 -0
  65. package/dist/core/exec-gate.d.ts +44 -0
  66. package/dist/core/exec-output-tail.d.ts +61 -0
  67. package/dist/core/file-snapshot-store.d.ts +104 -0
  68. package/dist/core/fs-write-gate-policy.d.ts +36 -0
  69. package/dist/core/git-worktree-env.d.ts +31 -0
  70. package/dist/core/governance-codes.d.ts +19 -0
  71. package/dist/core/hooks.d.ts +608 -1
  72. package/dist/core/human-input-projection.d.ts +37 -0
  73. package/dist/core/human-input-projection.js +13 -0
  74. package/dist/core/image-downsample.d.ts +74 -0
  75. package/dist/core/locked-config.d.ts +37 -0
  76. package/dist/core/lsp-diagnostics.d.ts +77 -0
  77. package/dist/core/lsp-protocol.d.ts +29 -0
  78. package/dist/core/lsp-session.d.ts +60 -1
  79. package/dist/core/lsp.d.ts +150 -1
  80. package/dist/core/mailbox-store.d.ts +57 -0
  81. package/dist/core/mcp.d.ts +381 -0
  82. package/dist/core/media-byte-cap.d.ts +21 -0
  83. package/dist/core/memory-admission.d.ts +71 -0
  84. package/dist/core/memory-engine/content-origin.d.ts +64 -0
  85. package/dist/core/memory-engine/data-plane.d.ts +43 -0
  86. package/dist/core/memory-engine/dual-root.d.ts +24 -0
  87. package/dist/core/memory-engine/engine.d.ts +230 -0
  88. package/dist/core/memory-engine/engine.js +103 -35
  89. package/dist/core/memory-engine/file-backend.d.ts +155 -0
  90. package/dist/core/memory-engine/frontmatter.d.ts +16 -0
  91. package/dist/core/memory-engine/layout.d.ts +217 -0
  92. package/dist/core/memory-engine/memory-backend-contract.d.ts +12 -0
  93. package/dist/core/memory-engine/migrate.d.ts +9 -0
  94. package/dist/core/memory-engine/scan.d.ts +12 -0
  95. package/dist/core/memory-engine/scope-contract.d.ts +61 -1
  96. package/dist/core/memory-engine/sync-client.d.ts +87 -0
  97. package/dist/core/memory-engine/sync.d.ts +60 -0
  98. package/dist/core/memory-engine/tools.d.ts +41 -0
  99. package/dist/core/memory-engine/types.d.ts +188 -0
  100. package/dist/core/memory-recall.d.ts +141 -0
  101. package/dist/core/memory-vector.d.ts +20 -0
  102. package/dist/core/memory.d.ts +458 -0
  103. package/dist/core/message-utils.d.ts +6 -0
  104. package/dist/core/oracle-isolation.d.ts +69 -0
  105. package/dist/core/permission-rule-consent.d.ts +138 -0
  106. package/dist/core/permission-rule-model.d.ts +122 -0
  107. package/dist/core/permission-rule-store.d.ts +119 -3
  108. package/dist/core/permission-rules.d.ts +87 -1
  109. package/dist/core/present-plan-tool.d.ts +20 -0
  110. package/dist/core/pricing.d.ts +26 -0
  111. package/dist/core/property-harness.d.ts +86 -0
  112. package/dist/core/protocol-naming.d.ts +38 -0
  113. package/dist/core/protocol-table.d.ts +61 -0
  114. package/dist/core/push-queue.d.ts +1 -0
  115. package/dist/core/remote-env.d.ts +383 -1
  116. package/dist/core/retention-policy.d.ts +33 -0
  117. package/dist/core/retention.d.ts +51 -0
  118. package/dist/core/roles.d.ts +59 -0
  119. package/dist/core/runner/active-skill-scope.d.ts +34 -0
  120. package/dist/core/runner/assemble-result.d.ts +134 -0
  121. package/dist/core/runner/compaction-call-options.d.ts +97 -1
  122. package/dist/core/runner/grounding-signal.d.ts +10 -0
  123. package/dist/core/runner/image.d.ts +17 -0
  124. package/dist/core/runner/image.js +29 -15
  125. package/dist/core/runner/memory-consolidation.d.ts +60 -0
  126. package/dist/core/runner/prepare-memory.d.ts +59 -0
  127. package/dist/core/runner/prepare-task.d.ts +1011 -2
  128. package/dist/core/runner/prepare-task.js +12 -11
  129. package/dist/core/runner/prompt-suggestions.d.ts +7 -0
  130. package/dist/core/runner/runtask.d.ts +304 -3
  131. package/dist/core/runner/session-file-state-replay.d.ts +49 -0
  132. package/dist/core/runner/session-rule-policy.d.ts +58 -0
  133. package/dist/core/runner/strict-output-schema.d.ts +18 -3
  134. package/dist/core/runner/synthetic-tools.d.ts +113 -0
  135. package/dist/core/runner/teardown-bounded.d.ts +34 -0
  136. package/dist/core/runner/tool-disclosure.d.ts +227 -0
  137. package/dist/core/runner/tool-output-projection.d.ts +6 -0
  138. package/dist/core/runner/turn-attachments.d.ts +634 -0
  139. package/dist/core/runner/usage-accounting.d.ts +32 -0
  140. package/dist/core/runtime.d.ts +9 -0
  141. package/dist/core/safe-notify.d.ts +64 -0
  142. package/dist/core/safety-axis-vocab.d.ts +23 -0
  143. package/dist/core/safety-merge-corpus.d.ts +37 -0
  144. package/dist/core/scheduler.d.ts +121 -0
  145. package/dist/core/secret-env.d.ts +32 -0
  146. package/dist/core/select-model.d.ts +15 -0
  147. package/dist/core/sensitive-path-policy.d.ts +42 -0
  148. package/dist/core/session-policy-store.d.ts +94 -0
  149. package/dist/core/session-reconcile.d.ts +80 -0
  150. package/dist/core/session-store.d.ts +85 -0
  151. package/dist/core/session.d.ts +153 -0
  152. package/dist/core/shared-memory/contract.d.ts +22 -0
  153. package/dist/core/shared-memory/normalize.d.ts +123 -2
  154. package/dist/core/shared-memory/tools.d.ts +14 -0
  155. package/dist/core/shared-memory/types.d.ts +105 -0
  156. package/dist/core/shutdown-debug.d.ts +6 -0
  157. package/dist/core/side-query.d.ts +38 -0
  158. package/dist/core/side-query.js +6 -1
  159. package/dist/core/skill-tool-specifier.d.ts +72 -0
  160. package/dist/core/skills-directory.d.ts +100 -1
  161. package/dist/core/spec-contract.d.ts +89 -0
  162. package/dist/core/store-contracts/background-agent-store-contract.d.ts +31 -0
  163. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +26 -0
  164. package/dist/core/store-contracts/contract-harness.d.ts +20 -0
  165. package/dist/core/store-contracts/contract-kit-version.d.ts +27 -0
  166. package/dist/core/store-contracts/file-snapshot-store-contract.d.ts +8 -0
  167. package/dist/core/store-contracts/mailbox-store-contract.d.ts +42 -0
  168. package/dist/core/store-contracts/tool-result-store-contract.d.ts +13 -0
  169. package/dist/core/strategy-store.d.ts +37 -0
  170. package/dist/core/stub-env.d.ts +7 -0
  171. package/dist/core/surrogate-safe-slice.d.ts +35 -0
  172. package/dist/core/task-notification.d.ts +202 -0
  173. package/dist/core/task-outcome.d.ts +53 -0
  174. package/dist/core/task-registry-agent.d.ts +337 -1
  175. package/dist/core/task-registry-monitor.d.ts +12 -0
  176. package/dist/core/task-registry-shared.d.ts +540 -0
  177. package/dist/core/task-registry.d.ts +343 -0
  178. package/dist/core/task-registry.js +13 -2
  179. package/dist/core/task-tool-shape.d.ts +44 -0
  180. package/dist/core/tighten-task-spec.d.ts +21 -0
  181. package/dist/core/tool-detach.d.ts +21 -0
  182. package/dist/core/tool-errors.d.ts +131 -0
  183. package/dist/core/tool-errors.js +4 -0
  184. package/dist/core/tool-name-aliases.d.ts +27 -0
  185. package/dist/core/tool-policy.d.ts +555 -0
  186. package/dist/core/tool-result-budget.d.ts +32 -0
  187. package/dist/core/tool-result-store.d.ts +174 -1
  188. package/dist/core/tools.d.ts +45 -0
  189. package/dist/core/trace.d.ts +323 -0
  190. package/dist/core/types.d.ts +3859 -2
  191. package/dist/core/untrusted-egress.d.ts +8 -0
  192. package/dist/core/untrusted-text.d.ts +156 -0
  193. package/dist/core/usage-window-store.d.ts +95 -0
  194. package/dist/core/version.d.ts +1 -0
  195. package/dist/core/warm-resume.d.ts +17 -0
  196. package/dist/core/wiring-manifest.d.ts +169 -0
  197. package/dist/core/with-retry.d.ts +24 -0
  198. package/dist/core/workflow-journal-store.d.ts +160 -0
  199. package/dist/core/workflow-run-store-contract.d.ts +25 -0
  200. package/dist/core/workflow-run-store.d.ts +119 -0
  201. package/dist/engine/compaction/compaction.d.ts +256 -1
  202. package/dist/engine/compaction/utils.d.ts +94 -0
  203. package/dist/engine/execution-env/kill-tree.d.ts +29 -0
  204. package/dist/engine/execution-env/node-execution-env.d.ts +94 -0
  205. package/dist/engine/harness/agent-harness.d.ts +116 -0
  206. package/dist/engine/harness/agent-harness.js +3 -14
  207. package/dist/engine/harness/messages.d.ts +15 -0
  208. package/dist/engine/harness/types.d.ts +464 -2
  209. package/dist/engine/llm/diagnostics.d.ts +4 -0
  210. package/dist/engine/llm/event-stream.d.ts +3 -0
  211. package/dist/engine/llm/index.d.ts +7 -0
  212. package/dist/engine/llm/types.d.ts +500 -3
  213. package/dist/engine/llm/validation.d.ts +3 -0
  214. package/dist/engine/loop/agent-loop.d.ts +87 -2
  215. package/dist/engine/loop/runtime-deps.d.ts +7 -0
  216. package/dist/engine/loop/types.d.ts +424 -0
  217. package/dist/engine/lsp/frame-decoder.d.ts +13 -0
  218. package/dist/engine/lsp/node-lsp-manager.d.ts +107 -0
  219. package/dist/engine/lsp/stdio-lsp-transport.d.ts +7 -0
  220. package/dist/engine/session/import-validate.d.ts +27 -0
  221. package/dist/engine/session/log-digest.d.ts +93 -0
  222. package/dist/engine/session/memory-repo.d.ts +6 -0
  223. package/dist/engine/session/memory-storage.d.ts +2 -0
  224. package/dist/engine/session/session.d.ts +75 -0
  225. package/dist/engine/session/storage-base.d.ts +8 -0
  226. package/dist/fixtures/index.d.ts +36 -0
  227. package/dist/index.d.ts +16 -1
  228. package/dist/index.js +0 -1
  229. package/dist/internal/harness-types.d.ts +6 -0
  230. package/dist/internal/harness.d.ts +11 -0
  231. package/dist/internal/llm.d.ts +6 -0
  232. package/dist/orchestration/builtin-workflows.d.ts +53 -0
  233. package/dist/orchestration/dev-vm-script-runner.d.ts +19 -0
  234. package/dist/orchestration/goal.d.ts +57 -0
  235. package/dist/orchestration/goal.js +3 -0
  236. package/dist/orchestration/run-spec.d.ts +42 -0
  237. package/dist/orchestration/run-workflow-tool.d.ts +169 -0
  238. package/dist/orchestration/workflow-governance.d.ts +61 -0
  239. package/dist/orchestration/workflow-meta.d.ts +28 -0
  240. package/dist/orchestration/workflow-observe.d.ts +60 -0
  241. package/dist/orchestration/workflow-primitives.d.ts +23 -1
  242. package/dist/orchestration/workflow-sandbox-conformance.d.ts +38 -0
  243. package/dist/orchestration/workflow-script-runner.d.ts +88 -0
  244. package/dist/orchestration/workflow-script-store.d.ts +98 -0
  245. package/dist/orchestration/workflow-size-guideline.d.ts +67 -0
  246. package/dist/orchestration/workflow-types.d.ts +169 -2
  247. package/dist/orchestration/workflow.d.ts +358 -0
  248. package/dist/prompt-assembly/artifact-store.d.ts +33 -0
  249. package/dist/prompt-assembly/artifact.d.ts +25 -0
  250. package/dist/prompt-assembly/assemble.d.ts +20 -0
  251. package/dist/prompt-assembly/composer.d.ts +29 -0
  252. package/dist/prompt-assembly/epoch.d.ts +55 -1
  253. package/dist/prompt-assembly/event-registry.d.ts +35 -0
  254. package/dist/prompt-assembly/explain.d.ts +12 -0
  255. package/dist/prompt-assembly/tool-catalog.d.ts +38 -0
  256. package/dist/prompt-assembly/turn-snapshot.d.ts +40 -0
  257. package/dist/prompt-assembly/types.d.ts +115 -0
  258. package/dist/prompts/coordinator.d.ts +27 -0
  259. package/dist/prompts/default.d.ts +539 -0
  260. package/dist/prompts/simple-sections.d.ts +45 -0
  261. package/dist/prompts/supervisor.d.ts +66 -0
  262. package/dist/scenarios/env.d.ts +28 -0
  263. package/dist/scenarios/full-body.d.ts +50 -0
  264. package/dist/scenarios/scenario-registry.d.ts +60 -0
  265. package/dist/scenarios/teacher-quickstart.d.ts +27 -0
  266. package/dist/server/http.d.ts +17 -0
  267. package/dist/stores/cc/lockfile.d.ts +6 -0
  268. package/dist/stores/cc/mailbox-store.d.ts +8 -0
  269. package/dist/stores/cc/roster-adapter.d.ts +4 -0
  270. package/dist/stores/cc/sidecar-transcript.d.ts +66 -0
  271. package/dist/stores/file/background-agent-store.d.ts +24 -0
  272. package/dist/stores/file/checkpoint-store.d.ts +38 -0
  273. package/dist/stores/file/file-snapshot-store.d.ts +25 -0
  274. package/dist/stores/file/fs-atomic.d.ts +155 -0
  275. package/dist/stores/file/index.d.ts +89 -0
  276. package/dist/stores/file/mailbox-store.d.ts +36 -0
  277. package/dist/stores/file/memory-store.d.ts +82 -0
  278. package/dist/stores/file/permission-rule-store.d.ts +79 -0
  279. package/dist/stores/file/session-policy-store.d.ts +28 -0
  280. package/dist/stores/file/session-store.d.ts +40 -0
  281. package/dist/stores/file/shared-ledger.d.ts +83 -0
  282. package/dist/stores/file/tool-result-store.d.ts +11 -0
  283. package/dist/stores/file/usage-window-store.d.ts +18 -0
  284. package/dist/stores/file/workflow-journal-store.d.ts +100 -0
  285. package/dist/stores/file/workflow-run-store.d.ts +11 -0
  286. package/dist/tools/fs/bash-readonly-classifier.d.ts +282 -0
  287. package/dist/tools/fs/encoding.d.ts +60 -0
  288. package/dist/tools/fs/fs-bash.d.ts +133 -0
  289. package/dist/tools/fs/fs-pdf.d.ts +28 -0
  290. package/dist/tools/fs/fs-search-tools.d.ts +5 -0
  291. package/dist/tools/fs/fs-shared.d.ts +360 -0
  292. package/dist/tools/fs/fs-write.d.ts +16 -0
  293. package/dist/tools/fs/gh-rate-limit.d.ts +22 -0
  294. package/dist/tools/fs/index.d.ts +79 -0
  295. package/dist/tools/fs/notebook.d.ts +56 -0
  296. package/dist/tools/fs/pdf.d.ts +70 -0
  297. package/dist/tools/fs/pdf.js +8 -2
  298. package/dist/tools/fs/repo-map.d.ts +10 -0
  299. package/dist/tools/fs/safety.d.ts +376 -0
  300. package/dist/tools/fs/search.d.ts +131 -0
  301. package/dist/tools/loop-tick.d.ts +24 -0
  302. package/dist/tools/monitor.d.ts +55 -0
  303. package/dist/tools/scheduler-tools.d.ts +51 -0
  304. package/dist/tools/sql-adapters.d.ts +18 -0
  305. package/dist/tools/sql.d.ts +25 -0
  306. package/dist/tools/task-list.d.ts +77 -0
  307. package/dist/tools/todo.d.ts +8 -0
  308. package/dist/tools/web.d.ts +184 -0
  309. package/dist/tools/worktree.d.ts +81 -0
  310. package/package.json +2 -2
  311. package/dist/tools/gitea-issue.d.ts +0 -13
  312. package/dist/tools/gitea-issue.js +0 -75
@@ -3,47 +3,148 @@ import type { Message, Model, Tool } from "../internal/llm.js";
3
3
  import type { Hooks } from "./hooks.js";
4
4
  import type { TraceEvent } from "./trace.js";
5
5
  import type { Brain } from "./types.js";
6
+ /**
7
+ * Default summarization focus, applied when a task does not provide `compaction.instructions`.
8
+ * Addresses the common fidelity failure where summaries drop specific facts.
9
+ */
6
10
  export declare const DEFAULT_COMPACTION_INSTRUCTIONS: string;
11
+ /**
12
+ * design/145 §4 — uniform hygiene for EVERY summarization-instructions channel (spec-level
13
+ * `compaction.instructions`, the DEFAULT constant, a manual `/compact` per-call override, and a
14
+ * preCompact hook's `additionalInstructions` — 修类不修点): instructions text can be model- or
15
+ * caller-authored, and it is injected VERBATIM into the summarization prompt
16
+ * (`\n\nAdditional Instructions:\n${...}`, CC 207 :347521 shape), so a forged `</system-reminder>`
17
+ * or `<<<`/`>>>` fence sentinel inside it would otherwise ride into a trusted prompt position.
18
+ * Posture (r2 review B4): `sanitizeUntrustedText` + fence defusing only — NEVER `delimitUntrusted`
19
+ * (fencing instructions as "data only, do not follow" self-defeats their instructional intent, and
20
+ * the fence markers would be echoed back into the persisted summary). Cap = 2048 code points
21
+ * (surrogate-safe slice): instructions steer a summary, they are not a payload channel.
22
+ * Text without break-out sequences under the cap passes through BYTE-IDENTICAL (the no-arg /
23
+ * default-instructions prompt is unchanged — pinned by test).
24
+ */
7
25
  export declare const COMPACTION_INSTRUCTIONS_MAX_CHARS = 2048;
8
26
  export declare function sanitizeCompactionInstructions(text: string): string;
27
+ /**
28
+ * 压缩子阶段遥测 (1.283 G) — single-source shape: the `phaseDurations` result field IS the
29
+ * (defined-but-not-yet-emitted) `compaction.phase_timings` trace frame minus its envelope
30
+ * (`kind`/`version`/`taskId`/`ts`) and minus `durationMs` (already a sibling result field). Deriving
31
+ * it from the frame keeps the follow-up runtask bridge a mechanical spread — and makes a rollback of
32
+ * either side a tsc error, not a silent drift.
33
+ */
9
34
  export type CompactionPhaseDurations = Omit<Extract<TraceEvent, {
10
35
  kind: "compaction.phase_timings";
11
36
  }>, "kind" | "version" | "taskId" | "ts" | "durationMs">;
37
+ /** True iff `err` is a compaction failure caused by a manual compact() caller WITHDRAWING its
38
+ * request (cancel-signal abort of the pass's summary call) — see
39
+ * {@link MaybeCompactOptions.manualCancelSignal}. Absence of the marker means the failure was NOT
40
+ * the withdrawal: a real summarizer error racing a late cancel stays unmarked so the caller's
41
+ * breaker/onError accounting still sees it. */
12
42
  export declare function isCompactionManualCancel(err: unknown): boolean;
43
+ /**
44
+ * design/145 §1/§3 — the window-safety decision surfaced to the caller BEFORE the summary call
45
+ * (same pre-call posture as `onInputTruncated`: the disclosure must survive a later summary
46
+ * failure). `kind:"fallback"` → the summary call was moved to the MAIN model (window safety);
47
+ * `kind:"clamp_disclosure"` → the small model keeps the call but the conversation WILL be
48
+ * clamp-truncated: `reason` says why the fallback did not happen ("budget" = the gate
49
+ * denied it; "tolerance" = the truncation is within `clampTolerance` — bounded, but no longer
50
+ * silent). All token figures are in the MAIN model's structural coordinate except
51
+ * `headroomTokens` (the小 model's — it describes THAT window's capacity).
52
+ */
13
53
  export interface CompactionWindowSafetyInfo {
14
54
  kind: "fallback" | "clamp_disclosure";
15
55
  truncationRatio: number;
56
+ /** Present on "clamp_disclosure": why the small model kept the call despite the truncation. */
16
57
  reason?: "budget" | "tolerance";
58
+ /** Serialized conversation size incl. any re-sent previousSummary (chars ÷ main-model charsPerToken). */
17
59
  contentTokens: number;
60
+ /** ≈ what fits in the compaction model's window (kept chars ÷ its charsPerToken); estimate. */
18
61
  headroomTokens?: number;
62
+ /** 门A estimate: main-model input price × contentTokens, integer micro-USD (absent when pricing
63
+ * was unavailable — the gate then never blocked on budget). */
19
64
  estCostMicroUsd?: number;
20
65
  }
66
+ /**
67
+ * SEMA-ONLY (trim-seam defense, no CC analogue) — stale-anchor freshness margin: a usage anchor is
68
+ * trusted only while the anchored estimate stays within `structural × margin + overhead` of the
69
+ * current message list. 2 covers the worst measured structural under-count (charsPerToken=3 vs a
70
+ * measured ~2.18 true ratio ⇒ ≤ ~1.4x) plus reasoning-block accounting slop, while still catching
71
+ * the live deception band (anchored estimates 2.9x–18x over the real context — docs/TOKEN-ESTIMATE-
72
+ * CALIBRATION-LIVE-2026-07-09.md §3/§4).
73
+ */
21
74
  export declare const STALE_ANCHOR_STRUCTURAL_MARGIN = 2;
22
75
  export declare function sanitizeCompactionSettings(settings: CompactionSettings, contextWindow: number | undefined): CompactionSettings;
76
+ /**
77
+ * design/169-A — the CC-form fork context: the main lane's latest REAL brain request (same
78
+ * `systemPrompt` bytes, same message-list bytes, same tools). The summary request built from it is
79
+ * that request plus ONE appended user-role instruction message, so the provider's prompt cache
80
+ * re-serves the already-paid main prefix — the economics that make "summarize on the main model"
81
+ * cheap. Structural twin of the engine-side `CompactionForkContext` (engine/compaction/compaction.ts
82
+ * — the engine layer cannot import core, so the shape is declared on both faces and must stay
83
+ * assignable; `compact()`'s parameter type is the checked seam).
84
+ */
23
85
  export interface CompactionForkContext {
24
86
  systemPrompt?: string;
87
+ /** The physical cache-span block layout of the main request, when it had one (Context.systemBlocks)
88
+ * — the fork must reproduce it or a multi-block pack's cache boundaries are silently lost. */
25
89
  systemBlocks?: Array<{
26
90
  text: string;
27
91
  cacheControlBoundary: boolean;
28
92
  }>;
29
93
  messages: Message[];
30
94
  tools?: Tool[];
95
+ /** The model id that served the recorded request — part of the provider cache key; the fork
96
+ * eligibility gate refuses a snapshot from a different model (see the engine-side twin's doc). */
31
97
  modelId?: string;
32
98
  }
33
99
  export interface MaybeCompactOptions {
100
+ /** RB-473 — disclosure channel for CONTAINED host-callback failures in this scope (the RB-463
101
+ * isolation primitive's bounded first-failure per site). Absent ⇒ failures are counted only. */
34
102
  onNotifyError?: (failure: import("./safe-notify.js").SafeNotifyFailure) => void;
103
+ /** The session to compact. Typed on the INTERFACE face (typecheck 车 2026-07-24): every member this
104
+ * module touches lives on `Session` (the optional `getPromptEpoch` degrades honestly via `?.()`). */
35
105
  session: Session;
106
+ /** [1068] ruling a — this run's provider-declared prompt sections (the epoch declaration axis):
107
+ * the compaction-boundary epoch restatement/advance must hash the SAME artifact identity as the
108
+ * prepare-time pin, or every compaction under a declaration-carrying run would flap the pin. */
36
109
  epochDeclaredSections?: import("../prompt-assembly/epoch.js").EpochDeclaredSections;
110
+ /** RB-31 (design/148 S2) — a compaction-boundary CENTER CANDIDATE ADOPTION, pre-assembled by the
111
+ * caller (prepare's seam): the descriptor advances with the candidate's declarations + provenance
112
+ * in the SAME CAS append as the new baseline, and `apply()` (the live prefix/fingerprint swap)
113
+ * runs ONLY after that append succeeded — a failed/blocked compaction must swap nothing. */
37
114
  centerAdoption?: {
115
+ /** Absent together with `clear` ⇒ never happens; adoption carries the new digest, ROLLBACK
116
+ * (explicit center disable, codex F1) carries `clear:true` and no digest. */
38
117
  centerArtifactDigest?: string;
39
118
  sourceRevision?: string;
40
119
  clear?: true;
41
120
  declaredSections: import("../prompt-assembly/epoch.js").EpochDeclaredSections;
121
+ /** codex F2 — the post-swap prompt overhead in the trigger estimate's coordinate: used for THIS
122
+ * compaction's post-measurement so PTL recovery/anti-thrash see the swapped prefix size. */
42
123
  overheadTokensAfter: number;
43
124
  apply: (committedArtifactDigest?: string) => void;
44
125
  };
126
+ /** Model whose context window bounds the budget (the model that runs the next turn). */
45
127
  model: Model;
128
+ /** Optional cheaper model used to produce the summary. Falls back to `model`.
129
+ * design/145 §1 (semantics精确化): used only while WINDOW-SAFE and the budget gate allows — when a
130
+ * dry-run clamp shows the conversation would lose more than `settings.clampTolerance` of its
131
+ * chars to fit this model's window, the summary call falls back to the MAIN model (`model`),
132
+ * which is always window-safe (the content grew inside its window; CC 207 :348496 compresses
133
+ * with the main-loop model unconditionally — the fallback IS the CC posture, the independent
134
+ * compaction model is sema's superset). Subagent note (design/145 §5): delegated children never
135
+ * inherit this option (subagent.ts buildChildSpec carries no compactionModel), so a child always
136
+ * self-compacts on its own main model — the judgment is structurally never triggered there. */
46
137
  compactionModel?: Model;
138
+ /**
139
+ * design/169-A — accessor for the main lane's latest real request context (see
140
+ * {@link CompactionForkContext}). Consulted per pass, at call time (the ref advances with every
141
+ * main request). Used ONLY when the summary call runs on the MAIN model (no `compactionModel` in
142
+ * play — an independent small model has no main prefix to share); `undefined` (or an accessor
143
+ * returning `undefined`: no main request issued yet, or a library caller driving maybeCompact
144
+ * directly) keeps the independent request form byte-for-byte. A fork-form prompt-too-long falls
145
+ * back ONCE to the independent form inside `compact()` (the fork form must not clamp — a clamp
146
+ * rewrites the cached prefix, defeating the form's purpose).
147
+ */
47
148
  forkContext?: () => CompactionForkContext | undefined;
48
149
  brain: Brain;
49
150
  getApiKeyAndHeaders?: (model: Model) => Promise<{
@@ -52,104 +153,470 @@ export interface MaybeCompactOptions {
52
153
  } | undefined>;
53
154
  thinking?: ThinkingLevel;
54
155
  settings?: CompactionSettings;
156
+ /** Appended to the summarization prompt to steer what must be preserved. Sanitized inside
157
+ * maybeCompact via {@link sanitizeCompactionInstructions} (design/145 §4 — every channel,
158
+ * including the preCompact hook's additions, gets the same treatment). */
55
159
  customInstructions?: string;
56
160
  signal?: AbortSignal;
161
+ /**
162
+ * Manual compact() withdrawal signal — the composed cancel signals of the manual callers THIS
163
+ * pass claimed (a strict SUBSET of `signal`, which additionally carries the task's own abort).
164
+ * Used only for failure ATTRIBUTION: when the summary call's failure is its abort outcome and
165
+ * this signal has fired, the thrown error is stamped so {@link isCompactionManualCancel} holds —
166
+ * the caller then treats the pass as withdrawn ("mooted") instead of summarizer evidence. It
167
+ * never aborts anything by itself (the same signals already ride inside `signal`).
168
+ */
57
169
  manualCancelSignal?: AbortSignal;
170
+ /**
171
+ * design/145 门A — budget interaction for the window-safety fallback: a MAIN-model re-compaction
172
+ * of a near-window conversation is one giant prefill whose cost lands in the SAME ledger the
173
+ * budget gate enforces (`recordCompactionUsage` → `stats.costMicroUsd` → `overBudget()`), so an
174
+ * un-gated fallback under a cost cap is the "钱花了任务照死" double loss. When present AND
175
+ * `mainInputPer1M` is known, the fallback is denied if `spentMicroUsd() + contentTokens ×
176
+ * mainInputPer1M > capMicroUsd` — the pass then keeps the small model and DISCLOSES the clamp
177
+ * (`clamp_disclosure`, reason "budget"). Absent field / absent pricing = the gate never blocks
178
+ * (design: "pricing/cap 不可得=门不拦").
179
+ */
58
180
  fallbackBudget?: {
181
+ /** Live cumulative spend reader (the caller's `stats.costMicroUsd` at decision time). */
59
182
  spentMicroUsd: () => number;
183
+ /** The run's cost ceiling, integer micro-USD. */
60
184
  capMicroUsd: number;
185
+ /** MAIN-model input price, absolute USD per 1M tokens (`ModelPricing.inputPer1M`) — numerically
186
+ * equal to micro-USD per token, so `est = contentTokens × mainInputPer1M` needs no unit dance. */
61
187
  mainInputPer1M?: number;
62
188
  };
189
+ /**
190
+ * design/145 §3 — pre-call observer for the window-safety decision (fallback / disclosed clamp).
191
+ * Fired BEFORE the summary call (survives a later failure, `onInputTruncated` posture); throws
192
+ * are swallowed (observe-only). The caller bridges it to the `compaction.model_fallback` /
193
+ * `compaction.clamp_disclosure` trace frames.
194
+ */
63
195
  onWindowSafety?: (info: CompactionWindowSafetyInfo) => void;
196
+ /**
197
+ * Anti-thrash re-trigger floor (design/64 §25.2): ALSO require the estimated context to exceed this
198
+ * many tokens before compacting. The within-task caller sets it after each compaction (post-compaction
199
+ * size × regrowth factor) so a compaction that could not free much headroom — small window, chunky
200
+ * turns, large summary — does not re-fire a real summary LLM call at every subsequent boundary
201
+ * (LONGRUN-1b measured 26/39 boundaries firing, +135% wall, without it). 0/undefined = no floor.
202
+ */
64
203
  minTokens?: number;
204
+ /**
205
+ * Force a compaction even when context is UNDER the auto-threshold (and ignore `minTokens`) — the
206
+ * manual `/compact` path (TaskStream.compact, shell K-1c). It bypasses ONLY the threshold gate, not the
207
+ * structural floor: if there is no valid cut point (too little history to summarize) the call still
208
+ * returns `{compacted:false}` quietly. Default `false` = the auto-threshold policy.
209
+ */
65
210
  force?: boolean;
211
+ /**
212
+ * design/123 D4 (r5 final discriminant) — trim→compaction pressure propagation: force a compaction
213
+ * whenever the NATURAL gate would not fire, i.e. `est < max(threshold, minTokens-floor)`. Trim
214
+ * dropping real messages is external hard evidence that compaction is overdue, and it must override
215
+ * BOTH gates that can wrongly hold it back:
216
+ * - est < threshold — the deceived-estimate regime (request-only trim deflates the next usage
217
+ * anchor while the session stays full-size; the 16k-live sawtooth), and
218
+ * - threshold ≤ est < floor — the floor-blocked regime (post-compaction §25.2 floor above an
219
+ * HONEST over-threshold estimate; 5th live run: 27 boundaries trim-dropping while the floor
220
+ * held compaction off and input climbed 16k→27.4k).
221
+ * `est ≥ max(threshold, floor)` fires naturally anyway (no force needed/applied — the result then
222
+ * reports `naturalTrigger: true`). Spiral protection lives in the CALLER via
223
+ * {@link nextTrimForceBackoff}: any landed compaction that still posts over the threshold
224
+ * (incompressible transcript, the LONGRUN-1b shape) disables further trim-forces until a landed
225
+ * compaction posts under the threshold again. Like `force`, this never bypasses the structural
226
+ * floor (no valid cut point ⇒ `{compacted:false}`).
227
+ */
66
228
  forceUnderThreshold?: boolean;
229
+ /**
230
+ * Working-file attachments (LONGRUN-2, CC-compact parity review 2026-06-12): after a successful
231
+ * summary, re-read up to `maxFiles` of the files the summarized region MODIFIED (from
232
+ * CompactionDetails.modifiedFiles) and append their current on-disk contents to the summary text.
233
+ * Why: LONGRUN-2 measured the model spending ≈2.3 extra read calls per compaction re-fetching
234
+ * files it had just lost — each one a full request round-trip at post-compaction context size.
235
+ * CC ships the same idea ("attachments", ≤5 files × ~5k tokens). Bounded: per-file char cap plus
236
+ * a total cap that self-scales to ~15% of the model window, so small windows never drown in
237
+ * attachments; the §25.2 freedTokens measurement naturally accounts for the added mass (the
238
+ * anti-thrash floor stays truthful). Reader failures skip the file (best-effort, never fails the
239
+ * compaction). Absent (default) = current behavior, paths-only.
240
+ * Pick order (design/71 P2-① resolved the LONGRUN-2b limitation): `maxFiles` picks the most
241
+ * RECENTLY touched files first (`CompactionDetails.modifiedFilesByRecency`, recency threaded
242
+ * through the engine fileOps accumulator); alphabetical `modifiedFiles` remains the fallback for
243
+ * details persisted before the field existed.
244
+ */
67
245
  workingFileAttachments?: {
246
+ /** Read a task workspace file; null/throw = skip it. Wired by the Runner from the task's ExecutionEnv. */
68
247
  readFile: (path: string) => Promise<string | null>;
248
+ /** Max modified files to attach. Default 3. */
69
249
  maxFiles?: number;
250
+ /** Per-file char cap (≈4 chars/token). Default 16_000 (~4k tokens). */
70
251
  maxCharsPerFile?: number;
252
+ /**
253
+ * Blackboard 2026-07-03 (CC-parity selection set): the files the task has READ, most recent
254
+ * first (CC 198's post-compact restore sorts readFileState by timestamp — the read set is wider
255
+ * than the modified set and includes reference files the model consulted). When provided and
256
+ * non-empty it WINS over `modifiedFilesByRecency`; absent/empty falls back to the modified set
257
+ * (the pre-2026-07-03 behavior, and the right answer for callers with no read tracking).
258
+ */
71
259
  recentlyReadFiles?: () => string[];
260
+ /**
261
+ * RB-197② (CC `compact.ts:1415-1463` `shouldExcludeFromPostCompactRestore` parity): paths already
262
+ * re-seeded through a DIFFERENT channel every turn (the deployment's declared instruction files —
263
+ * `ProjectMemoryLoad.instructionSources`, e.g. a project/user CLAUDE.md) are excluded from the
264
+ * `recentlyReadFiles`/fallback candidate set — re-attaching them here would just duplicate content
265
+ * the system-prompt lane already carries. A plain path list, not a hardcoded filename: core still
266
+ * never decides what counts as "an instruction file" on its own (types.ts's own seam rule) — it
267
+ * only trusts what the deployment already declared.
268
+ */
72
269
  instructionSourcePaths?: ReadonlyArray<string>;
270
+ /**
271
+ * RB-197②(独立复审 + codex 命中,已修): `recentlyReadFiles()` yields CANONICAL keys (resolveKey
272
+ * output — the same coordinate `ReadFileState` is keyed in), but `instructionSourcePaths` and the
273
+ * kept-tail scan inside `maybeCompact` (which reads raw tool-call arguments via
274
+ * `extractFileOpsFromMessage`) do NOT share that coordinate — a model-typed relative path and its
275
+ * canonical form are different strings, so a plain `Set.has()` between them silently never matches
276
+ * even for the identical file. Optional callback (present exactly when there's a containment root
277
+ * to resolve against — i.e. hands enabled) that canonicalizes a raw path the SAME way the hands
278
+ * toolkit does, so `maybeCompact` can normalize every side of the comparison before excluding.
279
+ * Best-effort: a throw/rejection is caught by the caller and treated as "leave this one path
280
+ * unnormalized" (a safe direction — worst case is a missed exclusion, not a wrong one). Absent
281
+ * when there is no containment root (hands disabled) — in that regime every path source is
282
+ * ALREADY in the same raw coordinate, so the fallback exact-string comparison is already correct.
283
+ */
73
284
  normalizePath?: (raw: string) => Promise<string>;
285
+ /**
286
+ * RB-197②(codex 交叉复审命中,已修) — a kept-tail Read tool-CALL's mere presence does not prove the
287
+ * file's real content is visible there: its toolRESULT may be a dedup stub ("unchanged since you
288
+ * last read it…") whose ORIGINAL full transmission sits in the summarized prefix THIS compaction is
289
+ * about to cut away — preserving read-state for such a path would leave both the kept tail and the
290
+ * next read pointing at content that is nowhere in context (RB-197①'s failure, reintroduced one hop
291
+ * removed). Optional predicate (present exactly when the caller's Read tool actually emits a
292
+ * recognizable stub marker) so `maybeCompact` can require at least one SUBSTANTIVE kept-tail Read
293
+ * result before trusting a path as genuinely visible; absent ⇒ every non-error kept-tail Read is
294
+ * trusted (the pre-this-fix behavior — still safe when the caller has no stub concept at all).
295
+ */
74
296
  isDedupStubResult?: (resultText: string) => boolean;
75
297
  };
298
+ /**
299
+ * RB-197: fires ONCE per LANDED compaction (after `appendCompaction` committed the new baseline), with the
300
+ * files that were attached WHOLE (untruncated) into the summary. The Runner wires this to the read-state
301
+ * invalidation (`applyCompactionToReadFileState`): the summary just replaced the history the read-dedup
302
+ * stubs point at, so stale entries must drop and the re-attached content re-registers. Kept OUTSIDE
303
+ * `workingFileAttachments` deliberately — the invalidation is owed even when attachments are disabled
304
+ * (an empty array then). Best-effort: a throwing callback must not fail the landed compaction.
305
+ *
306
+ * RB-197②(codex 命中,已修;独立复审第二轮又命中一条同族缺口,已修) `preserveReadState`:
307
+ * canonical-coordinate paths (same shape as `normalizePath`'s output) whose read-state entry must
308
+ * survive the compaction's clear even though they are NOT in `attachedComplete` — every file
309
+ * `maybeCompact` deliberately skipped re-attaching, for EITHER exclusion reason (kept-tail-visible,
310
+ * or matches a declared instruction source). Without this the read-state clear (see
311
+ * `applyCompactionToReadFileState`) would wipe them anyway, defeating both the read-before-edit gate
312
+ * and the next read's dedup for exactly the files this optimization was supposed to leave untouched.
313
+ * (The instruction-source half of this was missing in an earlier revision: `instructionSources` and
314
+ * `seededFiles` are independent `ProjectMemoryLoad` fields — a path can be declared in the former
315
+ * without ever being seeded via the latter, so an instruction-excluded file the model explicitly Read
316
+ * has a live, non-seeded entry that needs the SAME preservation as a kept-tail one.)
317
+ */
76
318
  onApplied?: (attachedComplete: ReadonlyArray<{
77
319
  path: string;
78
320
  content: string;
79
321
  }>, preserveReadState?: ReadonlyArray<string>) => void;
322
+ /**
323
+ * Fixed per-request prompt overhead (system prompt + tool schemas, in tokens), applied ONLY in the
324
+ * anchor-less regime (design/64 §26.7, search [91] fourth candidate): when no assistant in the
325
+ * visible history carries real usage (custom Brain implementations that don't report usage), the
326
+ * chars/4 fallback counts MESSAGES only and is blind to this overhead — the threshold would compare
327
+ * apples to oranges and under-trigger. When usage-anchored, the anchor IS the provider-billed input
328
+ * (system+tools included), so the overhead is already in and this is not added.
329
+ */
80
330
  overheadTokens?: number;
331
+ /**
332
+ * design/84 Seam C — compact-boundary COST optimization (data-gated). Fidelity is already achieved by
333
+ * the iterative-merge UPDATE_SUMMARY path (compaction.ts); the only remaining cost is one LLM call per
334
+ * boundary. A `summaryProvider` lets a caller supply a summary WITHOUT an LLM call: when it returns a
335
+ * NON-EMPTY string, that string is reused verbatim as the summary (the real `generateSummary` LLM call
336
+ * is skipped, `reused:true`). Returning `null`/`undefined`/an empty-or-whitespace string falls back to
337
+ * the existing `generateSummary` path — IDENTICAL to current behavior. **Absent (default) = no behavior
338
+ * change whatsoever**: the LLM path runs byte-for-byte as before.
339
+ *
340
+ * THIS IS A THIN SEAM ONLY: no provider is implemented in core. The provider implementation is gated on
341
+ * design/82 cost-per-truly-correct data (§3/§7-5). Reuse is guarded against degradation (see below).
342
+ *
343
+ * Inputs:
344
+ * - `messagesToSummarize`: the message range that would be summarized this boundary.
345
+ * - `previousSummary`: the prior compaction's summary (present on the UPDATE/iterative-merge path).
346
+ * - `modifiedFiles`: files the summarized range modified, newest-first (same source the working-file
347
+ * attachments use), so a provider can decide whether the reused summary is still representative.
348
+ */
81
349
  summaryProvider?: (input: {
82
350
  messagesToSummarize: AgentMessage[];
83
351
  previousSummary?: string;
84
352
  modifiedFiles: string[];
85
353
  }) => string | null | undefined | Promise<string | null | undefined>;
354
+ /**
355
+ * design/84 Seam C reuse guard (c): after this many CONSECUTIVE provider-reuse compactions, the next
356
+ * compaction is FORCED through the real `generateSummary` LLM path even if the provider would hit — this
357
+ * bounds summary drift from indefinite reuse. The caller owns the counter via {@link onCompaction}
358
+ * (`reused`) and feeds it back via this option; core treats `summaryProvider` as if absent for that one
359
+ * boundary when `consecutiveProviderReuse >= maxConsecutiveProviderReuse`. Default `3` (CC parity).
360
+ * `0`/undefined with no `consecutiveProviderReuse` = provider always consulted (no forced refresh).
361
+ */
86
362
  maxConsecutiveProviderReuse?: number;
363
+ /**
364
+ * design/84 Seam C reuse guard (c) — counter input: how many consecutive provider-reuse compactions have
365
+ * happened so far (caller-tracked from {@link onCompaction}'s `reused`). When this reaches
366
+ * `maxConsecutiveProviderReuse`, the provider is bypassed for this one boundary to force a real summary.
367
+ */
87
368
  consecutiveProviderReuse?: number;
369
+ /**
370
+ * design/84 Seam C — pure observer fired AFTER a successful compaction (never on a no-op/under-threshold
371
+ * return). Does NOT alter control flow. `reused` distinguishes a provider-supplied summary from a real
372
+ * LLM `generateSummary`. `freedTokens` is the §25.2 structural delta (may be ~0 when a reused summary
373
+ * frees little — see reuse guard (b): such a compaction does NOT raise the caller's anti-thrash floor).
374
+ */
88
375
  onCompaction?: (info: {
89
376
  messagesCompacted: number;
90
377
  freedTokens: number;
91
378
  tokensBefore: number;
92
379
  reused: boolean;
93
380
  }) => void;
381
+ /**
382
+ * design/134 §3.2 — which trigger this pass runs under, threaded into the pre/postCompact callback
383
+ * contexts and driving the block semantics: "auto" (threshold/boundary, the default) | "manual"
384
+ * (/compact) | "forced" (promptTooLong recovery and trim-pressure propagation — the compaction is
385
+ * not optional there, so a preCompact `block` is IGNORED on "forced").
386
+ */
94
387
  trigger?: "auto" | "manual" | "forced";
388
+ /**
389
+ * design/134 (CC PreCompact parity) — fired AFTER the trigger gate and a CONFIRMED valid cut point
390
+ * (so every invocation corresponds to a compaction that would actually happen), BEFORE the
391
+ * provider/summary call. `block` skips this compaction on auto/manual (`{compacted:false,
392
+ * blocked:true}`); ignored on "forced". `additionalInstructions` is APPENDED to the summarization
393
+ * instructions (never replaces them). A throw is swallowed on every path — treated as
394
+ * no-block/no-instructions (the caller's wrapper owns tracing; an observer bug must never feed the
395
+ * caller's breaker or kill PTL recovery).
396
+ */
95
397
  preCompact?: Hooks["preCompact"];
398
+ /**
399
+ * design/134 (CC PostCompact parity) — observe-only, fired after the compaction LANDED
400
+ * (appendCompaction done, post measurement taken). A throw is swallowed (same isolation contract
401
+ * as {@link onCompaction}: the compaction already succeeded).
402
+ */
96
403
  postCompact?: Hooks["postCompact"];
404
+ /**
405
+ * MF-18 修② ([496]③) — observe-only: fired when a summary call's serialized conversation INPUT was
406
+ * truncated to fit the compaction model's context window (the ~300K-session shape that previously
407
+ * guaranteed a provider prompt-too-long throw at every boundary). The caller bridges it to the
408
+ * `compaction.input_truncated` trace frame (fidelity disclosure). Fired BEFORE the summary call, so
409
+ * it reports truncation even when the attempt later fails.
410
+ */
97
411
  onInputTruncated?: (info: {
98
412
  label: "history" | "turn_prefix";
99
413
  droppedChars: number;
100
414
  keptChars: number;
101
415
  }) => void;
416
+ /**
417
+ * RB-402 ([2132]③c/[2133]) — the design/36 ToolSearch activation set LIVE at this pass (the
418
+ * runner threads `[...prepared.activeTools]` on all three lanes: boundary, PTL recovery, finish).
419
+ * Persisted into the landed compaction entry's details (`CompactionDetails.activeTools`) so the
420
+ * NEXT task boundary's re-derivation — whose transcript source (ToolSearch toolCall parts) this
421
+ * compaction just replaced with prose — re-seeds from a structured carrier instead (the
422
+ * checkpoint seed's `resume.seed.activeTools` sibling; prepare-task consumes it). Absent or
423
+ * empty ⇒ no key is written, byte-identical to pre-RB-402 entries.
424
+ */
102
425
  activeTools?: ReadonlyArray<string>;
103
426
  }
427
+ /**
428
+ * Compact the session in place when context usage exceeds the threshold.
429
+ *
430
+ * Two call sites, same policy: the within-task `turn_boundary` hook (design/64 §25 (A) — after the
431
+ * session flush, before the next request's context rebuild) and `finish()` at task end. The caller
432
+ * must ensure no session write is in flight (both sites are between model requests, post-flush).
433
+ *
434
+ * THROWS (council §26.6 #6 contract note): a summarization failure — including a summary that came
435
+ * back EMPTY after the analysis-block strip (a real LLM call was burned, history left untouched) —
436
+ * is thrown, not swallowed; callers are expected to catch, count it toward the §17.4 breaker, and
437
+ * surface it via onError. A legitimate nothing-to-compact (under threshold/floor, no cut point)
438
+ * returns `{compacted:false}` quietly.
439
+ * Honors an optional cheaper `compactionModel` without mutating the harness's active model.
440
+ * Zero-config: uses DEFAULT_COMPACTION_SETTINGS unless overridden; settings pathological for the
441
+ * model's window are repaired via {@link sanitizeCompactionSettings}.
442
+ */
104
443
  export declare function maybeCompact(opts: MaybeCompactOptions): Promise<{
105
444
  compacted: boolean;
445
+ /** design/134: set (with `compacted:false`) when a preCompact callback blocked this compaction
446
+ * (auto/manual triggers only — never on "forced"). NOT a failure: the caller must not count it
447
+ * toward the compaction breaker; the next boundary consults the callback again. */
106
448
  blocked?: boolean;
449
+ /** MF-18 修① ([496]③): set (with `compacted:false`) when compaction is DISABLED by settings
450
+ * (`enabled:false`) — the request can never be honored this run. Lets the caller resolve a manual
451
+ * /compact with the honest `"disabled"` outcome (and trace frame) instead of a structural noop. */
107
452
  disabled?: boolean;
453
+ /** RB-398-b ([2105] ANG-5): set (with `compacted:false`) when the pass PASSED the trigger gate
454
+ * (natural or forced) but found nothing to summarize — no valid cut point / empty history. Was
455
+ * previously indistinguishable from the quiet under-threshold return, so a forced pass with
456
+ * nothing to do looked identical to one that never wanted to run; the caller's outcome event
457
+ * (`compaction_outcome{outcome:"noop"}`) reads this flag. */
108
458
  noop?: true;
109
459
  tokensBefore?: number;
110
460
  freedTokens?: number;
111
461
  triggerTokens?: number;
462
+ /** P-13: post-compaction context size in the SAME coordinate as `triggerTokens` (estimate + anchor-less
463
+ * overhead). The caller's §25.2 regrowth floor = `postTriggerTokens × factor`, single-coordinate — never
464
+ * `triggerTokens − freedTokens` (which mixed a usage-anchored trigger with a chars/4 freed delta). */
112
465
  postTriggerTokens?: number;
466
+ /** design/99 MF-18 `preserved_segment`: the session-tree entry id where the KEPT TAIL begins (the floor of
467
+ * the surviving history after this compaction). Surfaced so the `compacted` wire event can carry it (CC
468
+ * `SDKCompactBoundary.preserved_segment` parity); a consumer maps it to wire messages via its eventId↔entryId
469
+ * map (the same one service keeps for resumeAt). Set only when `compacted` is true. */
113
470
  firstKeptEntryId?: string;
471
+ /** design/84 Seam C: true when this compaction reused a `summaryProvider` summary (no LLM call). */
114
472
  reused?: boolean;
473
+ /** Blackboard 2026-07-03 (ask ②): the working files re-read into the summary, in attachment order —
474
+ * surfaced so the `compacted` wire event carries them and a shell renders CC's post-compact
475
+ * `Read {path} (…)` cards. Set only when `compacted` is true and attachments were added. */
115
476
  attachedFiles?: Array<{
116
477
  path: string;
117
478
  chars: number;
118
479
  truncated: boolean;
119
480
  }>;
481
+ /** design/123 D4: true when the NATURAL gate fired (est ≥ max(threshold, minTokens) — no force was
482
+ * needed); false on a forced landing (`force`/`forceUnderThreshold`). Set only when `compacted`. */
120
483
  naturalTrigger?: boolean;
484
+ /** design/123 D4: whether the post-compaction size (`postTriggerTokens` coordinate) is STILL over the
485
+ * sanitized auto threshold — the "couldn't compact it down" signal {@link nextTrimForceBackoff}
486
+ * consumes. Set only when `compacted` and the post measurement succeeded. */
121
487
  postOverThreshold?: boolean;
488
+ /** TB telemetry B4 (service [397]): wall time of the whole compaction pass (context build → summary
489
+ * call → history rewrite → post measurement). Set only when `compacted` — the `compacted` wire event
490
+ * carries it so a consumer sees what a boundary pause actually cost. */
122
491
  durationMs?: number;
492
+ /** 压缩子阶段遥测 (1.283 批 G 观察项 / design/145 §6 正交后续批 — TB 观测到整段 ~55s 停顿,需要
493
+ * 子阶段读数支撑归因): wall-time split of THIS landed pass, in the same Date.now() coordinate as
494
+ * `durationMs`. `prepareMs` = context build → trigger math → cut-point selection → hooks/provider
495
+ * consult → clamp dry run + 门A/门B gating (everything before the summary call). `summaryMs` = the
496
+ * summary LLM leg (`compact()`: serialization → clamp → completion, incl. any PTL retries) — ABSENT
497
+ * on a provider-reuse pass (no LLM call happened; its provider consult time sits in `prepareMs`).
498
+ * `persistMs` = working-file attachments → session rewrite (`appendCompaction`) → post measurement →
499
+ * observers. The phases tile the pass exactly: prepareMs + (summaryMs ?? 0) + persistMs ===
500
+ * durationMs. `ptlRetries` = reactive prompt-too-long retries burned inside this pass's summary
501
+ * call(s) (both split-turn legs accumulate into the one counter; 0 on provider reuse). Set only when
502
+ * `compacted`. Exposure path note: runtask deliberately NOT touched this batch — the bridge to the
503
+ * `compaction.phase_timings` trace frame (trace.ts, defined-not-yet-emitted) is a follow-up wiring
504
+ * batch that adds an additive passthrough next to runtask's existing
505
+ * `...(comp.durationMs !== undefined ? { durationMs: comp.durationMs } : {})` spread. */
123
506
  phaseDurations?: CompactionPhaseDurations;
507
+ /** service [398] C3: set (with `compacted:false`) when the pass was over the auto threshold but the
508
+ * anti-thrash floor (`minTokens`) suppressed it — the caller bridges this to `compaction.suppressed`. */
124
509
  suppressedByFloor?: {
125
510
  estTokens: number;
126
511
  floor: number;
127
512
  };
513
+ /**
514
+ * Set (with `compacted:false`) when the trigger predicate could not be EVALUATED at all: the model
515
+ * declares no usable autocompact window (non-finite or <= 0), so `shouldCompact` refuses on the
516
+ * sentinel and `contextUsage` is honestly absent.
517
+ *
518
+ * This is a different state from "under the threshold", and it used to be indistinguishable from it:
519
+ * both returned a bare `{compacted:false}` with no `contextUsage`, no trace and no error, so a
520
+ * deployment whose model config lost its window had auto-compaction permanently disabled and the
521
+ * only notification was that nothing ever happened. The context still grows, the provider still
522
+ * eventually refuses the request, and the operator has nothing to read. The caller bridges this to
523
+ * a once-per-task host disclosure — silence is the defect here, so a noisy line is the fix.
524
+ *
525
+ * `estTokens` is the size this pass DID manage to estimate (structural + prompt overhead when no
526
+ * usage anchor is available), so the disclosure can say how big the context already is even though
527
+ * it cannot say how big the window is.
528
+ */
128
529
  unevaluableWindow?: {
129
530
  estTokens: number;
531
+ /** WHICH of the three window fields the `??` precedence actually selected. A defined-but-unusable
532
+ * higher-precedence field (`autoCompactTokens: 0`) shadows a healthy lower one, so "no window is
533
+ * declared" is the wrong story on that path — the caller reports THIS field, not all three. */
130
534
  windowField: "autoCompactTokens" | "contextTokens" | "contextWindow";
535
+ /** The unusable value that field carried, when it carried one at all (absent = nothing declared). */
131
536
  windowValue?: number;
132
537
  modelId?: string;
133
538
  };
539
+ /**
540
+ * RB-126 / blackboard [1669]⑥ (2026-07-25, server's ask): the trigger inputs THIS pass used, reported on
541
+ * EVERY return path — including the ordinary "nothing to do" one. A consumer rendering "how full is the
542
+ * context" was otherwise forced to re-derive the numerator itself, and a re-derivation that drifts from
543
+ * the engine's own is the projection-antipattern this repo keeps paying for: the displayed percentage
544
+ * would disagree with when compaction actually fires.
545
+ *
546
+ * `usedTokens` is the exact first argument to `shouldCompact` (usage-anchored when the anchor is fresh,
547
+ * structural + fixed prompt overhead otherwise — see the derivation above). `windowTokens` is the
548
+ * AUTOCOMPACT window (`autoCompactTokens` when the model declares one, else its context window), NOT
549
+ * necessarily the physical request window. `compactAtTokens` is the threshold those two are compared
550
+ * against, so `usedTokens > compactAtTokens` is precisely the engine's own trigger predicate.
551
+ */
134
552
  contextUsage?: {
135
553
  usedTokens: number;
136
554
  windowTokens: number;
137
555
  compactAtTokens: number;
138
556
  };
557
+ /** design/145 §3: this pass's summary call FELL BACK from the independent compaction model to the
558
+ * main model (window safety). Rides the `compacted` wire event as an additive field. */
139
559
  modelFallback?: true;
560
+ /** design/145 §3: why the fallback happened — "window" is the only reason today. */
140
561
  fallbackReason?: "window";
562
+ /** design/145 §3: the dry-run truncation ratio of a pass whose summary input WAS (or would be)
563
+ * clamp-truncated on the small model — set when a gate denied the fallback OR the ratio was
564
+ * within tolerance but non-zero. */
141
565
  clampedRatio?: number;
566
+ /** design/145 §3: "budget" = the gate denied the fallback; "tolerance" = within-tolerance
567
+ * ordinary truncation (disclosed, not silent). */
142
568
  clampReason?: "budget" | "tolerance";
143
569
  }>;
570
+ /**
571
+ * design/123 D4 (r5) — trim-force BACKOFF transition (pure; the run-scoped bit lives in the caller).
572
+ * Spiral protection replacing the §25.2 floor's role on the trim-force path: trim pressure re-arms
573
+ * every request while the transcript is oversized, so an unconditional force would burn a summary
574
+ * call at every boundary when summaries CANNOT shrink the context (the LONGRUN-1b incompressible
575
+ * shape). The invariant: trim-force is permitted only while the LATEST landed compaction proved it
576
+ * can bring the context back under the threshold (or no compaction has landed yet). Transitions,
577
+ * evaluated after each maybeCompact result:
578
+ * 1. no compaction landed → state unchanged (a structural no-op proves nothing either way);
579
+ * 2. a landed compaction with `postOverThreshold` → "压不动": BACKOFF ON — compaction demonstrably
580
+ * cannot reach under-threshold, so forcing more of them only burns summary calls; the §25.2
581
+ * floor policy takes back over (natural triggers are never gated by this bit);
582
+ * 3. a landed compaction that posted UNDER the threshold → summaries compress again: BACKOFF OFF
583
+ * (this is how the natural floor-crossing compaction of design/123 D4's reset clause re-enables
584
+ * the trim-force — its healthy landing posts under threshold);
585
+ * 4. post measurement unavailable → state unchanged (never flip on missing evidence);
586
+ * 5. (COMPACTION-LIVE-AUDIT D-1, evaluated BEFORE rule 3) a TRIM-FORCED landing with
587
+ * `freedTokens ≤ 0` → negative-yield: BACKOFF ON. The trim layer deceives the usage-anchored
588
+ * estimate down into the sawtooth trough (live: est 18807 on a ~55k session), the forced pass
589
+ * finds little compressible history, and summary + working-file attachments make the transcript
590
+ * LARGER (live: 18807→44609, 12679→35214). `freedTokens` is the structural pre/post delta
591
+ * (clamped ≥0, so ≤0 means "freed nothing") — orthogonal to rule 2/3's threshold test, which
592
+ * misses this shape because the bloated post (44609) can still sit UNDER the threshold (44800),
593
+ * so rule 3 alone would re-enable the force and repeat the negative-yield pass every boundary.
594
+ * SEMA-ONLY DEFENSE, not a CC port: CC's full compact keeps tail 0 and monotonically shrinks
595
+ * (capture §A4), and CC has no request-layer trim, so this regime cannot exist there — it is a
596
+ * derived interaction of our trim seam × keep-tail × attachment mass. Scoped to trim-forced
597
+ * passes only (`trimForced`), so Seam C reused-summary landings (freed≈0 by design) on the
598
+ * natural/manual paths never trip it. Release path unchanged: backoff gates only the FORCE, a
599
+ * later natural landing that posts under threshold (rule 3, non-trim-forced) turns it back off.
600
+ */
144
601
  export declare function nextTrimForceBackoff(prev: boolean, comp: {
145
602
  compacted: boolean;
146
603
  postOverThreshold?: boolean;
147
604
  freedTokens?: number;
148
605
  naturalTrigger?: boolean;
149
606
  }, trimForced?: boolean): boolean;
607
+ /** design/119 S3 (CC 198 rapid_refill_breaker): mutable per-task refill tracking state. */
150
608
  export interface RapidRefillState {
151
609
  lastCompactionTurn: number;
152
610
  count: number;
153
611
  }
612
+ /** Fresh tracking state (no compaction seen yet). */
154
613
  export declare function createRapidRefillState(): RapidRefillState;
614
+ /**
615
+ * design/119 S3 (CC 2.1.198 rapid_refill_breaker, :229717/:476338): record that a compaction just
616
+ * happened at `turn` and report whether the thrash breaker should TRIP. A compaction landing within
617
+ * `minGapTurns` of the previous one is a "rapid refill"; `tripAt` consecutive rapid refills = the
618
+ * context is dominated by incompressible content and further compaction only burns summary calls.
619
+ * CC terminates the task; sema's caller (runtask) deviates conservatively — it opens the existing
620
+ * compaction breaker (no more compaction this task) and lets budget/PTL/turn limits end the run.
621
+ */
155
622
  export declare function recordCompactionAndCheckRapidRefill(state: RapidRefillState, turn: number, minGapTurns?: number, tripAt?: number): boolean;