@bloxystudios/bloxycode 1.0.2 → 1.0.5

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