@code0123/opencode-android-arm64 1.1.55 → 1.1.57

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