@toolkit-cli/toolkode 1.3.8 → 1.3.10

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