innocode 1.0.0

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