onlycode 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/package.json +11 -146
  2. package/src/account/account.ts +0 -463
  3. package/src/account/repo.ts +0 -173
  4. package/src/account/schema.ts +0 -99
  5. package/src/account/url.ts +0 -8
  6. package/src/acp/agent.ts +0 -95
  7. package/src/acp/config-option.ts +0 -203
  8. package/src/acp/content.ts +0 -250
  9. package/src/acp/directory.ts +0 -210
  10. package/src/acp/error.ts +0 -90
  11. package/src/acp/event.ts +0 -342
  12. package/src/acp/permission.ts +0 -124
  13. package/src/acp/profile.ts +0 -42
  14. package/src/acp/service.ts +0 -1048
  15. package/src/acp/session.ts +0 -231
  16. package/src/acp/tool.ts +0 -367
  17. package/src/acp/usage.ts +0 -232
  18. package/src/agent/agent.ts +0 -459
  19. package/src/agent/generate.txt +0 -75
  20. package/src/agent/prompt/compaction.txt +0 -9
  21. package/src/agent/prompt/explore.txt +0 -18
  22. package/src/agent/prompt/summary.txt +0 -11
  23. package/src/agent/prompt/title.txt +0 -44
  24. package/src/agent/subagent-permissions.ts +0 -27
  25. package/src/audio.d.ts +0 -14
  26. package/src/auth/index.ts +0 -99
  27. package/src/background/job.ts +0 -39
  28. package/src/bus/global.ts +0 -22
  29. package/src/cli/bootstrap.ts +0 -11
  30. package/src/cli/cmd/account.ts +0 -264
  31. package/src/cli/cmd/acp.ts +0 -73
  32. package/src/cli/cmd/agent.ts +0 -259
  33. package/src/cli/cmd/attach.ts +0 -97
  34. package/src/cli/cmd/cmd.ts +0 -7
  35. package/src/cli/cmd/db.ts +0 -62
  36. package/src/cli/cmd/debug/agent.handler.ts +0 -193
  37. package/src/cli/cmd/debug/agent.ts +0 -27
  38. package/src/cli/cmd/debug/config.ts +0 -14
  39. package/src/cli/cmd/debug/file.ts +0 -73
  40. package/src/cli/cmd/debug/index.ts +0 -87
  41. package/src/cli/cmd/debug/lsp.ts +0 -50
  42. package/src/cli/cmd/debug/ripgrep.ts +0 -79
  43. package/src/cli/cmd/debug/scrap.ts +0 -15
  44. package/src/cli/cmd/debug/skill.ts +0 -15
  45. package/src/cli/cmd/debug/snapshot.ts +0 -50
  46. package/src/cli/cmd/debug/startup.ts +0 -11
  47. package/src/cli/cmd/debug/v2.ts +0 -44
  48. package/src/cli/cmd/export.ts +0 -292
  49. package/src/cli/cmd/generate.ts +0 -54
  50. package/src/cli/cmd/github.handler.ts +0 -1593
  51. package/src/cli/cmd/github.shared.ts +0 -30
  52. package/src/cli/cmd/github.ts +0 -42
  53. package/src/cli/cmd/import.ts +0 -224
  54. package/src/cli/cmd/mcp.ts +0 -849
  55. package/src/cli/cmd/models.ts +0 -66
  56. package/src/cli/cmd/plug.ts +0 -230
  57. package/src/cli/cmd/pr.ts +0 -115
  58. package/src/cli/cmd/prompt-display.ts +0 -1
  59. package/src/cli/cmd/providers.ts +0 -534
  60. package/src/cli/cmd/run/demo.ts +0 -1274
  61. package/src/cli/cmd/run/entry.body.ts +0 -205
  62. package/src/cli/cmd/run/footer.command.tsx +0 -1064
  63. package/src/cli/cmd/run/footer.menu.tsx +0 -351
  64. package/src/cli/cmd/run/footer.permission.tsx +0 -472
  65. package/src/cli/cmd/run/footer.prompt.tsx +0 -1306
  66. package/src/cli/cmd/run/footer.question.tsx +0 -573
  67. package/src/cli/cmd/run/footer.subagent.tsx +0 -173
  68. package/src/cli/cmd/run/footer.ts +0 -1129
  69. package/src/cli/cmd/run/footer.view.tsx +0 -943
  70. package/src/cli/cmd/run/footer.width.ts +0 -27
  71. package/src/cli/cmd/run/permission.shared.ts +0 -256
  72. package/src/cli/cmd/run/prompt.editor.ts +0 -157
  73. package/src/cli/cmd/run/prompt.shared.ts +0 -153
  74. package/src/cli/cmd/run/question.shared.ts +0 -340
  75. package/src/cli/cmd/run/runtime.boot.ts +0 -202
  76. package/src/cli/cmd/run/runtime.lifecycle.ts +0 -406
  77. package/src/cli/cmd/run/runtime.queue.ts +0 -349
  78. package/src/cli/cmd/run/runtime.shared.ts +0 -17
  79. package/src/cli/cmd/run/runtime.stdin.ts +0 -37
  80. package/src/cli/cmd/run/runtime.ts +0 -814
  81. package/src/cli/cmd/run/scrollback.shared.ts +0 -92
  82. package/src/cli/cmd/run/scrollback.surface.ts +0 -431
  83. package/src/cli/cmd/run/scrollback.writer.tsx +0 -352
  84. package/src/cli/cmd/run/session-data.ts +0 -1113
  85. package/src/cli/cmd/run/session-replay.ts +0 -374
  86. package/src/cli/cmd/run/session.shared.ts +0 -196
  87. package/src/cli/cmd/run/splash.ts +0 -275
  88. package/src/cli/cmd/run/stream.transport.ts +0 -1462
  89. package/src/cli/cmd/run/stream.ts +0 -175
  90. package/src/cli/cmd/run/subagent-data.ts +0 -876
  91. package/src/cli/cmd/run/theme.ts +0 -690
  92. package/src/cli/cmd/run/tool.ts +0 -1489
  93. package/src/cli/cmd/run/trace.ts +0 -94
  94. package/src/cli/cmd/run/turn-summary.ts +0 -47
  95. package/src/cli/cmd/run/types.ts +0 -350
  96. package/src/cli/cmd/run/variant.shared.ts +0 -215
  97. package/src/cli/cmd/run.ts +0 -894
  98. package/src/cli/cmd/serve.ts +0 -24
  99. package/src/cli/cmd/session.ts +0 -147
  100. package/src/cli/cmd/stats.ts +0 -393
  101. package/src/cli/cmd/tui.ts +0 -224
  102. package/src/cli/cmd/uninstall.ts +0 -353
  103. package/src/cli/cmd/upgrade.ts +0 -74
  104. package/src/cli/cmd/web.ts +0 -84
  105. package/src/cli/effect/prompt.ts +0 -37
  106. package/src/cli/effect-cmd.ts +0 -96
  107. package/src/cli/error.ts +0 -130
  108. package/src/cli/heap.ts +0 -45
  109. package/src/cli/logo-pixel.ts +0 -35
  110. package/src/cli/logo.ts +0 -1
  111. package/src/cli/network.ts +0 -64
  112. package/src/cli/tui/layer.ts +0 -7
  113. package/src/cli/tui/validate-session.ts +0 -29
  114. package/src/cli/tui/worker.ts +0 -71
  115. package/src/cli/ui.ts +0 -148
  116. package/src/cli/upgrade.ts +0 -53
  117. package/src/command/index.ts +0 -184
  118. package/src/command/template/initialize.txt +0 -66
  119. package/src/command/template/review.txt +0 -101
  120. package/src/config/agent.ts +0 -59
  121. package/src/config/command.ts +0 -39
  122. package/src/config/config.ts +0 -686
  123. package/src/config/entry-name.ts +0 -19
  124. package/src/config/managed.ts +0 -69
  125. package/src/config/markdown.ts +0 -36
  126. package/src/config/parse.ts +0 -79
  127. package/src/config/paths.ts +0 -45
  128. package/src/config/plugin.ts +0 -79
  129. package/src/config/tui-cwd.ts +0 -5
  130. package/src/config/tui-host-attention.ts +0 -21
  131. package/src/config/tui-migrate.ts +0 -132
  132. package/src/config/tui.ts +0 -274
  133. package/src/config/variable.ts +0 -91
  134. package/src/control-plane/adapters/index.ts +0 -41
  135. package/src/control-plane/adapters/worktree.ts +0 -96
  136. package/src/control-plane/dev/README.md +0 -19
  137. package/src/control-plane/dev/debug-workspace-plugin.ts +0 -73
  138. package/src/control-plane/types.ts +0 -59
  139. package/src/control-plane/util.ts +0 -39
  140. package/src/control-plane/workspace-adapter-runtime.ts +0 -51
  141. package/src/control-plane/workspace-context.ts +0 -26
  142. package/src/control-plane/workspace.ts +0 -989
  143. package/src/effect/app-runtime.ts +0 -132
  144. package/src/effect/bootstrap-runtime.ts +0 -23
  145. package/src/effect/bridge.ts +0 -84
  146. package/src/effect/config-service.ts +0 -67
  147. package/src/effect/instance-ref.ts +0 -11
  148. package/src/effect/instance-registry.ts +0 -12
  149. package/src/effect/instance-state.ts +0 -69
  150. package/src/effect/promise.ts +0 -17
  151. package/src/effect/run-service.ts +0 -47
  152. package/src/effect/runner.ts +0 -217
  153. package/src/effect/runtime-flags.ts +0 -79
  154. package/src/env/index.ts +0 -43
  155. package/src/event-v2-bridge.ts +0 -79
  156. package/src/format/formatter.ts +0 -404
  157. package/src/format/index.ts +0 -205
  158. package/src/git/index.ts +0 -350
  159. package/src/id/id.ts +0 -80
  160. package/src/ide/index.ts +0 -61
  161. package/src/image/image.ts +0 -174
  162. package/src/index.ts +0 -142
  163. package/src/installation/index.ts +0 -350
  164. package/src/lsp/client.ts +0 -650
  165. package/src/lsp/diagnostic.ts +0 -29
  166. package/src/lsp/language.ts +0 -121
  167. package/src/lsp/launch.ts +0 -21
  168. package/src/lsp/lsp.ts +0 -511
  169. package/src/lsp/server.ts +0 -1983
  170. package/src/markdown.d.ts +0 -4
  171. package/src/mcp/auth.ts +0 -174
  172. package/src/mcp/catalog.ts +0 -153
  173. package/src/mcp/index.ts +0 -953
  174. package/src/mcp/oauth-callback.ts +0 -233
  175. package/src/mcp/oauth-provider.ts +0 -206
  176. package/src/node.ts +0 -4
  177. package/src/patch/index.ts +0 -686
  178. package/src/permission/arity.ts +0 -163
  179. package/src/permission/evaluate.ts +0 -1
  180. package/src/permission/index.ts +0 -230
  181. package/src/plugin/azure.ts +0 -26
  182. package/src/plugin/cloudflare.ts +0 -76
  183. package/src/plugin/digitalocean.ts +0 -383
  184. package/src/plugin/github-copilot/copilot.ts +0 -414
  185. package/src/plugin/github-copilot/models.ts +0 -246
  186. package/src/plugin/index.ts +0 -316
  187. package/src/plugin/install.ts +0 -439
  188. package/src/plugin/loader.ts +0 -237
  189. package/src/plugin/meta.ts +0 -188
  190. package/src/plugin/openai/README.md +0 -31
  191. package/src/plugin/openai/codex.ts +0 -641
  192. package/src/plugin/openai/ws-pool.ts +0 -270
  193. package/src/plugin/openai/ws.ts +0 -381
  194. package/src/plugin/pty-environment.ts +0 -24
  195. package/src/plugin/shared.ts +0 -323
  196. package/src/plugin/snowflake-cortex.ts +0 -529
  197. package/src/plugin/tui/internal.ts +0 -10
  198. package/src/plugin/tui/runtime.ts +0 -1130
  199. package/src/plugin/xai.ts +0 -716
  200. package/src/project/bootstrap-service.ts +0 -9
  201. package/src/project/bootstrap.ts +0 -76
  202. package/src/project/instance-context.ts +0 -24
  203. package/src/project/instance-layer.ts +0 -11
  204. package/src/project/instance-runtime.ts +0 -16
  205. package/src/project/instance-store.ts +0 -209
  206. package/src/project/project.ts +0 -519
  207. package/src/project/vcs.ts +0 -431
  208. package/src/provider/auth.ts +0 -233
  209. package/src/provider/error.ts +0 -188
  210. package/src/provider/model-status.ts +0 -8
  211. package/src/provider/provider.ts +0 -1975
  212. package/src/provider/transform.ts +0 -1543
  213. package/src/question/index.ts +0 -229
  214. package/src/question/schema.ts +0 -10
  215. package/src/server/auth.ts +0 -48
  216. package/src/server/event.ts +0 -13
  217. package/src/server/global-lifecycle.ts +0 -28
  218. package/src/server/init-projectors.ts +0 -3
  219. package/src/server/mdns.ts +0 -47
  220. package/src/server/projectors.ts +0 -1
  221. package/src/server/proxy-util.ts +0 -48
  222. package/src/server/routes/instance/httpapi/AGENTS.md +0 -39
  223. package/src/server/routes/instance/httpapi/api.ts +0 -78
  224. package/src/server/routes/instance/httpapi/errors.ts +0 -193
  225. package/src/server/routes/instance/httpapi/groups/config.ts +0 -65
  226. package/src/server/routes/instance/httpapi/groups/control-plane.ts +0 -35
  227. package/src/server/routes/instance/httpapi/groups/control.ts +0 -76
  228. package/src/server/routes/instance/httpapi/groups/event.ts +0 -29
  229. package/src/server/routes/instance/httpapi/groups/experimental.ts +0 -275
  230. package/src/server/routes/instance/httpapi/groups/file.ts +0 -185
  231. package/src/server/routes/instance/httpapi/groups/global.ts +0 -138
  232. package/src/server/routes/instance/httpapi/groups/instance.ts +0 -206
  233. package/src/server/routes/instance/httpapi/groups/mcp.ts +0 -156
  234. package/src/server/routes/instance/httpapi/groups/metadata.ts +0 -18
  235. package/src/server/routes/instance/httpapi/groups/permission.ts +0 -61
  236. package/src/server/routes/instance/httpapi/groups/project-copy.ts +0 -32
  237. package/src/server/routes/instance/httpapi/groups/project.ts +0 -93
  238. package/src/server/routes/instance/httpapi/groups/provider.ts +0 -101
  239. package/src/server/routes/instance/httpapi/groups/pty.ts +0 -172
  240. package/src/server/routes/instance/httpapi/groups/query.ts +0 -12
  241. package/src/server/routes/instance/httpapi/groups/question.ts +0 -74
  242. package/src/server/routes/instance/httpapi/groups/session.ts +0 -462
  243. package/src/server/routes/instance/httpapi/groups/sync.ts +0 -113
  244. package/src/server/routes/instance/httpapi/groups/tui.ts +0 -208
  245. package/src/server/routes/instance/httpapi/groups/workspace.ts +0 -141
  246. package/src/server/routes/instance/httpapi/handlers/config.ts +0 -34
  247. package/src/server/routes/instance/httpapi/handlers/control-plane.ts +0 -37
  248. package/src/server/routes/instance/httpapi/handlers/control.ts +0 -43
  249. package/src/server/routes/instance/httpapi/handlers/event.ts +0 -99
  250. package/src/server/routes/instance/httpapi/handlers/experimental.ts +0 -192
  251. package/src/server/routes/instance/httpapi/handlers/file.ts +0 -139
  252. package/src/server/routes/instance/httpapi/handlers/global.ts +0 -156
  253. package/src/server/routes/instance/httpapi/handlers/instance.ts +0 -110
  254. package/src/server/routes/instance/httpapi/handlers/mcp.ts +0 -111
  255. package/src/server/routes/instance/httpapi/handlers/permission.ts +0 -41
  256. package/src/server/routes/instance/httpapi/handlers/project-copy.ts +0 -83
  257. package/src/server/routes/instance/httpapi/handlers/project.ts +0 -63
  258. package/src/server/routes/instance/httpapi/handlers/provider.ts +0 -113
  259. package/src/server/routes/instance/httpapi/handlers/pty.ts +0 -273
  260. package/src/server/routes/instance/httpapi/handlers/question.ts +0 -54
  261. package/src/server/routes/instance/httpapi/handlers/session-errors.ts +0 -21
  262. package/src/server/routes/instance/httpapi/handlers/session.ts +0 -440
  263. package/src/server/routes/instance/httpapi/handlers/sync.ts +0 -89
  264. package/src/server/routes/instance/httpapi/handlers/tui.ts +0 -131
  265. package/src/server/routes/instance/httpapi/handlers/workspace.ts +0 -102
  266. package/src/server/routes/instance/httpapi/lifecycle.ts +0 -54
  267. package/src/server/routes/instance/httpapi/middleware/authorization.ts +0 -150
  268. package/src/server/routes/instance/httpapi/middleware/compression.ts +0 -64
  269. package/src/server/routes/instance/httpapi/middleware/cors-vary.ts +0 -29
  270. package/src/server/routes/instance/httpapi/middleware/error.ts +0 -43
  271. package/src/server/routes/instance/httpapi/middleware/fence.ts +0 -25
  272. package/src/server/routes/instance/httpapi/middleware/instance-context.ts +0 -43
  273. package/src/server/routes/instance/httpapi/middleware/proxy.ts +0 -108
  274. package/src/server/routes/instance/httpapi/middleware/schema-error.ts +0 -41
  275. package/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +0 -250
  276. package/src/server/routes/instance/httpapi/public.ts +0 -535
  277. package/src/server/routes/instance/httpapi/server.ts +0 -298
  278. package/src/server/routes/instance/httpapi/websocket-tracker.ts +0 -57
  279. package/src/server/server.ts +0 -225
  280. package/src/server/shared/fence.ts +0 -60
  281. package/src/server/shared/pty-ticket.ts +0 -15
  282. package/src/server/shared/public-ui.ts +0 -12
  283. package/src/server/shared/tui-control.ts +0 -28
  284. package/src/server/shared/ui.ts +0 -108
  285. package/src/server/shared/workspace-routing.ts +0 -38
  286. package/src/server/tui-event.ts +0 -53
  287. package/src/session/compaction.ts +0 -620
  288. package/src/session/instruction.ts +0 -241
  289. package/src/session/llm/AGENTS.md +0 -90
  290. package/src/session/llm/ai-sdk.ts +0 -288
  291. package/src/session/llm/native-request.ts +0 -196
  292. package/src/session/llm/native-runtime.ts +0 -195
  293. package/src/session/llm/request.ts +0 -216
  294. package/src/session/llm.ts +0 -415
  295. package/src/session/message-error.ts +0 -14
  296. package/src/session/message-v2.ts +0 -747
  297. package/src/session/message.ts +0 -148
  298. package/src/session/overflow.ts +0 -34
  299. package/src/session/processor.ts +0 -1084
  300. package/src/session/prompt/anthropic.txt +0 -109
  301. package/src/session/prompt/beast.txt +0 -151
  302. package/src/session/prompt/build-switch.txt +0 -9
  303. package/src/session/prompt/codex.txt +0 -83
  304. package/src/session/prompt/copilot-gpt-5.txt +0 -147
  305. package/src/session/prompt/default.txt +0 -99
  306. package/src/session/prompt/gemini.txt +0 -159
  307. package/src/session/prompt/gpt.txt +0 -111
  308. package/src/session/prompt/kimi.txt +0 -99
  309. package/src/session/prompt/plan-mode.txt +0 -74
  310. package/src/session/prompt/plan-reminder-anthropic.txt +0 -71
  311. package/src/session/prompt/plan.txt +0 -30
  312. package/src/session/prompt/trinity.txt +0 -101
  313. package/src/session/prompt.ts +0 -1707
  314. package/src/session/reminders.ts +0 -92
  315. package/src/session/retry.ts +0 -201
  316. package/src/session/revert.ts +0 -160
  317. package/src/session/run-state.ts +0 -156
  318. package/src/session/schema.ts +0 -26
  319. package/src/session/session.ts +0 -1119
  320. package/src/session/status.ts +0 -97
  321. package/src/session/summary.ts +0 -165
  322. package/src/session/system.ts +0 -117
  323. package/src/session/todo.ts +0 -90
  324. package/src/session/tools.ts +0 -207
  325. package/src/share/session.ts +0 -61
  326. package/src/share/share-next.ts +0 -385
  327. package/src/skill/discovery.ts +0 -109
  328. package/src/skill/index.ts +0 -366
  329. package/src/snapshot/index.ts +0 -808
  330. package/src/sql.d.ts +0 -4
  331. package/src/storage/schema.ts +0 -5
  332. package/src/storage/storage.ts +0 -329
  333. package/src/sync/README.md +0 -179
  334. package/src/sync/schema.ts +0 -11
  335. package/src/temporary.ts +0 -31
  336. package/src/tool/apply_patch.ts +0 -315
  337. package/src/tool/apply_patch.txt +0 -33
  338. package/src/tool/apply_patch.zh.txt +0 -33
  339. package/src/tool/description.ts +0 -100
  340. package/src/tool/edit.ts +0 -739
  341. package/src/tool/edit.txt +0 -10
  342. package/src/tool/edit.zh.txt +0 -10
  343. package/src/tool/external-directory.ts +0 -49
  344. package/src/tool/glob.ts +0 -78
  345. package/src/tool/glob.txt +0 -6
  346. package/src/tool/glob.zh.txt +0 -6
  347. package/src/tool/grep.ts +0 -114
  348. package/src/tool/grep.txt +0 -8
  349. package/src/tool/grep.zh.txt +0 -8
  350. package/src/tool/invalid.ts +0 -21
  351. package/src/tool/json-schema.ts +0 -164
  352. package/src/tool/lsp.ts +0 -115
  353. package/src/tool/lsp.txt +0 -24
  354. package/src/tool/lsp.zh.txt +0 -24
  355. package/src/tool/mcp-websearch.ts +0 -96
  356. package/src/tool/plan-enter.txt +0 -14
  357. package/src/tool/plan-enter.zh.txt +0 -14
  358. package/src/tool/plan-exit.txt +0 -13
  359. package/src/tool/plan-exit.zh.txt +0 -13
  360. package/src/tool/plan.ts +0 -81
  361. package/src/tool/question.ts +0 -46
  362. package/src/tool/question.txt +0 -10
  363. package/src/tool/question.zh.txt +0 -10
  364. package/src/tool/read.ts +0 -388
  365. package/src/tool/read.txt +0 -14
  366. package/src/tool/read.zh.txt +0 -14
  367. package/src/tool/registry.ts +0 -440
  368. package/src/tool/schema.ts +0 -14
  369. package/src/tool/shell/id.ts +0 -19
  370. package/src/tool/shell/prompt.ts +0 -307
  371. package/src/tool/shell/shell.txt +0 -21
  372. package/src/tool/shell.ts +0 -657
  373. package/src/tool/skill.ts +0 -73
  374. package/src/tool/skill.txt +0 -5
  375. package/src/tool/skill.zh.txt +0 -5
  376. package/src/tool/task.ts +0 -348
  377. package/src/tool/task.txt +0 -19
  378. package/src/tool/task.zh.txt +0 -19
  379. package/src/tool/todo.ts +0 -59
  380. package/src/tool/todowrite.txt +0 -44
  381. package/src/tool/todowrite.zh.txt +0 -44
  382. package/src/tool/tool.ts +0 -183
  383. package/src/tool/truncate.ts +0 -158
  384. package/src/tool/truncation-dir.ts +0 -4
  385. package/src/tool/webfetch.ts +0 -194
  386. package/src/tool/webfetch.txt +0 -13
  387. package/src/tool/webfetch.zh.txt +0 -13
  388. package/src/tool/websearch.ts +0 -145
  389. package/src/tool/websearch.txt +0 -14
  390. package/src/tool/websearch.zh.txt +0 -14
  391. package/src/tool/write.ts +0 -106
  392. package/src/tool/write.txt +0 -8
  393. package/src/tool/write.zh.txt +0 -8
  394. package/src/util/archive.ts +0 -17
  395. package/src/util/bom.ts +0 -27
  396. package/src/util/data-url.ts +0 -9
  397. package/src/util/defer.ts +0 -10
  398. package/src/util/effect-http-client.ts +0 -11
  399. package/src/util/error.ts +0 -1
  400. package/src/util/filesystem.ts +0 -251
  401. package/src/util/html.ts +0 -8
  402. package/src/util/iife.ts +0 -3
  403. package/src/util/lazy.ts +0 -20
  404. package/src/util/local-context.ts +0 -25
  405. package/src/util/locale.ts +0 -2
  406. package/src/util/media.ts +0 -26
  407. package/src/util/process.ts +0 -177
  408. package/src/util/proxy-env.ts +0 -72
  409. package/src/util/queue.ts +0 -32
  410. package/src/util/record.ts +0 -1
  411. package/src/util/repository.ts +0 -232
  412. package/src/util/rpc.ts +0 -66
  413. package/src/util/signal.ts +0 -12
  414. package/src/util/timeout.ts +0 -13
  415. package/src/util/token.ts +0 -1
  416. package/src/util/wildcard.ts +0 -59
  417. package/src/worktree/index.ts +0 -654
@@ -1,1707 +0,0 @@
1
- import { LayerNode } from "@opencode-ai/core/effect/layer-node"
2
- import { PermissionV1 } from "@opencode-ai/core/v1/permission"
3
- import path from "path"
4
- import { SessionV1 } from "@opencode-ai/core/v1/session"
5
- import os from "os"
6
- import { SessionID, MessageID, PartID } from "./schema"
7
- import { MessageV2 } from "./message-v2"
8
- import { SessionRevert } from "./revert"
9
- import { Session } from "./session"
10
- import { Agent } from "../agent/agent"
11
- import { Provider } from "@/provider/provider"
12
-
13
- import { type Tool as AITool, tool, jsonSchema } from "ai"
14
- import type { JSONSchema7 } from "@ai-sdk/provider"
15
- import { SessionCompaction } from "./compaction"
16
- import { SystemPrompt } from "./system"
17
- import { Instruction } from "./instruction"
18
- import { Plugin } from "../plugin"
19
- import { MAX_STEPS_PROMPT } from "@opencode-ai/core/session/runner/max-steps"
20
- import { ToolRegistry } from "@/tool/registry"
21
- import { MCP } from "../mcp"
22
- import { LSP } from "@/lsp/lsp"
23
- import { ulid } from "ulid"
24
- import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
25
- import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
26
- import * as Stream from "effect/Stream"
27
- import { Command } from "../command"
28
- import { pathToFileURL, fileURLToPath } from "url"
29
- import { Config } from "@/config/config"
30
- import { ConfigMarkdown } from "@/config/markdown"
31
- import { SessionSummary } from "./summary"
32
- import { NamedError } from "@opencode-ai/core/util/error"
33
- import { SessionProcessor } from "./processor"
34
- import { Tool } from "@/tool/tool"
35
- import { Permission } from "@/permission"
36
- import { SessionStatus } from "./status"
37
- import { LLM } from "./llm"
38
- import { Shell } from "@opencode-ai/core/shell"
39
- import { ShellID } from "@/tool/shell/id"
40
- import { FSUtil } from "@opencode-ai/core/fs-util"
41
- import { Truncate } from "@/tool/truncate"
42
- import { Image } from "@/image/image"
43
- import { decodeDataUrl } from "@/util/data-url"
44
- import { Process } from "@/util/process"
45
- import { Cause, Effect, Exit, Latch, Layer, Option, Scope, Context, Schema, Types } from "effect"
46
- import { InstanceState } from "@/effect/instance-state"
47
- import { TaskTool, type TaskPromptOps } from "@/tool/task"
48
- import { SessionRunState } from "./run-state"
49
- import { RuntimeFlags } from "@/effect/runtime-flags"
50
- import { EventV2Bridge } from "@/event-v2-bridge"
51
- import { Database } from "@opencode-ai/core/database/database"
52
- import { SessionEvent } from "@opencode-ai/core/session/event"
53
- import { SessionMessage } from "@opencode-ai/core/session/message"
54
- import { ModelV2 } from "@opencode-ai/core/model"
55
- import { ProviderV2 } from "@opencode-ai/core/provider"
56
- import { AgentAttachment, FileAttachment, Prompt, Source } from "@opencode-ai/core/session/prompt"
57
- import * as DateTime from "effect/DateTime"
58
- import { eq } from "drizzle-orm"
59
- import { SessionTable } from "@opencode-ai/core/session/sql"
60
- import { SessionReminders } from "./reminders"
61
- import { SessionTools } from "./tools"
62
- import { LLMEvent } from "@opencode-ai/llm"
63
-
64
- // @ts-ignore
65
- globalThis.AI_SDK_LOG_WARNINGS = false
66
-
67
- const decodeMessageInfo = Schema.decodeUnknownExit(SessionV1.Info)
68
- const decodeMessagePart = Schema.decodeUnknownExit(SessionV1.Part)
69
-
70
- const STRUCTURED_OUTPUT_DESCRIPTION = `Use this tool to return your final response in the requested structured format.
71
-
72
- IMPORTANT:
73
- - You MUST call this tool exactly once at the end of your response
74
- - The input must be valid JSON matching the required schema
75
- - Complete all necessary research and tool calls BEFORE calling this tool
76
- - This tool provides your final answer - no further actions are taken after calling it`
77
-
78
- 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.`
79
-
80
- function isOrphanedInterruptedTool(part: SessionV1.ToolPart) {
81
- // cleanup() marks abandoned tool_use blocks this way after retries/aborts.
82
- // They are not pending work and must not trigger an assistant-prefill request.
83
- return part.state.status === "error" && part.state.metadata?.interrupted === true
84
- }
85
-
86
- export interface Interface {
87
- readonly cancel: (sessionID: SessionID) => Effect.Effect<void>
88
- readonly prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error>
89
- readonly loop: (input: LoopInput) => Effect.Effect<SessionV1.WithParts>
90
- readonly shell: (input: ShellInput) => Effect.Effect<SessionV1.WithParts, Session.BusyError>
91
- readonly command: (input: CommandInput) => Effect.Effect<SessionV1.WithParts, Image.Error>
92
- readonly resolvePromptParts: (template: string) => Effect.Effect<PromptInput["parts"]>
93
- }
94
-
95
- export class Service extends Context.Service<Service, Interface>()("@opencode/SessionPrompt") {}
96
-
97
- export const layer = Layer.effect(
98
- Service,
99
- Effect.gen(function* () {
100
- const status = yield* SessionStatus.Service
101
- const sessions = yield* Session.Service
102
- const agents = yield* Agent.Service
103
- const provider = yield* Provider.Service
104
- const processor = yield* SessionProcessor.Service
105
- const compaction = yield* SessionCompaction.Service
106
- const plugin = yield* Plugin.Service
107
- const commands = yield* Command.Service
108
- const config = yield* Config.Service
109
- const permission = yield* Permission.Service
110
- const fsys = yield* FSUtil.Service
111
- const mcp = yield* MCP.Service
112
- const lsp = yield* LSP.Service
113
- const registry = yield* ToolRegistry.Service
114
- const truncate = yield* Truncate.Service
115
- const image = yield* Image.Service
116
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
117
- const scope = yield* Scope.Scope
118
- const instruction = yield* Instruction.Service
119
- const state = yield* SessionRunState.Service
120
- const revert = yield* SessionRevert.Service
121
- const summary = yield* SessionSummary.Service
122
- const sys = yield* SystemPrompt.Service
123
- const llm = yield* LLM.Service
124
- const events = yield* EventV2Bridge.Service
125
- const flags = yield* RuntimeFlags.Service
126
- const database = yield* Database.Service
127
- const { db } = database
128
- const ops = Effect.fn("SessionPrompt.ops")(function* () {
129
- return {
130
- cancel: (sessionID: SessionID) => cancel(sessionID),
131
- resolvePromptParts: (template: string) => resolvePromptParts(template),
132
- prompt: (input: PromptInput) => prompt(input).pipe(Effect.catch(Effect.die)),
133
- } satisfies TaskPromptOps
134
- })
135
-
136
- const cancel = Effect.fn("SessionPrompt.cancel")(function* (sessionID: SessionID) {
137
- yield* Effect.logInfo("cancel", { "session.id": sessionID })
138
- yield* state.cancel(sessionID)
139
- })
140
-
141
- const resolvePromptParts = Effect.fn("SessionPrompt.resolvePromptParts")(function* (template: string) {
142
- const ctx = yield* InstanceState.context
143
- const parts: Types.DeepMutable<PromptInput["parts"]> = [{ type: "text", text: template }]
144
- const files = ConfigMarkdown.files(template)
145
- const seen = new Set<string>()
146
- yield* Effect.forEach(
147
- files,
148
- Effect.fnUntraced(function* (match) {
149
- const name = match[1]
150
- if (!name) return
151
- if (seen.has(name)) return
152
- seen.add(name)
153
-
154
- const filepath = name.startsWith("~/")
155
- ? path.join(os.homedir(), name.slice(2))
156
- : path.resolve(ctx.worktree, name)
157
-
158
- const info = yield* fsys.stat(filepath).pipe(Effect.option)
159
- if (Option.isNone(info)) {
160
- const found = yield* agents.get(name)
161
- if (found) parts.push({ type: "agent", name: found.name })
162
- return
163
- }
164
- const stat = info.value
165
- parts.push({
166
- type: "file",
167
- url: pathToFileURL(filepath).href,
168
- filename: name,
169
- mime: stat.type === "Directory" ? "application/x-directory" : "text/plain",
170
- })
171
- }),
172
- { concurrency: "unbounded", discard: true },
173
- )
174
- return parts
175
- })
176
-
177
- const title = Effect.fn("SessionPrompt.ensureTitle")(function* (input: {
178
- session: Session.Info
179
- history: SessionV1.WithParts[]
180
- providerID: ProviderV2.ID
181
- modelID: ModelV2.ID
182
- }) {
183
- if (input.session.parentID) return
184
- if (!Session.isDefaultTitle(input.session.title)) return
185
-
186
- const real = (m: SessionV1.WithParts) =>
187
- m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic)
188
- const idx = input.history.findIndex(real)
189
- if (idx === -1) return
190
- if (input.history.filter(real).length !== 1) return
191
-
192
- const context = input.history.slice(0, idx + 1)
193
- const firstUser = context[idx]
194
- if (!firstUser || firstUser.info.role !== "user") return
195
- const firstInfo = firstUser.info
196
-
197
- const subtasks = firstUser.parts.filter((p): p is SessionV1.SubtaskPart => p.type === "subtask")
198
- const onlySubtasks = subtasks.length > 0 && firstUser.parts.every((p) => p.type === "subtask")
199
-
200
- const ag = yield* agents.get("title")
201
- if (!ag) return
202
- const mdl = ag.model
203
- ? yield* provider.getModel(ag.model.providerID, ag.model.modelID)
204
- : ((yield* provider.getSmallModel(input.providerID)) ??
205
- (yield* provider.getModel(input.providerID, input.modelID)))
206
- const msgs = onlySubtasks
207
- ? [{ role: "user" as const, content: subtasks.map((p) => p.prompt).join("\n") }]
208
- : yield* MessageV2.toModelMessagesEffect(context, mdl)
209
- const text = yield* llm
210
- .stream({
211
- agent: ag,
212
- user: firstInfo,
213
- system: [],
214
- small: true,
215
- tools: {},
216
- model: mdl,
217
- sessionID: input.session.id,
218
- retries: 2,
219
- messages: [{ role: "user", content: "Generate a title for this conversation:\n" }, ...msgs],
220
- })
221
- .pipe(
222
- Stream.filter(LLMEvent.is.textDelta),
223
- Stream.map((e) => e.text),
224
- Stream.mkString,
225
- Effect.orDie,
226
- )
227
- const cleaned = text
228
- .replace(/<think>[\s\S]*?<\/think>\s*/g, "")
229
- .split("\n")
230
- .map((line) => line.trim())
231
- .find((line) => line.length > 0)
232
- if (!cleaned) return
233
- const t = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
234
- yield* sessions
235
- .setTitle({ sessionID: input.session.id, title: t })
236
- .pipe(Effect.catchCause((cause) => Effect.logError("failed to generate title", { error: Cause.squash(cause) })))
237
- })
238
-
239
- const handleSubtask = Effect.fn("SessionPrompt.handleSubtask")(function* (input: {
240
- task: SessionV1.SubtaskPart
241
- model: Provider.Model
242
- lastUser: SessionV1.User
243
- sessionID: SessionID
244
- session: Session.Info
245
- msgs: SessionV1.WithParts[]
246
- }) {
247
- const { task, model, lastUser, sessionID, session, msgs } = input
248
- const ctx = yield* InstanceState.context
249
- const promptOps = yield* ops()
250
- const { task: taskTool } = yield* registry.named()
251
- const taskModel = task.model ? yield* getModel(task.model.providerID, task.model.modelID, sessionID) : model
252
- const assistantMessage: SessionV1.Assistant = yield* sessions.updateMessage({
253
- id: MessageID.ascending(),
254
- role: "assistant",
255
- parentID: lastUser.id,
256
- sessionID,
257
- mode: task.agent,
258
- agent: task.agent,
259
- variant: lastUser.model.variant,
260
- path: { cwd: ctx.directory, root: ctx.worktree },
261
- cost: 0,
262
- tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
263
- modelID: taskModel.id,
264
- providerID: taskModel.providerID,
265
- time: { created: Date.now() },
266
- })
267
- let part: SessionV1.ToolPart = yield* sessions.updatePart({
268
- id: PartID.ascending(),
269
- messageID: assistantMessage.id,
270
- sessionID: assistantMessage.sessionID,
271
- type: "tool",
272
- callID: ulid(),
273
- tool: TaskTool.id,
274
- state: {
275
- status: "running",
276
- input: {
277
- prompt: task.prompt,
278
- description: task.description,
279
- subagent_type: task.agent,
280
- command: task.command,
281
- },
282
- time: { start: Date.now() },
283
- },
284
- })
285
- const taskArgs = {
286
- prompt: task.prompt,
287
- description: task.description,
288
- subagent_type: task.agent,
289
- command: task.command,
290
- }
291
- yield* plugin.trigger(
292
- "tool.execute.before",
293
- { tool: TaskTool.id, sessionID, callID: part.id },
294
- { args: taskArgs },
295
- )
296
-
297
- const taskAgent = yield* agents.get(task.agent)
298
- if (!taskAgent) {
299
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
300
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
301
- const error = new NamedError.Unknown({ message: `Agent not found: "${task.agent}".${hint}` })
302
- yield* events.publish(Session.Event.Error, { sessionID, error: error.toObject() })
303
- throw error
304
- }
305
-
306
- let error: Error | undefined
307
- const taskAbort = new AbortController()
308
- const result = yield* taskTool
309
- .execute(taskArgs, {
310
- agent: task.agent,
311
- messageID: assistantMessage.id,
312
- sessionID,
313
- abort: taskAbort.signal,
314
- callID: part.callID,
315
- extra: { bypassAgentCheck: true, promptOps },
316
- messages: msgs,
317
- metadata: (val: { title?: string; metadata?: Record<string, any> }) =>
318
- Effect.gen(function* () {
319
- part = yield* sessions.updatePart({
320
- ...part,
321
- type: "tool",
322
- state: { ...part.state, ...val },
323
- } satisfies SessionV1.ToolPart)
324
- }),
325
- ask: (req: any) =>
326
- permission
327
- .ask({
328
- ...req,
329
- sessionID,
330
- ruleset: Permission.merge(taskAgent.permission, session.permission ?? []),
331
- })
332
- .pipe(Effect.orDie),
333
- })
334
- .pipe(
335
- Effect.catchCause((cause) => {
336
- const defect = Cause.squash(cause)
337
- error = defect instanceof Error ? defect : new Error(String(defect))
338
- return Effect.logError("subtask execution failed", {
339
- error,
340
- agent: task.agent,
341
- description: task.description,
342
- })
343
- }),
344
- Effect.onInterrupt(() =>
345
- Effect.gen(function* () {
346
- taskAbort.abort()
347
- assistantMessage.finish = "tool-calls"
348
- assistantMessage.time.completed = Date.now()
349
- yield* sessions.updateMessage(assistantMessage)
350
- if (part.state.status === "running") {
351
- yield* sessions.updatePart({
352
- ...part,
353
- state: {
354
- status: "error",
355
- error: "Cancelled",
356
- time: { start: part.state.time.start, end: Date.now() },
357
- metadata: part.state.metadata,
358
- input: part.state.input,
359
- },
360
- } satisfies SessionV1.ToolPart)
361
- }
362
- }),
363
- ),
364
- )
365
-
366
- const attachments = result?.attachments?.map((attachment) => ({
367
- ...attachment,
368
- id: PartID.ascending(),
369
- sessionID,
370
- messageID: assistantMessage.id,
371
- }))
372
-
373
- yield* plugin.trigger(
374
- "tool.execute.after",
375
- { tool: TaskTool.id, sessionID, callID: part.id, args: taskArgs },
376
- result,
377
- )
378
-
379
- assistantMessage.finish = "tool-calls"
380
- assistantMessage.time.completed = Date.now()
381
- yield* sessions.updateMessage(assistantMessage)
382
-
383
- if (result && part.state.status === "running") {
384
- yield* sessions.updatePart({
385
- ...part,
386
- state: {
387
- status: "completed",
388
- input: part.state.input,
389
- title: result.title,
390
- metadata: result.metadata,
391
- output: result.output,
392
- attachments,
393
- time: { ...part.state.time, end: Date.now() },
394
- },
395
- } satisfies SessionV1.ToolPart)
396
- }
397
-
398
- if (!result) {
399
- yield* sessions.updatePart({
400
- ...part,
401
- state: {
402
- status: "error",
403
- error: error ? `Tool execution failed: ${error.message}` : "Tool execution failed",
404
- time: {
405
- start: part.state.status === "running" ? part.state.time.start : Date.now(),
406
- end: Date.now(),
407
- },
408
- metadata: part.state.status === "pending" ? undefined : part.state.metadata,
409
- input: part.state.input,
410
- },
411
- } satisfies SessionV1.ToolPart)
412
- }
413
-
414
- if (!task.command) return
415
-
416
- const summaryUserMsg: SessionV1.User = {
417
- id: MessageID.ascending(),
418
- sessionID,
419
- role: "user",
420
- time: { created: Date.now() },
421
- agent: lastUser.agent,
422
- model: lastUser.model,
423
- }
424
- yield* sessions.updateMessage(summaryUserMsg)
425
- yield* sessions.updatePart({
426
- id: PartID.ascending(),
427
- messageID: summaryUserMsg.id,
428
- sessionID,
429
- type: "text",
430
- text: "Summarize the task tool output above and continue with your task.",
431
- synthetic: true,
432
- } satisfies SessionV1.TextPart)
433
- })
434
-
435
- const shellImpl = Effect.fn("SessionPrompt.shellImpl")(function* (input: ShellInput, ready?: Latch.Latch) {
436
- return yield* Effect.uninterruptibleMask((restore) =>
437
- Effect.gen(function* () {
438
- const markReady = ready ? ready.open.pipe(Effect.asVoid) : Effect.void
439
- const { msg, part, cwd } = yield* Effect.gen(function* () {
440
- const ctx = yield* InstanceState.context
441
- const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
442
- if (session.revert) {
443
- yield* revert.cleanup(session)
444
- }
445
- const agent = yield* agents.get(input.agent)
446
- if (!agent) {
447
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
448
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
449
- const error = new NamedError.Unknown({ message: `Agent not found: "${input.agent}".${hint}` })
450
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
451
- throw error
452
- }
453
- const model = input.model ?? agent.model ?? (yield* currentModel(input.sessionID))
454
- const userMsg: SessionV1.User = {
455
- id: input.messageID ?? MessageID.ascending(),
456
- sessionID: input.sessionID,
457
- time: { created: Date.now() },
458
- role: "user",
459
- agent: input.agent,
460
- model: { providerID: model.providerID, modelID: model.modelID },
461
- }
462
- yield* sessions.updateMessage(userMsg)
463
- const userPart: SessionV1.Part = {
464
- type: "text",
465
- id: PartID.ascending(),
466
- messageID: userMsg.id,
467
- sessionID: input.sessionID,
468
- text: "The following tool was executed by the user",
469
- synthetic: true,
470
- }
471
- yield* sessions.updatePart(userPart)
472
-
473
- const msg: SessionV1.Assistant = {
474
- id: MessageID.ascending(),
475
- sessionID: input.sessionID,
476
- parentID: userMsg.id,
477
- mode: input.agent,
478
- agent: input.agent,
479
- cost: 0,
480
- path: { cwd: ctx.directory, root: ctx.worktree },
481
- time: { created: Date.now() },
482
- role: "assistant",
483
- tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
484
- modelID: model.modelID,
485
- providerID: model.providerID,
486
- }
487
- yield* sessions.updateMessage(msg)
488
- const started = Date.now()
489
- const part: SessionV1.ToolPart = {
490
- type: "tool",
491
- id: PartID.ascending(),
492
- messageID: msg.id,
493
- sessionID: input.sessionID,
494
- tool: ShellID.ToolID,
495
- callID: ulid(),
496
- state: {
497
- status: "running",
498
- time: { start: started },
499
- input: { command: input.command },
500
- },
501
- }
502
- yield* sessions.updatePart(part)
503
- if (flags.experimentalEventSystem) {
504
- yield* events.publish(SessionEvent.Shell.Started, {
505
- sessionID: input.sessionID,
506
- messageID: SessionMessage.ID.create(),
507
- timestamp: DateTime.makeUnsafe(started),
508
- callID: part.callID,
509
- command: input.command,
510
- })
511
- }
512
- return { msg, part, cwd: ctx.directory }
513
- }).pipe(Effect.ensuring(markReady))
514
-
515
- const cfg = yield* config.get()
516
- const sh = Shell.preferred(cfg.shell)
517
- const args = Shell.args(sh, input.command, cwd)
518
- let output = ""
519
- let aborted = false
520
-
521
- const finish = Effect.uninterruptible(
522
- Effect.gen(function* () {
523
- if (aborted) {
524
- output += "\n\n" + ["<metadata>", "User aborted the command", "</metadata>"].join("\n")
525
- }
526
- const completed = Date.now()
527
- if (flags.experimentalEventSystem) {
528
- yield* events.publish(SessionEvent.Shell.Ended, {
529
- sessionID: input.sessionID,
530
- timestamp: DateTime.makeUnsafe(completed),
531
- callID: part.callID,
532
- output,
533
- })
534
- }
535
- if (!msg.time.completed) {
536
- msg.time.completed = completed
537
- yield* sessions.updateMessage(msg)
538
- }
539
- if (part.state.status === "running") {
540
- part.state = {
541
- status: "completed",
542
- time: { ...part.state.time, end: completed },
543
- input: part.state.input,
544
- title: "",
545
- metadata: { output, description: "" },
546
- output,
547
- }
548
- yield* sessions.updatePart(part)
549
- }
550
- }),
551
- )
552
-
553
- const exit = yield* restore(
554
- Effect.gen(function* () {
555
- const shellEnv = yield* plugin.trigger(
556
- "shell.env",
557
- { cwd, sessionID: input.sessionID, callID: part.callID },
558
- { env: {} },
559
- )
560
- const cmd = ChildProcess.make(sh, args, {
561
- cwd,
562
- extendEnv: true,
563
- env: { ...shellEnv.env, TERM: "dumb" },
564
- stdin: "ignore",
565
- forceKillAfter: "3 seconds",
566
- })
567
- const handle = yield* spawner.spawn(cmd)
568
- yield* Stream.runForEach(Stream.decodeText(handle.all), (chunk) =>
569
- Effect.gen(function* () {
570
- output += chunk
571
- if (part.state.status === "running") {
572
- part.state.metadata = { output, description: "" }
573
- yield* sessions.updatePart(part)
574
- }
575
- }),
576
- )
577
- yield* handle.exitCode
578
- }).pipe(Effect.scoped, Effect.orDie),
579
- ).pipe(Effect.exit)
580
-
581
- if (Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause) && !Cause.hasDies(exit.cause)) {
582
- aborted = true
583
- }
584
- yield* finish
585
-
586
- if (Exit.isFailure(exit) && !aborted && !Cause.hasInterruptsOnly(exit.cause)) {
587
- return yield* Effect.failCause(exit.cause)
588
- }
589
-
590
- return { info: msg, parts: [part] }
591
- }),
592
- )
593
- })
594
-
595
- const getModel = Effect.fn("SessionPrompt.getModel")(function* (
596
- providerID: ProviderV2.ID,
597
- modelID: ModelV2.ID,
598
- sessionID: SessionID,
599
- ) {
600
- const exit = yield* provider.getModel(providerID, modelID).pipe(Effect.exit)
601
- if (Exit.isSuccess(exit)) return exit.value
602
- const err = Cause.squash(exit.cause)
603
- if (Provider.ModelNotFoundError.isInstance(err)) {
604
- const hint = err.suggestions?.length ? ` Did you mean: ${err.suggestions.join(", ")}?` : ""
605
- yield* events.publish(Session.Event.Error, {
606
- sessionID,
607
- error: new NamedError.Unknown({
608
- message: `Model not found: ${err.providerID}/${err.modelID}.${hint}`,
609
- }).toObject(),
610
- })
611
- }
612
- return yield* Effect.die(err)
613
- })
614
-
615
- const currentModel = Effect.fnUntraced(function* (sessionID: SessionID) {
616
- const current = yield* db
617
- .select({ model: SessionTable.model })
618
- .from(SessionTable)
619
- .where(eq(SessionTable.id, sessionID))
620
- .get()
621
- .pipe(Effect.orDie)
622
- if (current?.model) {
623
- return {
624
- providerID: ProviderV2.ID.make(current.model.providerID),
625
- modelID: ModelV2.ID.make(current.model.id),
626
- ...(current.model.variant && current.model.variant !== "default" ? { variant: current.model.variant } : {}),
627
- }
628
- }
629
- const match = yield* sessions
630
- .findMessage(sessionID, (m) => m.info.role === "user" && !!m.info.model)
631
- .pipe(Effect.orDie)
632
- if (Option.isSome(match) && match.value.info.role === "user") return match.value.info.model
633
- return yield* provider.defaultModel().pipe(Effect.orDie)
634
- })
635
-
636
- const createUserMessage = Effect.fn("SessionPrompt.createUserMessage")(function* (input: PromptInput) {
637
- const agentName = input.agent
638
- const ag = agentName ? yield* agents.get(agentName) : yield* agents.defaultInfo()
639
- if (!ag) {
640
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
641
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
642
- const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
643
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
644
- throw error
645
- }
646
-
647
- const current = yield* db
648
- .select({ agent: SessionTable.agent, model: SessionTable.model })
649
- .from(SessionTable)
650
- .where(eq(SessionTable.id, input.sessionID))
651
- .get()
652
- .pipe(Effect.orDie)
653
- const model = input.model ?? ag.model ?? (yield* currentModel(input.sessionID))
654
- const same = ag.model && model.providerID === ag.model.providerID && model.modelID === ag.model.modelID
655
- const full =
656
- !input.variant && ag.variant && same
657
- ? yield* provider
658
- .getModel(model.providerID, model.modelID)
659
- .pipe(Effect.catchIf(Provider.ModelNotFoundError.isInstance, () => Effect.succeed(undefined)))
660
- : undefined
661
- const variant = input.variant ?? (ag.variant && full?.variants?.[ag.variant] ? ag.variant : undefined)
662
-
663
- const info: SessionV1.User = {
664
- id: input.messageID ?? MessageID.ascending(),
665
- role: "user",
666
- sessionID: input.sessionID,
667
- time: { created: Date.now() },
668
- tools: input.tools,
669
- agent: ag.name,
670
- model: {
671
- providerID: model.providerID,
672
- modelID: model.modelID,
673
- variant,
674
- },
675
- system: input.system,
676
- format: input.format,
677
- }
678
-
679
- if (current?.agent !== info.agent) {
680
- yield* events.publish(SessionEvent.AgentSwitched, {
681
- sessionID: input.sessionID,
682
- messageID: SessionMessage.ID.create(),
683
- timestamp: DateTime.makeUnsafe(info.time.created),
684
- agent: info.agent,
685
- })
686
- }
687
- if (
688
- current?.model?.providerID !== info.model.providerID ||
689
- current.model.id !== info.model.modelID ||
690
- (current.model.variant === "default" ? undefined : current.model.variant) !== info.model.variant
691
- ) {
692
- yield* events.publish(SessionEvent.ModelSwitched, {
693
- sessionID: input.sessionID,
694
- messageID: SessionMessage.ID.create(),
695
- timestamp: DateTime.makeUnsafe(info.time.created),
696
- model: {
697
- id: ModelV2.ID.make(info.model.modelID),
698
- providerID: ProviderV2.ID.make(info.model.providerID),
699
- variant: ModelV2.VariantID.make(info.model.variant ?? "default"),
700
- },
701
- })
702
- }
703
-
704
- yield* Effect.addFinalizer(() => instruction.clear(info.id))
705
-
706
- type Draft<T> = T extends SessionV1.Part ? Omit<T, "id"> & { id?: string } : never
707
- const assign = (part: Draft<SessionV1.Part>): SessionV1.Part => ({
708
- ...part,
709
- id: part.id ? PartID.make(part.id) : PartID.ascending(),
710
- })
711
-
712
- const resolvePart: (part: PromptInput["parts"][number]) => Effect.Effect<Draft<SessionV1.Part>[]> = Effect.fn(
713
- "SessionPrompt.resolveUserPart",
714
- )(function* (part) {
715
- if (part.type === "file") {
716
- if (part.source?.type === "resource") {
717
- const { clientName, uri } = part.source
718
- yield* Effect.logInfo("mcp resource", { clientName, uri, mime: part.mime })
719
- const pieces: Draft<SessionV1.Part>[] = [
720
- {
721
- messageID: info.id,
722
- sessionID: input.sessionID,
723
- type: "text",
724
- synthetic: true,
725
- text: `Reading MCP resource: ${part.filename} (${uri})`,
726
- },
727
- ]
728
- const exit = yield* mcp.readResource(clientName, uri).pipe(Effect.exit)
729
- if (Exit.isSuccess(exit)) {
730
- const content = exit.value
731
- if (!content) throw new Error(`Resource not found: ${clientName}/${uri}`)
732
- const items = Array.isArray(content.contents) ? content.contents : [content.contents]
733
- for (const c of items) {
734
- if ("text" in c && c.text) {
735
- pieces.push({
736
- messageID: info.id,
737
- sessionID: input.sessionID,
738
- type: "text",
739
- synthetic: true,
740
- text: c.text,
741
- })
742
- } else if ("blob" in c && c.blob) {
743
- const mime = "mimeType" in c ? c.mimeType : part.mime
744
- pieces.push({
745
- messageID: info.id,
746
- sessionID: input.sessionID,
747
- type: "text",
748
- synthetic: true,
749
- text: `[Binary content: ${mime}]`,
750
- })
751
- }
752
- }
753
- pieces.push({ ...part, messageID: info.id, sessionID: input.sessionID })
754
- } else {
755
- const error = Cause.squash(exit.cause)
756
- yield* Effect.logError("failed to read MCP resource", { error, clientName, uri })
757
- const message = error instanceof Error ? error.message : String(error)
758
- pieces.push({
759
- messageID: info.id,
760
- sessionID: input.sessionID,
761
- type: "text",
762
- synthetic: true,
763
- text: `Failed to read MCP resource ${part.filename}: ${message}`,
764
- })
765
- }
766
- return pieces
767
- }
768
- const url = new URL(part.url)
769
- switch (url.protocol) {
770
- case "data:":
771
- if (part.mime === "text/plain") {
772
- return [
773
- {
774
- messageID: info.id,
775
- sessionID: input.sessionID,
776
- type: "text",
777
- synthetic: true,
778
- text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
779
- },
780
- {
781
- messageID: info.id,
782
- sessionID: input.sessionID,
783
- type: "text",
784
- synthetic: true,
785
- text: decodeDataUrl(part.url),
786
- },
787
- { ...part, messageID: info.id, sessionID: input.sessionID },
788
- ]
789
- }
790
- break
791
- case "file:": {
792
- yield* Effect.logInfo("file", { mime: part.mime })
793
- const filepath = fileURLToPath(part.url)
794
- const mime = (yield* fsys.isDir(filepath)) ? "application/x-directory" : part.mime
795
-
796
- const { read } = yield* registry.named()
797
- const execRead = (args: Parameters<typeof read.execute>[0], extra?: Tool.Context["extra"]) => {
798
- const controller = new AbortController()
799
- return read
800
- .execute(args, {
801
- sessionID: input.sessionID,
802
- abort: controller.signal,
803
- agent: input.agent!,
804
- messageID: info.id,
805
- extra: { bypassCwdCheck: true, ...extra },
806
- messages: [],
807
- metadata: () => Effect.void,
808
- ask: () => Effect.void,
809
- })
810
- .pipe(Effect.onInterrupt(() => Effect.sync(() => controller.abort())))
811
- }
812
-
813
- if (mime === "text/plain") {
814
- let offset: number | undefined
815
- let limit: number | undefined
816
- const range = { start: url.searchParams.get("start"), end: url.searchParams.get("end") }
817
- if (range.start != null) {
818
- const filePathURI = part.url.split("?")[0]
819
- let start = parseInt(range.start)
820
- let end = range.end ? parseInt(range.end) : undefined
821
- if (start === end) {
822
- const symbols = yield* lsp.documentSymbol(filePathURI).pipe(Effect.catch(() => Effect.succeed([])))
823
- for (const symbol of symbols) {
824
- let r: LSP.Range | undefined
825
- if ("range" in symbol) r = symbol.range
826
- else if ("location" in symbol) r = symbol.location.range
827
- if (r?.start?.line && r?.start?.line === start) {
828
- start = r.start.line
829
- end = r?.end?.line ?? start
830
- break
831
- }
832
- }
833
- }
834
- offset = Math.max(start, 1)
835
- if (end) limit = end - (offset - 1)
836
- }
837
- const args = { filePath: filepath, offset, limit }
838
- const pieces: Draft<SessionV1.Part>[] = [
839
- {
840
- messageID: info.id,
841
- sessionID: input.sessionID,
842
- type: "text",
843
- synthetic: true,
844
- text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
845
- },
846
- ]
847
- const exit = yield* provider.getModel(info.model.providerID, info.model.modelID).pipe(
848
- Effect.flatMap((mdl) => execRead(args, { model: mdl })),
849
- Effect.exit,
850
- )
851
- if (Exit.isSuccess(exit)) {
852
- const result = exit.value
853
- pieces.push({
854
- messageID: info.id,
855
- sessionID: input.sessionID,
856
- type: "text",
857
- synthetic: true,
858
- text: result.output,
859
- })
860
- if (result.attachments?.length) {
861
- pieces.push(
862
- ...result.attachments.map((a) => ({
863
- ...a,
864
- synthetic: true,
865
- filename: a.filename ?? part.filename,
866
- messageID: info.id,
867
- sessionID: input.sessionID,
868
- })),
869
- )
870
- } else {
871
- pieces.push({ ...part, mime, messageID: info.id, sessionID: input.sessionID })
872
- }
873
- } else {
874
- const error = Cause.squash(exit.cause)
875
- yield* Effect.logError("failed to read file", { error, filepath })
876
- const message = error instanceof Error ? error.message : String(error)
877
- yield* events.publish(Session.Event.Error, {
878
- sessionID: input.sessionID,
879
- error: new NamedError.Unknown({ message }).toObject(),
880
- })
881
- pieces.push({
882
- messageID: info.id,
883
- sessionID: input.sessionID,
884
- type: "text",
885
- synthetic: true,
886
- text: `Read tool failed to read ${filepath} with the following error: ${message}`,
887
- })
888
- }
889
- return pieces
890
- }
891
-
892
- if (mime === "application/x-directory") {
893
- const args = { filePath: filepath }
894
- const exit = yield* execRead(args).pipe(Effect.exit)
895
- if (Exit.isFailure(exit)) {
896
- const error = Cause.squash(exit.cause)
897
- yield* Effect.logError("failed to read directory", { error, filepath })
898
- const message = error instanceof Error ? error.message : String(error)
899
- yield* events.publish(Session.Event.Error, {
900
- sessionID: input.sessionID,
901
- error: new NamedError.Unknown({ message }).toObject(),
902
- })
903
- return [
904
- {
905
- messageID: info.id,
906
- sessionID: input.sessionID,
907
- type: "text",
908
- synthetic: true,
909
- text: `Read tool failed to read ${filepath} with the following error: ${message}`,
910
- },
911
- ]
912
- }
913
- return [
914
- {
915
- messageID: info.id,
916
- sessionID: input.sessionID,
917
- type: "text",
918
- synthetic: true,
919
- text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
920
- },
921
- {
922
- messageID: info.id,
923
- sessionID: input.sessionID,
924
- type: "text",
925
- synthetic: true,
926
- text: exit.value.output,
927
- },
928
- { ...part, mime, messageID: info.id, sessionID: input.sessionID },
929
- ]
930
- }
931
-
932
- return [
933
- {
934
- messageID: info.id,
935
- sessionID: input.sessionID,
936
- type: "text",
937
- synthetic: true,
938
- text: `Called the Read tool with the following input: {"filePath":"${filepath}"}`,
939
- },
940
- {
941
- id: part.id,
942
- messageID: info.id,
943
- sessionID: input.sessionID,
944
- type: "file",
945
- url:
946
- `data:${mime};base64,` +
947
- Buffer.from(yield* fsys.readFile(filepath).pipe(Effect.catch(Effect.die))).toString("base64"),
948
- mime,
949
- filename: part.filename!,
950
- source: part.source,
951
- },
952
- ]
953
- }
954
- }
955
- }
956
-
957
- if (part.type === "agent") {
958
- const perm = Permission.evaluate("task", part.name, ag.permission)
959
- const hint = perm.action === "deny" ? " . Invoked by user; guaranteed to exist." : ""
960
- return [
961
- { ...part, messageID: info.id, sessionID: input.sessionID },
962
- {
963
- messageID: info.id,
964
- sessionID: input.sessionID,
965
- type: "text",
966
- synthetic: true,
967
- text:
968
- " Use the above message and context to generate a prompt and call the task tool with subagent: " +
969
- part.name +
970
- hint,
971
- },
972
- ]
973
- }
974
-
975
- return [{ ...part, messageID: info.id, sessionID: input.sessionID }]
976
- })
977
-
978
- const resolvedParts = yield* Effect.forEach(input.parts, resolvePart, { concurrency: "unbounded" }).pipe(
979
- Effect.map((x) => x.flat().map(assign)),
980
- )
981
-
982
- yield* plugin.trigger(
983
- "chat.message",
984
- {
985
- sessionID: input.sessionID,
986
- agent: input.agent,
987
- model: input.model,
988
- messageID: input.messageID,
989
- variant: input.variant,
990
- },
991
- { message: info, parts: resolvedParts },
992
- )
993
-
994
- const parts = yield* Effect.forEach(resolvedParts, (part) =>
995
- part.type === "file" && part.mime.startsWith("image/")
996
- ? image.normalize(part).pipe(
997
- Effect.catchIf(
998
- (error) => error instanceof Image.ResizerUnavailableError,
999
- () => Effect.succeed(part),
1000
- ),
1001
- )
1002
- : Effect.succeed(part),
1003
- )
1004
-
1005
- const parsed = decodeMessageInfo(info, { errors: "all", propertyOrder: "original" })
1006
- if (Exit.isFailure(parsed)) {
1007
- yield* Effect.logError("invalid user message before save", {
1008
- sessionID: input.sessionID,
1009
- messageID: info.id,
1010
- agent: info.agent,
1011
- model: info.model,
1012
- cause: Cause.pretty(parsed.cause),
1013
- })
1014
- }
1015
- for (const [index, part] of parts.entries()) {
1016
- const p = decodeMessagePart(part, { errors: "all", propertyOrder: "original" })
1017
- if (Exit.isSuccess(p)) continue
1018
- yield* Effect.logError("invalid user part before save", {
1019
- sessionID: input.sessionID,
1020
- messageID: info.id,
1021
- partID: part.id,
1022
- partType: part.type,
1023
- index,
1024
- cause: Cause.pretty(p.cause),
1025
- part,
1026
- })
1027
- }
1028
-
1029
- yield* sessions.updateMessage(info)
1030
- for (const part of parts) yield* sessions.updatePart(part)
1031
- const nextPrompt = parts.reduce(
1032
- (result, part) => {
1033
- if (part.type === "text") {
1034
- if (part.synthetic) result.synthetic.push(part.text)
1035
- else result.text.push(part.text)
1036
- }
1037
- if (part.type === "file") {
1038
- result.files.push(
1039
- new FileAttachment({
1040
- uri: part.url,
1041
- mime: part.mime,
1042
- name: part.filename,
1043
- source: part.source
1044
- ? new Source({
1045
- start: part.source.text.start,
1046
- end: part.source.text.end,
1047
- text: part.source.text.value,
1048
- })
1049
- : undefined,
1050
- }),
1051
- )
1052
- }
1053
- if (part.type === "agent") {
1054
- result.agents.push(
1055
- new AgentAttachment({
1056
- name: part.name,
1057
- source: part.source
1058
- ? new Source({
1059
- start: part.source.start,
1060
- end: part.source.end,
1061
- text: part.source.value,
1062
- })
1063
- : undefined,
1064
- }),
1065
- )
1066
- }
1067
- return result
1068
- },
1069
- {
1070
- text: [] as string[],
1071
- files: [] as FileAttachment[],
1072
- agents: [] as AgentAttachment[],
1073
- synthetic: [] as string[],
1074
- },
1075
- )
1076
- // TODO(v2): Temporary dual-write while migrating session messages to v2 events.
1077
- if (flags.experimentalEventSystem) {
1078
- yield* events.publish(SessionEvent.Prompted, {
1079
- sessionID: input.sessionID,
1080
- messageID: SessionMessage.ID.create(),
1081
- timestamp: DateTime.makeUnsafe(info.time.created),
1082
- delivery: "steer",
1083
- prompt: new Prompt({
1084
- text: nextPrompt.text.join("\n"),
1085
- files: nextPrompt.files,
1086
- agents: nextPrompt.agents,
1087
- }),
1088
- })
1089
- }
1090
- for (const text of nextPrompt.synthetic) {
1091
- // TODO(v2): Temporary dual-write while migrating session messages to v2 events.
1092
- if (flags.experimentalEventSystem) {
1093
- yield* events.publish(SessionEvent.Synthetic, {
1094
- sessionID: input.sessionID,
1095
- messageID: SessionMessage.ID.create(),
1096
- timestamp: DateTime.makeUnsafe(info.time.created),
1097
- text,
1098
- })
1099
- }
1100
- }
1101
-
1102
- return { info, parts }
1103
- }, Effect.scoped)
1104
-
1105
- const prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error> = Effect.fn(
1106
- "SessionPrompt.prompt",
1107
- )(function* (input: PromptInput) {
1108
- const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
1109
- yield* revert.cleanup(session)
1110
- const message = yield* createUserMessage(input)
1111
- yield* sessions.touch(input.sessionID)
1112
-
1113
- const permissions: PermissionV1.Rule[] = []
1114
- for (const [t, enabled] of Object.entries(input.tools ?? {})) {
1115
- permissions.push({ permission: t, action: enabled ? "allow" : "deny", pattern: "*" })
1116
- }
1117
- if (permissions.length > 0) {
1118
- session.permission = permissions
1119
- yield* sessions.setPermission({ sessionID: session.id, permission: permissions })
1120
- }
1121
-
1122
- if (input.noReply === true) return message
1123
- return yield* loop({ sessionID: input.sessionID })
1124
- })
1125
-
1126
- const lastAssistant = Effect.fnUntraced(function* (sessionID: SessionID) {
1127
- const match = yield* sessions.findMessage(sessionID, (m) => m.info.role !== "user").pipe(Effect.orDie)
1128
- if (Option.isSome(match)) return match.value
1129
- const msgs = yield* sessions.messages({ sessionID, limit: 1 }).pipe(Effect.orDie)
1130
- if (msgs.length > 0) return msgs[0]
1131
- throw new Error("Impossible")
1132
- })
1133
-
1134
- const runLoop: (sessionID: SessionID) => Effect.Effect<SessionV1.WithParts> = Effect.fn("SessionPrompt.run")(
1135
- function* (sessionID: SessionID) {
1136
- const ctx = yield* InstanceState.context
1137
- let structured: unknown
1138
- let step = 0
1139
- const session = yield* sessions.get(sessionID).pipe(Effect.orDie)
1140
-
1141
- while (true) {
1142
- yield* status.set(sessionID, { type: "busy" })
1143
- yield* Effect.logInfo("loop", { "session.id": sessionID, step })
1144
-
1145
- let msgs = yield* MessageV2.filterCompactedEffect(sessionID).pipe(
1146
- Effect.provideService(Database.Service, database),
1147
- )
1148
-
1149
- const { user: lastUser, assistant: lastAssistant, finished: lastFinished, tasks } = MessageV2.latest(msgs)
1150
-
1151
- if (!lastUser) throw new Error("No user message found in stream. This should never happen.")
1152
-
1153
- const lastAssistantMsg = msgs.findLast(
1154
- (msg) => msg.info.role === "assistant" && msg.info.id === lastAssistant?.id,
1155
- )
1156
- // Some providers return "stop" even when the assistant message contains
1157
- // tool calls. Keep the loop running so tool results can be sent back to
1158
- // the model, but ignore cleanup-marked interrupted orphans.
1159
- const hasToolCalls =
1160
- lastAssistantMsg?.parts.some(
1161
- (part) => part.type === "tool" && !part.metadata?.providerExecuted && !isOrphanedInterruptedTool(part),
1162
- ) ?? false
1163
-
1164
- if (
1165
- lastAssistant?.finish &&
1166
- !["tool-calls"].includes(lastAssistant.finish) &&
1167
- !hasToolCalls &&
1168
- lastUser.id < lastAssistant.id
1169
- ) {
1170
- const orphan = lastAssistantMsg?.parts.find(
1171
- (part): part is SessionV1.ToolPart => part.type === "tool" && isOrphanedInterruptedTool(part),
1172
- )
1173
- if (orphan) {
1174
- yield* Effect.logWarning("loop exit with orphaned interrupted tool", {
1175
- "session.id": sessionID,
1176
- messageID: lastAssistant.id,
1177
- tool: orphan.tool,
1178
- callID: orphan.callID,
1179
- })
1180
- }
1181
- yield* Effect.logInfo("exiting loop", { "session.id": sessionID })
1182
- break
1183
- }
1184
-
1185
- step++
1186
- if (step === 1)
1187
- yield* title({
1188
- session,
1189
- modelID: lastUser.model.modelID,
1190
- providerID: lastUser.model.providerID,
1191
- history: msgs,
1192
- }).pipe(Effect.ignore, Effect.forkIn(scope))
1193
-
1194
- const model = yield* getModel(lastUser.model.providerID, lastUser.model.modelID, sessionID)
1195
- const task = tasks.pop()
1196
-
1197
- if (task?.type === "subtask") {
1198
- yield* handleSubtask({ task, model, lastUser, sessionID, session, msgs })
1199
- continue
1200
- }
1201
-
1202
- if (task?.type === "compaction") {
1203
- const result = yield* compaction.process({
1204
- messages: msgs,
1205
- parentID: lastUser.id,
1206
- sessionID,
1207
- auto: task.auto,
1208
- overflow: task.overflow,
1209
- })
1210
- if (result === "stop") break
1211
- continue
1212
- }
1213
-
1214
- if (
1215
- lastFinished &&
1216
- lastFinished.summary !== true &&
1217
- (yield* compaction.isOverflow({ tokens: lastFinished.tokens, model }))
1218
- ) {
1219
- yield* compaction.create({ sessionID, agent: lastUser.agent, model: lastUser.model, auto: true })
1220
- continue
1221
- }
1222
-
1223
- const agent = yield* agents.get(lastUser.agent)
1224
- if (!agent) {
1225
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
1226
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
1227
- const error = new NamedError.Unknown({ message: `Agent not found: "${lastUser.agent}".${hint}` })
1228
- yield* events.publish(Session.Event.Error, { sessionID, error: error.toObject() })
1229
- throw error
1230
- }
1231
- const maxSteps = agent.steps ?? Infinity
1232
- const isLastStep = step >= maxSteps
1233
- msgs = yield* SessionReminders.apply({ messages: msgs, agent, session }).pipe(
1234
- Effect.provideService(RuntimeFlags.Service, flags),
1235
- Effect.provideService(FSUtil.Service, fsys),
1236
- Effect.provideService(Session.Service, sessions),
1237
- )
1238
-
1239
- const msg: SessionV1.Assistant = {
1240
- id: MessageID.ascending(),
1241
- parentID: lastUser.id,
1242
- role: "assistant",
1243
- mode: agent.name,
1244
- agent: agent.name,
1245
- variant: lastUser.model.variant,
1246
- path: { cwd: ctx.directory, root: ctx.worktree },
1247
- cost: 0,
1248
- tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1249
- modelID: model.id,
1250
- providerID: model.providerID,
1251
- time: { created: Date.now() },
1252
- sessionID,
1253
- }
1254
- yield* sessions.updateMessage(msg)
1255
-
1256
- const finalizeInterruptedAssistant = Effect.gen(function* () {
1257
- if (msg.time.completed) return
1258
- msg.error ??= MessageV2.fromError(new DOMException("Aborted", "AbortError"), {
1259
- providerID: msg.providerID,
1260
- aborted: true,
1261
- })
1262
- msg.time.completed = Date.now()
1263
- yield* sessions.updateMessage(msg)
1264
- })
1265
-
1266
- const handle = yield* processor
1267
- .create({
1268
- assistantMessage: msg,
1269
- sessionID,
1270
- model,
1271
- })
1272
- .pipe(Effect.onInterrupt(() => finalizeInterruptedAssistant))
1273
-
1274
- const outcome: "break" | "continue" = yield* Effect.gen(function* () {
1275
- const lastUserMsg = msgs.findLast((m) => m.info.role === "user")
1276
- const bypassAgentCheck = lastUserMsg?.parts.some((p) => p.type === "agent") ?? false
1277
- const promptOps = yield* ops()
1278
-
1279
- const tools = yield* SessionTools.resolve({
1280
- agent,
1281
- session,
1282
- model,
1283
- processor: handle,
1284
- bypassAgentCheck,
1285
- messages: msgs,
1286
- promptOps,
1287
- }).pipe(
1288
- Effect.provideService(Plugin.Service, plugin),
1289
- Effect.provideService(Permission.Service, permission),
1290
- Effect.provideService(ToolRegistry.Service, registry),
1291
- Effect.provideService(MCP.Service, mcp),
1292
- Effect.provideService(Truncate.Service, truncate),
1293
- )
1294
-
1295
- if (lastUser.format?.type === "json_schema") {
1296
- tools["StructuredOutput"] = createStructuredOutputTool({
1297
- schema: lastUser.format.schema,
1298
- onSuccess(output) {
1299
- structured = output
1300
- },
1301
- })
1302
- }
1303
-
1304
- if (step === 1)
1305
- yield* summary.summarize({ sessionID, messageID: lastUser.id }).pipe(Effect.ignore, Effect.forkIn(scope))
1306
-
1307
- yield* plugin.trigger("experimental.chat.messages.transform", {}, { messages: msgs })
1308
-
1309
- const [skills, env, instructions, modelMsgs] = yield* Effect.all([
1310
- sys.skills(agent),
1311
- sys.environment(model),
1312
- instruction.system().pipe(Effect.orDie),
1313
- MessageV2.toModelMessagesEffect(msgs, model),
1314
- ])
1315
- const system = [...env, ...instructions, ...(skills ? [skills] : [])]
1316
- const format = lastUser.format ?? { type: "text" as const }
1317
- if (format.type === "json_schema") system.push(STRUCTURED_OUTPUT_SYSTEM_PROMPT)
1318
- const result = yield* handle.process({
1319
- user: lastUser,
1320
- agent,
1321
- permission: session.permission,
1322
- sessionID,
1323
- parentSessionID: session.parentID,
1324
- system,
1325
- messages: [
1326
- ...modelMsgs,
1327
- ...(isLastStep ? [{ role: "assistant" as const, content: MAX_STEPS_PROMPT }] : []),
1328
- ],
1329
- tools,
1330
- model,
1331
- toolChoice: format.type === "json_schema" ? "required" : undefined,
1332
- })
1333
-
1334
- if (structured !== undefined) {
1335
- handle.message.structured = structured
1336
- handle.message.finish = handle.message.finish ?? "stop"
1337
- yield* sessions.updateMessage(handle.message)
1338
- return "break" as const
1339
- }
1340
-
1341
- const finished = handle.message.finish && !["tool-calls", "unknown"].includes(handle.message.finish)
1342
- if (finished && !handle.message.error) {
1343
- // Surface any content-filter finish (e.g. Anthropic stop_reason:
1344
- // refusal) as an error. These turns may have produced no visible
1345
- // output at all — previously the session went idle silently — or
1346
- // partial text that was cut off by the provider's filter.
1347
- if (handle.message.finish === "content-filter") {
1348
- handle.message.error = new SessionV1.ContentFilterError({
1349
- message: "The response was blocked by the provider's content filter",
1350
- }).toObject()
1351
- yield* sessions.updateMessage(handle.message)
1352
- yield* events.publish(Session.Event.Error, { sessionID, error: handle.message.error })
1353
- return "break" as const
1354
- }
1355
- if (format.type === "json_schema") {
1356
- handle.message.error = new SessionV1.StructuredOutputError({
1357
- message: "Model did not produce structured output",
1358
- retries: 0,
1359
- }).toObject()
1360
- yield* sessions.updateMessage(handle.message)
1361
- return "break" as const
1362
- }
1363
- }
1364
-
1365
- if (result === "stop") return "break" as const
1366
- if (result === "compact") {
1367
- yield* compaction.create({
1368
- sessionID,
1369
- agent: lastUser.agent,
1370
- model: lastUser.model,
1371
- auto: true,
1372
- overflow: !handle.message.finish,
1373
- })
1374
- }
1375
- return "continue" as const
1376
- }).pipe(
1377
- Effect.ensuring(instruction.clear(handle.message.id)),
1378
- Effect.onInterrupt(() => finalizeInterruptedAssistant),
1379
- )
1380
- if (outcome === "break") break
1381
- continue
1382
- }
1383
-
1384
- yield* compaction.prune({ sessionID }).pipe(Effect.ignore, Effect.forkIn(scope))
1385
- return yield* lastAssistant(sessionID)
1386
- },
1387
- )
1388
-
1389
- const loop: (input: LoopInput) => Effect.Effect<SessionV1.WithParts> = Effect.fn("SessionPrompt.loop")(function* (
1390
- input: LoopInput,
1391
- ) {
1392
- return yield* state.ensureRunning(input.sessionID, lastAssistant(input.sessionID), runLoop(input.sessionID))
1393
- })
1394
-
1395
- const shell: (input: ShellInput) => Effect.Effect<SessionV1.WithParts, Session.BusyError> = Effect.fn(
1396
- "SessionPrompt.shell",
1397
- )(function* (input: ShellInput) {
1398
- const ready = yield* Latch.make()
1399
- return yield* state.startShell(input.sessionID, lastAssistant(input.sessionID), shellImpl(input, ready), ready)
1400
- })
1401
-
1402
- const command = Effect.fn("SessionPrompt.command")(function* (input: CommandInput) {
1403
- yield* Effect.logInfo("command", {
1404
- "session.id": input.sessionID,
1405
- command: input.command,
1406
- agent: input.agent,
1407
- })
1408
- const cmd = yield* commands.get(input.command)
1409
- if (!cmd) {
1410
- const available = (yield* commands.list()).map((c) => c.name)
1411
- const hint = available.length ? ` Available commands: ${available.join(", ")}` : ""
1412
- const error = new NamedError.Unknown({ message: `Command not found: "${input.command}".${hint}` })
1413
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
1414
- throw error
1415
- }
1416
- const agentName = cmd.agent ?? input.agent
1417
-
1418
- const raw = input.arguments.match(argsRegex) ?? []
1419
- const args = raw.map((arg) => arg.replace(quoteTrimRegex, ""))
1420
- const templateCommand = yield* Effect.promise(async () => cmd.template)
1421
-
1422
- const placeholders = templateCommand.match(placeholderRegex) ?? []
1423
- let last = 0
1424
- for (const item of placeholders) {
1425
- const value = Number(item.slice(1))
1426
- if (value > last) last = value
1427
- }
1428
-
1429
- const withArgs = templateCommand.replaceAll(placeholderRegex, (_, index) => {
1430
- const position = Number(index)
1431
- const argIndex = position - 1
1432
- if (argIndex >= args.length) return ""
1433
- if (position === last) return args.slice(argIndex).join(" ")
1434
- return args[argIndex]
1435
- })
1436
- const usesArgumentsPlaceholder = templateCommand.includes("$ARGUMENTS")
1437
- let template = withArgs.replaceAll("$ARGUMENTS", input.arguments)
1438
-
1439
- if (placeholders.length === 0 && !usesArgumentsPlaceholder && input.arguments.trim()) {
1440
- template = template + "\n\n" + input.arguments
1441
- }
1442
-
1443
- const shellMatches = ConfigMarkdown.shell(template)
1444
- if (shellMatches.length > 0) {
1445
- const cfg = yield* config.get()
1446
- const sh = Shell.preferred(cfg.shell)
1447
- const results = yield* Effect.promise(() =>
1448
- Promise.all(
1449
- shellMatches.map(async ([, cmd]) => (await Process.text([cmd], { shell: sh, nothrow: true })).text),
1450
- ),
1451
- )
1452
- let index = 0
1453
- template = template.replace(bashRegex, () => results[index++])
1454
- }
1455
- template = template.trim()
1456
-
1457
- const taskModel = yield* Effect.gen(function* () {
1458
- if (cmd.model) return Provider.parseModel(cmd.model)
1459
- if (cmd.agent) {
1460
- const cmdAgent = yield* agents.get(cmd.agent)
1461
- if (cmdAgent?.model) return cmdAgent.model
1462
- }
1463
- if (input.model) return Provider.parseModel(input.model)
1464
- return yield* currentModel(input.sessionID)
1465
- })
1466
-
1467
- yield* getModel(taskModel.providerID, taskModel.modelID, input.sessionID)
1468
-
1469
- const agent = agentName ? yield* agents.get(agentName) : yield* agents.defaultInfo()
1470
- if (!agent) {
1471
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
1472
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
1473
- const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
1474
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
1475
- throw error
1476
- }
1477
-
1478
- const templateParts = yield* resolvePromptParts(template)
1479
- const inputFiles = new Set(
1480
- input.parts?.filter((part) => new URL(part.url).protocol === "file:").map((part) => fileURLToPath(part.url)),
1481
- )
1482
- const uniqueTemplateParts = templateParts.filter(
1483
- (part) => part.type !== "file" || !inputFiles.has(fileURLToPath(part.url)),
1484
- )
1485
- const isSubtask = (agent.mode === "subagent" && cmd.subtask !== false) || cmd.subtask === true
1486
- const parts = isSubtask
1487
- ? [
1488
- {
1489
- type: "subtask" as const,
1490
- agent: agent.name,
1491
- description: cmd.description ?? "",
1492
- command: input.command,
1493
- model: { providerID: taskModel.providerID, modelID: taskModel.modelID },
1494
- prompt: templateParts.find((y) => y.type === "text")?.text ?? "",
1495
- },
1496
- ]
1497
- : [...uniqueTemplateParts, ...(input.parts ?? [])]
1498
-
1499
- const userAgent = isSubtask ? (input.agent ?? (yield* agents.defaultInfo()).name) : agent.name
1500
- const userModel = isSubtask
1501
- ? input.model
1502
- ? Provider.parseModel(input.model)
1503
- : yield* currentModel(input.sessionID)
1504
- : taskModel
1505
-
1506
- yield* plugin.trigger(
1507
- "command.execute.before",
1508
- { command: input.command, sessionID: input.sessionID, arguments: input.arguments },
1509
- { parts },
1510
- )
1511
-
1512
- const result = yield* prompt({
1513
- sessionID: input.sessionID,
1514
- messageID: input.messageID,
1515
- model: userModel,
1516
- agent: userAgent,
1517
- parts,
1518
- variant: input.variant,
1519
- })
1520
- yield* events.publish(Command.Event.Executed, {
1521
- name: input.command,
1522
- sessionID: input.sessionID,
1523
- arguments: input.arguments,
1524
- messageID: result.info.id,
1525
- })
1526
- return result
1527
- })
1528
-
1529
- return Service.of({
1530
- cancel,
1531
- prompt,
1532
- loop,
1533
- shell,
1534
- command,
1535
- resolvePromptParts,
1536
- })
1537
- }),
1538
- )
1539
-
1540
- export const defaultLayer = Layer.suspend(() =>
1541
- layer.pipe(
1542
- Layer.provide(SessionRunState.defaultLayer),
1543
- Layer.provide(SessionStatus.defaultLayer),
1544
- Layer.provide(SessionCompaction.defaultLayer),
1545
- Layer.provide(SessionProcessor.defaultLayer),
1546
- Layer.provide(Command.defaultLayer),
1547
- Layer.provide(Permission.defaultLayer),
1548
- Layer.provide(MCP.defaultLayer),
1549
- Layer.provide(LSP.defaultLayer),
1550
- Layer.provide(ToolRegistry.defaultLayer),
1551
- Layer.provide(Truncate.defaultLayer),
1552
- Layer.provide(Provider.defaultLayer),
1553
- Layer.provide(Config.defaultLayer),
1554
- Layer.provide(Instruction.defaultLayer),
1555
- Layer.provide(FSUtil.defaultLayer),
1556
- Layer.provide(Plugin.defaultLayer),
1557
- Layer.provide(Session.defaultLayer),
1558
- Layer.provide(SessionRevert.defaultLayer),
1559
- Layer.provide(SessionSummary.defaultLayer),
1560
- Layer.provide(Image.defaultLayer),
1561
- Layer.provide(
1562
- Layer.mergeAll(
1563
- Agent.defaultLayer,
1564
- Database.defaultLayer,
1565
- SystemPrompt.defaultLayer,
1566
- LLM.defaultLayer,
1567
- CrossSpawnSpawner.defaultLayer,
1568
- RuntimeFlags.defaultLayer,
1569
- EventV2Bridge.defaultLayer,
1570
- ),
1571
- ),
1572
- ),
1573
- )
1574
- const ModelRef = Schema.Struct({
1575
- providerID: ProviderV2.ID,
1576
- modelID: ModelV2.ID,
1577
- })
1578
-
1579
- export const PromptInput = Schema.Struct({
1580
- sessionID: SessionID,
1581
- messageID: Schema.optional(MessageID),
1582
- model: Schema.optional(ModelRef),
1583
- agent: Schema.optional(Schema.String),
1584
- noReply: Schema.optional(Schema.Boolean),
1585
- tools: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)).annotate({
1586
- description:
1587
- "@deprecated tools and permissions have been merged, you can set permissions on the session itself now",
1588
- }),
1589
- format: Schema.optional(SessionV1.Format),
1590
- system: Schema.optional(Schema.String),
1591
- variant: Schema.optional(Schema.String),
1592
- parts: Schema.Array(
1593
- Schema.Union([
1594
- SessionV1.TextPartInput,
1595
- SessionV1.FilePartInput,
1596
- SessionV1.AgentPartInput,
1597
- SessionV1.SubtaskPartInput,
1598
- ]).annotate({ discriminator: "type" }),
1599
- ),
1600
- })
1601
- export type PromptInput = Schema.Schema.Type<typeof PromptInput>
1602
-
1603
- export class LoopInput extends Schema.Class<LoopInput>("SessionPrompt.LoopInput")({
1604
- sessionID: SessionID,
1605
- }) {}
1606
-
1607
- export const ShellInput = Schema.Struct({
1608
- sessionID: SessionID,
1609
- messageID: Schema.optional(MessageID),
1610
- agent: Schema.String,
1611
- model: Schema.optional(ModelRef),
1612
- command: Schema.String,
1613
- })
1614
- export type ShellInput = Schema.Schema.Type<typeof ShellInput>
1615
-
1616
- export const CommandInput = Schema.Struct({
1617
- messageID: Schema.optional(MessageID),
1618
- sessionID: SessionID,
1619
- agent: Schema.optional(Schema.String),
1620
- model: Schema.optional(Schema.String),
1621
- arguments: Schema.String,
1622
- command: Schema.String,
1623
- variant: Schema.optional(Schema.String),
1624
- // Inlined (no identifier annotation) to keep the original SDK output — the
1625
- // PromptInput call site below references FilePartInput by ref via the
1626
- // Schema export in message-v2.ts.
1627
- parts: Schema.optional(
1628
- Schema.Array(
1629
- Schema.Union([
1630
- Schema.Struct({
1631
- id: Schema.optional(PartID),
1632
- type: Schema.Literal("file"),
1633
- mime: Schema.String,
1634
- filename: Schema.optional(Schema.String),
1635
- url: Schema.String,
1636
- source: Schema.optional(SessionV1.FilePartSource),
1637
- }),
1638
- ]).annotate({ discriminator: "type" }),
1639
- ),
1640
- ),
1641
- })
1642
- export type CommandInput = Schema.Schema.Type<typeof CommandInput>
1643
-
1644
- /** @internal Exported for testing */
1645
- export function createStructuredOutputTool(input: {
1646
- schema: Record<string, any>
1647
- onSuccess: (output: unknown) => void
1648
- }): AITool {
1649
- // Remove $schema property if present (not needed for tool input)
1650
- const { $schema: _, ...toolSchema } = input.schema
1651
-
1652
- return tool({
1653
- description: STRUCTURED_OUTPUT_DESCRIPTION,
1654
- inputSchema: jsonSchema(toolSchema as JSONSchema7),
1655
- async execute(args) {
1656
- // AI SDK validates args against inputSchema before calling execute()
1657
- input.onSuccess(args)
1658
- return {
1659
- output: "Structured output captured successfully.",
1660
- title: "Structured Output",
1661
- metadata: { valid: true },
1662
- }
1663
- },
1664
- toModelOutput({ output }) {
1665
- return {
1666
- type: "text",
1667
- value: output.output,
1668
- }
1669
- },
1670
- })
1671
- }
1672
- const bashRegex = /!`([^`]+)`/g
1673
- // Match [Image N] as single token, quoted strings, or non-space sequences
1674
- const argsRegex = /(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi
1675
- const placeholderRegex = /\$(\d+)/g
1676
- const quoteTrimRegex = /^["']|["']$/g
1677
-
1678
- export const node = LayerNode.make(layer, [
1679
- SessionStatus.node,
1680
- Session.node,
1681
- Agent.node,
1682
- Provider.node,
1683
- SessionProcessor.node,
1684
- SessionCompaction.node,
1685
- Plugin.node,
1686
- Command.node,
1687
- Config.node,
1688
- Permission.node,
1689
- FSUtil.node,
1690
- MCP.node,
1691
- LSP.node,
1692
- ToolRegistry.node,
1693
- Truncate.node,
1694
- Image.node,
1695
- CrossSpawnSpawner.node,
1696
- Instruction.node,
1697
- SessionRunState.node,
1698
- SessionRevert.node,
1699
- SessionSummary.node,
1700
- SystemPrompt.node,
1701
- LLM.node,
1702
- EventV2Bridge.node,
1703
- RuntimeFlags.node,
1704
- Database.node,
1705
- ])
1706
-
1707
- export * as SessionPrompt from "./prompt"