rird 2.1.231 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/AGENTS.md +86 -0
  2. package/COMPLETED_TEST_SUITE.txt +280 -0
  3. package/Dockerfile +18 -0
  4. package/README.md +397 -6
  5. package/RIRD_ERROR_HANDLING_SUMMARY.md +307 -0
  6. package/TESTING.md +512 -0
  7. package/TEST_IMPLEMENTATION_REPORT.md +463 -0
  8. package/TEST_SUITE.md +307 -0
  9. package/TEST_SUMMARY.txt +380 -0
  10. package/bin/rird-perf.js +37 -0
  11. package/bin/rird.js +43 -8
  12. package/bunfig.toml +4 -0
  13. package/create-wrapper.ps1 +51 -0
  14. package/docs/ARCHITECTURE.md +768 -0
  15. package/docs/CLI_REFERENCE.md +681 -0
  16. package/docs/DOCUMENTATION_MANIFEST.md +392 -0
  17. package/docs/INDEX.md +295 -0
  18. package/docs/PRODUCTION_SETUP.md +633 -0
  19. package/docs/TROUBLESHOOTING.md +914 -0
  20. package/facebook_ads_library.png +0 -0
  21. package/nul +0 -0
  22. package/nul`nif +0 -0
  23. package/package.json +104 -15
  24. package/parsers-config.ts +239 -0
  25. package/rird-1.0.199.tgz +0 -0
  26. package/rird-1.0.205.tgz +0 -0
  27. package/script/build-windows.ts +56 -0
  28. package/script/build.ts +165 -0
  29. package/{postinstall.mjs → script/postinstall.mjs} +47 -68
  30. package/script/publish-registries.ts +187 -0
  31. package/script/publish.ts +85 -0
  32. package/script/schema.ts +47 -0
  33. package/src/acp/README.md +164 -0
  34. package/src/acp/agent.ts +1063 -0
  35. package/src/acp/session.ts +101 -0
  36. package/src/acp/types.ts +22 -0
  37. package/src/agent/agent.ts +367 -0
  38. package/src/agent/generate.txt +75 -0
  39. package/src/agent/prompt/compaction.txt +12 -0
  40. package/src/agent/prompt/explore.txt +18 -0
  41. package/src/agent/prompt/summary.txt +10 -0
  42. package/src/agent/prompt/title.txt +36 -0
  43. package/src/auth/index.ts +70 -0
  44. package/src/bun/index.ts +114 -0
  45. package/src/bus/bus-event.ts +43 -0
  46. package/src/bus/global.ts +10 -0
  47. package/src/bus/index.ts +105 -0
  48. package/src/cli/bootstrap.ts +17 -0
  49. package/src/cli/cmd/acp.ts +104 -0
  50. package/src/cli/cmd/activate.ts +50 -0
  51. package/src/cli/cmd/agent.ts +256 -0
  52. package/src/cli/cmd/auth.ts +412 -0
  53. package/src/cli/cmd/cmd.ts +7 -0
  54. package/src/cli/cmd/debug/config.ts +15 -0
  55. package/src/cli/cmd/debug/file.ts +91 -0
  56. package/src/cli/cmd/debug/index.ts +43 -0
  57. package/src/cli/cmd/debug/lsp.ts +48 -0
  58. package/src/cli/cmd/debug/ripgrep.ts +83 -0
  59. package/src/cli/cmd/debug/scrap.ts +15 -0
  60. package/src/cli/cmd/debug/skill.ts +15 -0
  61. package/src/cli/cmd/debug/snapshot.ts +48 -0
  62. package/src/cli/cmd/export.ts +88 -0
  63. package/src/cli/cmd/generate.ts +38 -0
  64. package/src/cli/cmd/github.ts +1400 -0
  65. package/src/cli/cmd/import.ts +98 -0
  66. package/src/cli/cmd/mcp.ts +654 -0
  67. package/src/cli/cmd/models.ts +68 -0
  68. package/src/cli/cmd/pr.ts +112 -0
  69. package/src/cli/cmd/run.ts +434 -0
  70. package/src/cli/cmd/serve.ts +31 -0
  71. package/src/cli/cmd/session.ts +106 -0
  72. package/src/cli/cmd/stats.ts +298 -0
  73. package/src/cli/cmd/tui/app.tsx +694 -0
  74. package/src/cli/cmd/tui/attach.ts +30 -0
  75. package/src/cli/cmd/tui/component/border.tsx +21 -0
  76. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  77. package/src/cli/cmd/tui/component/dialog-command.tsx +124 -0
  78. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  79. package/src/cli/cmd/tui/component/dialog-model.tsx +236 -0
  80. package/src/cli/cmd/tui/component/dialog-provider.tsx +240 -0
  81. package/src/cli/cmd/tui/component/dialog-session-list.tsx +102 -0
  82. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  83. package/src/cli/cmd/tui/component/dialog-stash.tsx +86 -0
  84. package/src/cli/cmd/tui/component/dialog-status.tsx +162 -0
  85. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  86. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  87. package/src/cli/cmd/tui/component/did-you-know.tsx +85 -0
  88. package/src/cli/cmd/tui/component/logo.tsx +48 -0
  89. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +574 -0
  90. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  91. package/src/cli/cmd/tui/component/prompt/index.tsx +1087 -0
  92. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  93. package/src/cli/cmd/tui/component/tips.ts +27 -0
  94. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  95. package/src/cli/cmd/tui/context/args.tsx +14 -0
  96. package/src/cli/cmd/tui/context/directory.ts +13 -0
  97. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  98. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  99. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  100. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  101. package/src/cli/cmd/tui/context/local.tsx +345 -0
  102. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  103. package/src/cli/cmd/tui/context/route.tsx +46 -0
  104. package/src/cli/cmd/tui/context/sdk.tsx +74 -0
  105. package/src/cli/cmd/tui/context/sync.tsx +372 -0
  106. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  107. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  108. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  109. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  110. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  111. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  112. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  113. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  114. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  115. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  116. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  117. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  118. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  119. package/src/cli/cmd/tui/context/theme/lucent-orng.json +227 -0
  120. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  121. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  122. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  123. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  124. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  125. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  126. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  127. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  128. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  129. package/src/cli/cmd/tui/context/theme/rird.json +245 -0
  130. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  131. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  132. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  133. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  134. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  135. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  136. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  137. package/src/cli/cmd/tui/context/theme.tsx +1109 -0
  138. package/src/cli/cmd/tui/event.ts +40 -0
  139. package/src/cli/cmd/tui/hooks/use-safe-terminal-dimensions.ts +12 -0
  140. package/src/cli/cmd/tui/routes/home.tsx +138 -0
  141. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  142. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  143. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  144. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  145. package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
  146. package/src/cli/cmd/tui/routes/session/header.tsx +125 -0
  147. package/src/cli/cmd/tui/routes/session/index.tsx +1876 -0
  148. package/src/cli/cmd/tui/routes/session/sidebar.tsx +320 -0
  149. package/src/cli/cmd/tui/spawn.ts +60 -0
  150. package/src/cli/cmd/tui/thread.ts +142 -0
  151. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  152. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  153. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  154. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  155. package/src/cli/cmd/tui/ui/dialog-select.tsx +333 -0
  156. package/src/cli/cmd/tui/ui/dialog.tsx +171 -0
  157. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  158. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  159. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  160. package/src/cli/cmd/tui/util/editor.ts +32 -0
  161. package/src/cli/cmd/tui/util/terminal.ts +146 -0
  162. package/src/cli/cmd/tui/worker.ts +63 -0
  163. package/src/cli/cmd/uninstall.ts +344 -0
  164. package/src/cli/cmd/upgrade.ts +127 -0
  165. package/src/cli/cmd/web.ts +84 -0
  166. package/src/cli/error.ts +69 -0
  167. package/src/cli/ui.ts +101 -0
  168. package/src/cli/upgrade.ts +28 -0
  169. package/src/command/index.ts +80 -0
  170. package/src/command/template/initialize.txt +10 -0
  171. package/src/command/template/review.txt +97 -0
  172. package/src/config/config.ts +994 -0
  173. package/src/config/markdown.ts +41 -0
  174. package/src/env/index.ts +26 -0
  175. package/src/file/ignore.ts +83 -0
  176. package/src/file/index.ts +328 -0
  177. package/src/file/ripgrep.ts +393 -0
  178. package/src/file/time.ts +64 -0
  179. package/src/file/watcher.ts +103 -0
  180. package/src/flag/flag.ts +84 -0
  181. package/src/format/formatter.ts +315 -0
  182. package/src/format/index.ts +137 -0
  183. package/src/global/index.ts +101 -0
  184. package/src/id/id.ts +73 -0
  185. package/src/ide/index.ts +76 -0
  186. package/src/index.ts +297 -0
  187. package/src/index.ts.backup +271 -0
  188. package/src/installation/index.ts +258 -0
  189. package/src/lib/IMPLEMENTATION_NOTES.md +345 -0
  190. package/src/lib/error-handler.ts +225 -0
  191. package/src/lib/error-testing-guide.md +258 -0
  192. package/src/lib/errors.ts +285 -0
  193. package/src/lib/performance.ts +70 -0
  194. package/src/lib/telemetry.ts +282 -0
  195. package/src/lsp/client.ts +229 -0
  196. package/src/lsp/index.ts +485 -0
  197. package/src/lsp/language.ts +116 -0
  198. package/src/lsp/server.ts +1895 -0
  199. package/src/mcp/auth.ts +135 -0
  200. package/src/mcp/index.ts +1117 -0
  201. package/src/mcp/intent-analyzer.ts +376 -0
  202. package/src/mcp/oauth-callback.ts +200 -0
  203. package/src/mcp/oauth-provider.ts +154 -0
  204. package/src/patch/index.ts +632 -0
  205. package/src/permission/index.ts +199 -0
  206. package/src/plugin/index.ts +91 -0
  207. package/src/project/bootstrap.ts +33 -0
  208. package/src/project/instance.ts +78 -0
  209. package/src/project/project.ts +236 -0
  210. package/src/project/state.ts +65 -0
  211. package/src/project/vcs.ts +76 -0
  212. package/src/provider/auth.ts +143 -0
  213. package/src/provider/models-macro.ts +55 -0
  214. package/src/provider/models.ts +161 -0
  215. package/src/provider/provider.ts +1109 -0
  216. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  217. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  218. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
  219. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  220. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  221. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  222. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  223. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  224. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  225. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  226. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  227. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  228. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  229. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  230. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  231. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  232. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  233. package/src/provider/transform.ts +455 -0
  234. package/src/pty/index.ts +231 -0
  235. package/src/security/guardrails.test.ts +341 -0
  236. package/src/security/guardrails.ts +570 -0
  237. package/src/security/index.ts +19 -0
  238. package/src/server/error.ts +36 -0
  239. package/src/server/project.ts +79 -0
  240. package/src/server/server.ts +2641 -0
  241. package/src/server/tui.ts +71 -0
  242. package/src/session/compaction.ts +228 -0
  243. package/src/session/index.ts +464 -0
  244. package/src/session/llm.ts +201 -0
  245. package/src/session/message-v2.ts +695 -0
  246. package/src/session/message.ts +189 -0
  247. package/src/session/processor.ts +409 -0
  248. package/src/session/prompt/act-switch.txt +5 -0
  249. package/src/session/prompt/anthropic-20250930.txt +166 -0
  250. package/src/session/prompt/anthropic.txt +63 -0
  251. package/src/session/prompt/anthropic_spoof.txt +1 -0
  252. package/src/session/prompt/beast.txt +76 -0
  253. package/src/session/prompt/codex.txt +304 -0
  254. package/src/session/prompt/copilot-gpt-5.txt +137 -0
  255. package/src/session/prompt/gemini.txt +62 -0
  256. package/src/session/prompt/max-steps.txt +16 -0
  257. package/src/session/prompt/plan-reminder-anthropic.txt +35 -0
  258. package/src/session/prompt/plan.txt +24 -0
  259. package/src/session/prompt/polaris.txt +88 -0
  260. package/src/session/prompt/qwen.txt +59 -0
  261. package/src/session/prompt.ts +1552 -0
  262. package/src/session/retry.ts +86 -0
  263. package/src/session/revert.ts +108 -0
  264. package/src/session/sensitive-filter.test.ts +327 -0
  265. package/src/session/sensitive-filter.ts +466 -0
  266. package/src/session/status.ts +76 -0
  267. package/src/session/summary.ts +209 -0
  268. package/src/session/system.ts +122 -0
  269. package/src/session/todo.ts +37 -0
  270. package/src/share/share-next.ts +222 -0
  271. package/src/share/share.ts +87 -0
  272. package/src/shell/shell.ts +67 -0
  273. package/src/skill/index.ts +1 -0
  274. package/src/skill/skill.ts +83 -0
  275. package/src/snapshot/index.ts +197 -0
  276. package/src/storage/storage.ts +226 -0
  277. package/src/tests/agent.test.ts +308 -0
  278. package/src/tests/build-guards.test.ts +267 -0
  279. package/src/tests/config.test.ts +664 -0
  280. package/src/tests/tool-registry.test.ts +589 -0
  281. package/src/tool/bash.ts +314 -0
  282. package/src/tool/bash.txt +158 -0
  283. package/src/tool/batch.ts +175 -0
  284. package/src/tool/batch.txt +24 -0
  285. package/src/tool/codesearch.ts +184 -0
  286. package/src/tool/codesearch.txt +12 -0
  287. package/src/tool/edit.ts +675 -0
  288. package/src/tool/edit.txt +10 -0
  289. package/src/tool/glob.ts +65 -0
  290. package/src/tool/glob.txt +6 -0
  291. package/src/tool/grep.ts +121 -0
  292. package/src/tool/grep.txt +8 -0
  293. package/src/tool/invalid.ts +17 -0
  294. package/src/tool/ls.ts +110 -0
  295. package/src/tool/ls.txt +1 -0
  296. package/src/tool/lsp-diagnostics.ts +26 -0
  297. package/src/tool/lsp-diagnostics.txt +1 -0
  298. package/src/tool/lsp-hover.ts +31 -0
  299. package/src/tool/lsp-hover.txt +1 -0
  300. package/src/tool/lsp.ts +87 -0
  301. package/src/tool/lsp.txt +19 -0
  302. package/src/tool/multiedit.ts +46 -0
  303. package/src/tool/multiedit.txt +41 -0
  304. package/src/tool/patch.ts +233 -0
  305. package/src/tool/patch.txt +1 -0
  306. package/src/tool/read.ts +219 -0
  307. package/src/tool/read.txt +12 -0
  308. package/src/tool/registry.ts +162 -0
  309. package/src/tool/skill.ts +100 -0
  310. package/src/tool/task.ts +136 -0
  311. package/src/tool/task.txt +51 -0
  312. package/src/tool/todo.ts +39 -0
  313. package/src/tool/todoread.txt +14 -0
  314. package/src/tool/todowrite.txt +167 -0
  315. package/src/tool/tool.ts +71 -0
  316. package/src/tool/webfetch.ts +198 -0
  317. package/src/tool/webfetch.txt +13 -0
  318. package/src/tool/websearch.ts +268 -0
  319. package/src/tool/websearch.txt +13 -0
  320. package/src/tool/write.ts +110 -0
  321. package/src/tool/write.txt +8 -0
  322. package/src/util/archive.ts +16 -0
  323. package/src/util/color.ts +19 -0
  324. package/src/util/context.ts +25 -0
  325. package/src/util/defer.ts +12 -0
  326. package/src/util/eventloop.ts +20 -0
  327. package/src/util/filesystem.ts +83 -0
  328. package/src/util/fn.ts +11 -0
  329. package/src/util/iife.ts +3 -0
  330. package/src/util/keybind.ts +102 -0
  331. package/src/util/lazy.ts +11 -0
  332. package/src/util/license.ts +362 -0
  333. package/src/util/locale.ts +81 -0
  334. package/src/util/lock.ts +98 -0
  335. package/src/util/log.ts +180 -0
  336. package/src/util/queue.ts +32 -0
  337. package/src/util/rpc.ts +42 -0
  338. package/src/util/scrap.ts +10 -0
  339. package/src/util/signal.ts +12 -0
  340. package/src/util/timeout.ts +14 -0
  341. package/src/util/token.ts +7 -0
  342. package/src/util/wildcard.ts +54 -0
  343. package/sst-env.d.ts +9 -0
  344. package/test/agent/agent.test.ts +146 -0
  345. package/test/bun.test.ts +53 -0
  346. package/test/cli/cmd/acp.test.ts +144 -0
  347. package/test/cli/cmd/run.test.ts +250 -0
  348. package/test/cli/github-remote.test.ts +80 -0
  349. package/test/config/agent-color.test.ts +66 -0
  350. package/test/config/config.test.ts +536 -0
  351. package/test/config/markdown.test.ts +89 -0
  352. package/test/file/ignore.test.ts +10 -0
  353. package/test/fixture/fixture.ts +37 -0
  354. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  355. package/test/helpers.ts +172 -0
  356. package/test/ide/ide.test.ts +82 -0
  357. package/test/installation/installation.test.ts +143 -0
  358. package/test/keybind.test.ts +421 -0
  359. package/test/lsp/client.test.ts +95 -0
  360. package/test/mcp/headers.test.ts +153 -0
  361. package/test/patch/patch.test.ts +348 -0
  362. package/test/preload.ts +57 -0
  363. package/test/project/project.test.ts +74 -0
  364. package/test/provider/provider.test.ts +74 -0
  365. package/test/provider/transform.test.ts +411 -0
  366. package/test/session/retry.test.ts +111 -0
  367. package/test/session/session.test.ts +71 -0
  368. package/test/skill/skill.test.ts +131 -0
  369. package/test/snapshot/snapshot.test.ts +940 -0
  370. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  371. package/test/tool/bash.test.ts +434 -0
  372. package/test/tool/grep.test.ts +108 -0
  373. package/test/tool/patch.test.ts +259 -0
  374. package/test/tool/read.test.ts +42 -0
  375. package/test/util/iife.test.ts +36 -0
  376. package/test/util/lazy.test.ts +50 -0
  377. package/test/util/license.test.ts +235 -0
  378. package/test/util/timeout.test.ts +21 -0
  379. package/test/util/wildcard.test.ts +55 -0
  380. package/tsconfig.json +16 -0
  381. package/update-versions.ps1 +65 -0
@@ -0,0 +1,1552 @@
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 } 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 ACT_SWITCH from "../session/prompt/act-switch.txt"
21
+ import MAX_STEPS from "../session/prompt/max-steps.txt"
22
+ import { defer } from "../util/defer"
23
+ import { clone, mergeDeep, pipe } from "remeda"
24
+ import { ToolRegistry } from "../tool/registry"
25
+ import { Wildcard } from "../util/wildcard"
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 } 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 { SessionStatus } from "./status"
43
+ import { LLM } from "./llm"
44
+ import { iife } from "@/util/iife"
45
+ import { Shell } from "@/shell/shell"
46
+ import { SensitiveFilter } from "./sensitive-filter"
47
+
48
+ // @ts-ignore
49
+ globalThis.AI_SDK_LOG_WARNINGS = false
50
+
51
+ /**
52
+ * Recursively restore sensitive data placeholders in tool arguments.
53
+ * This allows the LLM to plan using placeholders while actual execution
54
+ * uses the real values - keeping sensitive data local and never sent to API.
55
+ */
56
+ function restoreSensitiveInArgs(args: unknown, sessionID: string): unknown {
57
+ if (typeof args === "string") {
58
+ return SensitiveFilter.restore(args, sessionID)
59
+ }
60
+ if (Array.isArray(args)) {
61
+ return args.map((item) => restoreSensitiveInArgs(item, sessionID))
62
+ }
63
+ if (args !== null && typeof args === "object") {
64
+ const restored: Record<string, unknown> = {}
65
+ for (const [key, value] of Object.entries(args)) {
66
+ restored[key] = restoreSensitiveInArgs(value, sessionID)
67
+ }
68
+ return restored
69
+ }
70
+ return args
71
+ }
72
+
73
+ export namespace SessionPrompt {
74
+ const log = Log.create({ service: "session.prompt" })
75
+ export const OUTPUT_TOKEN_MAX = Flag.OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX || 32_000
76
+
77
+ const state = Instance.state(
78
+ () => {
79
+ const data: Record<
80
+ string,
81
+ {
82
+ abort: AbortController
83
+ callbacks: {
84
+ resolve(input: MessageV2.WithParts): void
85
+ reject(): void
86
+ }[]
87
+ }
88
+ > = {}
89
+ return data
90
+ },
91
+ async (current) => {
92
+ for (const item of Object.values(current)) {
93
+ item.abort.abort()
94
+ }
95
+ },
96
+ )
97
+
98
+ export function assertNotBusy(sessionID: string) {
99
+ const match = state()[sessionID]
100
+ if (match) throw new Session.BusyError(sessionID)
101
+ }
102
+
103
+ export const PromptInput = z.object({
104
+ sessionID: Identifier.schema("session"),
105
+ messageID: Identifier.schema("message").optional(),
106
+ model: z
107
+ .object({
108
+ providerID: z.string(),
109
+ modelID: z.string(),
110
+ })
111
+ .optional(),
112
+ agent: z.string().optional(),
113
+ noReply: z.boolean().optional(),
114
+ tools: z.record(z.string(), z.boolean()).optional(),
115
+ system: z.string().optional(),
116
+ parts: z.array(
117
+ z.discriminatedUnion("type", [
118
+ MessageV2.TextPart.omit({
119
+ messageID: true,
120
+ sessionID: true,
121
+ })
122
+ .partial({
123
+ id: true,
124
+ })
125
+ .meta({
126
+ ref: "TextPartInput",
127
+ }),
128
+ MessageV2.FilePart.omit({
129
+ messageID: true,
130
+ sessionID: true,
131
+ })
132
+ .partial({
133
+ id: true,
134
+ })
135
+ .meta({
136
+ ref: "FilePartInput",
137
+ }),
138
+ MessageV2.AgentPart.omit({
139
+ messageID: true,
140
+ sessionID: true,
141
+ })
142
+ .partial({
143
+ id: true,
144
+ })
145
+ .meta({
146
+ ref: "AgentPartInput",
147
+ }),
148
+ MessageV2.SubtaskPart.omit({
149
+ messageID: true,
150
+ sessionID: true,
151
+ })
152
+ .partial({
153
+ id: true,
154
+ })
155
+ .meta({
156
+ ref: "SubtaskPartInput",
157
+ }),
158
+ ]),
159
+ ),
160
+ })
161
+ export type PromptInput = z.infer<typeof PromptInput>
162
+
163
+ export const prompt = fn(PromptInput, async (input) => {
164
+ const session = await Session.get(input.sessionID)
165
+ await SessionRevert.cleanup(session)
166
+
167
+ const message = await createUserMessage(input)
168
+ await Session.touch(input.sessionID)
169
+
170
+ if (input.noReply === true) {
171
+ return message
172
+ }
173
+
174
+ return loop(input.sessionID)
175
+ })
176
+
177
+ export async function resolvePromptParts(template: string): Promise<PromptInput["parts"]> {
178
+ const parts: PromptInput["parts"] = [
179
+ {
180
+ type: "text",
181
+ text: template,
182
+ },
183
+ ]
184
+ const files = ConfigMarkdown.files(template)
185
+ const seen = new Set<string>()
186
+ await Promise.all(
187
+ files.map(async (match) => {
188
+ const name = match[1]
189
+ if (seen.has(name)) return
190
+ seen.add(name)
191
+ const filepath = name.startsWith("~/")
192
+ ? path.join(os.homedir(), name.slice(2))
193
+ : path.resolve(Instance.worktree, name)
194
+
195
+ const stats = await fs.stat(filepath).catch(() => undefined)
196
+ if (!stats) {
197
+ const agent = await Agent.get(name)
198
+ if (agent) {
199
+ parts.push({
200
+ type: "agent",
201
+ name: agent.name,
202
+ })
203
+ }
204
+ return
205
+ }
206
+
207
+ if (stats.isDirectory()) {
208
+ parts.push({
209
+ type: "file",
210
+ url: `file://${filepath}`,
211
+ filename: name,
212
+ mime: "application/x-directory",
213
+ })
214
+ return
215
+ }
216
+
217
+ parts.push({
218
+ type: "file",
219
+ url: `file://${filepath}`,
220
+ filename: name,
221
+ mime: "text/plain",
222
+ })
223
+ }),
224
+ )
225
+ return parts
226
+ }
227
+
228
+ function start(sessionID: string) {
229
+ const s = state()
230
+ if (s[sessionID]) return
231
+ const controller = new AbortController()
232
+ s[sessionID] = {
233
+ abort: controller,
234
+ callbacks: [],
235
+ }
236
+ return controller.signal
237
+ }
238
+
239
+ export function cancel(sessionID: string) {
240
+ log.info("cancel", { sessionID })
241
+ const s = state()
242
+ const match = s[sessionID]
243
+ if (!match) return
244
+ match.abort.abort()
245
+ for (const item of match.callbacks) {
246
+ item.reject()
247
+ }
248
+ delete s[sessionID]
249
+ SessionStatus.set(sessionID, { type: "idle" })
250
+ // Unload MCP sections for this specific session when it ends
251
+ MCP.unloadSections(undefined, sessionID).catch((e) => log.debug("failed to unload MCP sections", { error: e, sessionID }))
252
+ return
253
+ }
254
+
255
+ export const loop = fn(Identifier.schema("session"), async (sessionID) => {
256
+ const abort = start(sessionID)
257
+ if (!abort) {
258
+ return new Promise<MessageV2.WithParts>((resolve, reject) => {
259
+ const callbacks = state()[sessionID].callbacks
260
+ callbacks.push({ resolve, reject })
261
+ })
262
+ }
263
+
264
+ using _ = defer(() => cancel(sessionID))
265
+
266
+ let step = 0
267
+ while (true) {
268
+ SessionStatus.set(sessionID, { type: "busy" })
269
+ log.info("loop", { step, sessionID })
270
+ if (abort.aborted) break
271
+ let msgs = await MessageV2.filterCompacted(MessageV2.stream(sessionID))
272
+
273
+ let lastUser: MessageV2.User | undefined
274
+ let lastAssistant: MessageV2.Assistant | undefined
275
+ let lastFinished: MessageV2.Assistant | undefined
276
+ let tasks: (MessageV2.CompactionPart | MessageV2.SubtaskPart)[] = []
277
+ for (let i = msgs.length - 1; i >= 0; i--) {
278
+ const msg = msgs[i]
279
+ if (!lastUser && msg.info.role === "user") lastUser = msg.info as MessageV2.User
280
+ if (!lastAssistant && msg.info.role === "assistant") lastAssistant = msg.info as MessageV2.Assistant
281
+ if (!lastFinished && msg.info.role === "assistant" && msg.info.finish)
282
+ lastFinished = msg.info as MessageV2.Assistant
283
+ if (lastUser && lastFinished) break
284
+ const task = msg.parts.filter((part) => part.type === "compaction" || part.type === "subtask")
285
+ if (task && !lastFinished) {
286
+ tasks.push(...task)
287
+ }
288
+ }
289
+
290
+ if (!lastUser) throw new Error("No user message found in stream. This should never happen.")
291
+ if (
292
+ lastAssistant?.finish &&
293
+ !["tool-calls", "unknown"].includes(lastAssistant.finish) &&
294
+ lastUser.id < lastAssistant.id
295
+ ) {
296
+ log.info("exiting loop", { sessionID })
297
+ break
298
+ }
299
+
300
+ step++
301
+ if (step === 1) {
302
+ ensureTitle({
303
+ session: await Session.get(sessionID),
304
+ modelID: lastUser.model.modelID,
305
+ providerID: lastUser.model.providerID,
306
+ message: msgs.find((m) => m.info.role === "user")!,
307
+ history: msgs,
308
+ })
309
+
310
+ // Automatically load MCP sections based on user prompt intent
311
+ const userMessage = msgs.find((m) => m.info.role === "user")
312
+ if (userMessage) {
313
+ const userTextParts = userMessage.parts
314
+ .filter((p): p is MessageV2.TextPart => p.type === "text" && !p.synthetic)
315
+ .map((p) => p.text)
316
+ const userPromptText = userTextParts.join(" ")
317
+ if (userPromptText) {
318
+ try {
319
+ await MCP.prepareToolsForPrompt(userPromptText, sessionID)
320
+ } catch (e) {
321
+ log.warn("failed to auto-load MCP sections", { error: e, sessionID })
322
+ // Continue execution - section loading is non-critical
323
+ }
324
+ }
325
+ }
326
+ }
327
+
328
+ const model = await Provider.getModel(lastUser.model.providerID, lastUser.model.modelID)
329
+ // Get action model (small/cheap model) for tool call continuation steps
330
+ let actionModel: Provider.Model | undefined
331
+ try {
332
+ actionModel = await Provider.getSmallModel(lastUser.model.providerID)
333
+ } catch (e) {
334
+ // Silently fall back to main model if small model unavailable
335
+ }
336
+ // Get vision model for image processing
337
+ let visionModel: Provider.Model | undefined
338
+ try {
339
+ visionModel = await Provider.getVisionModel(lastUser.model.providerID)
340
+ } catch (e) {
341
+ // Silently fall back to main model if vision model unavailable
342
+ }
343
+ // Check if messages contain images (need vision model)
344
+ const hasImages = msgs.some((msg) =>
345
+ msg.parts.some((part) => part.type === "file" && part.mime?.startsWith("image/"))
346
+ )
347
+ // Check if there are pending tool calls to execute (last assistant ended with tool-calls)
348
+ const hasPendingToolCalls = lastAssistant?.finish === "tool-calls"
349
+ // Model selection priority:
350
+ // 1. Vision model when images present
351
+ // 2. Action model ONLY for tool call execution (when lastAssistant has pending tool-calls)
352
+ // 3. Main model for planning (step 1), output, and retries
353
+ let effectiveModel = model
354
+ if (hasImages && visionModel) {
355
+ effectiveModel = visionModel
356
+ } else if (hasPendingToolCalls && actionModel) {
357
+ effectiveModel = actionModel
358
+ }
359
+ const task = tasks.pop()
360
+
361
+ // pending subtask
362
+ // TODO: centralize "invoke tool" logic
363
+ if (task?.type === "subtask") {
364
+ const taskTool = await TaskTool.init()
365
+ const assistantMessage = (await Session.updateMessage({
366
+ id: Identifier.ascending("message"),
367
+ role: "assistant",
368
+ parentID: lastUser.id,
369
+ sessionID,
370
+ mode: task.agent,
371
+ agent: task.agent,
372
+ path: {
373
+ cwd: Instance.directory,
374
+ root: Instance.worktree,
375
+ },
376
+ cost: 0,
377
+ tokens: {
378
+ input: 0,
379
+ output: 0,
380
+ reasoning: 0,
381
+ cache: { read: 0, write: 0 },
382
+ },
383
+ modelID: model.id,
384
+ providerID: model.providerID,
385
+ time: {
386
+ created: Date.now(),
387
+ },
388
+ })) as MessageV2.Assistant
389
+ let part = (await Session.updatePart({
390
+ id: Identifier.ascending("part"),
391
+ messageID: assistantMessage.id,
392
+ sessionID: assistantMessage.sessionID,
393
+ type: "tool",
394
+ callID: ulid(),
395
+ tool: TaskTool.id,
396
+ state: {
397
+ status: "running",
398
+ input: {
399
+ prompt: task.prompt,
400
+ description: task.description,
401
+ subagent_type: task.agent,
402
+ command: task.command,
403
+ },
404
+ time: {
405
+ start: Date.now(),
406
+ },
407
+ },
408
+ })) as MessageV2.ToolPart
409
+ const taskArgs = {
410
+ prompt: task.prompt,
411
+ description: task.description,
412
+ subagent_type: task.agent,
413
+ command: task.command,
414
+ }
415
+ await Plugin.trigger(
416
+ "tool.execute.before",
417
+ {
418
+ tool: "task",
419
+ sessionID,
420
+ callID: part.id,
421
+ },
422
+ { args: taskArgs },
423
+ )
424
+ let executionError: Error | undefined
425
+ const result = await taskTool
426
+ .execute(taskArgs, {
427
+ agent: task.agent,
428
+ messageID: assistantMessage.id,
429
+ sessionID: sessionID,
430
+ abort,
431
+ async metadata(input) {
432
+ await Session.updatePart({
433
+ ...part,
434
+ type: "tool",
435
+ state: {
436
+ ...part.state,
437
+ ...input,
438
+ },
439
+ } satisfies MessageV2.ToolPart)
440
+ },
441
+ })
442
+ .catch((error) => {
443
+ executionError = error
444
+ log.error("subtask execution failed", { error, agent: task.agent, description: task.description })
445
+ return undefined
446
+ })
447
+ await Plugin.trigger(
448
+ "tool.execute.after",
449
+ {
450
+ tool: "task",
451
+ sessionID,
452
+ callID: part.id,
453
+ },
454
+ result,
455
+ )
456
+ assistantMessage.finish = "tool-calls"
457
+ assistantMessage.time.completed = Date.now()
458
+ await Session.updateMessage(assistantMessage)
459
+ if (result && part.state.status === "running") {
460
+ await Session.updatePart({
461
+ ...part,
462
+ state: {
463
+ status: "completed",
464
+ input: part.state.input,
465
+ title: result.title,
466
+ metadata: result.metadata,
467
+ output: result.output,
468
+ attachments: result.attachments,
469
+ time: {
470
+ ...part.state.time,
471
+ end: Date.now(),
472
+ },
473
+ },
474
+ } satisfies MessageV2.ToolPart)
475
+ }
476
+ if (!result) {
477
+ await Session.updatePart({
478
+ ...part,
479
+ state: {
480
+ status: "error",
481
+ error: executionError ? `Tool execution failed: ${executionError.message}` : "Tool execution failed",
482
+ time: {
483
+ start: part.state.status === "running" ? part.state.time.start : Date.now(),
484
+ end: Date.now(),
485
+ },
486
+ metadata: part.metadata,
487
+ input: part.state.input,
488
+ },
489
+ } satisfies MessageV2.ToolPart)
490
+ }
491
+
492
+ // Add synthetic user message to prevent certain reasoning models from erroring
493
+ // If we create assistant messages w/ out user ones following mid loop thinking signatures
494
+ // will be missing and it can cause errors for models like gemini for example
495
+ const summaryUserMsg: MessageV2.User = {
496
+ id: Identifier.ascending("message"),
497
+ sessionID,
498
+ role: "user",
499
+ time: {
500
+ created: Date.now(),
501
+ },
502
+ agent: lastUser.agent,
503
+ model: lastUser.model,
504
+ }
505
+ await Session.updateMessage(summaryUserMsg)
506
+ await Session.updatePart({
507
+ id: Identifier.ascending("part"),
508
+ messageID: summaryUserMsg.id,
509
+ sessionID,
510
+ type: "text",
511
+ text: "Summarize the task tool output above and continue with your task.",
512
+ synthetic: true,
513
+ } satisfies MessageV2.TextPart)
514
+
515
+ continue
516
+ }
517
+
518
+ // pending compaction
519
+ if (task?.type === "compaction") {
520
+ const result = await SessionCompaction.process({
521
+ messages: msgs,
522
+ parentID: lastUser.id,
523
+ abort,
524
+ sessionID,
525
+ auto: task.auto,
526
+ })
527
+ if (result === "stop") break
528
+ continue
529
+ }
530
+
531
+ // context overflow, needs compaction
532
+ if (
533
+ lastFinished &&
534
+ lastFinished.summary !== true &&
535
+ SessionCompaction.isOverflow({ tokens: lastFinished.tokens, model })
536
+ ) {
537
+ await SessionCompaction.create({
538
+ sessionID,
539
+ agent: lastUser.agent,
540
+ model: lastUser.model,
541
+ auto: true,
542
+ })
543
+ continue
544
+ }
545
+
546
+ // normal processing
547
+ const agent = await Agent.get(lastUser.agent)
548
+ const maxSteps = agent.maxSteps ?? Infinity
549
+ const isLastStep = step >= maxSteps
550
+ msgs = insertReminders({
551
+ messages: msgs,
552
+ agent,
553
+ })
554
+
555
+ const processor = SessionProcessor.create({
556
+ assistantMessage: (await Session.updateMessage({
557
+ id: Identifier.ascending("message"),
558
+ parentID: lastUser.id,
559
+ role: "assistant",
560
+ mode: agent.name,
561
+ agent: agent.name,
562
+ path: {
563
+ cwd: Instance.directory,
564
+ root: Instance.worktree,
565
+ },
566
+ cost: 0,
567
+ tokens: {
568
+ input: 0,
569
+ output: 0,
570
+ reasoning: 0,
571
+ cache: { read: 0, write: 0 },
572
+ },
573
+ modelID: effectiveModel.id,
574
+ providerID: effectiveModel.providerID,
575
+ time: {
576
+ created: Date.now(),
577
+ },
578
+ sessionID,
579
+ })) as MessageV2.Assistant,
580
+ sessionID: sessionID,
581
+ model: effectiveModel,
582
+ abort,
583
+ })
584
+ const tools = await resolveTools({
585
+ agent,
586
+ sessionID,
587
+ model,
588
+ tools: lastUser.tools,
589
+ processor,
590
+ })
591
+
592
+ if (step === 1) {
593
+ SessionSummary.summarize({
594
+ sessionID: sessionID,
595
+ messageID: lastUser.id,
596
+ })
597
+ }
598
+
599
+ const sessionMessages = clone(msgs)
600
+
601
+ await Plugin.trigger("experimental.chat.messages.transform", {}, { messages: sessionMessages })
602
+
603
+ const result = await processor.process({
604
+ user: lastUser,
605
+ agent,
606
+ abort,
607
+ sessionID,
608
+ system: [...(await SystemPrompt.environment()), ...(await SystemPrompt.custom())],
609
+ messages: [
610
+ ...MessageV2.toModelMessage(sessionMessages, { sessionID }),
611
+ ...(isLastStep
612
+ ? [
613
+ {
614
+ role: "assistant" as const,
615
+ content: MAX_STEPS,
616
+ },
617
+ ]
618
+ : []),
619
+ ],
620
+ tools,
621
+ model: effectiveModel,
622
+ })
623
+ if (result === "stop") break
624
+ continue
625
+ }
626
+ SessionCompaction.prune({ sessionID })
627
+ for await (const item of MessageV2.stream(sessionID)) {
628
+ if (item.info.role === "user") continue
629
+ const queued = state()[sessionID]?.callbacks ?? []
630
+ for (const q of queued) {
631
+ q.resolve(item)
632
+ }
633
+ return item
634
+ }
635
+ throw new Error("Impossible")
636
+ })
637
+
638
+ async function lastModel(sessionID: string) {
639
+ for await (const item of MessageV2.stream(sessionID)) {
640
+ if (item.info.role === "user" && item.info.model) return item.info.model
641
+ }
642
+ return Provider.defaultModel()
643
+ }
644
+
645
+ async function resolveTools(input: {
646
+ agent: Agent.Info
647
+ model: Provider.Model
648
+ sessionID: string
649
+ tools?: Record<string, boolean>
650
+ processor: SessionProcessor.Info
651
+ }) {
652
+ using _ = log.time("resolveTools")
653
+ const tools: Record<string, AITool> = {}
654
+ const enabledTools = pipe(
655
+ input.agent.tools,
656
+ mergeDeep(await ToolRegistry.enabled(input.agent)),
657
+ mergeDeep(input.tools ?? {}),
658
+ )
659
+ for (const item of await ToolRegistry.tools(input.model.providerID, input.agent)) {
660
+ if (Wildcard.all(item.id, enabledTools) === false) continue
661
+ const schema = ProviderTransform.schema(input.model, z.toJSONSchema(item.parameters))
662
+ tools[item.id] = tool({
663
+ id: item.id as any,
664
+ description: item.description,
665
+ inputSchema: jsonSchema(schema as any),
666
+ async execute(args, options) {
667
+ await Plugin.trigger(
668
+ "tool.execute.before",
669
+ {
670
+ tool: item.id,
671
+ sessionID: input.sessionID,
672
+ callID: options.toolCallId,
673
+ },
674
+ {
675
+ args,
676
+ },
677
+ )
678
+ // Restore sensitive data placeholders to real values for actual execution
679
+ // LLM sees: "type [REDACTED-PASSWORD] in field" but tool types the real password
680
+ const restoredArgs = restoreSensitiveInArgs(args, input.sessionID)
681
+ const result = await item.execute(restoredArgs as typeof args, {
682
+ sessionID: input.sessionID,
683
+ abort: options.abortSignal!,
684
+ messageID: input.processor.message.id,
685
+ callID: options.toolCallId,
686
+ extra: { model: input.model },
687
+ agent: input.agent.name,
688
+ metadata: async (val) => {
689
+ const match = input.processor.partFromToolCall(options.toolCallId)
690
+ if (match && match.state.status === "running") {
691
+ await Session.updatePart({
692
+ ...match,
693
+ state: {
694
+ title: val.title,
695
+ metadata: val.metadata,
696
+ status: "running",
697
+ input: args,
698
+ time: {
699
+ start: Date.now(),
700
+ },
701
+ },
702
+ })
703
+ }
704
+ },
705
+ })
706
+ await Plugin.trigger(
707
+ "tool.execute.after",
708
+ {
709
+ tool: item.id,
710
+ sessionID: input.sessionID,
711
+ callID: options.toolCallId,
712
+ },
713
+ result,
714
+ )
715
+ return result
716
+ },
717
+ toModelOutput(result) {
718
+ return {
719
+ type: "text",
720
+ value: result.output,
721
+ }
722
+ },
723
+ })
724
+ }
725
+ for (const [key, item] of Object.entries(await MCP.tools())) {
726
+ if (Wildcard.all(key, enabledTools) === false) continue
727
+ const execute = item.execute
728
+ if (!execute) continue
729
+
730
+ // Wrap execute to add plugin hooks and format output
731
+ item.execute = async (args, opts) => {
732
+ await Plugin.trigger(
733
+ "tool.execute.before",
734
+ {
735
+ tool: key,
736
+ sessionID: input.sessionID,
737
+ callID: opts.toolCallId,
738
+ },
739
+ {
740
+ args,
741
+ },
742
+ )
743
+ const result = await execute(args, opts)
744
+
745
+ await Plugin.trigger(
746
+ "tool.execute.after",
747
+ {
748
+ tool: key,
749
+ sessionID: input.sessionID,
750
+ callID: opts.toolCallId,
751
+ },
752
+ result,
753
+ )
754
+
755
+ const textParts: string[] = []
756
+ const attachments: MessageV2.FilePart[] = []
757
+
758
+ for (const contentItem of result.content) {
759
+ if (contentItem.type === "text") {
760
+ textParts.push(contentItem.text)
761
+ } else if (contentItem.type === "image") {
762
+ attachments.push({
763
+ id: Identifier.ascending("part"),
764
+ sessionID: input.sessionID,
765
+ messageID: input.processor.message.id,
766
+ type: "file",
767
+ mime: contentItem.mimeType,
768
+ url: `data:${contentItem.mimeType};base64,${contentItem.data}`,
769
+ })
770
+ }
771
+ // Add support for other types if needed
772
+ }
773
+
774
+ return {
775
+ title: "",
776
+ metadata: result.metadata ?? {},
777
+ output: textParts.join("\n\n"),
778
+ attachments,
779
+ content: result.content, // directly return content to preserve ordering when outputting to model
780
+ }
781
+ }
782
+ item.toModelOutput = (result) => {
783
+ return {
784
+ type: "text",
785
+ value: result.output,
786
+ }
787
+ }
788
+ tools[key] = item
789
+ }
790
+ return tools
791
+ }
792
+
793
+ async function createUserMessage(input: PromptInput) {
794
+ const agent = await Agent.get(input.agent ?? (await Agent.defaultAgent()))
795
+ const resolvedModel = await (async () => {
796
+ const candidate = input.model ?? agent.model ?? (await lastModel(input.sessionID))
797
+ if (candidate) {
798
+ try {
799
+ await Provider.getModel(candidate.providerID, candidate.modelID)
800
+ return candidate
801
+ } catch {}
802
+ }
803
+ return await Provider.defaultModel()
804
+ })()
805
+ const info: MessageV2.Info = {
806
+ id: input.messageID ?? Identifier.ascending("message"),
807
+ role: "user",
808
+ sessionID: input.sessionID,
809
+ time: {
810
+ created: Date.now(),
811
+ },
812
+ tools: input.tools,
813
+ agent: agent.name,
814
+ model: resolvedModel,
815
+ system: input.system,
816
+ }
817
+
818
+ const parts = await Promise.all(
819
+ input.parts.map(async (part): Promise<MessageV2.Part[]> => {
820
+ if (part.type === "file") {
821
+ const url = new URL(part.url)
822
+ switch (url.protocol) {
823
+ case "data:":
824
+ if (part.mime === "text/plain") {
825
+ return [
826
+ {
827
+ id: Identifier.ascending("part"),
828
+ messageID: info.id,
829
+ sessionID: input.sessionID,
830
+ type: "text",
831
+ synthetic: true,
832
+ text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
833
+ },
834
+ {
835
+ id: Identifier.ascending("part"),
836
+ messageID: info.id,
837
+ sessionID: input.sessionID,
838
+ type: "text",
839
+ synthetic: true,
840
+ text: Buffer.from(part.url, "base64url").toString(),
841
+ },
842
+ {
843
+ ...part,
844
+ id: part.id ?? Identifier.ascending("part"),
845
+ messageID: info.id,
846
+ sessionID: input.sessionID,
847
+ },
848
+ ]
849
+ }
850
+ break
851
+ case "file:":
852
+ log.info("file", { mime: part.mime })
853
+ // have to normalize, symbol search returns absolute paths
854
+ // Decode the pathname since URL constructor doesn't automatically decode it
855
+ const filepath = fileURLToPath(part.url)
856
+ const stat = await Bun.file(filepath).stat()
857
+
858
+ if (stat.isDirectory()) {
859
+ part.mime = "application/x-directory"
860
+ }
861
+
862
+ if (part.mime === "text/plain") {
863
+ let offset: number | undefined = undefined
864
+ let limit: number | undefined = undefined
865
+ const range = {
866
+ start: url.searchParams.get("start"),
867
+ end: url.searchParams.get("end"),
868
+ }
869
+ if (range.start != null) {
870
+ const filePathURI = part.url.split("?")[0]
871
+ let start = parseInt(range.start)
872
+ let end = range.end ? parseInt(range.end) : undefined
873
+ // some LSP servers (eg, gopls) don't give full range in
874
+ // workspace/symbol searches, so we'll try to find the
875
+ // symbol in the document to get the full range
876
+ if (start === end) {
877
+ const symbols = await LSP.documentSymbol(filePathURI)
878
+ for (const symbol of symbols) {
879
+ let range: LSP.Range | undefined
880
+ if ("range" in symbol) {
881
+ range = symbol.range
882
+ } else if ("location" in symbol) {
883
+ range = symbol.location.range
884
+ }
885
+ if (range?.start?.line && range?.start?.line === start) {
886
+ start = range.start.line
887
+ end = range?.end?.line ?? start
888
+ break
889
+ }
890
+ }
891
+ }
892
+ offset = Math.max(start - 1, 0)
893
+ if (end) {
894
+ limit = end - offset
895
+ }
896
+ }
897
+ const args = { filePath: filepath, offset, limit }
898
+
899
+ const pieces: MessageV2.Part[] = [
900
+ {
901
+ id: Identifier.ascending("part"),
902
+ messageID: info.id,
903
+ sessionID: input.sessionID,
904
+ type: "text",
905
+ synthetic: true,
906
+ text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
907
+ },
908
+ ]
909
+
910
+ await ReadTool.init()
911
+ .then(async (t) => {
912
+ const model = await Provider.getModel(info.model.providerID, info.model.modelID)
913
+ const result = await t.execute(args, {
914
+ sessionID: input.sessionID,
915
+ abort: new AbortController().signal,
916
+ agent: input.agent!,
917
+ messageID: info.id,
918
+ extra: { bypassCwdCheck: true, model },
919
+ metadata: async () => {},
920
+ })
921
+ pieces.push({
922
+ id: Identifier.ascending("part"),
923
+ messageID: info.id,
924
+ sessionID: input.sessionID,
925
+ type: "text",
926
+ synthetic: true,
927
+ text: result.output,
928
+ })
929
+ if (result.attachments?.length) {
930
+ pieces.push(
931
+ ...result.attachments.map((attachment) => ({
932
+ ...attachment,
933
+ synthetic: true,
934
+ filename: attachment.filename ?? part.filename,
935
+ messageID: info.id,
936
+ sessionID: input.sessionID,
937
+ })),
938
+ )
939
+ } else {
940
+ pieces.push({
941
+ ...part,
942
+ id: part.id ?? Identifier.ascending("part"),
943
+ messageID: info.id,
944
+ sessionID: input.sessionID,
945
+ })
946
+ }
947
+ })
948
+ .catch((error) => {
949
+ log.error("failed to read file", { error })
950
+ const message = error instanceof Error ? error.message : error.toString()
951
+ Bus.publish(Session.Event.Error, {
952
+ sessionID: input.sessionID,
953
+ error: new NamedError.Unknown({
954
+ message,
955
+ }).toObject(),
956
+ })
957
+ pieces.push({
958
+ id: Identifier.ascending("part"),
959
+ messageID: info.id,
960
+ sessionID: input.sessionID,
961
+ type: "text",
962
+ synthetic: true,
963
+ text: `Read tool failed to read ${filepath} with the following error: ${message}`,
964
+ })
965
+ })
966
+
967
+ return pieces
968
+ }
969
+
970
+ if (part.mime === "application/x-directory") {
971
+ const args = { path: filepath }
972
+ const result = await ListTool.init().then((t) =>
973
+ t.execute(args, {
974
+ sessionID: input.sessionID,
975
+ abort: new AbortController().signal,
976
+ agent: input.agent!,
977
+ messageID: info.id,
978
+ extra: { bypassCwdCheck: true },
979
+ metadata: async () => {},
980
+ }),
981
+ )
982
+ return [
983
+ {
984
+ id: Identifier.ascending("part"),
985
+ messageID: info.id,
986
+ sessionID: input.sessionID,
987
+ type: "text",
988
+ synthetic: true,
989
+ text: `Called the list tool with the following input: ${JSON.stringify(args)}`,
990
+ },
991
+ {
992
+ id: Identifier.ascending("part"),
993
+ messageID: info.id,
994
+ sessionID: input.sessionID,
995
+ type: "text",
996
+ synthetic: true,
997
+ text: result.output,
998
+ },
999
+ {
1000
+ ...part,
1001
+ id: part.id ?? Identifier.ascending("part"),
1002
+ messageID: info.id,
1003
+ sessionID: input.sessionID,
1004
+ },
1005
+ ]
1006
+ }
1007
+
1008
+ const file = Bun.file(filepath)
1009
+ FileTime.read(input.sessionID, filepath)
1010
+ return [
1011
+ {
1012
+ id: Identifier.ascending("part"),
1013
+ messageID: info.id,
1014
+ sessionID: input.sessionID,
1015
+ type: "text",
1016
+ text: `Called the Read tool with the following input: {\"filePath\":\"${filepath}\"}`,
1017
+ synthetic: true,
1018
+ },
1019
+ {
1020
+ id: part.id ?? Identifier.ascending("part"),
1021
+ messageID: info.id,
1022
+ sessionID: input.sessionID,
1023
+ type: "file",
1024
+ url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64"),
1025
+ mime: part.mime,
1026
+ filename: part.filename!,
1027
+ source: part.source,
1028
+ },
1029
+ ]
1030
+ }
1031
+ }
1032
+
1033
+ if (part.type === "agent") {
1034
+ return [
1035
+ {
1036
+ id: Identifier.ascending("part"),
1037
+ ...part,
1038
+ messageID: info.id,
1039
+ sessionID: input.sessionID,
1040
+ },
1041
+ {
1042
+ id: Identifier.ascending("part"),
1043
+ messageID: info.id,
1044
+ sessionID: input.sessionID,
1045
+ type: "text",
1046
+ synthetic: true,
1047
+ text:
1048
+ "Use the above message and context to generate a prompt and call the task tool with subagent: " +
1049
+ part.name,
1050
+ },
1051
+ ]
1052
+ }
1053
+
1054
+ return [
1055
+ {
1056
+ id: Identifier.ascending("part"),
1057
+ ...part,
1058
+ messageID: info.id,
1059
+ sessionID: input.sessionID,
1060
+ },
1061
+ ]
1062
+ }),
1063
+ ).then((x) => x.flat())
1064
+
1065
+ await Plugin.trigger(
1066
+ "chat.message",
1067
+ {
1068
+ sessionID: input.sessionID,
1069
+ agent: input.agent,
1070
+ model: input.model,
1071
+ messageID: input.messageID,
1072
+ },
1073
+ {
1074
+ message: info,
1075
+ parts,
1076
+ },
1077
+ )
1078
+
1079
+ await Session.updateMessage(info)
1080
+ for (const part of parts) {
1081
+ await Session.updatePart(part)
1082
+ }
1083
+
1084
+ return {
1085
+ info,
1086
+ parts,
1087
+ }
1088
+ }
1089
+
1090
+ function insertReminders(input: { messages: MessageV2.WithParts[]; agent: Agent.Info }) {
1091
+ const userMessage = input.messages.findLast((msg) => msg.info.role === "user")
1092
+ if (!userMessage) return input.messages
1093
+ if (input.agent.name === "plan") {
1094
+ userMessage.parts.push({
1095
+ id: Identifier.ascending("part"),
1096
+ messageID: userMessage.info.id,
1097
+ sessionID: userMessage.info.sessionID,
1098
+ type: "text",
1099
+ // TODO (for mr dax): update to use the anthropic full fledged one (see plan-reminder-anthropic.txt)
1100
+ text: PROMPT_PLAN,
1101
+ synthetic: true,
1102
+ })
1103
+ }
1104
+ const wasPlan = input.messages.some((msg) => msg.info.role === "assistant" && msg.info.agent === "plan")
1105
+ if (wasPlan && input.agent.name === "act") {
1106
+ userMessage.parts.push({
1107
+ id: Identifier.ascending("part"),
1108
+ messageID: userMessage.info.id,
1109
+ sessionID: userMessage.info.sessionID,
1110
+ type: "text",
1111
+ text: ACT_SWITCH,
1112
+ synthetic: true,
1113
+ })
1114
+ }
1115
+ return input.messages
1116
+ }
1117
+
1118
+ export const ShellInput = z.object({
1119
+ sessionID: Identifier.schema("session"),
1120
+ agent: z.string(),
1121
+ model: z
1122
+ .object({
1123
+ providerID: z.string(),
1124
+ modelID: z.string(),
1125
+ })
1126
+ .optional(),
1127
+ command: z.string(),
1128
+ })
1129
+ export type ShellInput = z.infer<typeof ShellInput>
1130
+ export async function shell(input: ShellInput) {
1131
+ const abort = start(input.sessionID)
1132
+ if (!abort) {
1133
+ throw new Session.BusyError(input.sessionID)
1134
+ }
1135
+ using _ = defer(() => cancel(input.sessionID))
1136
+
1137
+ const session = await Session.get(input.sessionID)
1138
+ if (session.revert) {
1139
+ SessionRevert.cleanup(session)
1140
+ }
1141
+ const agent = await Agent.get(input.agent)
1142
+ const model = await (async () => {
1143
+ const candidate = input.model ?? agent.model ?? (await lastModel(input.sessionID))
1144
+ if (candidate) {
1145
+ try {
1146
+ await Provider.getModel(candidate.providerID, candidate.modelID)
1147
+ return candidate
1148
+ } catch {}
1149
+ }
1150
+ return await Provider.defaultModel()
1151
+ })()
1152
+ const userMsg: MessageV2.User = {
1153
+ id: Identifier.ascending("message"),
1154
+ sessionID: input.sessionID,
1155
+ time: {
1156
+ created: Date.now(),
1157
+ },
1158
+ role: "user",
1159
+ agent: input.agent,
1160
+ model: {
1161
+ providerID: model.providerID,
1162
+ modelID: model.modelID,
1163
+ },
1164
+ }
1165
+ await Session.updateMessage(userMsg)
1166
+ const userPart: MessageV2.Part = {
1167
+ type: "text",
1168
+ id: Identifier.ascending("part"),
1169
+ messageID: userMsg.id,
1170
+ sessionID: input.sessionID,
1171
+ text: "The following tool was executed by the user",
1172
+ synthetic: true,
1173
+ }
1174
+ await Session.updatePart(userPart)
1175
+
1176
+ const msg: MessageV2.Assistant = {
1177
+ id: Identifier.ascending("message"),
1178
+ sessionID: input.sessionID,
1179
+ parentID: userMsg.id,
1180
+ mode: input.agent,
1181
+ agent: input.agent,
1182
+ cost: 0,
1183
+ path: {
1184
+ cwd: Instance.directory,
1185
+ root: Instance.worktree,
1186
+ },
1187
+ time: {
1188
+ created: Date.now(),
1189
+ },
1190
+ role: "assistant",
1191
+ tokens: {
1192
+ input: 0,
1193
+ output: 0,
1194
+ reasoning: 0,
1195
+ cache: { read: 0, write: 0 },
1196
+ },
1197
+ modelID: model.modelID,
1198
+ providerID: model.providerID,
1199
+ }
1200
+ await Session.updateMessage(msg)
1201
+ const part: MessageV2.Part = {
1202
+ type: "tool",
1203
+ id: Identifier.ascending("part"),
1204
+ messageID: msg.id,
1205
+ sessionID: input.sessionID,
1206
+ tool: "bash",
1207
+ callID: ulid(),
1208
+ state: {
1209
+ status: "running",
1210
+ time: {
1211
+ start: Date.now(),
1212
+ },
1213
+ input: {
1214
+ command: input.command,
1215
+ },
1216
+ },
1217
+ }
1218
+ await Session.updatePart(part)
1219
+ const shell = Shell.preferred()
1220
+ const shellName = (
1221
+ process.platform === "win32" ? path.win32.basename(shell, ".exe") : path.basename(shell)
1222
+ ).toLowerCase()
1223
+
1224
+ const invocations: Record<string, { args: string[] }> = {
1225
+ nu: {
1226
+ args: ["-c", input.command],
1227
+ },
1228
+ fish: {
1229
+ args: ["-c", input.command],
1230
+ },
1231
+ zsh: {
1232
+ args: [
1233
+ "-c",
1234
+ "-l",
1235
+ `
1236
+ [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
1237
+ [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
1238
+ eval ${JSON.stringify(input.command)}
1239
+ `,
1240
+ ],
1241
+ },
1242
+ bash: {
1243
+ args: [
1244
+ "-c",
1245
+ "-l",
1246
+ `
1247
+ shopt -s expand_aliases
1248
+ [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
1249
+ eval ${JSON.stringify(input.command)}
1250
+ `,
1251
+ ],
1252
+ },
1253
+ // Windows cmd
1254
+ cmd: {
1255
+ args: ["/c", input.command],
1256
+ },
1257
+ // Windows PowerShell
1258
+ powershell: {
1259
+ args: ["-NoProfile", "-Command", input.command],
1260
+ },
1261
+ pwsh: {
1262
+ args: ["-NoProfile", "-Command", input.command],
1263
+ },
1264
+ // Fallback: any shell that doesn't match those above
1265
+ // - No -l, for max compatibility
1266
+ "": {
1267
+ args: ["-c", `${input.command}`],
1268
+ },
1269
+ }
1270
+
1271
+ const matchingInvocation = invocations[shellName] ?? invocations[""]
1272
+ const args = matchingInvocation?.args
1273
+
1274
+ const proc = spawn(shell, args, {
1275
+ cwd: Instance.directory,
1276
+ detached: process.platform !== "win32",
1277
+ stdio: ["ignore", "pipe", "pipe"],
1278
+ env: {
1279
+ ...process.env,
1280
+ TERM: "dumb",
1281
+ },
1282
+ })
1283
+
1284
+ let output = ""
1285
+
1286
+ proc.stdout?.on("data", (chunk) => {
1287
+ output += chunk.toString()
1288
+ if (part.state.status === "running") {
1289
+ part.state.metadata = {
1290
+ output: output,
1291
+ description: "",
1292
+ }
1293
+ Session.updatePart(part)
1294
+ }
1295
+ })
1296
+
1297
+ proc.stderr?.on("data", (chunk) => {
1298
+ output += chunk.toString()
1299
+ if (part.state.status === "running") {
1300
+ part.state.metadata = {
1301
+ output: output,
1302
+ description: "",
1303
+ }
1304
+ Session.updatePart(part)
1305
+ }
1306
+ })
1307
+
1308
+ let aborted = false
1309
+ let exited = false
1310
+
1311
+ const kill = () => Shell.killTree(proc, { exited: () => exited })
1312
+
1313
+ if (abort.aborted) {
1314
+ aborted = true
1315
+ await kill()
1316
+ }
1317
+
1318
+ const abortHandler = () => {
1319
+ aborted = true
1320
+ void kill()
1321
+ }
1322
+
1323
+ abort.addEventListener("abort", abortHandler, { once: true })
1324
+
1325
+ await new Promise<void>((resolve) => {
1326
+ proc.on("close", () => {
1327
+ exited = true
1328
+ abort.removeEventListener("abort", abortHandler)
1329
+ resolve()
1330
+ })
1331
+ })
1332
+
1333
+ if (aborted) {
1334
+ output += "\n\n" + ["<metadata>", "User aborted the command", "</metadata>"].join("\n")
1335
+ }
1336
+ msg.time.completed = Date.now()
1337
+ await Session.updateMessage(msg)
1338
+ if (part.state.status === "running") {
1339
+ part.state = {
1340
+ status: "completed",
1341
+ time: {
1342
+ ...part.state.time,
1343
+ end: Date.now(),
1344
+ },
1345
+ input: part.state.input,
1346
+ title: "",
1347
+ metadata: {
1348
+ output,
1349
+ description: "",
1350
+ },
1351
+ output,
1352
+ }
1353
+ await Session.updatePart(part)
1354
+ }
1355
+ return { info: msg, parts: [part] }
1356
+ }
1357
+
1358
+ export const CommandInput = z.object({
1359
+ messageID: Identifier.schema("message").optional(),
1360
+ sessionID: Identifier.schema("session"),
1361
+ agent: z.string().optional(),
1362
+ model: z.string().optional(),
1363
+ arguments: z.string(),
1364
+ command: z.string(),
1365
+ })
1366
+ export type CommandInput = z.infer<typeof CommandInput>
1367
+ const bashRegex = /!`([^`]+)`/g
1368
+ const argsRegex = /(?:[^\s"']+|"[^"]*"|'[^']*')+/g
1369
+ const placeholderRegex = /\$(\d+)/g
1370
+ const quoteTrimRegex = /^["']|["']$/g
1371
+ /**
1372
+ * Regular expression to match @ file references in text
1373
+ * Matches @ followed by file paths, excluding commas, periods at end of sentences, and backticks
1374
+ * Does not match when preceded by word characters or backticks (to avoid email addresses and quoted references)
1375
+ */
1376
+
1377
+ export async function command(input: CommandInput) {
1378
+ log.info("command", input)
1379
+ const command = await Command.get(input.command)
1380
+ const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent())
1381
+
1382
+ const raw = input.arguments.match(argsRegex) ?? []
1383
+ const args = raw.map((arg) => arg.replace(quoteTrimRegex, ""))
1384
+
1385
+ const placeholders = command.template.match(placeholderRegex) ?? []
1386
+ let last = 0
1387
+ for (const item of placeholders) {
1388
+ const value = Number(item.slice(1))
1389
+ if (value > last) last = value
1390
+ }
1391
+
1392
+ // Let the final placeholder swallow any extra arguments so prompts read naturally
1393
+ const withArgs = command.template.replaceAll(placeholderRegex, (_, index) => {
1394
+ const position = Number(index)
1395
+ const argIndex = position - 1
1396
+ if (argIndex >= args.length) return ""
1397
+ if (position === last) return args.slice(argIndex).join(" ")
1398
+ return args[argIndex]
1399
+ })
1400
+ let template = withArgs.replaceAll("$ARGUMENTS", input.arguments)
1401
+
1402
+ const shell = ConfigMarkdown.shell(template)
1403
+ if (shell.length > 0) {
1404
+ const results = await Promise.all(
1405
+ shell.map(async ([, cmd]) => {
1406
+ try {
1407
+ return await $`${{ raw: cmd }}`.quiet().nothrow().text()
1408
+ } catch (error) {
1409
+ return `Error executing command: ${error instanceof Error ? error.message : String(error)}`
1410
+ }
1411
+ }),
1412
+ )
1413
+ let index = 0
1414
+ template = template.replace(bashRegex, () => results[index++])
1415
+ }
1416
+ template = template.trim()
1417
+
1418
+ const model = await (async () => {
1419
+ if (command.model) {
1420
+ return Provider.parseModel(command.model)
1421
+ }
1422
+ if (command.agent) {
1423
+ const cmdAgent = await Agent.get(command.agent)
1424
+ if (cmdAgent.model) {
1425
+ return cmdAgent.model
1426
+ }
1427
+ }
1428
+ if (input.model) return Provider.parseModel(input.model)
1429
+ return await lastModel(input.sessionID)
1430
+ })()
1431
+
1432
+ try {
1433
+ await Provider.getModel(model.providerID, model.modelID)
1434
+ } catch (e) {
1435
+ if (Provider.ModelNotFoundError.isInstance(e)) {
1436
+ const { providerID, modelID, suggestions } = e.data
1437
+ const hint = suggestions?.length ? ` Did you mean: ${suggestions.join(", ")}?` : ""
1438
+ Bus.publish(Session.Event.Error, {
1439
+ sessionID: input.sessionID,
1440
+ error: new NamedError.Unknown({ message: `Model not found: ${providerID}/${modelID}.${hint}` }).toObject(),
1441
+ })
1442
+ }
1443
+ throw e
1444
+ }
1445
+ const agent = await Agent.get(agentName)
1446
+
1447
+ const parts =
1448
+ (agent.mode === "subagent" && command.subtask !== false) || command.subtask === true
1449
+ ? [
1450
+ {
1451
+ type: "subtask" as const,
1452
+ agent: agent.name,
1453
+ description: command.description ?? "",
1454
+ command: input.command,
1455
+ // TODO: how can we make task tool accept a more complex input?
1456
+ prompt: await resolvePromptParts(template).then((x) => x.find((y) => y.type === "text")?.text ?? ""),
1457
+ },
1458
+ ]
1459
+ : await resolvePromptParts(template)
1460
+
1461
+ const result = (await prompt({
1462
+ sessionID: input.sessionID,
1463
+ messageID: input.messageID,
1464
+ model,
1465
+ agent: agentName,
1466
+ parts,
1467
+ })) as MessageV2.WithParts
1468
+
1469
+ Bus.publish(Command.Event.Executed, {
1470
+ name: input.command,
1471
+ sessionID: input.sessionID,
1472
+ arguments: input.arguments,
1473
+ messageID: result.info.id,
1474
+ })
1475
+
1476
+ return result
1477
+ }
1478
+
1479
+ async function ensureTitle(input: {
1480
+ session: Session.Info
1481
+ message: MessageV2.WithParts
1482
+ history: MessageV2.WithParts[]
1483
+ providerID: string
1484
+ modelID: string
1485
+ }) {
1486
+ return // DISABLED FOR TESTING
1487
+ if (input.session.parentID) return
1488
+ if (!Session.isDefaultTitle(input.session.title)) return
1489
+ const isFirst =
1490
+ input.history.filter((m) => m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic))
1491
+ .length === 1
1492
+ if (!isFirst) return
1493
+ const agent = await Agent.get("title")
1494
+ if (!agent) return
1495
+ const result = await LLM.stream({
1496
+ agent,
1497
+ user: input.message.info as MessageV2.User,
1498
+ system: [],
1499
+ small: true,
1500
+ tools: {},
1501
+ model: await iife(async () => {
1502
+ if (agent.model) return await Provider.getModel(agent.model.providerID, agent.model.modelID)
1503
+ return (
1504
+ (await Provider.getSmallModel(input.providerID)) ?? (await Provider.getModel(input.providerID, input.modelID))
1505
+ )
1506
+ }),
1507
+ abort: new AbortController().signal,
1508
+ sessionID: input.session.id,
1509
+ retries: 2,
1510
+ messages: [
1511
+ {
1512
+ role: "user",
1513
+ content: "Generate a title for this conversation:\n",
1514
+ },
1515
+ ...MessageV2.toModelMessage([
1516
+ {
1517
+ info: {
1518
+ id: Identifier.ascending("message"),
1519
+ role: "user",
1520
+ sessionID: input.session.id,
1521
+ time: {
1522
+ created: Date.now(),
1523
+ },
1524
+ agent: input.message.info.role === "user" ? input.message.info.agent : await Agent.defaultAgent(),
1525
+ model: {
1526
+ providerID: input.providerID,
1527
+ modelID: input.modelID,
1528
+ },
1529
+ },
1530
+ parts: input.message.parts,
1531
+ },
1532
+ ], { sessionID: input.session.id }),
1533
+ ],
1534
+ })
1535
+ const text = await result.text.catch((err) => {
1536
+ log.error("failed to generate title", { error: err })
1537
+ return undefined as undefined
1538
+ })
1539
+ if (!text) return
1540
+ return Session.update(input.session.id, (draft) => {
1541
+ const cleaned = (text as string)
1542
+ .replace(/<think>[\s\S]*?<\/think>\s*/g, "")
1543
+ .split("\n")
1544
+ .map((line) => line.trim())
1545
+ .find((line) => line.length > 0)
1546
+ if (!cleaned) return
1547
+
1548
+ const title = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
1549
+ draft.title = title
1550
+ })
1551
+ }
1552
+ }