@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
@@ -1,69 +1,209 @@
1
1
  import type { Static, TSchema } from "typebox";
2
2
  import type { AssistantMessage, AssistantMessageEvent, DocumentContent, ImageContent, Message, Model, SimpleStreamOptions, StreamFn as LlmStreamFn, TextContent, Tool, ToolResultMessage } from "../llm/index.js";
3
+ /**
4
+ * Stream function used by the agent loop.
5
+ *
6
+ * Contract:
7
+ * - Must not throw or return a rejected promise for request/model/runtime failures.
8
+ * - Must return an AssistantMessageEventStream.
9
+ * - Failures must be encoded in the returned stream via protocol events and a
10
+ * final AssistantMessage with stopReason "error" or "aborted" and errorMessage.
11
+ */
3
12
  export type StreamFn = LlmStreamFn;
13
+ /**
14
+ * Configuration for how tool calls from a single assistant message are executed.
15
+ *
16
+ * - "sequential": each tool call is prepared, executed, and finalized before the next one starts.
17
+ * - "parallel": tool calls are prepared sequentially, then allowed tools execute concurrently.
18
+ * `tool_execution_end` is emitted in tool completion order after each tool is finalized,
19
+ * while tool-result message artifacts are emitted later in assistant source order.
20
+ */
4
21
  export type ToolExecutionMode = "sequential" | "parallel";
22
+ /**
23
+ * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.
24
+ *
25
+ * - "all": drain and inject every queued message at that point.
26
+ * - "one-at-a-time": drain and inject only the oldest queued message, leaving the rest queued for later drain points.
27
+ */
5
28
  export type QueueMode = "all" | "one-at-a-time";
29
+ /** A single tool call content block emitted by an assistant message. */
6
30
  export type AgentToolCall = Extract<AssistantMessage["content"][number], {
7
31
  type: "toolCall";
8
32
  }>;
33
+ /**
34
+ * Result returned from `beforeToolCall`.
35
+ *
36
+ * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.
37
+ * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.
38
+ *
39
+ * Returning `{ updatedInput }` (without `block`) REWRITES the arguments the tool executes with — the
40
+ * loop replaces the validated args with `updatedInput` and **re-runs `validateToolArguments` on it**
41
+ * before execution, so a rewrite can never smuggle schema-invalid args into `tool.execute()`. This is
42
+ * the generic carrier the higher layer uses for arg redaction/clamping (design/37); the loop itself
43
+ * stays policy-agnostic. `block` wins over `updatedInput` if both are set.
44
+ *
45
+ * Keep in sync with the harness hook result `ToolCallResult` (harness/types.ts), which the harness's
46
+ * `beforeToolCall` callback returns verbatim.
47
+ */
9
48
  export interface BeforeToolCallResult {
10
49
  block?: boolean;
11
50
  reason?: string;
12
51
  updatedInput?: unknown;
13
52
  }
53
+ /**
54
+ * Partial override returned from `afterToolCall`.
55
+ *
56
+ * Merge semantics are field-by-field:
57
+ * - `content`: if provided, replaces the tool result content array in full
58
+ * - `details`: if provided, replaces the tool result details value in full
59
+ * - `isError`: if provided, replaces the tool result error flag
60
+ * - `terminate`: if provided, replaces the early-termination hint
61
+ *
62
+ * Omitted fields keep the original executed tool result values.
63
+ * There is no deep merge for `content` or `details`.
64
+ */
14
65
  export interface AfterToolCallResult {
15
66
  content?: (TextContent | ImageContent | DocumentContent)[];
16
67
  details?: unknown;
17
68
  isError?: boolean;
69
+ /**
70
+ * Hint that the agent should stop after the current tool batch.
71
+ * Early termination only happens when every finalized tool result in the batch sets this to true.
72
+ */
18
73
  terminate?: boolean;
19
74
  }
75
+ /** Context passed to `beforeToolCall`. */
20
76
  export interface BeforeToolCallContext {
77
+ /** The assistant message that requested the tool call. */
21
78
  assistantMessage: AssistantMessage;
79
+ /** The raw tool call block from `assistantMessage.content`. */
22
80
  toolCall: AgentToolCall;
81
+ /** Validated tool arguments for the target tool schema. */
23
82
  args: unknown;
83
+ /** Current agent context at the time the tool call is prepared. */
24
84
  context: AgentContext;
25
85
  }
86
+ /** Context passed to `afterToolCall`. */
26
87
  export interface AfterToolCallContext {
88
+ /** The assistant message that requested the tool call. */
27
89
  assistantMessage: AssistantMessage;
90
+ /** The raw tool call block from `assistantMessage.content`. */
28
91
  toolCall: AgentToolCall;
92
+ /** Validated tool arguments for the target tool schema. */
29
93
  args: unknown;
94
+ /** The executed tool result before unknown `afterToolCall` overrides are applied. */
30
95
  result: AgentToolResult<unknown>;
96
+ /** Whether the executed tool result is currently treated as an error. */
31
97
  isError: boolean;
98
+ /** Current agent context at the time the tool call is finalized. */
32
99
  context: AgentContext;
33
100
  }
101
+ /** Context passed to `shouldStopAfterTurn`. */
34
102
  export interface ShouldStopAfterTurnContext {
103
+ /** The assistant message that completed the turn. */
35
104
  message: AssistantMessage;
105
+ /** Tool result messages passed to the preceding `turn_end` event. */
36
106
  toolResults: ToolResultMessage[];
107
+ /** Current agent context after the turn's assistant message and tool results have been appended. */
37
108
  context: AgentContext;
109
+ /** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */
38
110
  newMessages: AgentMessage[];
39
111
  }
112
+ /** Replacement runtime state used by the agent loop before starting another provider request. */
40
113
  export interface AgentLoopTurnUpdate {
114
+ /** Context for the next provider request. */
41
115
  context?: AgentContext;
116
+ /** Model for the next provider request. */
42
117
  model?: Model;
118
+ /** Thinking level for the next provider request. */
43
119
  thinkingLevel?: ThinkingLevel;
44
120
  }
45
121
  export interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {
46
122
  }
123
+ /**
124
+ * Prompt-too-long recovery seam (design/118 ④b, the CC reactive-compact chain adapted to sema's
125
+ * "brain outside" architecture). The LOOP owns the retry transition; the CALLER owns the policy —
126
+ * `recover` typically compacts/trims the transcript (the harness/runner wires it to the engine
127
+ * compaction machinery). Retries happen INSIDE the turn (no extra `turn_start`); the failed
128
+ * assistant is dropped from the retry context and never enters the run's returned messages.
129
+ */
47
130
  export interface LoopPromptTooLongRecovery {
131
+ /**
132
+ * Produce a replacement transcript to retry the provider request with (attempt starts at 1).
133
+ * Return undefined to give up — the loop then surfaces the original error unchanged.
134
+ * Contract: must not throw or reject.
135
+ */
48
136
  recover: (messages: AgentMessage[], attempt: number) => Promise<AgentMessage[] | undefined>;
137
+ /** Override the prompt-too-long classifier. Default: a conservative provider-message pattern. */
49
138
  detect?: (message: AssistantMessage) => boolean;
139
+ /** Max recovery retries per turn. Default: 2. */
50
140
  maxRetries?: number;
141
+ /**
142
+ * M1 (docs/PARITY-CONTEXT-TRANSACTIONS-2026-07-10 §4): withhold the failed assistant's
143
+ * message_start/message_end stream events while a recovery attempt is pending — CC 198 holds
144
+ * these errors inside its stream decoder (`claude-cli-2.1.198.pretty.js:473371-473374`) and only
145
+ * leaks them once recovery's outcome is known. Recovery succeeded ⇒ the failure stays invisible
146
+ * to event consumers; failed/declined ⇒ the events leak at that point (terminal truth unchanged).
147
+ * Default true (CC-aligned). `false` restores the pre-M1 live leak of the interim error.
148
+ */
51
149
  withholdErrorEvents?: boolean;
52
150
  }
151
+ /**
152
+ * Truncated-output auto-continue (design/118 ④b, the CC max_output_tokens recovery). When a turn
153
+ * stops with `stopReason: "length"` and produced NO tool calls, the loop injects a synthetic
154
+ * continue nudge (a `custom` message, `display: false`) and runs another turn, up to `maxContinues`
155
+ * CONSECUTIVE times (the counter resets on any non-length turn). Absent ⇒ OFF (a "length" answer
156
+ * ends the run — the pre-④b behavior).
157
+ *
158
+ * RB-258: when the budget IS configured and runs out on a still-`length` turn, the loop ends with the
159
+ * dedicated terminal reason `truncated_output_exhausted` (visible on the `LoopTraceSink`) instead of a
160
+ * plain `completed` — the caller can tell "kept hitting the output cap" apart from "actually finished".
161
+ * The OFF case is unchanged (no budget ⇒ nothing to exhaust ⇒ still `completed`).
162
+ */
53
163
  export interface LoopTruncatedOutputRecovery {
164
+ /** Max consecutive auto-continues. Default: 3. */
54
165
  maxContinues?: number;
55
166
  }
167
+ /**
168
+ * Malformed-tool-use retry (design/119 S2, CC 2.1.198 :473745-473785). A turn that stops with
169
+ * `toolUse` but carries ZERO parseable tool calls (the brain dropped truncated/invalid ones) used to
170
+ * end the run silently mid-task. When enabled, inject a synthetic retry nudge and run another turn,
171
+ * up to `maxRetries` per run (CC: once). Absent ⇒ OFF (pre-S2 behavior).
172
+ */
56
173
  export interface LoopMalformedToolUseRecovery {
174
+ /** Max retries per run. Default: 1. */
57
175
  maxRetries?: number;
58
176
  }
177
+ /**
178
+ * Thinking-only retry (design/119 S2, CC 2.1.198 :473786-473825 — the adaptive-thinking era
179
+ * companion). A turn that stops normally with thinking block(s) but NO visible text and NO tool
180
+ * calls used to end the run as a silent empty success. When enabled, inject a "respond with visible
181
+ * output" nudge and run another turn, up to `maxRetries` per run (CC: once). Absent ⇒ OFF.
182
+ */
59
183
  export interface LoopThinkingOnlyRecovery {
184
+ /** Max retries per run. Default: 1. */
60
185
  maxRetries?: number;
61
186
  }
187
+ /** Recovery chains the loop can drive (design/118 ④b + design/119 S2). All absent ⇒ the zero-recovery loop.
188
+ * REF-D22 (keep-with-reason, 2026-08): `engine/harness/agent-harness.ts`'s `HarnessLoopRecovery` mirrors
189
+ * this shape — `truncatedOutput`/`malformedToolUse`/`thinkingOnly` already reference the named types
190
+ * below by direct import (no drift risk); `degenerateOutput` (2 fields) is hand-copied there and is a
191
+ * candidate for a future `Pick`-style extraction; `promptTooLong` is
192
+ * INTENTIONALLY forked — the harness side is a session-level `recover(attempt)` reduction, this loop
193
+ * side is `recover(messages, attempt)` and also carries `withholdErrorEvents`, so the two can never share
194
+ * one type. (`agent-harness.ts` is outside this file's edit scope — its side of this mutual-reference
195
+ * note is pending.) */
62
196
  export interface LoopRecoveryOptions {
63
197
  promptTooLong?: LoopPromptTooLongRecovery;
64
198
  truncatedOutput?: LoopTruncatedOutputRecovery;
65
199
  malformedToolUse?: LoopMalformedToolUseRecovery;
66
200
  thinkingOnly?: LoopThinkingOnlyRecovery;
201
+ /** TB 尸检 T1-4: a degenerate-repetition CUTOFF turn (the brain cancelled the stream and stamped the
202
+ * turn errored) gets a bounded "take a different approach" continue instead of ending the run — the
203
+ * salvaged prefix is real work, and one bad sampling run shouldn't void it. `detect` is caller-injected
204
+ * (core owns the brain's DEGENERATE_MESSAGE constant; the loop stays brain-agnostic). Consecutive cap
205
+ * `maxContinues` (default 2); a second consecutive degeneration falls through to the normal error
206
+ * terminal (assemble → `output.degenerate` + salvagedOutput, unchanged). */
67
207
  degenerateOutput?: {
68
208
  detect: (message: AssistantMessage) => boolean;
69
209
  maxContinues?: number;
@@ -71,94 +211,378 @@ export interface LoopRecoveryOptions {
71
211
  }
72
212
  export interface AgentLoopConfig extends SimpleStreamOptions {
73
213
  model: Model;
214
+ /** Error-recovery chains (design/118 ④b). Absent ⇒ no recovery (errors end the run as before). */
74
215
  recovery?: LoopRecoveryOptions;
216
+ /**
217
+ * design/130 P1: per-CALL dynamic output-token cap, evaluated immediately before EACH provider
218
+ * call (the static `maxTokens` from SimpleStreamOptions is snapshotted once per run — this seam
219
+ * exists so a wall-clock-aware host can shrink individual calls as the budget drains). A
220
+ * `number` return overrides `maxTokens` for that call only; `undefined` leaves the static chain
221
+ * untouched. The provider must be cheap and side-effect-light: it runs on the hot path.
222
+ */
75
223
  maxTokensPerCall?: () => number | undefined;
224
+ /**
225
+ * 1.296 件A: per-CALL advisory stall watchdogs, evaluated immediately before EACH provider call
226
+ * and forwarded as `StreamOptions.stallTimeouts` — the host supplies values so a SILENT stream
227
+ * (zero deltas) is bounded by the brain's retryable stall machinery instead of hanging the run.
228
+ * Advisory: a brain's construction-time `BrainTimeoutConfig` field wins when present; `undefined`
229
+ * return ⇒ nothing supplied. Must be cheap (hot path).
230
+ */
76
231
  stallTimeoutsPerCall?: () => import("../llm/types.js").StallTimeouts | undefined;
232
+ /**
233
+ * design/120 P1: concurrency cap inside a parallel tool batch. Default 10 (CC 198's production
234
+ * default — its knob is the CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY env; sema takes config).
235
+ */
77
236
  maxToolConcurrency?: number;
237
+ /**
238
+ * design/120 P2: in-stream tool execution (CC StreamingToolExecutor, admission narrowed).
239
+ * When true, a concurrency-safe tool call whose arguments completed mid-stream (`toolcall_end`)
240
+ * starts executing while the model is still streaming, instead of waiting for the full response.
241
+ *
242
+ * Default: OFF (undefined) — behavior is exactly the P1 partitioned batch pipeline.
243
+ *
244
+ * Setting this true is the HOST'S PROMISE that no `beforeToolCall` gate on this run can durably
245
+ * suspend (mint a checkpoint + abort): in-stream calls still run the full prepare chain (defense
246
+ * in depth — block/updatedInput work as normal), but a mid-stream durable suspend has no stable
247
+ * leaf to hang its checkpoint on. The harness wires this only when no `tool_call` hook handler
248
+ * is registered (snapshot per turn); registering a suspending handler mid-run after opting in is
249
+ * a host contract violation (undefined behavior). Admission per call additionally requires:
250
+ * `toolExecution !== "sequential"`, the tool's `executionMode !== "sequential"`, the source-order
251
+ * barrier (once any call bounces to the batch pipeline, every later call bounces too — the CC
252
+ * processQueue FIFO-break equivalent), and in-flight < `maxToolConcurrency`.
253
+ */
78
254
  streamingToolExecution?: boolean;
255
+ /**
256
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
257
+ *
258
+ * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
259
+ * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
260
+ * status messages) should be filtered out.
261
+ *
262
+ * Contract: must not throw or reject. Return a safe fallback value instead.
263
+ * Throwing interrupts the low-level agent loop without producing a normal event sequence.
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * convertToLlm: (messages) => messages.flatMap(m => {
268
+ * if (m.role === "custom") {
269
+ * // Convert custom message to user message
270
+ * return [{ role: "user", content: m.content, timestamp: m.timestamp }];
271
+ * }
272
+ * if (m.role === "notification") {
273
+ * // Filter out UI-only messages
274
+ * return [];
275
+ * }
276
+ * // Pass through standard LLM messages
277
+ * return [m];
278
+ * })
279
+ * ```
280
+ */
79
281
  convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
282
+ /**
283
+ * Optional transform applied to the context before `convertToLlm`.
284
+ *
285
+ * Use this for operations that work at the AgentMessage level:
286
+ * - Context window management (pruning old messages)
287
+ * - Injecting context from external sources
288
+ *
289
+ * Contract: must not throw or reject. Return the original messages or another
290
+ * safe fallback value instead.
291
+ *
292
+ * @example
293
+ * ```typescript
294
+ * transformContext: async (messages) => {
295
+ * if (estimateTokens(messages) > MAX_TOKENS) {
296
+ * return pruneOldMessages(messages);
297
+ * }
298
+ * return messages;
299
+ * }
300
+ * ```
301
+ */
80
302
  transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
303
+ /**
304
+ * Resolves an API key dynamically for each LLM call.
305
+ *
306
+ * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire
307
+ * during long-running tool execution phases.
308
+ *
309
+ * Contract: must not throw or reject. Return undefined when no key is available.
310
+ */
81
311
  getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
312
+ /**
313
+ * Called after each turn fully completes and `turn_end` has been emitted.
314
+ *
315
+ * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,
316
+ * without starting another LLM call. The current assistant response and any tool executions finish normally.
317
+ *
318
+ * Use this to request a graceful stop after the current turn, e.g. before context gets too full.
319
+ *
320
+ * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.
321
+ */
82
322
  shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
323
+ /**
324
+ * Called after `turn_end` and before the loop decides whether another provider request should start.
325
+ * Return replacement context/model/thinking state to affect the next turn in this run.
326
+ * Return undefined to keep using the current context/config.
327
+ */
83
328
  prepareNextTurn?: (context: PrepareNextTurnContext) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;
329
+ /**
330
+ * Returns steering messages to inject into the conversation mid-run.
331
+ *
332
+ * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.
333
+ * If messages are returned, they are added to the context before the next LLM call.
334
+ * Tool calls from the current assistant message are not skipped.
335
+ *
336
+ * Use this for "steering" the agent while it's working.
337
+ *
338
+ * Contract: must not throw or reject. Return [] when no steering messages are available.
339
+ */
84
340
  getSteeringMessages?: () => Promise<AgentMessage[]>;
341
+ /**
342
+ * Returns follow-up messages to process after the agent would otherwise stop.
343
+ *
344
+ * Called when the agent has no more tool calls and no steering messages.
345
+ * If messages are returned, they're added to the context and the agent
346
+ * continues with another turn.
347
+ *
348
+ * Use this for follow-up messages that should wait until the agent finishes.
349
+ *
350
+ * Contract: must not throw or reject. Return [] when no follow-up messages are available.
351
+ */
85
352
  getFollowUpMessages?: () => Promise<AgentMessage[]>;
353
+ /**
354
+ * Tool execution mode.
355
+ * - "sequential": execute tool calls one by one
356
+ * - "parallel": preflight tool calls sequentially, then execute allowed tools concurrently;
357
+ * emit `tool_execution_end` in tool completion order after each tool is finalized,
358
+ * then emit tool-result message artifacts later in assistant source order
359
+ *
360
+ * Default: "parallel"
361
+ */
86
362
  toolExecution?: ToolExecutionMode;
363
+ /**
364
+ * Called before a tool is executed, after arguments have been validated.
365
+ *
366
+ * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.
367
+ * The hook receives the agent abort signal and is responsible for honoring it.
368
+ */
87
369
  beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
370
+ /**
371
+ * Classifies an in-loop abort for the short-circuit error results the loop mints when `signal`
372
+ * fires around tool execution (the "Operation aborted" / "operation aborted before execution"
373
+ * family). When supplied, a non-undefined return value is attached as the minted result's
374
+ * `details` — a host that KNOWS why the signal fired (e.g. a durable approval gate parked the
375
+ * batch) stamps a structured marker such as `{ code: "gate.parked" }`, so a consumer can
376
+ * distinguish a park poison frame from a plain cancel WITHOUT parsing the result text. The
377
+ * abort texts themselves are a consumer contract and never change here. Evaluated at mint time
378
+ * (after the abort fired), so the host reads its own post-abort state, not a snapshot.
379
+ */
88
380
  abortResultDetails?: () => Record<string, unknown> | undefined;
381
+ /**
382
+ * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.
383
+ *
384
+ * Return an `AfterToolCallResult` to override parts of the executed tool result:
385
+ * - `content` replaces the full content array
386
+ * - `details` replaces the full details payload
387
+ * - `isError` replaces the error flag
388
+ * - `terminate` replaces the early-termination hint
389
+ *
390
+ * Any omitted fields keep their original values. No deep merge is performed.
391
+ * The hook receives the agent abort signal and is responsible for honoring it.
392
+ */
89
393
  afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
90
394
  }
395
+ /**
396
+ * Thinking/reasoning level for models that support it.
397
+ * Note: "xhigh" is only supported by selected model families. Use model thinking-level metadata
398
+ * from openclaw/plugin-sdk/llm to detect support for a concrete model.
399
+ */
91
400
  export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
92
401
  export interface BashExecutionMessage {
402
+ /** Harness role for shell command transcripts. */
93
403
  role: "bashExecution";
404
+ /** Command line that was executed. */
94
405
  command: string;
406
+ /** Captured command output, usually already truncated for context. */
95
407
  output: string;
408
+ /** Process exit code when the command reached process exit. */
96
409
  exitCode: number | undefined;
410
+ /** True when the command was interrupted before normal completion. */
97
411
  cancelled: boolean;
412
+ /** True when output was shortened for transcript/context storage. */
98
413
  truncated: boolean;
414
+ /** Optional path containing the complete output when truncation occurred. */
99
415
  fullOutputPath?: string;
416
+ /** Millisecond timestamp for transcript ordering. */
100
417
  timestamp: number;
418
+ /** Exclude this command transcript from model context while keeping it in session history. */
101
419
  excludeFromContext?: boolean;
102
420
  }
103
421
  export interface CustomMessage<T = unknown> {
422
+ /** Harness role for application-defined transcript content. */
104
423
  role: "custom";
424
+ /** Application-defined discriminator for rendering or handling this message. */
105
425
  customType: string;
426
+ /** Content replayed into model context when this message is included. */
106
427
  content: string | (TextContent | ImageContent)[];
428
+ /** Whether UI surfaces should display this message. */
107
429
  display: boolean;
430
+ /** Optional application-specific metadata. */
108
431
  details?: T;
432
+ /** [c209-C] R3: this custom message is an ENGINE-INJECTED note (the loop's own recovery nudges) —
433
+ * convertToLlm threads the marker onto the minted user message (`UserMessage.provenance`), so
434
+ * derived views (auto-mode window, compaction serializer) present it under a neutral engine label,
435
+ * never `[user]` authority. Set by the INJECTOR at mint time; absent ⇒ verbatim user-lane render. */
109
436
  provenance?: "engine-note";
437
+ /** Millisecond timestamp for transcript ordering. */
110
438
  timestamp: number;
111
439
  }
112
440
  export interface CompactionSummaryMessage {
441
+ /** Harness role for summaries that replace compacted transcript history. */
113
442
  role: "compactionSummary";
443
+ /** Summary text inserted back into model context. */
114
444
  summary: string;
445
+ /** Estimated context tokens before compaction. */
115
446
  tokensBefore: number;
447
+ /** Timestamp may be numeric in memory or string when loaded from older persisted rows. */
116
448
  timestamp: number | string;
449
+ /** RB-398-b① ([2105]): how many transcript messages this summary stands in for — counted at
450
+ * render time by `buildSessionContext` (the one place entries become context), so it covers the
451
+ * cumulative elision across repeated compactions. Drives the wrapper's scale disclosure
452
+ * (`convertToLlm`); absent (directly constructed messages, older render paths) ⇒ the wrapper is
453
+ * byte-identical to the historical constant. */
117
454
  elidedMessages?: number;
455
+ /** Optional estimated context tokens after compaction. */
118
456
  tokensAfter?: number;
457
+ /** Optional first retained entry id from the compaction range. */
119
458
  firstKeptEntryId?: string;
459
+ /** Optional implementation-specific compaction metadata. */
120
460
  details?: unknown;
121
461
  }
462
+ /**
463
+ * Extensible interface for custom app and harness messages.
464
+ * Apps can extend via declaration merging.
465
+ */
122
466
  export interface CustomAgentMessages {
123
467
  bashExecution: BashExecutionMessage;
124
468
  custom: CustomMessage;
125
469
  compactionSummary: CompactionSummaryMessage;
126
470
  }
471
+ /**
472
+ * AgentMessage: Union of LLM messages + custom messages.
473
+ * This abstraction allows apps to add custom message types while maintaining
474
+ * type safety and compatibility with the base LLM messages.
475
+ */
127
476
  export type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];
477
+ /** Channel-safe progress text emitted by a running tool. */
128
478
  export interface AgentToolProgress {
479
+ /** Public text suitable for user-facing progress surfaces. */
129
480
  text: string;
481
+ /** Tool progress is rendered by channel progress UIs. */
130
482
  visibility: "channel";
483
+ /** Progress text must not contain secrets, private args, or fetched content. */
131
484
  privacy: "public";
485
+ /** Optional stable id for progress line replacement. */
132
486
  id?: string;
133
487
  }
488
+ /** Final or partial result produced by a tool. */
134
489
  export interface AgentToolResult<T> {
490
+ /** Text, image or document content returned to the model. */
135
491
  content: (TextContent | ImageContent | DocumentContent)[];
492
+ /** Arbitrary structured details for logs or UI rendering. */
136
493
  details: T;
494
+ /** [1331]③ — mark a RETURNED failure receipt as an error without throwing (keeps structured
495
+ * `details` while the wire tool_result carries is_error:true; a non-thrown failure marked
496
+ * non-error walks the shell's success rendering and can vanish). Omitted = success. */
137
497
  isError?: boolean;
498
+ /** Optional public progress hint for partial tool updates; never model content. */
138
499
  progress?: AgentToolProgress;
500
+ /**
501
+ * Hint that the agent should stop after the current tool batch.
502
+ * Early termination only happens when every finalized tool result in the batch sets this to true.
503
+ */
139
504
  terminate?: boolean;
140
505
  }
506
+ /** Callback used by tools to stream partial execution updates. */
141
507
  export type AgentToolUpdateCallback<T = unknown> = (partialResult: AgentToolResult<T>) => void;
508
+ /** Tool definition used by the agent runtime. */
142
509
  export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = unknown> extends Tool<TParameters> {
510
+ /** VENDORED EDIT (design/115 P0): inherited from Tool — additional names that dispatch to this tool (RB-476-A: no first-party legacy names remain; the seam serves third-party ToolSpec.aliases). */
143
511
  aliases?: string[];
512
+ /** Human-readable label for UI display. */
144
513
  label: string;
514
+ /**
515
+ * Optional compatibility shim for raw tool-call arguments before schema validation.
516
+ * Must return an object that matches `TParameters`.
517
+ */
145
518
  prepareArguments?: (args: unknown) => Static<TParameters>;
519
+ /** [1245] — OPTIONAL approval display projection: how this tool's args render for a human
520
+ * approval surface (live onAsk dialogs, durable approval inboxes). Pure and cheap; the gate
521
+ * clamps/serializes the result, strips control characters from every string leaf, and swallows
522
+ * throws. **UNTRUSTED + ADVISORY-ONLY** (codex [1245] F1): the projection is authored by the
523
+ * tool over model-authored args and can misrepresent the executable action — renderers MUST
524
+ * contextually escape it, and approval surfaces MUST offer the bound raw args alongside
525
+ * (boundInputHash binds args, never the preview). NEVER adjudication input. Mechanism-neutral:
526
+ * any tool may declare one (run_workflow projects its script meta). */
146
527
  approvalPreview?: (args: unknown) => unknown;
528
+ /** Execute the tool call. Throw on failure instead of encoding errors in `content`. */
147
529
  execute: (toolCallId: string, params: Static<TParameters>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
530
+ /**
531
+ * Per-tool execution mode override.
532
+ * - "sequential": this tool must execute one at a time with other tool calls.
533
+ * - "parallel": this tool can execute concurrently with other tool calls.
534
+ *
535
+ * If omitted, the tool is treated as NOT concurrency-safe unless its input-level
536
+ * `isConcurrencySafe` hook opts a call in (fail-closed; CC 2.1.206 TOOL_DEFAULTS parity).
537
+ */
148
538
  executionMode?: ToolExecutionMode;
539
+ /**
540
+ * MCP server self-declared result-size threshold (CC 198 `_meta["anthropic/maxResultSizeChars"]`,
541
+ * pretty.js:320015/:320061 — consumer caps at 500K). Set by the MCP materializer when the server
542
+ * declares it; consulted by the offload mount in prepare-task. Absent on non-MCP tools.
543
+ */
149
544
  mcpMaxResultSizeChars?: number;
545
+ /**
546
+ * RB-400-a — MCP server-declared inline pin (CC 220 `_meta["anthropic/alwaysLoad"]`): set by the
547
+ * MCP materializer when the server's tools/list entry declares it; prepare-task folds these names
548
+ * into the defer classification's exemption set, ahead of the MCP constant-defer arm — the
549
+ * server's own channel for keeping one tool's full schema inlined. Absent on non-MCP tools.
550
+ */
150
551
  mcpAlwaysLoad?: boolean;
552
+ /**
553
+ * design/120 P1.5 (CC `isConcurrencySafe(parsedInput)` parity): INPUT-level concurrency refinement
554
+ * for a tool whose safety depends on its arguments — CC's only real consumer is
555
+ * Bash (a read-only command is safe to parallelize; a write command is not). Consulted by the
556
+ * partitioner for every tool WITHOUT an explicit `executionMode:"parallel"` (a statically-parallel
557
+ * tool needs no refinement); `true` = treat THIS CALL as concurrency-safe. A throw = false
558
+ * (fail-closed, CC same). The partitioner validates the call's args against the tool schema FIRST
559
+ * (schema-invalid ⇒ unsafe, CC 206 safeParse parity) and hands the hook the validated+coerced
560
+ * args — still treat defensively (a direct caller may pass raw args). Omitted ⇒ the static mode stands.
561
+ */
151
562
  isConcurrencySafe?: (args: unknown) => boolean;
152
563
  }
564
+ /** Context snapshot passed into the low-level agent loop. */
153
565
  export interface AgentContext {
566
+ /** System prompt included with the request. */
154
567
  systemPrompt: string;
568
+ /** S4 (additive): the physical system-block face for block-aware brains. When present it always
569
+ * corresponds to the same bytes as `systemPrompt` (M13 projection duty — producer-enforced). */
155
570
  systemBlocks?: Array<{
156
571
  text: string;
157
572
  cacheControlBoundary: boolean;
158
573
  }>;
574
+ /** Transcript visible to the model. */
159
575
  messages: AgentMessage[];
576
+ /** Tools available for this run. */
160
577
  tools?: AgentTool[];
161
578
  }
579
+ /**
580
+ * Events emitted by the Agent for UI updates.
581
+ *
582
+ * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`
583
+ * listeners for that event are still part of run settlement. The agent becomes
584
+ * idle only after those listeners finish.
585
+ */
162
586
  export type AgentEvent = {
163
587
  type: "agent_start";
164
588
  } | {
@@ -1,2 +1,15 @@
1
+ /**
2
+ * LSP base-protocol framing over a byte stream (stdio) — `Content-Length: <n>\r\n\r\n<n bytes of JSON>`. A
3
+ * language server speaks JSON-RPC over stdin/stdout with THIS framing (the part a WebSocket transport skips,
4
+ * since each WS message is already one message). Ported 1:1 from service's unit-tested `lsp-frames` bridge
5
+ * decoder + CC's `StreamMessageReader`/`StreamMessageWriter` (vscode-jsonrpc) — hand-rolled here to keep core
6
+ * dependency-free (the framing is trivial; a native LSP-client dep is not worth it).
7
+ */
8
+ /** Encode a JSON-RPC message body as an LSP base-protocol frame (header + payload) ready to write to stdin. */
1
9
  export declare function encodeFrame(json: string): Buffer;
10
+ /**
11
+ * A stateful decoder: feed it stdout chunks, get back complete JSON payloads (0+ per chunk — a frame can span
12
+ * chunks, and a chunk can hold several). `maxBytes` caps the buffer so a server that never emits a delimiter
13
+ * (or a corrupt Content-Length) can't grow it unboundedly — on overflow the buffer is dropped (fail-safe).
14
+ */
2
15
  export declare function createFrameDecoder(maxBytes?: number): (chunk: Buffer) => string[];