@sema-agent/core 5.19.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 (329) hide show
  1. package/CHANGELOG.md +102 -4
  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/roster-store.js +3 -0
  13. package/dist/agents/send-message-tool.d.ts +92 -0
  14. package/dist/agents/session-util.d.ts +5 -0
  15. package/dist/agents/subagent-steps.d.ts +66 -0
  16. package/dist/agents/subagent.d.ts +600 -0
  17. package/dist/agents/suspend-guard.d.ts +29 -0
  18. package/dist/agents/teacher.d.ts +75 -0
  19. package/dist/agents/team.d.ts +120 -1
  20. package/dist/agents/tool-filter.d.ts +34 -0
  21. package/dist/agents/verify.d.ts +198 -0
  22. package/dist/bench/metrics.d.ts +455 -0
  23. package/dist/brain/anthropic.d.ts +30 -0
  24. package/dist/brain/circuit-breaker.d.ts +33 -0
  25. package/dist/brain/circuit-breaker.js +14 -3
  26. package/dist/brain/context-overflow.d.ts +60 -3
  27. package/dist/brain/degrading.d.ts +67 -0
  28. package/dist/brain/errors.d.ts +42 -0
  29. package/dist/brain/failover.d.ts +15 -0
  30. package/dist/brain/media-degrade.d.ts +39 -0
  31. package/dist/brain/model-presets.d.ts +31 -0
  32. package/dist/brain/open-responses.d.ts +19 -0
  33. package/dist/brain/openai.d.ts +46 -0
  34. package/dist/brain/reasoning.d.ts +106 -1
  35. package/dist/brain/repetition.d.ts +83 -0
  36. package/dist/brain/request-params.d.ts +56 -0
  37. package/dist/brain/retry.d.ts +46 -0
  38. package/dist/brain/routing.d.ts +12 -0
  39. package/dist/brain/status-sink.d.ts +30 -1
  40. package/dist/brain/stream-engine.d.ts +147 -0
  41. package/dist/brain/stream-shared.d.ts +34 -0
  42. package/dist/brain/terminal-cause.d.ts +31 -0
  43. package/dist/brain/timeout.d.ts +108 -0
  44. package/dist/brain/timeout.js +11 -0
  45. package/dist/brain/tool-call-id.d.ts +20 -0
  46. package/dist/brain/tool-call-repair.d.ts +13 -0
  47. package/dist/config/catalog.d.ts +47 -0
  48. package/dist/config/defaults.d.ts +33 -0
  49. package/dist/core/a2a-task-state.d.ts +53 -0
  50. package/dist/core/a2a.d.ts +51 -0
  51. package/dist/core/arg-summary.d.ts +62 -0
  52. package/dist/core/ask-question.d.ts +272 -2
  53. package/dist/core/auto-compaction.d.ts +467 -0
  54. package/dist/core/auto-compaction.js +20 -6
  55. package/dist/core/auto-mode-prompt-assets.d.ts +8 -0
  56. package/dist/core/auto-mode-prompt.d.ts +27 -0
  57. package/dist/core/auto-mode.d.ts +54 -3
  58. package/dist/core/auto-promote.d.ts +100 -0
  59. package/dist/core/background-agent-store.d.ts +293 -0
  60. package/dist/core/background-agent-store.js +5 -0
  61. package/dist/core/background-shell.d.ts +110 -0
  62. package/dist/core/cache-break-detector.d.ts +34 -0
  63. package/dist/core/canonical-json.d.ts +57 -0
  64. package/dist/core/checkpoint-store.d.ts +1574 -16
  65. package/dist/core/compliance.d.ts +30 -0
  66. package/dist/core/consolidate-scope.d.ts +75 -0
  67. package/dist/core/context-edit.d.ts +99 -0
  68. package/dist/core/context-guard.d.ts +46 -0
  69. package/dist/core/exec-gate.d.ts +44 -0
  70. package/dist/core/exec-output-tail.d.ts +61 -0
  71. package/dist/core/file-snapshot-store.d.ts +104 -0
  72. package/dist/core/fs-write-gate-policy.d.ts +36 -0
  73. package/dist/core/git-worktree-env.d.ts +31 -0
  74. package/dist/core/governance-codes.d.ts +19 -0
  75. package/dist/core/hooks.d.ts +609 -1
  76. package/dist/core/human-input-projection.d.ts +37 -0
  77. package/dist/core/human-input-projection.js +13 -0
  78. package/dist/core/image-downsample.d.ts +74 -0
  79. package/dist/core/locked-config.d.ts +37 -0
  80. package/dist/core/lsp-diagnostics.d.ts +77 -0
  81. package/dist/core/lsp-protocol.d.ts +29 -0
  82. package/dist/core/lsp-session.d.ts +60 -1
  83. package/dist/core/lsp.d.ts +150 -1
  84. package/dist/core/mailbox-store.d.ts +57 -0
  85. package/dist/core/mailbox-store.js +2 -0
  86. package/dist/core/mcp.d.ts +385 -0
  87. package/dist/core/mcp.js +58 -11
  88. package/dist/core/media-byte-cap.d.ts +21 -0
  89. package/dist/core/memory-admission.d.ts +71 -0
  90. package/dist/core/memory-engine/content-origin.d.ts +64 -0
  91. package/dist/core/memory-engine/data-plane.d.ts +43 -0
  92. package/dist/core/memory-engine/dual-root.d.ts +24 -0
  93. package/dist/core/memory-engine/engine.d.ts +230 -0
  94. package/dist/core/memory-engine/engine.js +103 -35
  95. package/dist/core/memory-engine/file-backend.d.ts +155 -0
  96. package/dist/core/memory-engine/frontmatter.d.ts +16 -0
  97. package/dist/core/memory-engine/layout.d.ts +217 -0
  98. package/dist/core/memory-engine/memory-backend-contract.d.ts +12 -0
  99. package/dist/core/memory-engine/migrate.d.ts +9 -0
  100. package/dist/core/memory-engine/scan.d.ts +12 -0
  101. package/dist/core/memory-engine/scope-contract.d.ts +61 -1
  102. package/dist/core/memory-engine/sync-client.d.ts +87 -0
  103. package/dist/core/memory-engine/sync.d.ts +60 -0
  104. package/dist/core/memory-engine/tools.d.ts +41 -0
  105. package/dist/core/memory-engine/types.d.ts +188 -0
  106. package/dist/core/memory-recall.d.ts +141 -0
  107. package/dist/core/memory-vector.d.ts +20 -0
  108. package/dist/core/memory.d.ts +458 -0
  109. package/dist/core/message-utils.d.ts +6 -0
  110. package/dist/core/oracle-isolation.d.ts +69 -0
  111. package/dist/core/permission-rule-consent.d.ts +138 -0
  112. package/dist/core/permission-rule-model.d.ts +122 -0
  113. package/dist/core/permission-rule-store.d.ts +119 -3
  114. package/dist/core/permission-rules.d.ts +87 -1
  115. package/dist/core/present-plan-tool.d.ts +20 -0
  116. package/dist/core/pricing.d.ts +26 -0
  117. package/dist/core/property-harness.d.ts +86 -0
  118. package/dist/core/protocol-naming.d.ts +38 -0
  119. package/dist/core/protocol-table.d.ts +61 -0
  120. package/dist/core/push-queue.d.ts +1 -0
  121. package/dist/core/remote-env.d.ts +383 -1
  122. package/dist/core/retention-policy.d.ts +40 -0
  123. package/dist/core/retention-policy.js +21 -0
  124. package/dist/core/retention.d.ts +51 -0
  125. package/dist/core/roles.d.ts +59 -0
  126. package/dist/core/runner/active-skill-scope.d.ts +34 -0
  127. package/dist/core/runner/assemble-result.d.ts +134 -0
  128. package/dist/core/runner/compaction-call-options.d.ts +97 -1
  129. package/dist/core/runner/grounding-signal.d.ts +10 -0
  130. package/dist/core/runner/image.d.ts +17 -0
  131. package/dist/core/runner/image.js +29 -15
  132. package/dist/core/runner/memory-consolidation.d.ts +60 -0
  133. package/dist/core/runner/prepare-memory.d.ts +59 -0
  134. package/dist/core/runner/prepare-task.d.ts +1011 -2
  135. package/dist/core/runner/prepare-task.js +51 -14
  136. package/dist/core/runner/prompt-suggestions.d.ts +7 -0
  137. package/dist/core/runner/runtask.d.ts +304 -3
  138. package/dist/core/runner/runtask.js +17 -2
  139. package/dist/core/runner/session-file-state-replay.d.ts +49 -0
  140. package/dist/core/runner/session-rule-policy.d.ts +58 -0
  141. package/dist/core/runner/strict-output-schema.d.ts +18 -3
  142. package/dist/core/runner/synthetic-tools.d.ts +113 -0
  143. package/dist/core/runner/teardown-bounded.d.ts +34 -0
  144. package/dist/core/runner/tool-disclosure.d.ts +227 -0
  145. package/dist/core/runner/tool-output-projection.d.ts +6 -0
  146. package/dist/core/runner/turn-attachments.d.ts +634 -0
  147. package/dist/core/runner/usage-accounting.d.ts +32 -0
  148. package/dist/core/runtime.d.ts +9 -0
  149. package/dist/core/safe-notify.d.ts +64 -0
  150. package/dist/core/safety-axis-vocab.d.ts +23 -0
  151. package/dist/core/safety-merge-corpus.d.ts +37 -0
  152. package/dist/core/scheduler.d.ts +121 -0
  153. package/dist/core/secret-env.d.ts +32 -0
  154. package/dist/core/select-model.d.ts +15 -0
  155. package/dist/core/sensitive-path-policy.d.ts +42 -0
  156. package/dist/core/session-policy-store.d.ts +94 -0
  157. package/dist/core/session-reconcile.d.ts +80 -0
  158. package/dist/core/session-store.d.ts +85 -0
  159. package/dist/core/session.d.ts +153 -0
  160. package/dist/core/shared-memory/contract.d.ts +22 -0
  161. package/dist/core/shared-memory/normalize.d.ts +123 -2
  162. package/dist/core/shared-memory/tools.d.ts +14 -0
  163. package/dist/core/shared-memory/types.d.ts +105 -0
  164. package/dist/core/shutdown-debug.d.ts +6 -0
  165. package/dist/core/side-query.d.ts +38 -0
  166. package/dist/core/side-query.js +6 -1
  167. package/dist/core/skill-tool-specifier.d.ts +72 -0
  168. package/dist/core/skills-directory.d.ts +100 -1
  169. package/dist/core/spec-contract.d.ts +89 -0
  170. package/dist/core/store-contracts/background-agent-store-contract.d.ts +31 -0
  171. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +26 -0
  172. package/dist/core/store-contracts/contract-harness.d.ts +20 -0
  173. package/dist/core/store-contracts/contract-kit-version.d.ts +27 -0
  174. package/dist/core/store-contracts/file-snapshot-store-contract.d.ts +8 -0
  175. package/dist/core/store-contracts/mailbox-store-contract.d.ts +42 -0
  176. package/dist/core/store-contracts/tool-result-store-contract.d.ts +13 -0
  177. package/dist/core/strategy-store.d.ts +37 -0
  178. package/dist/core/stub-env.d.ts +7 -0
  179. package/dist/core/surrogate-safe-slice.d.ts +35 -0
  180. package/dist/core/task-notification.d.ts +202 -0
  181. package/dist/core/task-outcome.d.ts +53 -0
  182. package/dist/core/task-registry-agent.d.ts +337 -1
  183. package/dist/core/task-registry-agent.js +2 -0
  184. package/dist/core/task-registry-monitor.d.ts +12 -0
  185. package/dist/core/task-registry-shared.d.ts +540 -0
  186. package/dist/core/task-registry.d.ts +343 -0
  187. package/dist/core/task-registry.js +13 -2
  188. package/dist/core/task-tool-shape.d.ts +44 -0
  189. package/dist/core/tighten-task-spec.d.ts +21 -0
  190. package/dist/core/tool-detach.d.ts +21 -0
  191. package/dist/core/tool-errors.d.ts +131 -0
  192. package/dist/core/tool-errors.js +4 -0
  193. package/dist/core/tool-name-aliases.d.ts +27 -0
  194. package/dist/core/tool-policy.d.ts +555 -0
  195. package/dist/core/tool-policy.js +3 -0
  196. package/dist/core/tool-result-budget.d.ts +32 -0
  197. package/dist/core/tool-result-store.d.ts +174 -1
  198. package/dist/core/tools.d.ts +45 -0
  199. package/dist/core/trace.d.ts +323 -0
  200. package/dist/core/types.d.ts +3859 -2
  201. package/dist/core/untrusted-egress.d.ts +8 -0
  202. package/dist/core/untrusted-text.d.ts +156 -0
  203. package/dist/core/usage-window-store.d.ts +95 -0
  204. package/dist/core/version.d.ts +1 -0
  205. package/dist/core/warm-resume.d.ts +17 -0
  206. package/dist/core/wiring-manifest.d.ts +169 -0
  207. package/dist/core/with-retry.d.ts +24 -0
  208. package/dist/core/workflow-journal-store.d.ts +160 -0
  209. package/dist/core/workflow-run-store-contract.d.ts +25 -0
  210. package/dist/core/workflow-run-store.d.ts +119 -0
  211. package/dist/core/workflow-run-store.js +2 -0
  212. package/dist/engine/compaction/compaction.d.ts +256 -1
  213. package/dist/engine/compaction/utils.d.ts +94 -0
  214. package/dist/engine/execution-env/kill-tree.d.ts +29 -0
  215. package/dist/engine/execution-env/node-execution-env.d.ts +94 -0
  216. package/dist/engine/harness/agent-harness.d.ts +116 -0
  217. package/dist/engine/harness/agent-harness.js +3 -14
  218. package/dist/engine/harness/messages.d.ts +15 -0
  219. package/dist/engine/harness/types.d.ts +464 -2
  220. package/dist/engine/llm/diagnostics.d.ts +4 -0
  221. package/dist/engine/llm/event-stream.d.ts +3 -0
  222. package/dist/engine/llm/index.d.ts +7 -0
  223. package/dist/engine/llm/types.d.ts +500 -3
  224. package/dist/engine/llm/validation.d.ts +3 -0
  225. package/dist/engine/loop/agent-loop.d.ts +87 -2
  226. package/dist/engine/loop/runtime-deps.d.ts +7 -0
  227. package/dist/engine/loop/types.d.ts +424 -0
  228. package/dist/engine/lsp/frame-decoder.d.ts +13 -0
  229. package/dist/engine/lsp/node-lsp-manager.d.ts +107 -0
  230. package/dist/engine/lsp/stdio-lsp-transport.d.ts +7 -0
  231. package/dist/engine/session/import-validate.d.ts +27 -0
  232. package/dist/engine/session/log-digest.d.ts +93 -0
  233. package/dist/engine/session/memory-repo.d.ts +6 -0
  234. package/dist/engine/session/memory-storage.d.ts +2 -0
  235. package/dist/engine/session/session.d.ts +75 -0
  236. package/dist/engine/session/storage-base.d.ts +8 -0
  237. package/dist/fixtures/index.d.ts +36 -0
  238. package/dist/index.d.ts +17 -2
  239. package/dist/index.js +1 -2
  240. package/dist/internal/harness-types.d.ts +6 -0
  241. package/dist/internal/harness.d.ts +11 -0
  242. package/dist/internal/llm.d.ts +6 -0
  243. package/dist/orchestration/builtin-workflows.d.ts +53 -0
  244. package/dist/orchestration/dev-vm-script-runner.d.ts +19 -0
  245. package/dist/orchestration/goal.d.ts +57 -0
  246. package/dist/orchestration/goal.js +3 -0
  247. package/dist/orchestration/run-spec.d.ts +42 -0
  248. package/dist/orchestration/run-spec.js +4 -0
  249. package/dist/orchestration/run-workflow-tool.d.ts +169 -0
  250. package/dist/orchestration/workflow-governance.d.ts +61 -0
  251. package/dist/orchestration/workflow-meta.d.ts +28 -0
  252. package/dist/orchestration/workflow-observe.d.ts +60 -0
  253. package/dist/orchestration/workflow-primitives.d.ts +23 -1
  254. package/dist/orchestration/workflow-sandbox-conformance.d.ts +38 -0
  255. package/dist/orchestration/workflow-script-runner.d.ts +88 -0
  256. package/dist/orchestration/workflow-script-store.d.ts +98 -0
  257. package/dist/orchestration/workflow-size-guideline.d.ts +67 -0
  258. package/dist/orchestration/workflow-types.d.ts +169 -2
  259. package/dist/orchestration/workflow.d.ts +358 -0
  260. package/dist/orchestration/workflow.js +13 -2
  261. package/dist/prompt-assembly/artifact-store.d.ts +33 -0
  262. package/dist/prompt-assembly/artifact.d.ts +25 -0
  263. package/dist/prompt-assembly/assemble.d.ts +20 -0
  264. package/dist/prompt-assembly/composer.d.ts +29 -0
  265. package/dist/prompt-assembly/epoch.d.ts +55 -1
  266. package/dist/prompt-assembly/event-registry.d.ts +35 -0
  267. package/dist/prompt-assembly/explain.d.ts +12 -0
  268. package/dist/prompt-assembly/tool-catalog.d.ts +38 -0
  269. package/dist/prompt-assembly/turn-snapshot.d.ts +40 -0
  270. package/dist/prompt-assembly/types.d.ts +115 -0
  271. package/dist/prompts/coordinator.d.ts +27 -0
  272. package/dist/prompts/default.d.ts +539 -0
  273. package/dist/prompts/simple-sections.d.ts +45 -0
  274. package/dist/prompts/supervisor.d.ts +66 -0
  275. package/dist/scenarios/env.d.ts +28 -0
  276. package/dist/scenarios/full-body.d.ts +50 -0
  277. package/dist/scenarios/scenario-registry.d.ts +60 -0
  278. package/dist/scenarios/teacher-quickstart.d.ts +27 -0
  279. package/dist/server/http.d.ts +17 -0
  280. package/dist/stores/cc/lockfile.d.ts +6 -0
  281. package/dist/stores/cc/mailbox-store.d.ts +8 -0
  282. package/dist/stores/cc/roster-adapter.d.ts +4 -0
  283. package/dist/stores/cc/sidecar-transcript.d.ts +66 -0
  284. package/dist/stores/file/background-agent-store.d.ts +24 -0
  285. package/dist/stores/file/background-agent-store.js +2 -1
  286. package/dist/stores/file/checkpoint-store.d.ts +38 -0
  287. package/dist/stores/file/file-snapshot-store.d.ts +25 -0
  288. package/dist/stores/file/fs-atomic.d.ts +155 -0
  289. package/dist/stores/file/index.d.ts +89 -0
  290. package/dist/stores/file/mailbox-store.d.ts +36 -0
  291. package/dist/stores/file/mailbox-store.js +2 -0
  292. package/dist/stores/file/memory-store.d.ts +82 -0
  293. package/dist/stores/file/permission-rule-store.d.ts +79 -0
  294. package/dist/stores/file/session-policy-store.d.ts +28 -0
  295. package/dist/stores/file/session-store.d.ts +40 -0
  296. package/dist/stores/file/shared-ledger.d.ts +83 -0
  297. package/dist/stores/file/tool-result-store.d.ts +11 -0
  298. package/dist/stores/file/usage-window-store.d.ts +18 -0
  299. package/dist/stores/file/workflow-journal-store.d.ts +100 -0
  300. package/dist/stores/file/workflow-run-store.d.ts +11 -0
  301. package/dist/stores/file/workflow-run-store.js +2 -0
  302. package/dist/tools/fs/bash-readonly-classifier.d.ts +282 -0
  303. package/dist/tools/fs/encoding.d.ts +60 -0
  304. package/dist/tools/fs/fs-bash.d.ts +133 -0
  305. package/dist/tools/fs/fs-pdf.d.ts +28 -0
  306. package/dist/tools/fs/fs-search-tools.d.ts +5 -0
  307. package/dist/tools/fs/fs-shared.d.ts +360 -0
  308. package/dist/tools/fs/fs-write.d.ts +16 -0
  309. package/dist/tools/fs/gh-rate-limit.d.ts +22 -0
  310. package/dist/tools/fs/index.d.ts +79 -0
  311. package/dist/tools/fs/notebook.d.ts +56 -0
  312. package/dist/tools/fs/pdf.d.ts +70 -0
  313. package/dist/tools/fs/pdf.js +8 -2
  314. package/dist/tools/fs/repo-map.d.ts +10 -0
  315. package/dist/tools/fs/safety.d.ts +376 -0
  316. package/dist/tools/fs/search.d.ts +131 -0
  317. package/dist/tools/loop-tick.d.ts +24 -0
  318. package/dist/tools/monitor.d.ts +55 -0
  319. package/dist/tools/scheduler-tools.d.ts +51 -0
  320. package/dist/tools/sql-adapters.d.ts +18 -0
  321. package/dist/tools/sql.d.ts +25 -0
  322. package/dist/tools/task-list.d.ts +77 -0
  323. package/dist/tools/todo.d.ts +8 -0
  324. package/dist/tools/web.d.ts +184 -0
  325. package/dist/tools/web.js +32 -5
  326. package/dist/tools/worktree.d.ts +81 -0
  327. package/package.json +2 -2
  328. package/dist/tools/gitea-issue.d.ts +0 -13
  329. package/dist/tools/gitea-issue.js +0 -75
@@ -3,88 +3,343 @@ import { type AgentCoreCompletionRuntimeDeps } from "../loop/runtime-deps.js";
3
3
  import type { AgentMessage, ThinkingLevel } from "../loop/types.js";
4
4
  import { CompactionError, type Result, type SessionTreeEntry } from "../harness/types.js";
5
5
  import { type FileOperations, type InvokedSkillRetention } from "./utils.js";
6
+ /** File-operation details stored on generated compaction entries. */
6
7
  export interface CompactionDetails {
8
+ /** Files read in the compacted history. */
7
9
  readFiles: string[];
10
+ /** Files modified in the compacted history (sorted, for stable display). */
8
11
  modifiedFiles: string[];
12
+ /**
13
+ * The same modified set ordered most-recently-touched FIRST. Top-N consumers (working-file
14
+ * attachments) pick from here so an alphabetical sort cannot push the file the model actually
15
+ * needs out of the window (the LONGRUN-2b miss). Optional: absent on details persisted before
16
+ * this field existed.
17
+ */
9
18
  modifiedFilesByRecency?: string[];
19
+ /**
20
+ * Invoked-skill retention area (CC 2.1.207 parity): the skills invoked in the COMPACTED range
21
+ * (merged over the previous compaction's retained set), most recent invocation first, already
22
+ * budgeted (per-skill truncation marker + total-area skip semantics — see compaction/utils.ts).
23
+ * Rendered onto the compaction summary message by `buildSessionContext`; kept OUT of the summary
24
+ * string so the summarizer LLM never re-chews skill bodies. Optional: absent on details persisted
25
+ * before this field existed, and omitted when no skill was ever invoked.
26
+ */
10
27
  invokedSkills?: InvokedSkillRetention[];
28
+ /**
29
+ * RB-398-b① ([2105]): CUMULATIVE count of transcript messages this compaction's summary stands in
30
+ * for (this range's folded messages + the previous compaction's carried count). WRITE-side
31
+ * accounting on purpose: deriving the count at render time from the branch walk broke the F3
32
+ * "bounded wake equals full wake" invariant (a floored storage cannot see below the floor, so the
33
+ * two sides disagreed — caught by test/session-floor.test.ts). Drives the summary wrapper's scale
34
+ * disclosure (`buildSessionContext` → `CompactionSummaryMessage.elidedMessages`). Optional-absent
35
+ * on pre-field entries (⇒ no disclosure, byte-identical legacy wrapper).
36
+ */
11
37
  elidedMessages?: number;
38
+ /**
39
+ * RB-398-c (blackboard [2105]): `<persisted-output ref="…">` handles found in the COMPACTED range
40
+ * (merged over the previous compaction's retained set, oldest-first, capped at
41
+ * {@link PERSISTED_OUTPUT_REFS_MAX_ENTRIES} newest). The offloaded blobs outlive the preview that
42
+ * carried their only address — without this channel the handle survived only if the summarizer
43
+ * model happened to copy the string. Rendered as a deterministic summary footer by `compact()`
44
+ * (`formatPersistedOutputRefs`), the same channel `readFiles`/`modifiedFiles` already have.
45
+ * Optional-absent when the range held no offloaded results.
46
+ */
12
47
  persistedOutputRefs?: string[];
48
+ /**
49
+ * RB-402 (blackboard [2132]③c/[2133]): the activated deferred-tool names LIVE at the
50
+ * moment this compaction landed — the design/36 activation state whose transcript carriers
51
+ * (the ToolSearch toolCall parts, and since RB-431 the successful direct calls, that
52
+ * `extractDiscoveredToolNames` replays at every task boundary)
53
+ * this very compaction just replaced with summary prose. Same field shape as the checkpoint
54
+ * seed's `CheckpointState.activeTools` (design/45 §4.bis — the sibling seam that already
55
+ * survives a suspend/resume). Written by the runtask compaction lanes
56
+ * (`MaybeCompactOptions.activeTools` → `maybeCompact`'s appendCompaction, NOT by
57
+ * `prepareCompaction` — the engine layer has no view of the runner's activation Set); consumed
58
+ * by prepare-task's boundary re-derivation via `readCompactionActiveTools` and intersected with
59
+ * the NEXT leg's own deferred registry (a name no longer deferred there is inert).
60
+ * Optional-absent on pre-RB-402 entries and on legs with no activations.
61
+ */
13
62
  activeTools?: string[];
14
63
  }
64
+ /** Generated compaction data ready to be persisted as a compaction entry. */
15
65
  export interface CompactionResult<T = unknown> {
66
+ /** Summary text that replaces compacted history in future context. */
16
67
  summary: string;
68
+ /** Entry id where retained history starts. */
17
69
  firstKeptEntryId: string;
70
+ /** Estimated context tokens before compaction. */
18
71
  tokensBefore: number;
72
+ /** Optional implementation-specific details stored with the compaction entry. */
19
73
  details?: T;
20
74
  }
75
+ /** Compaction thresholds and retention settings. */
21
76
  export interface CompactionSettings {
77
+ /** Enable automatic compaction decisions. */
22
78
  enabled: boolean;
79
+ /** Tokens reserved below the context window for the TRIGGER threshold (threshold = window −
80
+ * reserve). Historically this single knob ALSO seeded the summary legs' output budget
81
+ * (0.8×/0.5×); that second role is now owned by {@link summaryOutputBudgetTokens} (with this
82
+ * field as its default base), so trigger-geometry repairs (`sanitizeCompactionSettings`) can
83
+ * never silently move the summary budget. */
23
84
  reserveTokens: number;
85
+ /**
86
+ * Explicit base for the summary OUTPUT budget (the 0.8× history-leg / 0.5× turn-prefix-leg
87
+ * max_tokens derivation), decoupled from `reserveTokens`' trigger role. Absent ⇒ `reserveTokens`
88
+ * is the base (historical behavior). Either way the effective base is capped by the SUMMARY
89
+ * model's own max output (see {@link summaryOutputBudgetTokens}) — budgeting output the model
90
+ * cannot emit only starves the pre-send input clamp. `sanitizeCompactionSettings` passes this
91
+ * field through untouched: it is not trigger geometry.
92
+ */
24
93
  summaryOutputBudgetTokens?: number;
94
+ /** Approximate recent-context tokens to keep after compaction. */
25
95
  keepRecentTokens: number;
96
+ /** design/145 §1 — window-safety clamp tolerance for an independent (smaller-window) compaction
97
+ * model: when the summarization input would be clamp-truncated by MORE than this ratio (the
98
+ * {@link dryRunSummarizationClamp} judgment), the summary call becomes a candidate to fall back
99
+ * to the MAIN model, which is always window-safe (the content grew inside its window). 0 = any
100
+ * truncation is a fallback candidate; 1 = never fall back (the pre-145 clamp-only behavior, the
101
+ * escape hatch). Default {@link DEFAULT_CLAMP_TOLERANCE}. */
26
102
  clampTolerance?: number;
27
103
  }
104
+ /** design/145 §1 — default `clampTolerance`: head+tail clamping keeps ≤10% mid-section loss BOUNDED
105
+ * AND DISCLOSED (`compaction.clamp_disclosure`), not "lossless" — the honest wording is in the
106
+ * design doc. Above this, a cheap-model summary is judged too lossy and the main model takes over. */
28
107
  export declare const DEFAULT_CLAMP_TOLERANCE = 0.1;
108
+ /** Default compaction settings used by the harness.
109
+ * design/169-C (CC 220 :516151 `messagesToKeep: []` parity): the DEFAULT compaction is a FULL
110
+ * compaction — `keepRecentTokens: 0` keeps no verbatim token budget; the summary replaces the
111
+ * region entirely (the cut still lands on the nearest valid floor, so tool pairs and the
112
+ * in-progress turn's suffix stay intact). Keeping a verbatim tail is the reactive/partial posture
113
+ * and remains available as the explicit `keepRecentTokens` knob (the pre-169 default was 20000). */
29
114
  export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings;
115
+ /**
116
+ * design/123 D2 — default structural coefficient (chars per token) for every structural token
117
+ * estimate. 4 = the historical chars/4 heuristic (CC 198's legacy-family value); per-model override
118
+ * via `Model.charsPerToken` (newer families → 3, CJK-heavy → 2–3). Threaded as an explicit parameter
119
+ * through the estimate chain so caller-side coordinates never split (estimate vs cut-point vs defense).
120
+ */
30
121
  export declare const DEFAULT_CHARS_PER_TOKEN = 4;
122
+ /** Calculate total context tokens from provider usage. */
31
123
  export declare function calculateContextTokens(usage: Usage): number;
124
+ /**
125
+ * Return usage from the last successful assistant message in session entries.
126
+ *
127
+ * design/123 D1 stale-anchor note (fable-m2, same-family point): this scans RAW session entries, so
128
+ * unlike `buildSessionContext` (which shallow-strips the usage of kept-tail assistants replayed
129
+ * across a compaction boundary — the anchor "naturally disappears", CC 198 parity) it CAN still see
130
+ * a pre-compaction anchor. Any consumer using this across a compaction boundary must treat such an
131
+ * anchor as STALE: it reflects the pre-compaction request and overestimates the post-compaction
132
+ * context. (Currently exported with no in-repo production consumer.)
133
+ */
32
134
  export declare function getLastAssistantUsage(entries: SessionTreeEntry[]): Usage | undefined;
135
+ /** Estimated context-token usage for a message list. */
33
136
  export interface ContextUsageEstimate {
137
+ /** Estimated total context tokens. */
34
138
  tokens: number;
139
+ /** Tokens reported by the most recent assistant usage block. */
35
140
  usageTokens: number;
141
+ /** Estimated tokens after the most recent assistant usage block. */
36
142
  trailingTokens: number;
143
+ /** Index of the message that provided usage, or null when none exists. */
37
144
  lastUsageIndex: number | null;
38
145
  }
146
+ /** Estimate context tokens for messages using provider usage when available.
147
+ * `charsPerToken` (design/123 D2): structural coefficient for the anchor-less fallback and the
148
+ * trailing (post-anchor) increment — pass `Model.charsPerToken` so the estimate matches the model. */
39
149
  export declare function estimateContextTokens(messages: AgentMessage[], charsPerToken?: number): ContextUsageEstimate;
150
+ /** Return whether context usage exceeds the configured compaction threshold. */
40
151
  export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean;
152
+ /** Estimate token count for one message using a conservative character heuristic.
153
+ * `charsPerToken` (design/123 D2): per-model structural coefficient (default 4 = byte-compatible
154
+ * legacy heuristic). Images contribute a FIXED token weight independent of the coefficient. */
41
155
  export declare function estimateTokens(message: AgentMessage, charsPerToken?: number): number;
156
+ /** Find the user-visible message that starts the turn containing an entry. */
42
157
  export declare function findTurnStartIndex(entries: SessionTreeEntry[], entryIndex: number, startIndex: number): number;
158
+ /** Cut point selected for compaction. */
43
159
  export interface CutPointResult {
160
+ /** Index of the first entry retained after compaction. */
44
161
  firstKeptEntryIndex: number;
162
+ /** Index of the turn-start entry when the cut splits a turn, otherwise -1. */
45
163
  turnStartIndex: number;
164
+ /** Whether the selected cut point splits an in-progress turn. */
46
165
  isSplitTurn: boolean;
47
166
  }
167
+ /** Find the compaction cut point that keeps approximately the requested recent-token budget.
168
+ * `charsPerToken` (design/123 D2): the keep-recent accumulation must live in the SAME structural
169
+ * coordinate as the trigger estimate, or the kept tail is systematically over/under-sized. */
48
170
  export declare function findCutPoint(entries: SessionTreeEntry[], startIndex: number, endIndex: number, keepRecentTokens: number, charsPerToken?: number): CutPointResult;
49
171
  export declare const SUMMARIZATION_SYSTEM_PROMPT = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";
172
+ /**
173
+ * design/169-A (CC 220 :516490-516516 / :387325-387336) — the CC-form FORK context for a summary
174
+ * request: the main lane's latest REAL request. When present (and the summary model IS the main
175
+ * model), the summary request is the main conversation itself — same `systemPrompt` bytes, same
176
+ * message-list byte PREFIX, same tools — plus ONE appended user-role instruction message. The
177
+ * provider's prompt cache then re-serves the already-paid main prefix, which is the economics that
178
+ * make "summarize on the main model" cheap (an independent request re-prefills the whole
179
+ * conversation at full price every boundary).
180
+ *
181
+ * Mirrored structurally (not imported — core cannot be imported from the engine layer) by
182
+ * `CompactionForkContext` in `src/core/auto-compaction.ts`; the two must stay assignable.
183
+ */
50
184
  export interface CompactionForkContext {
185
+ /** The main request's system prompt, byte-identical (absent when the main request had none). */
51
186
  systemPrompt?: string;
187
+ /** The main request's PHYSICAL system-block layout (Context.systemBlocks), when present — the
188
+ * cache-span boundaries are part of the prefix identity a fork must reproduce. */
52
189
  systemBlocks?: Context["systemBlocks"];
190
+ /** The main request's message list — reused as the fork's byte-identical prefix. */
53
191
  messages: Message[];
192
+ /** The main request's tool declarations (part of the provider's cached prefix; optional — the
193
+ * instruction forbids tool calls either way). */
54
194
  tools?: Tool[];
195
+ /** The model id that SERVED the recorded request. The model is part of the provider's cache key:
196
+ * a fork whose summary call runs on a different model (mid-run budget degradation swapped models
197
+ * after the snapshot) pays a full prefill — the eligibility gate compares this against the
198
+ * summary model and degrades to the independent form on mismatch. Optional so a direct caller
199
+ * that manages its own model constancy can omit it (absent = caller vouches). */
55
200
  modelId?: string;
56
201
  }
202
+ /** Extract the fork-form summary from its envelope; `undefined` = non-conforming response.
203
+ *
204
+ * Grammar (adversarial round 3, both arms pinned): after stripping the permitted `<analysis>`
205
+ * scratch blocks, the ENTIRE remaining response must be one envelope — text outside it is a
206
+ * rejection, not noise ("<summary>placeholder</summary> I refuse" must not pass as "placeholder").
207
+ * The inner match is GREEDY with the closing tag anchored at the END, because the summary quotes
208
+ * user messages VERBATIM — a quoted literal `</summary>` inside the body must not truncate an
209
+ * otherwise conforming summary into an accepted fragment (the first-match form silently dropped
210
+ * every section after the quote). */
57
211
  export declare function extractForkSummaryEnvelope(text: string): string | undefined;
212
+ /** design/169-A — the single user-role instruction message appended to the forked main prefix.
213
+ * Semantics = SUMMARIZATION_SYSTEM_PROMPT's text-only contract + SUMMARIZATION_PROMPT's nine-section
214
+ * body ("The messages above…" reads exactly right in the fork form: the conversation IS the
215
+ * messages above, un-serialized) + the fork-only summary envelope (see
216
+ * {@link FORK_SUMMARY_ENVELOPE_DEMAND}; the independent form keeps its envelope-free contract).
217
+ * Instructions inject in the same CC-verbatim shape as the independent form so every channel keeps
218
+ * one injection grammar. */
58
219
  export declare function forkSummarizationInstruction(customInstructions?: string): string;
220
+ /**
221
+ * Trigger-reserve / summary-budget decoupling (blocker fix, 触发点对标批复审追补): the base for the
222
+ * summary legs' OUTPUT budget (history leg = 0.8× this, turn-prefix leg = 0.5× this).
223
+ *
224
+ * Two semantics used to ride one knob: `reserveTokens` is the TRIGGER deduction (threshold =
225
+ * window − reserve, repaired by `sanitizeCompactionSettings` against the trigger frontier), and the
226
+ * same — possibly repaired — value seeded the summary output budget. That coupling made the summary
227
+ * budget a hostage of trigger geometry: when the frontier moved (0.7W → W−33000), a 200k-window
228
+ * default's budget silently shrank 48000 → 26400 with zero summary-semantics justification.
229
+ *
230
+ * Decoupled shape:
231
+ * base = settings.summaryOutputBudgetTokens ?? settings.reserveTokens (explicit knob wins)
232
+ * effective = min(base, summary model's max output) (never budget output
233
+ * the model can't emit)
234
+ * CC contrast (2.1.207): CC's summary output cap is purely model-derived (its summary call runs at
235
+ * the model's max output) and fully separate from the trigger deduction — the `min(model.maxTokens,…)`
236
+ * leg IS that posture. The base deliberately stays reserve-derived rather than jumping to the raw
237
+ * model max: sema (unlike CC) clamps the summarization INPUT pre-send, and the clamp budgets
238
+ * `window − max(0.8×base, reasoning floor)` — a model-max base (e.g. 64k) would eat half a small
239
+ * summarizer's window in output reservation and starve the input side. Callers wanting the pure CC
240
+ * posture set `summaryOutputBudgetTokens = model.maxTokens` explicitly.
241
+ *
242
+ * SINGLE SOURCE: consumed by `compact()` (both real legs), `dryRunSummarizationClamp` (the 1.286
243
+ * same-params dry-run judgment), and the prepare-time `compaction.window_config_warning` estimate —
244
+ * so the dry run and the real clamp cannot drift.
245
+ */
59
246
  export declare function summaryOutputBudgetTokens(model: Model, settings: CompactionSettings): number;
247
+ /** Fidelity-disclosure payload for a truncated summarization input (bridged by the caller to the
248
+ * `compaction.input_truncated` trace frame). `keptChars` = surviving conversation chars (marker excluded). */
60
249
  export interface SummarizationInputTruncation {
61
250
  label: "history" | "turn_prefix";
62
251
  droppedChars: number;
63
252
  keptChars: number;
64
253
  }
254
+ /** design/145 §1 — result of a window-safety clamp DRY RUN (see {@link dryRunSummarizationClamp}). */
65
255
  export interface SummarizationClampDryRun {
256
+ /** Conversation chars the clamp would drop across BOTH summary legs (history + split-turn prefix). */
66
257
  droppedChars: number;
258
+ /** Conversation chars that would survive (marker excluded), across both legs. */
67
259
  keptChars: number;
260
+ /** `droppedChars / max(1, droppedChars + keptChars)` — always ∈ [0,1]; 0 for empty content
261
+ * (nothing to drop) and <1 even at negative headroom (the clamp keeps a MIN_KEEP floor). */
68
262
  truncationRatio: number;
263
+ /** Total serialized conversation chars (pre-clamp), across both legs — the honest "content size"
264
+ * coordinate for the fallback cost gate (chars ÷ the consumer's charsPerToken). */
69
265
  conversationChars: number;
70
266
  }
267
+ /**
268
+ * design/145 §1 — the SINGLE-SOURCE window-safety judgment: dry-run `clampSummarizationConversation`
269
+ * with the SAME parameters the real summary call(s) would use (same serialization, same fixed-prompt
270
+ * charge, same output reservation), WITHOUT sending anything. Consumed by `maybeCompact` to decide
271
+ * whether an independent (smaller-window) compaction model would truncate the conversation past
272
+ * `CompactionSettings.clampTolerance` — the r2 review killed the r1 token-domain twin formula
273
+ * precisely because two formulas drift; this function IS the clamp, so the judgment cannot.
274
+ *
275
+ * Split-turn boundaries aggregate both legs (history + turn prefix): the real path clamps each leg
276
+ * against its own budget (0.8× vs 0.5× reserve), so the dry run mirrors both and reports the summed
277
+ * ratio. Multi-round compactions are covered by construction: the preparation's `previousSummary`
278
+ * charges the fixed-prompt budget exactly as `generateSummary` does, so round 2's judgment is over
279
+ * "prior summary + new increment", not the original history.
280
+ */
71
281
  export declare function dryRunSummarizationClamp(preparation: CompactionPreparation, model: Model, customInstructions?: string, charsPerToken?: number): SummarizationClampDryRun;
282
+ /** CC 198 jNl — verbatim marker inserted where the oldest conversation groups were dropped. */
72
283
  export declare const COMPACTION_PTL_RETRY_MARKER = "[earlier conversation truncated for compaction retry]";
284
+ /** Generate or update a conversation summary for compaction.
285
+ * `summaryBudgetTokens` — the OUTPUT budget base (history leg = 0.8× it). Callers going through
286
+ * `compact()` get the decoupled, model-capped value from {@link summaryOutputBudgetTokens}; this
287
+ * parameter was historically the raw `settings.reserveTokens` (trigger reserve). */
73
288
  export declare function generateSummary(currentMessages: AgentMessage[], model: Model, summaryBudgetTokens: number, apiKey: string | undefined, headers?: Record<string, string>, signal?: AbortSignal, customInstructions?: string, previousSummary?: string, thinkingLevel?: ThinkingLevel, streamFn?: StreamFn, runtime?: AgentCoreCompletionRuntimeDeps, charsPerToken?: number, onInputTruncated?: (info: SummarizationInputTruncation) => void, onPtlRetry?: () => void): Promise<Result<string, CompactionError>>;
289
+ /** Prepared inputs for a compaction run. */
74
290
  export interface CompactionPreparation {
291
+ /** Entry id where retained history starts. */
75
292
  firstKeptEntryId: string;
293
+ /** Messages summarized into the history summary. */
76
294
  messagesToSummarize: AgentMessage[];
295
+ /** Prefix messages summarized separately when compaction splits a turn. */
77
296
  turnPrefixMessages: AgentMessage[];
297
+ /** Whether compaction splits a turn. */
78
298
  isSplitTurn: boolean;
299
+ /** Estimated context tokens before compaction. */
79
300
  tokensBefore: number;
301
+ /** Previous compaction summary used for iterative updates. */
80
302
  previousSummary?: string;
303
+ /** File operations extracted from summarized history. */
81
304
  fileOps: FileOperations;
305
+ /** Budgeted invoked-skill retention for the DROPPED range (merged over the previous compaction's
306
+ * retained set), most-recent-first — ready to persist as `CompactionDetails.invokedSkills`. */
82
307
  invokedSkills: InvokedSkillRetention[];
308
+ /** RB-398-c: offload handles from the DROPPED range (merged over the previous compaction's
309
+ * retained set, oldest-first, capped) — ready to persist as
310
+ * `CompactionDetails.persistedOutputRefs` and render as the summary footer. Optional so
311
+ * hand-built preparations (tests, external callers) stay valid; absent = none. */
83
312
  persistedOutputRefs?: string[];
313
+ /** RB-398-b①: cumulative folded-message count (this range + the previous carrier's count) —
314
+ * ready to persist as `CompactionDetails.elidedMessages`. Optional (same rule as above). */
84
315
  elidedMessages?: number;
316
+ /** Settings used to prepare compaction. */
85
317
  settings: CompactionSettings;
86
318
  }
319
+ /** Prepare session entries for compaction, or return undefined when compaction is not applicable.
320
+ * `charsPerToken` (design/123 D2, signature threading): keeps `tokensBefore` and the cut-point
321
+ * accounting in the same per-model structural coordinate as the caller's trigger estimate.
322
+ * `windowTokens` (window-aware retention clamp): the trigger window of the model that will consume
323
+ * the post-compaction context. When provided, the invoked-skills retained area is clamped to the
324
+ * headroom that window leaves after the existing geometry (`window − reserveTokens −
325
+ * keepRecentTokens`, in chars) — the CC-shaped 20k/100k retention caps are UPPER BOUNDS tuned for
326
+ * large windows, and on a small-window model an unclamped area would push every post-compaction
327
+ * request straight back over the window the compaction just freed. Absent ⇒ the plain CC-shaped
328
+ * budget (legacy behavior). */
87
329
  export declare function prepareCompaction(pathEntries: SessionTreeEntry[], settings: CompactionSettings, charsPerToken?: number, windowTokens?: number): Result<CompactionPreparation | undefined, CompactionError>;
88
330
  export { computeFileLists, serializeConversation } from "./utils.js";
89
- export declare function compact(preparation: CompactionPreparation, model: Model, apiKey: string | undefined, headers?: Record<string, string>, customInstructions?: string, signal?: AbortSignal, thinkingLevel?: ThinkingLevel, streamFn?: StreamFn, runtime?: AgentCoreCompletionRuntimeDeps, charsPerToken?: number, onInputTruncated?: (info: SummarizationInputTruncation) => void, onPtlRetry?: () => void, forkContext?: CompactionForkContext): Promise<Result<CompactionResult, CompactionError>>;
331
+ /** Generate compaction summary data from prepared session history.
332
+ * `charsPerToken` (design/123 D2, signature threading): coefficient for the summarization-input
333
+ * window guard. Defaults to the SUMMARY model's own `charsPerToken` (the estimated input is sent to
334
+ * THAT model), then 4. */
335
+ export declare function compact(preparation: CompactionPreparation, model: Model, apiKey: string | undefined, headers?: Record<string, string>, customInstructions?: string, signal?: AbortSignal, thinkingLevel?: ThinkingLevel, streamFn?: StreamFn, runtime?: AgentCoreCompletionRuntimeDeps, charsPerToken?: number, onInputTruncated?: (info: SummarizationInputTruncation) => void, onPtlRetry?: () => void,
336
+ /** design/169-A — when present, the summary is attempted in the CC FORK form first (main prefix +
337
+ * one instruction message; see {@link CompactionForkContext}). A prompt-too-long on the fork form
338
+ * falls back ONCE to the independent form below (which can clamp; the fork form must not — a
339
+ * clamp would rewrite the cached prefix). The caller only passes this when the summary model IS
340
+ * the main model; an independent compaction model has no main prefix to share. */
341
+ forkContext?: CompactionForkContext): Promise<Result<CompactionResult, CompactionError>>;
342
+ /** The prefix leg's base prompt, with the caller's instructions injected in the SAME shape the
343
+ * history leg uses (`\n\nAdditional Instructions:\n${…}`, CC 198 verbatim). Single source so the
344
+ * dry-run clamp charges exactly what the real call sends. */
90
345
  export declare function turnPrefixSummarizationPrompt(customInstructions?: string): string;
@@ -1,37 +1,131 @@
1
1
  import type { Message } from "../llm/index.js";
2
2
  import type { AgentMessage } from "../loop/types.js";
3
+ /** File paths touched by a session branch or compaction range. */
3
4
  export interface FileOperations {
5
+ /** Files read but not necessarily modified. */
4
6
  read: Set<string>;
7
+ /** Files written by full-file write operations. */
5
8
  written: Set<string>;
9
+ /** Files modified by edit operations. */
6
10
  edited: Set<string>;
11
+ /**
12
+ * Cross-set touch order for modified files (written ∪ edited), oldest→newest — a re-touch moves
13
+ * the path to the end (Set insertion-order semantics via delete-then-add). This is what lets
14
+ * working-file attachments pick the MOST RECENTLY touched files instead of the first N
15
+ * alphabetically (the LONGRUN-2b miss: orders.js sorted out of the top-3).
16
+ */
7
17
  modifiedOrder: Set<string>;
8
18
  }
19
+ /** Create an empty file-operation accumulator. */
9
20
  export declare function createFileOps(): FileOperations;
21
+ /** Add file operations from assistant tool calls to an accumulator. */
10
22
  export declare function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void;
23
+ /** One retained invoked skill: the Skill tool result text as it stood in context (possibly
24
+ * truncated with {@link SKILL_RETENTION_TRUNCATION_MARKER}). */
11
25
  export interface InvokedSkillRetention {
12
26
  name: string;
13
27
  content: string;
14
28
  }
29
+ /** Per-skill retained-content cap (chars; CC: 5000 tokens). Truncation is marker-inclusive: a
30
+ * truncated entry is EXACTLY this long, marker included. */
15
31
  export declare const SKILL_RETENTION_PER_SKILL_MAX_CHARS = 20000;
32
+ /** Total retained-area budget (chars; CC: 25000 tokens). Skills that do not fit whole are skipped
33
+ * individually — later (smaller) skills may still fit. */
16
34
  export declare const SKILL_RETENTION_TOTAL_MAX_CHARS = 100000;
35
+ /** In-band truncation marker. CC's marker points at `Read` on the skill's file path; sema skills
36
+ * are spec-supplied content with no filesystem path, so the equivalent recovery route here is
37
+ * re-invoking the Skill tool (which, post-parity, always serves the FULL text). */
17
38
  export declare const SKILL_RETENTION_TRUNCATION_MARKER = "[... skill content truncated for compaction; invoke the Skill tool again if you need the full text]";
39
+ /** Strip the appended model-supplied `## Input` args section from a Skill tool result body (see
40
+ * {@link SKILL_INPUT_SECTION_SEPARATOR}); returns the body unchanged when no section is present. */
18
41
  export declare function stripSkillInputSection(text: string): string;
42
+ /**
43
+ * Scan dropped messages for successful Skill tool invocations and merge them over the previous
44
+ * compaction's retained set. Returns the UNBUDGETED merged list, most recent invocation FIRST.
45
+ *
46
+ * - `prevRetained` (the prior compaction's `details.invokedSkills`, newest-first) seeds the set:
47
+ * every prior entry is older than anything scanned here, and a re-invocation refreshes both the
48
+ * content and the recency rank (delete-then-set Map insertion order).
49
+ * - Only NON-error Skill results count (an unknown-skill error result carries no skill body).
50
+ * - The skill NAME comes from the paired assistant toolCall's arguments (`skill`, legacy `name`);
51
+ * the result message alone only knows the tool name.
52
+ */
19
53
  export declare function extractInvokedSkills(droppedMessages: AgentMessage[], prevRetained: InvokedSkillRetention[] | undefined): InvokedSkillRetention[];
54
+ /** Apply the CC-shaped retention budget to a newest-first invoked-skill list: per-skill truncation
55
+ * (marker-inclusive), then the total budget with SKIP-not-break semantics for over-budget entries.
56
+ *
57
+ * `maxTotalChars` (window-aware clamp): the CC-shaped 20k/100k caps are UPPER BOUNDS tuned for
58
+ * ≥100k-token windows, not guarantees — on a small-window model an area that big would push
59
+ * 「summary + retention + kept tail」 past the window on every post-compaction request. A caller
60
+ * that knows the consuming model's window passes its remaining chars headroom here; the effective
61
+ * total budget is `min(100k, maxTotalChars)`, and the per-skill cap shrinks to the effective
62
+ * total so the MOST RECENT skill is truncated-to-fit rather than skipped whole (skip-whole is the
63
+ * right CC semantics between skills, but under a window clamp it would drop the newest skill in
64
+ * favor of an older smaller one). A budget too small to hold even the truncation marker retains
65
+ * nothing. Absent ⇒ the plain CC-shaped budget. */
20
66
  export declare function budgetInvokedSkillsRetention(newestFirst: InvokedSkillRetention[], maxTotalChars?: number): InvokedSkillRetention[];
67
+ /**
68
+ * Replace the bodies of successful Skill tool results with a bounded placeholder before the
69
+ * summarizer sees them. Extraction copies those bodies into the retained invoked-skills area, so
70
+ * leaving the originals in the summarization input would (a) double-charge the window budget and
71
+ * (b) let multi-thousand-char skill texts crowd real conversation out of the summary input clamp.
72
+ * The toolResult MESSAGE stays (shallow-copied, same toolCallId/toolName) so the call/result
73
+ * pairing stays legal for serialization; only its content is swapped for a short note. `groups`
74
+ * lets a split-turn boundary pass both legs at once so the call→name pairing map spans them.
75
+ * `retainedNames` keeps the placeholder honest: a skill the retention budget skipped is disclosed
76
+ * as omitted, not claimed preserved. Non-matching messages pass through by reference.
77
+ */
21
78
  export declare function replaceInvokedSkillBodiesForSummary(groups: AgentMessage[][], retainedNames: ReadonlySet<string>): AgentMessage[][];
79
+ /** Defensive reader for persisted `CompactionDetails.invokedSkills` (details is `unknown` on the
80
+ * wire; sessions persisted before this field existed simply yield an empty list). */
22
81
  export declare function readRetainedInvokedSkills(details: unknown): InvokedSkillRetention[];
82
+ /** Render the retained invoked-skills area appended to the compaction summary MESSAGE at context
83
+ * build time (never baked into the persisted summary string — see the module note above). */
23
84
  export declare function renderInvokedSkillsRetention(skills: InvokedSkillRetention[]): string;
85
+ /** Bound on the retained ref list — write-side cap AND the import door's ceiling (import-validate
86
+ * bounds against the producer's own constant so the two never drift). The list is oldest-first
87
+ * (carry-forward seed, then this range's refs); over the cap the OLDEST refs are dropped — the
88
+ * newest elisions are the likeliest to be paged back. */
24
89
  export declare const PERSISTED_OUTPUT_REFS_MAX_ENTRIES = 50;
90
+ /** Collect `<persisted-output ref="…">` handles from tool results in `messages` into `into`
91
+ * (insertion-ordered Set = first appearance order; duplicates collapse). */
25
92
  export declare function extractPersistedOutputRefs(messages: AgentMessage[], into: Set<string>): void;
93
+ /** Defensive reader for persisted `CompactionDetails.elidedMessages` (RB-398-b①): a non-negative
94
+ * safe integer, else absent (pre-field sessions / foreign shapes yield undefined ⇒ no wrapper
95
+ * disclosure — the byte-identical legacy render). */
26
96
  export declare function readElidedMessages(details: unknown): number | undefined;
97
+ /** Defensive reader for persisted `CompactionDetails.activeTools` (RB-402, blackboard [2132]③c/
98
+ * [2133]): the ToolSearch activation snapshot each landed compaction restates. details is
99
+ * `unknown` on the wire — pre-field sessions and foreign shapes yield an empty list; non-string/
100
+ * empty members are dropped (the consumer additionally intersects with the current leg's deferred
101
+ * registry, so an unknown name is inert either way). */
27
102
  export declare function readCompactionActiveTools(details: unknown): string[];
103
+ /** Defensive reader for persisted `CompactionDetails.persistedOutputRefs` (details is `unknown` on
104
+ * the wire; sessions persisted before this field existed simply yield an empty list). */
28
105
  export declare function readPersistedOutputRefs(details: unknown): string[];
106
+ /** Render the retained handles as a summary footer section — the deterministic counterpart of the
107
+ * `clearStaleToolResults` marker's "full text persisted; call ReadToolResult with ref …" note.
108
+ * Empty list ⇒ empty string (pre-existing summaries stay byte-identical). */
29
109
  export declare function formatPersistedOutputRefs(refs: string[]): string;
110
+ /**
111
+ * Compute the file lists from accumulated operations: the display lists stay SORTED (stable
112
+ * summary-tag output), `modifiedFilesByRecency` carries the same modified set most-recent-FIRST
113
+ * for consumers that pick a top-N (working-file attachments).
114
+ */
30
115
  export declare function computeFileLists(fileOps: FileOperations): {
31
116
  readFiles: string[];
32
117
  modifiedFiles: string[];
33
118
  modifiedFilesByRecency: string[];
34
119
  };
120
+ /** Format file lists as summary metadata tags (each list capped at {@link FILE_LIST_MAX_ENTRIES}). */
35
121
  export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string;
122
+ /**
123
+ * Inverse of {@link formatFileOperations}: strip a TRAILING file-ops footer block from a stored summary.
124
+ * Every summary persisted by `compact()` ends with this footer; when a prior summary is threaded verbatim
125
+ * as the history of a later split-turn compaction (bug-hunt #1), the canonical superset footer is
126
+ * re-appended — so the stale embedded one must be removed first to avoid a duplicate. Anchored at end-of-
127
+ * string, so a `<read-files>`/`<modified-files>` string that legitimately appears mid-body is untouched.
128
+ */
36
129
  export declare function stripFileOperationsFooter(summary: string): string;
130
+ /** Serialize LLM messages to plain text for summarization prompts. */
37
131
  export declare function serializeConversation(messages: Message[]): string;
@@ -4,8 +4,37 @@ export type KillProcessTreeOptions = {
4
4
  graceMs?: number;
5
5
  detached?: boolean;
6
6
  force?: boolean;
7
+ /**
8
+ * 1.296 件2 — identity anchor for the graceful SIGKILL escalation. A pid is a NAME, not an
9
+ * identity: when the original process (group) exits within the grace window and the OS re-uses
10
+ * the pid (small pid_max containers + fork-heavy build workloads make the window real), the
11
+ * pid-liveness recheck reads the STRANGER as "still alive" and the SIGKILL lands on an unrelated
12
+ * process. When provided, the escalation leg consults this callback FIRST — it must return true
13
+ * only while the ORIGINAL process is known not to have exited (e.g. a retained ChildProcess
14
+ * handle with `exitCode === null && signalCode === null`); the pid probe remains only an
15
+ * auxiliary check. Absent ⇒ the pre-existing pid-only behavior (callers without a process handle).
16
+ *
17
+ * codex R2 (1.296.1) — `false` cancels the DIRECT-pid escalation (that is where pid-reuse risk
18
+ * lives), but on the group-kill lane it no longer cancels the GROUP leg: the anchor only knows
19
+ * the LEADER — a detached shell that honors SIGTERM and exits while its TERM-ignoring descendants
20
+ * (run89's build workers) keep the group alive. While ANY original member lives, POSIX reserves
21
+ * the pgid for this group, so a group-scoped SIGKILL cannot land on a stranger; the group leg
22
+ * therefore probes group liveness and fires group-only. (Residual window — the WHOLE group died
23
+ * AND the pid was recycled as a NEW group leader inside the grace window — is the same one every
24
+ * `kill -- -PGID` accepts, documented not closed.)
25
+ */
7
26
  stillRunning?: () => boolean;
8
27
  };
28
+ /**
29
+ * Best-effort process-tree termination with graceful shutdown.
30
+ * - Windows: use taskkill /T to include descendants. Sends SIGTERM-equivalent
31
+ * first (without /F), then force-kills if process survives.
32
+ * - Unix: send SIGTERM to process group first, wait grace period, then SIGKILL.
33
+ *
34
+ * When the child was spawned with `detached: false`, pass `detached: false` to
35
+ * skip the Unix `process.kill(-pid, ...)` group-kill. That avoids signaling the
36
+ * gateway's own process group.
37
+ */
9
38
  export declare function killProcessTree(pid: number, opts?: KillProcessTreeOptions): void;
10
39
  export declare function signalProcessTree(pid: number, signal: "SIGTERM" | "SIGKILL", opts?: {
11
40
  detached?: boolean;