opencode-v2 1.1.53

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