anymous 1.2.7 → 1.3.1

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