jonsoc 1.1.48 → 1.1.50

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