@toolkit-cli/toolkode 1.3.7

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