@stonerzju/opencode 1.2.16-offline.1

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