easc-cli 1.1.28

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