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,2660 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useApp, useBoxMetrics, useInput, usePaste, useStdout, useWindowSize } from 'ink';
3
+ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from 'react';
4
+ import { AGENTS_FILENAME, MAX_INSTRUCTIONS_BYTES } from '../agent/instructions.js';
5
+ import { APPROVAL_MODES, describeApprovalMode, isApprovalMode, } from '../agent/permission.js';
6
+ import { compactFocusRefusal, normalizeCompactFocus } from '../agent/compact.js';
7
+ import { formatUsageValue, sumUsage, usageBuckets, usageRows, cacheEffectivenessRows } from '../agent/usage.js';
8
+ import { describeModelCosts } from '../agent/cost.js';
9
+ import { averageRequestInputTokens } from '../agent/call-stats.js';
10
+ import { runWithStreamResumption, STREAM_CONTINUATION_NOTICE } from '../agent/stream-resumption.js';
11
+ import { retryFailureNotice } from '../agent/model-retry.js';
12
+ import { isRefusalStop, REFUSAL_NOTICE } from '../agent/refusal.js';
13
+ import { contextOverflowErrorMessage } from '../context-overflow-error.js';
14
+ import { routeSdkLogs } from '../agent/sdk-logging.js';
15
+ import { SYSTEM_PROMPT_FILENAME } from '../agent/system-prompt.js';
16
+ import { isThinkingEffort, THINKING_EFFORTS, } from '../agent/thinking.js';
17
+ import { CONFIG_FILENAME } from '../config.js';
18
+ import { BUILTIN_COMMAND_NAMES } from '../commands/custom-commands.js';
19
+ import { WORKFLOW_COMMAND_USAGE, parseWorkflowCommand } from '../commands/workflow-command.js';
20
+ import { MCP_CONFIG_FILENAME, mcpConfigCandidates } from '../mcp/registry.js';
21
+ import { DARWIN_DIRNAME } from '../paths.js';
22
+ import { readBackgroundTails } from '../tools/background-tail.js';
23
+ import { exportTranscript } from '../trajectory/export.js';
24
+ import { readPromptHistory, } from '../trajectory/prompt-history.js';
25
+ import { InputBox, MAX_COMPLETIONS, completionSelection, moveCompletionSelection, } from './InputBox.js';
26
+ import { busySuffix } from './busy-suffix.js';
27
+ import { LIVE_BLOCK_CHROME_ROWS, wrapToRows } from './live-text.js';
28
+ import { fenceOpenAfter } from './markdown.js';
29
+ import { PERMISSION_BOX_FIXED_ROWS, frameBudget, promptBoxWanted, queueListWanted, toolDetailsVisible, toolInputRows, toolPanelWanted, } from './frame-budget.js';
30
+ import { MessageList } from './MessageList.js';
31
+ import { PermissionPrompt, permissionBoxClaim } from './PermissionPrompt.js';
32
+ import { welcomeLayout } from './WelcomeHeader.js';
33
+ import { ActiveToolCalls } from './ToolCallPanel.js';
34
+ import { QueuedMessages } from './QueuedMessages.js';
35
+ import { backspaceAtCursor, deleteAtCursor, deleteWordAfter, deleteWordBefore, insertAtCursor, killToRowEdge, layoutEditor, moveHorizontal, moveToRowEdge, moveVertical, moveWordHorizontal, popUndo, pushUndo, } from './prompt-editor.js';
36
+ import { NO_WORKSPACE_PATHS, applyPathCompletion, scanWorkspacePaths, workspacePathsNote, } from './path-completion.js';
37
+ import { promptCompletionState, visiblePromptCompletions, } from './prompt-completion.js';
38
+ import { openPromptRecall, promptRecallIndicator, stepPromptRecall, } from './prompt-recall.js';
39
+ import { acceptPromptHistorySearch, appendPromptHistorySearchQuery, backspacePromptHistorySearchQuery, cancelPromptHistorySearch, clearPromptHistorySearchQuery, movePromptHistorySearchSelection, openPromptHistorySearch, promptHistorySearchView, resolvePromptHistorySearch, } from './prompt-history-search.js';
40
+ import { ESCAPE_REWIND_CHORD_MS, acceptRewindSearch, appendRewindSearchQuery, backspaceRewindSearchQuery, cancelRewindSearch, clearRewindSearchQuery, moveRewindSearchSelection, openRewindSearch, rewindSearchView, } from './rewind-search.js';
41
+ import { clipboardImageFact, readClipboardImage } from './clipboard-image.js';
42
+ import { hasQueuedImage, queuedCountHint, refusesToQueue, takeBackDraft } from './prompt-queue.js';
43
+ import { composeShellReport, parseShellCommand, projectShellOutput, runShellCommand, } from './shell-command.js';
44
+ import { formatTaskCompletion, formatTasksReport } from './task-format.js';
45
+ import { formatDispatchCancellation, formatDispatchCompletion, formatDispatchesReport, } from './subagent-format.js';
46
+ import { createContextWarnLatch, formatContextReport } from './context-format.js';
47
+ import { COPY_COMMAND_USAGE, runCopyCommand } from './copy-command.js';
48
+ import { formatHelpReport } from './help-format.js';
49
+ import { formatMcpReport } from './mcp-format.js';
50
+ import { formatPromptCache, formatPromptCacheState, formatStatusReport, formatThinking, } from './status-format.js';
51
+ import { PlanChecklist } from './PlanChecklist.js';
52
+ import { ringTerminalBell } from './terminal-bell.js';
53
+ import { initialTurnState, turnReducer } from './turn-state.js';
54
+ import { visualColor, visualMarker } from './visual-language.js';
55
+ /** Window in which a second Ctrl+C means "exit", not "cancel again". */
56
+ const DOUBLE_INTERRUPT_MS = 2000;
57
+ const SPINNER_INTERVAL_MS = 90;
58
+ /**
59
+ * How long one workspace path scan is reused before the next `@` re-reads the tree.
60
+ *
61
+ * Long enough that completing `@src/tui/App.tsx` one segment at a time is a single
62
+ * scan, short enough that a file the agent just wrote is offered the next time the
63
+ * user reaches for it. Staleness is only ever a missing row: an accepted completion
64
+ * is text, so a path that has since moved costs a wrong argument to a tool call the
65
+ * user can see, not a silent read of the wrong file.
66
+ */
67
+ const PATH_SCAN_TTL_MS = 5000;
68
+ /**
69
+ * Header height assumed before the first layout pass: this project's own header,
70
+ * rounded up. Guessing high only costs a few rows of the first streamed frame;
71
+ * guessing low costs the scrollback.
72
+ */
73
+ const ASSUMED_HEADER_ROWS = 14;
74
+ /** C0 controls except LF and tab, plus DEL: never treated as draft text. */
75
+ const NON_TEXT_CONTROLS = /[\u0000-\u0008\u000b-\u001f\u007f]/g;
76
+ /**
77
+ * Erase the screen, the scrollback and home the cursor — Ink's own `clearTerminal`,
78
+ * spelled out here because `ansi-escapes` is Ink's dependency and not darwin's.
79
+ *
80
+ * Written exactly once per `/clear`, through Ink's stdout writer. This is the same
81
+ * sequence Ink's pathological over-tall-frame branch writes per render, which is what
82
+ * `frame-budget.ts` exists to avoid: one deliberate clear on an explicit command is a
83
+ * different thing from one per text delta.
84
+ */
85
+ const CLEAR_TERMINAL = '\u001B[2J\u001B[3J\u001B[H';
86
+ /** Canonicalizes terminal line endings and drops controls without losing layout. */
87
+ function normalizeDraftText(value) {
88
+ return value.replace(/\r+\n/g, '\n').replace(/\r/g, '\n').replace(NON_TEXT_CONTROLS, '');
89
+ }
90
+ export function App({ runtime: initialRuntime, permissions, initialHistory = [], startNewSession, startRewind, }) {
91
+ const { exit, waitUntilRenderFlush } = useApp();
92
+ const { columns, rows } = useWindowSize();
93
+ const { write: writeToTerminal } = useStdout();
94
+ // The live session. A prop at startup, state afterwards: `/clear` replaces the
95
+ // runtime rather than resetting one, so everything read off it — session id, usage
96
+ // meter, trajectory recorder, context estimate — moves to the new session together,
97
+ // and the old session's numbers cannot leak into the new transcript.
98
+ const [runtime, setRuntime] = useState(initialRuntime);
99
+ const [state, recordAction] = useReducer(turnReducer, initialHistory, (history) => ({ ...initialTurnState, history: [...history] }));
100
+ // The ready welcome is process/App-scoped, not session-scoped. Capture its
101
+ // complete responsive variant once so a later resize cannot mutate an item
102
+ // that Ink's Static has already committed to scrollback.
103
+ const [initialWelcome] = useState(() => welcomeLayout(columns, rows));
104
+ // Swapped whole rather than branched per call: with `diagnostics` off — the default —
105
+ // `dispatch` *is* the reducer's own dispatch, so not one of the ~50 notice sites
106
+ // below pays anything, and the mirror cannot be forgotten at a new one either.
107
+ const dispatch = useMemo(() => withNoticeDiagnostics(recordAction, runtime.diagnostics), [recordAction, runtime]);
108
+ // The transcript as of the latest render, for `/copy`: `submit` is memoized on a
109
+ // few deps and must not be rebuilt on every streamed line, so it reads the history
110
+ // through this mirror rather than closing over `state`.
111
+ const historyRef = useRef(state.history);
112
+ historyRef.current = state.history;
113
+ const [status, setStatus] = useState('idle');
114
+ const [workspacePaths, setWorkspacePaths] = useState(NO_WORKSPACE_PATHS);
115
+ const commandNames = useMemo(() => [
116
+ ...BUILTIN_COMMAND_NAMES,
117
+ ...runtime.info.commandNames,
118
+ ...runtime.info.skillNames,
119
+ ], [runtime]);
120
+ // Escape suppresses one computed query generation, not the draft. Mirrors are
121
+ // required for the same reason as the editor/selection mirrors: a second batched
122
+ // key must see the first Escape before React commits its render.
123
+ const [dismissedCompletion, setDismissedCompletionState] = useState(undefined);
124
+ const dismissedCompletionRef = useRef(dismissedCompletion);
125
+ const setDismissedCompletion = useCallback((next) => {
126
+ dismissedCompletionRef.current = next;
127
+ setDismissedCompletionState(next);
128
+ }, []);
129
+ const [editor, setEditorState] = useState({
130
+ text: '',
131
+ cursor: { offset: 0, affinity: 'downstream' },
132
+ });
133
+ // React may render after several stdin events have already arrived. Keep one
134
+ // immediate editor mirror so batched events cannot read different generations
135
+ // of the draft and cursor. A change that creates a different query generation
136
+ // re-arms completion immediately; Escape itself never calls this setter.
137
+ const editorRef = useRef(editor);
138
+ const setEditor = useCallback((next) => {
139
+ const current = editorRef.current;
140
+ const value = typeof next === 'function' ? next(current) : next;
141
+ editorRef.current = value;
142
+ if (dismissedCompletionRef.current !== undefined && (value.text !== current.text || value.cursor.offset !== current.cursor.offset ||
143
+ value.cursor.affinity !== current.cursor.affinity)) {
144
+ const changedCompletion = promptCompletionState(value, commandNames, workspacePaths);
145
+ if (changedCompletion.identity !== dismissedCompletionRef.current)
146
+ setDismissedCompletion(undefined);
147
+ }
148
+ setEditorState(value);
149
+ }, [commandNames, setDismissedCompletion, workspacePaths]);
150
+ const draft = editor.text;
151
+ /** Pending clipboard image, live-only; bytes never enter editor text or records. */
152
+ const [attachedImage, setAttachedImageState] = useState(undefined);
153
+ const attachedImageRef = useRef(attachedImage);
154
+ const setAttachedImage = useCallback((next) => {
155
+ attachedImageRef.current = next;
156
+ setAttachedImageState(next);
157
+ }, []);
158
+ const layout = layoutEditor(draft, columns, editor.cursor);
159
+ const preferredColumn = useRef(undefined);
160
+ // Composer undo (SER-044): the drafts destroyed by kill/word-delete chords,
161
+ // owned here like `preferredColumn`. Cleared wherever the draft leaves the
162
+ // editor's ownership (submit, queue take-back, recall walk, search accept),
163
+ // so Ctrl+_ can never resurrect a prompt that was already sent or recorded.
164
+ const undoStack = useRef([]);
165
+ /**
166
+ * Applies one destructive editing chord: snapshots the exact draft it
167
+ * destroys (only when it destroys anything — a no-op kill at an edge must
168
+ * not burn an undo step), then commits the result. Reads the immediate
169
+ * editor mirror for the same batched-stdin reason `setEditor` does.
170
+ */
171
+ const applyDestructive = useCallback((edit) => {
172
+ const current = editorRef.current;
173
+ const next = edit(current);
174
+ if (next.text !== current.text)
175
+ undoStack.current = pushUndo(undoStack.current, current);
176
+ setEditor(next);
177
+ }, [setEditor]);
178
+ // The frame's fixed furniture. Only the header is *measured*: its height depends
179
+ // on nothing below it, so measuring it cannot oscillate. Everything else states
180
+ // what it wants and `frameBudget` hands out the rows — see `frame-budget.ts` for
181
+ // why the round-1 arrangement (measure the chrome, give the answer the rest) was
182
+ // not enough once the chrome turned out to be unbounded too.
183
+ const headerRef = useRef(null);
184
+ const chromeRef = useRef(null);
185
+ const header = useBoxMetrics(headerRef);
186
+ // Still measured, but only for the cursor: `useBoxMetrics` is parent-relative and
187
+ // `useCursor` is frame-absolute, so `InputBox` needs its parent's offset.
188
+ const chrome = useBoxMetrics(chromeRef);
189
+ // Like the editor and recall mirrors below, completion selection must advance on
190
+ // each stdin event immediately. The visible marker and Tab/Enter acceptance then
191
+ // read the same full-list identity even when a terminal batches arrow keys.
192
+ const [selectedCompletion, setSelectedCompletionState] = useState(0);
193
+ const selectedCompletionRef = useRef(selectedCompletion);
194
+ const setSelectedCompletion = useCallback((next) => {
195
+ const value = typeof next === 'function' ? next(selectedCompletionRef.current) : next;
196
+ selectedCompletionRef.current = value;
197
+ setSelectedCompletionState(value);
198
+ }, []);
199
+ const [frame, setFrame] = useState(0);
200
+ const interruptedAt = useRef(undefined);
201
+ /** Wall-clock start of the in-flight turn; undefined whenever no turn is running. */
202
+ const turnStartedAt = useRef(undefined);
203
+ const contextWarnLatch = useRef(createContextWarnLatch());
204
+ /** One trajectory-problem notice per session; the recorder latches the failure itself. */
205
+ const trajectoryWarned = useRef(false);
206
+ /** Same, once, for the diagnostics log: it latches its own failure too. */
207
+ const diagnosticsWarned = useRef(false);
208
+ /** One bounded project-memory degradation notice per runtime. */
209
+ const memoryWarned = useRef(false);
210
+ /** True while `/clear` is assembling the successor runtime; see the handler. */
211
+ const clearing = useRef(false);
212
+ /** Kill handle of the running `!` command; undefined whenever none is running. */
213
+ const shellRun = useRef(undefined);
214
+ /** Distinguishes the live panel rows of successive `!` commands. */
215
+ const shellRunCount = useRef(0);
216
+ /**
217
+ * Bounded `!` reports awaiting the next model-bound prompt (PRD D5). They ride
218
+ * ahead of that prompt's text through the ordinary send path — never injected
219
+ * into `agent.messages`, never a turn of their own — and `/clear` drops them
220
+ * with the conversation they were destined for.
221
+ */
222
+ const pendingShellReports = useRef([]);
223
+ /**
224
+ * The prompt queue (SER-027, superseding SER-010's no-queue contract by explicit
225
+ * user decision): submissions made while a turn streams or a `!` command runs,
226
+ * oldest first. Drained one entry per idle through the ordinary submit path;
227
+ * taken back into the editor by `Up`; returned unsent after a cancel or a failed
228
+ * turn; dropped by `/clear` with the conversation. The ref is the same
229
+ * immediate mirror `editorRef` is: batched stdin events must read one
230
+ * generation of the queue.
231
+ */
232
+ const [queued, setQueuedState] = useState([]);
233
+ const queuedRef = useRef(queued);
234
+ const setQueued = useCallback((next) => {
235
+ queuedRef.current = next;
236
+ setQueuedState(next);
237
+ }, []);
238
+ /** True from a user Ctrl+C (or a turn failure) until the busy state it aborted ends. */
239
+ const turnAborted = useRef(false);
240
+ /** Latch: one queue entry in flight through submit(); see the drain effect. */
241
+ const draining = useRef(false);
242
+ /** Re-arms the drain effect after an entry whose submit left every dep unchanged. */
243
+ const [drainCycle, setDrainCycle] = useState(0);
244
+ /** Invalidates late clipboard-helper settlements after remove/send/clear. */
245
+ const clipboardReadGeneration = useRef(0);
246
+ /** Image currently owned by one model-bound invocation, blocking reassociation. */
247
+ const imageTurnInFlight = useRef(false);
248
+ /**
249
+ * Terminal-only acknowledgement for the answer-close handoff. Dispatching a
250
+ * reducer action proves only that React accepted it; the layout effect below
251
+ * acknowledges the specific commit that removed the mutable tail.
252
+ */
253
+ const answerCloseSequence = useRef(0);
254
+ const answerCloseWaiters = useRef(new Map());
255
+ const presentationMounted = useRef(true);
256
+ const unmountBarrier = useRef(undefined);
257
+ if (unmountBarrier.current === undefined) {
258
+ let resolve = () => undefined;
259
+ const promise = new Promise((done) => { resolve = done; });
260
+ unmountBarrier.current = { promise, resolve };
261
+ }
262
+ useLayoutEffect(() => {
263
+ for (const [id, acknowledge] of answerCloseWaiters.current) {
264
+ if (id > state.answerCloseCommit)
265
+ continue;
266
+ answerCloseWaiters.current.delete(id);
267
+ acknowledge();
268
+ }
269
+ }, [state.answerCloseCommit]);
270
+ useLayoutEffect(() => () => {
271
+ presentationMounted.current = false;
272
+ for (const acknowledge of answerCloseWaiters.current.values())
273
+ acknowledge();
274
+ answerCloseWaiters.current.clear();
275
+ unmountBarrier.current?.resolve();
276
+ }, []);
277
+ const prepareAnswerClose = useCallback(() => {
278
+ if (!presentationMounted.current)
279
+ return Promise.resolve();
280
+ const id = answerCloseSequence.current + 1;
281
+ answerCloseSequence.current = id;
282
+ return new Promise((acknowledge) => {
283
+ answerCloseWaiters.current.set(id, acknowledge);
284
+ dispatch({ type: 'prepareAnswerClose', id });
285
+ });
286
+ }, [dispatch]);
287
+ const pendingPermission = useSyncExternalStore((onChange) => permissions.subscribe(onChange), permissions.getSnapshot, permissions.getSnapshot);
288
+ // A pending confirmation outranks streaming: the loop is blocked on it.
289
+ const effectiveStatus = pendingPermission !== undefined ? 'awaiting-permission' : status;
290
+ // Built-ins stay first, then project commands, then skills. Collision filtering
291
+ // happens in the command loader so every row here is actually invokable. Both
292
+ // candidate sources share one query identity so Escape can suppress only this
293
+ // generation without mutating the editor.
294
+ const completionState = promptCompletionState(editor, commandNames, workspacePaths);
295
+ const pathQuery = completionState.pathQuery;
296
+ // Scan bookkeeping lives in a ref so a finished scan cannot re-trigger the effect
297
+ // that started it. Keyed on the project root: `/clear` hands over a new runtime
298
+ // for the same tree, and re-reading it for that would be work for nothing.
299
+ const pathScan = useRef({ root: '', scannedAt: 0, inFlight: false });
300
+ const pathMenuOpen = pathQuery !== undefined;
301
+ const pathQueryText = pathQuery?.text;
302
+ // Nothing here is awaited by a keystroke: the editor renders from whatever the last
303
+ // scan produced (nothing, on the first `@`) and re-renders when one lands. Started
304
+ // by the first trigger rather than at startup, so a session that never mentions a
305
+ // path never walks the tree at all.
306
+ useEffect(() => {
307
+ if (!pathMenuOpen)
308
+ return;
309
+ const root = runtime.info.projectRoot;
310
+ const state = pathScan.current;
311
+ if (state.inFlight)
312
+ return;
313
+ if (state.root === root && Date.now() - state.scannedAt < PATH_SCAN_TTL_MS)
314
+ return;
315
+ state.root = root;
316
+ state.inFlight = true;
317
+ // Deliberately not cancelled when the query closes: the reading describes the
318
+ // tree, not the query, so keeping it is what makes the *next* `@` instant. A
319
+ // discarded result would also have to un-stamp `scannedAt`, or a query abandoned
320
+ // mid-scan would leave the menu empty for the whole TTL.
321
+ void scanWorkspacePaths(root)
322
+ .then(setWorkspacePaths)
323
+ .finally(() => {
324
+ state.inFlight = false;
325
+ state.scannedAt = Date.now();
326
+ });
327
+ }, [pathMenuOpen, runtime]);
328
+ // Prompt recall. `undefined` history means "not read yet", which is a different
329
+ // answer from an empty reading and is stated as such on the indicator row: claiming
330
+ // a project has no earlier prompts before its record has been opened would be a lie
331
+ // in the one row the user is reading.
332
+ const [history, setHistory] = useState(undefined);
333
+ const [recall, setRecallState] = useState(undefined);
334
+ // Same immediate-mirror reason as `editorRef`: several stdin events can be batched
335
+ // into one React pass, and two Up presses in that pass must walk two entries.
336
+ const recallRef = useRef(recall);
337
+ const setRecall = useCallback((next) => {
338
+ recallRef.current = next;
339
+ setRecallState(next);
340
+ }, []);
341
+ // Reverse search is an editor-local mode over the same bounded project reader.
342
+ // Its immediate mirror makes batched query/navigation/accept keys observe one
343
+ // generation, just like editor, completion and sequential recall state above.
344
+ const [historySearch, setHistorySearchState] = useState(undefined);
345
+ const historySearchRef = useRef(historySearch);
346
+ const setHistorySearch = useCallback((next) => {
347
+ historySearchRef.current = next;
348
+ setHistorySearchState(next);
349
+ }, []);
350
+ const updateHistorySearch = useCallback((update) => {
351
+ const current = historySearchRef.current;
352
+ if (current !== undefined)
353
+ setHistorySearch(update(current));
354
+ }, [setHistorySearch]);
355
+ // `/rewind` owns the same bounded search rows as Ctrl+R, but its entries carry
356
+ // SDK snapshot identities and acceptance replaces the runtime rather than only text.
357
+ const [rewindSearch, setRewindSearchState] = useState(undefined);
358
+ const rewindSearchRef = useRef(rewindSearch);
359
+ const setRewindSearch = useCallback((next) => {
360
+ rewindSearchRef.current = next;
361
+ setRewindSearchState(next);
362
+ }, []);
363
+ const updateRewindSearch = useCallback((update) => {
364
+ const current = rewindSearchRef.current;
365
+ if (current !== undefined)
366
+ setRewindSearch(update(current));
367
+ }, [setRewindSearch]);
368
+ // The one way the chooser opens — `/rewind` and the Esc Esc chord (SER-059)
369
+ // both call it, so they cannot drift. Opening is local/read-only: the catalogue
370
+ // listing is the only runtime accessor, no snapshot is created, nothing is sent.
371
+ // Resolves `true` only when the chooser is actually up; every refusal is one
372
+ // bounded notice and `false`.
373
+ const openRewindChooser = useCallback(async () => {
374
+ if (startRewind === undefined) {
375
+ dispatch({ type: 'notice', text: '/rewind is not available in this driver', severity: 'warn' });
376
+ return false;
377
+ }
378
+ const catalogue = await runtime.listRewindCheckpoints();
379
+ if (catalogue.problem !== undefined) {
380
+ dispatch({ type: 'notice', text: `rewind unavailable: ${catalogue.problem}`, severity: 'warn' });
381
+ return false;
382
+ }
383
+ if (catalogue.checkpoints.length === 0) {
384
+ dispatch({
385
+ type: 'notice',
386
+ text: runtime.info.resumed
387
+ ? 'rewind unavailable — this resumed session has no catalogued completed prompt boundary; unmapped historical SDK snapshots are not guessed'
388
+ : 'rewind unavailable — no completed prompt checkpoint is catalogued yet',
389
+ severity: 'warn',
390
+ });
391
+ return false;
392
+ }
393
+ if (catalogue.captureCapacityReached) {
394
+ dispatch({
395
+ type: 'notice',
396
+ text: 'rewind checkpoint capacity reached — existing completed boundaries remain available; later turns are not added',
397
+ severity: 'warn',
398
+ });
399
+ }
400
+ const opening = editorRef.current;
401
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
402
+ setRecall(undefined);
403
+ setHistorySearch(undefined);
404
+ setRewindSearch(openRewindSearch(opening, runtime.info.sessionId, catalogue.checkpoints));
405
+ return true;
406
+ }, [dispatch, runtime, setEditor, setHistorySearch, setRecall, setRewindSearch, startRewind]);
407
+ // When the first no-op Escape landed on an empty idle composer; a second one
408
+ // within ESCAPE_REWIND_CHORD_MS opens the chooser. Cleared by any other key or
409
+ // owner, so the chord can never straddle a draft, a turn or a menu.
410
+ const escapeArmedAt = useRef(undefined);
411
+ const historySearchRequest = useRef(0);
412
+ // Read bookkeeping, in a ref for the same reason the path scan's is: a landed read
413
+ // must not re-trigger the thing that started it. `stale` is set when a turn ends —
414
+ // that is when the turn's own `userInput` line reaches the file (one append per turn),
415
+ // so the next Up re-reads instead of offering a history that stops one prompt short.
416
+ const historyRead = useRef({ root: '', inFlight: false, stale: true, promise: undefined });
417
+ const requestHistory = useCallback(() => {
418
+ const root = runtime.info.projectRoot;
419
+ const state = historyRead.current;
420
+ if (state.inFlight)
421
+ return state.promise;
422
+ if (state.root === root && !state.stale)
423
+ return undefined;
424
+ state.root = root;
425
+ state.inFlight = true;
426
+ state.stale = false;
427
+ // Never awaited by a keystroke, exactly like the workspace scan: the editor renders
428
+ // from whatever the last reading produced (nothing, on the very first Up) and
429
+ // re-renders when one lands. `readPromptHistory` cannot reject.
430
+ const promise = readPromptHistory(root);
431
+ state.promise = promise;
432
+ void promise
433
+ .then(setHistory)
434
+ .finally(() => {
435
+ if (state.promise === promise) {
436
+ state.inFlight = false;
437
+ state.promise = undefined;
438
+ }
439
+ });
440
+ return promise;
441
+ }, [runtime]);
442
+ const completionKind = completionState.kind;
443
+ const completions = visiblePromptCompletions(completionState, dismissedCompletion);
444
+ const completionNote = completionKind === 'path' && completions.length > 0 ? workspacePathsNote(workspacePaths) : undefined;
445
+ // One row while a walk is open, composed where the walk lives so the budget below and
446
+ // the box that draws it are counting the same thing.
447
+ const recallIndicator = recall === undefined || historySearch !== undefined || rewindSearch !== undefined
448
+ ? undefined
449
+ : promptRecallIndicator(recall);
450
+ const historySearchProjection = historySearch === undefined
451
+ ? undefined
452
+ : promptHistorySearchView(historySearch);
453
+ const rewindSearchProjection = rewindSearch === undefined
454
+ ? undefined
455
+ : rewindSearchView(rewindSearch);
456
+ // Every participant of the redrawn frame states what it wants; the header is the
457
+ // only one measured. The grants are what each box is then allowed to draw, and
458
+ // `frame-budget.ts` owns the priority between them (prompt, tools, answer) as
459
+ // well as the share ceiling that stops the first from taking everything.
460
+ //
461
+ // The busy rows' live readout, recomputed on every spinner tick below: elapsed
462
+ // wall clock from the turn's start ref, spend from `runtime.usage` — a synchronous
463
+ // in-memory read of the SDK's accumulator, which counts a model call when it
464
+ // finishes (the same reading mid-turn `/usage` reports as "not counted yet").
465
+ // No second interval, no I/O, and nothing of it while idle or compacting. A pending
466
+ // model-retry wait (`runtime.retryWait()`, SER-067) rides the same read as one more
467
+ // phrase on the same rows — never a row of its own.
468
+ const busyElapsedMs = effectiveStatus === 'streaming' && turnStartedAt.current !== undefined
469
+ ? Date.now() - turnStartedAt.current
470
+ : undefined;
471
+ const busyRetryWait = busyElapsedMs === undefined ? undefined : liveRetryWait(runtime);
472
+ const streamingHint = hintForStatus(effectiveStatus, busyElapsedMs === undefined ? undefined : busySuffix(busyElapsedMs, liveSpend(runtime), busyRetryWait), queued.length);
473
+ const activeToolClaims = state.activeTools.map((tool) => ({
474
+ detailRows: toolDetailsVisible(tool.name, state.toolDetailsExpanded)
475
+ ? toolInputRows(tool.input, columns, tool.name).length
476
+ : 0,
477
+ }));
478
+ const offeredCompletions = Math.min(completions.length, MAX_COMPLETIONS);
479
+ const liveTextRows = state.liveText === '' ? 0 : wrapToRows(state.liveText, columns).length;
480
+ const thinkingRows = state.thinking && effectiveStatus === 'streaming' ? 1 : 0;
481
+ const grants = frameBudget({
482
+ rows,
483
+ headerRows: header.hasMeasured ? header.height : ASSUMED_HEADER_ROWS,
484
+ thinkingRows,
485
+ prompt: pendingPermission === undefined
486
+ ? {
487
+ wanted: promptBoxWanted({
488
+ draftRows: layout.rows.length,
489
+ completions: offeredCompletions,
490
+ moreCompletions: completions.length > offeredCompletions,
491
+ hasHint: streamingHint !== undefined,
492
+ hasAttachment: attachedImage !== undefined,
493
+ hasRecall: recallIndicator !== undefined,
494
+ ...((rewindSearchProjection ?? historySearchProjection) === undefined ? {} : {
495
+ searchMatches: (rewindSearchProjection ?? historySearchProjection)?.matches.length ?? 0,
496
+ moreSearchMatches: ((rewindSearchProjection ?? historySearchProjection)?.hiddenAbove ?? 0) +
497
+ ((rewindSearchProjection ?? historySearchProjection)?.hiddenBelow ?? 0) > 0,
498
+ }),
499
+ }),
500
+ // The row the cursor is on. Everything else in the region can go.
501
+ floor: 1,
502
+ }
503
+ : {
504
+ wanted: permissionBoxClaim(pendingPermission, permissions.waiting, columns),
505
+ // The box keeps its heading, summary and decision row while it can:
506
+ // a question that scrolled off the frame blocks the agent loop.
507
+ floor: PERMISSION_BOX_FIXED_ROWS,
508
+ // And it is never asked to share with the call it is asking about: it
509
+ // is modal, so those rows are not what the answer or the spinner need.
510
+ modal: true,
511
+ },
512
+ tools: {
513
+ wanted: toolPanelWanted(activeToolClaims),
514
+ floor: activeToolClaims.length > 0 ? 1 : 0,
515
+ },
516
+ plan: {
517
+ wanted: state.livePlan.length === 0 ? 0 : state.livePlan.length + 1,
518
+ // One row still names the checklist and states its full item count.
519
+ floor: state.livePlan.length === 0 ? 0 : 1,
520
+ },
521
+ // The queued listing (SER-027): one row per entry, cut entries stated by the
522
+ // queue's own notice row. Floor 0 — the busy hint's count keeps a fully cut
523
+ // listing from going invisible.
524
+ queued: { wanted: queueListWanted(queued.length), floor: 0 },
525
+ // The answer yields first: it is the one participant whose content is already
526
+ // guaranteed to reach `<Static>` history in full.
527
+ live: { wanted: liveTextRows === 0 ? 0 : liveTextRows + LIVE_BLOCK_CHROME_ROWS, floor: 0 },
528
+ });
529
+ // Spinner tick, while a model is actually streaming or a `!` command is running —
530
+ // the running command's panel row carries the same spinner and elapsed suffix.
531
+ // `/compact` waits on its own model calls too, but has no per-call tool panel to
532
+ // animate.
533
+ useEffect(() => {
534
+ if (effectiveStatus !== 'streaming' && effectiveStatus !== 'shell')
535
+ return;
536
+ const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS);
537
+ return () => clearInterval(timer);
538
+ }, [effectiveStatus]);
539
+ // A `!` command must not outlive the TUI that ran it: on unmount (Ctrl+D, /exit,
540
+ // a second Ctrl+C) the group gets the same TERM→KILL reaping a cancel gives it.
541
+ useEffect(() => () => shellRun.current?.kill(), []);
542
+ // The SDK's default logger writes to the console, which tears this frame. It has
543
+ // something to say now that `/model` exists: switching away from Claude with a
544
+ // reasoning block in the history makes the OpenAI adapter warn, once per
545
+ // request, that it is dropping it. Surfaced as a notice instead of swallowed —
546
+ // the model is losing part of its own history and that is worth one line.
547
+ useEffect(() => routeSdkLogs((entry) => dispatch({ type: 'notice', text: `sdk ${entry.level}: ${entry.message}`, severity: entry.level })), [dispatch]);
548
+ // Where the diagnostics went, said once, in the transcript. A frame row is not an
549
+ // option — the header shares its height with the permission box and the tool panel,
550
+ // which is the contract `spike/verify-tui.ts approve` enforces on a 50-row terminal —
551
+ // and a file nobody can find is a file nobody reads. Only when the run asked for it.
552
+ useEffect(() => {
553
+ const file = runtime.info.diagnosticsFile;
554
+ if (file === undefined)
555
+ return;
556
+ dispatch({ type: 'notice', text: `diagnostics: recording SDK debug/info to ${file}` });
557
+ }, [dispatch, runtime]);
558
+ // Terminal task events are transcript-only observers: they never alter turn
559
+ // status, active tools, permissions, or the agent loop. React dispatch also
560
+ // causes an immediate idle render; cleanup prevents shutdown notices after exit.
561
+ useEffect(() => runtime.subscribeToBackgroundTasks((task) => {
562
+ dispatch({ type: 'notice', text: formatTaskCompletion(task) });
563
+ }), [runtime]);
564
+ // Same observer-only contract for finished delegations: a notice, never a status
565
+ // change. Concurrent children finish in an order nobody scripted, so a dispatch
566
+ // that ends mid-turn (or while a prompt is up) has to be able to say so without
567
+ // touching the live frame's ownership.
568
+ useEffect(() => runtime.subscribeToSubagentDispatches((dispatched) => {
569
+ dispatch({ type: 'notice', text: formatDispatchCompletion(dispatched) });
570
+ }), [runtime]);
571
+ // Safe phase changes and periodic heartbeats update only the existing live tool
572
+ // row. They never append transcript history or enter the model/trajectory.
573
+ useEffect(() => runtime.subscribeToSubagentProgress((progress) => {
574
+ dispatch({ type: 'subagentProgress', progress });
575
+ }), [runtime]);
576
+ /**
577
+ * Puts every queued entry back into the editor, unsent — ahead of any typed
578
+ * text, one per line, cursor at the end — and says so. The take-back gesture
579
+ * and the post-abort return share this so "what a cancel does to the queue"
580
+ * and "what `Up` does to the queue" cannot drift apart; `withNotice` is the
581
+ * only difference (the gesture explains itself).
582
+ */
583
+ const returnQueuedToEditor = useCallback((withNotice) => {
584
+ const entries = queuedRef.current;
585
+ if (entries.length === 0)
586
+ return false;
587
+ const text = takeBackDraft(entries, editorRef.current.text);
588
+ const returnedImage = entries.find((entry) => entry.image !== undefined)?.image;
589
+ setQueued([]);
590
+ if (returnedImage !== undefined)
591
+ setAttachedImage(returnedImage);
592
+ // The queue's entries replace the draft wholesale; the drafts destroyed by
593
+ // earlier chords are no longer what Ctrl+_ should bring back.
594
+ undoStack.current = [];
595
+ setEditor({ text, cursor: { offset: text.length, affinity: 'upstream' } });
596
+ preferredColumn.current = undefined;
597
+ setSelectedCompletion(0);
598
+ if (withNotice) {
599
+ dispatch({
600
+ type: 'notice',
601
+ text: `${entries.length} queued ${entries.length === 1 ? 'message' : 'messages'} returned to the editor, not sent`,
602
+ });
603
+ }
604
+ return true;
605
+ }, [dispatch, setAttachedImage, setEditor, setQueued]);
606
+ const runTurn = useCallback(async (text, userInput = text, image) => {
607
+ turnStartedAt.current = Date.now();
608
+ turnAborted.current = false;
609
+ let lifecycleOutcome = 'success';
610
+ setStatus('streaming');
611
+ try {
612
+ await runWithStreamResumption(text, async (turnInput) => {
613
+ let answerTailLive = false;
614
+ for await (const event of runtime.send(turnInput, userInput, turnInput === text ? image : undefined)) {
615
+ if (event.type === 'modelStreamUpdateEvent' &&
616
+ event.event.type === 'modelContentBlockDeltaEvent' &&
617
+ event.event.delta.type === 'textDelta' &&
618
+ event.event.delta.text !== '') {
619
+ answerTailLive = true;
620
+ }
621
+ if (answerTailLive &&
622
+ event.type === 'contentBlockEvent' &&
623
+ event.contentBlock.type === 'textBlock') {
624
+ // A text block closes the mutable answer tail into `<Static>`. If
625
+ // both changes share one Ink render, a terminal may scroll the old
626
+ // live rows out of the erasable frame before Static writes the same
627
+ // text, leaving a visible duplicate. Commit an answer-free frame
628
+ // first; the authoritative event still follows through the ordinary
629
+ // reducer path, in order, and no text/event is suppressed.
630
+ const unmounted = unmountBarrier.current?.promise ?? Promise.resolve();
631
+ await Promise.race([prepareAnswerClose(), unmounted]);
632
+ if (presentationMounted.current) {
633
+ await Promise.race([waitUntilRenderFlush(), unmounted]);
634
+ }
635
+ }
636
+ dispatch({ type: 'streamEvent', event });
637
+ if (event.type === 'contentBlockEvent' && event.contentBlock.type === 'textBlock') {
638
+ answerTailLive = false;
639
+ }
640
+ // The SDK ends a refused turn normally, so the transcript would show an
641
+ // empty (or cut-short) answer with no reason. Name it once, as a notice.
642
+ if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason)) {
643
+ dispatch({ type: 'notice', text: REFUSAL_NOTICE, severity: 'warn' });
644
+ }
645
+ }
646
+ }, (error) => {
647
+ // The failed attempt is a complete transcript/trajectory fact before the
648
+ // next ordinary turn starts. Keep the busy owner and queued work intact.
649
+ dispatch({ type: 'turnEnded' });
650
+ dispatch({
651
+ type: 'notice',
652
+ text: `turn failed: ${error.message}`,
653
+ severity: 'error',
654
+ });
655
+ dispatch({ type: 'notice', text: STREAM_CONTINUATION_NOTICE, severity: 'warn' });
656
+ });
657
+ await runtime.markResumable();
658
+ }
659
+ catch (error) {
660
+ // A failed turn must not kill the session; the user may want to retry.
661
+ // It also must not send the queue: auto-resending into an error is how
662
+ // retry loops start, so the queue is returned to the editor below.
663
+ lifecycleOutcome = turnAborted.current ? 'cancelled' : 'failure';
664
+ turnAborted.current = true;
665
+ // A throttled turn names how retry ended — the cap (`after N attempts`) or a
666
+ // wait Esc cut short — from the runtime's own outcome, never the message text.
667
+ dispatch({
668
+ type: 'notice',
669
+ text: retryFailureNotice(lastRetryOutcome(runtime), contextOverflowErrorMessage(error)),
670
+ severity: 'error',
671
+ });
672
+ }
673
+ finally {
674
+ if (turnAborted.current && lifecycleOutcome === 'success')
675
+ lifecycleOutcome = 'cancelled';
676
+ runtime.observeTurnComplete(lifecycleOutcome, 'interactive');
677
+ // The attention bell shares the TurnComplete publication moment exactly:
678
+ // one raw BEL to stdout per finished turn (any outcome), interactive only,
679
+ // and a no-op unless `terminalBell` is configured on.
680
+ ringTerminalBell(runtime.config.terminalBell === true);
681
+ dispatch({ type: 'turnEnded' });
682
+ setStatus('idle');
683
+ // Cleared with the status, so a cancelled or failed turn stops the busy
684
+ // readout in the same breath as the tick that was redrawing it.
685
+ turnStartedAt.current = undefined;
686
+ interruptedAt.current = undefined;
687
+ // The turn's own `userInput` line reaches the record when the turn closes (one
688
+ // append per turn), so this is the moment the reading in memory is one prompt
689
+ // short. Marked, never re-read here: the next `Up` pays for it, and a session
690
+ // that never recalls never opens the file at all.
691
+ historyRead.current.stale = true;
692
+ }
693
+ // A cancelled or failed turn never silently sends the queue (SER-027): what
694
+ // was queued behind it comes back to the editor, visible and unsent, and the
695
+ // drain effect below finds nothing to send.
696
+ const failed = turnAborted.current;
697
+ if (failed) {
698
+ turnAborted.current = false;
699
+ returnQueuedToEditor(true);
700
+ }
701
+ // Post-turn context-pressure check: reuse the configurable warning latch
702
+ // and existing Static transcript notice — no second threshold or live row.
703
+ // Compaction remains an explicit user command. A failed estimate is silently
704
+ // dropped so this advisory path cannot mask the completed turn above it.
705
+ try {
706
+ const estimate = await runtime.contextEstimate();
707
+ const notice = contextWarnLatch.current.check(estimate, runtime.config.contextWarnRatio);
708
+ if (notice !== null)
709
+ dispatch({ type: 'notice', text: notice, severity: 'warn' });
710
+ }
711
+ catch {
712
+ // best-effort
713
+ }
714
+ // Same shape for the trajectory: read after the turn, never during it, and at
715
+ // most once per session. The recorder latches its first failure, so this says
716
+ // "the record stopped here" exactly when that is news — a session that keeps
717
+ // working with a short record must not do so silently.
718
+ const trajectoryProblem = runtime.trajectoryStatus?.problem;
719
+ if (trajectoryProblem !== undefined && !trajectoryWarned.current) {
720
+ trajectoryWarned.current = true;
721
+ dispatch({
722
+ type: 'notice',
723
+ text: `trajectory: ${trajectoryProblem}`,
724
+ // The session is unaffected, so this is a degradation, not a failure.
725
+ severity: 'warn',
726
+ });
727
+ }
728
+ // And the same for the diagnostics log, on the same terms: it latched, the turn
729
+ // did not notice, and the user has to be told once that the file they are tailing
730
+ // stopped growing — including when it stopped because it filled its budget.
731
+ const diagnosticsProblem = runtime.diagnosticsStatus?.problem;
732
+ if (diagnosticsProblem !== undefined && !diagnosticsWarned.current) {
733
+ diagnosticsWarned.current = true;
734
+ dispatch({ type: 'notice', text: `diagnostics: ${diagnosticsProblem}`, severity: 'warn' });
735
+ }
736
+ const memoryProblem = runtime.memoryStatus?.problem;
737
+ if (memoryProblem !== undefined && !memoryWarned.current) {
738
+ memoryWarned.current = true;
739
+ dispatch({ type: 'notice', text: `learned memory: ${memoryProblem}`, severity: 'warn' });
740
+ }
741
+ for (const problem of runtime.takeHookProblems()) {
742
+ dispatch({ type: 'notice', text: `hook: ${problem}`, severity: 'warn' });
743
+ }
744
+ return !failed;
745
+ }, [prepareAnswerClose, returnQueuedToEditor, runtime, waitUntilRenderFlush]);
746
+ const submit = useCallback(async (raw, queuedEntry) => {
747
+ const text = raw.trim();
748
+ // A drained entry owns its optional image, including explicit absence. It
749
+ // must never borrow a newer attachment still sitting beside the editor.
750
+ const image = queuedEntry === undefined ? attachedImageRef.current : queuedEntry.image;
751
+ if (text === '')
752
+ return;
753
+ // A submission ends the draft's life in the editor (accepted, queued, or
754
+ // expanded into a local command). Conservative on the few busy refusals
755
+ // that retain the draft: clearing there only loses undo history — the
756
+ // failure mode this guards against is resurrecting a sent prompt.
757
+ undoStack.current = [];
758
+ // A bounded pure projection of canonical commands and fixed input controls.
759
+ // It owns every whitespace-separated /help form before the busy guard, so an
760
+ // argument is rejected locally and a valid report remains available while a
761
+ // turn or user `!` command is running. No runtime accessor, tool, or I/O is
762
+ // involved; the existing transcript notice is its only output surface.
763
+ if (/^\/help(?:\s|$)/.test(text)) {
764
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
765
+ setSelectedCompletion(0);
766
+ dispatch({ type: 'userInput', text });
767
+ dispatch({
768
+ type: 'notice',
769
+ text: text === '/help' ? formatHelpReport() : '/help takes no arguments',
770
+ });
771
+ return;
772
+ }
773
+ // SER-057: the last *completed* answer's transcript text onto the clipboard —
774
+ // OSC 52 through Ink's own stdout writer first (this is usually an SSH session),
775
+ // the platform tool only when a display is present. Before the busy guard like
776
+ // /help, so mid-turn it copies the previous answer while the current one streams.
777
+ // Reads history only: no runtime accessor, model, tool, record or file.
778
+ if (/^\/copy(?:\s|$)/.test(text)) {
779
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
780
+ setSelectedCompletion(0);
781
+ dispatch({ type: 'userInput', text });
782
+ if (text !== '/copy') {
783
+ dispatch({ type: 'notice', text: COPY_COMMAND_USAGE });
784
+ return;
785
+ }
786
+ const copied = await runCopyCommand({ history: historyRef.current, writeToTerminal });
787
+ dispatch({ type: 'notice', text: copied.text, severity: copied.severity });
788
+ return;
789
+ }
790
+ // Answered from the SDK's meter, never sent to the model: a report on token
791
+ // spend that costs a turn of its own would be self-defeating. Handled before
792
+ // the busy check, so it also answers mid-turn — a long turn is exactly when
793
+ // the question comes up, and reading a counter cannot disturb one.
794
+ if (text === '/usage') {
795
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
796
+ setSelectedCompletion(0);
797
+ dispatch({ type: 'userInput', text });
798
+ dispatch({
799
+ type: 'notice',
800
+ text: formatUsageReport(runtime.usage, runtime.config, runtime.info.resumed, status === 'streaming', runtime.lastTurnUsage, runtime.childUsage, runtime.callStats, runtime.modelShares),
801
+ });
802
+ return;
803
+ }
804
+ // Also before the busy check, and for a stronger reason than /usage: a turn
805
+ // makes many model calls, so "think harder" is worth acting on while one is
806
+ // running — the level applies from the next call on. It reconfigures the live
807
+ // model rather than sending anything, so it cannot disturb the turn.
808
+ if (text === '/effort' || text.startsWith('/effort ')) {
809
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
810
+ setSelectedCompletion(0);
811
+ dispatch({ type: 'userInput', text });
812
+ applyEffortCommand(runtime, text, dispatch);
813
+ return;
814
+ }
815
+ // Before the busy check for the strongest reason of all: mid-turn is exactly
816
+ // when the enforcement policy needs changing — the model is about to write
817
+ // something that should have been planned first, or the user has stopped
818
+ // wanting to confirm every call. It sends nothing and rebuilds nothing: the
819
+ // gate takes the new mode for its next decision and withdraws any decision
820
+ // still pending, so no call is judged half by one mode and half by another.
821
+ if (text === '/mode' || text.startsWith('/mode ')) {
822
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
823
+ setSelectedCompletion(0);
824
+ dispatch({ type: 'userInput', text });
825
+ applyModeCommand(runtime, text, dispatch);
826
+ return;
827
+ }
828
+ // Before the busy check for the same reason as /mode: revocation only ever
829
+ // *narrows* what runs silently, and mid-turn is exactly when a rule that
830
+ // turned out too broad needs pulling — the gate stops honouring it before
831
+ // this handler returns, so the very next matching call prompts. User-only
832
+ // like /mode: this never reaches the agent, and there is no tool that can
833
+ // invoke it. Additions have no path through here; they stay exclusively
834
+ // with the permission-prompt grant flow.
835
+ if (text === '/permissions' || text.startsWith('/permissions ')) {
836
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
837
+ setSelectedCompletion(0);
838
+ dispatch({ type: 'userInput', text });
839
+ applyPermissionsCommand(runtime, text, dispatch);
840
+ return;
841
+ }
842
+ // User-only local memory management. Like permission revocation, forgetting
843
+ // narrows future context synchronously; remember is an explicit typed command,
844
+ // never a model tool. Keep it idle-only so a running request cannot race a
845
+ // system-prompt replacement.
846
+ if (/^\/memory(?:\s|$)/.test(text)) {
847
+ if (status !== 'idle') {
848
+ dispatch({ type: 'notice', text: '/memory does not queue — run it after current work finishes' });
849
+ return;
850
+ }
851
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
852
+ setSelectedCompletion(0);
853
+ dispatch({ type: 'userInput', text });
854
+ try {
855
+ const result = await runtime.manageMemory(text);
856
+ dispatch({ type: 'notice', text: result.text });
857
+ }
858
+ catch (error) {
859
+ dispatch({
860
+ type: 'notice',
861
+ text: `memory command failed: ${error instanceof Error ? error.message : String(error)}`,
862
+ severity: 'warn',
863
+ });
864
+ }
865
+ return;
866
+ }
867
+ // Reads the manager directly rather than entering the model/tool loop. Like
868
+ // /usage it remains available mid-turn and cannot queue or cancel work. The
869
+ // output tails come from the logs themselves, never through the manager's
870
+ // cursor, so a glance here cannot move the model's `output`/`wait` offsets;
871
+ // every tail settles before the one notice is composed.
872
+ if (/^\/tasks(?:\s|$)/.test(text)) {
873
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
874
+ setSelectedCompletion(0);
875
+ dispatch({ type: 'userInput', text });
876
+ if (text !== '/tasks') {
877
+ dispatch({ type: 'notice', text: '/tasks takes no arguments' });
878
+ return;
879
+ }
880
+ try {
881
+ const tasks = await runtime.listBackgroundTasks();
882
+ const tails = await readBackgroundTails(tasks);
883
+ dispatch({ type: 'notice', text: formatTasksReport(tasks, Date.now(), tails) });
884
+ }
885
+ catch (error) {
886
+ dispatch({
887
+ type: 'notice',
888
+ text: `could not list background tasks: ${error instanceof Error ? error.message : String(error)}`,
889
+ });
890
+ }
891
+ return;
892
+ }
893
+ // Reads or narrows the dispatch registry directly: no model call/tool event,
894
+ // and deliberately above busy queueing because mid-turn is when a specific
895
+ // long-running child must be stopped. Cancellation is user-only; no agent
896
+ // tool reaches this runtime method.
897
+ if (/^\/agents(?:\s|$)/.test(text)) {
898
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
899
+ setSelectedCompletion(0);
900
+ dispatch({ type: 'userInput', text });
901
+ if (text === '/agents') {
902
+ dispatch({ type: 'notice', text: formatDispatchesReport(runtime.listSubagentDispatches()) });
903
+ return;
904
+ }
905
+ const match = /^\/agents\s+cancel\s+([a-zA-Z0-9]{1,8})$/.exec(text);
906
+ if (match === null) {
907
+ dispatch({ type: 'notice', text: 'usage: /agents cancel <dispatch-id>' });
908
+ return;
909
+ }
910
+ const dispatchId = match[1];
911
+ dispatch({
912
+ type: 'notice',
913
+ text: formatDispatchCancellation(dispatchId, runtime.cancelSubagentDispatch(dispatchId)),
914
+ });
915
+ return;
916
+ }
917
+ // Free like /usage: the count is the SDK's character heuristic, so asking
918
+ // costs nothing, sends nothing, and can be answered mid-turn — the moment
919
+ // a long turn makes "how big has this grown" worth asking.
920
+ if (/^\/context(?:\s|$)/.test(text)) {
921
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
922
+ setSelectedCompletion(0);
923
+ dispatch({ type: 'userInput', text });
924
+ if (text !== '/context') {
925
+ dispatch({ type: 'notice', text: '/context takes no arguments' });
926
+ return;
927
+ }
928
+ try {
929
+ dispatch({ type: 'notice', text: formatContextReport(await runtime.contextEstimate()) });
930
+ }
931
+ catch (error) {
932
+ dispatch({
933
+ type: 'notice',
934
+ text: `could not estimate context: ${error instanceof Error ? error.message : String(error)}`,
935
+ });
936
+ }
937
+ return;
938
+ }
939
+ // Reads the recorder's own counters — no file access, no model call — so it
940
+ // belongs with the other local reports above the busy check. Read-only by
941
+ // design: search, fork and replay work over *past* sessions and live on the
942
+ // `darwin trajectory` subcommand, where their output is not competing with a
943
+ // live frame for height.
944
+ if (/^\/trajectory(?:\s|$)/.test(text)) {
945
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
946
+ setSelectedCompletion(0);
947
+ dispatch({ type: 'userInput', text });
948
+ if (text !== '/trajectory') {
949
+ dispatch({ type: 'notice', text: '/trajectory takes no arguments' });
950
+ return;
951
+ }
952
+ dispatch({
953
+ type: 'notice',
954
+ text: formatTrajectoryReport(runtime.trajectoryStatus, runtime.info.sessionId),
955
+ severity: runtime.trajectoryStatus?.problem === undefined ? 'info' : 'warn',
956
+ });
957
+ return;
958
+ }
959
+ // Writes this session's transcript — the same `formatReplay` projection the
960
+ // `darwin trajectory replay` verb prints — to a file the user names. A pure
961
+ // *reader* over the record, so it belongs with the local reports above the
962
+ // busy check: reading mid-turn just sees the file one turn short, and the
963
+ // small local write is awaited because the notice *is* its result. Every
964
+ // outcome comes back as a notice; a failed export never costs the session.
965
+ if (/^\/export(?:\s|$)/.test(text)) {
966
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
967
+ setSelectedCompletion(0);
968
+ dispatch({ type: 'userInput', text });
969
+ const outcome = await exportTranscript({
970
+ argument: text.slice('/export'.length).trim(),
971
+ projectRoot: runtime.info.projectRoot,
972
+ sessionId: runtime.info.sessionId,
973
+ recordFile: runtime.trajectoryStatus?.file,
974
+ });
975
+ dispatch({ type: 'notice', text: outcome.text, severity: outcome.severity });
976
+ return;
977
+ }
978
+ // Reads the projection of the MCP clients the runtime already holds — no
979
+ // model call, and deliberately no connection attempt, so asking about a
980
+ // server cannot change its state. Available mid-turn like /tasks: a server
981
+ // that failed at startup contributed zero tools silently, and "where did my
982
+ // tools go" is asked exactly while the model is visibly not finding them.
983
+ if (/^\/mcp(?:\s|$)/.test(text)) {
984
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
985
+ setSelectedCompletion(0);
986
+ dispatch({ type: 'userInput', text });
987
+ if (text !== '/mcp') {
988
+ dispatch({ type: 'notice', text: '/mcp takes no arguments' });
989
+ return;
990
+ }
991
+ const candidates = mcpConfigCandidates(runtime.info.projectRoot);
992
+ dispatch({
993
+ type: 'notice',
994
+ text: formatMcpReport(runtime.listMcpServers(), {
995
+ configPaths: runtime.info.mcpConfigPaths,
996
+ overriddenServerNames: runtime.info.mcpOverriddenServerNames,
997
+ ignoredConfigPath: runtime.info.mcpIgnoredConfigPath,
998
+ candidatePaths: [candidates.global, candidates.preferred, candidates.fallback],
999
+ }),
1000
+ });
1001
+ return;
1002
+ }
1003
+ // One consolidated read of state the session already holds (SER-026), on the
1004
+ // /mcp precedent: a formatter over existing accessors, never a new information
1005
+ // channel — no model call, no connection attempt, no mutation. Above the busy
1006
+ // check because a scrolled-away header is the use case, and mid-turn is when
1007
+ // "what is this session actually configured as" gets asked.
1008
+ if (/^\/status(?:\s|$)/.test(text)) {
1009
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1010
+ setSelectedCompletion(0);
1011
+ dispatch({ type: 'userInput', text });
1012
+ if (text !== '/status') {
1013
+ dispatch({ type: 'notice', text: '/status takes no arguments' });
1014
+ return;
1015
+ }
1016
+ // The /context machinery, degraded rather than fatal: a failed estimate
1017
+ // costs one line of the report, never the report.
1018
+ let context;
1019
+ let contextProblem;
1020
+ try {
1021
+ context = await runtime.contextEstimate();
1022
+ }
1023
+ catch (error) {
1024
+ contextProblem = error instanceof Error ? error.message : String(error);
1025
+ }
1026
+ dispatch({
1027
+ type: 'notice',
1028
+ text: formatStatusReport({
1029
+ config: runtime.config,
1030
+ sessionId: runtime.info.sessionId,
1031
+ resumed: runtime.info.resumed,
1032
+ promptCache: runtime.promptCache,
1033
+ thinking: runtime.thinking,
1034
+ mode: runtime.permissionMode,
1035
+ allowRuleCount: runtime.allowRuleCount,
1036
+ mcpServers: runtime.listMcpServers(),
1037
+ skillNames: runtime.info.skillNames,
1038
+ trajectory: runtime.trajectoryStatus,
1039
+ diagnostics: runtime.diagnosticsStatus,
1040
+ usage: runtime.usage,
1041
+ modelPrice: runtime.modelPrice,
1042
+ modelShares: runtime.modelShares,
1043
+ childUsage: runtime.childUsage,
1044
+ callStats: runtime.callStats,
1045
+ turnInFlight: status === 'streaming',
1046
+ context,
1047
+ ...(contextProblem !== undefined && { contextProblem }),
1048
+ }),
1049
+ });
1050
+ return;
1051
+ }
1052
+ // Everything below needs the agent, and the SDK runs one turn at a time.
1053
+ // A submission while a turn streams or a `!` command runs is **queued**
1054
+ // (SER-027 — deliberately superseding SER-010's "retained, never queued"
1055
+ // contract, by explicit user product decision, 2026-08-19): it leaves the
1056
+ // editor, is listed above the input box, counted on the busy hint, and is
1057
+ // sent through this same path when the session returns to idle. Two
1058
+ // deliberate exceptions keep the old refusal shape:
1059
+ // - compaction owns the keyboard entirely, so this branch is a safety net;
1060
+ // - `/clear`, `/compact`, `/model`, `/exit` and `/quit` replace the session
1061
+ // or the process, and running one minutes later, unprompted, is worse
1062
+ // than asking for a second Enter — they refuse, draft retained.
1063
+ if (status !== 'idle') {
1064
+ if (status === 'compacting') {
1065
+ dispatch({ type: 'notice', text: 'still compacting — press enter again once it finishes' });
1066
+ return;
1067
+ }
1068
+ if (refusesToQueue(text)) {
1069
+ dispatch({
1070
+ type: 'notice',
1071
+ text: status === 'shell'
1072
+ ? `${text.split(/\s/, 1)[0]} does not queue — press enter again when the ! command finishes`
1073
+ : `${text.split(/\s/, 1)[0]} does not queue — press enter again once the turn ends`,
1074
+ });
1075
+ return;
1076
+ }
1077
+ // Nothing is dispatched and nothing is recorded here: a queued entry
1078
+ // becomes a `userInput` only at the moment it is actually sent, and one
1079
+ // taken back or dropped by /clear was never sent at all.
1080
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1081
+ setSelectedCompletion(0);
1082
+ const queuedAttachment = text.startsWith('!') ? undefined : image;
1083
+ setQueued([...queuedRef.current, {
1084
+ text,
1085
+ ...(queuedAttachment === undefined ? {} : { image: queuedAttachment }),
1086
+ }]);
1087
+ if (queuedAttachment !== undefined) {
1088
+ clipboardReadGeneration.current += 1;
1089
+ setAttachedImage(undefined);
1090
+ }
1091
+ return;
1092
+ }
1093
+ // A user-typed shell command (SER-024). Deliberately *below* the busy check —
1094
+ // submitted mid-turn it queues like a prompt (SER-027, the Claude Code shape:
1095
+ // shell commands are held until the turn ends and run one at a time), and a
1096
+ // drained `!` re-enters here at idle. And deliberately *not*
1097
+ // through the permission gate: the gate's subject is model tool calls, and a
1098
+ // user running their own command needs no approval from themselves — the
1099
+ // transcript row, the trajectory record and the held report are the honesty
1100
+ // this bargain costs. That reasoning covers plan mode too: plan constrains
1101
+ // the model's writes, not the user's hands.
1102
+ const shellCommand = parseShellCommand(text);
1103
+ if (shellCommand !== undefined) {
1104
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1105
+ setSelectedCompletion(0);
1106
+ if (shellCommand === '') {
1107
+ dispatch({ type: 'userInput', text });
1108
+ dispatch({ type: 'notice', text: '! runs a shell command: !<command>' });
1109
+ return;
1110
+ }
1111
+ // The normalized echo (`!` + trimmed command) is also what a replayed
1112
+ // `shellCommand` record prints, so live and replay show one user row.
1113
+ dispatch({ type: 'userInput', text: `!${shellCommand}` });
1114
+ shellRunCount.current += 1;
1115
+ const id = `shell-${shellRunCount.current}`;
1116
+ dispatch({ type: 'shellStarted', id, command: shellCommand });
1117
+ setStatus('shell');
1118
+ turnAborted.current = false;
1119
+ try {
1120
+ const run = runShellCommand(shellCommand, {
1121
+ cwd: runtime.info.projectRoot,
1122
+ onOutput: (tail) => dispatch({ type: 'shellOutput', id, tail }),
1123
+ });
1124
+ shellRun.current = run;
1125
+ const result = await run.done;
1126
+ const output = projectShellOutput(result.output);
1127
+ const outcome = {
1128
+ command: shellCommand,
1129
+ exitCode: result.exitCode,
1130
+ signal: result.signal,
1131
+ timedOut: result.timedOut,
1132
+ durationMs: result.durationMs,
1133
+ };
1134
+ // One bounded projection, three surfaces (PRD D4): the finished
1135
+ // transcript row, the trajectory record, and the report held for the
1136
+ // next prompt.
1137
+ dispatch({ type: 'shellCommand', ...outcome, output });
1138
+ runtime.recordShellCommand({ ...outcome, output });
1139
+ pendingShellReports.current.push(composeShellReport(outcome, output));
1140
+ }
1141
+ finally {
1142
+ // Whatever happened, the prompt is freed: a `!` command can time out or
1143
+ // be killed, but it cannot wedge the session.
1144
+ shellRun.current = undefined;
1145
+ setStatus('idle');
1146
+ interruptedAt.current = undefined;
1147
+ }
1148
+ // A user-cancelled `!` never silently sends the queue, exactly like a
1149
+ // cancelled turn (SER-027): what was queued behind it comes back to the
1150
+ // editor, visible and unsent. A timeout is not a cancel — the user asked
1151
+ // for nothing there, so the queue drains normally.
1152
+ if (turnAborted.current) {
1153
+ turnAborted.current = false;
1154
+ returnQueuedToEditor(true);
1155
+ }
1156
+ return;
1157
+ }
1158
+ if (text === '/exit' || text === '/quit') {
1159
+ exit();
1160
+ return;
1161
+ }
1162
+ // Deliberately *below* the busy check, with /compact and /model rather than with
1163
+ // Conversation-only branch selection. Opening is local/read-only; acceptance
1164
+ // revalidates the selected SDK checkpoint before runtime ownership changes.
1165
+ if (/^\/rewind(?:\s|$)/.test(text)) {
1166
+ setSelectedCompletion(0);
1167
+ dispatch({ type: 'userInput', text });
1168
+ // A refused open is a consumed command like any other local notice: the
1169
+ // draft is cleared so `/rewind` does not linger in front of the next prompt.
1170
+ // An opened chooser owns the editor itself (and restores it on Escape).
1171
+ if (text !== '/rewind') {
1172
+ dispatch({ type: 'notice', text: '/rewind takes no arguments' });
1173
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1174
+ return;
1175
+ }
1176
+ if (!(await openRewindChooser())) {
1177
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1178
+ }
1179
+ return;
1180
+ }
1181
+ // the local reports above it: this replaces the conversation the running turn is
1182
+ // streaming into, and the SDK's session snapshot is written when that turn ends —
1183
+ // so a mid-turn switch would hand the old session's manager a conversation it no
1184
+ // longer owns. `/clear` is idle-only, and the wording says why.
1185
+ if (/^\/clear(?:\s|$)/.test(text)) {
1186
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1187
+ setSelectedCompletion(0);
1188
+ dispatch({ type: 'userInput', text });
1189
+ if (text !== '/clear') {
1190
+ dispatch({ type: 'notice', text: '/clear takes no arguments' });
1191
+ return;
1192
+ }
1193
+ if (startNewSession === undefined) {
1194
+ dispatch({ type: 'notice', text: '/clear is not available in this driver', severity: 'warn' });
1195
+ return;
1196
+ }
1197
+ // The switch awaits an assembly (skills, tools, a new Agent), and `status` stays
1198
+ // idle throughout — so without this latch a second enter could start a second
1199
+ // successor and leak the first.
1200
+ if (clearing.current) {
1201
+ dispatch({ type: 'notice', text: 'still starting the new session — press enter again once it appears' });
1202
+ return;
1203
+ }
1204
+ clearing.current = true;
1205
+ const previousSessionId = runtime.info.sessionId;
1206
+ let next;
1207
+ try {
1208
+ next = await startNewSession();
1209
+ }
1210
+ catch (error) {
1211
+ // Nothing was released: the session that was live is still live.
1212
+ dispatch({
1213
+ type: 'notice',
1214
+ text: `could not start a new session; still in ${previousSessionId}: ${error instanceof Error ? error.message : String(error)}`,
1215
+ severity: 'error',
1216
+ });
1217
+ return;
1218
+ }
1219
+ finally {
1220
+ clearing.current = false;
1221
+ }
1222
+ // `<Static>` cannot be recalled, so a fresh screen means clearing the terminal —
1223
+ // once, here, not the per-render clear the live-frame budget exists to prevent.
1224
+ // Routed through Ink's own stdout writer so the frame is torn down and restored
1225
+ // around it, and paired with the reducer's `<Static>` remount, which is what
1226
+ // makes Ink drop the transcript it would otherwise replay on the next
1227
+ // whole-screen redraw.
1228
+ writeToTerminal(CLEAR_TERMINAL);
1229
+ dispatch({ type: 'clear' });
1230
+ setRuntime(next);
1231
+ // Per-session latches, reset with the session they were latched for.
1232
+ contextWarnLatch.current = createContextWarnLatch();
1233
+ trajectoryWarned.current = false;
1234
+ diagnosticsWarned.current = false;
1235
+ // Held `!` reports were destined for the conversation just set aside; the
1236
+ // successor starts empty, and the old session's record still has them.
1237
+ pendingShellReports.current = [];
1238
+ // The queue dies with the conversation it was typed at (SER-027): nothing
1239
+ // was sent, so nothing is recorded — the entries simply never existed.
1240
+ setQueued([]);
1241
+ clipboardReadGeneration.current += 1;
1242
+ setAttachedImage(undefined);
1243
+ // Mirrored to the *successor's* diagnostics log: the memoized `dispatch` still
1244
+ // points at the predecessor's, which this switch has just closed.
1245
+ withNoticeDiagnostics(recordAction, next.diagnostics)({
1246
+ type: 'notice',
1247
+ text: `cleared — new session ${next.info.sessionId}. Previous session ${previousSessionId} is saved and ` +
1248
+ `resumable (darwin --session ${previousSessionId}); background jobs and MCP servers keep running.`,
1249
+ });
1250
+ return;
1251
+ }
1252
+ if (text === '/compact' || text.startsWith('/compact ')) {
1253
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1254
+ setSelectedCompletion(0);
1255
+ dispatch({ type: 'userInput', text });
1256
+ // Optional focus: plain text the summarizer is told to keep, never a
1257
+ // sub-command. Over the cap is a local notice — no hook, no model call.
1258
+ const focus = normalizeCompactFocus(text.slice('/compact'.length));
1259
+ const refusal = compactFocusRefusal(focus);
1260
+ if (refusal !== undefined) {
1261
+ dispatch({ type: 'notice', text: refusal });
1262
+ return;
1263
+ }
1264
+ setStatus('compacting');
1265
+ try {
1266
+ const result = await runtime.compact(focus);
1267
+ dispatch({ type: 'notice', text: formatCompactReport(result) });
1268
+ }
1269
+ catch (error) {
1270
+ dispatch({
1271
+ type: 'notice',
1272
+ text: `compaction failed; conversation restored: ${error instanceof Error ? error.message : String(error)}`,
1273
+ severity: 'error',
1274
+ });
1275
+ }
1276
+ finally {
1277
+ setStatus('idle');
1278
+ }
1279
+ return;
1280
+ }
1281
+ // Deliberately *after* the busy check, unlike /effort: that only adjusts the
1282
+ // live model's config, while this replaces the model object outright, which
1283
+ // would change the model under a turn that is already streaming from it.
1284
+ if (text === '/model' || text.startsWith('/model ')) {
1285
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1286
+ setSelectedCompletion(0);
1287
+ dispatch({ type: 'userInput', text });
1288
+ await applyModelCommand(runtime, text, dispatch);
1289
+ return;
1290
+ }
1291
+ // Bare /workflow is the built-in's local usage notice, never a turn: the
1292
+ // runtime maps 'missing-task' to null, so without this it would fall
1293
+ // through as ordinary input and spend a model call. With a task it takes
1294
+ // the generic expansion path below like any other prompt command.
1295
+ if (parseWorkflowCommand(text) === 'missing-task') {
1296
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1297
+ setSelectedCompletion(0);
1298
+ dispatch({ type: 'userInput', text });
1299
+ dispatch({ type: 'notice', text: WORKFLOW_COMMAND_USAGE });
1300
+ return;
1301
+ }
1302
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1303
+ setSelectedCompletion(0);
1304
+ dispatch({ type: 'userInput', text });
1305
+ // Skills and project commands send their expanded prompt instead of the
1306
+ // literal command. Unknown slash input falls through as ordinary input.
1307
+ let toSend = text;
1308
+ try {
1309
+ const expanded = await runtime.expandSlashCommand(text);
1310
+ if (expanded !== null) {
1311
+ dispatch({
1312
+ type: 'notice',
1313
+ text: expanded.kind === 'skill'
1314
+ ? `loaded skill "${expanded.skill.name}"`
1315
+ : expanded.kind === 'workflow'
1316
+ ? 'delegating via the workflow tool'
1317
+ : `loaded command "/${expanded.command.name}"`,
1318
+ });
1319
+ toSend = expanded.message;
1320
+ }
1321
+ }
1322
+ catch (error) {
1323
+ dispatch({
1324
+ type: 'notice',
1325
+ text: `could not expand ${text}: ${error instanceof Error ? error.message : String(error)}`,
1326
+ severity: 'error',
1327
+ });
1328
+ }
1329
+ // Reports from `!` commands run since the last turn ride ahead of this
1330
+ // prompt (PRD D5): one string through the ordinary send path, so the
1331
+ // trajectory's `userInput` line stays exactly what the model received.
1332
+ const shellReports = pendingShellReports.current;
1333
+ if (shellReports.length > 0) {
1334
+ pendingShellReports.current = [];
1335
+ toSend = `${shellReports.join('\n\n')}\n\n${toSend}`;
1336
+ }
1337
+ // The invocation owns its image while streaming. Success consumes it; a
1338
+ // provider/model rejection restores the exact image + literal prompt so the
1339
+ // user can retry or remove without rereading the clipboard.
1340
+ if (image !== undefined)
1341
+ imageTurnInFlight.current = true;
1342
+ if (image !== undefined && queuedEntry === undefined) {
1343
+ clipboardReadGeneration.current += 1;
1344
+ setAttachedImage(undefined);
1345
+ }
1346
+ const completed = await runTurn(toSend, text, image);
1347
+ if (image !== undefined)
1348
+ imageTurnInFlight.current = false;
1349
+ if (!completed && image !== undefined) {
1350
+ const retryDraft = takeBackDraft([{ text }], editorRef.current.text);
1351
+ setEditor({ text: retryDraft, cursor: { offset: retryDraft.length, affinity: 'upstream' } });
1352
+ setAttachedImage(image);
1353
+ dispatch({
1354
+ type: 'notice',
1355
+ text: 'image prompt restored after the failed turn — retry or press Ctrl+O to remove the image',
1356
+ severity: 'warn',
1357
+ });
1358
+ }
1359
+ }, [dispatch, exit, openRewindChooser, recordAction, returnQueuedToEditor, runtime, runTurn, setAttachedImage, setEditor, setQueued, startNewSession, status, writeToTerminal]);
1360
+ // The drain (SER-027): when the session is idle and nothing owns the keyboard,
1361
+ // the oldest queued entry goes back through the ordinary submit path — its own
1362
+ // turn for a prompt, its own run for a `!`, its own `userInput` recorded at
1363
+ // this moment and not before. One entry at a time: `draining` latches while an
1364
+ // entry is in flight (submit awaits expansion before it flips `status`, and a
1365
+ // render in that window must not double-dequeue), and `drainCycle` re-arms the
1366
+ // effect after an entry — a local command, say — that left every other dep
1367
+ // unchanged. Never while a permission decision is pending (the queue is held
1368
+ // untouched under a prompt) and never while `/clear` is assembling a successor.
1369
+ useEffect(() => {
1370
+ if (draining.current || status !== 'idle' || pendingPermission !== undefined || clearing.current)
1371
+ return;
1372
+ const next = queuedRef.current[0];
1373
+ if (next === undefined)
1374
+ return;
1375
+ draining.current = true;
1376
+ setQueued(queuedRef.current.slice(1));
1377
+ void submit(next.text, next).finally(() => {
1378
+ draining.current = false;
1379
+ setDrainCycle((cycle) => cycle + 1);
1380
+ });
1381
+ }, [drainCycle, pendingPermission, queued, setQueued, status, submit]);
1382
+ /**
1383
+ * Answers the pending confirmation and, when the user picked an "always allow"
1384
+ * option, remembers the rule.
1385
+ *
1386
+ * The gate honours the rule from the decision alone, so the write to
1387
+ * `~/.darwin/config.json` is reported rather than awaited: a failed write means
1388
+ * "this session only", which the user has to be told, but it must not delay the
1389
+ * tool call they just approved.
1390
+ */
1391
+ const answerPermission = useCallback((decision) => {
1392
+ permissions.answer(decision);
1393
+ const rule = decision.rule;
1394
+ if (rule === undefined)
1395
+ return;
1396
+ runtime.saveAllowRule(rule).then(() => {
1397
+ dispatch({
1398
+ type: 'notice',
1399
+ text: `always allowing ${rule} — saved to ${runtime.info.permissionRulesPath}`,
1400
+ });
1401
+ }, (error) => {
1402
+ dispatch({
1403
+ type: 'notice',
1404
+ text: `always allowing ${rule} for this session only — could not write ` +
1405
+ `${runtime.info.permissionRulesPath}: ${error instanceof Error ? error.message : String(error)}`,
1406
+ // The rule still applies this session, so a degradation, not a failure.
1407
+ severity: 'warn',
1408
+ });
1409
+ });
1410
+ }, [permissions, runtime]);
1411
+ /** Any edit ends the walk: the draft is the user's again, not an entry from the record. */
1412
+ const endRecall = useCallback(() => {
1413
+ if (recallRef.current !== undefined)
1414
+ setRecall(undefined);
1415
+ }, [setRecall]);
1416
+ const currentPromptCompletions = useCallback(() => {
1417
+ const completion = promptCompletionState(editorRef.current, commandNames, workspacePaths);
1418
+ return {
1419
+ completion,
1420
+ candidates: visiblePromptCompletions(completion, dismissedCompletionRef.current),
1421
+ };
1422
+ }, [commandNames, workspacePaths]);
1423
+ const acceptCompletion = useCallback(() => {
1424
+ // Recompute from the immediate editor and dismissal mirrors for the same
1425
+ // batched-input reason path splicing does below. Arrow events or Escape may
1426
+ // have advanced those refs before React commits the render that derives
1427
+ // `completions`; acceptance must not act on that stale frame.
1428
+ const { completion: currentCompletion, candidates: currentCompletions } = currentPromptCompletions();
1429
+ const selected = completionSelection(selectedCompletionRef.current, currentCompletions.length);
1430
+ const chosen = currentCompletions[selected];
1431
+ if (chosen === undefined)
1432
+ return;
1433
+ if (currentCompletion.kind === 'path') {
1434
+ // Re-derived from the immediate editor mirror rather than from the render's
1435
+ // `pathQuery`: several stdin events can be batched into one React pass, and
1436
+ // splicing a path at an offset the draft has moved past would corrupt it.
1437
+ const query = currentCompletion.pathQuery;
1438
+ if (query === undefined)
1439
+ return;
1440
+ // Text, and only text. Nothing about the chosen path is opened, stat-ed for
1441
+ // content or sent anywhere — the whole point of the Codex shape over
1442
+ // OpenCode's is that file bytes keep going through the gated `fileEditor` read.
1443
+ setEditor(applyPathCompletion(editorRef.current, query, chosen));
1444
+ }
1445
+ else {
1446
+ setEditor({ text: `/${chosen} `, cursor: { offset: chosen.length + 2, affinity: 'upstream' } });
1447
+ }
1448
+ preferredColumn.current = undefined;
1449
+ setSelectedCompletion(0);
1450
+ endRecall();
1451
+ }, [currentPromptCompletions, endRecall, setEditor, setSelectedCompletion]);
1452
+ /**
1453
+ * Puts a recalled prompt in the draft, cursor at its end.
1454
+ *
1455
+ * The end, not the start, is what makes walking further back work on a multi-row
1456
+ * prompt: `Up` moves up through its rows first and only steps to an older entry from
1457
+ * the top one, which is the rule that leaves `moveVertical` intact.
1458
+ */
1459
+ const applyRecalled = useCallback((text) => {
1460
+ // A recalled record entry replaces the draft: the recall walk keeps its own
1461
+ // snapshot behavior, and undo must not cross into a different prompt's text.
1462
+ undoStack.current = [];
1463
+ setEditor({ text, cursor: { offset: text.length, affinity: 'upstream' } });
1464
+ preferredColumn.current = undefined;
1465
+ // A recalled `/…` prompt reopens the command menu, so the selection has to start
1466
+ // from the top of it rather than from wherever the last menu was left.
1467
+ setSelectedCompletion(0);
1468
+ }, [setEditor]);
1469
+ /**
1470
+ * `Up` as queue take-back (SER-027), or `false` when this keypress is not one.
1471
+ *
1472
+ * Consulted after the completion menu and before prompt recall, and it fires
1473
+ * only when the queue is non-empty, no recall walk is open (an open walk keeps
1474
+ * its own `Up` semantics — one can only open while the queue is empty, and this
1475
+ * guard makes that structural), and the cursor sits on the **first visual row**
1476
+ * of the draft, the empty draft included. Every other keypress falls through:
1477
+ * below the first row `Up` is still cursor movement, and with an empty queue
1478
+ * recall is exactly as reachable as before this feature existed. One press
1479
+ * takes the whole queue back — entries one per line, ahead of any typed text.
1480
+ */
1481
+ const takeBackQueued = useCallback(() => {
1482
+ if (queuedRef.current.length === 0 || recallRef.current !== undefined)
1483
+ return false;
1484
+ const value = editorRef.current;
1485
+ const shape = layoutEditor(value.text, columns, value.cursor);
1486
+ if (shape.cursor.row !== 0)
1487
+ return false;
1488
+ return returnQueuedToEditor(false);
1489
+ }, [columns, returnQueuedToEditor]);
1490
+ /**
1491
+ * `Up`/`Down` as prompt recall, or `false` when this keypress is not recall at all.
1492
+ *
1493
+ * Returning `false` is the whole contract: the caller then falls through to
1494
+ * `moveVertical`, so cursor movement in a multi-line draft is untouched, and a
1495
+ * completion menu never reaches here because `App` handles menu selection first.
1496
+ * State is read from the mirrors rather than from the render, because several stdin
1497
+ * events can arrive in one React pass.
1498
+ */
1499
+ const stepRecall = useCallback((direction) => {
1500
+ const current = recallRef.current;
1501
+ const value = editorRef.current;
1502
+ if (current === undefined) {
1503
+ // Only from an empty draft: typed text is never replaced by a recalled prompt,
1504
+ // which is why no stashed draft has to exist for this to be safe.
1505
+ if (direction !== 'older' || value.text !== '')
1506
+ return false;
1507
+ // A reading that a finished turn has marked stale — or one still arriving — opens a
1508
+ // *pending* walk rather than offering last time's answer: the prompt a user wants
1509
+ // right after a turn is usually the one that turn just sent. Read before
1510
+ // `requestHistory()`, which clears the flag it is asking about. (A record append is
1511
+ // scheduled at turn end, not awaited, so a prompt whose write is still in flight
1512
+ // arrives in the reading after it — sub-millisecond in practice.)
1513
+ const known = historyRead.current.stale || historyRead.current.inFlight ? undefined : history;
1514
+ // Started here rather than at startup, like the workspace scan: a session that
1515
+ // never presses Up never opens a record.
1516
+ requestHistory();
1517
+ const opened = openPromptRecall(known);
1518
+ setRecall(opened.recall);
1519
+ if (opened.text !== undefined)
1520
+ applyRecalled(opened.text);
1521
+ return true;
1522
+ }
1523
+ // Laid out from the mirror, not from the render's `layout`: that one may describe a
1524
+ // draft an earlier event in this same batch has already replaced.
1525
+ const shape = layoutEditor(value.text, columns, value.cursor);
1526
+ const cursorRow = shape.cursor.row;
1527
+ const rowCount = shape.rows.length;
1528
+ // Inside a walk the arrows still move the cursor first: older only from the top
1529
+ // row, newer only from the bottom one. Nothing above or below to move to is what
1530
+ // makes the key mean "step in history" instead.
1531
+ if (direction === 'older' ? cursorRow !== 0 : cursorRow !== rowCount - 1)
1532
+ return false;
1533
+ const step = stepPromptRecall(current, direction);
1534
+ setRecall(step.recall);
1535
+ if (step.text !== undefined)
1536
+ applyRecalled(step.text);
1537
+ return true;
1538
+ }, [applyRecalled, columns, history, requestHistory, setRecall]);
1539
+ const openHistorySearch = useCallback(() => {
1540
+ const requestId = ++historySearchRequest.current;
1541
+ const known = historyRead.current.stale || historyRead.current.inFlight ? undefined : history;
1542
+ const opened = openPromptHistorySearch(editorRef.current, requestId, known);
1543
+ setHistorySearch(opened);
1544
+ setRecall(undefined);
1545
+ setDismissedCompletion(promptCompletionState(editorRef.current, commandNames, workspacePaths).identity);
1546
+ const pending = requestHistory();
1547
+ // Attach this opening to the reader's single in-flight promise without making the
1548
+ // key await it. Request identity prevents a cancelled/reopened search from accepting
1549
+ // an older landing; sequential recall shares the same cached reading.
1550
+ if (known === undefined && pending !== undefined) {
1551
+ void pending.then((reading) => {
1552
+ const current = historySearchRef.current;
1553
+ if (current !== undefined) {
1554
+ setHistorySearch(resolvePromptHistorySearch(current, requestId, reading));
1555
+ }
1556
+ });
1557
+ }
1558
+ }, [commandNames, history, requestHistory, setDismissedCompletion, setHistorySearch, setRecall, workspacePaths]);
1559
+ const handleHistorySearchKey = useCallback((typed, key) => {
1560
+ const current = historySearchRef.current;
1561
+ if (current === undefined)
1562
+ return false;
1563
+ if (key.escape) {
1564
+ setEditor(cancelPromptHistorySearch(current));
1565
+ setHistorySearch(undefined);
1566
+ preferredColumn.current = undefined;
1567
+ return true;
1568
+ }
1569
+ if (key.return || key.tab) {
1570
+ const accepted = acceptPromptHistorySearch(current);
1571
+ if (accepted !== undefined) {
1572
+ // Acceptance replaces the draft with a past prompt; the search's own
1573
+ // Escape-restore snapshot stays untouched, but undo must not reach
1574
+ // back into the pre-search draft from a different text.
1575
+ undoStack.current = [];
1576
+ setEditor(accepted);
1577
+ setSelectedCompletion(0);
1578
+ preferredColumn.current = undefined;
1579
+ setHistorySearch(undefined);
1580
+ }
1581
+ return true;
1582
+ }
1583
+ if ((key.ctrl && typed === 'r') || key.upArrow || key.downArrow) {
1584
+ const delta = key.downArrow ? -1 : 1;
1585
+ updateHistorySearch((value) => movePromptHistorySearchSelection(value, delta));
1586
+ return true;
1587
+ }
1588
+ if (key.backspace || key.delete) {
1589
+ updateHistorySearch(backspacePromptHistorySearchQuery);
1590
+ return true;
1591
+ }
1592
+ if (key.ctrl && typed === 'u') {
1593
+ updateHistorySearch(clearPromptHistorySearchQuery);
1594
+ return true;
1595
+ }
1596
+ if (!key.ctrl && typed !== '') {
1597
+ updateHistorySearch((value) => appendPromptHistorySearchQuery(value, normalizeDraftText(typed)));
1598
+ return true;
1599
+ }
1600
+ return true;
1601
+ }, [setEditor, setHistorySearch, setSelectedCompletion, updateHistorySearch]);
1602
+ const acceptRewind = useCallback(async () => {
1603
+ const search = rewindSearchRef.current;
1604
+ const selected = search === undefined ? undefined : acceptRewindSearch(search);
1605
+ if (search === undefined || selected === undefined || startRewind === undefined)
1606
+ return;
1607
+ if (clearing.current)
1608
+ return;
1609
+ if (runtime.info.sessionId !== search.sourceSessionId) {
1610
+ setRewindSearch(undefined);
1611
+ dispatch({ type: 'notice', text: 'rewind selection is stale — the live session changed', severity: 'warn' });
1612
+ return;
1613
+ }
1614
+ clearing.current = true;
1615
+ let next;
1616
+ try {
1617
+ next = await startRewind(selected);
1618
+ }
1619
+ catch (error) {
1620
+ dispatch({
1621
+ type: 'notice',
1622
+ text: `could not rewind; still in ${search.sourceSessionId}: ${error instanceof Error ? error.message : String(error)}`,
1623
+ severity: 'error',
1624
+ });
1625
+ return;
1626
+ }
1627
+ finally {
1628
+ clearing.current = false;
1629
+ }
1630
+ writeToTerminal(CLEAR_TERMINAL);
1631
+ recordAction({ type: 'clear' });
1632
+ setRuntime(next);
1633
+ setRewindSearch(undefined);
1634
+ // The restored session replaces the whole editor state; the selected prompt
1635
+ // returns unsent, and undo must not reach across the session boundary.
1636
+ undoStack.current = [];
1637
+ setEditor({ text: selected.prompt, cursor: { offset: selected.prompt.length, affinity: 'upstream' } });
1638
+ setSelectedCompletion(0);
1639
+ contextWarnLatch.current = createContextWarnLatch();
1640
+ trajectoryWarned.current = false;
1641
+ diagnosticsWarned.current = false;
1642
+ pendingShellReports.current = [];
1643
+ setQueued([]);
1644
+ withNoticeDiagnostics(recordAction, next.diagnostics)({
1645
+ type: 'notice',
1646
+ severity: 'warn',
1647
+ text: `rewound conversation into new session ${next.info.sessionId}; source ${search.sourceSessionId} remains saved and resumable. ` +
1648
+ 'Workspace unchanged: workspace files, shell and ! effects, hooks, MCP writes, subagents, background jobs, and learned-memory files were not rewound.',
1649
+ });
1650
+ }, [dispatch, recordAction, runtime, setEditor, setQueued, setRewindSearch, startRewind, writeToTerminal]);
1651
+ const handleRewindSearchKey = useCallback((typed, key) => {
1652
+ const current = rewindSearchRef.current;
1653
+ if (current === undefined)
1654
+ return false;
1655
+ if (key.escape) {
1656
+ setEditor(cancelRewindSearch(current));
1657
+ setRewindSearch(undefined);
1658
+ return true;
1659
+ }
1660
+ if (key.return || key.tab) {
1661
+ void acceptRewind();
1662
+ return true;
1663
+ }
1664
+ if (key.upArrow || key.downArrow) {
1665
+ updateRewindSearch((value) => moveRewindSearchSelection(value, key.downArrow ? 1 : -1));
1666
+ return true;
1667
+ }
1668
+ if (key.backspace || key.delete) {
1669
+ updateRewindSearch(backspaceRewindSearchQuery);
1670
+ return true;
1671
+ }
1672
+ if (key.ctrl && typed === 'u') {
1673
+ updateRewindSearch(clearRewindSearchQuery);
1674
+ return true;
1675
+ }
1676
+ if (!key.ctrl && typed !== '')
1677
+ updateRewindSearch((value) => appendRewindSearchQuery(value, normalizeDraftText(typed)));
1678
+ return true;
1679
+ }, [acceptRewind, setEditor, setRewindSearch, updateRewindSearch]);
1680
+ // A walk opened before the read landed is finished here, once, and only while the
1681
+ // draft is still the empty one it was opened on — a read that lands after the user
1682
+ // started typing must not overwrite what they typed.
1683
+ useEffect(() => {
1684
+ const current = recallRef.current;
1685
+ if (current === undefined || !current.pending)
1686
+ return;
1687
+ if (history === undefined || editorRef.current.text !== '')
1688
+ return;
1689
+ const opened = openPromptRecall(history);
1690
+ setRecall(opened.recall);
1691
+ if (opened.text !== undefined)
1692
+ applyRecalled(opened.text);
1693
+ }, [applyRecalled, history, setRecall]);
1694
+ const handleInterrupt = useCallback(() => {
1695
+ const now = Date.now();
1696
+ const previous = interruptedAt.current;
1697
+ if (status === 'idle' && pendingPermission === undefined) {
1698
+ exit();
1699
+ return;
1700
+ }
1701
+ if (previous !== undefined && now - previous < DOUBLE_INTERRUPT_MS) {
1702
+ exit();
1703
+ return;
1704
+ }
1705
+ interruptedAt.current = now;
1706
+ if (status === 'shell') {
1707
+ // The user's own `!` command: TERM its group now, KILL after the grace. The
1708
+ // completion path in submit() reports it as killed and frees the prompt —
1709
+ // and, because this was a user cancel, returns the queue to the editor
1710
+ // unsent (SER-027) instead of draining it.
1711
+ turnAborted.current = true;
1712
+ shellRun.current?.kill();
1713
+ dispatch({ type: 'notice', text: 'interrupted — press ctrl+c again to exit' });
1714
+ return;
1715
+ }
1716
+ if (status === 'compacting') {
1717
+ dispatch({ type: 'notice', text: 'compaction cannot be cancelled safely — press ctrl+c again to exit' });
1718
+ return;
1719
+ }
1720
+ // Deny anything waiting so the loop is not left blocked on a prompt. Not
1721
+ // close(): the session survives a cancelled turn, so later turns must still
1722
+ // be able to ask for approval. The abort mark is what keeps the queue from
1723
+ // being silently sent when the cancelled turn winds down (SER-027).
1724
+ turnAborted.current = true;
1725
+ permissions.denyPending();
1726
+ runtime.cancel();
1727
+ dispatch({ type: 'notice', text: 'interrupted — press ctrl+c again to exit' });
1728
+ }, [exit, pendingPermission, permissions, runtime, status]);
1729
+ useInput((typed, key) => {
1730
+ // Esc Esc chord (SER-059) bookkeeping: every key disarms it, and only the
1731
+ // composer's own Escape branch below re-arms — so an Escape consumed by an
1732
+ // earlier owner (permission, a search mode, a menu) never counts as a first press.
1733
+ const armedEscapeAt = escapeArmedAt.current;
1734
+ escapeArmedAt.current = undefined;
1735
+ if (key.ctrl && typed === 'd') {
1736
+ exit();
1737
+ return;
1738
+ }
1739
+ if (key.ctrl && typed === 'c') {
1740
+ handleInterrupt();
1741
+ return;
1742
+ }
1743
+ // Confirmations take the keyboard while one is pending.
1744
+ if (pendingPermission !== undefined) {
1745
+ if (typed === 'y' || typed === 'Y')
1746
+ answerPermission({ allowed: true });
1747
+ else if (typed === 'n' || typed === 'N' || key.escape)
1748
+ answerPermission({ allowed: false });
1749
+ // Lowercase takes the narrow offer, uppercase the whole tool — the more
1750
+ // sweeping choice costs the more deliberate keystroke.
1751
+ else if (typed === 'a' || typed === 'A') {
1752
+ const suggestions = pendingPermission.suggestions;
1753
+ const chosen = typed === 'a' ? suggestions[0] : suggestions[suggestions.length - 1];
1754
+ if (chosen !== undefined)
1755
+ answerPermission({ allowed: true, rule: chosen.rule });
1756
+ }
1757
+ return;
1758
+ }
1759
+ // Display-only and session-local. It is deliberately after permission
1760
+ // ownership, but before editor commands, so the draft and cursor are untouched.
1761
+ if (key.ctrl && typed === 'b') {
1762
+ dispatch({ type: 'toggleToolDetails' });
1763
+ return;
1764
+ }
1765
+ // Compaction rewrites the conversation outside the agent loop and owns the
1766
+ // editor until that atomic operation finishes. Global, permission, and
1767
+ // display-only controls above still work; no draft operation below does.
1768
+ if (status === 'compacting')
1769
+ return;
1770
+ // Search modes own query/navigation/accept keys after permission/compaction.
1771
+ if (rewindSearchRef.current !== undefined) {
1772
+ if (handleRewindSearchKey(typed, key))
1773
+ return;
1774
+ }
1775
+ if (historySearchRef.current !== undefined) {
1776
+ if (handleHistorySearchKey(typed, key))
1777
+ return;
1778
+ }
1779
+ if (key.ctrl && typed === 'r' && status === 'idle') {
1780
+ openHistorySearch();
1781
+ return;
1782
+ }
1783
+ // Clipboard image attachment is editor ownership, below permission,
1784
+ // compaction and search modes. Ctrl+O toggles without editing draft text.
1785
+ if (key.ctrl && typed === 'o') {
1786
+ clipboardReadGeneration.current += 1;
1787
+ if (attachedImageRef.current !== undefined) {
1788
+ setAttachedImage(undefined);
1789
+ dispatch({ type: 'notice', text: 'clipboard image removed from the next prompt' });
1790
+ }
1791
+ else if (imageTurnInFlight.current || hasQueuedImage(queuedRef.current)) {
1792
+ dispatch({ type: 'notice', text: 'one clipboard image is already queued or sending — take it back or let it finish first' });
1793
+ }
1794
+ else {
1795
+ const generation = clipboardReadGeneration.current;
1796
+ void readClipboardImage().then((image) => {
1797
+ if (clipboardReadGeneration.current !== generation)
1798
+ return;
1799
+ setAttachedImage(image);
1800
+ dispatch({ type: 'notice', text: clipboardImageFact(image) });
1801
+ }, (error) => {
1802
+ if (clipboardReadGeneration.current !== generation)
1803
+ return;
1804
+ dispatch({
1805
+ type: 'notice',
1806
+ text: `could not attach clipboard image; draft unchanged: ${error instanceof Error ? error.message : String(error)}`,
1807
+ severity: 'warn',
1808
+ });
1809
+ });
1810
+ }
1811
+ return;
1812
+ }
1813
+ // Escape belongs to the highest transient prompt UI currently shown. A menu
1814
+ // wins over recall just as it wins the arrow keys; neither branch touches the
1815
+ // editor, submits, dispatches, or changes the queue/runtime. The dismissed query
1816
+ // is read from the immediate editor mirror so batched Escape/text is coherent.
1817
+ if (key.escape) {
1818
+ const { completion: currentCompletion, candidates: visible } = currentPromptCompletions();
1819
+ if (visible.length > 0 && currentCompletion.identity !== undefined) {
1820
+ setDismissedCompletion(currentCompletion.identity);
1821
+ setSelectedCompletion(0);
1822
+ }
1823
+ else if (recallRef.current !== undefined) {
1824
+ endRecall();
1825
+ }
1826
+ else if (status === 'idle' && queuedRef.current.length === 0 && editorRef.current.text === '') {
1827
+ // Esc Esc (SER-059): no owner took this Escape and there is nothing to
1828
+ // lose — empty draft, no turn or `!` command, no queue (a pending
1829
+ // permission returned above). The first press arms a timestamp; a second
1830
+ // inside the window opens the `/rewind` chooser through the command's own
1831
+ // path. Two ESC bytes in one stdin chunk reach Ink as one escape with
1832
+ // `meta`, which is both presses at once.
1833
+ const now = Date.now();
1834
+ if (key.meta || (armedEscapeAt !== undefined && now - armedEscapeAt < ESCAPE_REWIND_CHORD_MS)) {
1835
+ void openRewindChooser();
1836
+ }
1837
+ else {
1838
+ escapeArmedAt.current = now;
1839
+ }
1840
+ }
1841
+ return;
1842
+ }
1843
+ // Readline-style editing chords. After permission ownership (a pending
1844
+ // prompt still owns 'a'/'e'), before the generic ctrl/meta ignore below.
1845
+ if (key.ctrl && (typed === 'a' || typed === 'e')) {
1846
+ setEditor((current) => ({
1847
+ ...current,
1848
+ cursor: moveToRowEdge(layoutEditor(current.text, columns, current.cursor), typed === 'a' ? 'start' : 'end'),
1849
+ }));
1850
+ preferredColumn.current = undefined;
1851
+ return;
1852
+ }
1853
+ // Composer undo (SER-044). Most terminals send both Ctrl+_ and Ctrl+- as
1854
+ // byte 0x1f, which Ink's legacy parser reports as the bare unit separator
1855
+ // with no modifier flags; the kitty protocol reports a real ctrl chord.
1856
+ // An empty stack is a harmless no-op — the key is consumed either way, so
1857
+ // the byte can never fall through into the draft as text.
1858
+ if (typed === '\u001f' || (key.ctrl && (typed === '_' || typed === '-'))) {
1859
+ const popped = popUndo(undoStack.current);
1860
+ if (popped !== undefined) {
1861
+ undoStack.current = popped.stack;
1862
+ setEditor(popped.value);
1863
+ preferredColumn.current = undefined;
1864
+ setSelectedCompletion(0);
1865
+ endRecall();
1866
+ }
1867
+ return;
1868
+ }
1869
+ if (key.ctrl && (typed === 'k' || typed === 'u')) {
1870
+ applyDestructive((current) => killToRowEdge(current, layoutEditor(current.text, columns, current.cursor), typed === 'k' ? 'end' : 'start'));
1871
+ preferredColumn.current = undefined;
1872
+ setSelectedCompletion(0);
1873
+ endRecall();
1874
+ return;
1875
+ }
1876
+ if (key.ctrl && typed === 'w') {
1877
+ applyDestructive((current) => deleteWordBefore(current));
1878
+ preferredColumn.current = undefined;
1879
+ setSelectedCompletion(0);
1880
+ endRecall();
1881
+ return;
1882
+ }
1883
+ // Word chords (readline Alt+B/Alt+F/Alt+D). The parser strips the ESC
1884
+ // prefix, so these arrive as key.meta plus the bare letter — after the
1885
+ // owners above (a pending permission took the keyboard, search modes took
1886
+ // their query keys) and before the generic meta ignore below.
1887
+ if (key.meta && !key.ctrl && (typed === 'b' || typed === 'f')) {
1888
+ setEditor((current) => ({
1889
+ ...current,
1890
+ cursor: moveWordHorizontal(current.text, current.cursor, typed === 'b' ? -1 : 1),
1891
+ }));
1892
+ preferredColumn.current = undefined;
1893
+ return;
1894
+ }
1895
+ if (key.meta && !key.ctrl && typed === 'd') {
1896
+ applyDestructive((current) => deleteWordAfter(current));
1897
+ preferredColumn.current = undefined;
1898
+ setSelectedCompletion(0);
1899
+ endRecall();
1900
+ return;
1901
+ }
1902
+ // No guard for a streaming turn: typing during one stays allowed, and a
1903
+ // submission during one is queued in submit() (SER-027) — local commands
1904
+ // like /usage still answer mid-turn immediately. (A pending confirmation is
1905
+ // different — it took the keyboard above, because the loop is blocked until
1906
+ // it is answered, and the queue is held untouched while it is up.)
1907
+ if (key.return) {
1908
+ // A trailing backslash is an explicit continuation marker. Consume it so
1909
+ // the prompt sent later contains the intended newline, not editor syntax.
1910
+ if (editorRef.current.text.endsWith('\\')) {
1911
+ const text = `${editorRef.current.text.slice(0, -1)}\n`;
1912
+ setEditor({ text, cursor: { offset: text.length, affinity: 'upstream' } });
1913
+ preferredColumn.current = undefined;
1914
+ setSelectedCompletion(0);
1915
+ endRecall();
1916
+ return;
1917
+ }
1918
+ // With a completion highlighted, Enter accepts it rather than submitting a
1919
+ // half-typed skill name. Consult the immediate mirrors: Escape and Enter can
1920
+ // arrive in one stdin batch before `completions` re-renders as empty.
1921
+ if (currentPromptCompletions().candidates.length > 0) {
1922
+ acceptCompletion();
1923
+ return;
1924
+ }
1925
+ // Submitting is the end of the walk too: the record's entry has become this
1926
+ // session's prompt, and the indicator has nothing left to describe.
1927
+ endRecall();
1928
+ void submit(editorRef.current.text);
1929
+ return;
1930
+ }
1931
+ // A pty or terminal may batch printable text with Enter on either side of
1932
+ // the same event. Depending on line discipline, that terminator reaches Ink
1933
+ // as CR, LF, or CRLF (occasionally doubled); keep one Enter's semantics and
1934
+ // preserve the printable text. A single LF remains Ctrl+J below.
1935
+ const leadingEnter = typed.length > 1 ? typed.match(/^[\r\n]+/)?.[0] : undefined;
1936
+ const trailingEnter = typed.length > 1 ? typed.match(/[\r\n]+$/)?.[0] : undefined;
1937
+ const batchedEnter = leadingEnter ?? trailingEnter;
1938
+ if (batchedEnter !== undefined) {
1939
+ const payload = leadingEnter === undefined
1940
+ ? typed.slice(0, -batchedEnter.length)
1941
+ : typed.slice(batchedEnter.length);
1942
+ const beforeEnter = leadingEnter === undefined
1943
+ ? insertAtCursor(editorRef.current, normalizeDraftText(payload))
1944
+ : editorRef.current;
1945
+ if (beforeEnter.text.endsWith('\\')) {
1946
+ const text = `${beforeEnter.text.slice(0, -1)}\n`;
1947
+ const continued = { text, cursor: { offset: text.length, affinity: 'upstream' } };
1948
+ setEditor(leadingEnter === undefined ? continued : insertAtCursor(continued, normalizeDraftText(payload)));
1949
+ preferredColumn.current = undefined;
1950
+ setSelectedCompletion(0);
1951
+ endRecall();
1952
+ return;
1953
+ }
1954
+ const next = leadingEnter === undefined
1955
+ ? beforeEnter
1956
+ : insertAtCursor(beforeEnter, normalizeDraftText(payload));
1957
+ // Mirrored into the editor *before* submitting, so a submission the busy
1958
+ // check refuses (SER-027's /clear-family exception keeps SER-010's retention
1959
+ // shape) leaves the batched text visible in the draft instead of silently
1960
+ // dropping it — a pty or paste can deliver `text\r` as one event, and
1961
+ // retention must not depend on how the terminal chunked the keystrokes. An
1962
+ // accepted or queued submission clears it anyway.
1963
+ setEditor(next);
1964
+ preferredColumn.current = undefined;
1965
+ setSelectedCompletion(0);
1966
+ endRecall();
1967
+ void submit(next.text);
1968
+ return;
1969
+ }
1970
+ // Terminals encode Ctrl+J as LF, distinct from the CR emitted by Enter.
1971
+ // Ink does not expose an `enter` flag, so the literal input is the contract.
1972
+ if (typed === '\n') {
1973
+ setEditor((current) => insertAtCursor(current, '\n'));
1974
+ preferredColumn.current = undefined;
1975
+ setSelectedCompletion(0);
1976
+ endRecall();
1977
+ return;
1978
+ }
1979
+ const immediateCompletionCount = currentPromptCompletions().candidates.length;
1980
+ if (key.tab && immediateCompletionCount > 0) {
1981
+ acceptCompletion();
1982
+ return;
1983
+ }
1984
+ if (key.upArrow && immediateCompletionCount > 0) {
1985
+ setSelectedCompletion((i) => moveCompletionSelection(i, immediateCompletionCount, -1));
1986
+ return;
1987
+ }
1988
+ if (key.downArrow && immediateCompletionCount > 0) {
1989
+ setSelectedCompletion((i) => moveCompletionSelection(i, immediateCompletionCount, 1));
1990
+ return;
1991
+ }
1992
+ // Word jumps on modified arrows (terminals encode Alt+Left as CSI 1;3D,
1993
+ // Ctrl+Left as CSI 1;5D — both reach Ink as arrow plus meta/ctrl). After
1994
+ // the menu's Tab/Up/Down ownership above; plain arrows keep their exact
1995
+ // one-grapheme contract below.
1996
+ if ((key.leftArrow || key.rightArrow) && (key.ctrl || key.meta)) {
1997
+ setEditor((current) => ({
1998
+ ...current,
1999
+ cursor: moveWordHorizontal(current.text, current.cursor, key.leftArrow ? -1 : 1),
2000
+ }));
2001
+ preferredColumn.current = undefined;
2002
+ return;
2003
+ }
2004
+ if (key.leftArrow || key.rightArrow) {
2005
+ setEditor((current) => ({
2006
+ ...current,
2007
+ cursor: moveHorizontal(current.text, current.cursor, key.leftArrow ? -1 : 1, layoutEditor(current.text, columns, current.cursor)),
2008
+ }));
2009
+ preferredColumn.current = undefined;
2010
+ return;
2011
+ }
2012
+ if (key.home || key.end) {
2013
+ setEditor((current) => ({
2014
+ ...current,
2015
+ cursor: moveToRowEdge(layoutEditor(current.text, columns, current.cursor), key.home ? 'start' : 'end'),
2016
+ }));
2017
+ preferredColumn.current = undefined;
2018
+ return;
2019
+ }
2020
+ if (key.upArrow || key.downArrow) {
2021
+ // The Up chain, in fixed precedence (SER-027 joined it): the completion
2022
+ // menu already took both keys above; queue take-back is consulted next,
2023
+ // then recall — each answers `false` for every keypress that is ordinary
2024
+ // cursor movement, which is what leaves a multi-line draft's rows navigable.
2025
+ if (key.upArrow && takeBackQueued())
2026
+ return;
2027
+ if (stepRecall(key.upArrow ? 'older' : 'newer'))
2028
+ return;
2029
+ const moved = moveVertical(layout, key.upArrow ? -1 : 1, preferredColumn.current);
2030
+ setEditor((current) => ({ ...current, cursor: moved.cursor }));
2031
+ preferredColumn.current = moved.preferredColumn;
2032
+ return;
2033
+ }
2034
+ if (key.backspace || key.delete) {
2035
+ // Alt+Backspace (ESC+DEL or ESC+BS → meta+backspace) deletes the word
2036
+ // before the cursor with the exact primitive Ctrl+W uses; Alt+Delete is
2037
+ // its forward mirror, matching the unmodified pairing below. Only the
2038
+ // word variants snapshot for undo — a single-grapheme delete is not the
2039
+ // destructive loss SER-044 guards, and would flood the bounded stack.
2040
+ if (key.meta) {
2041
+ applyDestructive((current) => key.backspace ? deleteWordBefore(current) : deleteWordAfter(current));
2042
+ }
2043
+ else {
2044
+ setEditor((current) => key.backspace ? backspaceAtCursor(current) : deleteAtCursor(current));
2045
+ }
2046
+ preferredColumn.current = undefined;
2047
+ setSelectedCompletion(0);
2048
+ endRecall();
2049
+ return;
2050
+ }
2051
+ // Ignore chords and non-printable keys; take everything else as text.
2052
+ if (key.ctrl || key.meta || key.escape || typed === '')
2053
+ return;
2054
+ // A terminal without bracketed-paste support can still deliver a whole write
2055
+ // here. Preserve every line just like usePaste rather than submitting at the
2056
+ // first one and silently dropping the rest.
2057
+ const printable = normalizeDraftText(typed);
2058
+ if (printable === '')
2059
+ return;
2060
+ setEditor((current) => insertAtCursor(current, printable));
2061
+ preferredColumn.current = undefined;
2062
+ setSelectedCompletion(0);
2063
+ endRecall();
2064
+ });
2065
+ usePaste((pasted) => {
2066
+ // Permission and compaction own all input while visible/busy, including paste.
2067
+ if (pendingPermission !== undefined || status === 'compacting')
2068
+ return;
2069
+ const text = normalizeDraftText(pasted);
2070
+ if (text === '')
2071
+ return;
2072
+ setEditor((current) => insertAtCursor(current, text));
2073
+ preferredColumn.current = undefined;
2074
+ setSelectedCompletion(0);
2075
+ endRecall();
2076
+ });
2077
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { ref: headerRef, flexDirection: "column", children: _jsx(Header, { runtime: runtime, status: effectiveStatus, frame: frame }) }), _jsx(MessageList, { history: state.history, ...(state.staticEpoch === 0 ? { welcome: initialWelcome } : {}), liveText: state.liveText, liveCodeOpen: fenceOpenAfter(state.committedAnswer), columns: columns, maxLiveRows: grants.live, staticEpoch: state.staticEpoch }), _jsxs(Box, { ref: chromeRef, flexDirection: "column", children: [state.thinking && effectiveStatus === 'streaming' && (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: `thinking…${busyElapsedMs === undefined ? '' : busySuffix(busyElapsedMs, undefined, busyRetryWait)}` })), _jsx(ActiveToolCalls, { tools: state.activeTools, frame: frame, toolDetailsExpanded: state.toolDetailsExpanded, columns: columns, maxRows: grants.tools }), _jsx(PlanChecklist, { plan: state.livePlan, maxRows: grants.plan }), _jsx(QueuedMessages, { entries: queued, maxRows: grants.queued }), pendingPermission !== undefined ? (_jsx(PermissionPrompt, { request: pendingPermission, waiting: permissions.waiting, columns: columns, maxRows: grants.prompt })) : (_jsx(InputBox, { layout: layout, completions: completions, completionKind: completionKind, completionNote: completionNote, selectedCompletion: selectedCompletion, editable: effectiveStatus !== 'compacting', offset: { top: chrome.top, left: chrome.left }, maxRows: grants.prompt, hint: streamingHint, attachment: attachedImage === undefined ? undefined : clipboardImageFact(attachedImage), recallIndicator: recallIndicator, historySearch: historySearchProjection, rewindSearch: rewindSearchProjection }))] })] }));
2078
+ }
2079
+ /** The hint row under the draft, or nothing when the session is idle. */
2080
+ function hintForStatus(status, busyReadout, queuedCount = 0) {
2081
+ if (status === 'streaming') {
2082
+ // The live readout rides directly behind `working…`, ahead of the static command
2083
+ // hints: the row is one truncated <Text>, so on a narrow terminal the tail is what
2084
+ // goes missing, and the tail should be the part that never changes. The queue
2085
+ // count (SER-027) rides with it: even a listing cut to nothing stays counted here.
2086
+ return `working…${busyReadout ?? ''}${queuedCountHint(queuedCount)} /tasks lists jobs · /agents lists dispatches · /usage reports tokens · ctrl+c cancels this turn`;
2087
+ }
2088
+ // Elapsed lives on the command's own panel row, so this row can stay static.
2089
+ if (status === 'shell')
2090
+ return `running ! command…${queuedCountHint(queuedCount)} ctrl+c cancels it`;
2091
+ return status === 'compacting' ? 'compacting conversation…' : undefined;
2092
+ }
2093
+ /**
2094
+ * The session's reported spend, or undefined when the meter cannot be read.
2095
+ *
2096
+ * Read per spinner tick, so it follows `startTurnSpend`'s cannot-throw precedent: a
2097
+ * failure degrades the suffix to elapsed-only rather than becoming a render error.
2098
+ */
2099
+ function liveSpend(runtime) {
2100
+ try {
2101
+ return usageBuckets(runtime.usage, runtime.config);
2102
+ }
2103
+ catch {
2104
+ return undefined;
2105
+ }
2106
+ }
2107
+ /** The parent's pending model-retry wait, under the same cannot-throw rule as {@link liveSpend}. */
2108
+ function liveRetryWait(runtime) {
2109
+ try {
2110
+ return runtime.retryWait();
2111
+ }
2112
+ catch {
2113
+ return undefined;
2114
+ }
2115
+ }
2116
+ /** The retry ending of the turn that just failed, or `undefined`; never throws into a notice. */
2117
+ function lastRetryOutcome(runtime) {
2118
+ try {
2119
+ return runtime.retryOutcome();
2120
+ }
2121
+ catch {
2122
+ return undefined;
2123
+ }
2124
+ }
2125
+ export function Header({ runtime, status = 'idle', frame = 0, }) {
2126
+ const info = runtime.info;
2127
+ const instructions = info.projectInstructions;
2128
+ // Live, not info.permissionMode: /mode moves it mid-session, and a header still
2129
+ // naming the startup policy would be worse than no header — this row is the only
2130
+ // place the effective mode is stated, and it must not gain a second one.
2131
+ const mode = runtime.permissionMode;
2132
+ return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { children: [_jsxs(Text, { color: visualColor.identity, bold: true, children: [visualMarker.identity, " DARWIN"] }), _jsxs(Text, { dimColor: true, children: [' · ', status === 'streaming' ? _jsx(WorkingStatus, { frame: frame }) : headerStatus(status)] })] }), _jsxs(Text, { dimColor: true, children: [runtime.config.provider, "/", runtime.config.model, " \u00B7 session ", info.sessionId, info.resumed ? ' (resumed)' : '', formatPromptCache(runtime.promptCache), formatThinking(runtime.thinking)] }), mode === 'yolo' ? (_jsx(Text, { color: visualColor.warning, children: "mode: yolo \u2014 every tool call runs without confirmation" })) : mode === 'plan' ? (_jsxs(Text, { color: visualColor.warning, children: ["mode: plan \u2014 read-only; write and execute calls are denied", runtime.allowRuleCount > 0 ? ` · ${runtime.allowRuleCount} allow rule(s) ignored` : ''] })) : (_jsxs(Text, { dimColor: true, children: ["mode: ", mode, runtime.allowRuleCount > 0 ? ` · ${runtime.allowRuleCount} allow rule(s)` : ''] })), instructions !== undefined &&
2133
+ (instructions.truncated ? (_jsxs(Text, { color: visualColor.warning, children: [AGENTS_FILENAME, ": loaded (", formatBytes(instructions.bytes), ", truncated to", ' ', MAX_INSTRUCTIONS_BYTES / 1024, " KB)"] })) : (_jsxs(Text, { dimColor: true, children: [AGENTS_FILENAME, ": loaded (", formatBytes(instructions.bytes), ")"] }))), info.projectInstructionsProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: [AGENTS_FILENAME, ": skipped \u2014 ", info.projectInstructionsProblem] })), info.systemPromptSource === 'config' && (_jsxs(Text, { dimColor: true, children: ["system prompt: overridden by ", DARWIN_DIRNAME, "/", CONFIG_FILENAME] })), info.systemPromptSource === 'file' && (_jsxs(Text, { dimColor: true, children: ["system prompt: ", DARWIN_DIRNAME, "/", SYSTEM_PROMPT_FILENAME] })), info.systemPromptProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["system prompt: using the default \u2014 ", info.systemPromptProblem] })), info.workingContextProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["working context: no directory listing \u2014 ", info.workingContextProblem] })), info.promptCache.problem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["prompt cache: off \u2014 ", info.promptCache.problem] })), runtime.thinking.problem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["thinking: ", runtime.thinking.problem] })), hasCapabilities(info) && (_jsxs(Text, { dimColor: true, children: ["loaded: ", formatCapabilities(info), " \u00B7 type / for commands"] })), info.mcpIgnoredConfigPath !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["mcp: using ", DARWIN_DIRNAME, "/", MCP_CONFIG_FILENAME, " \u2014 ", info.mcpIgnoredConfigPath, " ignored"] })), info.hookShadowNotices.map((notice) => (_jsxs(Text, { color: visualColor.warning, wrap: "truncate-end", children: ["hooks: ", notice.layer, " ", notice.directory, " shadows ", notice.shadowed.join(', ')] }, notice.directory))), info.skillProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["skill skipped: ", problem.directory, " \u2014 ", problem.reason] }, problem.directory))), info.commandProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["command skipped: ", problem.file, " \u2014 ", problem.reason] }, problem.file))), info.agentProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["agent skipped: ", problem.file, " \u2014 ", problem.reason] }, problem.file))), _jsx(Text, { dimColor: true, children: "/ for actions \u00B7 @ for paths \u00B7 ctrl+c cancels \u00B7 /exit quits" })] }));
2134
+ }
2135
+ const WORKING_LABEL = 'working';
2136
+ /** Highlights one letter in place, preserving the header's exact width and row count. */
2137
+ export function workingStatusIndex(frame) {
2138
+ return frame % WORKING_LABEL.length;
2139
+ }
2140
+ function WorkingStatus({ frame }) {
2141
+ const active = workingStatusIndex(frame);
2142
+ return (_jsx(_Fragment, { children: [...WORKING_LABEL].map((letter, index) => (_jsx(Text, { ...(index === active ? { color: visualColor.active, bold: true } : {}), children: letter }, index))) }));
2143
+ }
2144
+ function headerStatus(status) {
2145
+ switch (status) {
2146
+ case 'idle':
2147
+ return 'ready';
2148
+ case 'shell':
2149
+ return 'running !';
2150
+ case 'compacting':
2151
+ return 'compacting';
2152
+ case 'awaiting-permission':
2153
+ return 'permission needed';
2154
+ }
2155
+ }
2156
+ function hasCapabilities(info) {
2157
+ return info.skillNames.length + info.commandNames.length + info.agentNames.length + info.mcpServerCount > 0;
2158
+ }
2159
+ function formatCapabilities(info) {
2160
+ const capabilities = [
2161
+ capabilityCount(info.skillNames.length, 'skill'),
2162
+ capabilityCount(info.commandNames.length, 'command'),
2163
+ capabilityCount(info.agentNames.length, 'agent'),
2164
+ capabilityCount(info.mcpServerCount, 'MCP server'),
2165
+ ];
2166
+ return capabilities.filter((value) => value !== undefined).join(' · ');
2167
+ }
2168
+ function capabilityCount(count, label) {
2169
+ return count > 0 ? `${count} ${label}${count === 1 ? '' : 's'}` : undefined;
2170
+ }
2171
+ /** Sizes are shown so an accidentally huge AGENTS.md is visible at a glance. */
2172
+ function formatBytes(bytes) {
2173
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
2174
+ }
2175
+ /**
2176
+ * Provider-aware token counters as a labelled block.
2177
+ *
2178
+ * Numbers are aligned rather than run together on one line: the point of asking
2179
+ * is to compare them (a large cache read next to a small input is the cache
2180
+ * working), and that comparison is what a column makes readable. An unavailable
2181
+ * provider metric remains text rather than masquerading as numeric zero.
2182
+ */
2183
+ export function formatUsageReport(usage, config, resumed, turnInFlight = false, lastTurn, children, callStats, modelShares) {
2184
+ const rows = usageRows(usage, config);
2185
+ const derived = cacheEffectivenessRows(usage, config);
2186
+ const labelWidth = Math.max(...rows.map(({ label }) => label.length), ...derived.map(({ label }) => label.length));
2187
+ const lines = [
2188
+ ...rows.map(({ label, value }) => ({ label, rendered: formatUsageValue(value) })),
2189
+ ...derived.map(({ label, value }) => ({ label, rendered: value ?? 'not reported' })),
2190
+ ].map(({ label, rendered }) => ` ${label.padEnd(labelWidth)} ${rendered.padStart(12)}`);
2191
+ // The cost line closes the block — the same per-model projection `/status`
2192
+ // prints, each model's share at its own rates, so the two cannot disagree.
2193
+ // Present only when the caller has the shares (the runtime always does; a
2194
+ // formatter-only caller that passes none renders the pre-cost report byte for
2195
+ // byte). When more than one model contributed, one bounded line per model follows,
2196
+ // so the mixed figure can be taken apart; a single-model session adds nothing.
2197
+ if (modelShares !== undefined) {
2198
+ lines.push(` ${'cost'.padEnd(labelWidth)} ${describeModelCosts(modelShares)}`);
2199
+ if (modelShares.length > 1) {
2200
+ for (const share of modelShares) {
2201
+ lines.push(` ${share.config.provider}/${share.config.model}: ${describeModelCosts([share])}`);
2202
+ }
2203
+ }
2204
+ }
2205
+ // "This run" is the honest scope: the SDK's meter is per-process, so a resumed
2206
+ // session's earlier spend is simply not knowable here.
2207
+ const heading = resumed
2208
+ ? 'token usage — this run (resumed: earlier runs are not counted)'
2209
+ : 'token usage — this run';
2210
+ // Asked mid-turn, the totals are the ones from before it: the meter accumulates
2211
+ // a model call when it finishes. Said out loud, because numbers that do not move
2212
+ // while the agent is visibly working read as a broken counter.
2213
+ const footer = turnInFlight ? [' (the turn in flight is not counted yet)'] : [];
2214
+ // Last-turn section: only when a turn has completed. Mid-turn, lastTurn is the
2215
+ // previous completed turn, labelled clearly so it is not mistaken for the
2216
+ // in-flight one.
2217
+ const lastTurnSection = lastTurn === undefined ? [] : formatLastTurnSection(lastTurn, config, labelWidth);
2218
+ // Child sections: only when a dispatch reported spend (`runtime.childUsage`),
2219
+ // so a session that never delegated renders byte-identical to before children
2220
+ // were counted at all. The session total repeats the parent's projection rules
2221
+ // over the summed meters — same rows, same absent-metric honesty.
2222
+ const childSections = children === undefined
2223
+ ? []
2224
+ : [
2225
+ ...usageSection(`subagents (${children.dispatches} dispatch${children.dispatches === 1 ? '' : 'es'})`, children.usage, config, labelWidth),
2226
+ ...usageSection('session total (incl. subagents)', sumUsage([usage, children.usage]), config, labelWidth),
2227
+ ];
2228
+ // Efficiency section: only when a completed model call was observed
2229
+ // (`runtime.callStats`), so a session with none renders byte-identical to before
2230
+ // per-call stats existed — the childUsage additive convention, again.
2231
+ const efficiencySection = callStats === undefined ? [] : formatEfficiencySection(callStats, config, labelWidth);
2232
+ return [heading, ...lines, ...footer, ...lastTurnSection, ...childSections, ...efficiencySection].join('\n');
2233
+ }
2234
+ /**
2235
+ * The per-call efficiency section of the usage report: how many model round trips
2236
+ * the session has made, how big the average request has been running, and how many
2237
+ * responses bought no, one, or several tools — the shape the "repeated long-context
2238
+ * single-tool round" pattern shows up in. The numbers come from the same
2239
+ * `call-stats` arithmetic `/status` renders, so the two surfaces cannot drift; an
2240
+ * unknown average reads `not reported`, never 0.
2241
+ */
2242
+ function formatEfficiencySection(stats, config, labelWidth) {
2243
+ const rows = [
2244
+ { label: 'model calls', rendered: stats.calls.toLocaleString('en-US') },
2245
+ { label: 'avg request input/call', rendered: formatUsageValue(averageRequestInputTokens(stats, config)) },
2246
+ { label: 'single-tool responses', rendered: stats.singleTool.toLocaleString('en-US') },
2247
+ { label: 'multi-tool responses', rendered: stats.multiTool.toLocaleString('en-US') },
2248
+ { label: 'no-tool responses', rendered: stats.noTool.toLocaleString('en-US') },
2249
+ ];
2250
+ const width = Math.max(labelWidth, ...rows.map(({ label }) => label.length));
2251
+ return [
2252
+ 'efficiency (completed model calls)',
2253
+ ...rows.map(({ label, rendered }) => ` ${label.padEnd(width)} ${rendered.padStart(12)}`),
2254
+ ];
2255
+ }
2256
+ /**
2257
+ * One additional labelled section of usage rows, aligned to at least the parent
2258
+ * table's label width — the shape `formatLastTurnSection` set.
2259
+ */
2260
+ function usageSection(heading, usage, config, labelWidth) {
2261
+ const rows = usageRows(usage, config);
2262
+ const width = Math.max(labelWidth, ...rows.map(({ label }) => label.length));
2263
+ return [
2264
+ heading,
2265
+ ...rows.map(({ label, value }) => ` ${label.padEnd(width)} ${formatUsageValue(value).padStart(12)}`),
2266
+ ];
2267
+ }
2268
+ /**
2269
+ * One-section "last turn (previous turn)" block, reusing the same label
2270
+ * width as the parent table for visual alignment.
2271
+ */
2272
+ function formatLastTurnSection(lastTurn, config, labelWidth) {
2273
+ const lastRows = usageRows(lastTurn, config);
2274
+ const lastDerived = cacheEffectivenessRows(lastTurn, config);
2275
+ const allLastWidth = Math.max(labelWidth, ...lastRows.map(({ label }) => label.length), ...lastDerived.map(({ label }) => label.length));
2276
+ const lastLines = [
2277
+ ...lastRows.map(({ label, value }) => ({ label, rendered: formatUsageValue(value) })),
2278
+ ...lastDerived.map(({ label, value }) => ({ label, rendered: value ?? 'not reported' })),
2279
+ ].map(({ label, rendered }) => ` ${label.padEnd(allLastWidth)} ${rendered.padStart(12)}`);
2280
+ return ['last turn (previous turn)', ...lastLines];
2281
+ }
2282
+ /**
2283
+ * Wraps a reducer dispatch so every notice is also written to the diagnostics log,
2284
+ * with the severity it was shown at — or hands the dispatch straight back when there
2285
+ * is no log, which is the default.
2286
+ *
2287
+ * Outside the reducer, never inside it: `turnReducer` is pure and shared with
2288
+ * `trajectory replay`, so a side effect in it would both fire twice under React's
2289
+ * strict double-invocation and make replaying a record write to a log. Wrapping the
2290
+ * dispatch instead means no notice site had to change, and a notice added later is
2291
+ * mirrored without anyone remembering to do it.
2292
+ *
2293
+ * The action reaches the reducer unchanged and unconditionally: the log is a copy of
2294
+ * what the transcript said, and a broken log may not cost the user the line itself.
2295
+ */
2296
+ export function withNoticeDiagnostics(dispatch, log) {
2297
+ if (log === undefined)
2298
+ return dispatch;
2299
+ return (action) => {
2300
+ // `write` is synchronous and swallows its own failures, so this cannot delay or
2301
+ // deny the render below; the severity defaults exactly as the reducer defaults it.
2302
+ if (action.type === 'notice')
2303
+ log.notice(action.text, action.severity ?? 'info');
2304
+ dispatch(action);
2305
+ };
2306
+ }
2307
+ /**
2308
+ * What this session has recorded, or why it has not.
2309
+ *
2310
+ * "This run" is the honest scope for the counters, exactly as in the usage report:
2311
+ * the file may hold earlier runs of the same session (recording continues across
2312
+ * `--resume`), but this process only knows what it appended itself. The reader is
2313
+ * pointed at the file rather than told a total it cannot trust.
2314
+ */
2315
+ export function formatTrajectoryReport(status, sessionId) {
2316
+ if (status === undefined) {
2317
+ return [
2318
+ 'trajectory: not recording (trajectory: false)',
2319
+ ` set "trajectory": true in ~/${DARWIN_DIRNAME}/${CONFIG_FILENAME} to record this session`,
2320
+ ].join('\n');
2321
+ }
2322
+ const lines = [
2323
+ status.active ? 'trajectory: recording' : 'trajectory: stopped',
2324
+ ` file ${status.file}`,
2325
+ ` records this run ${groupDigits(status.recordsThisRun)}`,
2326
+ ` bytes this run ${groupDigits(status.bytesThisRun)}`,
2327
+ ];
2328
+ if (status.truncationsThisRun > 0) {
2329
+ // Said out loud: a capped record is still a faithful record of *what happened*,
2330
+ // but not of every byte, and a reader deserves to know before quoting it.
2331
+ lines.push(` truncated fields ${groupDigits(status.truncationsThisRun)} (size caps)`);
2332
+ }
2333
+ if (status.problem !== undefined)
2334
+ lines.push(` problem ${status.problem}`);
2335
+ lines.push(` replay it with: darwin trajectory replay ${sessionId}`);
2336
+ return lines.join('\n');
2337
+ }
2338
+ /** Formats the context reduction from `/compact` without implying billing savings. */
2339
+ export function formatCompactReport(result) {
2340
+ if (!result.compacted) {
2341
+ return `conversation already compact — ${result.messagesBefore} message(s), nothing old enough to summarize`;
2342
+ }
2343
+ return [
2344
+ `conversation compacted — ${groupDigits(result.messagesBefore)} → ${groupDigits(result.messagesAfter)} messages`,
2345
+ ` estimated context tokens ${groupDigits(result.estimatedTokensBefore)} → ${groupDigits(result.estimatedTokensAfter)}`,
2346
+ ` estimated tokens saved ${groupDigits(result.estimatedTokensSaved)}`,
2347
+ ].join('\n');
2348
+ }
2349
+ /** Explicit locale: the report should read the same on every machine. */
2350
+ function groupDigits(value) {
2351
+ return value.toLocaleString('en-US');
2352
+ }
2353
+ /**
2354
+ * Runs `/effort`, dispatching whatever notice it earns.
2355
+ *
2356
+ * Reporting and setting share one entry point because they share one answer: what
2357
+ * the model is doing now. A bad level changes nothing and says what the levels
2358
+ * are, rather than falling through to the model as a prompt.
2359
+ *
2360
+ * The level is in effect the moment {@link AgentRuntime.changeThinkingEffort}
2361
+ * returns, so — exactly as with an accepted allow-rule — the `~/.darwin/config.json`
2362
+ * write is reported rather than awaited: a failed write means "this session only",
2363
+ * which the user has to be told but must not wait for.
2364
+ */
2365
+ function applyEffortCommand(runtime, text, dispatch) {
2366
+ const argument = text.slice('/effort'.length).trim().toLowerCase();
2367
+ if (argument === '') {
2368
+ dispatch({ type: 'notice', text: `thinking effort: ${describeThinking(runtime.thinking)}` });
2369
+ return;
2370
+ }
2371
+ if (!isThinkingEffort(argument)) {
2372
+ dispatch({
2373
+ type: 'notice',
2374
+ text: `${argument} is not a thinking effort level — expected one of ${THINKING_EFFORTS.join(', ')}\n` +
2375
+ ` thinking effort: ${describeThinking(runtime.thinking)} (unchanged)`,
2376
+ });
2377
+ return;
2378
+ }
2379
+ const { plan, saved } = runtime.changeThinkingEffort(argument);
2380
+ const applied = `thinking effort: ${describeThinking(plan)}`;
2381
+ saved.then(() => {
2382
+ dispatch({ type: 'notice', text: `${applied} — saved to ~/${DARWIN_DIRNAME}/${CONFIG_FILENAME}` });
2383
+ }, (error) => {
2384
+ dispatch({
2385
+ type: 'notice',
2386
+ text: `${applied}, this session only — could not write ` +
2387
+ `~/${DARWIN_DIRNAME}/${CONFIG_FILENAME}: ${error instanceof Error ? error.message : String(error)}`,
2388
+ // The level is live already; only its persistence degraded.
2389
+ severity: 'warn',
2390
+ });
2391
+ });
2392
+ }
2393
+ /**
2394
+ * Runs `/mode`, dispatching whatever notice it earns.
2395
+ *
2396
+ * Reporting and switching share one entry point, like `/effort` and `/model`: both
2397
+ * answer "what is being enforced right now". An unusable argument changes nothing,
2398
+ * names the valid modes, and never falls through to the model as a prompt.
2399
+ *
2400
+ * Nothing is awaited and nothing is written: this is session-scoped state by
2401
+ * design, so — unlike `/effort` and `/model` — there is no "saved to …" half of the
2402
+ * report. The notice says so, because a user who has met the other two commands
2403
+ * will otherwise assume the mode is remembered.
2404
+ */
2405
+ function applyModeCommand(runtime, text, dispatch) {
2406
+ const argument = text.slice('/mode'.length).trim().toLowerCase();
2407
+ const available = ` available: ${APPROVAL_MODES.join(', ')} · /mode <name> switches for this session only`;
2408
+ if (argument === '') {
2409
+ dispatch({
2410
+ type: 'notice',
2411
+ text: `permission mode: ${describeApprovalMode(runtime.permissionMode)}\n${available}`,
2412
+ });
2413
+ return;
2414
+ }
2415
+ if (!isApprovalMode(argument)) {
2416
+ dispatch({
2417
+ type: 'notice',
2418
+ text: `${argument} is not a permission mode — expected one of ${APPROVAL_MODES.join(', ')}\n` +
2419
+ ` permission mode: ${describeApprovalMode(runtime.permissionMode)} (unchanged)`,
2420
+ });
2421
+ return;
2422
+ }
2423
+ const change = runtime.changePermissionMode(argument);
2424
+ if (change.previous === change.mode) {
2425
+ dispatch({
2426
+ type: 'notice',
2427
+ text: `already in ${change.mode} mode — ${describeApprovalMode(change.mode)}\n${available}`,
2428
+ });
2429
+ return;
2430
+ }
2431
+ // The withdrawal line is the visible half of the in-flight contract: a prompt
2432
+ // that vanished or a classifier check that was abandoned must be accounted for,
2433
+ // or the user is left wondering which mode answered their question.
2434
+ const withdrawn = change.withdrawn === 0
2435
+ ? ''
2436
+ : `\n ${change.withdrawn} pending tool decision(s) withdrawn and re-decided under ${change.mode}`;
2437
+ dispatch({
2438
+ type: 'notice',
2439
+ text: `permission mode: ${describeApprovalMode(change.mode)} (was ${change.previous})${withdrawn}\n` +
2440
+ ` this session only — ~/${DARWIN_DIRNAME}/${CONFIG_FILENAME} is unchanged`,
2441
+ // Widening enforcement is a warning, exactly as the header colours yolo.
2442
+ ...(change.mode === 'yolo' ? { severity: 'warn' } : {}),
2443
+ });
2444
+ }
2445
+ /**
2446
+ * The `/permissions` listing: every live allow-rule, numbered, with its origin.
2447
+ *
2448
+ * Origin is stated per rule because the two kinds answer different questions —
2449
+ * a `configured` rule was a deliberate entry in the project's permission-rules
2450
+ * file, a `granted this session` rule is minutes old and the more likely
2451
+ * revocation target. Exported for the free spike, like `formatUsageReport`.
2452
+ */
2453
+ export function formatPermissionRulesReport(entries, rulesFile) {
2454
+ if (entries.length === 0) {
2455
+ return ('no allow-rules in effect — every non-safe call asks\n' +
2456
+ ` rules come from the permission prompt\u2019s "always allow" options, or from ${rulesFile}`);
2457
+ }
2458
+ const rows = entries.map((entry, index) => ` ${index + 1}. ${entry.rule} — ${entry.origin === 'configured' ? 'configured' : 'granted this session'}`);
2459
+ return [
2460
+ `allow-rules in effect (${entries.length}) — configured rules load from ${rulesFile}`,
2461
+ ...rows,
2462
+ ' /permissions revoke <n|rule|all> revokes; new rules come only from the permission prompt',
2463
+ ].join('\n');
2464
+ }
2465
+ /**
2466
+ * Runs `/permissions`, dispatching whatever notice it earns.
2467
+ *
2468
+ * Listing and revoking share one entry point, like `/mode`: both answer "what
2469
+ * runs without asking right now". This command can only ever *narrow*: there is
2470
+ * no argument form that adds or rewrites a rule, so a parsing bug costs an
2471
+ * unrevoked rule (visible in the listing) or an extra prompt, never a widening.
2472
+ *
2473
+ * Revocation takes effect on the gate synchronously — the very next matching
2474
+ * tool call prompts again — and the file write is reported rather than awaited,
2475
+ * exactly like the grant flow: a failed write means the rule is gone for this
2476
+ * session but will load again next process, and the notice says so.
2477
+ */
2478
+ export function applyPermissionsCommand(runtime, text, dispatch) {
2479
+ const argument = text.slice('/permissions'.length).trim();
2480
+ const usage = 'usage: /permissions — list allow-rules · /permissions revoke <n|rule|all>';
2481
+ if (argument === '') {
2482
+ dispatch({
2483
+ type: 'notice',
2484
+ text: formatPermissionRulesReport(runtime.listAllowRules(), runtime.info.permissionRulesPath),
2485
+ });
2486
+ return;
2487
+ }
2488
+ const separator = argument.search(/\s/);
2489
+ const verb = separator === -1 ? argument : argument.slice(0, separator);
2490
+ // The verb is case-insensitive; the target never is, because rules are exact
2491
+ // strings and `bash:PNPM *` is not `bash:pnpm *`.
2492
+ const target = separator === -1 ? '' : argument.slice(separator).trim();
2493
+ if (verb.toLowerCase() !== 'revoke') {
2494
+ dispatch({ type: 'notice', text: `${verb} is not a /permissions subcommand\n ${usage}` });
2495
+ return;
2496
+ }
2497
+ if (target === '') {
2498
+ dispatch({ type: 'notice', text: `revoke needs a target\n ${usage}` });
2499
+ return;
2500
+ }
2501
+ const entries = runtime.listAllowRules();
2502
+ let targets;
2503
+ if (target.toLowerCase() === 'all') {
2504
+ targets = entries.map((entry) => entry.rule);
2505
+ if (targets.length === 0) {
2506
+ dispatch({ type: 'notice', text: 'no allow-rules in effect — nothing to revoke' });
2507
+ return;
2508
+ }
2509
+ }
2510
+ else {
2511
+ // An index from the listing, or the exact rule string. Index wins for a
2512
+ // purely numeric target: rules carry a tool name, so none is all digits.
2513
+ const index = /^\d+$/.test(target) ? Number(target) : undefined;
2514
+ const chosen = index !== undefined ? entries[index - 1] : entries.find((entry) => entry.rule === target);
2515
+ if (chosen === undefined) {
2516
+ dispatch({
2517
+ type: 'notice',
2518
+ text: `${target} matches no live allow-rule — nothing revoked\n /permissions lists them with their numbers`,
2519
+ });
2520
+ return;
2521
+ }
2522
+ targets = [chosen.rule];
2523
+ }
2524
+ const { removed, saved } = runtime.revokeAllowRules(targets);
2525
+ const headline = removed.length === 1
2526
+ ? `revoked ${removed[0]} — the next matching call will ask again`
2527
+ : `revoked ${removed.length} allow-rules — the next matching calls will ask again`;
2528
+ saved.then(() => {
2529
+ dispatch({ type: 'notice', text: `${headline}\n removed from ${runtime.info.permissionRulesPath}` });
2530
+ }, (error) => {
2531
+ dispatch({
2532
+ type: 'notice',
2533
+ text: `${headline}, but this session only — could not write ` +
2534
+ `${runtime.info.permissionRulesPath}: ${error instanceof Error ? error.message : String(error)}\n` +
2535
+ ' a fresh process will load the rule again',
2536
+ // The gate already stopped honouring it; only the file lost out.
2537
+ severity: 'warn',
2538
+ });
2539
+ });
2540
+ }
2541
+ /** One line covering both what was asked for and what the model will actually do. */
2542
+ function describeThinking(plan) {
2543
+ if (plan.problem !== undefined)
2544
+ return `${plan.requested} — ${plan.problem}`;
2545
+ return plan.requested;
2546
+ }
2547
+ /**
2548
+ * Runs `/model`, dispatching whatever notice it earns.
2549
+ *
2550
+ * Listing and switching share one entry point for the same reason `/effort` does:
2551
+ * both answer "which model am I talking to". An unresolvable argument changes
2552
+ * nothing and prints the list, rather than falling through to the model as a
2553
+ * prompt — a mistyped model name is not a question worth paying for.
2554
+ *
2555
+ * The switch is awaited (building a model can need a dynamic import) but the
2556
+ * `~/.darwin/config.json` write is not, exactly as with `/effort` and an accepted
2557
+ * allow-rule: a failed write means "this session only", which must be reported and
2558
+ * must not be waited for.
2559
+ */
2560
+ async function applyModelCommand(runtime, text, dispatch) {
2561
+ const argument = text.slice('/model'.length).trim();
2562
+ const choices = runtime.modelChoices;
2563
+ if (argument === '') {
2564
+ dispatch({ type: 'notice', text: formatModelList(choices) });
2565
+ return;
2566
+ }
2567
+ const target = resolveModelChoice(choices, argument);
2568
+ if (target === undefined) {
2569
+ dispatch({
2570
+ type: 'notice',
2571
+ text: `no configured model matches ${JSON.stringify(argument)}\n${formatModelList(choices)}`,
2572
+ });
2573
+ return;
2574
+ }
2575
+ if (target === 'ambiguous') {
2576
+ dispatch({
2577
+ type: 'notice',
2578
+ text: `${JSON.stringify(argument)} matches more than one model — be more specific\n${formatModelList(choices)}`,
2579
+ });
2580
+ return;
2581
+ }
2582
+ if (target.enabled) {
2583
+ dispatch({ type: 'notice', text: `already on ${target.name}\n${formatModelList(choices)}` });
2584
+ return;
2585
+ }
2586
+ let result;
2587
+ try {
2588
+ result = await runtime.changeModel(target);
2589
+ }
2590
+ catch (error) {
2591
+ // The session is still on the old model — changeModel builds before it swaps —
2592
+ // so this is a report, not a broken state.
2593
+ dispatch({
2594
+ type: 'notice',
2595
+ text: `could not switch to ${target.name}: ${error instanceof Error ? error.message : String(error)}\n` +
2596
+ ` still on ${describeChoice(choices.find((choice) => choice.enabled))}`,
2597
+ severity: 'error',
2598
+ });
2599
+ return;
2600
+ }
2601
+ const applied = `model: ${describeChoice(result.choice)}\n` +
2602
+ ` thinking effort: ${describeThinking(result.thinking)}\n` +
2603
+ ` prompt cache: ${formatPromptCacheState(result.promptCache)}`;
2604
+ result.saved.then(() => {
2605
+ dispatch({ type: 'notice', text: `${applied}\n saved to ~/${DARWIN_DIRNAME}/${CONFIG_FILENAME}` });
2606
+ }, (error) => {
2607
+ dispatch({
2608
+ type: 'notice',
2609
+ text: `${applied}\n this session only — could not write ` +
2610
+ `~/${DARWIN_DIRNAME}/${CONFIG_FILENAME}: ${error instanceof Error ? error.message : String(error)}`,
2611
+ // The switch already happened; only its persistence degraded.
2612
+ severity: 'warn',
2613
+ });
2614
+ });
2615
+ }
2616
+ /** The catalogue, one row each, with the live entry marked. */
2617
+ function formatModelList(choices) {
2618
+ const rows = choices.map((choice) => ` ${choice.enabled ? '*' : ' '} ${choice.index + 1}. ${describeChoice(choice)}`);
2619
+ return [
2620
+ choices.length === 1 ? 'one model configured:' : `${choices.length} models configured:`,
2621
+ ...rows,
2622
+ ...(choices.length === 1
2623
+ ? [` add a "models" array to ~/${DARWIN_DIRNAME}/${CONFIG_FILENAME} to switch between several`]
2624
+ : [' switch with /model <number|name>']),
2625
+ ].join('\n');
2626
+ }
2627
+ /** `name (provider/model-id)`, collapsing the name when it is the model id. */
2628
+ function describeChoice(choice) {
2629
+ const { name, fields } = choice;
2630
+ const target = `${fields.provider}/${fields.model}`;
2631
+ return name === fields.model ? target : `${name} (${target})`;
2632
+ }
2633
+ /**
2634
+ * Resolves a `/model` argument to a choice: a 1-based position, an exact name, or
2635
+ * a unique case-insensitive substring of either the name or the model id.
2636
+ *
2637
+ * Three ways rather than one because the same list is addressed by eye ("2"), by
2638
+ * habit ("sol") and by paste ("openai.gpt-5.6-sol"). A substring that matches
2639
+ * several entries returns `'ambiguous'` instead of the first hit: picking one
2640
+ * would switch to a model the user did not name.
2641
+ *
2642
+ * An all-digits argument is *only* ever a position — never a substring. Falling
2643
+ * through would let `/model 4` land on `claude-sonnet-4-6` because its id happens
2644
+ * to contain a 4, which is the worst kind of match: plausible, silent and wrong.
2645
+ */
2646
+ export function resolveModelChoice(choices, argument) {
2647
+ const needle = argument.toLowerCase();
2648
+ if (/^\d+$/.test(argument)) {
2649
+ const position = Number(argument);
2650
+ return position >= 1 && position <= choices.length ? choices[position - 1] : undefined;
2651
+ }
2652
+ const exact = choices.filter((choice) => choice.name.toLowerCase() === needle);
2653
+ if (exact.length === 1)
2654
+ return exact[0];
2655
+ const partial = choices.filter((choice) => choice.name.toLowerCase().includes(needle) || choice.fields.model.toLowerCase().includes(needle));
2656
+ if (partial.length === 1)
2657
+ return partial[0];
2658
+ return partial.length > 1 ? 'ambiguous' : undefined;
2659
+ }
2660
+ //# sourceMappingURL=App.js.map