strands-darwin 0.0.3

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 (417) hide show
  1. package/README.md +140 -0
  2. package/README.zh-CN.md +140 -0
  3. package/dist/patches/@strands-agents+sdk+1.16.0.patch +1443 -0
  4. package/dist/src/agent/background-delegation.d.ts +67 -0
  5. package/dist/src/agent/background-delegation.js +159 -0
  6. package/dist/src/agent/background-delegation.js.map +1 -0
  7. package/dist/src/agent/call-stats.d.ts +118 -0
  8. package/dist/src/agent/call-stats.js +128 -0
  9. package/dist/src/agent/call-stats.js.map +1 -0
  10. package/dist/src/agent/compact.d.ts +108 -0
  11. package/dist/src/agent/compact.js +192 -0
  12. package/dist/src/agent/compact.js.map +1 -0
  13. package/dist/src/agent/context-anchor.d.ts +64 -0
  14. package/dist/src/agent/context-anchor.js +43 -0
  15. package/dist/src/agent/context-anchor.js.map +1 -0
  16. package/dist/src/agent/cost.d.ts +56 -0
  17. package/dist/src/agent/cost.js +44 -0
  18. package/dist/src/agent/cost.js.map +1 -0
  19. package/dist/src/agent/diagnostics.d.ts +212 -0
  20. package/dist/src/agent/diagnostics.js +374 -0
  21. package/dist/src/agent/diagnostics.js.map +1 -0
  22. package/dist/src/agent/instructions.d.ts +54 -0
  23. package/dist/src/agent/instructions.js +118 -0
  24. package/dist/src/agent/instructions.js.map +1 -0
  25. package/dist/src/agent/max-tokens-recovery.d.ts +17 -0
  26. package/dist/src/agent/max-tokens-recovery.js +65 -0
  27. package/dist/src/agent/max-tokens-recovery.js.map +1 -0
  28. package/dist/src/agent/model-call-budget.d.ts +8 -0
  29. package/dist/src/agent/model-call-budget.js +24 -0
  30. package/dist/src/agent/model-call-budget.js.map +1 -0
  31. package/dist/src/agent/model-retry.d.ts +134 -0
  32. package/dist/src/agent/model-retry.js +256 -0
  33. package/dist/src/agent/model-retry.js.map +1 -0
  34. package/dist/src/agent/permission-rules.d.ts +47 -0
  35. package/dist/src/agent/permission-rules.js +260 -0
  36. package/dist/src/agent/permission-rules.js.map +1 -0
  37. package/dist/src/agent/permission.d.ts +361 -0
  38. package/dist/src/agent/permission.js +797 -0
  39. package/dist/src/agent/permission.js.map +1 -0
  40. package/dist/src/agent/prompt-cache.d.ts +66 -0
  41. package/dist/src/agent/prompt-cache.js +194 -0
  42. package/dist/src/agent/prompt-cache.js.map +1 -0
  43. package/dist/src/agent/refusal.d.ts +20 -0
  44. package/dist/src/agent/refusal.js +23 -0
  45. package/dist/src/agent/refusal.js.map +1 -0
  46. package/dist/src/agent/retry-guard.d.ts +26 -0
  47. package/dist/src/agent/retry-guard.js +193 -0
  48. package/dist/src/agent/retry-guard.js.map +1 -0
  49. package/dist/src/agent/rewind.d.ts +29 -0
  50. package/dist/src/agent/rewind.js +118 -0
  51. package/dist/src/agent/rewind.js.map +1 -0
  52. package/dist/src/agent/runtime.d.ts +814 -0
  53. package/dist/src/agent/runtime.js +1596 -0
  54. package/dist/src/agent/runtime.js.map +1 -0
  55. package/dist/src/agent/safety-classifier.d.ts +11 -0
  56. package/dist/src/agent/safety-classifier.js +0 -0
  57. package/dist/src/agent/safety-classifier.js.map +1 -0
  58. package/dist/src/agent/sdk-logging.d.ts +49 -0
  59. package/dist/src/agent/sdk-logging.js +110 -0
  60. package/dist/src/agent/sdk-logging.js.map +1 -0
  61. package/dist/src/agent/session.d.ts +102 -0
  62. package/dist/src/agent/session.js +244 -0
  63. package/dist/src/agent/session.js.map +1 -0
  64. package/dist/src/agent/stream-resumption.d.ts +16 -0
  65. package/dist/src/agent/stream-resumption.js +33 -0
  66. package/dist/src/agent/stream-resumption.js.map +1 -0
  67. package/dist/src/agent/system-prompt.d.ts +50 -0
  68. package/dist/src/agent/system-prompt.js +161 -0
  69. package/dist/src/agent/system-prompt.js.map +1 -0
  70. package/dist/src/agent/thinking.d.ts +99 -0
  71. package/dist/src/agent/thinking.js +145 -0
  72. package/dist/src/agent/thinking.js.map +1 -0
  73. package/dist/src/agent/usage.d.ts +132 -0
  74. package/dist/src/agent/usage.js +233 -0
  75. package/dist/src/agent/usage.js.map +1 -0
  76. package/dist/src/agent/working-context.d.ts +51 -0
  77. package/dist/src/agent/working-context.js +160 -0
  78. package/dist/src/agent/working-context.js.map +1 -0
  79. package/dist/src/agents/child-recipe.d.ts +33 -0
  80. package/dist/src/agents/child-recipe.js +98 -0
  81. package/dist/src/agents/child-recipe.js.map +1 -0
  82. package/dist/src/agents/concurrency-limit.d.ts +25 -0
  83. package/dist/src/agents/concurrency-limit.js +43 -0
  84. package/dist/src/agents/concurrency-limit.js.map +1 -0
  85. package/dist/src/agents/dispatch-registry.d.ts +180 -0
  86. package/dist/src/agents/dispatch-registry.js +289 -0
  87. package/dist/src/agents/dispatch-registry.js.map +1 -0
  88. package/dist/src/agents/failed-child-text.d.ts +44 -0
  89. package/dist/src/agents/failed-child-text.js +69 -0
  90. package/dist/src/agents/failed-child-text.js.map +1 -0
  91. package/dist/src/agents/loader.d.ts +26 -0
  92. package/dist/src/agents/loader.js +134 -0
  93. package/dist/src/agents/loader.js.map +1 -0
  94. package/dist/src/agents/report-projection.d.ts +31 -0
  95. package/dist/src/agents/report-projection.js +125 -0
  96. package/dist/src/agents/report-projection.js.map +1 -0
  97. package/dist/src/agents/subagent-tool.d.ts +61 -0
  98. package/dist/src/agents/subagent-tool.js +180 -0
  99. package/dist/src/agents/subagent-tool.js.map +1 -0
  100. package/dist/src/agents/workflow-tool.d.ts +85 -0
  101. package/dist/src/agents/workflow-tool.js +530 -0
  102. package/dist/src/agents/workflow-tool.js.map +1 -0
  103. package/dist/src/cli-args.d.ts +39 -0
  104. package/dist/src/cli-args.js +198 -0
  105. package/dist/src/cli-args.js.map +1 -0
  106. package/dist/src/cli-doctor.d.ts +26 -0
  107. package/dist/src/cli-doctor.js +398 -0
  108. package/dist/src/cli-doctor.js.map +1 -0
  109. package/dist/src/cli-main.d.ts +1 -0
  110. package/dist/src/cli-main.js +279 -0
  111. package/dist/src/cli-main.js.map +1 -0
  112. package/dist/src/cli-sessions.d.ts +17 -0
  113. package/dist/src/cli-sessions.js +136 -0
  114. package/dist/src/cli-sessions.js.map +1 -0
  115. package/dist/src/cli-trajectory.d.ts +37 -0
  116. package/dist/src/cli-trajectory.js +303 -0
  117. package/dist/src/cli-trajectory.js.map +1 -0
  118. package/dist/src/cli-usage.d.ts +18 -0
  119. package/dist/src/cli-usage.js +53 -0
  120. package/dist/src/cli-usage.js.map +1 -0
  121. package/dist/src/cli.d.ts +2 -0
  122. package/dist/src/cli.js +29 -0
  123. package/dist/src/cli.js.map +1 -0
  124. package/dist/src/commands/custom-commands.d.ts +43 -0
  125. package/dist/src/commands/custom-commands.js +155 -0
  126. package/dist/src/commands/custom-commands.js.map +1 -0
  127. package/dist/src/commands/workflow-command.d.ts +26 -0
  128. package/dist/src/commands/workflow-command.js +56 -0
  129. package/dist/src/commands/workflow-command.js.map +1 -0
  130. package/dist/src/config.d.ts +463 -0
  131. package/dist/src/config.js +1457 -0
  132. package/dist/src/config.js.map +1 -0
  133. package/dist/src/context-overflow-error.d.ts +7 -0
  134. package/dist/src/context-overflow-error.js +26 -0
  135. package/dist/src/context-overflow-error.js.map +1 -0
  136. package/dist/src/dev-repl.d.ts +1 -0
  137. package/dist/src/dev-repl.js +365 -0
  138. package/dist/src/dev-repl.js.map +1 -0
  139. package/dist/src/headless-protocol.d.ts +147 -0
  140. package/dist/src/headless-protocol.js +359 -0
  141. package/dist/src/headless-protocol.js.map +1 -0
  142. package/dist/src/headless-runner.d.ts +30 -0
  143. package/dist/src/headless-runner.js +405 -0
  144. package/dist/src/headless-runner.js.map +1 -0
  145. package/dist/src/headless-stdin.d.ts +28 -0
  146. package/dist/src/headless-stdin.js +78 -0
  147. package/dist/src/headless-stdin.js.map +1 -0
  148. package/dist/src/headless.d.ts +106 -0
  149. package/dist/src/headless.js +229 -0
  150. package/dist/src/headless.js.map +1 -0
  151. package/dist/src/hooks/codex-hook-runner.d.ts +92 -0
  152. package/dist/src/hooks/codex-hook-runner.js +446 -0
  153. package/dist/src/hooks/codex-hook-runner.js.map +1 -0
  154. package/dist/src/hooks/codex-hooks.d.ts +23 -0
  155. package/dist/src/hooks/codex-hooks.js +152 -0
  156. package/dist/src/hooks/codex-hooks.js.map +1 -0
  157. package/dist/src/hooks/hook-process.d.ts +23 -0
  158. package/dist/src/hooks/hook-process.js +241 -0
  159. package/dist/src/hooks/hook-process.js.map +1 -0
  160. package/dist/src/hooks/lifecycle-hooks.d.ts +37 -0
  161. package/dist/src/hooks/lifecycle-hooks.js +153 -0
  162. package/dist/src/hooks/lifecycle-hooks.js.map +1 -0
  163. package/dist/src/hooks/tool-hooks.d.ts +63 -0
  164. package/dist/src/hooks/tool-hooks.js +350 -0
  165. package/dist/src/hooks/tool-hooks.js.map +1 -0
  166. package/dist/src/mcp/codegraph-preflight.d.ts +29 -0
  167. package/dist/src/mcp/codegraph-preflight.js +232 -0
  168. package/dist/src/mcp/codegraph-preflight.js.map +1 -0
  169. package/dist/src/mcp/registry.d.ts +133 -0
  170. package/dist/src/mcp/registry.js +209 -0
  171. package/dist/src/mcp/registry.js.map +1 -0
  172. package/dist/src/mcp/web-search-empty-results.d.ts +14 -0
  173. package/dist/src/mcp/web-search-empty-results.js +94 -0
  174. package/dist/src/mcp/web-search-empty-results.js.map +1 -0
  175. package/dist/src/memory/command.d.ts +11 -0
  176. package/dist/src/memory/command.js +253 -0
  177. package/dist/src/memory/command.js.map +1 -0
  178. package/dist/src/memory/controller.d.ts +51 -0
  179. package/dist/src/memory/controller.js +316 -0
  180. package/dist/src/memory/controller.js.map +1 -0
  181. package/dist/src/memory/prompt.d.ts +4 -0
  182. package/dist/src/memory/prompt.js +22 -0
  183. package/dist/src/memory/prompt.js.map +1 -0
  184. package/dist/src/memory/scheduler.d.ts +33 -0
  185. package/dist/src/memory/scheduler.js +134 -0
  186. package/dist/src/memory/scheduler.js.map +1 -0
  187. package/dist/src/memory/state.d.ts +112 -0
  188. package/dist/src/memory/state.js +355 -0
  189. package/dist/src/memory/state.js.map +1 -0
  190. package/dist/src/memory/store.d.ts +19 -0
  191. package/dist/src/memory/store.js +130 -0
  192. package/dist/src/memory/store.js.map +1 -0
  193. package/dist/src/memory/tools.d.ts +29 -0
  194. package/dist/src/memory/tools.js +22 -0
  195. package/dist/src/memory/tools.js.map +1 -0
  196. package/dist/src/memory/validation.d.ts +33 -0
  197. package/dist/src/memory/validation.js +159 -0
  198. package/dist/src/memory/validation.js.map +1 -0
  199. package/dist/src/npm-package/generate-patch.d.ts +23 -0
  200. package/dist/src/npm-package/generate-patch.js +88 -0
  201. package/dist/src/npm-package/generate-patch.js.map +1 -0
  202. package/dist/src/npm-package/patch-package-format.d.ts +43 -0
  203. package/dist/src/npm-package/patch-package-format.js +66 -0
  204. package/dist/src/npm-package/patch-package-format.js.map +1 -0
  205. package/dist/src/paths.d.ts +39 -0
  206. package/dist/src/paths.js +105 -0
  207. package/dist/src/paths.js.map +1 -0
  208. package/dist/src/pricing/cost.d.ts +182 -0
  209. package/dist/src/pricing/cost.js +215 -0
  210. package/dist/src/pricing/cost.js.map +1 -0
  211. package/dist/src/pricing/model-prices.d.ts +112 -0
  212. package/dist/src/pricing/model-prices.js +320 -0
  213. package/dist/src/pricing/model-prices.js.map +1 -0
  214. package/dist/src/sdk-patch-preflight.d.ts +23 -0
  215. package/dist/src/sdk-patch-preflight.js +71 -0
  216. package/dist/src/sdk-patch-preflight.js.map +1 -0
  217. package/dist/src/skills/builtin/commit-message/SKILL.md +45 -0
  218. package/dist/src/skills/builtin/commit-message/references/types.md +8 -0
  219. package/dist/src/skills/builtin/developer/SKILL.md +107 -0
  220. package/dist/src/skills/builtin/self-evolution-research/SKILL.md +150 -0
  221. package/dist/src/skills/builtin/self-evolution-research/scripts/roll-research-path.mjs +208 -0
  222. package/dist/src/skills/builtin/self-reflection/SKILL.md +172 -0
  223. package/dist/src/skills/builtin/self-reflection/references/reflection-template.md +90 -0
  224. package/dist/src/skills/builtin/self-reflection/scripts/locate-trajectory.mjs +175 -0
  225. package/dist/src/skills/loader.d.ts +26 -0
  226. package/dist/src/skills/loader.js +186 -0
  227. package/dist/src/skills/loader.js.map +1 -0
  228. package/dist/src/skills/plugin.d.ts +34 -0
  229. package/dist/src/skills/plugin.js +137 -0
  230. package/dist/src/skills/plugin.js.map +1 -0
  231. package/dist/src/skills/prompt.d.ts +8 -0
  232. package/dist/src/skills/prompt.js +214 -0
  233. package/dist/src/skills/prompt.js.map +1 -0
  234. package/dist/src/skills/resource-safety.d.ts +15 -0
  235. package/dist/src/skills/resource-safety.js +149 -0
  236. package/dist/src/skills/resource-safety.js.map +1 -0
  237. package/dist/src/tools/background-bash.d.ts +95 -0
  238. package/dist/src/tools/background-bash.js +639 -0
  239. package/dist/src/tools/background-bash.js.map +1 -0
  240. package/dist/src/tools/background-tail.d.ts +28 -0
  241. package/dist/src/tools/background-tail.js +75 -0
  242. package/dist/src/tools/background-tail.js.map +1 -0
  243. package/dist/src/tools/background-wait-contract.d.ts +4 -0
  244. package/dist/src/tools/background-wait-contract.js +7 -0
  245. package/dist/src/tools/background-wait-contract.js.map +1 -0
  246. package/dist/src/tools/file-editor-serial.d.ts +24 -0
  247. package/dist/src/tools/file-editor-serial.js +99 -0
  248. package/dist/src/tools/file-editor-serial.js.map +1 -0
  249. package/dist/src/tools/image-viewer.d.ts +43 -0
  250. package/dist/src/tools/image-viewer.js +256 -0
  251. package/dist/src/tools/image-viewer.js.map +1 -0
  252. package/dist/src/tools/update-plan.d.ts +30 -0
  253. package/dist/src/tools/update-plan.js +65 -0
  254. package/dist/src/tools/update-plan.js.map +1 -0
  255. package/dist/src/tools/web-fetch.d.ts +70 -0
  256. package/dist/src/tools/web-fetch.js +667 -0
  257. package/dist/src/tools/web-fetch.js.map +1 -0
  258. package/dist/src/trajectory/export.d.ts +31 -0
  259. package/dist/src/trajectory/export.js +116 -0
  260. package/dist/src/trajectory/export.js.map +1 -0
  261. package/dist/src/trajectory/fork.d.ts +19 -0
  262. package/dist/src/trajectory/fork.js +110 -0
  263. package/dist/src/trajectory/fork.js.map +1 -0
  264. package/dist/src/trajectory/memory-tool.d.ts +20 -0
  265. package/dist/src/trajectory/memory-tool.js +98 -0
  266. package/dist/src/trajectory/memory-tool.js.map +1 -0
  267. package/dist/src/trajectory/prompt-history.d.ts +62 -0
  268. package/dist/src/trajectory/prompt-history.js +256 -0
  269. package/dist/src/trajectory/prompt-history.js.map +1 -0
  270. package/dist/src/trajectory/reader.d.ts +21 -0
  271. package/dist/src/trajectory/reader.js +62 -0
  272. package/dist/src/trajectory/reader.js.map +1 -0
  273. package/dist/src/trajectory/record.d.ts +417 -0
  274. package/dist/src/trajectory/record.js +394 -0
  275. package/dist/src/trajectory/record.js.map +1 -0
  276. package/dist/src/trajectory/replay.d.ts +74 -0
  277. package/dist/src/trajectory/replay.js +285 -0
  278. package/dist/src/trajectory/replay.js.map +1 -0
  279. package/dist/src/trajectory/resume-recap.d.ts +43 -0
  280. package/dist/src/trajectory/resume-recap.js +68 -0
  281. package/dist/src/trajectory/resume-recap.js.map +1 -0
  282. package/dist/src/trajectory/search.d.ts +40 -0
  283. package/dist/src/trajectory/search.js +127 -0
  284. package/dist/src/trajectory/search.js.map +1 -0
  285. package/dist/src/trajectory/spend.d.ts +157 -0
  286. package/dist/src/trajectory/spend.js +264 -0
  287. package/dist/src/trajectory/spend.js.map +1 -0
  288. package/dist/src/trajectory/stream.d.ts +30 -0
  289. package/dist/src/trajectory/stream.js +30 -0
  290. package/dist/src/trajectory/stream.js.map +1 -0
  291. package/dist/src/trajectory/writer.d.ts +310 -0
  292. package/dist/src/trajectory/writer.js +636 -0
  293. package/dist/src/trajectory/writer.js.map +1 -0
  294. package/dist/src/tui/App.d.ts +109 -0
  295. package/dist/src/tui/App.js +2660 -0
  296. package/dist/src/tui/App.js.map +1 -0
  297. package/dist/src/tui/InputBox.d.ts +90 -0
  298. package/dist/src/tui/InputBox.js +129 -0
  299. package/dist/src/tui/InputBox.js.map +1 -0
  300. package/dist/src/tui/MarkdownText.d.ts +16 -0
  301. package/dist/src/tui/MarkdownText.js +117 -0
  302. package/dist/src/tui/MarkdownText.js.map +1 -0
  303. package/dist/src/tui/MessageList.d.ts +27 -0
  304. package/dist/src/tui/MessageList.js +61 -0
  305. package/dist/src/tui/MessageList.js.map +1 -0
  306. package/dist/src/tui/PermissionPrompt.d.ts +18 -0
  307. package/dist/src/tui/PermissionPrompt.js +114 -0
  308. package/dist/src/tui/PermissionPrompt.js.map +1 -0
  309. package/dist/src/tui/PlanChecklist.d.ts +7 -0
  310. package/dist/src/tui/PlanChecklist.js +12 -0
  311. package/dist/src/tui/PlanChecklist.js.map +1 -0
  312. package/dist/src/tui/QueuedMessages.d.ts +8 -0
  313. package/dist/src/tui/QueuedMessages.js +24 -0
  314. package/dist/src/tui/QueuedMessages.js.map +1 -0
  315. package/dist/src/tui/StartupScreen.d.ts +25 -0
  316. package/dist/src/tui/StartupScreen.js +51 -0
  317. package/dist/src/tui/StartupScreen.js.map +1 -0
  318. package/dist/src/tui/ToolCallPanel.d.ts +33 -0
  319. package/dist/src/tui/ToolCallPanel.js +112 -0
  320. package/dist/src/tui/ToolCallPanel.js.map +1 -0
  321. package/dist/src/tui/WelcomeHeader.d.ts +30 -0
  322. package/dist/src/tui/WelcomeHeader.js +69 -0
  323. package/dist/src/tui/WelcomeHeader.js.map +1 -0
  324. package/dist/src/tui/background-tool-presentation.d.ts +22 -0
  325. package/dist/src/tui/background-tool-presentation.js +209 -0
  326. package/dist/src/tui/background-tool-presentation.js.map +1 -0
  327. package/dist/src/tui/busy-suffix.d.ts +37 -0
  328. package/dist/src/tui/busy-suffix.js +39 -0
  329. package/dist/src/tui/busy-suffix.js.map +1 -0
  330. package/dist/src/tui/clipboard-image.d.ts +18 -0
  331. package/dist/src/tui/clipboard-image.js +109 -0
  332. package/dist/src/tui/clipboard-image.js.map +1 -0
  333. package/dist/src/tui/context-format.d.ts +43 -0
  334. package/dist/src/tui/context-format.js +71 -0
  335. package/dist/src/tui/context-format.js.map +1 -0
  336. package/dist/src/tui/copy-command.d.ts +68 -0
  337. package/dist/src/tui/copy-command.js +182 -0
  338. package/dist/src/tui/copy-command.js.map +1 -0
  339. package/dist/src/tui/edit-diff.d.ts +135 -0
  340. package/dist/src/tui/edit-diff.js +356 -0
  341. package/dist/src/tui/edit-diff.js.map +1 -0
  342. package/dist/src/tui/frame-budget.d.ts +351 -0
  343. package/dist/src/tui/frame-budget.js +446 -0
  344. package/dist/src/tui/frame-budget.js.map +1 -0
  345. package/dist/src/tui/help-format.d.ts +17 -0
  346. package/dist/src/tui/help-format.js +38 -0
  347. package/dist/src/tui/help-format.js.map +1 -0
  348. package/dist/src/tui/live-text.d.ts +51 -0
  349. package/dist/src/tui/live-text.js +154 -0
  350. package/dist/src/tui/live-text.js.map +1 -0
  351. package/dist/src/tui/markdown.d.ts +62 -0
  352. package/dist/src/tui/markdown.js +244 -0
  353. package/dist/src/tui/markdown.js.map +1 -0
  354. package/dist/src/tui/mcp-format.d.ts +28 -0
  355. package/dist/src/tui/mcp-format.js +67 -0
  356. package/dist/src/tui/mcp-format.js.map +1 -0
  357. package/dist/src/tui/path-completion.d.ts +119 -0
  358. package/dist/src/tui/path-completion.js +305 -0
  359. package/dist/src/tui/path-completion.js.map +1 -0
  360. package/dist/src/tui/permission-queue.d.ts +61 -0
  361. package/dist/src/tui/permission-queue.js +129 -0
  362. package/dist/src/tui/permission-queue.js.map +1 -0
  363. package/dist/src/tui/plan-format.d.ts +9 -0
  364. package/dist/src/tui/plan-format.js +30 -0
  365. package/dist/src/tui/plan-format.js.map +1 -0
  366. package/dist/src/tui/prompt-completion.d.ts +22 -0
  367. package/dist/src/tui/prompt-completion.js +46 -0
  368. package/dist/src/tui/prompt-completion.js.map +1 -0
  369. package/dist/src/tui/prompt-editor.d.ts +102 -0
  370. package/dist/src/tui/prompt-editor.js +379 -0
  371. package/dist/src/tui/prompt-editor.js.map +1 -0
  372. package/dist/src/tui/prompt-history-search.d.ts +53 -0
  373. package/dist/src/tui/prompt-history-search.js +123 -0
  374. package/dist/src/tui/prompt-history-search.js.map +1 -0
  375. package/dist/src/tui/prompt-queue.d.ts +58 -0
  376. package/dist/src/tui/prompt-queue.js +74 -0
  377. package/dist/src/tui/prompt-queue.js.map +1 -0
  378. package/dist/src/tui/prompt-recall.d.ts +74 -0
  379. package/dist/src/tui/prompt-recall.js +90 -0
  380. package/dist/src/tui/prompt-recall.js.map +1 -0
  381. package/dist/src/tui/react-environment.d.ts +11 -0
  382. package/dist/src/tui/react-environment.js +24 -0
  383. package/dist/src/tui/react-environment.js.map +1 -0
  384. package/dist/src/tui/rewind-search.d.ts +34 -0
  385. package/dist/src/tui/rewind-search.js +68 -0
  386. package/dist/src/tui/rewind-search.js.map +1 -0
  387. package/dist/src/tui/shell-command.d.ts +114 -0
  388. package/dist/src/tui/shell-command.js +310 -0
  389. package/dist/src/tui/shell-command.js.map +1 -0
  390. package/dist/src/tui/spend-advisory.d.ts +52 -0
  391. package/dist/src/tui/spend-advisory.js +64 -0
  392. package/dist/src/tui/spend-advisory.js.map +1 -0
  393. package/dist/src/tui/status-format.d.ts +120 -0
  394. package/dist/src/tui/status-format.js +192 -0
  395. package/dist/src/tui/status-format.js.map +1 -0
  396. package/dist/src/tui/subagent-format.d.ts +49 -0
  397. package/dist/src/tui/subagent-format.js +146 -0
  398. package/dist/src/tui/subagent-format.js.map +1 -0
  399. package/dist/src/tui/task-format.d.ts +29 -0
  400. package/dist/src/tui/task-format.js +87 -0
  401. package/dist/src/tui/task-format.js.map +1 -0
  402. package/dist/src/tui/terminal-bell.d.ts +20 -0
  403. package/dist/src/tui/terminal-bell.js +33 -0
  404. package/dist/src/tui/terminal-bell.js.map +1 -0
  405. package/dist/src/tui/tool-detail-presentation.d.ts +60 -0
  406. package/dist/src/tui/tool-detail-presentation.js +206 -0
  407. package/dist/src/tui/tool-detail-presentation.js.map +1 -0
  408. package/dist/src/tui/turn-state.d.ts +195 -0
  409. package/dist/src/tui/turn-state.js +548 -0
  410. package/dist/src/tui/turn-state.js.map +1 -0
  411. package/dist/src/tui/visual-language.d.ts +45 -0
  412. package/dist/src/tui/visual-language.js +57 -0
  413. package/dist/src/tui/visual-language.js.map +1 -0
  414. package/dist/src/version.d.ts +7 -0
  415. package/dist/src/version.js +38 -0
  416. package/dist/src/version.js.map +1 -0
  417. package/package.json +60 -0
@@ -0,0 +1,1596 @@
1
+ /**
2
+ * Agent assembly. The only place that constructs the SDK `Agent`.
3
+ *
4
+ * The runtime is deliberately thin: it wires SDK pieces together and hands the
5
+ * raw event stream to whatever is driving it. Callers (the dev REPL now, Ink
6
+ * later) decide how to render.
7
+ */
8
+ import { Agent, BeforeInvocationEvent, SummarizingConversationManager, TextBlock } from '@strands-agents/sdk';
9
+ import { fileEditor } from '@strands-agents/sdk/vended-tools/file-editor';
10
+ import { httpRequest } from '@strands-agents/sdk/vended-tools/http-request';
11
+ import { ContextOffloader } from '@strands-agents/sdk/vended-plugins/context-offloader';
12
+ import { LocalFileStorage } from '@strands-agents/sdk/storage';
13
+ import path from 'node:path';
14
+ import { compactConversation, countConversationTokens, createCompactionManager, normalizeCompactFocus, stripReasoningFromUserMessages, } from './compact.js';
15
+ import { DiagnosticsLog } from './diagnostics.js';
16
+ import { BackgroundDelegationObserver, backgroundDelegationConfig, MANAGE_BACKGROUND_TASK_TOOL_NAME, } from './background-delegation.js';
17
+ import { installMaxTokensRecovery } from './max-tokens-recovery.js';
18
+ import { installModelCallBudget } from './model-call-budget.js';
19
+ import { installModelRetry } from './model-retry.js';
20
+ import { loadAgentDefinitions } from '../agents/loader.js';
21
+ import { concurrencyCap } from '../agents/concurrency-limit.js';
22
+ import { SubagentDispatchRegistry, } from '../agents/dispatch-registry.js';
23
+ import { SUBAGENT_TOOL_NAME, SubagentTool } from '../agents/subagent-tool.js';
24
+ import { WORKFLOW_TOOL_NAME, WorkflowTool } from '../agents/workflow-tool.js';
25
+ import { expandCustomCommand, loadCustomCommands, } from '../commands/custom-commands.js';
26
+ import { parseWorkflowCommand } from '../commands/workflow-command.js';
27
+ import { appendAllowRule, applyThinkingEffort, createModelFromConfig, loadConfig, loadProjectPolicy, permissionRulesPath, removeAllowRules, saveEnabledModel, saveThinkingEffort, withModelChoice, } from '../config.js';
28
+ import { BackgroundBashManager, createBackgroundBashTool, createForegroundBashTool, } from '../tools/background-bash.js';
29
+ import { SerializedFileEditorTool } from '../tools/file-editor-serial.js';
30
+ import { createImageViewerTool, normalizeRestoredImages } from '../tools/image-viewer.js';
31
+ import { createUpdatePlanTool } from '../tools/update-plan.js';
32
+ import { webFetch } from '../tools/web-fetch.js';
33
+ import { LifecycleHookRunner, lifecycleHooksFromConfig, } from '../hooks/lifecycle-hooks.js';
34
+ import { CodexHookRunner, injectCodexContext } from '../hooks/codex-hook-runner.js';
35
+ import { ToolHookGate } from '../hooks/tool-hooks.js';
36
+ import { CodeGraphPreflight } from '../mcp/codegraph-preflight.js';
37
+ import { disconnectAll, loadMcpClients, mcpServerStatuses } from '../mcp/registry.js';
38
+ import { WebSearchEmptyResults } from '../mcp/web-search-empty-results.js';
39
+ import { SkillsPlugin, expandSkillCommand } from '../skills/plugin.js';
40
+ import { orderOfficialSkillsPrompt } from '../skills/prompt.js';
41
+ import { runMemoryCommand } from '../memory/command.js';
42
+ import { MemoryToolController } from '../memory/controller.js';
43
+ import { createMemoryTools } from '../memory/tools.js';
44
+ import { recordStream } from '../trajectory/stream.js';
45
+ import { TrajectoryRecorder, } from '../trajectory/writer.js';
46
+ import { DARWIN_VERSION } from '../version.js';
47
+ import { composeSystemPrompt, loadProjectInstructions, } from './instructions.js';
48
+ import { PermissionGate } from './permission.js';
49
+ import { applySystemPromptCachePoint, canUpdateSystemPromptCache, planPromptCache, } from './prompt-cache.js';
50
+ import { createModelClassifier } from './safety-classifier.js';
51
+ import { createSessionManager, diagnosticsPath, resolveSession, sessionPaths, trajectoryPath, writePointer, } from './session.js';
52
+ import { setSdkVerboseSink } from './sdk-logging.js';
53
+ import { loadSystemPrompt } from './system-prompt.js';
54
+ import { applyWorkingContext, buildWorkingContext } from './working-context.js';
55
+ import { planThinking } from './thinking.js';
56
+ import { MAX_REWIND_CHECKPOINTS, appendRewindCheckpoint, newestRewindCheckpoints, readRewindCatalogue, rewindPromptEligible, } from './rewind.js';
57
+ import { deltaUsage, startCallSpend, startTurnSpend, sumUsage } from './usage.js';
58
+ import { emptyCallStats, recordCompletedCall, } from './call-stats.js';
59
+ import { anchorFromCall, resolveAnchor } from './context-anchor.js';
60
+ import { defaultModelPriceStore } from '../pricing/model-prices.js';
61
+ let runtimeCreateCheckpoint;
62
+ export function setRuntimeCreateCheckpointForTest(callback) {
63
+ runtimeCreateCheckpoint = callback;
64
+ }
65
+ /** Test seam for deterministic offline runtime and recorder-boundary verification. */
66
+ let runtimeModelFactory = createModelFromConfig;
67
+ let runtimeRecorderOverrides;
68
+ export function setRuntimeModelFactoryForTest(factory) {
69
+ runtimeModelFactory = factory ?? createModelFromConfig;
70
+ }
71
+ export function setRuntimeRecorderOverridesForTest(overrides) {
72
+ runtimeRecorderOverrides = overrides;
73
+ }
74
+ /**
75
+ * Stable across runs by necessity: session snapshots are stored under
76
+ * `<sessionId>/scopes/agent/<agentId>/`, so a changing agent id would hide
77
+ * previous snapshots from `--resume`.
78
+ */
79
+ const AGENT_ID = 'darwin';
80
+ /**
81
+ * Parent-registered tools that never enter the child catalogue: the offloader's
82
+ * retrieval tool (parent-session storage) and both network tools (children are
83
+ * for workspace reads; network access is a parent decision). `update_plan`,
84
+ * `workflow`, `subagent` and the memory tools stay parent-only by registration
85
+ * order instead — they are added after the catalogue is captured.
86
+ */
87
+ const PARENT_ONLY_TOOL_NAMES = new Set([
88
+ 'retrieve_offloaded_content',
89
+ httpRequest.name,
90
+ webFetch.name,
91
+ // Registered by the SDK's backgroundTasks plugin during initialize(); a child has
92
+ // no plugin, so the tool would list nothing and could not cancel anything.
93
+ MANAGE_BACKGROUND_TASK_TOOL_NAME,
94
+ ]);
95
+ export class AgentRuntime {
96
+ agent;
97
+ model;
98
+ projectRoot;
99
+ mcp;
100
+ skills;
101
+ commands;
102
+ subagents;
103
+ workflows;
104
+ subagentDispatches;
105
+ backgroundDelegation;
106
+ modelRetry;
107
+ backgroundBash;
108
+ gate;
109
+ lifecycleHooks;
110
+ toolHookLayers;
111
+ codexHooks;
112
+ sessionManager;
113
+ preserveRecentMessages;
114
+ trajectory;
115
+ diagnosticsLog;
116
+ memoryController;
117
+ info;
118
+ createOptions;
119
+ /**
120
+ * The live thinking plan. Mutable, unlike everything in {@link RuntimeInfo}:
121
+ * `/effort` changes it mid-session by reconfiguring the model in place.
122
+ */
123
+ thinkingPlan;
124
+ /**
125
+ * The config in effect right now. Diverges from `info.config` after `/model`:
126
+ * `info` is the startup snapshot, this moves with the session.
127
+ */
128
+ liveConfig;
129
+ /** What the live model can cache. Recomputed on `/model`, like the plan above. */
130
+ promptCachePlan;
131
+ lastTurnDelta = undefined;
132
+ /**
133
+ * Completed turns' meter deltas, tallied under the config in effect for each turn —
134
+ * the same `before` snapshot and config the trajectory's turn meter reads, so the
135
+ * in-process per-model shares and the recorded per-turn spend attribute identically.
136
+ * Exists so `/status`, `/usage` and the headless `cost:` record can price each
137
+ * model's tokens at its own rates after a `/model` switch instead of the live
138
+ * model's rates over the whole meter. Read through {@link modelShares}.
139
+ */
140
+ turnUsageByModel = [];
141
+ /**
142
+ * Per-model-call efficiency tallies for this session (issue #8 follow-up A).
143
+ * Parent-only and session-scoped by construction: only this runtime's own
144
+ * `send()` feeds it, and `/clear`'s successor runtime starts a fresh one.
145
+ */
146
+ callStatsState = emptyCallStats();
147
+ /**
148
+ * Latched on the first tally failure. The stats are an observer of the stream:
149
+ * a broken tally degrades every surface to absence (no efficiency section, no
150
+ * `model-calls:` record) rather than reporting numbers it can no longer trust —
151
+ * and can never become a second reason a turn dies.
152
+ */
153
+ callStatsBroken = false;
154
+ /**
155
+ * The most recent completed model call's measured prompt size, with where the
156
+ * conversation stood when it was measured — the base {@link contextEstimate} builds
157
+ * on. Parent-only and session-scoped for the same reason as the call stats: only
158
+ * this runtime's `send()` installs it, and `/clear`/`/rewind` successors start
159
+ * without one. `undefined` until a metered call completes, which is also what a
160
+ * resumed session reports until its first turn.
161
+ */
162
+ contextAnchor = undefined;
163
+ /**
164
+ * Latched on the first anchor failure, separately from {@link callStatsBroken}: the
165
+ * two observers must not be able to break each other, and a broken anchor degrades
166
+ * `/context` to the plain heuristic line rather than to a wrong number.
167
+ */
168
+ contextAnchorBroken = false;
169
+ /** Serializes the bounded list/save/list critical section across concurrent callers. */
170
+ rewindCaptureTail = Promise.resolve();
171
+ /**
172
+ * The per-process model price cache (`~/.darwin/model-prices.json`). Process-wide
173
+ * on purpose: a `/clear` successor shares its fetch-once bookkeeping, and children
174
+ * never touch it — they report tokens, the parent prices them.
175
+ */
176
+ modelPrices = defaultModelPriceStore();
177
+ constructor(agent,
178
+ // Not readonly: `/model` replaces it, which is also why `Agent.model` being a
179
+ // mutable property matters — the conversation survives a provider change.
180
+ model, projectRoot,
181
+ /** Kept whole, not just the clients: a successor inherits the header metadata too. */
182
+ mcp, skills, commands, subagents, workflows, subagentDispatches,
183
+ /** Forwards background runs' `AfterToolCallEvent`s into `send()`'s stream (SER-064). */
184
+ backgroundDelegation,
185
+ /** The parent Agent's own retry state; children keep theirs behind their installer (SER-066). */
186
+ modelRetry, backgroundBash, gate,
187
+ /** Undefined when neither native lifecycle event is configured. */
188
+ lifecycleHooks, toolHookLayers,
189
+ /** Portable Codex-dialect session/tool/lifecycle adapter. */
190
+ codexHooks, sessionManager,
191
+ /** The `/compact` recent window; the manager itself is built per call (focus is constructor-only). */
192
+ preserveRecentMessages,
193
+ /** Undefined when `trajectory: false` switched recording off for this run. */
194
+ trajectory,
195
+ /** Undefined unless `diagnostics: true` asked for the log. Off is the default. */
196
+ diagnosticsLog,
197
+ /** Undefined only when effective config disables derived project context. */
198
+ memoryController, info,
199
+ /**
200
+ * What this runtime was created with, so {@link startNewSession} can assemble its
201
+ * successor through the same factory instead of a second, drifting assembly.
202
+ */
203
+ createOptions) {
204
+ this.agent = agent;
205
+ this.model = model;
206
+ this.projectRoot = projectRoot;
207
+ this.mcp = mcp;
208
+ this.skills = skills;
209
+ this.commands = commands;
210
+ this.subagents = subagents;
211
+ this.workflows = workflows;
212
+ this.subagentDispatches = subagentDispatches;
213
+ this.backgroundDelegation = backgroundDelegation;
214
+ this.modelRetry = modelRetry;
215
+ this.backgroundBash = backgroundBash;
216
+ this.gate = gate;
217
+ this.lifecycleHooks = lifecycleHooks;
218
+ this.toolHookLayers = toolHookLayers;
219
+ this.codexHooks = codexHooks;
220
+ this.sessionManager = sessionManager;
221
+ this.preserveRecentMessages = preserveRecentMessages;
222
+ this.trajectory = trajectory;
223
+ this.diagnosticsLog = diagnosticsLog;
224
+ this.memoryController = memoryController;
225
+ this.info = info;
226
+ this.createOptions = createOptions;
227
+ this.thinkingPlan = info.thinking;
228
+ this.liveConfig = info.config;
229
+ this.promptCachePlan = info.promptCache;
230
+ // Fire and forget: a mapped id costs one file read, an unmapped one starts the
231
+ // single bounded background fetch. Nothing awaits it — not startup, not the
232
+ // first turn — and it cannot reject, so it cannot become a startup failure.
233
+ void this.modelPrices.ensure(this.liveConfig);
234
+ }
235
+ /**
236
+ * Releases startup-owned observers and external clients when construction fails.
237
+ * Successful creation transfers the same resources to `shutdown()` instead.
238
+ */
239
+ static async unwindCreate(diagnosticsLog, mcpClients = [], backgroundBash, memoryController, lifecycleHooks, codexHooks) {
240
+ if (diagnosticsLog !== undefined)
241
+ setSdkVerboseSink(undefined);
242
+ await Promise.allSettled([
243
+ disconnectAll(mcpClients),
244
+ backgroundBash?.shutdown() ?? Promise.resolve(),
245
+ diagnosticsLog?.close() ?? Promise.resolve(),
246
+ memoryController?.close() ?? Promise.resolve(),
247
+ lifecycleHooks?.close() ?? Promise.resolve(),
248
+ codexHooks?.close() ?? Promise.resolve(),
249
+ ]);
250
+ }
251
+ static async create(options) {
252
+ // Resolve explicit ids before provider/model construction: a bad automation
253
+ // selector must fail locally without initializing anything billable.
254
+ const session = await resolveSession(options.projectRoot, options.session, AGENT_ID);
255
+ options.onSessionResolved?.(session.sessionId);
256
+ // A successor created by `/clear` takes the predecessor's *live* config instead of
257
+ // re-reading the file, so a `/model` or `/effort` change made this session survives
258
+ // the switch (see InheritedRuntimeResources).
259
+ const config = options.inherit?.config ?? (await loadConfig(options.projectRoot));
260
+ const policy = await loadProjectPolicy(options.projectRoot);
261
+ // Built here, before the model, the MCP clients and the skills plugin, because all
262
+ // three log at `debug` while they start up (MCP tool renames, skill discovery) and
263
+ // a diagnostics log that begins after startup cannot answer a question about
264
+ // startup. It opens no file yet: the first line is buffered, so a session that
265
+ // never logs again still leaves nothing behind. Installing the tap is what makes
266
+ // the SDK's `debug`/`info` reach anything at all — with `diagnostics` off they stay
267
+ // the literal no-ops `sdk-logging.ts` installs, and no line is ever formatted.
268
+ const diagnosticsLog = config.diagnostics === true
269
+ ? new DiagnosticsLog({
270
+ file: diagnosticsPath(options.projectRoot, session.sessionId),
271
+ run: {
272
+ session: session.sessionId,
273
+ darwinVersion: DARWIN_VERSION,
274
+ provider: config.provider,
275
+ model: config.model,
276
+ },
277
+ })
278
+ : undefined;
279
+ if (diagnosticsLog !== undefined)
280
+ setSdkVerboseSink(diagnosticsLog.sdkSink);
281
+ let startupMcpClients = [];
282
+ let startupBackgroundBash;
283
+ let startupMemoryController;
284
+ let startupLifecycleHooks;
285
+ let startupCodexHooks;
286
+ // Keep assembly in one function so one catch owns every resource acquired
287
+ // after the process-global diagnostics tap is installed.
288
+ const assemble = async () => {
289
+ const model = await runtimeModelFactory(config);
290
+ const skills = await SkillsPlugin.load(options.projectRoot);
291
+ const commands = await loadCustomCommands(options.projectRoot, skills.skills.map((skill) => skill.name));
292
+ const loadedInstructions = await loadProjectInstructions(options.projectRoot);
293
+ const instructions = loadedInstructions.instructions;
294
+ const basePrompt = await loadSystemPrompt(options.projectRoot, config.systemPrompt);
295
+ const basePromptText = options.systemPromptSuffix === undefined
296
+ ? basePrompt.prompt
297
+ : `${basePrompt.prompt}\n\n${options.systemPromptSuffix}`;
298
+ const mcp = options.inherit?.mcp ?? await loadMcpClients(options.projectRoot, {
299
+ quietStdioStderr: options.quietMcpStderr === true,
300
+ });
301
+ // Inherited resources belong to a predecessor that is still alive: if this
302
+ // assembly fails, the unwind must not release them out from under it.
303
+ if (options.inherit === undefined)
304
+ startupMcpClients = mcp.clients;
305
+ const permissionMode = options.permissionModeOverride ?? config.permissionMode;
306
+ // Built before the gate on purpose: the gate must resolve provenance for
307
+ // children that do not exist yet, and only the narrow resolver crosses over —
308
+ // the permission layer never learns about the delegation tool itself.
309
+ const subagentDispatches = new SubagentDispatchRegistry();
310
+ const gate = new PermissionGate({
311
+ mode: permissionMode,
312
+ projectRoot: options.projectRoot,
313
+ ask: options.permissionBridge,
314
+ allowRules: policy.allowRules,
315
+ dispatchSource: (agentId) => subagentDispatches.sourceFor(agentId),
316
+ // Built for every run, not only an `auto` one: `/mode auto` can arrive
317
+ // mid-session and the gate must have a classifier to consult. Costs nothing
318
+ // until it is used — the closure defers building its model to the first call.
319
+ classifier: createModelClassifier(config, options.projectRoot),
320
+ });
321
+ const codexHooks = policy.codexHooks === undefined ? undefined : new CodexHookRunner({
322
+ projectRoot: options.projectRoot,
323
+ hooks: policy.codexHooks,
324
+ sessionId: session.sessionId,
325
+ config,
326
+ permissionMode: () => gate.mode,
327
+ ...(diagnosticsLog === undefined ? {} : { problem: (problem) => diagnosticsLog.notice(problem, 'warn') }),
328
+ });
329
+ startupCodexHooks = codexHooks;
330
+ // The intervention is assembled before the Agent, while rewritten input validation
331
+ // needs the final post-initialize registry (including MCP tools). The callback is
332
+ // assigned immediately after construction and is never invoked during assembly.
333
+ let toolForName = () => undefined;
334
+ // One composed intervention owns retry → native/portable Pre → permission → body
335
+ // → portable/native Post ordering. Lifecycle adapters stay outside the SDK loop.
336
+ const intervention = new ToolHookGate(options.projectRoot, policy.hooks ?? {}, gate, undefined, codexHooks, policy.toolHookLayers, (name) => toolForName(name));
337
+ const lifecycleConfig = lifecycleHooksFromConfig(policy.hooks);
338
+ const lifecycleHooks = lifecycleConfig === undefined
339
+ ? undefined
340
+ : new LifecycleHookRunner(options.projectRoot, lifecycleConfig);
341
+ startupLifecycleHooks = lifecycleHooks;
342
+ const sessionManager = createSessionManager(options.projectRoot, session.sessionId);
343
+ // One manager and wrapper are shared by the main Agent and every child tool
344
+ // catalogue. Foreground calls still delegate with the caller's ToolContext.
345
+ // Across `/clear` the manager is inherited, not rebuilt: its jobs are running
346
+ // processes owned by this process, and a second manager would leave them
347
+ // unlistable and unreaped.
348
+ const backgroundBash = options.inherit?.backgroundBash ?? new BackgroundBashManager(options.projectRoot, session.sessionId);
349
+ if (options.inherit === undefined)
350
+ startupBackgroundBash = backgroundBash;
351
+ const bash = createBackgroundBashTool(backgroundBash, createForegroundBashTool(options.projectRoot));
352
+ const imageViewer = createImageViewerTool(options.projectRoot);
353
+ const conversationManager = new SummarizingConversationManager({
354
+ summaryRatio: config.summaryRatio,
355
+ preserveRecentMessages: config.preserveRecentMessages,
356
+ });
357
+ // `/compact` builds its own SummarizingConversationManager per call (see
358
+ // `createCompactionManager` in compact.ts): the optional focus is constructor-only.
359
+ // On by default for every main runtime; explicit config false opts out and the
360
+ // headless CLI override can force it back on for one process. Storage is
361
+ // session-scoped and on disk, next to the background-task logs, so a reference
362
+ // the model holds still resolves after `--resume`; `evictAfterCycles: null`
363
+ // disables eviction for the same reason — a resumed conversation can cite a
364
+ // reference from many cycles ago. The
365
+ // corollary is that offload files accumulate unbounded: nothing in darwin
366
+ // deletes session state today (there is no session GC to align with), so the
367
+ // bound is manual — delete a finished session's directories, as documented
368
+ // on `contextOffload` in config.ts. Do not add per-session cleanup here: a
369
+ // fresh session id is timestamp-unique, so its offload dir never pre-exists,
370
+ // and any other session's dir may still be resumed. `excludeTools` (SRF-024):
371
+ // a `load_skill` body must reach the model whole in one round — the preview is
372
+ // not the skill, and a retrieval round replays the whole context — so that one
373
+ // name is never offloaded; no other tool is excluded.
374
+ const contextOffload = options.contextOffloadOverride === true || config.contextOffload;
375
+ const offloader = contextOffload
376
+ ? new ContextOffloader({
377
+ storage: new LocalFileStorage(path.join(sessionPaths(options.projectRoot).sessionsDir, session.sessionId, 'offload')),
378
+ evictAfterCycles: null,
379
+ excludeTools: ['load_skill'],
380
+ ...(config.maxResultTokens !== undefined && { maxResultTokens: config.maxResultTokens }),
381
+ })
382
+ : undefined;
383
+ const memoryController = config.memory === true ? new MemoryToolController(options.projectRoot, config.memoryHorizonDays ?? 28) : undefined;
384
+ startupMemoryController = memoryController;
385
+ // The fileEditor is the SDK singleton behind a same-path ordering wrapper
386
+ // (SRF-020): substituted here rather than `addOrReplace`d after construction
387
+ // because it is static, so the raw tool is never registered, and `childTools`
388
+ // below hands children the same wrapper with per-Agent chains.
389
+ const ordinaryTools = [bash, new SerializedFileEditorTool(fileEditor), imageViewer, httpRequest, webFetch];
390
+ // SER-064: the two delegation tools are the only ones the model may route to the
391
+ // SDK's background executor; everything else — the ordinary tools by name, and by
392
+ // wildcard whatever `initialize()` discovers later — stays foreground. Cap and
393
+ // delegation tools are the parent's; children are built by `buildRecipeChild`
394
+ // and never receive this option.
395
+ const backgroundDelegationTools = [SUBAGENT_TOOL_NAME, WORKFLOW_TOOL_NAME];
396
+ const backgroundDelegation = new BackgroundDelegationObserver(backgroundDelegationTools);
397
+ const agent = new Agent({
398
+ id: AGENT_ID,
399
+ model,
400
+ // AGENTS.md is folded in here. Official AgentSkills injects its catalogue
401
+ // before each invocation; the post-plugin hook below restores Darwin's fixed
402
+ // order. Only the base is user-overridable: project instructions stay additive.
403
+ systemPrompt: composeSystemPrompt(basePromptText, instructions),
404
+ // McpClient instances act as tool sources: the SDK discovers and registers
405
+ // their tools during initialize().
406
+ tools: [...ordinaryTools, ...mcp.clients],
407
+ plugins: offloader === undefined ? [skills] : [skills, offloader],
408
+ sessionManager,
409
+ conversationManager,
410
+ interventions: [intervention],
411
+ backgroundTasks: backgroundDelegationConfig({
412
+ delegationTools: backgroundDelegationTools,
413
+ ordinaryToolNames: ordinaryTools.map((tool) => tool.name),
414
+ maxConcurrency: concurrencyCap(config),
415
+ }),
416
+ // Required: the SDK's own printer writes to stdout and would interleave
417
+ // with our rendering (and fight Ink for the terminal in step 5).
418
+ printer: false,
419
+ // Explicit opt-out of the SDK's DefaultModelRetryStrategy, whose backoff sleeps
420
+ // inside the hook callback — hidden from the driver and deaf to cancel().
421
+ // Darwin's own hook + middleware below keep the same schedule (SER-066).
422
+ retryStrategy: null,
423
+ });
424
+ toolForName = (name) => agent.tools.find((candidate) => candidate.name === name);
425
+ installMaxTokensRecovery(agent);
426
+ const modelRetry = installModelRetry(agent);
427
+ backgroundDelegation.install(agent);
428
+ // The constructor does not initialize; the SDK defers it to the first
429
+ // invocation. Session restore runs on InitializedEvent, MCP tools are
430
+ // discovered here, and plugins inject their system prompt fragments — so
431
+ // without this the resumed history and MCP tools would not exist yet.
432
+ await agent.initialize();
433
+ // A rewind successor is always fresh, so initialization cannot accidentally
434
+ // load its own latest snapshot. Restore the selected *source* immutable snapshot
435
+ // explicitly, before Darwin refreshes current prompt fragments below. The source
436
+ // manager is read-only here; the successor manager owns all future writes.
437
+ if (options.rewindRestore !== undefined) {
438
+ const sourceManager = createSessionManager(options.projectRoot, options.rewindRestore.sourceSessionId);
439
+ const restored = await sourceManager.restoreSnapshot({
440
+ target: agent,
441
+ snapshotId: options.rewindRestore.snapshotId,
442
+ });
443
+ if (!restored)
444
+ throw new Error('The selected rewind checkpoint no longer exists.');
445
+ }
446
+ // Older summarizer versions copied reasoning blocks into the user-role
447
+ // summary message; providers reject any request containing it. Repair the
448
+ // restored history in memory (covers both ordinary resume above and the
449
+ // rewind restore just before this); the next ordinary save persists it.
450
+ // Trajectory files are never rewritten. No notice channel exists here, so
451
+ // a nonzero count is intentionally silent.
452
+ stripReasoningFromUserMessages(agent.messages);
453
+ // Sessions saved before the image dimension cap dropped to Anthropic's
454
+ // many-image limit (2000px once a request holds more than 20 images) can
455
+ // carry tool-result images the provider now rejects on every turn. Shrink
456
+ // them in memory through the imageViewer's own normalizer; same persistence
457
+ // and silence contract as the reasoning repair above.
458
+ await normalizeRestoredImages(agent.messages);
459
+ // CodeGraph semantic reads are useful only when their target already has a
460
+ // structurally usable index. Prime the current target once, then replace the
461
+ // discovered server tools before the same catalogue is handed to children.
462
+ if (mcp.clients.some((client) => client.clientName === 'codegraph')) {
463
+ const codegraphPreflight = new CodeGraphPreflight(options.projectRoot);
464
+ await codegraphPreflight.primeCurrent();
465
+ codegraphPreflight.apply(agent, mcp.clients);
466
+ }
467
+ new WebSearchEmptyResults().apply(agent, mcp.clients);
468
+ // Official AgentSkills injects its catalogue on BeforeInvocationEvent. This
469
+ // callback is registered afterwards, so it moves that official TextBlock
470
+ // ahead of current working context and Darwin's final cache point before the
471
+ // model sees the request. Repeated and resumed calls keep one catalogue: the
472
+ // official callback removes its previous exact block first.
473
+ agent.addHook(BeforeInvocationEvent, ({ agent: invokingAgent }) => {
474
+ if (!orderOfficialSkillsPrompt(invokingAgent)) {
475
+ throw new Error('Could not place the official skills catalogue before working context and cache.');
476
+ }
477
+ });
478
+ if (options.maxModelCalls !== undefined)
479
+ installModelCallBudget(agent, options.maxModelCalls);
480
+ // Child tool allowlists can include MCP and plugin tools, whose final names do
481
+ // not exist until initialization. Capture that catalogue before registering
482
+ // `subagent` so children can never recursively delegate. The offloader's
483
+ // retrieval capability is parent-session state: children have no matching
484
+ // plugin/storage contract, so never hand them a dangling retrieval tool.
485
+ // Network access (`http_request`, `web_fetch`) stays parent-only too: the
486
+ // documented invariant is that children work on reads inside the workspace.
487
+ const childTools = agent.tools.filter((tool) => !PARENT_ONLY_TOOL_NAMES.has(tool.name));
488
+ const agentDefinitions = await loadAgentDefinitions(options.projectRoot, childTools.map((tool) => tool.name));
489
+ // Progress belongs to the parent turn. Register only after the child catalogue
490
+ // and allowlists are fixed, so no child can author an unrelated checklist.
491
+ agent.toolRegistry.add(createUpdatePlanTool());
492
+ if (memoryController !== undefined)
493
+ agent.toolRegistry.add(createMemoryTools(memoryController));
494
+ // Children build their models through the same factory seam as the parent: in
495
+ // production it *is* `createModelFromConfig`; offline suites can script a child
496
+ // (`spike/verify-background-delegation.ts`) without a provider.
497
+ const createChildModel = (childConfig) => runtimeModelFactory(childConfig);
498
+ const subagents = new SubagentTool({
499
+ registry: agentDefinitions,
500
+ tools: childTools,
501
+ intervention,
502
+ projectInstructions: instructions,
503
+ config,
504
+ createModel: createChildModel,
505
+ dispatches: subagentDispatches,
506
+ ...(codexHooks === undefined ? {} : { codexHooks }),
507
+ });
508
+ agent.toolRegistry.add(subagents.tool);
509
+ // Same fixed child catalogue and shared gate as `subagent`; registered after
510
+ // the catalogue capture so `workflow` stays parent-only, like `update_plan`.
511
+ const workflows = new WorkflowTool({
512
+ registry: agentDefinitions,
513
+ tools: childTools,
514
+ intervention,
515
+ projectInstructions: instructions,
516
+ config,
517
+ createModel: createChildModel,
518
+ dispatches: subagentDispatches,
519
+ ...(codexHooks === undefined ? {} : { codexHooks }),
520
+ });
521
+ agent.toolRegistry.add(workflows.tool);
522
+ // Strictly after initialize(): session restore may have replaced both prompt
523
+ // and official skill appState. Refresh current facts, then place the final
524
+ // cache point. On invocation, official AgentSkills injects one catalogue and
525
+ // Darwin's later hook moves it before these two trailing blocks. Tools and the
526
+ // conversation are cached by the model's own cacheConfig, set in config.ts.
527
+ //
528
+ // The working context is refreshed here for a second reason: restoring a
529
+ // session overwrites `systemPrompt` with the snapshot's copy, so composing it
530
+ // earlier would leave a resumed run advertising the previous run's date and
531
+ // directory listing. Applied last, it is also the only fragment a resumed
532
+ // prompt can still be corrected by.
533
+ const workingContext = await buildWorkingContext(options.projectRoot);
534
+ if (!applyWorkingContext(agent, workingContext.fragment)) {
535
+ throw new Error('Could not refresh working context on the restored system prompt.');
536
+ }
537
+ const promptCache = planPromptCache(config);
538
+ if (promptCache.parts.includes('system prompt') && !applySystemPromptCachePoint(agent, promptCache)) {
539
+ throw new Error('Could not place the final cache point on the assembled system prompt.');
540
+ }
541
+ // Persist the fully refreshed branch state under the successor id. This never
542
+ // moves the resume pointer; the ordinary completed-turn path remains its owner.
543
+ if (options.rewindRestore !== undefined) {
544
+ await sessionManager.saveSnapshot({ target: agent, isLatest: true });
545
+ }
546
+ runtimeCreateCheckpoint?.('after-initialize');
547
+ // Built last and given nothing but facts: the recorder is an observer, so it
548
+ // must not be able to influence assembly. It opens no file here — the first
549
+ // recorded turn creates it, so a session that never runs one leaves nothing
550
+ // behind, the same rule `markResumable()` follows for the resume pointer.
551
+ const thinkingPlan = planThinking(config);
552
+ const trajectory = config.trajectory === false
553
+ ? undefined
554
+ : new TrajectoryRecorder({
555
+ file: trajectoryPath(options.projectRoot, session.sessionId),
556
+ run: {
557
+ session: session.sessionId,
558
+ agentId: AGENT_ID,
559
+ darwinVersion: DARWIN_VERSION,
560
+ provider: config.provider,
561
+ model: config.model,
562
+ permissionMode,
563
+ thinkingEffort: thinkingPlan.effective,
564
+ resumed: session.restoreRequested && agent.messages.length > 0,
565
+ restoredMessages: agent.messages.length,
566
+ },
567
+ ...runtimeRecorderOverrides,
568
+ ...(memoryController === undefined ? {} : { onTurnSettled: (settlement) => memoryController.settle(settlement) }),
569
+ });
570
+ const runtime = new AgentRuntime(agent, model, options.projectRoot, mcp, skills, commands, subagents, workflows, subagentDispatches, backgroundDelegation, modelRetry, backgroundBash, gate, lifecycleHooks, policy.toolHookLayers, codexHooks, sessionManager, config.preserveRecentMessages, trajectory, diagnosticsLog, memoryController, {
571
+ config,
572
+ projectRoot: options.projectRoot,
573
+ permissionMode,
574
+ sessionId: session.sessionId,
575
+ resumed: session.restoreRequested && agent.messages.length > 0,
576
+ skillNames: skills.skills.map((skill) => skill.name),
577
+ skillProblems: skills.problems.map((problem) => ({ ...problem })),
578
+ commandNames: commands.commands.map((command) => command.name),
579
+ commandProblems: commands.problems.map((problem) => ({ ...problem })),
580
+ agentNames: agentDefinitions.definitions.map((definition) => definition.name),
581
+ agentProblems: agentDefinitions.problems.map((problem) => ({ ...problem })),
582
+ projectInstructions: instructions === undefined
583
+ ? undefined
584
+ : { path: instructions.path, bytes: instructions.bytes, truncated: instructions.truncated },
585
+ projectInstructionsProblem: loadedInstructions.problem,
586
+ systemPromptSource: basePrompt.source,
587
+ systemPromptPath: basePrompt.path,
588
+ systemPromptProblem: basePrompt.problem,
589
+ workingContextProblem: workingContext.problem,
590
+ promptCache,
591
+ // Recomputed rather than returned from createModelFromConfig: the model
592
+ // factory needs only the fields, while the header needs the reason a level
593
+ // was clamped. Both come from the same pure planner, so they cannot disagree.
594
+ thinking: thinkingPlan,
595
+ mcpConfigPath: mcp.configPath,
596
+ mcpConfigPaths: mcp.configPaths,
597
+ mcpOverriddenServerNames: mcp.overriddenServerNames,
598
+ permissionRulesPath: permissionRulesPath(options.projectRoot),
599
+ hookSources: policy.hookSources,
600
+ hookShadowNotices: policy.hookShadowNotices.map((notice) => ({
601
+ ...notice,
602
+ shadowed: [...notice.shadowed],
603
+ })),
604
+ mcpIgnoredConfigPath: mcp.ignoredConfigPath,
605
+ mcpServerCount: mcp.clients.length,
606
+ toolNames: agent.tools.map((tool) => tool.name).sort(),
607
+ trajectoryFile: trajectory?.status.file,
608
+ diagnosticsFile: diagnosticsLog?.path,
609
+ }, options);
610
+ if (options.rewindRestore === undefined) {
611
+ const source = options.inherit !== undefined
612
+ ? 'clear'
613
+ : session.restoreRequested
614
+ ? 'resume'
615
+ : 'startup';
616
+ await codexHooks?.sessionStart(source);
617
+ }
618
+ return runtime;
619
+ };
620
+ return assemble().catch(async (error) => {
621
+ await AgentRuntime.unwindCreate(diagnosticsLog, startupMcpClients, startupBackgroundBash, startupMemoryController, startupLifecycleHooks, startupCodexHooks);
622
+ throw error;
623
+ });
624
+ }
625
+ /**
626
+ * Runs one turn, yielding SDK stream events untouched so callers can render
627
+ * whichever ones they care about.
628
+ *
629
+ * Snapshots the accumulated usage before the turn so `lastTurnUsage` can
630
+ * report the delta — including cancelled turns, where the delta reflects
631
+ * whatever model calls completed before the cancel.
632
+ *
633
+ * The trajectory recorder first crosses one bounded, no-throw durability barrier
634
+ * for `userInput`, before `Agent.stream()` can invoke a provider or tool. Later
635
+ * events are observed between `stream()` and the `yield`, in {@link recordStream} —
636
+ * a pass-through generator that records synchronously and cannot throw, so it can
637
+ * neither reorder, delay nor swallow an event. Both properties are measured over a
638
+ * real offline `AgentRuntime` in `spike/verify-trajectory.ts`.
639
+ *
640
+ * The turn's spend reaches the record through a meter handed to `beginTurn`, and not
641
+ * from this `finally`, because of when the two run: `recordStream`'s `finally` closes
642
+ * and buffers the `turnEnded` record *before* this one executes, so a number produced
643
+ * here would always be one step too late for it. The meter is read while that record is
644
+ * composed. Keeping the write there also keeps it off this error path, where a throw
645
+ * would replace the provider's error object with the recorder's — the one thing the
646
+ * observer contract forbids.
647
+ *
648
+ * One `before` snapshot feeds both the meter and `lastTurnDelta`, so what the record
649
+ * says a turn cost and what `/usage` says it cost cannot be two different readings.
650
+ */
651
+ async *send(input, userInput = input, image) {
652
+ const before = this.usage;
653
+ // The config this turn is attributed to, for the recorded spend and the in-process
654
+ // per-model tally alike. `/model` is refused while a turn is busy, so the live
655
+ // config cannot move under the turn; capturing it once makes that a property of
656
+ // this method rather than of the drivers.
657
+ const turnConfig = this.liveConfig;
658
+ const submitted = await this.codexHooks?.userPromptSubmit(userInput);
659
+ if (submitted !== undefined && !submitted.allowed) {
660
+ throw new Error(submitted.reason ?? 'UserPromptSubmit hook blocked this prompt.');
661
+ }
662
+ const modelInput = injectCodexContext(input, submitted?.context);
663
+ let checkpointId;
664
+ // A text-only checkpoint cannot truthfully reproduce a multimodal boundary.
665
+ if (image === undefined && rewindPromptEligible(input)) {
666
+ checkpointId = await this.captureRewindCheckpoint();
667
+ }
668
+ let completed = false;
669
+ let sealed = false;
670
+ try {
671
+ // A multimodal turn's durable text is the literal submitted prompt. Expanded
672
+ // command text and held shell reports still reach the model, but image bytes
673
+ // and synthetic attachment/path text never enter the trajectory.
674
+ const recording = this.trajectory?.beginTurn(userInput, startTurnSpend(before, () => this.usage, turnConfig),
675
+ // The per-call spend projector, injected beside the turn meter and for its
676
+ // reason: the `modelCall` record needs the live provider/model config, which
677
+ // `src/trajectory/**` must never import.
678
+ startCallSpend(turnConfig));
679
+ // The model may receive an expanded skill/custom-command prompt, but
680
+ // preference/identity provenance is allowed to quote only what the user
681
+ // actually submitted. Drivers pass that raw text as the second argument.
682
+ this.memoryController?.openTurn(recording?.turn, userInput);
683
+ // The current input is the one exception to fire-and-forget recording: make it
684
+ // readable to offline observers before Agent.stream() can invoke a provider or
685
+ // tool. The recorder owns the bound and resolves on write failure/timeout, so
686
+ // this wait can delay a turn briefly but can never become a reason it dies.
687
+ await recording?.inputDurable();
688
+ if (recording !== undefined && this.trajectory?.status.active === false) {
689
+ this.memoryController?.discard();
690
+ }
691
+ // Later events and turn-end are still observed synchronously and appended in
692
+ // the background; `shutdown()` is where that append chain is waited for. The
693
+ // SDK stream is first passed through the background-delegation observer, which
694
+ // yields the hook-only `AfterToolCallEvent` of a background child ahead of the
695
+ // next SDK event, so the recorder and every driver see one ordinary
696
+ // before/after pair for a delegation the model routed to the background.
697
+ const invocation = image === undefined ? modelInput : [new TextBlock(modelInput), image];
698
+ const stream = this.backgroundDelegation.observe(this.agent.stream(invocation));
699
+ for await (const event of recordStream(stream, recording)) {
700
+ if (event.type === 'agentResultEvent' && event.result.stopReason === 'endTurn')
701
+ completed = true;
702
+ // Observed at the same point `recordStream` observes: synchronously, between
703
+ // `stream()` and the `yield`, so `/usage` asked mid-turn already counts the
704
+ // calls that completed. Cannot throw — see {@link observeCallStats}.
705
+ this.observeCallStats(event);
706
+ this.observeContextAnchor(event);
707
+ yield event;
708
+ }
709
+ this.memoryController?.seal(completed && this.trajectory?.status.active !== false);
710
+ sealed = true;
711
+ if (completed && checkpointId !== undefined) {
712
+ const catalogue = await appendRewindCheckpoint(this.projectRoot, this.info.sessionId, {
713
+ snapshotId: checkpointId,
714
+ prompt: input,
715
+ completedAt: new Date().toISOString(),
716
+ });
717
+ if (catalogue.problem !== undefined) {
718
+ this.diagnosticsLog?.notice(`rewind checkpoint not catalogued: ${catalogue.problem}`, 'warn');
719
+ }
720
+ }
721
+ }
722
+ finally {
723
+ // Seeing an endTurn event is not enough when the consumer abandons this
724
+ // generator before natural completion: only the natural path above seals.
725
+ if (!sealed)
726
+ this.memoryController?.discard();
727
+ this.lastTurnDelta = deltaUsage(before, this.usage);
728
+ this.tallyTurnUsage(turnConfig, this.lastTurnDelta);
729
+ }
730
+ }
731
+ /**
732
+ * Adds one completed turn's delta to its model's share. Runs in `send`'s `finally`,
733
+ * so it cannot throw: a tally that failed would replace the provider's error with
734
+ * its own, which the observer contract forbids — a failure costs the tally, not
735
+ * the turn (the remainder rule in {@link modelShares} then attributes the tokens
736
+ * to the live model, so nothing goes uncounted).
737
+ */
738
+ tallyTurnUsage(config, delta) {
739
+ try {
740
+ const entry = this.turnUsageByModel.find((candidate) => candidate.config.model === config.model && candidate.config.provider === config.provider);
741
+ if (entry === undefined)
742
+ this.turnUsageByModel.push({ config, usage: delta });
743
+ else
744
+ entry.usage = sumUsage([entry.usage, delta]);
745
+ }
746
+ catch {
747
+ // Observer discipline: never a second reason a turn dies.
748
+ }
749
+ }
750
+ /**
751
+ * What this run has recorded, or `undefined` when recording is switched off.
752
+ *
753
+ * Read rather than pushed: a trajectory problem is worth one notice after the
754
+ * turn that hit it (where the context-pressure check already lives), not an
755
+ * observer that could interrupt the frame mid-stream.
756
+ */
757
+ get trajectoryStatus() {
758
+ return this.trajectory?.status;
759
+ }
760
+ /**
761
+ * Records a user-typed `!` command (SER-024) in the session's trajectory.
762
+ *
763
+ * A passthrough to the recorder and nothing else: the command was run by the
764
+ * TUI under the user's own authority, so it neither enters the agent loop nor
765
+ * asks permission here — this is the honesty half of that bargain. No-op when
766
+ * recording is off or has latched itself off, like every other record.
767
+ */
768
+ recordShellCommand(entry) {
769
+ this.trajectory?.recordShellCommand(entry);
770
+ }
771
+ /**
772
+ * The diagnostics log, or `undefined` when nobody asked for one.
773
+ *
774
+ * Handed out rather than wrapped in per-entry methods so a caller can decide *once*
775
+ * whether it is logging at all: the TUI swaps its whole dispatch function on this
776
+ * being defined, which is what keeps a default run's notice path byte-for-byte what
777
+ * it was. Everything on it is synchronous and non-throwing by contract.
778
+ */
779
+ get diagnostics() {
780
+ return this.diagnosticsLog;
781
+ }
782
+ /**
783
+ * What this run has logged, or `undefined` when the log is off. Read after a turn,
784
+ * exactly like {@link trajectoryStatus} and for the same reason: a problem is worth
785
+ * one notice where the context-pressure check already lives, never an observer that
786
+ * interrupts the frame mid-stream.
787
+ */
788
+ get diagnosticsStatus() {
789
+ return this.diagnosticsLog?.status;
790
+ }
791
+ /** Best-effort status of enabled derived project memory. */
792
+ get memoryStatus() {
793
+ return this.memoryController?.status;
794
+ }
795
+ /**
796
+ * Runs the user-only local `/memory` command and refreshes the verified Darwin-owned
797
+ * prompt block before a successful mutation returns. No Agent invocation is made.
798
+ */
799
+ async manageMemory(input) {
800
+ if (this.liveConfig.memory !== true) {
801
+ return { changed: false, text: 'project memory is off — remove memory: false if set, and enable trajectory recording in ~/.darwin/config.json' };
802
+ }
803
+ const result = await runMemoryCommand(this.projectRoot, input, {
804
+ horizonDays: this.liveConfig.memoryHorizonDays ?? 28,
805
+ });
806
+ return result;
807
+ }
808
+ /**
809
+ * Replaces old conversation history with rolling summaries, keeping the recent
810
+ * configured window verbatim, then persists the rewritten session immediately.
811
+ *
812
+ * This is deliberately a direct conversation-manager call, not an agent turn:
813
+ * `/compact` must not become part of the context it is trying to shrink. The
814
+ * original messages are cloned so any model/count/storage failure can put the
815
+ * live agent back exactly where it started.
816
+ *
817
+ * `focus` (trimmed here; blank means none) makes this one summary keep what it
818
+ * names: the summarizer's system prompt becomes the SDK default followed by one
819
+ * fixed focus section. Without a focus the manager is configured exactly as
820
+ * before per-call construction existed. An over-cap focus is refused here,
821
+ * before the PreCompact hook and before any model call.
822
+ */
823
+ async compact(focus) {
824
+ const manager = createCompactionManager(this.preserveRecentMessages, normalizeCompactFocus(focus));
825
+ const pre = await this.codexHooks?.preCompact('manual');
826
+ if (pre !== undefined && !pre.allowed)
827
+ throw new Error(pre.reason ?? 'PreCompact hook blocked compaction.');
828
+ try {
829
+ const result = await compactConversation({
830
+ agent: this.agent,
831
+ model: this.model,
832
+ manager,
833
+ preserveRecentMessages: this.preserveRecentMessages,
834
+ persist: async () => {
835
+ await this.agent.sessionManager?.saveSnapshot({ target: this.agent, isLatest: true });
836
+ await this.markResumable();
837
+ },
838
+ });
839
+ await this.codexHooks?.postCompact('manual');
840
+ return result;
841
+ }
842
+ catch (error) {
843
+ // compactConversation has already restored the live messages. If saving the
844
+ // compact snapshot succeeded but the pointer write failed, overwrite latest
845
+ // with that restored state too, so disk and memory cannot diverge.
846
+ try {
847
+ await this.agent.sessionManager?.saveSnapshot({ target: this.agent, isLatest: true });
848
+ }
849
+ catch {
850
+ // Preserve the original failure; this repair is necessarily best-effort.
851
+ }
852
+ throw error;
853
+ }
854
+ }
855
+ /** Messages restored from a resumed session, for showing prior context. */
856
+ get messageCount() {
857
+ return this.agent.messages.length;
858
+ }
859
+ /**
860
+ * Estimates the context the next model request would carry, without sending it:
861
+ * this reads messages and never mutates them, so it is safe to call mid-turn.
862
+ *
863
+ * Two shapes, one honest reading. With a live measurement anchor
864
+ * (`src/agent/context-anchor.ts`) the base is the provider's own prompt-token total
865
+ * for the most recent completed call — system prompt and every `toolSpec` included,
866
+ * measured rather than guessed — and only the messages appended since that call are
867
+ * counted here, which bounds the estimated part to one call's worth of tail. Without
868
+ * one (a fresh or resumed session before its first metered call, after `/compact`,
869
+ * after a `/model` switch) it falls back to counting the whole assembled request.
870
+ *
871
+ * Either way the count itself is the SDK's character heuristic in practice —
872
+ * `useNativeTokenCount` is on, but Bedrock's `CountTokens` refuses the
873
+ * inference-profile ids darwin requires (see README "Known limitations"), so the
874
+ * first attempt per model may make one cheap non-streaming call that fails and is
875
+ * then cached as skipped. The window comes from the SDK's own per-model table,
876
+ * `undefined` when unknown.
877
+ */
878
+ async contextEstimate() {
879
+ const messages = this.agent.messages;
880
+ const windowTokens = this.model.getConfig().contextWindowLimit;
881
+ const anchor = resolveAnchor(this.contextAnchor, messages);
882
+ if (anchor === undefined) {
883
+ return {
884
+ estimatedTokens: await countConversationTokens(this.model, this.agent),
885
+ messageCount: messages.length,
886
+ windowTokens,
887
+ };
888
+ }
889
+ // Only the tail is estimated, and deliberately without `systemPrompt`/`toolSpecs`:
890
+ // the anchor already measured those, and counting them again would double them.
891
+ const tail = messages.slice(anchor.messageCount);
892
+ let tailTokens = 0;
893
+ if (tail.length > 0) {
894
+ try {
895
+ tailTokens = await this.model.countTokens(tail, {});
896
+ }
897
+ catch {
898
+ // A failed tail count must not throw away the measurement it was refining.
899
+ tailTokens = undefined;
900
+ }
901
+ }
902
+ return {
903
+ estimatedTokens: anchor.requestTokens + (tailTokens ?? 0),
904
+ messageCount: messages.length,
905
+ windowTokens,
906
+ measuredTokens: anchor.requestTokens,
907
+ ...(tailTokens === undefined ? {} : { tailTokens }),
908
+ };
909
+ }
910
+ /**
911
+ * How many wildcard allow-rules are in effect right now — config plus anything
912
+ * accepted this session. Read live from the gate rather than snapshotted into
913
+ * `info`, which is fixed at startup.
914
+ */
915
+ get allowRuleCount() {
916
+ return this.gate.allowRules.length;
917
+ }
918
+ /**
919
+ * Persists a rule the user accepted in a confirmation prompt. The gate is
920
+ * already honouring it (it came back on the decision), so a rejected write only
921
+ * costs the memory of it in the next session — which is why this throws instead
922
+ * of swallowing: the caller reports it to the user.
923
+ */
924
+ async saveAllowRule(rule) {
925
+ this.gate.addAllowRule(rule);
926
+ await appendAllowRule(this.projectRoot, rule);
927
+ }
928
+ /**
929
+ * The live allow-rules with their provenance — config-loaded vs granted this
930
+ * session — for the `/permissions` report. Read live from the gate, like
931
+ * {@link allowRuleCount}.
932
+ */
933
+ listAllowRules() {
934
+ return this.gate.listAllowRules();
935
+ }
936
+ /**
937
+ * The configured MCP servers with their live connection state and registered
938
+ * tool names, for the `/mcp` report. A read-only projection — names, states and
939
+ * counts only, never tool results or server output — that connects nothing:
940
+ * a server that never connected is reported as such, not probed.
941
+ */
942
+ listMcpServers() {
943
+ return mcpServerStatuses(this.mcp.clients);
944
+ }
945
+ /**
946
+ * Revokes allow-rules, on the user's instruction only.
947
+ *
948
+ * The gate stops honouring them *before* this returns — the live rule list is
949
+ * the enforcement surface, so the very next matching call prompts again — and
950
+ * `saved` is the persistence of exactly the rules that were live, reported by
951
+ * the caller rather than awaited (the grant flow's shape, and the same
952
+ * degradation: a failed write costs the file, not the session — the rule only
953
+ * resurrects in the next process). Rules that were not live are skipped, never
954
+ * "revoked": persisting the removal of a rule that was never in force would
955
+ * make this command able to edit the file beyond narrowing what it showed.
956
+ */
957
+ revokeAllowRules(rules) {
958
+ const removed = rules.filter((rule) => this.gate.removeAllowRule(rule));
959
+ const saved = removed.length === 0 ? Promise.resolve() : removeAllowRules(this.projectRoot, removed);
960
+ return { removed, saved };
961
+ }
962
+ /**
963
+ * The approval mode enforcing right now — `info.permissionMode` is the startup
964
+ * one, which is a different question and the one the trajectory record and the
965
+ * headless report mean. Read live from the gate, which owns the value.
966
+ */
967
+ get permissionMode() {
968
+ return this.gate.mode;
969
+ }
970
+ /**
971
+ * Switches the approval mode for the rest of this session, on the user's
972
+ * instruction only.
973
+ *
974
+ * Nothing is persisted, deliberately and unlike `/effort` or `/model`: this
975
+ * changes *enforcement*, so a widening that outlived the process would defeat the
976
+ * rule that no allow-rule may cover `~/.darwin/config.json`. The next process
977
+ * starts from configured/CLI policy again.
978
+ *
979
+ * Synchronous, and it must stay that way: the mode has to be in force before the
980
+ * very next gate decision, and there is nothing to await — no file, no model, no
981
+ * rebuild. The gate is the single decision point, so the intervention the parent
982
+ * and every child share sees the new value with no further plumbing.
983
+ */
984
+ changePermissionMode(next) {
985
+ return this.gate.setMode(next);
986
+ }
987
+ /** How hard the model is thinking right now, and why that is not what was asked. */
988
+ get thinking() {
989
+ return this.thinkingPlan;
990
+ }
991
+ /**
992
+ * Switches the effort level for the rest of the session and remembers it in
993
+ * `~/.darwin/config.json`.
994
+ *
995
+ * The model is reconfigured before the file is written, and the new plan is
996
+ * returned rather than awaited alongside the write: an effort change must take
997
+ * effect on the very next turn, so a slow or failing disk cannot be allowed to
998
+ * hold it up. A rejected write therefore means "this session only", which is why
999
+ * it rethrows through {@link ThinkingChangeResult.saved} instead of being
1000
+ * swallowed — the caller says so.
1001
+ *
1002
+ * Only ever `adaptive` → `adaptive`, so this does not invalidate the conversation
1003
+ * cache breakpoint (switching thinking *modes* would).
1004
+ */
1005
+ changeThinkingEffort(effort) {
1006
+ this.thinkingPlan = applyThinkingEffort(this.model, this.liveConfig, effort);
1007
+ return {
1008
+ plan: this.thinkingPlan,
1009
+ saved: saveThinkingEffort(this.projectRoot, effort),
1010
+ };
1011
+ }
1012
+ /** The config in effect now — the startup one until `/model` changes it. */
1013
+ get config() {
1014
+ return this.liveConfig;
1015
+ }
1016
+ /** What this run can cache right now; moves with `/model`. */
1017
+ get promptCache() {
1018
+ return this.promptCachePlan;
1019
+ }
1020
+ /**
1021
+ * What the price cache knows about the live model — `priced` with its LiteLLM
1022
+ * key and base rates, `none` when LiteLLM lists no such id, `unavailable` until
1023
+ * the background fetch has recorded it. A read of the cache file, never a fetch
1024
+ * or a write, so `/status` and `/usage` stay byte-zero mutation.
1025
+ */
1026
+ get modelPrice() {
1027
+ return this.modelPrices.lookup(this.liveConfig);
1028
+ }
1029
+ /**
1030
+ * This process's meter split per model, each share with the config that projects
1031
+ * it and what the price cache says about it — what `/status`, `/usage` and the
1032
+ * headless `cost:` record price, each model at its own rates.
1033
+ *
1034
+ * The completed turns' tally comes first, in first-appearance order; whatever the
1035
+ * meter holds beyond it — the turn in flight, or a tally that failed — belongs to
1036
+ * the live model, so the shares always sum to {@link usage} metric for metric and a
1037
+ * single-model session is exactly one share over the whole meter (which keeps its
1038
+ * reports byte-identical to the one-lookup rendering). A zero remainder adds no
1039
+ * share once any turn has been tallied, so a `/model` switch that has not run a
1040
+ * turn yet does not appear as a second model that spent nothing; before the first
1041
+ * turn, the live model's zero share is the report's only subject.
1042
+ *
1043
+ * A read of the cache file per share, never a fetch or a write.
1044
+ */
1045
+ get modelShares() {
1046
+ const meter = this.usage;
1047
+ const live = this.liveConfig;
1048
+ const shares = this.turnUsageByModel.map((entry) => ({ config: entry.config, usage: entry.usage }));
1049
+ const remainder = deltaUsage(sumUsage(shares.map((share) => share.usage)), meter);
1050
+ const remainderIsZero = remainder.inputTokens === 0 &&
1051
+ remainder.outputTokens === 0 &&
1052
+ (remainder.cacheReadInputTokens ?? 0) === 0 &&
1053
+ (remainder.cacheWriteInputTokens ?? 0) === 0;
1054
+ const liveShare = shares.find((share) => share.config.model === live.model && share.config.provider === live.provider);
1055
+ if (liveShare !== undefined)
1056
+ liveShare.usage = sumUsage([liveShare.usage, remainder]);
1057
+ else if (shares.length === 0 || !remainderIsZero)
1058
+ shares.push({ config: live, usage: remainder });
1059
+ return shares.map((share) => ({ ...share, lookup: this.modelPrices.lookup(share.config) }));
1060
+ }
1061
+ /** Every configured model, with the live one marked. */
1062
+ get modelChoices() {
1063
+ return this.liveConfig.modelChoices;
1064
+ }
1065
+ /**
1066
+ * Switches the live model to another configured entry, keeping the conversation.
1067
+ *
1068
+ * `Agent.model` is a mutable property, so this replaces the model in place
1069
+ * instead of rebuilding the agent — which is the whole point: the history, the
1070
+ * session file, the tools and the permission gate all survive. Both switch
1071
+ * directions were measured to carry a conversation containing tool calls
1072
+ * (`spike/probe-model-switch.ts`); a Claude reasoning block in the history is
1073
+ * dropped with a warning by the OpenAI adapter rather than rejected, which is
1074
+ * why the TUI routes SDK warnings into notices.
1075
+ *
1076
+ * The thinking and cache plans are recomputed rather than carried over: effort
1077
+ * clamping is per-model and caching is per-provider, so the old plans would
1078
+ * describe a model that is no longer there.
1079
+ */
1080
+ async changeModel(target) {
1081
+ const next = withModelChoice(this.liveConfig, target);
1082
+ // Built before anything is mutated: a failure here (a missing peer dependency,
1083
+ // a bad region) must leave the session on the model it was already using. Same
1084
+ // factory seam as `create()`: `createModelFromConfig` in production.
1085
+ const model = await runtimeModelFactory(next);
1086
+ const thinkingPlan = planThinking(next);
1087
+ const promptCachePlan = planPromptCache(next);
1088
+ // Validate/cache-shape mutation before swapping the live model. A malformed
1089
+ // prompt must leave provider/config selection untouched, even when the target
1090
+ // provider needs no explicit cache point.
1091
+ if (!canUpdateSystemPromptCache(this.agent)) {
1092
+ throw new Error('Could not update the final cache point on the assembled system prompt.');
1093
+ }
1094
+ const cacheUpdated = applySystemPromptCachePoint(this.agent, promptCachePlan);
1095
+ if (promptCachePlan.parts.includes('system prompt') !== cacheUpdated) {
1096
+ throw new Error('Could not update the final cache point on the assembled system prompt.');
1097
+ }
1098
+ this.agent.model = model;
1099
+ this.model = model;
1100
+ this.liveConfig = next;
1101
+ // Same rule as startup: lookup → fetch once if the new id is unmapped → record.
1102
+ void this.modelPrices.ensure(next);
1103
+ // The measured `/context` base came from the previous model's tokenizer and its
1104
+ // prompt overhead, and describes a request this model would not have sent.
1105
+ this.contextAnchor = undefined;
1106
+ this.subagents.updateConfig(next);
1107
+ this.codexHooks?.updateConfig(next);
1108
+ this.thinkingPlan = thinkingPlan;
1109
+ this.promptCachePlan = promptCachePlan;
1110
+ const choice = next.modelChoices.find((entry) => entry.index === target.index);
1111
+ return {
1112
+ choice,
1113
+ thinking: this.thinkingPlan,
1114
+ promptCache: this.promptCachePlan,
1115
+ saved: saveEnabledModel(this.projectRoot, target.index),
1116
+ };
1117
+ }
1118
+ /**
1119
+ * Token totals for every model call this agent has made so far.
1120
+ *
1121
+ * Read live from the SDK's meter rather than tallied from stream events:
1122
+ * `accumulatedUsage` is a lifetime accumulator (see the SDK reuse section of
1123
+ * `docs/architecture/load-bearing-decisions.md`), so it is already the
1124
+ * running total and is readable between turns, including after a cancelled one
1125
+ * that never produced an `agentResultEvent`.
1126
+ *
1127
+ * Counts this process only. Sessions persist messages, not metrics, so a
1128
+ * `--resume`d session starts from zero however much it spent before — callers
1129
+ * that show these numbers should say so.
1130
+ */
1131
+ get usage() {
1132
+ const usage = this.agent.metrics.accumulatedUsage;
1133
+ return {
1134
+ inputTokens: usage.inputTokens,
1135
+ outputTokens: usage.outputTokens,
1136
+ // Absence and a measured zero are different provider statements. Preserve
1137
+ // that distinction for the provider-aware usage projection.
1138
+ ...(usage.cacheReadInputTokens !== undefined && {
1139
+ cacheReadInputTokens: usage.cacheReadInputTokens,
1140
+ }),
1141
+ ...(usage.cacheWriteInputTokens !== undefined && {
1142
+ cacheWriteInputTokens: usage.cacheWriteInputTokens,
1143
+ }),
1144
+ };
1145
+ }
1146
+ /**
1147
+ * Token delta for the most recently completed turn, or `undefined` before any
1148
+ * turn has finished. A cancelled turn still produces a delta covering whatever
1149
+ * model calls completed before the cancel.
1150
+ */
1151
+ get lastTurnUsage() {
1152
+ return this.lastTurnDelta;
1153
+ }
1154
+ /**
1155
+ * The parent Agent's model-retry wait in progress — decided on a failed attempt,
1156
+ * cleared when the wait ends (timer or cancel) and at turn end — or `undefined`
1157
+ * when no attempt is waiting. Read on the driver's existing tick; a child's wait is
1158
+ * reachable only through its own installer and never surfaces here (SER-066).
1159
+ */
1160
+ retryWait() {
1161
+ return this.modelRetry.retryWait();
1162
+ }
1163
+ /**
1164
+ * How the parent's last turn ended when retry played a part — the cap reached, or
1165
+ * a wait cancelled — for the driver's failure notice; `undefined` otherwise and
1166
+ * once the next turn begins (SER-067). Parent only, like {@link retryWait}.
1167
+ */
1168
+ retryOutcome() {
1169
+ return this.modelRetry.retryOutcome();
1170
+ }
1171
+ /**
1172
+ * Folds one stream event into the session call stats. Synchronous, and swallows
1173
+ * its own failures on the recorder's terms: an observer between `stream()` and
1174
+ * `yield` that could throw would be a second way for a turn to die. The first
1175
+ * failure latches the stats broken — every surface then reads absence rather
1176
+ * than a tally that silently missed calls.
1177
+ */
1178
+ observeCallStats(event) {
1179
+ if (this.callStatsBroken || event.type !== 'afterModelCallEvent')
1180
+ return;
1181
+ try {
1182
+ const stopData = event.stopData;
1183
+ // A failed attempt has no stopData: nothing completed, nothing to count.
1184
+ if (stopData === undefined)
1185
+ return;
1186
+ this.callStatsState = recordCompletedCall(this.callStatsState, stopData);
1187
+ }
1188
+ catch {
1189
+ this.callStatsBroken = true;
1190
+ }
1191
+ }
1192
+ /**
1193
+ * Folds one stream event into the `/context` measurement anchor: a completed model
1194
+ * call's provider counters say exactly how large the request it just sent was, so
1195
+ * that number replaces the heuristic base for the next estimate.
1196
+ *
1197
+ * Same observer discipline as {@link observeCallStats}, with its own latch so
1198
+ * neither can break the other. A call that measures nothing (failed attempt,
1199
+ * unreported counters, a split that cannot be made honestly) leaves the previous
1200
+ * anchor in place — it is still the best measurement available — rather than
1201
+ * downgrading `/context` to a pure heuristic mid-session.
1202
+ */
1203
+ observeContextAnchor(event) {
1204
+ if (this.contextAnchorBroken || event.type !== 'afterModelCallEvent')
1205
+ return;
1206
+ try {
1207
+ const stopData = event.stopData;
1208
+ if (stopData === undefined)
1209
+ return;
1210
+ const anchor = anchorFromCall(stopData, this.agent.messages, this.liveConfig);
1211
+ if (anchor !== undefined)
1212
+ this.contextAnchor = anchor;
1213
+ }
1214
+ catch {
1215
+ this.contextAnchorBroken = true;
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Per-model-call efficiency stats for this session's parent agent, or
1220
+ * `undefined` until a completed call has been observed — so every surface that
1221
+ * reads this stays byte-identical to before the feature existed when nothing
1222
+ * happened yet (the `childUsage` convention). Also `undefined` after a tally
1223
+ * failure: a broken stat degrades to absence, never to a wrong number. Children
1224
+ * are deliberately not counted here; their spend is {@link childUsage}'s story.
1225
+ */
1226
+ get callStats() {
1227
+ if (this.callStatsBroken || this.callStatsState.calls === 0)
1228
+ return undefined;
1229
+ return this.callStatsState;
1230
+ }
1231
+ /**
1232
+ * Token totals for this run's child agents (subagent dispatches and workflow
1233
+ * nodes), summed over the dispatch registry — running children read live,
1234
+ * finished ones report their frozen terminal reading, and a cancelled or
1235
+ * failed child still counts what it spent. `dispatches` counts only the
1236
+ * dispatches whose usage was included in the sum. `undefined` when no
1237
+ * dispatch ever reported usage, so zero-delegation sessions are
1238
+ * indistinguishable from before children were counted at all.
1239
+ */
1240
+ get childUsage() {
1241
+ return this.subagentDispatches.totalUsage();
1242
+ }
1243
+ /**
1244
+ * Everything this session has spent: the parent meter ({@link usage}) plus
1245
+ * {@link childUsage} when any child reported spend — exactly `this.usage`
1246
+ * otherwise, so callers without delegation see the same totals they always
1247
+ * did. Summed with `sumUsage`, whose cache counters stay absent until some
1248
+ * meter reports them (never an invented zero). Like the parent meter across
1249
+ * `/model` switches, the raw sum is projected with the *live* config.
1250
+ */
1251
+ get sessionUsage() {
1252
+ const children = this.childUsage;
1253
+ if (children === undefined)
1254
+ return this.usage;
1255
+ return sumUsage([this.usage, children.usage]);
1256
+ }
1257
+ /** Current-process background tasks, without creating an agent tool call. */
1258
+ listBackgroundTasks() {
1259
+ return this.backgroundBash.list();
1260
+ }
1261
+ /** Publishes future terminal task snapshots until the returned closure is called. */
1262
+ subscribeToBackgroundTasks(listener) {
1263
+ return this.backgroundBash.subscribe(listener);
1264
+ }
1265
+ /**
1266
+ * Every subagent dispatch of this run, in start order, running and finished
1267
+ * alike. Synchronous — unlike {@link listBackgroundTasks}, which snapshots live
1268
+ * OS processes through per-task queues, this is an in-memory registry with no
1269
+ * I/O at all.
1270
+ *
1271
+ * These are *runs*, not the catalogue: `info.agentNames` lists the definitions
1272
+ * that may be dispatched, which is a different question answered by a different
1273
+ * path. Records carry name, task text, closed phase, state, timestamps and the
1274
+ * child meter's usage counters — never any part of a child's transcript or tool
1275
+ * payload.
1276
+ */
1277
+ listSubagentDispatches() {
1278
+ return this.subagentDispatches.list();
1279
+ }
1280
+ /** Publishes future terminal dispatch snapshots until the returned closure is called. */
1281
+ subscribeToSubagentDispatches(listener) {
1282
+ return this.subagentDispatches.subscribe(listener);
1283
+ }
1284
+ /** User-visible safe phase updates and periodic heartbeats; never model/trajectory input. */
1285
+ subscribeToSubagentProgress(listener) {
1286
+ return this.subagentDispatches.subscribeProgress(listener);
1287
+ }
1288
+ /** User-only exact-id cancellation; no agent tool exposes this operation. */
1289
+ cancelSubagentDispatch(dispatchId) {
1290
+ return this.subagentDispatches.cancel(dispatchId);
1291
+ }
1292
+ /**
1293
+ * Asks the agent to stop the current turn at its next safe point. The stream
1294
+ * ends with `stopReason: 'cancelled'` rather than throwing.
1295
+ */
1296
+ cancel() {
1297
+ this.lifecycleHooks?.cancel();
1298
+ this.codexHooks?.cancel();
1299
+ this.subagents.cancelActive();
1300
+ this.workflows.cancelActive();
1301
+ this.agent.cancel();
1302
+ }
1303
+ /** Publishes a bounded driver-owned turn outcome; command results are unobservable. */
1304
+ observeTurnComplete(outcome, source) {
1305
+ this.lifecycleHooks?.publish({ event: 'TurnComplete', outcome, source });
1306
+ this.codexHooks?.stop(outcome);
1307
+ }
1308
+ /** Drains bounded portable-hook diagnostics for the existing driver notice channels. */
1309
+ takeHookProblems() {
1310
+ return this.codexHooks?.takeProblems() ?? [];
1311
+ }
1312
+ /** Publishes one truthful approval request only when it becomes visible. */
1313
+ observePermissionRequest(request) {
1314
+ const event = { event: 'PermissionRequest', source: request.source };
1315
+ if (this.codexHooks === undefined) {
1316
+ this.lifecycleHooks?.publish(event);
1317
+ return;
1318
+ }
1319
+ // Setup order is source-granular: portable before native within each .agents layer.
1320
+ for (const layer of this.toolHookLayers) {
1321
+ if (layer.dialect === 'codex') {
1322
+ this.codexHooks.permissionRequest(request, layer.hooks.PermissionRequest);
1323
+ }
1324
+ else {
1325
+ this.lifecycleHooks?.publishGroups(event, layer.hooks.PermissionRequest);
1326
+ }
1327
+ }
1328
+ }
1329
+ /** Completed prompt boundaries available for an in-session conversation branch. */
1330
+ async listRewindCheckpoints() {
1331
+ const catalogue = await readRewindCatalogue(this.projectRoot, this.info.sessionId);
1332
+ const snapshotIds = await this.sessionManager.listSnapshotIds({
1333
+ target: this.agent,
1334
+ limit: MAX_REWIND_CHECKPOINTS,
1335
+ });
1336
+ return {
1337
+ ...catalogue,
1338
+ checkpoints: newestRewindCheckpoints(catalogue),
1339
+ captureCapacityReached: snapshotIds.length >= MAX_REWIND_CHECKPOINTS,
1340
+ };
1341
+ }
1342
+ /**
1343
+ * Branches from one catalogued source boundary into a fresh runtime.
1344
+ *
1345
+ * Selection is re-read immediately before assembly, so a stale UI row cannot name
1346
+ * an arbitrary SDK snapshot. Source files remain read-only throughout; only the
1347
+ * fresh successor id receives a latest snapshot.
1348
+ */
1349
+ async startRewind(checkpoint) {
1350
+ const catalogue = await readRewindCatalogue(this.projectRoot, this.info.sessionId);
1351
+ if (catalogue.problem !== undefined)
1352
+ throw new Error(catalogue.problem);
1353
+ const current = catalogue.checkpoints.find((entry) => entry.snapshotId === checkpoint.snapshotId);
1354
+ if (current === undefined || current.prompt !== checkpoint.prompt || current.completedAt !== checkpoint.completedAt) {
1355
+ throw new Error('The selected rewind checkpoint is stale or unmapped.');
1356
+ }
1357
+ let successor;
1358
+ try {
1359
+ successor = await AgentRuntime.create({
1360
+ ...this.createOptions,
1361
+ session: { kind: 'new' },
1362
+ rewindRestore: {
1363
+ sourceSessionId: this.info.sessionId,
1364
+ snapshotId: current.snapshotId,
1365
+ },
1366
+ permissionModeOverride: this.gate.mode,
1367
+ inherit: {
1368
+ config: this.liveConfig,
1369
+ mcp: this.mcp,
1370
+ backgroundBash: this.backgroundBash,
1371
+ },
1372
+ });
1373
+ }
1374
+ catch (error) {
1375
+ if (this.diagnosticsLog !== undefined)
1376
+ setSdkVerboseSink(this.diagnosticsLog.sdkSink);
1377
+ throw error;
1378
+ }
1379
+ await this.retire();
1380
+ return successor;
1381
+ }
1382
+ /**
1383
+ * Records this session as the one `--resume` should reopen. Called after a turn
1384
+ * completes, so an unused session never displaces a useful one.
1385
+ */
1386
+ async markResumable() {
1387
+ await writePointer(this.projectRoot, this.info.sessionId);
1388
+ }
1389
+ /**
1390
+ * Starts a brand-new session in this process and returns the runtime that owns it.
1391
+ * This runtime is retired and must not be used again; the caller becomes
1392
+ * responsible for shutting the successor down.
1393
+ *
1394
+ * A *new Agent* is what makes this a new session, and there is no cheaper way:
1395
+ * `SessionManager` is an SDK plugin whose snapshot hooks are registered during
1396
+ * `initialize()` with no removal path, and its session id is private and readonly.
1397
+ * Assigning a second manager
1398
+ * would leave the first one's hooks live, and at the end of the next turn it would
1399
+ * overwrite the *previous* session's `snapshot_latest.json` with the cleared
1400
+ * conversation — destroying the thing `/clear` exists to preserve. So the successor
1401
+ * is assembled through the same {@link create} factory rather than a second
1402
+ * hand-written assembly that could drift from it.
1403
+ *
1404
+ * Nothing is deleted, moved or rewritten: the session being left keeps its snapshot,
1405
+ * its `trajectory.jsonl` (flushed here, never truncated), its `offload/` and its
1406
+ * `background/` exactly as they are, and stays resumable by id.
1407
+ *
1408
+ * The resume pointer is deliberately *not* moved. `markResumable()` writes it after a
1409
+ * completed turn precisely so an unused session cannot displace a useful one — and
1410
+ * an empty session has no snapshot to resume, so pointing `--resume` at it would cost
1411
+ * the user the conversation they just set aside. The successor claims the pointer on
1412
+ * its first finished turn, through the ordinary path.
1413
+ *
1414
+ * If assembling the successor fails, this runtime stays fully usable: nothing it owns
1415
+ * has been released yet, and the diagnostics tap it installed at startup is put back
1416
+ * (the failed successor's unwind clears the process-global sink).
1417
+ */
1418
+ async startNewSession() {
1419
+ let successor;
1420
+ try {
1421
+ successor = await AgentRuntime.create({
1422
+ ...this.createOptions,
1423
+ session: { kind: 'new' },
1424
+ // The live mode, not the one this runtime was created with: `/mode` is the
1425
+ // user's own standing instruction about enforcement, and letting `/clear`
1426
+ // quietly restore a *wider* startup policy would be a widening nobody asked
1427
+ // for. A fresh process still starts from configured/CLI policy.
1428
+ permissionModeOverride: this.gate.mode,
1429
+ inherit: {
1430
+ config: this.liveConfig,
1431
+ mcp: this.mcp,
1432
+ backgroundBash: this.backgroundBash,
1433
+ },
1434
+ });
1435
+ }
1436
+ catch (error) {
1437
+ if (this.diagnosticsLog !== undefined)
1438
+ setSdkVerboseSink(this.diagnosticsLog.sdkSink);
1439
+ throw error;
1440
+ }
1441
+ await this.retire();
1442
+ return successor;
1443
+ }
1444
+ /**
1445
+ * Releases what this runtime owns *alone* after a successor has taken over.
1446
+ *
1447
+ * The complement of {@link shutdown}, and the difference is the point: the MCP
1448
+ * clients and the background-job manager now belong to the successor, so
1449
+ * disconnecting the servers or stopping the jobs here would break a live session.
1450
+ * The process-global SDK verbose sink is left alone for the same reason — the
1451
+ * successor installed its own, and clearing it would silence the new session's
1452
+ * diagnostics.
1453
+ *
1454
+ * What is released: this Agent's own persistent bash shell (the vended tool keys
1455
+ * shells per Agent, so leaving it would hold the event loop open forever), the
1456
+ * subagent tool, and the two observers, closed so their bytes are durable. Failures
1457
+ * are settled, not thrown: a retirement that cannot flush must not take the new
1458
+ * session down with it.
1459
+ */
1460
+ async retire() {
1461
+ // `/clear` and rewind retire the session before any still-pending closing append
1462
+ // may accept memory. Already accepted commits are unaffected and still awaited.
1463
+ this.memoryController?.discardUnsettled();
1464
+ const ownedWork = await Promise.allSettled([
1465
+ this.subagents.shutdown(),
1466
+ this.stopBashSession(),
1467
+ this.lifecycleHooks?.close() ?? Promise.resolve(),
1468
+ this.trajectory?.close() ?? Promise.resolve(),
1469
+ ]);
1470
+ // Closing trajectory first publishes the final settlement. The controller then
1471
+ // discards unresolved staging and waits only for commits already accepted.
1472
+ await Promise.allSettled([Promise.resolve(ownedWork), this.memoryController?.close() ?? Promise.resolve()]);
1473
+ // SessionEnd is the final advisory boundary: all session-owned work above has
1474
+ // settled, while diagnostics remains open to retain a bounded hook problem.
1475
+ await Promise.allSettled([
1476
+ this.codexHooks?.sessionEnd('other').then(() => this.codexHooks?.close()) ?? Promise.resolve(),
1477
+ ]);
1478
+ await Promise.allSettled([this.diagnosticsLog?.close() ?? Promise.resolve()]);
1479
+ }
1480
+ /**
1481
+ * Creates one bounded rewind snapshot, serialized so concurrent callers cannot
1482
+ * both observe the final free slot. The tail is repaired after rejection so one
1483
+ * storage failure does not permanently block later ordinary turns.
1484
+ */
1485
+ captureRewindCheckpoint() {
1486
+ const capture = this.rewindCaptureTail.then(async () => {
1487
+ // Probe only as far as Darwin can own. Failed/cancelled turns consume capacity
1488
+ // too, because their immutable SDK snapshots cannot be deleted or reused. At
1489
+ // capacity, rewind capture degrades open: the ordinary invocation and latest
1490
+ // resumable snapshot still proceed, but no 101st immutable snapshot is created.
1491
+ const existingIds = await this.sessionManager.listSnapshotIds({
1492
+ target: this.agent,
1493
+ limit: MAX_REWIND_CHECKPOINTS,
1494
+ });
1495
+ if (existingIds.length >= MAX_REWIND_CHECKPOINTS) {
1496
+ this.diagnosticsLog?.notice(`rewind checkpoint omitted: immutable snapshot capacity ${MAX_REWIND_CHECKPOINTS} reached`, 'warn');
1497
+ return undefined;
1498
+ }
1499
+ const previousId = existingIds.at(-1);
1500
+ await this.sessionManager.saveSnapshot({ target: this.agent, isLatest: false });
1501
+ const createdIds = await this.sessionManager.listSnapshotIds({
1502
+ target: this.agent,
1503
+ limit: 1,
1504
+ ...(previousId === undefined ? {} : { startAfter: previousId }),
1505
+ });
1506
+ if (createdIds.length === 1)
1507
+ return createdIds[0];
1508
+ throw new Error('Could not identify the immutable rewind checkpoint created for this prompt.');
1509
+ });
1510
+ this.rewindCaptureTail = capture.then(() => undefined, () => undefined);
1511
+ return capture;
1512
+ }
1513
+ /**
1514
+ * Expands a built-in prompt command, a skill, or a project command into the
1515
+ * prompt sent to the model. `/workflow` is checked first: built-in
1516
+ * reservation precedes skills and custom commands, so no extension can
1517
+ * shadow it. Its bare form returns null — the drivers own that local usage
1518
+ * notice, and the runtime never fabricates a turn. Skills are checked before
1519
+ * custom commands as a defensive backstop to the loader's collision
1520
+ * filtering. Unknown slash input remains ordinary user input.
1521
+ */
1522
+ async expandSlashCommand(input) {
1523
+ const workflow = parseWorkflowCommand(input);
1524
+ if (workflow === 'missing-task')
1525
+ return null;
1526
+ if (workflow !== null)
1527
+ return { kind: 'workflow', ...workflow };
1528
+ const skill = await expandSkillCommand(this.skills, input);
1529
+ if (skill !== null)
1530
+ return { kind: 'skill', ...skill };
1531
+ const command = expandCustomCommand(this.commands, input);
1532
+ return command === null ? null : { kind: 'command', ...command };
1533
+ }
1534
+ /**
1535
+ * Releases every child process the session owns. Must run on exit: both the
1536
+ * bash shell and stdio MCP servers are spawned subprocesses whose open pipes
1537
+ * keep the event loop alive, so skipping this hangs the process instead of
1538
+ * exiting.
1539
+ */
1540
+ async shutdown(options = {}) {
1541
+ const results = await Promise.allSettled([
1542
+ this.subagents.shutdown(),
1543
+ this.workflows.shutdown(),
1544
+ this.backgroundBash.shutdown(),
1545
+ this.stopBashSession(options.throwOnError === true),
1546
+ this.lifecycleHooks?.close() ?? Promise.resolve(),
1547
+ disconnectAll(this.mcp.clients, { throwOnError: options.throwOnError === true }),
1548
+ // Settle the append chain before memory closes below. The callback stays
1549
+ // unawaited; cleanup only waits for a commit after durable acceptance.
1550
+ this.trajectory?.close() ?? Promise.resolve(),
1551
+ ]);
1552
+ const memoryResults = await Promise.allSettled([this.memoryController?.close() ?? Promise.resolve()]);
1553
+ results.push(...memoryResults);
1554
+ // SessionEnd is advisory but ordered after owned work. Keep diagnostics open
1555
+ // through it, then detach the process-global SDK tap before closing the file.
1556
+ results.push(...await Promise.allSettled([
1557
+ this.codexHooks?.sessionEnd('other').then(() => this.codexHooks?.close()) ?? Promise.resolve(),
1558
+ ]));
1559
+ if (this.diagnosticsLog !== undefined)
1560
+ setSdkVerboseSink(undefined);
1561
+ results.push(...await Promise.allSettled([this.diagnosticsLog?.close() ?? Promise.resolve()]));
1562
+ const failures = results.flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
1563
+ if (options.throwOnError === true && failures.length > 0) {
1564
+ throw new AggregateError(failures, `${failures.length} runtime cleanup operation(s) failed`);
1565
+ }
1566
+ }
1567
+ /**
1568
+ * Kills the persistent bash shell the vended `bash` tool keeps per agent.
1569
+ *
1570
+ * The SDK registers a `beforeExit` handler to do this, but `beforeExit` only
1571
+ * fires once the event loop is empty — and the shell's own stdio pipes are what
1572
+ * keep it non-empty, so that handler never runs and the process hangs forever
1573
+ * after any command has been executed.
1574
+ *
1575
+ * `mode: 'restart'` is the public way to reach the session: it stops the running
1576
+ * shell and installs a fresh one that is only spawned on the next command, so
1577
+ * nothing is left holding the loop open. The call is made directly (bypassing
1578
+ * the model loop) with history recording off, so it neither prompts for
1579
+ * permission nor appears in the conversation.
1580
+ */
1581
+ async stopBashSession(throwOnError = false) {
1582
+ const bashTool = this.agent.tool['bash'];
1583
+ if (bashTool === undefined)
1584
+ return;
1585
+ try {
1586
+ await bashTool.invoke({ mode: 'restart' }, { recordDirectToolCall: false });
1587
+ }
1588
+ catch (error) {
1589
+ // Interactive shutdown remains best-effort. Headless mode asks for the
1590
+ // failure after every cleanup operation has still had its chance to run.
1591
+ if (throwOnError)
1592
+ throw error;
1593
+ }
1594
+ }
1595
+ }
1596
+ //# sourceMappingURL=runtime.js.map