koro-ai 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (670) hide show
  1. package/AGENTS.md +69 -0
  2. package/BUN_SHELL_MIGRATION_PLAN.md +136 -0
  3. package/Dockerfile +18 -0
  4. package/README.md +15 -0
  5. package/bin/koro +16 -0
  6. package/bin/opencode +179 -0
  7. package/bunfig.toml +7 -0
  8. package/drizzle.config.ts +10 -0
  9. package/git +0 -0
  10. package/migration/20260127222353_familiar_lady_ursula/migration.sql +90 -0
  11. package/migration/20260127222353_familiar_lady_ursula/snapshot.json +796 -0
  12. package/migration/20260211171708_add_project_commands/migration.sql +1 -0
  13. package/migration/20260211171708_add_project_commands/snapshot.json +806 -0
  14. package/migration/20260213144116_wakeful_the_professor/migration.sql +11 -0
  15. package/migration/20260213144116_wakeful_the_professor/snapshot.json +897 -0
  16. package/migration/20260225215848_workspace/migration.sql +7 -0
  17. package/migration/20260225215848_workspace/snapshot.json +959 -0
  18. package/migration/20260227213759_add_session_workspace_id/migration.sql +2 -0
  19. package/migration/20260227213759_add_session_workspace_id/snapshot.json +983 -0
  20. package/migration/20260228203230_blue_harpoon/migration.sql +17 -0
  21. package/migration/20260228203230_blue_harpoon/snapshot.json +1102 -0
  22. package/migration/20260303231226_add_workspace_fields/migration.sql +5 -0
  23. package/migration/20260303231226_add_workspace_fields/snapshot.json +1013 -0
  24. package/migration/20260309230000_move_org_to_state/migration.sql +3 -0
  25. package/migration/20260309230000_move_org_to_state/snapshot.json +1156 -0
  26. package/migration/20260312043431_session_message_cursor/migration.sql +4 -0
  27. package/migration/20260312043431_session_message_cursor/snapshot.json +1168 -0
  28. package/migration/20260323234822_events/migration.sql +13 -0
  29. package/migration/20260323234822_events/snapshot.json +1271 -0
  30. package/package.json +163 -0
  31. package/parsers-config.ts +290 -0
  32. package/script/build-node.ts +56 -0
  33. package/script/build.ts +276 -0
  34. package/script/check-migrations.ts +16 -0
  35. package/script/postinstall.mjs +131 -0
  36. package/script/publish.ts +181 -0
  37. package/script/schema.ts +63 -0
  38. package/script/seed-e2e.ts +60 -0
  39. package/script/upgrade-opentui.ts +64 -0
  40. package/specs/effect-migration.md +294 -0
  41. package/specs/tui-plugins.md +436 -0
  42. package/src/account/account.sql.ts +39 -0
  43. package/src/account/index.ts +424 -0
  44. package/src/account/repo.ts +163 -0
  45. package/src/account/schema.ts +91 -0
  46. package/src/acp/README.md +174 -0
  47. package/src/acp/agent.ts +1763 -0
  48. package/src/acp/session.ts +116 -0
  49. package/src/acp/types.ts +24 -0
  50. package/src/agent/agent.ts +476 -0
  51. package/src/agent/generate.txt +75 -0
  52. package/src/agent/prompt/compaction.txt +15 -0
  53. package/src/agent/prompt/explore.txt +18 -0
  54. package/src/agent/prompt/summary.txt +11 -0
  55. package/src/agent/prompt/title.txt +44 -0
  56. package/src/auth/index.ts +109 -0
  57. package/src/bus/bus-event.ts +40 -0
  58. package/src/bus/global.ts +10 -0
  59. package/src/bus/index.ts +185 -0
  60. package/src/cli/bootstrap.ts +17 -0
  61. package/src/cli/cmd/account.ts +257 -0
  62. package/src/cli/cmd/acp.ts +70 -0
  63. package/src/cli/cmd/agent.ts +245 -0
  64. package/src/cli/cmd/cmd.ts +7 -0
  65. package/src/cli/cmd/db.ts +119 -0
  66. package/src/cli/cmd/debug/agent.ts +167 -0
  67. package/src/cli/cmd/debug/config.ts +16 -0
  68. package/src/cli/cmd/debug/file.ts +97 -0
  69. package/src/cli/cmd/debug/index.ts +48 -0
  70. package/src/cli/cmd/debug/lsp.ts +53 -0
  71. package/src/cli/cmd/debug/ripgrep.ts +87 -0
  72. package/src/cli/cmd/debug/scrap.ts +16 -0
  73. package/src/cli/cmd/debug/skill.ts +16 -0
  74. package/src/cli/cmd/debug/snapshot.ts +52 -0
  75. package/src/cli/cmd/export.ts +89 -0
  76. package/src/cli/cmd/generate.ts +38 -0
  77. package/src/cli/cmd/github.ts +1646 -0
  78. package/src/cli/cmd/import.ts +207 -0
  79. package/src/cli/cmd/mcp.ts +754 -0
  80. package/src/cli/cmd/models.ts +78 -0
  81. package/src/cli/cmd/plug.ts +233 -0
  82. package/src/cli/cmd/pr.ts +127 -0
  83. package/src/cli/cmd/providers.ts +478 -0
  84. package/src/cli/cmd/run.ts +676 -0
  85. package/src/cli/cmd/serve.ts +24 -0
  86. package/src/cli/cmd/session.ts +159 -0
  87. package/src/cli/cmd/stats.ts +410 -0
  88. package/src/cli/cmd/tui/app.tsx +919 -0
  89. package/src/cli/cmd/tui/attach.ts +88 -0
  90. package/src/cli/cmd/tui/component/border.tsx +21 -0
  91. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  92. package/src/cli/cmd/tui/component/dialog-command.tsx +171 -0
  93. package/src/cli/cmd/tui/component/dialog-import-share.tsx +118 -0
  94. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  95. package/src/cli/cmd/tui/component/dialog-model.tsx +179 -0
  96. package/src/cli/cmd/tui/component/dialog-provider.tsx +329 -0
  97. package/src/cli/cmd/tui/component/dialog-session-list.tsx +108 -0
  98. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  99. package/src/cli/cmd/tui/component/dialog-skill.tsx +36 -0
  100. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  101. package/src/cli/cmd/tui/component/dialog-status.tsx +168 -0
  102. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  103. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  104. package/src/cli/cmd/tui/component/dialog-variant.tsx +39 -0
  105. package/src/cli/cmd/tui/component/dialog-workspace-list.tsx +320 -0
  106. package/src/cli/cmd/tui/component/error-component.tsx +92 -0
  107. package/src/cli/cmd/tui/component/logo.tsx +85 -0
  108. package/src/cli/cmd/tui/component/plugin-route-missing.tsx +14 -0
  109. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +672 -0
  110. package/src/cli/cmd/tui/component/prompt/frecency.tsx +90 -0
  111. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  112. package/src/cli/cmd/tui/component/prompt/index.tsx +1310 -0
  113. package/src/cli/cmd/tui/component/prompt/part.ts +16 -0
  114. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  115. package/src/cli/cmd/tui/component/spinner.tsx +24 -0
  116. package/src/cli/cmd/tui/component/startup-loading.tsx +63 -0
  117. package/src/cli/cmd/tui/component/task-panel.tsx +44 -0
  118. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  119. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  120. package/src/cli/cmd/tui/component/token-bar.tsx +60 -0
  121. package/src/cli/cmd/tui/component/workspace/dialog-session-list.tsx +151 -0
  122. package/src/cli/cmd/tui/context/args.tsx +15 -0
  123. package/src/cli/cmd/tui/context/directory.ts +13 -0
  124. package/src/cli/cmd/tui/context/exit.tsx +60 -0
  125. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  126. package/src/cli/cmd/tui/context/keybind.tsx +105 -0
  127. package/src/cli/cmd/tui/context/kv.tsx +52 -0
  128. package/src/cli/cmd/tui/context/local.tsx +412 -0
  129. package/src/cli/cmd/tui/context/plugin-keybinds.ts +41 -0
  130. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  131. package/src/cli/cmd/tui/context/route.tsx +52 -0
  132. package/src/cli/cmd/tui/context/sdk.tsx +128 -0
  133. package/src/cli/cmd/tui/context/sync.tsx +504 -0
  134. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  135. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  136. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  137. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  138. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  139. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  140. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  141. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  142. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  143. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  144. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  145. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  146. package/src/cli/cmd/tui/context/theme/gruvbox.json +242 -0
  147. package/src/cli/cmd/tui/context/theme/gtr.json +245 -0
  148. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  149. package/src/cli/cmd/tui/context/theme/koro.json +241 -0
  150. package/src/cli/cmd/tui/context/theme/lucent-orng.json +237 -0
  151. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  152. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  153. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  154. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  155. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  156. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  157. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  158. package/src/cli/cmd/tui/context/theme/opencode.json +245 -0
  159. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  160. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  161. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  162. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  163. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  164. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  165. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  166. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  167. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  168. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  169. package/src/cli/cmd/tui/context/theme.tsx +1240 -0
  170. package/src/cli/cmd/tui/context/tui-config.tsx +9 -0
  171. package/src/cli/cmd/tui/event.ts +49 -0
  172. package/src/cli/cmd/tui/feature-plugins/home/footer.tsx +93 -0
  173. package/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx +152 -0
  174. package/src/cli/cmd/tui/feature-plugins/home/tips.tsx +50 -0
  175. package/src/cli/cmd/tui/feature-plugins/sidebar/context.tsx +63 -0
  176. package/src/cli/cmd/tui/feature-plugins/sidebar/files.tsx +62 -0
  177. package/src/cli/cmd/tui/feature-plugins/sidebar/footer.tsx +93 -0
  178. package/src/cli/cmd/tui/feature-plugins/sidebar/lsp.tsx +66 -0
  179. package/src/cli/cmd/tui/feature-plugins/sidebar/mcp.tsx +96 -0
  180. package/src/cli/cmd/tui/feature-plugins/sidebar/todo.tsx +48 -0
  181. package/src/cli/cmd/tui/feature-plugins/system/plugins.tsx +270 -0
  182. package/src/cli/cmd/tui/plugin/api.tsx +430 -0
  183. package/src/cli/cmd/tui/plugin/index.ts +3 -0
  184. package/src/cli/cmd/tui/plugin/internal.ts +27 -0
  185. package/src/cli/cmd/tui/plugin/runtime.ts +1033 -0
  186. package/src/cli/cmd/tui/plugin/slots.tsx +60 -0
  187. package/src/cli/cmd/tui/routes/home.tsx +84 -0
  188. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +65 -0
  189. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +110 -0
  190. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  191. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  192. package/src/cli/cmd/tui/routes/session/footer.tsx +93 -0
  193. package/src/cli/cmd/tui/routes/session/index.tsx +2270 -0
  194. package/src/cli/cmd/tui/routes/session/permission.tsx +691 -0
  195. package/src/cli/cmd/tui/routes/session/question.tsx +468 -0
  196. package/src/cli/cmd/tui/routes/session/sidebar.tsx +74 -0
  197. package/src/cli/cmd/tui/routes/session/subagent-footer.tsx +131 -0
  198. package/src/cli/cmd/tui/thread.ts +232 -0
  199. package/src/cli/cmd/tui/ui/dialog-alert.tsx +59 -0
  200. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +89 -0
  201. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +211 -0
  202. package/src/cli/cmd/tui/ui/dialog-help.tsx +40 -0
  203. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +130 -0
  204. package/src/cli/cmd/tui/ui/dialog-select.tsx +409 -0
  205. package/src/cli/cmd/tui/ui/dialog.tsx +192 -0
  206. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  207. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  208. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  209. package/src/cli/cmd/tui/util/clipboard.ts +192 -0
  210. package/src/cli/cmd/tui/util/editor.ts +37 -0
  211. package/src/cli/cmd/tui/util/model.ts +23 -0
  212. package/src/cli/cmd/tui/util/scroll.ts +23 -0
  213. package/src/cli/cmd/tui/util/selection.ts +25 -0
  214. package/src/cli/cmd/tui/util/signal.ts +7 -0
  215. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  216. package/src/cli/cmd/tui/util/transcript.ts +112 -0
  217. package/src/cli/cmd/tui/win32.ts +129 -0
  218. package/src/cli/cmd/tui/worker.ts +175 -0
  219. package/src/cli/cmd/uninstall.ts +353 -0
  220. package/src/cli/cmd/upgrade.ts +73 -0
  221. package/src/cli/cmd/web.ts +81 -0
  222. package/src/cli/effect/prompt.ts +25 -0
  223. package/src/cli/error.ts +46 -0
  224. package/src/cli/heap.ts +59 -0
  225. package/src/cli/logo.ts +14 -0
  226. package/src/cli/network.ts +60 -0
  227. package/src/cli/ui.ts +133 -0
  228. package/src/cli/upgrade.ts +31 -0
  229. package/src/command/index.ts +195 -0
  230. package/src/command/template/initialize.txt +66 -0
  231. package/src/command/template/review.txt +101 -0
  232. package/src/config/config.ts +1591 -0
  233. package/src/config/markdown.ts +99 -0
  234. package/src/config/paths.ts +181 -0
  235. package/src/config/tui-migrate.ts +155 -0
  236. package/src/config/tui-schema.ts +36 -0
  237. package/src/config/tui.ts +171 -0
  238. package/src/control-plane/adaptors/index.ts +20 -0
  239. package/src/control-plane/adaptors/worktree.ts +38 -0
  240. package/src/control-plane/schema.ts +17 -0
  241. package/src/control-plane/sse.ts +66 -0
  242. package/src/control-plane/types.ts +21 -0
  243. package/src/control-plane/workspace.sql.ts +17 -0
  244. package/src/control-plane/workspace.ts +154 -0
  245. package/src/effect/cross-spawn-spawner.ts +502 -0
  246. package/src/effect/instance-ref.ts +6 -0
  247. package/src/effect/instance-registry.ts +12 -0
  248. package/src/effect/instance-state.ts +82 -0
  249. package/src/effect/run-service.ts +33 -0
  250. package/src/effect/runner.ts +216 -0
  251. package/src/env/index.ts +28 -0
  252. package/src/file/ignore.ts +82 -0
  253. package/src/file/index.ts +686 -0
  254. package/src/file/protected.ts +59 -0
  255. package/src/file/ripgrep.ts +376 -0
  256. package/src/file/time.ts +133 -0
  257. package/src/file/watcher.ts +171 -0
  258. package/src/filesystem/index.ts +226 -0
  259. package/src/flag/flag.ts +155 -0
  260. package/src/format/formatter.ts +413 -0
  261. package/src/format/index.ts +203 -0
  262. package/src/git/index.ts +303 -0
  263. package/src/global/index.ts +161 -0
  264. package/src/id/id.ts +85 -0
  265. package/src/ide/index.ts +74 -0
  266. package/src/index.ts +240 -0
  267. package/src/installation/index.ts +355 -0
  268. package/src/installation/meta.ts +7 -0
  269. package/src/lsp/client.ts +252 -0
  270. package/src/lsp/index.ts +558 -0
  271. package/src/lsp/language.ts +120 -0
  272. package/src/lsp/launch.ts +21 -0
  273. package/src/lsp/server.ts +1958 -0
  274. package/src/mcp/auth.ts +173 -0
  275. package/src/mcp/index.ts +921 -0
  276. package/src/mcp/oauth-callback.ts +215 -0
  277. package/src/mcp/oauth-provider.ts +185 -0
  278. package/src/memory/index.ts +117 -0
  279. package/src/node.ts +1 -0
  280. package/src/npm/index.ts +180 -0
  281. package/src/orchestrator/agent-registry.ts +38 -0
  282. package/src/orchestrator/conflict.ts +25 -0
  283. package/src/orchestrator/context-manager.ts +22 -0
  284. package/src/orchestrator/index.ts +9 -0
  285. package/src/orchestrator/scheduler.ts +30 -0
  286. package/src/orchestrator/state-tracker.ts +71 -0
  287. package/src/orchestrator/task-manager.ts +69 -0
  288. package/src/patch/index.ts +680 -0
  289. package/src/permission/arity.ts +163 -0
  290. package/src/permission/evaluate.ts +15 -0
  291. package/src/permission/index.ts +325 -0
  292. package/src/permission/schema.ts +17 -0
  293. package/src/plugin/codex.ts +596 -0
  294. package/src/plugin/github-copilot/copilot.ts +353 -0
  295. package/src/plugin/github-copilot/models.ts +144 -0
  296. package/src/plugin/index.ts +281 -0
  297. package/src/plugin/install.ts +439 -0
  298. package/src/plugin/loader.ts +174 -0
  299. package/src/plugin/meta.ts +188 -0
  300. package/src/plugin/shared.ts +307 -0
  301. package/src/project/bootstrap.ts +31 -0
  302. package/src/project/instance.ts +175 -0
  303. package/src/project/project.sql.ts +16 -0
  304. package/src/project/project.ts +519 -0
  305. package/src/project/schema.ts +16 -0
  306. package/src/project/state.ts +70 -0
  307. package/src/project/vcs.ts +240 -0
  308. package/src/provider/auth.ts +253 -0
  309. package/src/provider/error.ts +197 -0
  310. package/src/provider/models-snapshot.ts +60410 -0
  311. package/src/provider/models.ts +162 -0
  312. package/src/provider/provider.ts +1677 -0
  313. package/src/provider/schema.ts +38 -0
  314. package/src/provider/sdk/copilot/README.md +5 -0
  315. package/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  316. package/src/provider/sdk/copilot/chat/get-response-metadata.ts +15 -0
  317. package/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  318. package/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +64 -0
  319. package/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  320. package/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +28 -0
  321. package/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  322. package/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  323. package/src/provider/sdk/copilot/copilot-provider.ts +100 -0
  324. package/src/provider/sdk/copilot/index.ts +2 -0
  325. package/src/provider/sdk/copilot/openai-compatible-error.ts +27 -0
  326. package/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  327. package/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  328. package/src/provider/sdk/copilot/responses/openai-config.ts +18 -0
  329. package/src/provider/sdk/copilot/responses/openai-error.ts +22 -0
  330. package/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  331. package/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +1769 -0
  332. package/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  333. package/src/provider/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  334. package/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  335. package/src/provider/sdk/copilot/responses/tool/file-search.ts +127 -0
  336. package/src/provider/sdk/copilot/responses/tool/image-generation.ts +114 -0
  337. package/src/provider/sdk/copilot/responses/tool/local-shell.ts +64 -0
  338. package/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  339. package/src/provider/sdk/copilot/responses/tool/web-search.ts +102 -0
  340. package/src/provider/transform.ts +1046 -0
  341. package/src/pty/index.ts +401 -0
  342. package/src/pty/schema.ts +17 -0
  343. package/src/question/index.ts +224 -0
  344. package/src/question/schema.ts +17 -0
  345. package/src/server/error.ts +36 -0
  346. package/src/server/event.ts +7 -0
  347. package/src/server/instance.ts +314 -0
  348. package/src/server/mdns.ts +60 -0
  349. package/src/server/middleware.ts +33 -0
  350. package/src/server/projectors.ts +28 -0
  351. package/src/server/router.ts +99 -0
  352. package/src/server/routes/config.ts +92 -0
  353. package/src/server/routes/event.ts +83 -0
  354. package/src/server/routes/experimental.ts +271 -0
  355. package/src/server/routes/file.ts +197 -0
  356. package/src/server/routes/global.ts +312 -0
  357. package/src/server/routes/mcp.ts +225 -0
  358. package/src/server/routes/permission.ts +69 -0
  359. package/src/server/routes/project.ts +118 -0
  360. package/src/server/routes/provider.ts +171 -0
  361. package/src/server/routes/pty.ts +211 -0
  362. package/src/server/routes/question.ts +99 -0
  363. package/src/server/routes/session.ts +1031 -0
  364. package/src/server/routes/tui.ts +379 -0
  365. package/src/server/routes/workspace.ts +94 -0
  366. package/src/server/server.ts +312 -0
  367. package/src/session/compaction.ts +428 -0
  368. package/src/session/index.ts +887 -0
  369. package/src/session/instruction.ts +258 -0
  370. package/src/session/llm.ts +370 -0
  371. package/src/session/message-v2.ts +1031 -0
  372. package/src/session/message.ts +191 -0
  373. package/src/session/overflow.ts +22 -0
  374. package/src/session/processor.ts +523 -0
  375. package/src/session/projectors.ts +135 -0
  376. package/src/session/prompt/anthropic.txt +105 -0
  377. package/src/session/prompt/beast.txt +147 -0
  378. package/src/session/prompt/build-switch.txt +5 -0
  379. package/src/session/prompt/codex.txt +79 -0
  380. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  381. package/src/session/prompt/default.txt +105 -0
  382. package/src/session/prompt/gemini.txt +155 -0
  383. package/src/session/prompt/gpt.txt +107 -0
  384. package/src/session/prompt/kimi.txt +114 -0
  385. package/src/session/prompt/max-steps.txt +16 -0
  386. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  387. package/src/session/prompt/plan.txt +26 -0
  388. package/src/session/prompt/trinity.txt +97 -0
  389. package/src/session/prompt.ts +1908 -0
  390. package/src/session/retry.ts +106 -0
  391. package/src/session/revert.ts +176 -0
  392. package/src/session/schema.ts +38 -0
  393. package/src/session/session.sql.ts +103 -0
  394. package/src/session/status.ts +102 -0
  395. package/src/session/summary.ts +177 -0
  396. package/src/session/system.ts +76 -0
  397. package/src/session/todo.ts +95 -0
  398. package/src/share/share-next.ts +369 -0
  399. package/src/share/share.sql.ts +13 -0
  400. package/src/shell/shell.ts +110 -0
  401. package/src/skill/discovery.ts +116 -0
  402. package/src/skill/index.ts +277 -0
  403. package/src/snapshot/index.ts +571 -0
  404. package/src/sql.d.ts +4 -0
  405. package/src/storage/db.bun.ts +8 -0
  406. package/src/storage/db.node.ts +8 -0
  407. package/src/storage/db.ts +174 -0
  408. package/src/storage/json-migration.ts +425 -0
  409. package/src/storage/schema.sql.ts +10 -0
  410. package/src/storage/schema.ts +5 -0
  411. package/src/storage/storage.ts +353 -0
  412. package/src/sync/README.md +179 -0
  413. package/src/sync/event.sql.ts +16 -0
  414. package/src/sync/index.ts +263 -0
  415. package/src/sync/schema.ts +14 -0
  416. package/src/token/index.ts +77 -0
  417. package/src/tool/apply_patch.ts +281 -0
  418. package/src/tool/apply_patch.txt +33 -0
  419. package/src/tool/bash.ts +496 -0
  420. package/src/tool/bash.txt +117 -0
  421. package/src/tool/batch.ts +183 -0
  422. package/src/tool/batch.txt +24 -0
  423. package/src/tool/codesearch.ts +132 -0
  424. package/src/tool/codesearch.txt +12 -0
  425. package/src/tool/edit.ts +667 -0
  426. package/src/tool/edit.txt +10 -0
  427. package/src/tool/external-directory.ts +37 -0
  428. package/src/tool/glob.ts +78 -0
  429. package/src/tool/glob.txt +6 -0
  430. package/src/tool/grep.ts +156 -0
  431. package/src/tool/grep.txt +8 -0
  432. package/src/tool/invalid.ts +17 -0
  433. package/src/tool/ls.ts +121 -0
  434. package/src/tool/ls.txt +1 -0
  435. package/src/tool/lsp.ts +97 -0
  436. package/src/tool/lsp.txt +19 -0
  437. package/src/tool/multiedit.ts +46 -0
  438. package/src/tool/multiedit.txt +41 -0
  439. package/src/tool/plan-enter.txt +14 -0
  440. package/src/tool/plan-exit.txt +13 -0
  441. package/src/tool/plan.ts +131 -0
  442. package/src/tool/question.ts +46 -0
  443. package/src/tool/question.txt +10 -0
  444. package/src/tool/read.ts +296 -0
  445. package/src/tool/read.txt +14 -0
  446. package/src/tool/registry.ts +248 -0
  447. package/src/tool/schema.ts +17 -0
  448. package/src/tool/skill.ts +105 -0
  449. package/src/tool/task.ts +166 -0
  450. package/src/tool/task.txt +60 -0
  451. package/src/tool/todo.ts +48 -0
  452. package/src/tool/todowrite.txt +167 -0
  453. package/src/tool/tool.ts +112 -0
  454. package/src/tool/truncate.ts +144 -0
  455. package/src/tool/truncation-dir.ts +4 -0
  456. package/src/tool/webfetch.ts +206 -0
  457. package/src/tool/webfetch.txt +13 -0
  458. package/src/tool/websearch.ts +150 -0
  459. package/src/tool/websearch.txt +14 -0
  460. package/src/tool/write.ts +84 -0
  461. package/src/tool/write.txt +8 -0
  462. package/src/util/abort.ts +35 -0
  463. package/src/util/archive.ts +17 -0
  464. package/src/util/color.ts +19 -0
  465. package/src/util/context.ts +25 -0
  466. package/src/util/data-url.ts +9 -0
  467. package/src/util/defer.ts +12 -0
  468. package/src/util/effect-http-client.ts +11 -0
  469. package/src/util/effect-zod.ts +98 -0
  470. package/src/util/error.ts +77 -0
  471. package/src/util/filesystem.ts +245 -0
  472. package/src/util/flock.ts +333 -0
  473. package/src/util/fn.ts +21 -0
  474. package/src/util/format.ts +20 -0
  475. package/src/util/glob.ts +34 -0
  476. package/src/util/hash.ts +7 -0
  477. package/src/util/iife.ts +3 -0
  478. package/src/util/keybind.ts +103 -0
  479. package/src/util/lazy.ts +23 -0
  480. package/src/util/locale.ts +81 -0
  481. package/src/util/lock.ts +98 -0
  482. package/src/util/log.ts +182 -0
  483. package/src/util/network.ts +9 -0
  484. package/src/util/process.ts +176 -0
  485. package/src/util/queue.ts +32 -0
  486. package/src/util/record.ts +3 -0
  487. package/src/util/rpc.ts +66 -0
  488. package/src/util/schema.ts +53 -0
  489. package/src/util/scrap.ts +10 -0
  490. package/src/util/signal.ts +12 -0
  491. package/src/util/timeout.ts +14 -0
  492. package/src/util/token.ts +7 -0
  493. package/src/util/update-schema.ts +13 -0
  494. package/src/util/which.ts +14 -0
  495. package/src/util/wildcard.ts +59 -0
  496. package/src/worktree/index.ts +612 -0
  497. package/sst-env.d.ts +10 -0
  498. package/test/AGENTS.md +81 -0
  499. package/test/account/repo.test.ts +326 -0
  500. package/test/account/service.test.ts +393 -0
  501. package/test/acp/agent-interface.test.ts +51 -0
  502. package/test/acp/event-subscription.test.ts +685 -0
  503. package/test/agent/agent.test.ts +717 -0
  504. package/test/auth/auth.test.ts +58 -0
  505. package/test/bus/bus-effect.test.ts +164 -0
  506. package/test/bus/bus-integration.test.ts +87 -0
  507. package/test/bus/bus.test.ts +219 -0
  508. package/test/cli/account.test.ts +26 -0
  509. package/test/cli/cmd/tui/prompt-part.test.ts +47 -0
  510. package/test/cli/github-action.test.ts +198 -0
  511. package/test/cli/github-remote.test.ts +80 -0
  512. package/test/cli/import.test.ts +54 -0
  513. package/test/cli/plugin-auth-picker.test.ts +120 -0
  514. package/test/cli/tui/keybind-plugin.test.ts +90 -0
  515. package/test/cli/tui/plugin-add.test.ts +107 -0
  516. package/test/cli/tui/plugin-install.test.ts +89 -0
  517. package/test/cli/tui/plugin-lifecycle.test.ts +225 -0
  518. package/test/cli/tui/plugin-loader-entrypoint.test.ts +492 -0
  519. package/test/cli/tui/plugin-loader-pure.test.ts +72 -0
  520. package/test/cli/tui/plugin-loader.test.ts +752 -0
  521. package/test/cli/tui/plugin-toggle.test.ts +159 -0
  522. package/test/cli/tui/slot-replace.test.tsx +47 -0
  523. package/test/cli/tui/theme-store.test.ts +51 -0
  524. package/test/cli/tui/thread.test.ts +128 -0
  525. package/test/cli/tui/transcript.test.ts +426 -0
  526. package/test/config/agent-color.test.ts +71 -0
  527. package/test/config/config.test.ts +2348 -0
  528. package/test/config/fixtures/empty-frontmatter.md +4 -0
  529. package/test/config/fixtures/frontmatter.md +28 -0
  530. package/test/config/fixtures/markdown-header.md +11 -0
  531. package/test/config/fixtures/no-frontmatter.md +1 -0
  532. package/test/config/fixtures/weird-model-id.md +13 -0
  533. package/test/config/markdown.test.ts +228 -0
  534. package/test/config/tui.test.ts +752 -0
  535. package/test/control-plane/sse.test.ts +56 -0
  536. package/test/effect/cross-spawn-spawner.test.ts +412 -0
  537. package/test/effect/instance-state.test.ts +482 -0
  538. package/test/effect/run-service.test.ts +46 -0
  539. package/test/effect/runner.test.ts +523 -0
  540. package/test/fake/provider.ts +81 -0
  541. package/test/file/fsmonitor.test.ts +62 -0
  542. package/test/file/ignore.test.ts +10 -0
  543. package/test/file/index.test.ts +946 -0
  544. package/test/file/path-traversal.test.ts +198 -0
  545. package/test/file/ripgrep.test.ts +54 -0
  546. package/test/file/time.test.ts +445 -0
  547. package/test/file/watcher.test.ts +247 -0
  548. package/test/filesystem/filesystem.test.ts +319 -0
  549. package/test/fixture/db.ts +11 -0
  550. package/test/fixture/fixture.test.ts +26 -0
  551. package/test/fixture/fixture.ts +172 -0
  552. package/test/fixture/flock-worker.ts +72 -0
  553. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  554. package/test/fixture/plug-worker.ts +93 -0
  555. package/test/fixture/plugin-meta-worker.ts +26 -0
  556. package/test/fixture/skills/agents-sdk/SKILL.md +152 -0
  557. package/test/fixture/skills/agents-sdk/references/callable.md +92 -0
  558. package/test/fixture/skills/cloudflare/SKILL.md +211 -0
  559. package/test/fixture/skills/index.json +6 -0
  560. package/test/fixture/tui-plugin.ts +337 -0
  561. package/test/fixture/tui-runtime.ts +27 -0
  562. package/test/format/format.test.ts +171 -0
  563. package/test/git/git.test.ts +128 -0
  564. package/test/ide/ide.test.ts +82 -0
  565. package/test/installation/installation.test.ts +151 -0
  566. package/test/keybind.test.ts +421 -0
  567. package/test/lib/effect.ts +53 -0
  568. package/test/lib/filesystem.ts +10 -0
  569. package/test/lib/llm-server.ts +795 -0
  570. package/test/lsp/client.test.ts +95 -0
  571. package/test/lsp/index.test.ts +55 -0
  572. package/test/lsp/launch.test.ts +22 -0
  573. package/test/lsp/lifecycle.test.ts +147 -0
  574. package/test/mcp/headers.test.ts +153 -0
  575. package/test/mcp/lifecycle.test.ts +750 -0
  576. package/test/mcp/oauth-auto-connect.test.ts +199 -0
  577. package/test/mcp/oauth-browser.test.ts +249 -0
  578. package/test/memory/abort-leak.test.ts +137 -0
  579. package/test/patch/patch.test.ts +348 -0
  580. package/test/permission/arity.test.ts +33 -0
  581. package/test/permission/next.test.ts +1148 -0
  582. package/test/permission-task.test.ts +323 -0
  583. package/test/plugin/auth-override.test.ts +74 -0
  584. package/test/plugin/codex.test.ts +123 -0
  585. package/test/plugin/github-copilot-models.test.ts +117 -0
  586. package/test/plugin/install-concurrency.test.ts +140 -0
  587. package/test/plugin/install.test.ts +570 -0
  588. package/test/plugin/loader-shared.test.ts +1136 -0
  589. package/test/plugin/meta.test.ts +137 -0
  590. package/test/plugin/trigger.test.ts +111 -0
  591. package/test/preload.ts +90 -0
  592. package/test/project/migrate-global.test.ts +140 -0
  593. package/test/project/project.test.ts +459 -0
  594. package/test/project/state.test.ts +115 -0
  595. package/test/project/vcs.test.ts +228 -0
  596. package/test/project/worktree-remove.test.ts +96 -0
  597. package/test/project/worktree.test.ts +173 -0
  598. package/test/provider/amazon-bedrock.test.ts +447 -0
  599. package/test/provider/copilot/convert-to-copilot-messages.test.ts +523 -0
  600. package/test/provider/copilot/copilot-chat-model.test.ts +592 -0
  601. package/test/provider/gitlab-duo.test.ts +412 -0
  602. package/test/provider/provider.test.ts +2284 -0
  603. package/test/provider/transform.test.ts +2839 -0
  604. package/test/pty/pty-output-isolation.test.ts +141 -0
  605. package/test/pty/pty-session.test.ts +92 -0
  606. package/test/pty/pty-shell.test.ts +59 -0
  607. package/test/question/question.test.ts +453 -0
  608. package/test/server/global-session-list.test.ts +89 -0
  609. package/test/server/project-init-git.test.ts +121 -0
  610. package/test/server/session-actions.test.ts +83 -0
  611. package/test/server/session-list.test.ts +98 -0
  612. package/test/server/session-messages.test.ts +159 -0
  613. package/test/server/session-select.test.ts +84 -0
  614. package/test/session/compaction.test.ts +1212 -0
  615. package/test/session/instruction.test.ts +286 -0
  616. package/test/session/llm.test.ts +1098 -0
  617. package/test/session/message-v2.test.ts +957 -0
  618. package/test/session/messages-pagination.test.ts +885 -0
  619. package/test/session/processor-effect.test.ts +747 -0
  620. package/test/session/prompt-effect.test.ts +1241 -0
  621. package/test/session/prompt.test.ts +518 -0
  622. package/test/session/retry.test.ts +232 -0
  623. package/test/session/revert-compact.test.ts +621 -0
  624. package/test/session/session.test.ts +142 -0
  625. package/test/session/snapshot-tool-race.test.ts +242 -0
  626. package/test/session/structured-output-integration.test.ts +233 -0
  627. package/test/session/structured-output.test.ts +391 -0
  628. package/test/session/system.test.ts +59 -0
  629. package/test/share/share-next.test.ts +333 -0
  630. package/test/shell/shell.test.ts +73 -0
  631. package/test/skill/discovery.test.ts +116 -0
  632. package/test/skill/skill.test.ts +392 -0
  633. package/test/snapshot/snapshot.test.ts +1312 -0
  634. package/test/storage/db.test.ts +14 -0
  635. package/test/storage/json-migration.test.ts +849 -0
  636. package/test/storage/storage.test.ts +295 -0
  637. package/test/sync/index.test.ts +191 -0
  638. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  639. package/test/tool/apply_patch.test.ts +567 -0
  640. package/test/tool/bash.test.ts +1099 -0
  641. package/test/tool/edit.test.ts +681 -0
  642. package/test/tool/external-directory.test.ts +198 -0
  643. package/test/tool/fixtures/large-image.png +0 -0
  644. package/test/tool/fixtures/models-api.json +65179 -0
  645. package/test/tool/grep.test.ts +111 -0
  646. package/test/tool/question.test.ts +126 -0
  647. package/test/tool/read.test.ts +546 -0
  648. package/test/tool/registry.test.ts +126 -0
  649. package/test/tool/skill.test.ts +167 -0
  650. package/test/tool/task.test.ts +49 -0
  651. package/test/tool/tool-define.test.ts +101 -0
  652. package/test/tool/truncation.test.ts +161 -0
  653. package/test/tool/webfetch.test.ts +101 -0
  654. package/test/tool/write.test.ts +353 -0
  655. package/test/util/data-url.test.ts +14 -0
  656. package/test/util/effect-zod.test.ts +61 -0
  657. package/test/util/error.test.ts +38 -0
  658. package/test/util/filesystem.test.ts +656 -0
  659. package/test/util/flock.test.ts +383 -0
  660. package/test/util/format.test.ts +59 -0
  661. package/test/util/glob.test.ts +164 -0
  662. package/test/util/iife.test.ts +36 -0
  663. package/test/util/lazy.test.ts +50 -0
  664. package/test/util/lock.test.ts +72 -0
  665. package/test/util/module.test.ts +59 -0
  666. package/test/util/process.test.ts +128 -0
  667. package/test/util/timeout.test.ts +21 -0
  668. package/test/util/which.test.ts +100 -0
  669. package/test/util/wildcard.test.ts +90 -0
  670. package/tsconfig.json +23 -0
@@ -0,0 +1,1908 @@
1
+ import path from "path"
2
+ import os from "os"
3
+ import z from "zod"
4
+ import { SessionID, MessageID, PartID } from "./schema"
5
+ import { MessageV2 } from "./message-v2"
6
+ import { Log } from "../util/log"
7
+ import { SessionRevert } from "./revert"
8
+ import { Session } from "."
9
+ import { Agent } from "../agent/agent"
10
+ import { Provider } from "../provider/provider"
11
+ import { ModelID, ProviderID } from "../provider/schema"
12
+ import { type Tool as AITool, tool, jsonSchema, type ToolExecutionOptions, asSchema } from "ai"
13
+ import { SessionCompaction } from "./compaction"
14
+ import { Instance } from "../project/instance"
15
+ import { Bus } from "../bus"
16
+ import { ProviderTransform } from "../provider/transform"
17
+ import { SystemPrompt } from "./system"
18
+ import { Instruction } from "./instruction"
19
+ import { Plugin } from "../plugin"
20
+ import PROMPT_PLAN from "../session/prompt/plan.txt"
21
+ import BUILD_SWITCH from "../session/prompt/build-switch.txt"
22
+ import MAX_STEPS from "../session/prompt/max-steps.txt"
23
+ import { ToolRegistry } from "../tool/registry"
24
+ import { Runner } from "@/effect/runner"
25
+ import { MCP } from "../mcp"
26
+ import { LSP } from "../lsp"
27
+ import { ReadTool } from "../tool/read"
28
+ import { FileTime } from "../file/time"
29
+ import { Flag } from "../flag/flag"
30
+ import { ulid } from "ulid"
31
+ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
32
+ import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
33
+ import * as Stream from "effect/Stream"
34
+ import { Command } from "../command"
35
+ import { pathToFileURL, fileURLToPath } from "url"
36
+ import { ConfigMarkdown } from "../config/markdown"
37
+ import { SessionSummary } from "./summary"
38
+ import { NamedError } from "@opencode-ai/util/error"
39
+ import { SessionProcessor } from "./processor"
40
+ import { TaskTool } from "@/tool/task"
41
+ import { Tool } from "@/tool/tool"
42
+ import { Permission } from "@/permission"
43
+ import { SessionStatus } from "./status"
44
+ import { LLM } from "./llm"
45
+ import { Shell } from "@/shell/shell"
46
+ import { AppFileSystem } from "@/filesystem"
47
+ import { Truncate } from "@/tool/truncate"
48
+ import { decodeDataUrl } from "@/util/data-url"
49
+ import { Process } from "@/util/process"
50
+ import { Cause, Effect, Exit, Layer, Option, Scope, ServiceMap } from "effect"
51
+ import { InstanceState } from "@/effect/instance-state"
52
+ import { makeRuntime } from "@/effect/run-service"
53
+
54
+ // @ts-ignore
55
+ globalThis.AI_SDK_LOG_WARNINGS = false
56
+
57
+ const STRUCTURED_OUTPUT_DESCRIPTION = `Use this tool to return your final response in the requested structured format.
58
+
59
+ IMPORTANT:
60
+ - You MUST call this tool exactly once at the end of your response
61
+ - The input must be valid JSON matching the required schema
62
+ - Complete all necessary research and tool calls BEFORE calling this tool
63
+ - This tool provides your final answer - no further actions are taken after calling it`
64
+
65
+ const STRUCTURED_OUTPUT_SYSTEM_PROMPT = `IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.`
66
+
67
+ export namespace SessionPrompt {
68
+ const log = Log.create({ service: "session.prompt" })
69
+
70
+ export interface Interface {
71
+ readonly assertNotBusy: (sessionID: SessionID) => Effect.Effect<void, Session.BusyError>
72
+ readonly cancel: (sessionID: SessionID) => Effect.Effect<void>
73
+ readonly prompt: (input: PromptInput) => Effect.Effect<MessageV2.WithParts>
74
+ readonly loop: (input: z.infer<typeof LoopInput>) => Effect.Effect<MessageV2.WithParts>
75
+ readonly shell: (input: ShellInput) => Effect.Effect<MessageV2.WithParts>
76
+ readonly command: (input: CommandInput) => Effect.Effect<MessageV2.WithParts>
77
+ readonly resolvePromptParts: (template: string) => Effect.Effect<PromptInput["parts"]>
78
+ }
79
+
80
+ export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/SessionPrompt") {}
81
+
82
+ export const layer = Layer.effect(
83
+ Service,
84
+ Effect.gen(function* () {
85
+ const bus = yield* Bus.Service
86
+ const status = yield* SessionStatus.Service
87
+ const sessions = yield* Session.Service
88
+ const agents = yield* Agent.Service
89
+ const provider = yield* Provider.Service
90
+ const processor = yield* SessionProcessor.Service
91
+ const compaction = yield* SessionCompaction.Service
92
+ const plugin = yield* Plugin.Service
93
+ const commands = yield* Command.Service
94
+ const permission = yield* Permission.Service
95
+ const fsys = yield* AppFileSystem.Service
96
+ const mcp = yield* MCP.Service
97
+ const lsp = yield* LSP.Service
98
+ const filetime = yield* FileTime.Service
99
+ const registry = yield* ToolRegistry.Service
100
+ const truncate = yield* Truncate.Service
101
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
102
+ const scope = yield* Scope.Scope
103
+ const instruction = yield* Instruction.Service
104
+
105
+ const state = yield* InstanceState.make(
106
+ Effect.fn("SessionPrompt.state")(function* () {
107
+ const runners = new Map<string, Runner<MessageV2.WithParts>>()
108
+ yield* Effect.addFinalizer(
109
+ Effect.fnUntraced(function* () {
110
+ yield* Effect.forEach(runners.values(), (r) => r.cancel, { concurrency: "unbounded", discard: true })
111
+ runners.clear()
112
+ }),
113
+ )
114
+ return { runners }
115
+ }),
116
+ )
117
+
118
+ const getRunner = (runners: Map<string, Runner<MessageV2.WithParts>>, sessionID: SessionID) => {
119
+ const existing = runners.get(sessionID)
120
+ if (existing) return existing
121
+ const runner = Runner.make<MessageV2.WithParts>(scope, {
122
+ onIdle: Effect.gen(function* () {
123
+ runners.delete(sessionID)
124
+ yield* status.set(sessionID, { type: "idle" })
125
+ }),
126
+ onBusy: status.set(sessionID, { type: "busy" }),
127
+ onInterrupt: lastAssistant(sessionID),
128
+ busy: () => {
129
+ throw new Session.BusyError(sessionID)
130
+ },
131
+ })
132
+ runners.set(sessionID, runner)
133
+ return runner
134
+ }
135
+
136
+ const assertNotBusy: (sessionID: SessionID) => Effect.Effect<void, Session.BusyError> = Effect.fn(
137
+ "SessionPrompt.assertNotBusy",
138
+ )(function* (sessionID: SessionID) {
139
+ const s = yield* InstanceState.get(state)
140
+ const runner = s.runners.get(sessionID)
141
+ if (runner?.busy) throw new Session.BusyError(sessionID)
142
+ })
143
+
144
+ const cancel = Effect.fn("SessionPrompt.cancel")(function* (sessionID: SessionID) {
145
+ log.info("cancel", { sessionID })
146
+ const s = yield* InstanceState.get(state)
147
+ const runner = s.runners.get(sessionID)
148
+ if (!runner || !runner.busy) {
149
+ yield* status.set(sessionID, { type: "idle" })
150
+ return
151
+ }
152
+ yield* runner.cancel
153
+ })
154
+
155
+ const resolvePromptParts = Effect.fn("SessionPrompt.resolvePromptParts")(function* (template: string) {
156
+ const ctx = yield* InstanceState.context
157
+ const parts: PromptInput["parts"] = [{ type: "text", text: template }]
158
+ const files = ConfigMarkdown.files(template)
159
+ const seen = new Set<string>()
160
+ yield* Effect.forEach(
161
+ files,
162
+ Effect.fnUntraced(function* (match) {
163
+ const name = match[1]
164
+ if (seen.has(name)) return
165
+ seen.add(name)
166
+ const filepath = name.startsWith("~/")
167
+ ? path.join(os.homedir(), name.slice(2))
168
+ : path.resolve(ctx.worktree, name)
169
+
170
+ const info = yield* fsys.stat(filepath).pipe(Effect.option)
171
+ if (Option.isNone(info)) {
172
+ const found = yield* agents.get(name)
173
+ if (found) parts.push({ type: "agent", name: found.name })
174
+ return
175
+ }
176
+ const stat = info.value
177
+ parts.push({
178
+ type: "file",
179
+ url: pathToFileURL(filepath).href,
180
+ filename: name,
181
+ mime: stat.type === "Directory" ? "application/x-directory" : "text/plain",
182
+ })
183
+ }),
184
+ { concurrency: "unbounded", discard: true },
185
+ )
186
+ return parts
187
+ })
188
+
189
+ const title = Effect.fn("SessionPrompt.ensureTitle")(function* (input: {
190
+ session: Session.Info
191
+ history: MessageV2.WithParts[]
192
+ providerID: ProviderID
193
+ modelID: ModelID
194
+ }) {
195
+ if (input.session.parentID) return
196
+ if (!Session.isDefaultTitle(input.session.title)) return
197
+
198
+ const real = (m: MessageV2.WithParts) =>
199
+ m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic)
200
+ const idx = input.history.findIndex(real)
201
+ if (idx === -1) return
202
+ if (input.history.filter(real).length !== 1) return
203
+
204
+ const context = input.history.slice(0, idx + 1)
205
+ const firstUser = context[idx]
206
+ if (!firstUser || firstUser.info.role !== "user") return
207
+ const firstInfo = firstUser.info
208
+
209
+ const subtasks = firstUser.parts.filter((p): p is MessageV2.SubtaskPart => p.type === "subtask")
210
+ const onlySubtasks = subtasks.length > 0 && firstUser.parts.every((p) => p.type === "subtask")
211
+
212
+ const ag = yield* agents.get("title")
213
+ if (!ag) return
214
+ const mdl = ag.model
215
+ ? yield* provider.getModel(ag.model.providerID, ag.model.modelID)
216
+ : ((yield* provider.getSmallModel(input.providerID)) ??
217
+ (yield* provider.getModel(input.providerID, input.modelID)))
218
+ const msgs = onlySubtasks
219
+ ? [{ role: "user" as const, content: subtasks.map((p) => p.prompt).join("\n") }]
220
+ : yield* MessageV2.toModelMessagesEffect(context, mdl)
221
+ const text = yield* Effect.promise(async (signal) => {
222
+ const result = await LLM.stream({
223
+ agent: ag,
224
+ user: firstInfo,
225
+ system: [],
226
+ small: true,
227
+ tools: {},
228
+ model: mdl,
229
+ abort: signal,
230
+ sessionID: input.session.id,
231
+ retries: 2,
232
+ messages: [{ role: "user", content: "Generate a title for this conversation:\n" }, ...msgs],
233
+ })
234
+ return result.text
235
+ })
236
+ const cleaned = text
237
+ .replace(/<think>[\s\S]*?<\/think>\s*/g, "")
238
+ .split("\n")
239
+ .map((line) => line.trim())
240
+ .find((line) => line.length > 0)
241
+ if (!cleaned) return
242
+ const t = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
243
+ yield* sessions
244
+ .setTitle({ sessionID: input.session.id, title: t })
245
+ .pipe(
246
+ Effect.catchCause((cause) =>
247
+ Effect.sync(() => log.error("failed to generate title", { error: Cause.squash(cause) })),
248
+ ),
249
+ )
250
+ })
251
+
252
+ const insertReminders = Effect.fn("SessionPrompt.insertReminders")(function* (input: {
253
+ messages: MessageV2.WithParts[]
254
+ agent: Agent.Info
255
+ session: Session.Info
256
+ }) {
257
+ const userMessage = input.messages.findLast((msg) => msg.info.role === "user")
258
+ if (!userMessage) return input.messages
259
+
260
+ if (!Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE) {
261
+ if (input.agent.name === "plan") {
262
+ userMessage.parts.push({
263
+ id: PartID.ascending(),
264
+ messageID: userMessage.info.id,
265
+ sessionID: userMessage.info.sessionID,
266
+ type: "text",
267
+ text: PROMPT_PLAN,
268
+ synthetic: true,
269
+ })
270
+ }
271
+ const wasPlan = input.messages.some((msg) => msg.info.role === "assistant" && msg.info.agent === "plan")
272
+ if (wasPlan && input.agent.name === "build") {
273
+ userMessage.parts.push({
274
+ id: PartID.ascending(),
275
+ messageID: userMessage.info.id,
276
+ sessionID: userMessage.info.sessionID,
277
+ type: "text",
278
+ text: BUILD_SWITCH,
279
+ synthetic: true,
280
+ })
281
+ }
282
+ return input.messages
283
+ }
284
+
285
+ const assistantMessage = input.messages.findLast((msg) => msg.info.role === "assistant")
286
+ if (input.agent.name !== "plan" && assistantMessage?.info.agent === "plan") {
287
+ const plan = Session.plan(input.session)
288
+ if (!(yield* fsys.existsSafe(plan))) return input.messages
289
+ const part = yield* sessions.updatePart({
290
+ id: PartID.ascending(),
291
+ messageID: userMessage.info.id,
292
+ sessionID: userMessage.info.sessionID,
293
+ type: "text",
294
+ text:
295
+ BUILD_SWITCH + "\n\n" + `A plan file exists at ${plan}. You should execute on the plan defined within it`,
296
+ synthetic: true,
297
+ })
298
+ userMessage.parts.push(part)
299
+ return input.messages
300
+ }
301
+
302
+ if (input.agent.name !== "plan" || assistantMessage?.info.agent === "plan") return input.messages
303
+
304
+ const plan = Session.plan(input.session)
305
+ const exists = yield* fsys.existsSafe(plan)
306
+ if (!exists) yield* fsys.ensureDir(path.dirname(plan)).pipe(Effect.catch(Effect.die))
307
+ const part = yield* sessions.updatePart({
308
+ id: PartID.ascending(),
309
+ messageID: userMessage.info.id,
310
+ sessionID: userMessage.info.sessionID,
311
+ type: "text",
312
+ text: `<system-reminder>
313
+ Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
314
+
315
+ ## Plan File Info:
316
+ ${exists ? `A plan file already exists at ${plan}. You can read it and make incremental edits using the edit tool.` : `No plan file exists yet. You should create your plan at ${plan} using the write tool.`}
317
+ You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
318
+
319
+ ## Plan Workflow
320
+
321
+ ### Phase 1: Initial Understanding
322
+ Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the explore subagent type.
323
+
324
+ 1. Focus on understanding the user's request and the code associated with their request
325
+
326
+ 2. **Launch up to 3 explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
327
+ - Use 1 agent when the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change.
328
+ - Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
329
+ - Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
330
+ - If using multiple agents: Provide each agent with a specific search focus or area to explore. Example: One agent searches for existing implementations, another explores related components, a third investigates testing patterns
331
+
332
+ 3. After exploring the code, use the question tool to clarify ambiguities in the user request up front.
333
+
334
+ ### Phase 2: Design
335
+ Goal: Design an implementation approach.
336
+
337
+ Launch general agent(s) to design the implementation based on the user's intent and your exploration results from Phase 1.
338
+
339
+ You can launch up to 1 agent(s) in parallel.
340
+
341
+ **Guidelines:**
342
+ - **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
343
+ - **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
344
+
345
+ Examples of when to use multiple agents:
346
+ - The task touches multiple parts of the codebase
347
+ - It's a large refactor or architectural change
348
+ - There are many edge cases to consider
349
+ - You'd benefit from exploring different approaches
350
+
351
+ Example perspectives by task type:
352
+ - New feature: simplicity vs performance vs maintainability
353
+ - Bug fix: root cause vs workaround vs prevention
354
+ - Refactoring: minimal change vs clean architecture
355
+
356
+ In the agent prompt:
357
+ - Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
358
+ - Describe requirements and constraints
359
+ - Request a detailed implementation plan
360
+
361
+ ### Phase 3: Review
362
+ Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
363
+ 1. Read the critical files identified by agents to deepen your understanding
364
+ 2. Ensure that the plans align with the user's original request
365
+ 3. Use question tool to clarify any remaining questions with the user
366
+
367
+ ### Phase 4: Final Plan
368
+ Goal: Write your final plan to the plan file (the only file you can edit).
369
+ - Include only your recommended approach, not all alternatives
370
+ - Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
371
+ - Include the paths of critical files to be modified
372
+ - Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
373
+
374
+ ### Phase 5: Call plan_exit tool
375
+ At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call plan_exit to indicate to the user that you are done planning.
376
+ This is critical - your turn should only end with either asking the user a question or calling plan_exit. Do not stop unless it's for these 2 reasons.
377
+
378
+ **Important:** Use question tool to clarify requirements/approach, use plan_exit to request plan approval. Do NOT use question tool to ask "Is this plan okay?" - that's what plan_exit does.
379
+
380
+ NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
381
+ </system-reminder>`,
382
+ synthetic: true,
383
+ })
384
+ userMessage.parts.push(part)
385
+ return input.messages
386
+ })
387
+
388
+ const resolveTools = Effect.fn("SessionPrompt.resolveTools")(function* (input: {
389
+ agent: Agent.Info
390
+ model: Provider.Model
391
+ session: Session.Info
392
+ tools?: Record<string, boolean>
393
+ processor: Pick<SessionProcessor.Handle, "message" | "partFromToolCall">
394
+ bypassAgentCheck: boolean
395
+ messages: MessageV2.WithParts[]
396
+ }) {
397
+ using _ = log.time("resolveTools")
398
+ const tools: Record<string, AITool> = {}
399
+
400
+ const context = (args: any, options: ToolExecutionOptions): Tool.Context => ({
401
+ sessionID: input.session.id,
402
+ abort: options.abortSignal!,
403
+ messageID: input.processor.message.id,
404
+ callID: options.toolCallId,
405
+ extra: { model: input.model, bypassAgentCheck: input.bypassAgentCheck },
406
+ agent: input.agent.name,
407
+ messages: input.messages,
408
+ metadata: (val) =>
409
+ Effect.runPromise(
410
+ Effect.gen(function* () {
411
+ const match = input.processor.partFromToolCall(options.toolCallId)
412
+ if (!match || !["running", "pending"].includes(match.state.status)) return
413
+ yield* sessions.updatePart({
414
+ ...match,
415
+ state: {
416
+ title: val.title,
417
+ metadata: val.metadata,
418
+ status: "running",
419
+ input: args,
420
+ time: { start: Date.now() },
421
+ },
422
+ })
423
+ }),
424
+ ),
425
+ ask: (req) =>
426
+ Effect.runPromise(
427
+ permission.ask({
428
+ ...req,
429
+ sessionID: input.session.id,
430
+ tool: { messageID: input.processor.message.id, callID: options.toolCallId },
431
+ ruleset: Permission.merge(input.agent.permission, input.session.permission ?? []),
432
+ }),
433
+ ),
434
+ })
435
+
436
+ for (const item of yield* registry.tools(
437
+ { modelID: ModelID.make(input.model.api.id), providerID: input.model.providerID },
438
+ input.agent,
439
+ )) {
440
+ const schema = ProviderTransform.schema(input.model, z.toJSONSchema(item.parameters))
441
+ tools[item.id] = tool({
442
+ id: item.id as any,
443
+ description: item.description,
444
+ inputSchema: jsonSchema(schema as any),
445
+ execute(args, options) {
446
+ return Effect.runPromise(
447
+ Effect.gen(function* () {
448
+ const ctx = context(args, options)
449
+ yield* plugin.trigger(
450
+ "tool.execute.before",
451
+ { tool: item.id, sessionID: ctx.sessionID, callID: ctx.callID },
452
+ { args },
453
+ )
454
+ const result = yield* Effect.promise(() => item.execute(args, ctx))
455
+ const output = {
456
+ ...result,
457
+ attachments: result.attachments?.map((attachment) => ({
458
+ ...attachment,
459
+ id: PartID.ascending(),
460
+ sessionID: ctx.sessionID,
461
+ messageID: input.processor.message.id,
462
+ })),
463
+ }
464
+ yield* plugin.trigger(
465
+ "tool.execute.after",
466
+ { tool: item.id, sessionID: ctx.sessionID, callID: ctx.callID, args },
467
+ output,
468
+ )
469
+ return output
470
+ }),
471
+ )
472
+ },
473
+ })
474
+ }
475
+
476
+ for (const [key, item] of Object.entries(yield* mcp.tools())) {
477
+ const execute = item.execute
478
+ if (!execute) continue
479
+
480
+ const schema = yield* Effect.promise(() => Promise.resolve(asSchema(item.inputSchema).jsonSchema))
481
+ const transformed = ProviderTransform.schema(input.model, schema)
482
+ item.inputSchema = jsonSchema(transformed)
483
+ item.execute = (args, opts) =>
484
+ Effect.runPromise(
485
+ Effect.gen(function* () {
486
+ const ctx = context(args, opts)
487
+ yield* plugin.trigger(
488
+ "tool.execute.before",
489
+ { tool: key, sessionID: ctx.sessionID, callID: opts.toolCallId },
490
+ { args },
491
+ )
492
+ yield* Effect.promise(() => ctx.ask({ permission: key, metadata: {}, patterns: ["*"], always: ["*"] }))
493
+ const result: Awaited<ReturnType<NonNullable<typeof execute>>> = yield* Effect.promise(() =>
494
+ execute(args, opts),
495
+ )
496
+ yield* plugin.trigger(
497
+ "tool.execute.after",
498
+ { tool: key, sessionID: ctx.sessionID, callID: opts.toolCallId, args },
499
+ result,
500
+ )
501
+
502
+ const textParts: string[] = []
503
+ const attachments: Omit<MessageV2.FilePart, "id" | "sessionID" | "messageID">[] = []
504
+ for (const contentItem of result.content) {
505
+ if (contentItem.type === "text") textParts.push(contentItem.text)
506
+ else if (contentItem.type === "image") {
507
+ attachments.push({
508
+ type: "file",
509
+ mime: contentItem.mimeType,
510
+ url: `data:${contentItem.mimeType};base64,${contentItem.data}`,
511
+ })
512
+ } else if (contentItem.type === "resource") {
513
+ const { resource } = contentItem
514
+ if (resource.text) textParts.push(resource.text)
515
+ if (resource.blob) {
516
+ attachments.push({
517
+ type: "file",
518
+ mime: resource.mimeType ?? "application/octet-stream",
519
+ url: `data:${resource.mimeType ?? "application/octet-stream"};base64,${resource.blob}`,
520
+ filename: resource.uri,
521
+ })
522
+ }
523
+ }
524
+ }
525
+
526
+ const truncated = yield* truncate.output(textParts.join("\n\n"), {}, input.agent)
527
+ const metadata = {
528
+ ...(result.metadata ?? {}),
529
+ truncated: truncated.truncated,
530
+ ...(truncated.truncated && { outputPath: truncated.outputPath }),
531
+ }
532
+
533
+ return {
534
+ title: "",
535
+ metadata,
536
+ output: truncated.content,
537
+ attachments: attachments.map((attachment) => ({
538
+ ...attachment,
539
+ id: PartID.ascending(),
540
+ sessionID: ctx.sessionID,
541
+ messageID: input.processor.message.id,
542
+ })),
543
+ content: result.content,
544
+ }
545
+ }),
546
+ )
547
+ tools[key] = item
548
+ }
549
+
550
+ return tools
551
+ })
552
+
553
+ const handleSubtask = Effect.fn("SessionPrompt.handleSubtask")(function* (input: {
554
+ task: MessageV2.SubtaskPart
555
+ model: Provider.Model
556
+ lastUser: MessageV2.User
557
+ sessionID: SessionID
558
+ session: Session.Info
559
+ msgs: MessageV2.WithParts[]
560
+ }) {
561
+ const { task, model, lastUser, sessionID, session, msgs } = input
562
+ const ctx = yield* InstanceState.context
563
+ const taskTool = yield* Effect.promise(() => registry.named.task.init())
564
+ const taskModel = task.model ? yield* getModel(task.model.providerID, task.model.modelID, sessionID) : model
565
+ const assistantMessage: MessageV2.Assistant = yield* sessions.updateMessage({
566
+ id: MessageID.ascending(),
567
+ role: "assistant",
568
+ parentID: lastUser.id,
569
+ sessionID,
570
+ mode: task.agent,
571
+ agent: task.agent,
572
+ variant: lastUser.variant,
573
+ path: { cwd: ctx.directory, root: ctx.worktree },
574
+ cost: 0,
575
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
576
+ modelID: taskModel.id,
577
+ providerID: taskModel.providerID,
578
+ time: { created: Date.now() },
579
+ })
580
+ let part: MessageV2.ToolPart = yield* sessions.updatePart({
581
+ id: PartID.ascending(),
582
+ messageID: assistantMessage.id,
583
+ sessionID: assistantMessage.sessionID,
584
+ type: "tool",
585
+ callID: ulid(),
586
+ tool: registry.named.task.id,
587
+ state: {
588
+ status: "running",
589
+ input: {
590
+ prompt: task.prompt,
591
+ description: task.description,
592
+ subagent_type: task.agent,
593
+ command: task.command,
594
+ },
595
+ time: { start: Date.now() },
596
+ },
597
+ })
598
+ const taskArgs = {
599
+ prompt: task.prompt,
600
+ description: task.description,
601
+ subagent_type: task.agent,
602
+ command: task.command,
603
+ }
604
+ yield* plugin.trigger("tool.execute.before", { tool: "task", sessionID, callID: part.id }, { args: taskArgs })
605
+
606
+ const taskAgent = yield* agents.get(task.agent)
607
+ if (!taskAgent) {
608
+ const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
609
+ const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
610
+ const error = new NamedError.Unknown({ message: `Agent not found: "${task.agent}".${hint}` })
611
+ yield* bus.publish(Session.Event.Error, { sessionID, error: error.toObject() })
612
+ throw error
613
+ }
614
+
615
+ let error: Error | undefined
616
+ const result = yield* Effect.promise((signal) =>
617
+ taskTool
618
+ .execute(taskArgs, {
619
+ agent: task.agent,
620
+ messageID: assistantMessage.id,
621
+ sessionID,
622
+ abort: signal,
623
+ callID: part.callID,
624
+ extra: { bypassAgentCheck: true },
625
+ messages: msgs,
626
+ metadata(val: { title?: string; metadata?: Record<string, any> }) {
627
+ return Effect.runPromise(
628
+ Effect.gen(function* () {
629
+ part = yield* sessions.updatePart({
630
+ ...part,
631
+ type: "tool",
632
+ state: { ...part.state, ...val },
633
+ } satisfies MessageV2.ToolPart)
634
+ }),
635
+ )
636
+ },
637
+ ask(req: any) {
638
+ return Effect.runPromise(
639
+ permission.ask({
640
+ ...req,
641
+ sessionID,
642
+ ruleset: Permission.merge(taskAgent.permission, session.permission ?? []),
643
+ }),
644
+ )
645
+ },
646
+ })
647
+ .catch((e) => {
648
+ error = e instanceof Error ? e : new Error(String(e))
649
+ log.error("subtask execution failed", { error, agent: task.agent, description: task.description })
650
+ return undefined
651
+ }),
652
+ ).pipe(
653
+ Effect.onInterrupt(() =>
654
+ Effect.gen(function* () {
655
+ assistantMessage.finish = "tool-calls"
656
+ assistantMessage.time.completed = Date.now()
657
+ yield* sessions.updateMessage(assistantMessage)
658
+ if (part.state.status === "running") {
659
+ yield* sessions.updatePart({
660
+ ...part,
661
+ state: {
662
+ status: "error",
663
+ error: "Cancelled",
664
+ time: { start: part.state.time.start, end: Date.now() },
665
+ metadata: part.state.metadata,
666
+ input: part.state.input,
667
+ },
668
+ } satisfies MessageV2.ToolPart)
669
+ }
670
+ }),
671
+ ),
672
+ )
673
+
674
+ const attachments = result?.attachments?.map((attachment) => ({
675
+ ...attachment,
676
+ id: PartID.ascending(),
677
+ sessionID,
678
+ messageID: assistantMessage.id,
679
+ }))
680
+
681
+ yield* plugin.trigger(
682
+ "tool.execute.after",
683
+ { tool: "task", sessionID, callID: part.id, args: taskArgs },
684
+ result,
685
+ )
686
+
687
+ assistantMessage.finish = "tool-calls"
688
+ assistantMessage.time.completed = Date.now()
689
+ yield* sessions.updateMessage(assistantMessage)
690
+
691
+ if (result && part.state.status === "running") {
692
+ yield* sessions.updatePart({
693
+ ...part,
694
+ state: {
695
+ status: "completed",
696
+ input: part.state.input,
697
+ title: result.title,
698
+ metadata: result.metadata,
699
+ output: result.output,
700
+ attachments,
701
+ time: { ...part.state.time, end: Date.now() },
702
+ },
703
+ } satisfies MessageV2.ToolPart)
704
+ }
705
+
706
+ if (!result) {
707
+ yield* sessions.updatePart({
708
+ ...part,
709
+ state: {
710
+ status: "error",
711
+ error: error ? `Tool execution failed: ${error.message}` : "Tool execution failed",
712
+ time: {
713
+ start: part.state.status === "running" ? part.state.time.start : Date.now(),
714
+ end: Date.now(),
715
+ },
716
+ metadata: part.state.status === "pending" ? undefined : part.state.metadata,
717
+ input: part.state.input,
718
+ },
719
+ } satisfies MessageV2.ToolPart)
720
+ }
721
+
722
+ if (!task.command) return
723
+
724
+ const summaryUserMsg: MessageV2.User = {
725
+ id: MessageID.ascending(),
726
+ sessionID,
727
+ role: "user",
728
+ time: { created: Date.now() },
729
+ agent: lastUser.agent,
730
+ model: lastUser.model,
731
+ }
732
+ yield* sessions.updateMessage(summaryUserMsg)
733
+ yield* sessions.updatePart({
734
+ id: PartID.ascending(),
735
+ messageID: summaryUserMsg.id,
736
+ sessionID,
737
+ type: "text",
738
+ text: "Summarize the task tool output above and continue with your task.",
739
+ synthetic: true,
740
+ } satisfies MessageV2.TextPart)
741
+ })
742
+
743
+ const shellImpl = Effect.fn("SessionPrompt.shellImpl")(function* (input: ShellInput, signal: AbortSignal) {
744
+ const ctx = yield* InstanceState.context
745
+ const session = yield* sessions.get(input.sessionID)
746
+ if (session.revert) {
747
+ yield* Effect.promise(() => SessionRevert.cleanup(session))
748
+ }
749
+ const agent = yield* agents.get(input.agent)
750
+ if (!agent) {
751
+ const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
752
+ const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
753
+ const error = new NamedError.Unknown({ message: `Agent not found: "${input.agent}".${hint}` })
754
+ yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
755
+ throw error
756
+ }
757
+ const model = input.model ?? agent.model ?? (yield* lastModel(input.sessionID))
758
+ const userMsg: MessageV2.User = {
759
+ id: input.messageID ?? MessageID.ascending(),
760
+ sessionID: input.sessionID,
761
+ time: { created: Date.now() },
762
+ role: "user",
763
+ agent: input.agent,
764
+ model: { providerID: model.providerID, modelID: model.modelID },
765
+ }
766
+ yield* sessions.updateMessage(userMsg)
767
+ const userPart: MessageV2.Part = {
768
+ type: "text",
769
+ id: PartID.ascending(),
770
+ messageID: userMsg.id,
771
+ sessionID: input.sessionID,
772
+ text: "The following tool was executed by the user",
773
+ synthetic: true,
774
+ }
775
+ yield* sessions.updatePart(userPart)
776
+
777
+ const msg: MessageV2.Assistant = {
778
+ id: MessageID.ascending(),
779
+ sessionID: input.sessionID,
780
+ parentID: userMsg.id,
781
+ mode: input.agent,
782
+ agent: input.agent,
783
+ cost: 0,
784
+ path: { cwd: ctx.directory, root: ctx.worktree },
785
+ time: { created: Date.now() },
786
+ role: "assistant",
787
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
788
+ modelID: model.modelID,
789
+ providerID: model.providerID,
790
+ }
791
+ yield* sessions.updateMessage(msg)
792
+ const part: MessageV2.ToolPart = {
793
+ type: "tool",
794
+ id: PartID.ascending(),
795
+ messageID: msg.id,
796
+ sessionID: input.sessionID,
797
+ tool: "bash",
798
+ callID: ulid(),
799
+ state: {
800
+ status: "running",
801
+ time: { start: Date.now() },
802
+ input: { command: input.command },
803
+ },
804
+ }
805
+ yield* sessions.updatePart(part)
806
+
807
+ const sh = Shell.preferred()
808
+ const shellName = (
809
+ process.platform === "win32" ? path.win32.basename(sh, ".exe") : path.basename(sh)
810
+ ).toLowerCase()
811
+ const invocations: Record<string, { args: string[] }> = {
812
+ nu: { args: ["-c", input.command] },
813
+ fish: { args: ["-c", input.command] },
814
+ zsh: {
815
+ args: [
816
+ "-l",
817
+ "-c",
818
+ `
819
+ __oc_cwd=$PWD
820
+ [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
821
+ [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
822
+ cd "$__oc_cwd"
823
+ eval ${JSON.stringify(input.command)}
824
+ `,
825
+ ],
826
+ },
827
+ bash: {
828
+ args: [
829
+ "-l",
830
+ "-c",
831
+ `
832
+ __oc_cwd=$PWD
833
+ shopt -s expand_aliases
834
+ [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
835
+ cd "$__oc_cwd"
836
+ eval ${JSON.stringify(input.command)}
837
+ `,
838
+ ],
839
+ },
840
+ cmd: { args: ["/c", input.command] },
841
+ powershell: { args: ["-NoProfile", "-Command", input.command] },
842
+ pwsh: { args: ["-NoProfile", "-Command", input.command] },
843
+ "": { args: ["-c", input.command] },
844
+ }
845
+
846
+ const args = (invocations[shellName] ?? invocations[""]).args
847
+ const cwd = ctx.directory
848
+ const shellEnv = yield* plugin.trigger(
849
+ "shell.env",
850
+ { cwd, sessionID: input.sessionID, callID: part.callID },
851
+ { env: {} },
852
+ )
853
+
854
+ const cmd = ChildProcess.make(sh, args, {
855
+ cwd,
856
+ extendEnv: true,
857
+ env: { ...shellEnv.env, TERM: "dumb" },
858
+ stdin: "ignore",
859
+ forceKillAfter: "3 seconds",
860
+ })
861
+
862
+ let output = ""
863
+ let aborted = false
864
+
865
+ const finish = Effect.uninterruptible(
866
+ Effect.gen(function* () {
867
+ if (aborted) {
868
+ output += "\n\n" + ["<metadata>", "User aborted the command", "</metadata>"].join("\n")
869
+ }
870
+ if (!msg.time.completed) {
871
+ msg.time.completed = Date.now()
872
+ yield* sessions.updateMessage(msg)
873
+ }
874
+ if (part.state.status === "running") {
875
+ part.state = {
876
+ status: "completed",
877
+ time: { ...part.state.time, end: Date.now() },
878
+ input: part.state.input,
879
+ title: "",
880
+ metadata: { output, description: "" },
881
+ output,
882
+ }
883
+ yield* sessions.updatePart(part)
884
+ }
885
+ }),
886
+ )
887
+
888
+ const exit = yield* Effect.gen(function* () {
889
+ const handle = yield* spawner.spawn(cmd)
890
+ yield* Stream.runForEach(Stream.decodeText(handle.all), (chunk) =>
891
+ Effect.sync(() => {
892
+ output += chunk
893
+ if (part.state.status === "running") {
894
+ part.state.metadata = { output, description: "" }
895
+ void Effect.runFork(sessions.updatePart(part))
896
+ }
897
+ }),
898
+ )
899
+ yield* handle.exitCode
900
+ }).pipe(
901
+ Effect.scoped,
902
+ Effect.onInterrupt(() =>
903
+ Effect.sync(() => {
904
+ aborted = true
905
+ }),
906
+ ),
907
+ Effect.orDie,
908
+ Effect.ensuring(finish),
909
+ Effect.exit,
910
+ )
911
+
912
+ if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
913
+ return yield* Effect.failCause(exit.cause)
914
+ }
915
+
916
+ return { info: msg, parts: [part] }
917
+ })
918
+
919
+ const getModel = Effect.fn("SessionPrompt.getModel")(function* (
920
+ providerID: ProviderID,
921
+ modelID: ModelID,
922
+ sessionID: SessionID,
923
+ ) {
924
+ const exit = yield* provider.getModel(providerID, modelID).pipe(Effect.exit)
925
+ if (Exit.isSuccess(exit)) return exit.value
926
+ const err = Cause.squash(exit.cause)
927
+ if (Provider.ModelNotFoundError.isInstance(err)) {
928
+ const hint = err.data.suggestions?.length ? ` Did you mean: ${err.data.suggestions.join(", ")}?` : ""
929
+ yield* bus.publish(Session.Event.Error, {
930
+ sessionID,
931
+ error: new NamedError.Unknown({
932
+ message: `Model not found: ${err.data.providerID}/${err.data.modelID}.${hint}`,
933
+ }).toObject(),
934
+ })
935
+ }
936
+ return yield* Effect.failCause(exit.cause)
937
+ })
938
+
939
+ const lastModel = Effect.fnUntraced(function* (sessionID: SessionID) {
940
+ const model = yield* Effect.promise(async () => {
941
+ for await (const item of MessageV2.stream(sessionID)) {
942
+ if (item.info.role === "user" && item.info.model) return item.info.model
943
+ }
944
+ })
945
+ if (model) return model
946
+ return yield* provider.defaultModel()
947
+ })
948
+
949
+ const createUserMessage = Effect.fn("SessionPrompt.createUserMessage")(function* (input: PromptInput) {
950
+ const agentName = input.agent || (yield* agents.defaultAgent())
951
+ const ag = yield* agents.get(agentName)
952
+ if (!ag) {
953
+ const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
954
+ const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
955
+ const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
956
+ yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
957
+ throw error
958
+ }
959
+
960
+ const model = input.model ?? ag.model ?? (yield* lastModel(input.sessionID))
961
+ const same = ag.model && model.providerID === ag.model.providerID && model.modelID === ag.model.modelID
962
+ const full =
963
+ !input.variant && ag.variant && same
964
+ ? yield* provider
965
+ .getModel(model.providerID, model.modelID)
966
+ .pipe(Effect.catch(() => Effect.succeed(undefined)))
967
+ : undefined
968
+ const variant = input.variant ?? (ag.variant && full?.variants?.[ag.variant] ? ag.variant : undefined)
969
+
970
+ const info: MessageV2.Info = {
971
+ id: input.messageID ?? MessageID.ascending(),
972
+ role: "user",
973
+ sessionID: input.sessionID,
974
+ time: { created: Date.now() },
975
+ tools: input.tools,
976
+ agent: ag.name,
977
+ model,
978
+ system: input.system,
979
+ format: input.format,
980
+ variant,
981
+ }
982
+
983
+ yield* Effect.addFinalizer(() =>
984
+ InstanceState.withALS(() => instruction.clear(info.id)).pipe(Effect.flatMap((x) => x)),
985
+ )
986
+
987
+ type Draft<T> = T extends MessageV2.Part ? Omit<T, "id"> & { id?: string } : never
988
+ const assign = (part: Draft<MessageV2.Part>): MessageV2.Part => ({
989
+ ...part,
990
+ id: part.id ? PartID.make(part.id) : PartID.ascending(),
991
+ })
992
+
993
+ const resolvePart: (part: PromptInput["parts"][number]) => Effect.Effect<Draft<MessageV2.Part>[]> = Effect.fn(
994
+ "SessionPrompt.resolveUserPart",
995
+ )(function* (part) {
996
+ if (part.type === "file") {
997
+ if (part.source?.type === "resource") {
998
+ const { clientName, uri } = part.source
999
+ log.info("mcp resource", { clientName, uri, mime: part.mime })
1000
+ const pieces: Draft<MessageV2.Part>[] = [
1001
+ {
1002
+ messageID: info.id,
1003
+ sessionID: input.sessionID,
1004
+ type: "text",
1005
+ synthetic: true,
1006
+ text: `Reading MCP resource: ${part.filename} (${uri})`,
1007
+ },
1008
+ ]
1009
+ const exit = yield* mcp.readResource(clientName, uri).pipe(Effect.exit)
1010
+ if (Exit.isSuccess(exit)) {
1011
+ const content = exit.value
1012
+ if (!content) throw new Error(`Resource not found: ${clientName}/${uri}`)
1013
+ const items = Array.isArray(content.contents) ? content.contents : [content.contents]
1014
+ for (const c of items) {
1015
+ if ("text" in c && c.text) {
1016
+ pieces.push({
1017
+ messageID: info.id,
1018
+ sessionID: input.sessionID,
1019
+ type: "text",
1020
+ synthetic: true,
1021
+ text: c.text,
1022
+ })
1023
+ } else if ("blob" in c && c.blob) {
1024
+ const mime = "mimeType" in c ? c.mimeType : part.mime
1025
+ pieces.push({
1026
+ messageID: info.id,
1027
+ sessionID: input.sessionID,
1028
+ type: "text",
1029
+ synthetic: true,
1030
+ text: `[Binary content: ${mime}]`,
1031
+ })
1032
+ }
1033
+ }
1034
+ pieces.push({ ...part, messageID: info.id, sessionID: input.sessionID })
1035
+ } else {
1036
+ const error = Cause.squash(exit.cause)
1037
+ log.error("failed to read MCP resource", { error, clientName, uri })
1038
+ const message = error instanceof Error ? error.message : String(error)
1039
+ pieces.push({
1040
+ messageID: info.id,
1041
+ sessionID: input.sessionID,
1042
+ type: "text",
1043
+ synthetic: true,
1044
+ text: `Failed to read MCP resource ${part.filename}: ${message}`,
1045
+ })
1046
+ }
1047
+ return pieces
1048
+ }
1049
+ const url = new URL(part.url)
1050
+ switch (url.protocol) {
1051
+ case "data:":
1052
+ if (part.mime === "text/plain") {
1053
+ return [
1054
+ {
1055
+ messageID: info.id,
1056
+ sessionID: input.sessionID,
1057
+ type: "text",
1058
+ synthetic: true,
1059
+ text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
1060
+ },
1061
+ {
1062
+ messageID: info.id,
1063
+ sessionID: input.sessionID,
1064
+ type: "text",
1065
+ synthetic: true,
1066
+ text: decodeDataUrl(part.url),
1067
+ },
1068
+ { ...part, messageID: info.id, sessionID: input.sessionID },
1069
+ ]
1070
+ }
1071
+ break
1072
+ case "file:": {
1073
+ log.info("file", { mime: part.mime })
1074
+ const filepath = fileURLToPath(part.url)
1075
+ if (yield* fsys.isDir(filepath)) part.mime = "application/x-directory"
1076
+
1077
+ if (part.mime === "text/plain") {
1078
+ let offset: number | undefined
1079
+ let limit: number | undefined
1080
+ const range = { start: url.searchParams.get("start"), end: url.searchParams.get("end") }
1081
+ if (range.start != null) {
1082
+ const filePathURI = part.url.split("?")[0]
1083
+ let start = parseInt(range.start)
1084
+ let end = range.end ? parseInt(range.end) : undefined
1085
+ if (start === end) {
1086
+ const symbols = yield* lsp
1087
+ .documentSymbol(filePathURI)
1088
+ .pipe(Effect.catch(() => Effect.succeed([])))
1089
+ for (const symbol of symbols) {
1090
+ let r: LSP.Range | undefined
1091
+ if ("range" in symbol) r = symbol.range
1092
+ else if ("location" in symbol) r = symbol.location.range
1093
+ if (r?.start?.line && r?.start?.line === start) {
1094
+ start = r.start.line
1095
+ end = r?.end?.line ?? start
1096
+ break
1097
+ }
1098
+ }
1099
+ }
1100
+ offset = Math.max(start, 1)
1101
+ if (end) limit = end - (offset - 1)
1102
+ }
1103
+ const args = { filePath: filepath, offset, limit }
1104
+ const pieces: Draft<MessageV2.Part>[] = [
1105
+ {
1106
+ messageID: info.id,
1107
+ sessionID: input.sessionID,
1108
+ type: "text",
1109
+ synthetic: true,
1110
+ text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
1111
+ },
1112
+ ]
1113
+ const read = yield* Effect.promise(() => registry.named.read.init()).pipe(
1114
+ Effect.flatMap((t) =>
1115
+ provider.getModel(info.model.providerID, info.model.modelID).pipe(
1116
+ Effect.flatMap((mdl) =>
1117
+ Effect.promise(() =>
1118
+ t.execute(args, {
1119
+ sessionID: input.sessionID,
1120
+ abort: new AbortController().signal,
1121
+ agent: input.agent!,
1122
+ messageID: info.id,
1123
+ extra: { bypassCwdCheck: true, model: mdl },
1124
+ messages: [],
1125
+ metadata: async () => {},
1126
+ ask: async () => {},
1127
+ }),
1128
+ ),
1129
+ ),
1130
+ ),
1131
+ ),
1132
+ Effect.exit,
1133
+ )
1134
+ if (Exit.isSuccess(read)) {
1135
+ const result = read.value
1136
+ pieces.push({
1137
+ messageID: info.id,
1138
+ sessionID: input.sessionID,
1139
+ type: "text",
1140
+ synthetic: true,
1141
+ text: result.output,
1142
+ })
1143
+ if (result.attachments?.length) {
1144
+ pieces.push(
1145
+ ...result.attachments.map((a) => ({
1146
+ ...a,
1147
+ synthetic: true,
1148
+ filename: a.filename ?? part.filename,
1149
+ messageID: info.id,
1150
+ sessionID: input.sessionID,
1151
+ })),
1152
+ )
1153
+ } else {
1154
+ pieces.push({ ...part, messageID: info.id, sessionID: input.sessionID })
1155
+ }
1156
+ } else {
1157
+ const error = Cause.squash(read.cause)
1158
+ log.error("failed to read file", { error })
1159
+ const message = error instanceof Error ? error.message : String(error)
1160
+ yield* bus.publish(Session.Event.Error, {
1161
+ sessionID: input.sessionID,
1162
+ error: new NamedError.Unknown({ message }).toObject(),
1163
+ })
1164
+ pieces.push({
1165
+ messageID: info.id,
1166
+ sessionID: input.sessionID,
1167
+ type: "text",
1168
+ synthetic: true,
1169
+ text: `Read tool failed to read ${filepath} with the following error: ${message}`,
1170
+ })
1171
+ }
1172
+ return pieces
1173
+ }
1174
+
1175
+ if (part.mime === "application/x-directory") {
1176
+ const args = { filePath: filepath }
1177
+ const result = yield* Effect.promise(() => registry.named.read.init()).pipe(
1178
+ Effect.flatMap((t) =>
1179
+ Effect.promise(() =>
1180
+ t.execute(args, {
1181
+ sessionID: input.sessionID,
1182
+ abort: new AbortController().signal,
1183
+ agent: input.agent!,
1184
+ messageID: info.id,
1185
+ extra: { bypassCwdCheck: true },
1186
+ messages: [],
1187
+ metadata: async () => {},
1188
+ ask: async () => {},
1189
+ }),
1190
+ ),
1191
+ ),
1192
+ )
1193
+ return [
1194
+ {
1195
+ messageID: info.id,
1196
+ sessionID: input.sessionID,
1197
+ type: "text",
1198
+ synthetic: true,
1199
+ text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
1200
+ },
1201
+ {
1202
+ messageID: info.id,
1203
+ sessionID: input.sessionID,
1204
+ type: "text",
1205
+ synthetic: true,
1206
+ text: result.output,
1207
+ },
1208
+ { ...part, messageID: info.id, sessionID: input.sessionID },
1209
+ ]
1210
+ }
1211
+
1212
+ yield* filetime.read(input.sessionID, filepath)
1213
+ return [
1214
+ {
1215
+ messageID: info.id,
1216
+ sessionID: input.sessionID,
1217
+ type: "text",
1218
+ synthetic: true,
1219
+ text: `Called the Read tool with the following input: {"filePath":"${filepath}"}`,
1220
+ },
1221
+ {
1222
+ id: part.id,
1223
+ messageID: info.id,
1224
+ sessionID: input.sessionID,
1225
+ type: "file",
1226
+ url:
1227
+ `data:${part.mime};base64,` +
1228
+ Buffer.from(yield* fsys.readFile(filepath).pipe(Effect.catch(Effect.die))).toString("base64"),
1229
+ mime: part.mime,
1230
+ filename: part.filename!,
1231
+ source: part.source,
1232
+ },
1233
+ ]
1234
+ }
1235
+ }
1236
+ }
1237
+
1238
+ if (part.type === "agent") {
1239
+ const perm = Permission.evaluate("task", part.name, ag.permission)
1240
+ const hint = perm.action === "deny" ? " . Invoked by user; guaranteed to exist." : ""
1241
+ return [
1242
+ { ...part, messageID: info.id, sessionID: input.sessionID },
1243
+ {
1244
+ messageID: info.id,
1245
+ sessionID: input.sessionID,
1246
+ type: "text",
1247
+ synthetic: true,
1248
+ text:
1249
+ " Use the above message and context to generate a prompt and call the task tool with subagent: " +
1250
+ part.name +
1251
+ hint,
1252
+ },
1253
+ ]
1254
+ }
1255
+
1256
+ return [{ ...part, messageID: info.id, sessionID: input.sessionID }]
1257
+ })
1258
+
1259
+ const parts = yield* Effect.forEach(input.parts, resolvePart, { concurrency: "unbounded" }).pipe(
1260
+ Effect.map((x) => x.flat().map(assign)),
1261
+ )
1262
+
1263
+ yield* plugin.trigger(
1264
+ "chat.message",
1265
+ {
1266
+ sessionID: input.sessionID,
1267
+ agent: input.agent,
1268
+ model: input.model,
1269
+ messageID: input.messageID,
1270
+ variant: input.variant,
1271
+ },
1272
+ { message: info, parts },
1273
+ )
1274
+
1275
+ const parsed = MessageV2.Info.safeParse(info)
1276
+ if (!parsed.success) {
1277
+ log.error("invalid user message before save", {
1278
+ sessionID: input.sessionID,
1279
+ messageID: info.id,
1280
+ agent: info.agent,
1281
+ model: info.model,
1282
+ issues: parsed.error.issues,
1283
+ })
1284
+ }
1285
+ parts.forEach((part, index) => {
1286
+ const p = MessageV2.Part.safeParse(part)
1287
+ if (p.success) return
1288
+ log.error("invalid user part before save", {
1289
+ sessionID: input.sessionID,
1290
+ messageID: info.id,
1291
+ partID: part.id,
1292
+ partType: part.type,
1293
+ index,
1294
+ issues: p.error.issues,
1295
+ part,
1296
+ })
1297
+ })
1298
+
1299
+ yield* sessions.updateMessage(info)
1300
+ for (const part of parts) yield* sessions.updatePart(part)
1301
+
1302
+ return { info, parts }
1303
+ }, Effect.scoped)
1304
+
1305
+ const prompt: (input: PromptInput) => Effect.Effect<MessageV2.WithParts> = Effect.fn("SessionPrompt.prompt")(
1306
+ function* (input: PromptInput) {
1307
+ const session = yield* sessions.get(input.sessionID)
1308
+ yield* Effect.promise(() => SessionRevert.cleanup(session))
1309
+ const message = yield* createUserMessage(input)
1310
+ yield* sessions.touch(input.sessionID)
1311
+
1312
+ const permissions: Permission.Ruleset = []
1313
+ for (const [t, enabled] of Object.entries(input.tools ?? {})) {
1314
+ permissions.push({ permission: t, action: enabled ? "allow" : "deny", pattern: "*" })
1315
+ }
1316
+ if (permissions.length > 0) {
1317
+ session.permission = permissions
1318
+ yield* sessions.setPermission({ sessionID: session.id, permission: permissions })
1319
+ }
1320
+
1321
+ if (input.noReply === true) return message
1322
+ return yield* loop({ sessionID: input.sessionID })
1323
+ },
1324
+ )
1325
+
1326
+ const lastAssistant = (sessionID: SessionID) =>
1327
+ Effect.promise(async () => {
1328
+ let latest: MessageV2.WithParts | undefined
1329
+ for await (const item of MessageV2.stream(sessionID)) {
1330
+ latest ??= item
1331
+ if (item.info.role !== "user") return item
1332
+ }
1333
+ if (latest) return latest
1334
+ throw new Error("Impossible")
1335
+ })
1336
+
1337
+ const runLoop: (sessionID: SessionID) => Effect.Effect<MessageV2.WithParts> = Effect.fn("SessionPrompt.run")(
1338
+ function* (sessionID: SessionID) {
1339
+ const ctx = yield* InstanceState.context
1340
+ let structured: unknown | undefined
1341
+ let step = 0
1342
+ const session = yield* sessions.get(sessionID)
1343
+
1344
+ while (true) {
1345
+ yield* status.set(sessionID, { type: "busy" })
1346
+ log.info("loop", { step, sessionID })
1347
+
1348
+ let msgs = yield* MessageV2.filterCompactedEffect(sessionID)
1349
+
1350
+ let lastUser: MessageV2.User | undefined
1351
+ let lastAssistant: MessageV2.Assistant | undefined
1352
+ let lastFinished: MessageV2.Assistant | undefined
1353
+ let tasks: (MessageV2.CompactionPart | MessageV2.SubtaskPart)[] = []
1354
+ for (let i = msgs.length - 1; i >= 0; i--) {
1355
+ const msg = msgs[i]
1356
+ if (!lastUser && msg.info.role === "user") lastUser = msg.info
1357
+ if (!lastAssistant && msg.info.role === "assistant") lastAssistant = msg.info
1358
+ if (!lastFinished && msg.info.role === "assistant" && msg.info.finish) lastFinished = msg.info
1359
+ if (lastUser && lastFinished) break
1360
+ const task = msg.parts.filter((part) => part.type === "compaction" || part.type === "subtask")
1361
+ if (task && !lastFinished) tasks.push(...task)
1362
+ }
1363
+
1364
+ if (!lastUser) throw new Error("No user message found in stream. This should never happen.")
1365
+
1366
+ const lastAssistantMsg = msgs.findLast(
1367
+ (msg) => msg.info.role === "assistant" && msg.info.id === lastAssistant?.id,
1368
+ )
1369
+ // Some providers return "stop" even when the assistant message contains tool calls.
1370
+ // Keep the loop running so tool results can be sent back to the model.
1371
+ const hasToolCalls = lastAssistantMsg?.parts.some((part) => part.type === "tool") ?? false
1372
+
1373
+ if (
1374
+ lastAssistant?.finish &&
1375
+ !["tool-calls"].includes(lastAssistant.finish) &&
1376
+ !hasToolCalls &&
1377
+ lastUser.id < lastAssistant.id
1378
+ ) {
1379
+ log.info("exiting loop", { sessionID })
1380
+ break
1381
+ }
1382
+
1383
+ step++
1384
+ if (step === 1)
1385
+ yield* title({
1386
+ session,
1387
+ modelID: lastUser.model.modelID,
1388
+ providerID: lastUser.model.providerID,
1389
+ history: msgs,
1390
+ }).pipe(Effect.ignore, Effect.forkIn(scope))
1391
+
1392
+ const model = yield* getModel(lastUser.model.providerID, lastUser.model.modelID, sessionID)
1393
+ const task = tasks.pop()
1394
+
1395
+ if (task?.type === "subtask") {
1396
+ yield* handleSubtask({ task, model, lastUser, sessionID, session, msgs })
1397
+ continue
1398
+ }
1399
+
1400
+ if (task?.type === "compaction") {
1401
+ const result = yield* compaction.process({
1402
+ messages: msgs,
1403
+ parentID: lastUser.id,
1404
+ sessionID,
1405
+ auto: task.auto,
1406
+ overflow: task.overflow,
1407
+ })
1408
+ if (result === "stop") break
1409
+ continue
1410
+ }
1411
+
1412
+ if (
1413
+ lastFinished &&
1414
+ lastFinished.summary !== true &&
1415
+ (yield* compaction.isOverflow({ tokens: lastFinished.tokens, model }))
1416
+ ) {
1417
+ yield* compaction.create({ sessionID, agent: lastUser.agent, model: lastUser.model, auto: true })
1418
+ continue
1419
+ }
1420
+
1421
+ const agent = yield* agents.get(lastUser.agent)
1422
+ if (!agent) {
1423
+ const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
1424
+ const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
1425
+ const error = new NamedError.Unknown({ message: `Agent not found: "${lastUser.agent}".${hint}` })
1426
+ yield* bus.publish(Session.Event.Error, { sessionID, error: error.toObject() })
1427
+ throw error
1428
+ }
1429
+ const maxSteps = agent.steps ?? Infinity
1430
+ const isLastStep = step >= maxSteps
1431
+ msgs = yield* insertReminders({ messages: msgs, agent, session })
1432
+
1433
+ const msg: MessageV2.Assistant = {
1434
+ id: MessageID.ascending(),
1435
+ parentID: lastUser.id,
1436
+ role: "assistant",
1437
+ mode: agent.name,
1438
+ agent: agent.name,
1439
+ variant: lastUser.variant,
1440
+ path: { cwd: ctx.directory, root: ctx.worktree },
1441
+ cost: 0,
1442
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1443
+ modelID: model.id,
1444
+ providerID: model.providerID,
1445
+ time: { created: Date.now() },
1446
+ sessionID,
1447
+ }
1448
+ yield* sessions.updateMessage(msg)
1449
+ const handle = yield* processor.create({
1450
+ assistantMessage: msg,
1451
+ sessionID,
1452
+ model,
1453
+ })
1454
+
1455
+ const outcome: "break" | "continue" = yield* Effect.onExit(
1456
+ Effect.gen(function* () {
1457
+ const lastUserMsg = msgs.findLast((m) => m.info.role === "user")
1458
+ const bypassAgentCheck = lastUserMsg?.parts.some((p) => p.type === "agent") ?? false
1459
+
1460
+ const tools = yield* resolveTools({
1461
+ agent,
1462
+ session,
1463
+ model,
1464
+ tools: lastUser.tools,
1465
+ processor: handle,
1466
+ bypassAgentCheck,
1467
+ messages: msgs,
1468
+ })
1469
+
1470
+ if (lastUser.format?.type === "json_schema") {
1471
+ tools["StructuredOutput"] = createStructuredOutputTool({
1472
+ schema: lastUser.format.schema,
1473
+ onSuccess(output) {
1474
+ structured = output
1475
+ },
1476
+ })
1477
+ }
1478
+
1479
+ if (step === 1) SessionSummary.summarize({ sessionID, messageID: lastUser.id })
1480
+
1481
+ if (step > 1 && lastFinished) {
1482
+ for (const m of msgs) {
1483
+ if (m.info.role !== "user" || m.info.id <= lastFinished.id) continue
1484
+ for (const p of m.parts) {
1485
+ if (p.type !== "text" || p.ignored || p.synthetic) continue
1486
+ if (!p.text.trim()) continue
1487
+ p.text = [
1488
+ "<system-reminder>",
1489
+ "The user sent the following message:",
1490
+ p.text,
1491
+ "",
1492
+ "Please address this message and continue with your tasks.",
1493
+ "</system-reminder>",
1494
+ ].join("\n")
1495
+ }
1496
+ }
1497
+ }
1498
+
1499
+ yield* plugin.trigger("experimental.chat.messages.transform", {}, { messages: msgs })
1500
+
1501
+ const [skills, env, instructions, modelMsgs] = yield* Effect.all([
1502
+ Effect.promise(() => SystemPrompt.skills(agent)),
1503
+ Effect.promise(() => SystemPrompt.environment(model)),
1504
+ instruction.system().pipe(Effect.orDie),
1505
+ Effect.promise(() => MessageV2.toModelMessages(msgs, model)),
1506
+ ])
1507
+ const system = [...env, ...(skills ? [skills] : []), ...instructions]
1508
+ const format = lastUser.format ?? { type: "text" as const }
1509
+ if (format.type === "json_schema") system.push(STRUCTURED_OUTPUT_SYSTEM_PROMPT)
1510
+ const result = yield* handle.process({
1511
+ user: lastUser,
1512
+ agent,
1513
+ permission: session.permission,
1514
+ sessionID,
1515
+ parentSessionID: session.parentID,
1516
+ system,
1517
+ messages: [...modelMsgs, ...(isLastStep ? [{ role: "assistant" as const, content: MAX_STEPS }] : [])],
1518
+ tools,
1519
+ model,
1520
+ toolChoice: format.type === "json_schema" ? "required" : undefined,
1521
+ })
1522
+
1523
+ if (structured !== undefined) {
1524
+ handle.message.structured = structured
1525
+ handle.message.finish = handle.message.finish ?? "stop"
1526
+ yield* sessions.updateMessage(handle.message)
1527
+ return "break" as const
1528
+ }
1529
+
1530
+ const finished = handle.message.finish && !["tool-calls", "unknown"].includes(handle.message.finish)
1531
+ if (finished && !handle.message.error) {
1532
+ if (format.type === "json_schema") {
1533
+ handle.message.error = new MessageV2.StructuredOutputError({
1534
+ message: "Model did not produce structured output",
1535
+ retries: 0,
1536
+ }).toObject()
1537
+ yield* sessions.updateMessage(handle.message)
1538
+ return "break" as const
1539
+ }
1540
+ }
1541
+
1542
+ if (result === "stop") return "break" as const
1543
+ if (result === "compact") {
1544
+ yield* compaction.create({
1545
+ sessionID,
1546
+ agent: lastUser.agent,
1547
+ model: lastUser.model,
1548
+ auto: true,
1549
+ overflow: !handle.message.finish,
1550
+ })
1551
+ }
1552
+ return "continue" as const
1553
+ }),
1554
+ Effect.fnUntraced(function* (exit) {
1555
+ if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) yield* handle.abort()
1556
+ yield* InstanceState.withALS(() => instruction.clear(handle.message.id)).pipe(Effect.flatMap((x) => x))
1557
+ }),
1558
+ )
1559
+ if (outcome === "break") break
1560
+ continue
1561
+ }
1562
+
1563
+ yield* compaction.prune({ sessionID }).pipe(Effect.ignore, Effect.forkIn(scope))
1564
+ return yield* lastAssistant(sessionID)
1565
+ },
1566
+ )
1567
+
1568
+ const loop: (input: z.infer<typeof LoopInput>) => Effect.Effect<MessageV2.WithParts> = Effect.fn(
1569
+ "SessionPrompt.loop",
1570
+ )(function* (input: z.infer<typeof LoopInput>) {
1571
+ const s = yield* InstanceState.get(state)
1572
+ const runner = getRunner(s.runners, input.sessionID)
1573
+ return yield* runner.ensureRunning(runLoop(input.sessionID))
1574
+ })
1575
+
1576
+ const shell: (input: ShellInput) => Effect.Effect<MessageV2.WithParts> = Effect.fn("SessionPrompt.shell")(
1577
+ function* (input: ShellInput) {
1578
+ const s = yield* InstanceState.get(state)
1579
+ const runner = getRunner(s.runners, input.sessionID)
1580
+ return yield* runner.startShell((signal) => shellImpl(input, signal))
1581
+ },
1582
+ )
1583
+
1584
+ const command = Effect.fn("SessionPrompt.command")(function* (input: CommandInput) {
1585
+ log.info("command", input)
1586
+ const cmd = yield* commands.get(input.command)
1587
+ if (!cmd) {
1588
+ const available = (yield* commands.list()).map((c) => c.name)
1589
+ const hint = available.length ? ` Available commands: ${available.join(", ")}` : ""
1590
+ const error = new NamedError.Unknown({ message: `Command not found: "${input.command}".${hint}` })
1591
+ yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
1592
+ throw error
1593
+ }
1594
+ const agentName = cmd.agent ?? input.agent ?? (yield* agents.defaultAgent())
1595
+
1596
+ const raw = input.arguments.match(argsRegex) ?? []
1597
+ const args = raw.map((arg) => arg.replace(quoteTrimRegex, ""))
1598
+ const templateCommand = yield* Effect.promise(async () => cmd.template)
1599
+
1600
+ const placeholders = templateCommand.match(placeholderRegex) ?? []
1601
+ let last = 0
1602
+ for (const item of placeholders) {
1603
+ const value = Number(item.slice(1))
1604
+ if (value > last) last = value
1605
+ }
1606
+
1607
+ const withArgs = templateCommand.replaceAll(placeholderRegex, (_, index) => {
1608
+ const position = Number(index)
1609
+ const argIndex = position - 1
1610
+ if (argIndex >= args.length) return ""
1611
+ if (position === last) return args.slice(argIndex).join(" ")
1612
+ return args[argIndex]
1613
+ })
1614
+ const usesArgumentsPlaceholder = templateCommand.includes("$ARGUMENTS")
1615
+ let template = withArgs.replaceAll("$ARGUMENTS", input.arguments)
1616
+
1617
+ if (placeholders.length === 0 && !usesArgumentsPlaceholder && input.arguments.trim()) {
1618
+ template = template + "\n\n" + input.arguments
1619
+ }
1620
+
1621
+ const shellMatches = ConfigMarkdown.shell(template)
1622
+ if (shellMatches.length > 0) {
1623
+ const sh = Shell.preferred()
1624
+ const results = yield* Effect.promise(() =>
1625
+ Promise.all(
1626
+ shellMatches.map(async ([, cmd]) => (await Process.text([cmd], { shell: sh, nothrow: true })).text),
1627
+ ),
1628
+ )
1629
+ let index = 0
1630
+ template = template.replace(bashRegex, () => results[index++])
1631
+ }
1632
+ template = template.trim()
1633
+
1634
+ const taskModel = yield* Effect.gen(function* () {
1635
+ if (cmd.model) return Provider.parseModel(cmd.model)
1636
+ if (cmd.agent) {
1637
+ const cmdAgent = yield* agents.get(cmd.agent)
1638
+ if (cmdAgent?.model) return cmdAgent.model
1639
+ }
1640
+ if (input.model) return Provider.parseModel(input.model)
1641
+ return yield* lastModel(input.sessionID)
1642
+ })
1643
+
1644
+ yield* getModel(taskModel.providerID, taskModel.modelID, input.sessionID)
1645
+
1646
+ const agent = yield* agents.get(agentName)
1647
+ if (!agent) {
1648
+ const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
1649
+ const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
1650
+ const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
1651
+ yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
1652
+ throw error
1653
+ }
1654
+
1655
+ const templateParts = yield* resolvePromptParts(template)
1656
+ const isSubtask = (agent.mode === "subagent" && cmd.subtask !== false) || cmd.subtask === true
1657
+ const parts = isSubtask
1658
+ ? [
1659
+ {
1660
+ type: "subtask" as const,
1661
+ agent: agent.name,
1662
+ description: cmd.description ?? "",
1663
+ command: input.command,
1664
+ model: { providerID: taskModel.providerID, modelID: taskModel.modelID },
1665
+ prompt: templateParts.find((y) => y.type === "text")?.text ?? "",
1666
+ },
1667
+ ]
1668
+ : [...templateParts, ...(input.parts ?? [])]
1669
+
1670
+ const userAgent = isSubtask ? (input.agent ?? (yield* agents.defaultAgent())) : agentName
1671
+ const userModel = isSubtask
1672
+ ? input.model
1673
+ ? Provider.parseModel(input.model)
1674
+ : yield* lastModel(input.sessionID)
1675
+ : taskModel
1676
+
1677
+ yield* plugin.trigger(
1678
+ "command.execute.before",
1679
+ { command: input.command, sessionID: input.sessionID, arguments: input.arguments },
1680
+ { parts },
1681
+ )
1682
+
1683
+ const result = yield* prompt({
1684
+ sessionID: input.sessionID,
1685
+ messageID: input.messageID,
1686
+ model: userModel,
1687
+ agent: userAgent,
1688
+ parts,
1689
+ variant: input.variant,
1690
+ })
1691
+ yield* bus.publish(Command.Event.Executed, {
1692
+ name: input.command,
1693
+ sessionID: input.sessionID,
1694
+ arguments: input.arguments,
1695
+ messageID: result.info.id,
1696
+ })
1697
+ return result
1698
+ })
1699
+
1700
+ return Service.of({
1701
+ assertNotBusy,
1702
+ cancel,
1703
+ prompt,
1704
+ loop,
1705
+ shell,
1706
+ command,
1707
+ resolvePromptParts,
1708
+ })
1709
+ }),
1710
+ )
1711
+
1712
+ const defaultLayer = Layer.unwrap(
1713
+ Effect.sync(() =>
1714
+ layer.pipe(
1715
+ Layer.provide(SessionStatus.layer),
1716
+ Layer.provide(SessionCompaction.defaultLayer),
1717
+ Layer.provide(SessionProcessor.defaultLayer),
1718
+ Layer.provide(Command.defaultLayer),
1719
+ Layer.provide(Permission.defaultLayer),
1720
+ Layer.provide(MCP.defaultLayer),
1721
+ Layer.provide(LSP.defaultLayer),
1722
+ Layer.provide(FileTime.defaultLayer),
1723
+ Layer.provide(ToolRegistry.defaultLayer),
1724
+ Layer.provide(Truncate.layer),
1725
+ Layer.provide(Provider.defaultLayer),
1726
+ Layer.provide(Instruction.defaultLayer),
1727
+ Layer.provide(AppFileSystem.defaultLayer),
1728
+ Layer.provide(Plugin.defaultLayer),
1729
+ Layer.provide(Session.defaultLayer),
1730
+ Layer.provide(Agent.defaultLayer),
1731
+ Layer.provide(Bus.layer),
1732
+ Layer.provide(CrossSpawnSpawner.defaultLayer),
1733
+ ),
1734
+ ),
1735
+ )
1736
+ const { runPromise } = makeRuntime(Service, defaultLayer)
1737
+
1738
+ export async function assertNotBusy(sessionID: SessionID) {
1739
+ return runPromise((svc) => svc.assertNotBusy(SessionID.zod.parse(sessionID)))
1740
+ }
1741
+
1742
+ export const PromptInput = z.object({
1743
+ sessionID: SessionID.zod,
1744
+ messageID: MessageID.zod.optional(),
1745
+ model: z
1746
+ .object({
1747
+ providerID: ProviderID.zod,
1748
+ modelID: ModelID.zod,
1749
+ })
1750
+ .optional(),
1751
+ agent: z.string().optional(),
1752
+ noReply: z.boolean().optional(),
1753
+ tools: z
1754
+ .record(z.string(), z.boolean())
1755
+ .optional()
1756
+ .describe(
1757
+ "@deprecated tools and permissions have been merged, you can set permissions on the session itself now",
1758
+ ),
1759
+ format: MessageV2.Format.optional(),
1760
+ system: z.string().optional(),
1761
+ variant: z.string().optional(),
1762
+ parts: z.array(
1763
+ z.discriminatedUnion("type", [
1764
+ MessageV2.TextPart.omit({
1765
+ messageID: true,
1766
+ sessionID: true,
1767
+ })
1768
+ .partial({
1769
+ id: true,
1770
+ })
1771
+ .meta({
1772
+ ref: "TextPartInput",
1773
+ }),
1774
+ MessageV2.FilePart.omit({
1775
+ messageID: true,
1776
+ sessionID: true,
1777
+ })
1778
+ .partial({
1779
+ id: true,
1780
+ })
1781
+ .meta({
1782
+ ref: "FilePartInput",
1783
+ }),
1784
+ MessageV2.AgentPart.omit({
1785
+ messageID: true,
1786
+ sessionID: true,
1787
+ })
1788
+ .partial({
1789
+ id: true,
1790
+ })
1791
+ .meta({
1792
+ ref: "AgentPartInput",
1793
+ }),
1794
+ MessageV2.SubtaskPart.omit({
1795
+ messageID: true,
1796
+ sessionID: true,
1797
+ })
1798
+ .partial({
1799
+ id: true,
1800
+ })
1801
+ .meta({
1802
+ ref: "SubtaskPartInput",
1803
+ }),
1804
+ ]),
1805
+ ),
1806
+ })
1807
+ export type PromptInput = z.infer<typeof PromptInput>
1808
+
1809
+ export async function prompt(input: PromptInput) {
1810
+ return runPromise((svc) => svc.prompt(PromptInput.parse(input)))
1811
+ }
1812
+
1813
+ export async function resolvePromptParts(template: string) {
1814
+ return runPromise((svc) => svc.resolvePromptParts(z.string().parse(template)))
1815
+ }
1816
+
1817
+ export async function cancel(sessionID: SessionID) {
1818
+ return runPromise((svc) => svc.cancel(SessionID.zod.parse(sessionID)))
1819
+ }
1820
+
1821
+ export const LoopInput = z.object({
1822
+ sessionID: SessionID.zod,
1823
+ })
1824
+
1825
+ export async function loop(input: z.infer<typeof LoopInput>) {
1826
+ return runPromise((svc) => svc.loop(LoopInput.parse(input)))
1827
+ }
1828
+
1829
+ export const ShellInput = z.object({
1830
+ sessionID: SessionID.zod,
1831
+ messageID: MessageID.zod.optional(),
1832
+ agent: z.string(),
1833
+ model: z
1834
+ .object({
1835
+ providerID: ProviderID.zod,
1836
+ modelID: ModelID.zod,
1837
+ })
1838
+ .optional(),
1839
+ command: z.string(),
1840
+ })
1841
+ export type ShellInput = z.infer<typeof ShellInput>
1842
+
1843
+ export async function shell(input: ShellInput) {
1844
+ return runPromise((svc) => svc.shell(ShellInput.parse(input)))
1845
+ }
1846
+
1847
+ export const CommandInput = z.object({
1848
+ messageID: MessageID.zod.optional(),
1849
+ sessionID: SessionID.zod,
1850
+ agent: z.string().optional(),
1851
+ model: z.string().optional(),
1852
+ arguments: z.string(),
1853
+ command: z.string(),
1854
+ variant: z.string().optional(),
1855
+ parts: z
1856
+ .array(
1857
+ z.discriminatedUnion("type", [
1858
+ MessageV2.FilePart.omit({
1859
+ messageID: true,
1860
+ sessionID: true,
1861
+ }).partial({
1862
+ id: true,
1863
+ }),
1864
+ ]),
1865
+ )
1866
+ .optional(),
1867
+ })
1868
+ export type CommandInput = z.infer<typeof CommandInput>
1869
+
1870
+ export async function command(input: CommandInput) {
1871
+ return runPromise((svc) => svc.command(CommandInput.parse(input)))
1872
+ }
1873
+
1874
+ /** @internal Exported for testing */
1875
+ export function createStructuredOutputTool(input: {
1876
+ schema: Record<string, any>
1877
+ onSuccess: (output: unknown) => void
1878
+ }): AITool {
1879
+ // Remove $schema property if present (not needed for tool input)
1880
+ const { $schema, ...toolSchema } = input.schema
1881
+
1882
+ return tool({
1883
+ id: "StructuredOutput" as any,
1884
+ description: STRUCTURED_OUTPUT_DESCRIPTION,
1885
+ inputSchema: jsonSchema(toolSchema as any),
1886
+ async execute(args) {
1887
+ // AI SDK validates args against inputSchema before calling execute()
1888
+ input.onSuccess(args)
1889
+ return {
1890
+ output: "Structured output captured successfully.",
1891
+ title: "Structured Output",
1892
+ metadata: { valid: true },
1893
+ }
1894
+ },
1895
+ toModelOutput({ output }) {
1896
+ return {
1897
+ type: "text",
1898
+ value: output.output,
1899
+ }
1900
+ },
1901
+ })
1902
+ }
1903
+ const bashRegex = /!`([^`]+)`/g
1904
+ // Match [Image N] as single token, quoted strings, or non-space sequences
1905
+ const argsRegex = /(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi
1906
+ const placeholderRegex = /\$(\d+)/g
1907
+ const quoteTrimRegex = /^["']|["']$/g
1908
+ }