@miaws/miaw 1.18.3 → 1.18.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (752) hide show
  1. package/AGENTS.md +131 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +15 -0
  4. package/{miaw.js → bin/miaw} +0 -0
  5. package/bunfig.toml +7 -0
  6. package/git +0 -0
  7. package/migration/20260511173437_session-metadata/migration.sql +1 -0
  8. package/migration/20260511173437_session-metadata/snapshot.json +1500 -0
  9. package/package.json +154 -12
  10. package/parsers-config.ts +1 -0
  11. package/script/bench-search.ts +94 -0
  12. package/script/bench-test-suite.ts +52 -0
  13. package/script/build.ts +243 -0
  14. package/script/generate.ts +14 -0
  15. package/script/httpapi-exercise.ts +1 -0
  16. package/script/postinstall.mjs +189 -0
  17. package/script/profile-test-files.ts +42 -0
  18. package/script/publish.ts +213 -0
  19. package/script/run-workspace-server +106 -0
  20. package/script/schema.ts +77 -0
  21. package/script/time.ts +6 -0
  22. package/script/trace-imports.ts +153 -0
  23. package/specs/effect/error-boundaries-plan.md +235 -0
  24. package/specs/effect/errors.md +207 -0
  25. package/specs/effect/facades.md +218 -0
  26. package/specs/effect/guide.md +247 -0
  27. package/specs/effect/instance-context.md +13 -0
  28. package/specs/effect/loose-ends.md +30 -0
  29. package/specs/effect/migration.md +62 -0
  30. package/specs/effect/routes.md +61 -0
  31. package/specs/effect/schema.md +88 -0
  32. package/specs/effect/server-package.md +58 -0
  33. package/specs/effect/todo.md +241 -0
  34. package/specs/effect/tools.md +88 -0
  35. package/specs/openapi-translation-cleanup.md +204 -0
  36. package/specs/tui-plugins.md +544 -0
  37. package/specs/v2/api.ts +67 -0
  38. package/specs/v2/message-shape.md +136 -0
  39. package/specs/v2/notifications.md +13 -0
  40. package/specs/v2/tui-command-shim.md +67 -0
  41. package/src/account/account.ts +463 -0
  42. package/src/account/repo.ts +173 -0
  43. package/src/account/schema.ts +99 -0
  44. package/src/account/url.ts +8 -0
  45. package/src/acp/agent.ts +95 -0
  46. package/src/acp/config-option.ts +203 -0
  47. package/src/acp/content.ts +250 -0
  48. package/src/acp/directory.ts +210 -0
  49. package/src/acp/error.ts +90 -0
  50. package/src/acp/event.ts +336 -0
  51. package/src/acp/permission.ts +124 -0
  52. package/src/acp/profile.ts +42 -0
  53. package/src/acp/service.ts +1048 -0
  54. package/src/acp/session.ts +231 -0
  55. package/src/acp/tool.ts +321 -0
  56. package/src/acp/usage.ts +232 -0
  57. package/src/agent/agent.ts +467 -0
  58. package/src/agent/generate.txt +75 -0
  59. package/src/agent/prompt/compaction.txt +9 -0
  60. package/src/agent/prompt/explore.txt +18 -0
  61. package/src/agent/prompt/summary.txt +11 -0
  62. package/src/agent/prompt/title.txt +44 -0
  63. package/src/agent/subagent-permissions.ts +27 -0
  64. package/src/audio.d.ts +14 -0
  65. package/src/auth/index.ts +99 -0
  66. package/src/background/job.ts +39 -0
  67. package/src/bus/global.ts +22 -0
  68. package/src/cli/bootstrap.ts +11 -0
  69. package/src/cli/cmd/account.ts +264 -0
  70. package/src/cli/cmd/acp.ts +73 -0
  71. package/src/cli/cmd/agent.ts +253 -0
  72. package/src/cli/cmd/attach.ts +97 -0
  73. package/src/cli/cmd/cmd.ts +7 -0
  74. package/src/cli/cmd/db.ts +62 -0
  75. package/src/cli/cmd/debug/agent.handler.ts +193 -0
  76. package/src/cli/cmd/debug/agent.ts +27 -0
  77. package/src/cli/cmd/debug/config.ts +14 -0
  78. package/src/cli/cmd/debug/file.ts +73 -0
  79. package/src/cli/cmd/debug/index.ts +87 -0
  80. package/src/cli/cmd/debug/lsp.ts +50 -0
  81. package/src/cli/cmd/debug/ripgrep.ts +79 -0
  82. package/src/cli/cmd/debug/scrap.ts +15 -0
  83. package/src/cli/cmd/debug/skill.ts +15 -0
  84. package/src/cli/cmd/debug/snapshot.ts +50 -0
  85. package/src/cli/cmd/debug/startup.ts +11 -0
  86. package/src/cli/cmd/debug/v2.ts +49 -0
  87. package/src/cli/cmd/export.ts +292 -0
  88. package/src/cli/cmd/generate.ts +54 -0
  89. package/src/cli/cmd/github.handler.ts +1593 -0
  90. package/src/cli/cmd/github.shared.ts +30 -0
  91. package/src/cli/cmd/github.ts +42 -0
  92. package/src/cli/cmd/import.ts +224 -0
  93. package/src/cli/cmd/mcp.ts +849 -0
  94. package/src/cli/cmd/models.ts +66 -0
  95. package/src/cli/cmd/plug.ts +230 -0
  96. package/src/cli/cmd/pr.ts +115 -0
  97. package/src/cli/cmd/prompt-display.ts +1 -0
  98. package/src/cli/cmd/providers.ts +534 -0
  99. package/src/cli/cmd/run/demo.ts +1274 -0
  100. package/src/cli/cmd/run/entry.body.ts +205 -0
  101. package/src/cli/cmd/run/footer.command.tsx +1064 -0
  102. package/src/cli/cmd/run/footer.menu.tsx +351 -0
  103. package/src/cli/cmd/run/footer.permission.tsx +472 -0
  104. package/src/cli/cmd/run/footer.prompt.tsx +1306 -0
  105. package/src/cli/cmd/run/footer.question.tsx +573 -0
  106. package/src/cli/cmd/run/footer.subagent.tsx +173 -0
  107. package/src/cli/cmd/run/footer.ts +1129 -0
  108. package/src/cli/cmd/run/footer.view.tsx +943 -0
  109. package/src/cli/cmd/run/footer.width.ts +27 -0
  110. package/src/cli/cmd/run/permission.shared.ts +256 -0
  111. package/src/cli/cmd/run/prompt.editor.ts +157 -0
  112. package/src/cli/cmd/run/prompt.shared.ts +153 -0
  113. package/src/cli/cmd/run/question.shared.ts +340 -0
  114. package/src/cli/cmd/run/runtime.boot.ts +202 -0
  115. package/src/cli/cmd/run/runtime.lifecycle.ts +406 -0
  116. package/src/cli/cmd/run/runtime.queue.ts +349 -0
  117. package/src/cli/cmd/run/runtime.shared.ts +17 -0
  118. package/src/cli/cmd/run/runtime.stdin.ts +37 -0
  119. package/src/cli/cmd/run/runtime.ts +814 -0
  120. package/src/cli/cmd/run/scrollback.shared.ts +92 -0
  121. package/src/cli/cmd/run/scrollback.surface.ts +431 -0
  122. package/src/cli/cmd/run/scrollback.writer.tsx +352 -0
  123. package/src/cli/cmd/run/session-data.ts +1113 -0
  124. package/src/cli/cmd/run/session-replay.ts +374 -0
  125. package/src/cli/cmd/run/session.shared.ts +196 -0
  126. package/src/cli/cmd/run/splash.ts +280 -0
  127. package/src/cli/cmd/run/stream.transport.ts +1462 -0
  128. package/src/cli/cmd/run/stream.ts +175 -0
  129. package/src/cli/cmd/run/subagent-data.ts +876 -0
  130. package/src/cli/cmd/run/theme.ts +690 -0
  131. package/src/cli/cmd/run/tool.ts +1489 -0
  132. package/src/cli/cmd/run/trace.ts +94 -0
  133. package/src/cli/cmd/run/turn-summary.ts +47 -0
  134. package/src/cli/cmd/run/types.ts +350 -0
  135. package/src/cli/cmd/run/variant.shared.ts +215 -0
  136. package/src/cli/cmd/run.ts +894 -0
  137. package/src/cli/cmd/serve.ts +24 -0
  138. package/src/cli/cmd/session.ts +147 -0
  139. package/src/cli/cmd/stats.ts +393 -0
  140. package/src/cli/cmd/tui.ts +224 -0
  141. package/src/cli/cmd/uninstall.ts +353 -0
  142. package/src/cli/cmd/upgrade.ts +74 -0
  143. package/src/cli/cmd/web.ts +84 -0
  144. package/src/cli/effect/prompt.ts +37 -0
  145. package/src/cli/effect-cmd.ts +96 -0
  146. package/src/cli/error.ts +130 -0
  147. package/src/cli/heap.ts +45 -0
  148. package/src/cli/logo.ts +1 -0
  149. package/src/cli/network.ts +64 -0
  150. package/src/cli/tui/layer.ts +7 -0
  151. package/src/cli/tui/validate-session.ts +29 -0
  152. package/src/cli/tui/worker.ts +71 -0
  153. package/src/cli/ui.ts +132 -0
  154. package/src/cli/upgrade.ts +53 -0
  155. package/src/command/index.ts +184 -0
  156. package/src/command/template/initialize.txt +66 -0
  157. package/src/command/template/review.txt +101 -0
  158. package/src/config/agent-preset.ts +175 -0
  159. package/src/config/agent.ts +59 -0
  160. package/src/config/command.ts +39 -0
  161. package/src/config/config.ts +703 -0
  162. package/src/config/entry-name.ts +19 -0
  163. package/src/config/managed.ts +69 -0
  164. package/src/config/markdown.ts +36 -0
  165. package/src/config/parse.ts +79 -0
  166. package/src/config/paths.ts +45 -0
  167. package/src/config/plugin.ts +79 -0
  168. package/src/config/tui-cwd.ts +5 -0
  169. package/src/config/tui-host-attention.ts +21 -0
  170. package/src/config/tui-migrate.ts +132 -0
  171. package/src/config/tui.ts +274 -0
  172. package/src/config/variable.ts +91 -0
  173. package/src/control-plane/adapters/index.ts +41 -0
  174. package/src/control-plane/adapters/worktree.ts +96 -0
  175. package/src/control-plane/dev/README.md +19 -0
  176. package/src/control-plane/dev/debug-workspace-plugin.ts +73 -0
  177. package/src/control-plane/types.ts +59 -0
  178. package/src/control-plane/util.ts +39 -0
  179. package/src/control-plane/workspace-adapter-runtime.ts +51 -0
  180. package/src/control-plane/workspace-context.ts +26 -0
  181. package/src/control-plane/workspace.ts +989 -0
  182. package/src/effect/app-runtime.ts +132 -0
  183. package/src/effect/bootstrap-runtime.ts +23 -0
  184. package/src/effect/bridge.ts +84 -0
  185. package/src/effect/config-service.ts +67 -0
  186. package/src/effect/instance-ref.ts +11 -0
  187. package/src/effect/instance-registry.ts +12 -0
  188. package/src/effect/instance-state.ts +69 -0
  189. package/src/effect/promise.ts +17 -0
  190. package/src/effect/run-service.ts +47 -0
  191. package/src/effect/runner.ts +217 -0
  192. package/src/effect/runtime-flags.ts +79 -0
  193. package/src/env/index.ts +43 -0
  194. package/src/event-v2-bridge.ts +79 -0
  195. package/src/format/formatter.ts +404 -0
  196. package/src/format/index.ts +205 -0
  197. package/src/git/index.ts +350 -0
  198. package/src/id/id.ts +80 -0
  199. package/src/ide/index.ts +61 -0
  200. package/src/image/image.ts +174 -0
  201. package/src/index.ts +142 -0
  202. package/src/installation/index.ts +350 -0
  203. package/src/lsp/client.ts +650 -0
  204. package/src/lsp/diagnostic.ts +29 -0
  205. package/src/lsp/language.ts +121 -0
  206. package/src/lsp/launch.ts +21 -0
  207. package/src/lsp/lsp.ts +511 -0
  208. package/src/lsp/server.ts +1983 -0
  209. package/src/markdown.d.ts +4 -0
  210. package/src/mcp/auth.ts +174 -0
  211. package/src/mcp/catalog.ts +144 -0
  212. package/src/mcp/index.ts +953 -0
  213. package/src/mcp/oauth-callback.ts +221 -0
  214. package/src/mcp/oauth-provider.ts +206 -0
  215. package/src/node.ts +4 -0
  216. package/src/patch/index.ts +686 -0
  217. package/src/permission/arity.ts +163 -0
  218. package/src/permission/evaluate.ts +1 -0
  219. package/src/permission/index.ts +230 -0
  220. package/src/plugin/azure.ts +26 -0
  221. package/src/plugin/cloudflare.ts +76 -0
  222. package/src/plugin/digitalocean.ts +383 -0
  223. package/src/plugin/github-copilot/copilot.ts +413 -0
  224. package/src/plugin/github-copilot/models.ts +246 -0
  225. package/src/plugin/index.ts +315 -0
  226. package/src/plugin/install.ts +439 -0
  227. package/src/plugin/loader.ts +237 -0
  228. package/src/plugin/meta.ts +188 -0
  229. package/src/plugin/openai/README.md +31 -0
  230. package/src/plugin/openai/codex.ts +640 -0
  231. package/src/plugin/openai/ws-pool.ts +270 -0
  232. package/src/plugin/openai/ws.ts +381 -0
  233. package/src/plugin/pty-environment.ts +24 -0
  234. package/src/plugin/shared.ts +323 -0
  235. package/src/plugin/snowflake-cortex.ts +529 -0
  236. package/src/plugin/tui/internal.ts +10 -0
  237. package/src/plugin/tui/runtime.ts +1130 -0
  238. package/src/plugin/xai.ts +734 -0
  239. package/src/project/bootstrap-service.ts +9 -0
  240. package/src/project/bootstrap.ts +76 -0
  241. package/src/project/instance-context.ts +24 -0
  242. package/src/project/instance-layer.ts +11 -0
  243. package/src/project/instance-runtime.ts +16 -0
  244. package/src/project/instance-store.ts +209 -0
  245. package/src/project/project.ts +519 -0
  246. package/src/project/vcs.ts +431 -0
  247. package/src/provider/auth.ts +233 -0
  248. package/src/provider/error.ts +188 -0
  249. package/src/provider/model-status.ts +8 -0
  250. package/src/provider/provider.ts +1975 -0
  251. package/src/provider/transform.ts +1426 -0
  252. package/src/question/index.ts +229 -0
  253. package/src/question/schema.ts +10 -0
  254. package/src/server/auth.ts +48 -0
  255. package/src/server/event.ts +13 -0
  256. package/src/server/global-lifecycle.ts +28 -0
  257. package/src/server/init-projectors.ts +3 -0
  258. package/src/server/mdns.ts +47 -0
  259. package/src/server/projectors.ts +1 -0
  260. package/src/server/proxy-util.ts +48 -0
  261. package/src/server/routes/instance/httpapi/AGENTS.md +39 -0
  262. package/src/server/routes/instance/httpapi/api.ts +78 -0
  263. package/src/server/routes/instance/httpapi/errors.ts +193 -0
  264. package/src/server/routes/instance/httpapi/groups/config.ts +65 -0
  265. package/src/server/routes/instance/httpapi/groups/control-plane.ts +35 -0
  266. package/src/server/routes/instance/httpapi/groups/control.ts +76 -0
  267. package/src/server/routes/instance/httpapi/groups/event.ts +29 -0
  268. package/src/server/routes/instance/httpapi/groups/experimental.ts +260 -0
  269. package/src/server/routes/instance/httpapi/groups/file.ts +185 -0
  270. package/src/server/routes/instance/httpapi/groups/global.ts +138 -0
  271. package/src/server/routes/instance/httpapi/groups/instance.ts +206 -0
  272. package/src/server/routes/instance/httpapi/groups/mcp.ts +156 -0
  273. package/src/server/routes/instance/httpapi/groups/metadata.ts +18 -0
  274. package/src/server/routes/instance/httpapi/groups/permission.ts +61 -0
  275. package/src/server/routes/instance/httpapi/groups/project-copy.ts +32 -0
  276. package/src/server/routes/instance/httpapi/groups/project.ts +93 -0
  277. package/src/server/routes/instance/httpapi/groups/provider.ts +101 -0
  278. package/src/server/routes/instance/httpapi/groups/pty.ts +172 -0
  279. package/src/server/routes/instance/httpapi/groups/query.ts +12 -0
  280. package/src/server/routes/instance/httpapi/groups/question.ts +74 -0
  281. package/src/server/routes/instance/httpapi/groups/session.ts +462 -0
  282. package/src/server/routes/instance/httpapi/groups/sync.ts +113 -0
  283. package/src/server/routes/instance/httpapi/groups/tui.ts +208 -0
  284. package/src/server/routes/instance/httpapi/groups/workspace.ts +141 -0
  285. package/src/server/routes/instance/httpapi/handlers/config.ts +34 -0
  286. package/src/server/routes/instance/httpapi/handlers/control-plane.ts +37 -0
  287. package/src/server/routes/instance/httpapi/handlers/control.ts +43 -0
  288. package/src/server/routes/instance/httpapi/handlers/event.ts +99 -0
  289. package/src/server/routes/instance/httpapi/handlers/experimental.ts +187 -0
  290. package/src/server/routes/instance/httpapi/handlers/file.ts +139 -0
  291. package/src/server/routes/instance/httpapi/handlers/global.ts +156 -0
  292. package/src/server/routes/instance/httpapi/handlers/instance.ts +110 -0
  293. package/src/server/routes/instance/httpapi/handlers/mcp.ts +111 -0
  294. package/src/server/routes/instance/httpapi/handlers/permission.ts +41 -0
  295. package/src/server/routes/instance/httpapi/handlers/project-copy.ts +83 -0
  296. package/src/server/routes/instance/httpapi/handlers/project.ts +63 -0
  297. package/src/server/routes/instance/httpapi/handlers/provider.ts +113 -0
  298. package/src/server/routes/instance/httpapi/handlers/pty.ts +273 -0
  299. package/src/server/routes/instance/httpapi/handlers/question.ts +54 -0
  300. package/src/server/routes/instance/httpapi/handlers/session-errors.ts +21 -0
  301. package/src/server/routes/instance/httpapi/handlers/session.ts +440 -0
  302. package/src/server/routes/instance/httpapi/handlers/sync.ts +89 -0
  303. package/src/server/routes/instance/httpapi/handlers/tui.ts +131 -0
  304. package/src/server/routes/instance/httpapi/handlers/workspace.ts +102 -0
  305. package/src/server/routes/instance/httpapi/lifecycle.ts +54 -0
  306. package/src/server/routes/instance/httpapi/middleware/authorization.ts +150 -0
  307. package/src/server/routes/instance/httpapi/middleware/compression.ts +64 -0
  308. package/src/server/routes/instance/httpapi/middleware/cors-vary.ts +29 -0
  309. package/src/server/routes/instance/httpapi/middleware/error.ts +43 -0
  310. package/src/server/routes/instance/httpapi/middleware/fence.ts +25 -0
  311. package/src/server/routes/instance/httpapi/middleware/instance-context.ts +43 -0
  312. package/src/server/routes/instance/httpapi/middleware/proxy.ts +108 -0
  313. package/src/server/routes/instance/httpapi/middleware/schema-error.ts +41 -0
  314. package/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +250 -0
  315. package/src/server/routes/instance/httpapi/public.ts +535 -0
  316. package/src/server/routes/instance/httpapi/server.ts +298 -0
  317. package/src/server/routes/instance/httpapi/websocket-tracker.ts +57 -0
  318. package/src/server/server.ts +217 -0
  319. package/src/server/shared/fence.ts +60 -0
  320. package/src/server/shared/pty-ticket.ts +15 -0
  321. package/src/server/shared/public-ui.ts +12 -0
  322. package/src/server/shared/tui-control.ts +28 -0
  323. package/src/server/shared/ui.ts +108 -0
  324. package/src/server/shared/workspace-routing.ts +38 -0
  325. package/src/server/tui-event.ts +53 -0
  326. package/src/session/compaction.ts +620 -0
  327. package/src/session/instruction.ts +250 -0
  328. package/src/session/llm/AGENTS.md +90 -0
  329. package/src/session/llm/ai-sdk.ts +288 -0
  330. package/src/session/llm/native-request.ts +196 -0
  331. package/src/session/llm/native-runtime.ts +195 -0
  332. package/src/session/llm/request.ts +216 -0
  333. package/src/session/llm.ts +415 -0
  334. package/src/session/message-error.ts +14 -0
  335. package/src/session/message-v2.ts +744 -0
  336. package/src/session/message.ts +148 -0
  337. package/src/session/overflow.ts +34 -0
  338. package/src/session/processor.ts +1084 -0
  339. package/src/session/prompt/anthropic.txt +105 -0
  340. package/src/session/prompt/beast.txt +147 -0
  341. package/src/session/prompt/build-switch.txt +5 -0
  342. package/src/session/prompt/codex.txt +79 -0
  343. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  344. package/src/session/prompt/default.txt +95 -0
  345. package/src/session/prompt/gemini.txt +155 -0
  346. package/src/session/prompt/gpt.txt +107 -0
  347. package/src/session/prompt/kimi.txt +95 -0
  348. package/src/session/prompt/max-steps.txt +16 -0
  349. package/src/session/prompt/plan-mode.txt +70 -0
  350. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  351. package/src/session/prompt/plan.txt +26 -0
  352. package/src/session/prompt/trinity.txt +97 -0
  353. package/src/session/prompt/ultrawork.txt +289 -0
  354. package/src/session/prompt.ts +1725 -0
  355. package/src/session/reminders.ts +92 -0
  356. package/src/session/retry.ts +201 -0
  357. package/src/session/revert.ts +160 -0
  358. package/src/session/run-state.ts +156 -0
  359. package/src/session/schema.ts +26 -0
  360. package/src/session/session.ts +1119 -0
  361. package/src/session/status.ts +97 -0
  362. package/src/session/summary.ts +165 -0
  363. package/src/session/system.ts +117 -0
  364. package/src/session/todo.ts +90 -0
  365. package/src/session/tools.ts +207 -0
  366. package/src/session/ultrawork.ts +26 -0
  367. package/src/share/session.ts +61 -0
  368. package/src/share/share-next.ts +385 -0
  369. package/src/skill/discovery.ts +109 -0
  370. package/src/skill/index.ts +366 -0
  371. package/src/snapshot/index.ts +808 -0
  372. package/src/sql.d.ts +4 -0
  373. package/src/storage/schema.ts +5 -0
  374. package/src/storage/storage.ts +329 -0
  375. package/src/sync/README.md +179 -0
  376. package/src/sync/schema.ts +11 -0
  377. package/src/temporary.ts +31 -0
  378. package/src/tool/apply_patch.ts +313 -0
  379. package/src/tool/apply_patch.txt +33 -0
  380. package/src/tool/edit.ts +737 -0
  381. package/src/tool/edit.txt +10 -0
  382. package/src/tool/external-directory.ts +49 -0
  383. package/src/tool/glob.ts +76 -0
  384. package/src/tool/glob.txt +6 -0
  385. package/src/tool/grep.ts +112 -0
  386. package/src/tool/grep.txt +8 -0
  387. package/src/tool/invalid.ts +21 -0
  388. package/src/tool/json-schema.ts +164 -0
  389. package/src/tool/lsp.ts +113 -0
  390. package/src/tool/lsp.txt +24 -0
  391. package/src/tool/mcp-websearch.ts +96 -0
  392. package/src/tool/plan-enter.txt +14 -0
  393. package/src/tool/plan-exit.txt +13 -0
  394. package/src/tool/plan.ts +79 -0
  395. package/src/tool/question.ts +44 -0
  396. package/src/tool/question.txt +10 -0
  397. package/src/tool/read.ts +386 -0
  398. package/src/tool/read.txt +14 -0
  399. package/src/tool/registry.ts +440 -0
  400. package/src/tool/schema.ts +14 -0
  401. package/src/tool/shell/id.ts +19 -0
  402. package/src/tool/shell/prompt.ts +307 -0
  403. package/src/tool/shell/shell.txt +21 -0
  404. package/src/tool/shell.ts +657 -0
  405. package/src/tool/skill.ts +71 -0
  406. package/src/tool/skill.txt +5 -0
  407. package/src/tool/task.ts +346 -0
  408. package/src/tool/task.txt +19 -0
  409. package/src/tool/todo.ts +57 -0
  410. package/src/tool/todowrite.txt +44 -0
  411. package/src/tool/tool.ts +183 -0
  412. package/src/tool/truncate.ts +158 -0
  413. package/src/tool/truncation-dir.ts +4 -0
  414. package/src/tool/webfetch.ts +192 -0
  415. package/src/tool/webfetch.txt +13 -0
  416. package/src/tool/websearch.ts +143 -0
  417. package/src/tool/websearch.txt +14 -0
  418. package/src/tool/write.ts +104 -0
  419. package/src/tool/write.txt +8 -0
  420. package/src/util/archive.ts +17 -0
  421. package/src/util/bom.ts +27 -0
  422. package/src/util/data-url.ts +9 -0
  423. package/src/util/defer.ts +10 -0
  424. package/src/util/effect-http-client.ts +11 -0
  425. package/src/util/error.ts +1 -0
  426. package/src/util/filesystem.ts +251 -0
  427. package/src/util/iife.ts +3 -0
  428. package/src/util/lazy.ts +20 -0
  429. package/src/util/local-context.ts +25 -0
  430. package/src/util/locale.ts +2 -0
  431. package/src/util/media.ts +26 -0
  432. package/src/util/process.ts +177 -0
  433. package/src/util/proxy-env.ts +72 -0
  434. package/src/util/queue.ts +32 -0
  435. package/src/util/record.ts +1 -0
  436. package/src/util/repository.ts +232 -0
  437. package/src/util/rpc.ts +66 -0
  438. package/src/util/signal.ts +12 -0
  439. package/src/util/timeout.ts +13 -0
  440. package/src/util/token.ts +1 -0
  441. package/src/util/wildcard.ts +59 -0
  442. package/src/worktree/index.ts +654 -0
  443. package/sst-env.d.ts +10 -0
  444. package/test/AGENTS.md +204 -0
  445. package/test/EFFECT_TEST_MIGRATION.md +169 -0
  446. package/test/account/repo.test.ts +353 -0
  447. package/test/account/service.test.ts +453 -0
  448. package/test/acp/config-option.test.ts +229 -0
  449. package/test/acp/content.test.ts +201 -0
  450. package/test/acp/directory.test.ts +186 -0
  451. package/test/acp/error.test.ts +67 -0
  452. package/test/acp/event.test.ts +743 -0
  453. package/test/acp/permission.test.ts +273 -0
  454. package/test/acp/service-session.test.ts +1174 -0
  455. package/test/acp/session.test.ts +200 -0
  456. package/test/acp/tool.test.ts +210 -0
  457. package/test/acp/usage.test.ts +315 -0
  458. package/test/agent/agent.test.ts +760 -0
  459. package/test/agent/plan-mode-subagent-bypass.test.ts +159 -0
  460. package/test/agent/plugin-agent-regression.test.ts +64 -0
  461. package/test/auth/auth.test.ts +77 -0
  462. package/test/background/job.test.ts +243 -0
  463. package/test/cli/account.test.ts +30 -0
  464. package/test/cli/acp/acp-test-client.ts +97 -0
  465. package/test/cli/acp/config-options.test.ts +103 -0
  466. package/test/cli/acp/helpers.ts +96 -0
  467. package/test/cli/acp/initialize-auth.test.ts +61 -0
  468. package/test/cli/acp/lifecycle.test.ts +118 -0
  469. package/test/cli/acp/prompt-content.test.ts +97 -0
  470. package/test/cli/acp/skills.test.ts +38 -0
  471. package/test/cli/cmd/tui/attention.test.ts +484 -0
  472. package/test/cli/effect-cmd-instance-als.test.ts +39 -0
  473. package/test/cli/error.test.ts +95 -0
  474. package/test/cli/github-action.test.ts +199 -0
  475. package/test/cli/github-remote.test.ts +90 -0
  476. package/test/cli/help/__snapshots__/help-snapshots.test.ts.snap +631 -0
  477. package/test/cli/help/help-snapshots.test.ts +137 -0
  478. package/test/cli/import.test.ts +54 -0
  479. package/test/cli/mcp-add.test.ts +74 -0
  480. package/test/cli/plugin-auth-picker.test.ts +120 -0
  481. package/test/cli/run/entry.body.test.ts +536 -0
  482. package/test/cli/run/footer.menu.test.ts +43 -0
  483. package/test/cli/run/footer.view.test.tsx +1375 -0
  484. package/test/cli/run/footer.width.test.ts +35 -0
  485. package/test/cli/run/permission.shared.test.ts +144 -0
  486. package/test/cli/run/prompt.editor.test.ts +101 -0
  487. package/test/cli/run/prompt.shared.test.ts +101 -0
  488. package/test/cli/run/question.shared.test.ts +115 -0
  489. package/test/cli/run/run-process.test.ts +84 -0
  490. package/test/cli/run/runtime.boot.test.ts +283 -0
  491. package/test/cli/run/runtime.queue.test.ts +481 -0
  492. package/test/cli/run/runtime.stdin.test.ts +71 -0
  493. package/test/cli/run/runtime.test.ts +238 -0
  494. package/test/cli/run/scrollback.surface.test.ts +1065 -0
  495. package/test/cli/run/session-data.test.ts +595 -0
  496. package/test/cli/run/session-replay.test.ts +692 -0
  497. package/test/cli/run/session.shared.test.ts +247 -0
  498. package/test/cli/run/stream.test.ts +56 -0
  499. package/test/cli/run/stream.transport.test.ts +2363 -0
  500. package/test/cli/run/subagent-data.test.ts +547 -0
  501. package/test/cli/run/theme.test.ts +177 -0
  502. package/test/cli/run/variant.shared.test.ts +217 -0
  503. package/test/cli/serve/serve-process.test.ts +61 -0
  504. package/test/cli/smokes/read-only.test.ts +115 -0
  505. package/test/cli/tui/attach.test.ts +11 -0
  506. package/test/cli/tui/editor-context-zed.test.ts +379 -0
  507. package/test/cli/tui/editor-context.test.tsx +297 -0
  508. package/test/cli/tui/plugin-add.test.ts +110 -0
  509. package/test/cli/tui/plugin-install.test.ts +87 -0
  510. package/test/cli/tui/plugin-lifecycle.test.ts +224 -0
  511. package/test/cli/tui/plugin-loader-entrypoint.test.ts +485 -0
  512. package/test/cli/tui/plugin-loader-pure.test.ts +72 -0
  513. package/test/cli/tui/plugin-loader.test.ts +1332 -0
  514. package/test/cli/tui/plugin-toggle.test.ts +264 -0
  515. package/test/cli/tui/thread.test.ts +36 -0
  516. package/test/config/agent-color.test.ts +47 -0
  517. package/test/config/config.test.ts +2041 -0
  518. package/test/config/entry-name.test.ts +57 -0
  519. package/test/config/fixtures/empty-frontmatter.md +4 -0
  520. package/test/config/fixtures/frontmatter.md +28 -0
  521. package/test/config/fixtures/markdown-header.md +11 -0
  522. package/test/config/fixtures/no-frontmatter.md +1 -0
  523. package/test/config/fixtures/weird-model-id.md +13 -0
  524. package/test/config/lsp.test.ts +69 -0
  525. package/test/config/markdown.test.ts +228 -0
  526. package/test/config/plugin.test.ts +0 -0
  527. package/test/config/tui.test.ts +886 -0
  528. package/test/control-plane/adapters.test.ts +71 -0
  529. package/test/control-plane/workspace.test.ts +1703 -0
  530. package/test/effect/app-graph-types.test.ts +108 -0
  531. package/test/effect/app-graph.test.ts +204 -0
  532. package/test/effect/app-runtime-logger.test.ts +99 -0
  533. package/test/effect/config-service.test.ts +65 -0
  534. package/test/effect/instance-state.test.ts +391 -0
  535. package/test/effect/run-service.test.ts +89 -0
  536. package/test/effect/runner.test.ts +514 -0
  537. package/test/effect/runtime-flags.test.ts +373 -0
  538. package/test/fake/account.ts +9 -0
  539. package/test/fake/auth.ts +8 -0
  540. package/test/fake/npm.ts +8 -0
  541. package/test/fake/provider.ts +82 -0
  542. package/test/fake/skill.ts +8 -0
  543. package/test/filesystem/filesystem.test.ts +319 -0
  544. package/test/fixture/agent-plugin.constants.ts +6 -0
  545. package/test/fixture/agent-plugin.ts +12 -0
  546. package/test/fixture/config.ts +23 -0
  547. package/test/fixture/db.ts +11 -0
  548. package/test/fixture/fixture.test.ts +26 -0
  549. package/test/fixture/fixture.ts +224 -0
  550. package/test/fixture/flag.ts +20 -0
  551. package/test/fixture/flock-worker.ts +72 -0
  552. package/test/fixture/lsp/fake-lsp-server.js +249 -0
  553. package/test/fixture/mcp-session-recovery.ts +50 -0
  554. package/test/fixture/plug-worker.ts +93 -0
  555. package/test/fixture/plugin-meta-worker.ts +19 -0
  556. package/test/fixture/plugin.ts +10 -0
  557. package/test/fixture/skills/agents-sdk/SKILL.md +152 -0
  558. package/test/fixture/skills/agents-sdk/references/callable.md +92 -0
  559. package/test/fixture/skills/cloudflare/SKILL.md +211 -0
  560. package/test/fixture/skills/index.json +6 -0
  561. package/test/fixture/tui-environment.tsx +32 -0
  562. package/test/fixture/tui-plugin.ts +355 -0
  563. package/test/fixture/tui-runtime.ts +56 -0
  564. package/test/fixture/tui-sdk.ts +82 -0
  565. package/test/fixture/workspace.ts +30 -0
  566. package/test/fixtures/recordings/session/native-anthropic-tool-loop.json +49 -0
  567. package/test/fixtures/recordings/session/native-openai-oauth-tool-loop.json +45 -0
  568. package/test/fixtures/recordings/session/native-zen-tool-loop.json +49 -0
  569. package/test/format/format.test.ts +228 -0
  570. package/test/git/git.test.ts +178 -0
  571. package/test/ide/ide.test.ts +82 -0
  572. package/test/image/fixtures/picture-5mb-base64.png +0 -0
  573. package/test/image/image.test.ts +123 -0
  574. package/test/installation/installation.test.ts +230 -0
  575. package/test/lib/cli-process.ts +459 -0
  576. package/test/lib/effect.ts +177 -0
  577. package/test/lib/filesystem.ts +10 -0
  578. package/test/lib/llm-server.ts +779 -0
  579. package/test/lib/snapshot.ts +73 -0
  580. package/test/lib/test-provider.ts +37 -0
  581. package/test/lib/websocket.ts +46 -0
  582. package/test/lsp/client.test.ts +488 -0
  583. package/test/lsp/index.test.ts +232 -0
  584. package/test/lsp/jdtls-root.test.ts +459 -0
  585. package/test/lsp/launch.test.ts +22 -0
  586. package/test/lsp/lifecycle.test.ts +160 -0
  587. package/test/mcp/auth.test.ts +78 -0
  588. package/test/mcp/headers.test.ts +126 -0
  589. package/test/mcp/lifecycle.test.ts +1213 -0
  590. package/test/mcp/oauth-auto-connect.test.ts +276 -0
  591. package/test/mcp/oauth-browser.test.ts +239 -0
  592. package/test/mcp/oauth-callback.test.ts +34 -0
  593. package/test/mcp/oauth-provider.test.ts +61 -0
  594. package/test/mcp/session-recovery.test.ts +27 -0
  595. package/test/patch/patch.test.ts +383 -0
  596. package/test/permission/arity.test.ts +33 -0
  597. package/test/permission/next.test.ts +1176 -0
  598. package/test/permission-task.test.ts +318 -0
  599. package/test/plugin/auth-override.test.ts +105 -0
  600. package/test/plugin/cloudflare.test.ts +68 -0
  601. package/test/plugin/codex.test.ts +247 -0
  602. package/test/plugin/github-copilot-models.test.ts +332 -0
  603. package/test/plugin/install-concurrency.test.ts +140 -0
  604. package/test/plugin/install.test.ts +570 -0
  605. package/test/plugin/loader-shared.test.ts +1303 -0
  606. package/test/plugin/meta.test.ts +137 -0
  607. package/test/plugin/openai-rollout.test.ts +17 -0
  608. package/test/plugin/openai-ws.test.ts +877 -0
  609. package/test/plugin/shared.test.ts +88 -0
  610. package/test/plugin/snowflake-cortex.test.ts +278 -0
  611. package/test/plugin/trigger.test.ts +120 -0
  612. package/test/plugin/workspace-adapter.test.ts +140 -0
  613. package/test/plugin/xai.test.ts +634 -0
  614. package/test/preload.ts +92 -0
  615. package/test/project/instance-bootstrap.test.ts +110 -0
  616. package/test/project/instance.test.ts +245 -0
  617. package/test/project/migrate-global.test.ts +167 -0
  618. package/test/project/project-directory.test.ts +201 -0
  619. package/test/project/project.test.ts +815 -0
  620. package/test/project/vcs.test.ts +336 -0
  621. package/test/project/worktree-remove.test.ts +126 -0
  622. package/test/project/worktree.test.ts +320 -0
  623. package/test/provider/amazon-bedrock.test.ts +360 -0
  624. package/test/provider/cf-ai-gateway-e2e.test.ts +132 -0
  625. package/test/provider/digitalocean.test.ts +123 -0
  626. package/test/provider/gitlab-duo.test.ts +412 -0
  627. package/test/provider/header-timeout.test.ts +233 -0
  628. package/test/provider/model-status.test.ts +61 -0
  629. package/test/provider/provider.test.ts +1793 -0
  630. package/test/provider/transform.test.ts +4207 -0
  631. package/test/question/question.test.ts +465 -0
  632. package/test/server/AGENTS.md +15 -0
  633. package/test/server/auth.test.ts +59 -0
  634. package/test/server/global-bus.ts +31 -0
  635. package/test/server/global-session-list.test.ts +104 -0
  636. package/test/server/httpapi-authorization.test.ts +174 -0
  637. package/test/server/httpapi-compression.test.ts +151 -0
  638. package/test/server/httpapi-config.test.ts +110 -0
  639. package/test/server/httpapi-control-plane.test.ts +63 -0
  640. package/test/server/httpapi-cors-vary.test.ts +63 -0
  641. package/test/server/httpapi-cors.test.ts +122 -0
  642. package/test/server/httpapi-error-middleware.test.ts +101 -0
  643. package/test/server/httpapi-event.test.ts +94 -0
  644. package/test/server/httpapi-exercise/assertions.ts +64 -0
  645. package/test/server/httpapi-exercise/backend.ts +144 -0
  646. package/test/server/httpapi-exercise/dsl.ts +210 -0
  647. package/test/server/httpapi-exercise/environment.ts +40 -0
  648. package/test/server/httpapi-exercise/index.ts +1685 -0
  649. package/test/server/httpapi-exercise/report.ts +66 -0
  650. package/test/server/httpapi-exercise/routing.ts +96 -0
  651. package/test/server/httpapi-exercise/runner.ts +267 -0
  652. package/test/server/httpapi-exercise/runtime.ts +52 -0
  653. package/test/server/httpapi-exercise/types.ts +123 -0
  654. package/test/server/httpapi-experimental.test.ts +297 -0
  655. package/test/server/httpapi-file.test.ts +73 -0
  656. package/test/server/httpapi-global.test.ts +66 -0
  657. package/test/server/httpapi-instance-context.test.ts +348 -0
  658. package/test/server/httpapi-instance-route-auth.test.ts +81 -0
  659. package/test/server/httpapi-instance.test.ts +265 -0
  660. package/test/server/httpapi-layer.ts +33 -0
  661. package/test/server/httpapi-listen.test.ts +412 -0
  662. package/test/server/httpapi-mcp-oauth.test.ts +73 -0
  663. package/test/server/httpapi-mcp.test.ts +223 -0
  664. package/test/server/httpapi-mdns.test.ts +79 -0
  665. package/test/server/httpapi-promptasync-context.test.ts +223 -0
  666. package/test/server/httpapi-provider.test.ts +400 -0
  667. package/test/server/httpapi-pty.test.ts +299 -0
  668. package/test/server/httpapi-public-openapi.test.ts +319 -0
  669. package/test/server/httpapi-query-schema-drift.test.ts +330 -0
  670. package/test/server/httpapi-reference.test.ts +62 -0
  671. package/test/server/httpapi-schema-error-body.test.ts +165 -0
  672. package/test/server/httpapi-sdk.test.ts +909 -0
  673. package/test/server/httpapi-session.test.ts +1011 -0
  674. package/test/server/httpapi-sync.test.ts +148 -0
  675. package/test/server/httpapi-ui.test.ts +453 -0
  676. package/test/server/httpapi-v2-location.test.ts +82 -0
  677. package/test/server/httpapi-v2-pty.test.ts +250 -0
  678. package/test/server/httpapi-workspace-routing.test.ts +555 -0
  679. package/test/server/httpapi-workspace.test.ts +513 -0
  680. package/test/server/negative-tokens-regression.test.ts +83 -0
  681. package/test/server/project-copy.test.ts +121 -0
  682. package/test/server/project-init-git.test.ts +114 -0
  683. package/test/server/proxy-util.test.ts +113 -0
  684. package/test/server/sdk-error-shape.test.ts +81 -0
  685. package/test/server/sdk-v1-smoke.test.ts +57 -0
  686. package/test/server/session-actions.test.ts +109 -0
  687. package/test/server/session-diff-missing-patch.test.ts +96 -0
  688. package/test/server/session-list.test.ts +312 -0
  689. package/test/server/session-messages.test.ts +179 -0
  690. package/test/server/session-select.test.ts +66 -0
  691. package/test/server/workspace-proxy.test.ts +181 -0
  692. package/test/server/workspace-routing.test.ts +94 -0
  693. package/test/server/worktree-endpoint-repro.test.ts +307 -0
  694. package/test/session/compaction.test.ts +1834 -0
  695. package/test/session/instruction.test.ts +256 -0
  696. package/test/session/llm-native-recorded.test.ts +433 -0
  697. package/test/session/llm-native.test.ts +760 -0
  698. package/test/session/llm.test.ts +1932 -0
  699. package/test/session/message-v2.test.ts +1661 -0
  700. package/test/session/messages-pagination.test.ts +1056 -0
  701. package/test/session/processor-effect.test.ts +1076 -0
  702. package/test/session/prompt.test.ts +2326 -0
  703. package/test/session/retry.test.ts +439 -0
  704. package/test/session/revert-compact.test.ts +639 -0
  705. package/test/session/schema-decoding.test.ts +313 -0
  706. package/test/session/session-schema.test.ts +78 -0
  707. package/test/session/session.test.ts +248 -0
  708. package/test/session/snapshot-tool-race.test.ts +190 -0
  709. package/test/session/structured-output-integration.test.ts +235 -0
  710. package/test/session/structured-output.test.ts +387 -0
  711. package/test/session/system.test.ts +86 -0
  712. package/test/session/ultrawork.test.ts +25 -0
  713. package/test/share/share-next.test.ts +326 -0
  714. package/test/skill/discovery.test.ts +139 -0
  715. package/test/skill/skill.test.ts +571 -0
  716. package/test/snapshot/snapshot.test.ts +1121 -0
  717. package/test/storage/storage.test.ts +296 -0
  718. package/test/tool/__snapshots__/parameters.test.ts.snap +484 -0
  719. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  720. package/test/tool/apply_patch.test.ts +533 -0
  721. package/test/tool/edit.test.ts +578 -0
  722. package/test/tool/external-directory.test.ts +155 -0
  723. package/test/tool/fixtures/large-image.png +0 -0
  724. package/test/tool/fixtures/models-api.json +117299 -0
  725. package/test/tool/glob.test.ts +136 -0
  726. package/test/tool/grep.test.ts +225 -0
  727. package/test/tool/lsp.test.ts +181 -0
  728. package/test/tool/parameters.test.ts +293 -0
  729. package/test/tool/question.test.ts +138 -0
  730. package/test/tool/read.test.ts +605 -0
  731. package/test/tool/registry.test.ts +497 -0
  732. package/test/tool/shell.test.ts +1238 -0
  733. package/test/tool/skill.test.ts +136 -0
  734. package/test/tool/task.test.ts +898 -0
  735. package/test/tool/tool-define.test.ts +153 -0
  736. package/test/tool/truncation.test.ts +266 -0
  737. package/test/tool/webfetch.test.ts +113 -0
  738. package/test/tool/websearch.test.ts +99 -0
  739. package/test/tool/write.test.ts +276 -0
  740. package/test/util/data-url.test.ts +14 -0
  741. package/test/util/error.test.ts +16 -0
  742. package/test/util/filesystem.test.ts +656 -0
  743. package/test/util/glob.test.ts +164 -0
  744. package/test/util/iife.test.ts +36 -0
  745. package/test/util/lazy.test.ts +50 -0
  746. package/test/util/module.test.ts +59 -0
  747. package/test/util/process.test.ts +128 -0
  748. package/test/util/repository.test.ts +93 -0
  749. package/test/util/timeout.test.ts +21 -0
  750. package/test/util/wildcard.test.ts +90 -0
  751. package/test/v2/session-message-updater.test.ts +269 -0
  752. package/tsconfig.json +16 -0
@@ -0,0 +1,2326 @@
1
+ import { NodeFileSystem } from "@effect/platform-node"
2
+ import { ConfigV1 } from "@miaw/core/v1/config/config"
3
+ import { SessionV1 } from "@miaw/core/v1/session"
4
+ import { Database } from "@miaw/core/database/database"
5
+ import { eq } from "drizzle-orm"
6
+ import { EventV2Bridge } from "@/event-v2-bridge"
7
+ import { FetchHttpClient } from "effect/unstable/http"
8
+ import { expect } from "bun:test"
9
+ import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer } from "effect"
10
+ import path from "path"
11
+ import { fileURLToPath, pathToFileURL } from "url"
12
+ import { NamedError } from "@miaw/core/util/error"
13
+ import { Agent as AgentSvc } from "../../src/agent/agent"
14
+ import { BackgroundJob } from "@/background/job"
15
+ import { Command } from "../../src/command"
16
+ import { Config } from "@/config/config"
17
+ import { LSP } from "@/lsp/lsp"
18
+ import { MCP } from "../../src/mcp"
19
+ import { Permission } from "../../src/permission"
20
+ import { Plugin } from "../../src/plugin"
21
+ import { Provider as ProviderSvc } from "@/provider/provider"
22
+ import { Env } from "../../src/env"
23
+ import { Git } from "../../src/git"
24
+ import { Image } from "../../src/image/image"
25
+
26
+ import { Question } from "../../src/question"
27
+ import { Todo } from "../../src/session/todo"
28
+ import { Session } from "@/session/session"
29
+ import { SessionMessageTable } from "@miaw/core/session/sql"
30
+ import { LLM } from "../../src/session/llm"
31
+ import { MessageV2 } from "../../src/session/message-v2"
32
+ import { FSUtil } from "@miaw/core/fs-util"
33
+ import { SessionCompaction } from "../../src/session/compaction"
34
+ import { SessionSummary } from "../../src/session/summary"
35
+ import { Instruction } from "../../src/session/instruction"
36
+ import { SessionProcessor } from "../../src/session/processor"
37
+ import { SessionPrompt } from "../../src/session/prompt"
38
+ import { SessionRevert } from "../../src/session/revert"
39
+ import { SessionRunState } from "../../src/session/run-state"
40
+ import { MessageID, PartID, SessionID } from "../../src/session/schema"
41
+ import { SessionStatus } from "../../src/session/status"
42
+ import { SessionV2 } from "@miaw/core/session"
43
+ import { SessionExecution } from "@miaw/core/session/execution"
44
+ import { Skill } from "../../src/skill"
45
+ import { SystemPrompt } from "../../src/session/system"
46
+ import { Shell } from "@miaw/core/shell"
47
+ import { Snapshot } from "../../src/snapshot"
48
+ import { ToolRegistry } from "@/tool/registry"
49
+ import { Truncate } from "@/tool/truncate"
50
+ import { CrossSpawnSpawner } from "@miaw/core/cross-spawn-spawner"
51
+ import { Ripgrep } from "@miaw/core/ripgrep"
52
+ import { Format } from "../../src/format"
53
+ import { TestInstance } from "../fixture/fixture"
54
+ import { awaitWithTimeout, pollWithTimeout, testEffect } from "../lib/effect"
55
+ import { reply, TestLLMServer } from "../lib/llm-server"
56
+ import { RuntimeFlags } from "@/effect/runtime-flags"
57
+ import { ProviderV2 } from "@miaw/core/provider"
58
+ import { ModelV2 } from "@miaw/core/model"
59
+
60
+ const summary = Layer.succeed(
61
+ SessionSummary.Service,
62
+ SessionSummary.Service.of({
63
+ summarize: () => Effect.void,
64
+ diff: () => Effect.succeed([]),
65
+ computeDiff: () => Effect.succeed([]),
66
+ }),
67
+ )
68
+
69
+ const ref = {
70
+ providerID: ProviderV2.ID.make("test"),
71
+ modelID: ModelV2.ID.make("test-model"),
72
+ }
73
+
74
+ function withSh<A, E, R>(fx: () => Effect.Effect<A, E, R>) {
75
+ return Effect.acquireUseRelease(
76
+ Effect.sync(() => {
77
+ const prev = process.env.SHELL
78
+ process.env.SHELL = "/bin/sh"
79
+ Shell.preferred.reset()
80
+ return prev
81
+ }),
82
+ () => fx(),
83
+ (prev) =>
84
+ Effect.sync(() => {
85
+ if (prev === undefined) delete process.env.SHELL
86
+ else process.env.SHELL = prev
87
+ Shell.preferred.reset()
88
+ }),
89
+ )
90
+ }
91
+
92
+ function toolPart(parts: SessionV1.Part[]) {
93
+ return parts.find((part): part is SessionV1.ToolPart => part.type === "tool")
94
+ }
95
+
96
+ type CompletedToolPart = SessionV1.ToolPart & { state: SessionV1.ToolStateCompleted }
97
+ type ErrorToolPart = SessionV1.ToolPart & { state: SessionV1.ToolStateError }
98
+
99
+ function completedTool(parts: SessionV1.Part[]) {
100
+ const part = toolPart(parts)
101
+ expect(part?.state.status).toBe("completed")
102
+ return part?.state.status === "completed" ? (part as CompletedToolPart) : undefined
103
+ }
104
+
105
+ function errorTool(parts: SessionV1.Part[]) {
106
+ const part = toolPart(parts)
107
+ expect(part?.state.status).toBe("error")
108
+ return part?.state.status === "error" ? (part as ErrorToolPart) : undefined
109
+ }
110
+
111
+ const mcp = Layer.succeed(
112
+ MCP.Service,
113
+ MCP.Service.of({
114
+ status: () => Effect.succeed({}),
115
+ clients: () => Effect.succeed({}),
116
+ tools: () => Effect.succeed({}),
117
+ prompts: () => Effect.succeed({}),
118
+ resources: () => Effect.succeed({}),
119
+ add: () => Effect.succeed({ status: { status: "disabled" as const } }),
120
+ connect: () => Effect.void,
121
+ disconnect: () => Effect.void,
122
+ getPrompt: () => Effect.succeed(undefined),
123
+ readResource: () => Effect.succeed(undefined),
124
+ startAuth: () => Effect.die("unexpected MCP auth in prompt-effect tests"),
125
+ authenticate: () => Effect.die("unexpected MCP auth in prompt-effect tests"),
126
+ finishAuth: () => Effect.die("unexpected MCP auth in prompt-effect tests"),
127
+ removeAuth: () => Effect.void,
128
+ supportsOAuth: () => Effect.succeed(false),
129
+ hasStoredTokens: () => Effect.succeed(false),
130
+ getAuthStatus: () => Effect.succeed("not_authenticated" as const),
131
+ }),
132
+ )
133
+
134
+ const lsp = Layer.succeed(
135
+ LSP.Service,
136
+ LSP.Service.of({
137
+ init: () => Effect.void,
138
+ status: () => Effect.succeed([]),
139
+ hasClients: () => Effect.succeed(false),
140
+ touchFile: () => Effect.void,
141
+ diagnostics: () => Effect.succeed({}),
142
+ hover: () => Effect.succeed(undefined),
143
+ definition: () => Effect.succeed([]),
144
+ references: () => Effect.succeed([]),
145
+ implementation: () => Effect.succeed([]),
146
+ documentSymbol: () => Effect.succeed([]),
147
+ workspaceSymbol: () => Effect.succeed([]),
148
+ prepareCallHierarchy: () => Effect.succeed([]),
149
+ incomingCalls: () => Effect.succeed([]),
150
+ outgoingCalls: () => Effect.succeed([]),
151
+ }),
152
+ )
153
+
154
+ const status = SessionStatus.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer))
155
+ const run = SessionRunState.layer.pipe(Layer.provide(status))
156
+ const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer)
157
+
158
+ const processorCreateStarted: Array<() => void> = []
159
+ const blockingProcessor = Layer.succeed(
160
+ SessionProcessor.Service,
161
+ SessionProcessor.Service.of({
162
+ create: () => Effect.sync(() => processorCreateStarted.shift()?.()).pipe(Effect.andThen(Effect.never)),
163
+ }),
164
+ )
165
+
166
+ function makePrompt(input?: { processor?: "blocking" }) {
167
+ const deps = Layer.mergeAll(
168
+ Session.defaultLayer,
169
+ Snapshot.defaultLayer,
170
+ LLM.defaultLayer,
171
+ Env.defaultLayer,
172
+ AgentSvc.defaultLayer,
173
+ Command.defaultLayer,
174
+ Permission.defaultLayer,
175
+ Plugin.defaultLayer,
176
+ Config.defaultLayer,
177
+ ProviderSvc.defaultLayer,
178
+ lsp,
179
+ mcp,
180
+ FSUtil.defaultLayer,
181
+ BackgroundJob.defaultLayer,
182
+ status,
183
+ Database.defaultLayer,
184
+ EventV2Bridge.defaultLayer,
185
+ ).pipe(Layer.provideMerge(infra))
186
+ const question = Question.layer.pipe(Layer.provideMerge(deps))
187
+ const todo = Todo.layer.pipe(Layer.provideMerge(deps))
188
+ const registry = ToolRegistry.layer.pipe(
189
+ Layer.provide(Skill.defaultLayer),
190
+ Layer.provide(FetchHttpClient.layer),
191
+ Layer.provide(CrossSpawnSpawner.defaultLayer),
192
+ Layer.provide(Git.defaultLayer),
193
+ Layer.provide(Ripgrep.defaultLayer),
194
+ Layer.provide(Format.defaultLayer),
195
+ Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })),
196
+ Layer.provideMerge(todo),
197
+ Layer.provideMerge(question),
198
+ Layer.provideMerge(deps),
199
+ )
200
+ const trunc = Truncate.layer.pipe(Layer.provideMerge(deps))
201
+ const proc =
202
+ input?.processor === "blocking"
203
+ ? blockingProcessor
204
+ : SessionProcessor.layer.pipe(
205
+ Layer.provide(summary),
206
+ Layer.provide(Image.defaultLayer),
207
+ Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })),
208
+ Layer.provideMerge(deps),
209
+ )
210
+ const compact = SessionCompaction.layer.pipe(
211
+ Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })),
212
+ Layer.provideMerge(proc),
213
+ Layer.provideMerge(deps),
214
+ )
215
+ return SessionPrompt.layer.pipe(
216
+ Layer.provide(SessionRevert.defaultLayer),
217
+ Layer.provide(Image.defaultLayer),
218
+ Layer.provide(summary),
219
+ Layer.provideMerge(run),
220
+ Layer.provideMerge(compact),
221
+ Layer.provideMerge(proc),
222
+ Layer.provideMerge(registry),
223
+ Layer.provideMerge(trunc),
224
+ Layer.provide(Instruction.defaultLayer),
225
+ Layer.provide(SystemPrompt.defaultLayer),
226
+ Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })),
227
+ Layer.provideMerge(deps),
228
+ Layer.provide(summary),
229
+ )
230
+ }
231
+
232
+ function makeHttp(input?: { processor?: "blocking" }) {
233
+ return Layer.mergeAll(TestLLMServer.layer, makePrompt(input))
234
+ }
235
+
236
+ function makeHttpNoLLMServer(input?: { processor?: "blocking" }) {
237
+ return makePrompt(input)
238
+ }
239
+
240
+ const it = testEffect(makeHttp())
241
+ const noLLMServer = testEffect(makeHttpNoLLMServer())
242
+ const raceNoLLMServer = testEffect(makeHttpNoLLMServer({ processor: "blocking" }))
243
+ const unix = process.platform !== "win32" ? it.instance : it.instance.skip
244
+ const unixNoLLMServer = process.platform !== "win32" ? noLLMServer.instance : noLLMServer.instance.skip
245
+
246
+ // Config that registers a custom "test" provider with a "test-model" model
247
+ // so provider model lookup succeeds inside the loop.
248
+ const cfg = {
249
+ provider: {
250
+ test: {
251
+ name: "Test",
252
+ id: "test",
253
+ env: [],
254
+ npm: "@ai-sdk/openai-compatible",
255
+ models: {
256
+ "test-model": {
257
+ id: "test-model",
258
+ name: "Test Model",
259
+ attachment: false,
260
+ reasoning: false,
261
+ temperature: false,
262
+ tool_call: true,
263
+ release_date: "2025-01-01",
264
+ limit: { context: 100000, output: 10000 },
265
+ cost: { input: 0, output: 0 },
266
+ options: {},
267
+ },
268
+ },
269
+ options: {
270
+ apiKey: "test-key",
271
+ baseURL: "http://localhost:1/v1",
272
+ },
273
+ },
274
+ },
275
+ }
276
+
277
+ function providerCfg(url: string) {
278
+ return {
279
+ ...cfg,
280
+ provider: {
281
+ ...cfg.provider,
282
+ test: {
283
+ ...cfg.provider.test,
284
+ options: {
285
+ ...cfg.provider.test.options,
286
+ baseURL: url,
287
+ },
288
+ },
289
+ },
290
+ }
291
+ }
292
+
293
+ const writeText = Effect.fn("test.writeText")(function* (file: string, text: string) {
294
+ const fs = yield* FSUtil.Service
295
+ yield* fs.writeWithDirs(file, text)
296
+ })
297
+
298
+ const ensureDir = Effect.fn("test.ensureDir")(function* (dir: string) {
299
+ const fs = yield* FSUtil.Service
300
+ yield* fs.ensureDir(dir)
301
+ })
302
+
303
+ const writeConfig = Effect.fn("test.writeConfig")(function* (dir: string, config: Partial<ConfigV1.Info>) {
304
+ yield* writeText(
305
+ path.join(dir, "miaw.json"),
306
+ JSON.stringify({ $schema: "https://miaw/config.json", ...config }),
307
+ )
308
+ })
309
+
310
+ const useServerConfig = Effect.fn("test.useServerConfig")(function* (config: (url: string) => Partial<ConfigV1.Info>) {
311
+ const { directory: dir } = yield* TestInstance
312
+ const llm = yield* TestLLMServer
313
+ yield* writeConfig(dir, config(llm.url))
314
+ return { dir, llm }
315
+ })
316
+
317
+ // Wait for a session's runner to enter a busy state. SessionStatus is flipped
318
+ // inside Runner.startShell's serialized transition, so cancel can't no-op once
319
+ // we observe it.
320
+ const waitForBusy = (sessionID: SessionID, duration: Duration.Input = "2 seconds") =>
321
+ pollWithTimeout(
322
+ Effect.gen(function* () {
323
+ const status = yield* SessionStatus.Service
324
+ const s = yield* status.get(sessionID)
325
+ return s.type === "busy" ? (true as const) : undefined
326
+ }),
327
+ `session ${sessionID} never became busy`,
328
+ duration,
329
+ )
330
+
331
+ const hasBash = Effect.sync(() => Bun.which("bash") !== null)
332
+
333
+ const deferredAsPromise = <A>(deferred: Deferred.Deferred<A>): PromiseLike<A> => ({
334
+ then: (onfulfilled, onrejected) => {
335
+ Effect.runFork(
336
+ Deferred.await(deferred).pipe(
337
+ Effect.match({
338
+ onFailure: (error) => {
339
+ onrejected?.(error)
340
+ },
341
+ onSuccess: (value) => {
342
+ onfulfilled?.(value)
343
+ },
344
+ }),
345
+ ),
346
+ )
347
+ return deferredAsPromise(deferred) as PromiseLike<never>
348
+ },
349
+ })
350
+
351
+ function defer<T>() {
352
+ let resolve!: (value: T | PromiseLike<T>) => void
353
+ const promise = new Promise<T>((done) => {
354
+ resolve = done
355
+ })
356
+ return { promise, resolve }
357
+ }
358
+
359
+ const succeedVoid = (deferred: Deferred.Deferred<void>) => {
360
+ Effect.runSync(Deferred.succeed(deferred, void 0).pipe(Effect.ignore))
361
+ }
362
+
363
+ const user = Effect.fn("test.user")(function* (sessionID: SessionID, text: string) {
364
+ const session = yield* Session.Service
365
+ const msg = yield* session.updateMessage({
366
+ id: MessageID.ascending(),
367
+ role: "user",
368
+ sessionID,
369
+ agent: "build",
370
+ model: ref,
371
+ time: { created: Date.now() },
372
+ })
373
+ yield* session.updatePart({
374
+ id: PartID.ascending(),
375
+ messageID: msg.id,
376
+ sessionID,
377
+ type: "text",
378
+ text,
379
+ })
380
+ return msg
381
+ })
382
+
383
+ const seed = Effect.fn("test.seed")(function* (sessionID: SessionID, opts?: { finish?: string }) {
384
+ const session = yield* Session.Service
385
+ const msg = yield* user(sessionID, "hello")
386
+ const assistant: SessionV1.Assistant = {
387
+ id: MessageID.ascending(),
388
+ role: "assistant",
389
+ parentID: msg.id,
390
+ sessionID,
391
+ mode: "build",
392
+ agent: "build",
393
+ cost: 0,
394
+ path: { cwd: "/tmp", root: "/tmp" },
395
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
396
+ modelID: ref.modelID,
397
+ providerID: ref.providerID,
398
+ time: { created: Date.now() },
399
+ ...(opts?.finish ? { finish: opts.finish } : {}),
400
+ }
401
+ yield* session.updateMessage(assistant)
402
+ yield* session.updatePart({
403
+ id: PartID.ascending(),
404
+ messageID: assistant.id,
405
+ sessionID,
406
+ type: "text",
407
+ text: "hi there",
408
+ })
409
+ return { user: msg, assistant }
410
+ })
411
+
412
+ const addSubtask = (sessionID: SessionID, messageID: MessageID, model = ref) =>
413
+ Effect.gen(function* () {
414
+ const session = yield* Session.Service
415
+ yield* session.updatePart({
416
+ id: PartID.ascending(),
417
+ messageID,
418
+ sessionID,
419
+ type: "subtask",
420
+ prompt: "look into the cache key path",
421
+ description: "inspect bug",
422
+ agent: "general",
423
+ model,
424
+ })
425
+ })
426
+
427
+ const boot = Effect.fn("test.boot")(function* (input?: { title?: string }) {
428
+ const config = yield* Config.Service
429
+ const prompt = yield* SessionPrompt.Service
430
+ const run = yield* SessionRunState.Service
431
+ const sessions = yield* Session.Service
432
+ yield* config.get()
433
+ const chat = yield* sessions.create(input ?? { title: "Pinned" })
434
+ return { prompt, run, sessions, chat }
435
+ })
436
+
437
+ // Loop semantics
438
+
439
+ noLLMServer.instance(
440
+ "loop exits immediately when last assistant has stop finish",
441
+ () =>
442
+ Effect.gen(function* () {
443
+ const prompt = yield* SessionPrompt.Service
444
+ const sessions = yield* Session.Service
445
+ const chat = yield* sessions.create({ title: "Pinned" })
446
+ yield* seed(chat.id, { finish: "stop" })
447
+
448
+ const result = yield* prompt.loop({ sessionID: chat.id })
449
+ expect(result.info.role).toBe("assistant")
450
+ if (result.info.role === "assistant") expect(result.info.finish).toBe("stop")
451
+ }),
452
+ { config: cfg },
453
+ )
454
+
455
+ it.instance("loop exits without an LLM request for interrupted orphan tool calls", () =>
456
+ Effect.gen(function* () {
457
+ const { llm } = yield* useServerConfig(providerCfg)
458
+ const prompt = yield* SessionPrompt.Service
459
+ const sessions = yield* Session.Service
460
+ const chat = yield* sessions.create({ title: "Pinned" })
461
+ const seeded = yield* seed(chat.id, { finish: "stop" })
462
+ yield* sessions.updatePart({
463
+ id: PartID.ascending(),
464
+ messageID: seeded.assistant.id,
465
+ sessionID: chat.id,
466
+ type: "tool",
467
+ callID: "interrupted-call",
468
+ tool: "edit",
469
+ state: {
470
+ status: "error",
471
+ input: {},
472
+ error: "Tool execution aborted",
473
+ metadata: { interrupted: true },
474
+ time: { start: 1, end: 2 },
475
+ },
476
+ })
477
+
478
+ const result = yield* prompt.loop({ sessionID: chat.id })
479
+ expect(result.info.id).toBe(seeded.assistant.id)
480
+ expect(yield* llm.hits).toHaveLength(0)
481
+ }),
482
+ )
483
+
484
+ it.instance("loop calls LLM and returns assistant message", () =>
485
+ Effect.gen(function* () {
486
+ const { llm } = yield* useServerConfig(providerCfg)
487
+ const prompt = yield* SessionPrompt.Service
488
+ const sessions = yield* Session.Service
489
+ const chat = yield* sessions.create({
490
+ title: "Pinned",
491
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
492
+ })
493
+ yield* prompt.prompt({
494
+ sessionID: chat.id,
495
+ agent: "build",
496
+ noReply: true,
497
+ parts: [{ type: "text", text: "hello" }],
498
+ })
499
+ yield* llm.text("world")
500
+
501
+ const result = yield* prompt.loop({ sessionID: chat.id })
502
+ expect(result.info.role).toBe("assistant")
503
+ const parts = result.parts.filter((p) => p.type === "text")
504
+ expect(parts.some((p) => p.type === "text" && p.text === "world")).toBe(true)
505
+ expect(yield* llm.hits).toHaveLength(1)
506
+ }),
507
+ )
508
+
509
+ it.instance("loop surfaces content-filter finishes as session errors", () =>
510
+ Effect.gen(function* () {
511
+ const { llm } = yield* useServerConfig(providerCfg)
512
+ const events = yield* EventV2Bridge.Service
513
+ const prompt = yield* SessionPrompt.Service
514
+ const sessions = yield* Session.Service
515
+ const chat = yield* sessions.create({ title: "Pinned" })
516
+ const errors: NonNullable<SessionV1.Assistant["error"]>[] = []
517
+ const expected = {
518
+ name: "ContentFilterError",
519
+ data: { message: "The response was blocked by the provider's content filter" },
520
+ } satisfies NonNullable<SessionV1.Assistant["error"]>
521
+ const off = yield* events.listen((event) => {
522
+ if (event.type !== Session.Event.Error.type) return Effect.void
523
+ const data = event.data as typeof Session.Event.Error.data.Type
524
+ if (data.sessionID === chat.id && data.error) errors.push(data.error)
525
+ return Effect.void
526
+ })
527
+
528
+ yield* prompt.prompt({
529
+ sessionID: chat.id,
530
+ agent: "build",
531
+ noReply: true,
532
+ parts: [{ type: "text", text: "hello" }],
533
+ })
534
+ yield* llm.push(reply().text("partial response").contentFilter())
535
+
536
+ const result = yield* prompt.loop({ sessionID: chat.id })
537
+ const stored = yield* MessageV2.get({ sessionID: chat.id, messageID: result.info.id })
538
+ yield* off
539
+
540
+ expect(yield* llm.hits).toHaveLength(1)
541
+ expect(result.info.role).toBe("assistant")
542
+ expect(stored.info.role).toBe("assistant")
543
+ if (result.info.role === "assistant" && stored.info.role === "assistant") {
544
+ expect(result.info.finish).toBe("content-filter")
545
+ expect(result.info.error).toEqual(expected)
546
+ expect(stored.info.error).toEqual(result.info.error)
547
+ expect(errors).toContainEqual(expected)
548
+ }
549
+ expect(result.parts).toEqual(
550
+ expect.arrayContaining([expect.objectContaining({ type: "text", text: "partial response" })]),
551
+ )
552
+ }),
553
+ )
554
+
555
+ it.instance("loop stops provider overflow instead of auto-compacting when disabled", () =>
556
+ Effect.gen(function* () {
557
+ const { llm } = yield* useServerConfig((url) => ({
558
+ ...providerCfg(url),
559
+ compaction: { auto: false },
560
+ }))
561
+ const prompt = yield* SessionPrompt.Service
562
+ const sessions = yield* Session.Service
563
+ const chat = yield* sessions.create({ title: "Pinned" })
564
+
565
+ yield* llm.error(413, { error: { message: "request entity too large" } })
566
+ yield* prompt.prompt({
567
+ sessionID: chat.id,
568
+ agent: "build",
569
+ noReply: true,
570
+ parts: [{ type: "text", text: "hello" }],
571
+ })
572
+
573
+ const result = yield* prompt.loop({ sessionID: chat.id })
574
+ const messages = yield* sessions.messages({ sessionID: chat.id })
575
+
576
+ expect(result.info.role).toBe("assistant")
577
+ if (result.info.role === "assistant") {
578
+ expect(result.info.error?.name).toBe("ContextOverflowError")
579
+ expect(result.info.finish).toBe("error")
580
+ }
581
+ expect(messages.some((message) => message.parts.some((part) => part.type === "compaction"))).toBe(false)
582
+ }),
583
+ )
584
+
585
+ noLLMServer.instance.skip(
586
+ "prompt emits v2 prompted and synthetic events (v2 projector disabled)",
587
+ () =>
588
+ Effect.gen(function* () {
589
+ const prompt = yield* SessionPrompt.Service
590
+ const sessions = yield* Session.Service
591
+ const chat = yield* sessions.create({ title: "Pinned" })
592
+
593
+ yield* prompt.prompt({
594
+ sessionID: chat.id,
595
+ agent: "build",
596
+ noReply: true,
597
+ parts: [
598
+ { type: "text", text: "hello v2" },
599
+ {
600
+ type: "file",
601
+ mime: "text/plain",
602
+ filename: "note.txt",
603
+ url: "data:text/plain;base64,bm90ZSBjb250ZW50",
604
+ },
605
+ ],
606
+ })
607
+
608
+ const messages = yield* SessionV2.Service.use((session) => session.messages({ sessionID: chat.id })).pipe(
609
+ Effect.provide(SessionExecution.noopLayer),
610
+ Effect.provide(SessionV2.defaultLayer),
611
+ )
612
+ const { db } = yield* Database.Service
613
+ const row = yield* db
614
+ .select()
615
+ .from(SessionMessageTable)
616
+ .where(eq(SessionMessageTable.session_id, chat.id))
617
+ .get()
618
+ .pipe(Effect.orDie)
619
+ expect(messages.find((message) => message.type === "user")).toMatchObject({ type: "user", text: "hello v2" })
620
+ expect(typeof row?.data.time.created).toBe("number")
621
+ expect(messages).toEqual(
622
+ expect.arrayContaining([
623
+ expect.objectContaining({ type: "synthetic", text: expect.stringContaining("Called the Read tool") }),
624
+ expect.objectContaining({ type: "synthetic", text: "note content" }),
625
+ ]),
626
+ )
627
+ }),
628
+ { config: cfg },
629
+ )
630
+
631
+ it.instance("static loop returns assistant text through local provider", () =>
632
+ Effect.gen(function* () {
633
+ const { llm } = yield* useServerConfig(providerCfg)
634
+ const prompt = yield* SessionPrompt.Service
635
+ const sessions = yield* Session.Service
636
+ const session = yield* sessions.create({
637
+ title: "Prompt provider",
638
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
639
+ })
640
+
641
+ yield* prompt.prompt({
642
+ sessionID: session.id,
643
+ agent: "build",
644
+ noReply: true,
645
+ parts: [{ type: "text", text: "hello" }],
646
+ })
647
+
648
+ yield* llm.text("world")
649
+
650
+ const result = yield* prompt.loop({ sessionID: session.id })
651
+ expect(result.info.role).toBe("assistant")
652
+ expect(result.parts.some((part) => part.type === "text" && part.text === "world")).toBe(true)
653
+ expect(yield* llm.hits).toHaveLength(1)
654
+ expect(yield* llm.pending).toBe(0)
655
+ }),
656
+ )
657
+
658
+ it.instance("static loop consumes queued replies across turns", () =>
659
+ Effect.gen(function* () {
660
+ const { llm } = yield* useServerConfig(providerCfg)
661
+ const prompt = yield* SessionPrompt.Service
662
+ const sessions = yield* Session.Service
663
+ const session = yield* sessions.create({
664
+ title: "Prompt provider turns",
665
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
666
+ })
667
+
668
+ yield* prompt.prompt({
669
+ sessionID: session.id,
670
+ agent: "build",
671
+ noReply: true,
672
+ parts: [{ type: "text", text: "hello one" }],
673
+ })
674
+
675
+ yield* llm.text("world one")
676
+
677
+ const first = yield* prompt.loop({ sessionID: session.id })
678
+ expect(first.info.role).toBe("assistant")
679
+ expect(first.parts.some((part) => part.type === "text" && part.text === "world one")).toBe(true)
680
+
681
+ yield* prompt.prompt({
682
+ sessionID: session.id,
683
+ agent: "build",
684
+ noReply: true,
685
+ parts: [{ type: "text", text: "hello two" }],
686
+ })
687
+
688
+ yield* llm.text("world two")
689
+
690
+ const second = yield* prompt.loop({ sessionID: session.id })
691
+ expect(second.info.role).toBe("assistant")
692
+ expect(second.parts.some((part) => part.type === "text" && part.text === "world two")).toBe(true)
693
+
694
+ expect(yield* llm.hits).toHaveLength(2)
695
+ expect(yield* llm.pending).toBe(0)
696
+ }),
697
+ )
698
+
699
+ it.instance("loop continues when finish is tool-calls", () =>
700
+ Effect.gen(function* () {
701
+ const { llm } = yield* useServerConfig(providerCfg)
702
+ const prompt = yield* SessionPrompt.Service
703
+ const sessions = yield* Session.Service
704
+ const session = yield* sessions.create({
705
+ title: "Pinned",
706
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
707
+ })
708
+ yield* prompt.prompt({
709
+ sessionID: session.id,
710
+ agent: "build",
711
+ noReply: true,
712
+ parts: [{ type: "text", text: "hello" }],
713
+ })
714
+ yield* llm.tool("first", { value: "first" })
715
+ yield* llm.text("second")
716
+
717
+ const result = yield* prompt.loop({ sessionID: session.id })
718
+ expect(yield* llm.calls).toBe(2)
719
+ expect(result.info.role).toBe("assistant")
720
+ if (result.info.role === "assistant") {
721
+ expect(result.parts.some((part) => part.type === "text" && part.text === "second")).toBe(true)
722
+ expect(result.info.finish).toBe("stop")
723
+ }
724
+ }),
725
+ )
726
+
727
+ it.instance("glob tool keeps instance context during prompt runs", () =>
728
+ Effect.gen(function* () {
729
+ const { dir, llm } = yield* useServerConfig(providerCfg)
730
+ const prompt = yield* SessionPrompt.Service
731
+ const sessions = yield* Session.Service
732
+ const session = yield* sessions.create({
733
+ title: "Glob context",
734
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
735
+ })
736
+ const file = path.join(dir, "probe.txt")
737
+ yield* writeText(file, "probe")
738
+
739
+ yield* prompt.prompt({
740
+ sessionID: session.id,
741
+ agent: "build",
742
+ noReply: true,
743
+ parts: [{ type: "text", text: "find text files" }],
744
+ })
745
+ yield* llm.tool("glob", { pattern: "**/*.txt" })
746
+ yield* llm.text("done")
747
+
748
+ const result = yield* prompt.loop({ sessionID: session.id })
749
+ expect(result.info.role).toBe("assistant")
750
+
751
+ const msgs = yield* MessageV2.filterCompactedEffect(session.id)
752
+ const tool = msgs
753
+ .flatMap((msg) => msg.parts)
754
+ .find(
755
+ (part): part is CompletedToolPart =>
756
+ part.type === "tool" && part.tool === "glob" && part.state.status === "completed",
757
+ )
758
+ if (!tool) return
759
+
760
+ expect(tool.state.output).toContain(file)
761
+ expect(tool.state.output).not.toContain("No context found for instance")
762
+ expect(result.parts.some((part) => part.type === "text" && part.text === "done")).toBe(true)
763
+ }),
764
+ )
765
+
766
+ it.instance("loop continues when finish is stop but assistant has tool parts", () =>
767
+ Effect.gen(function* () {
768
+ const { llm } = yield* useServerConfig(providerCfg)
769
+ const prompt = yield* SessionPrompt.Service
770
+ const sessions = yield* Session.Service
771
+ const session = yield* sessions.create({
772
+ title: "Pinned",
773
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
774
+ })
775
+ yield* prompt.prompt({
776
+ sessionID: session.id,
777
+ agent: "build",
778
+ noReply: true,
779
+ parts: [{ type: "text", text: "hello" }],
780
+ })
781
+ yield* llm.push(reply().tool("first", { value: "first" }).stop())
782
+ yield* llm.text("second")
783
+
784
+ const result = yield* prompt.loop({ sessionID: session.id })
785
+ expect(yield* llm.calls).toBe(2)
786
+ expect(result.info.role).toBe("assistant")
787
+ if (result.info.role === "assistant") {
788
+ expect(result.parts.some((part) => part.type === "text" && part.text === "second")).toBe(true)
789
+ expect(result.info.finish).toBe("stop")
790
+ }
791
+ }),
792
+ )
793
+
794
+ it.instance("failed subtask preserves metadata on error tool state", () =>
795
+ Effect.gen(function* () {
796
+ const { llm } = yield* useServerConfig((url) => ({
797
+ ...providerCfg(url),
798
+ agent: {
799
+ general: {
800
+ model: "test/missing-model",
801
+ },
802
+ },
803
+ }))
804
+ const prompt = yield* SessionPrompt.Service
805
+ const sessions = yield* Session.Service
806
+ const chat = yield* sessions.create({ title: "Pinned" })
807
+ yield* llm.tool("task", {
808
+ description: "inspect bug",
809
+ prompt: "look into the cache key path",
810
+ subagent_type: "general",
811
+ })
812
+ yield* llm.text("done")
813
+ const msg = yield* user(chat.id, "hello")
814
+ yield* addSubtask(chat.id, msg.id)
815
+
816
+ const result = yield* prompt.loop({ sessionID: chat.id })
817
+ expect(result.info.role).toBe("assistant")
818
+ expect(yield* llm.calls).toBe(2)
819
+
820
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
821
+ const taskMsg = msgs.find((item) => item.info.role === "assistant" && item.info.agent === "general")
822
+ expect(taskMsg?.info.role).toBe("assistant")
823
+ if (!taskMsg || taskMsg.info.role !== "assistant") return
824
+
825
+ const tool = errorTool(taskMsg.parts)
826
+ if (!tool) return
827
+
828
+ expect(tool.state.error).toContain("Tool execution failed")
829
+ expect(tool.state.metadata).toBeDefined()
830
+ expect(tool.state.metadata?.sessionId).toBeDefined()
831
+ expect(tool.state.metadata?.model).toEqual({
832
+ providerID: ProviderV2.ID.make("test"),
833
+ modelID: ModelV2.ID.make("missing-model"),
834
+ })
835
+ }),
836
+ )
837
+
838
+ it.instance("subtask child inherits parent session external_directory allow", () =>
839
+ Effect.gen(function* () {
840
+ const { llm } = yield* useServerConfig(providerCfg)
841
+ const prompt = yield* SessionPrompt.Service
842
+ const sessions = yield* Session.Service
843
+ const chat = yield* sessions.create({
844
+ title: "Parent",
845
+ permission: [{ permission: "external_directory", pattern: "/tmp/allowed/*", action: "allow" }],
846
+ })
847
+ yield* llm.text("done")
848
+ const msg = yield* user(chat.id, "hello")
849
+ yield* addSubtask(chat.id, msg.id)
850
+
851
+ yield* prompt.loop({ sessionID: chat.id })
852
+
853
+ const kids = yield* sessions.children(chat.id)
854
+ expect(kids).toHaveLength(1)
855
+ const child = kids[0]!
856
+ const rules = child.permission ?? []
857
+ expect(rules).toEqual(
858
+ expect.arrayContaining([{ permission: "external_directory", pattern: "/tmp/allowed/*", action: "allow" }]),
859
+ )
860
+ expect(Permission.evaluate("external_directory", "/tmp/allowed/file", rules).action).toBe("allow")
861
+ expect(Permission.evaluate("task", "anything", rules).action).toBe("deny")
862
+ }),
863
+ )
864
+
865
+ noLLMServer.instance("prompt tools replace previous prompt tool rules", () =>
866
+ Effect.gen(function* () {
867
+ const prompt = yield* SessionPrompt.Service
868
+ const sessions = yield* Session.Service
869
+ const session = yield* sessions.create({ title: "Prompt tools" })
870
+
871
+ yield* prompt.prompt({
872
+ sessionID: session.id,
873
+ agent: "build",
874
+ noReply: true,
875
+ tools: { bash: false },
876
+ parts: [{ type: "text", text: "first" }],
877
+ })
878
+ yield* prompt.prompt({
879
+ sessionID: session.id,
880
+ agent: "build",
881
+ noReply: true,
882
+ tools: { read: true },
883
+ parts: [{ type: "text", text: "second" }],
884
+ })
885
+
886
+ const reloaded = yield* sessions.get(session.id)
887
+ expect(reloaded.permission).toEqual([{ permission: "read", pattern: "*", action: "allow" }])
888
+ expect(Permission.evaluate("bash", "anything", reloaded.permission ?? []).action).toBe("ask")
889
+ }),
890
+ )
891
+
892
+ it.instance(
893
+ "running subtask preserves metadata after tool-call transition",
894
+ () =>
895
+ Effect.gen(function* () {
896
+ const { llm } = yield* useServerConfig(providerCfg)
897
+ const prompt = yield* SessionPrompt.Service
898
+ const sessions = yield* Session.Service
899
+ const chat = yield* sessions.create({ title: "Pinned" })
900
+ yield* llm.hang
901
+ const msg = yield* user(chat.id, "hello")
902
+ yield* addSubtask(chat.id, msg.id)
903
+
904
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
905
+
906
+ const tool = yield* pollWithTimeout(
907
+ Effect.gen(function* () {
908
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
909
+ const taskMsg = msgs.find((item) => item.info.role === "assistant" && item.info.agent === "general")
910
+ const tool = taskMsg?.parts.find((part): part is SessionV1.ToolPart => part.type === "tool")
911
+ if (tool?.state.status === "running" && tool.state.metadata?.sessionId) return tool
912
+ }),
913
+ "timed out waiting for running subtask metadata",
914
+ )
915
+
916
+ if (tool.state.status !== "running") return
917
+ expect(typeof tool.state.metadata?.sessionId).toBe("string")
918
+ expect(tool.state.title).toBeDefined()
919
+ expect(tool.state.metadata?.model).toBeDefined()
920
+
921
+ yield* prompt.cancel(chat.id)
922
+ yield* Fiber.await(fiber)
923
+ }),
924
+ 5_000,
925
+ )
926
+
927
+ it.instance(
928
+ "running task tool preserves metadata after tool-call transition",
929
+ () =>
930
+ Effect.gen(function* () {
931
+ const { llm } = yield* useServerConfig(providerCfg)
932
+ const prompt = yield* SessionPrompt.Service
933
+ const sessions = yield* Session.Service
934
+ const chat = yield* sessions.create({
935
+ title: "Pinned",
936
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
937
+ })
938
+ yield* llm.tool("task", {
939
+ description: "inspect bug",
940
+ prompt: "look into the cache key path",
941
+ subagent_type: "general",
942
+ })
943
+ yield* llm.hang
944
+ yield* user(chat.id, "hello")
945
+
946
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
947
+
948
+ const tool = yield* pollWithTimeout(
949
+ Effect.gen(function* () {
950
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
951
+ const assistant = msgs.findLast((item) => item.info.role === "assistant" && item.info.agent === "build")
952
+ const tool = assistant?.parts.find(
953
+ (part): part is SessionV1.ToolPart => part.type === "tool" && part.tool === "task",
954
+ )
955
+ if (tool?.state.status === "running" && tool.state.metadata?.sessionId) return tool
956
+ }),
957
+ "timed out waiting for running task metadata",
958
+ )
959
+
960
+ if (tool.state.status !== "running") return
961
+ expect(typeof tool.state.metadata?.sessionId).toBe("string")
962
+ expect(tool.state.title).toBe("inspect bug")
963
+ expect(tool.state.metadata?.model).toBeDefined()
964
+
965
+ yield* prompt.cancel(chat.id)
966
+ yield* Fiber.await(fiber)
967
+ }),
968
+ 10_000,
969
+ )
970
+
971
+ it.instance(
972
+ "loop sets status to busy then idle",
973
+ () =>
974
+ Effect.gen(function* () {
975
+ const { llm } = yield* useServerConfig(providerCfg)
976
+ const prompt = yield* SessionPrompt.Service
977
+ const sessions = yield* Session.Service
978
+ const status = yield* SessionStatus.Service
979
+
980
+ yield* llm.hang
981
+
982
+ const chat = yield* sessions.create({})
983
+ yield* user(chat.id, "hi")
984
+
985
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
986
+ yield* llm.wait(1)
987
+ expect((yield* status.get(chat.id)).type).toBe("busy")
988
+ yield* prompt.cancel(chat.id)
989
+ yield* Fiber.await(fiber)
990
+ expect((yield* status.get(chat.id)).type).toBe("idle")
991
+ }),
992
+ 3_000,
993
+ )
994
+
995
+ // Cancel semantics
996
+
997
+ it.instance(
998
+ "cancel interrupts loop and resolves with an assistant message",
999
+ () =>
1000
+ Effect.gen(function* () {
1001
+ const { llm } = yield* useServerConfig(providerCfg)
1002
+ const prompt = yield* SessionPrompt.Service
1003
+ const sessions = yield* Session.Service
1004
+ const chat = yield* sessions.create({ title: "Pinned" })
1005
+ yield* seed(chat.id)
1006
+
1007
+ yield* llm.hang
1008
+
1009
+ yield* user(chat.id, "more")
1010
+
1011
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1012
+ yield* llm.wait(1)
1013
+ yield* prompt.cancel(chat.id)
1014
+ const exit = yield* Fiber.await(fiber)
1015
+ expect(Exit.isSuccess(exit)).toBe(true)
1016
+ if (Exit.isSuccess(exit)) {
1017
+ expect(exit.value.info.role).toBe("assistant")
1018
+ }
1019
+ }),
1020
+ 3_000,
1021
+ )
1022
+
1023
+ it.instance(
1024
+ "cancel records MessageAbortedError on interrupted process",
1025
+ () =>
1026
+ Effect.gen(function* () {
1027
+ const { llm } = yield* useServerConfig(providerCfg)
1028
+ const prompt = yield* SessionPrompt.Service
1029
+ const sessions = yield* Session.Service
1030
+ const chat = yield* sessions.create({ title: "Pinned" })
1031
+ yield* llm.hang
1032
+ yield* user(chat.id, "hello")
1033
+
1034
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1035
+ yield* llm.wait(1)
1036
+ yield* prompt.cancel(chat.id)
1037
+ const exit = yield* Fiber.await(fiber)
1038
+ expect(Exit.isSuccess(exit)).toBe(true)
1039
+ if (Exit.isSuccess(exit)) {
1040
+ const info = exit.value.info
1041
+ if (info.role === "assistant") {
1042
+ expect(info.error?.name).toBe("MessageAbortedError")
1043
+ }
1044
+ }
1045
+ }),
1046
+ 3_000,
1047
+ )
1048
+
1049
+ raceNoLLMServer.instance(
1050
+ "finalizes assistant when cancelled before processor creation completes",
1051
+ () =>
1052
+ Effect.gen(function* () {
1053
+ processorCreateStarted.length = 0
1054
+ yield* Effect.addFinalizer(() =>
1055
+ Effect.sync(() => {
1056
+ processorCreateStarted.length = 0
1057
+ }),
1058
+ )
1059
+
1060
+ const prompt = yield* SessionPrompt.Service
1061
+ const sessions = yield* Session.Service
1062
+ const chat = yield* sessions.create({ title: "Processor creation race" })
1063
+
1064
+ yield* prompt.prompt({
1065
+ sessionID: chat.id,
1066
+ agent: "build",
1067
+ noReply: true,
1068
+ parts: [{ type: "text", text: "first" }],
1069
+ })
1070
+
1071
+ const firstCreate = defer<void>()
1072
+ processorCreateStarted.push(firstCreate.resolve)
1073
+ const first = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1074
+ yield* Effect.promise(() => firstCreate.promise)
1075
+
1076
+ yield* prompt.cancel(chat.id)
1077
+ const firstExit = yield* Fiber.await(first)
1078
+ expect(Exit.isSuccess(firstExit)).toBe(true)
1079
+
1080
+ let messages = yield* sessions.messages({ sessionID: chat.id })
1081
+ const firstInterrupted = messages.at(-1)
1082
+ expect(firstInterrupted?.info.role).toBe("assistant")
1083
+ expect(firstInterrupted?.parts).toHaveLength(0)
1084
+ if (firstInterrupted?.info.role === "assistant") {
1085
+ expect(firstInterrupted.info.finish).toBeUndefined()
1086
+ expect(firstInterrupted.info.time.completed).toBeNumber()
1087
+ expect(firstInterrupted.info.error?.name).toBe("MessageAbortedError")
1088
+ }
1089
+
1090
+ yield* prompt.prompt({
1091
+ sessionID: chat.id,
1092
+ agent: "build",
1093
+ noReply: true,
1094
+ parts: [{ type: "text", text: "second" }],
1095
+ })
1096
+
1097
+ const secondCreate = defer<void>()
1098
+ processorCreateStarted.push(secondCreate.resolve)
1099
+ const second = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1100
+ yield* Effect.promise(() => secondCreate.promise)
1101
+
1102
+ yield* prompt.cancel(chat.id)
1103
+ const secondExit = yield* Fiber.await(second)
1104
+ expect(Exit.isSuccess(secondExit)).toBe(true)
1105
+
1106
+ messages = yield* sessions.messages({ sessionID: chat.id })
1107
+ const poisonMessages = messages.filter(
1108
+ (message) =>
1109
+ message.info.role === "assistant" &&
1110
+ message.parts.length === 0 &&
1111
+ !message.info.finish &&
1112
+ !message.info.time.completed &&
1113
+ !message.info.error,
1114
+ )
1115
+ expect(poisonMessages).toHaveLength(0)
1116
+
1117
+ const interruptedMessages = messages.filter(
1118
+ (message) =>
1119
+ message.info.role === "assistant" &&
1120
+ message.parts.length === 0 &&
1121
+ message.info.time.completed &&
1122
+ message.info.error?.name === "MessageAbortedError",
1123
+ )
1124
+ expect(interruptedMessages).toHaveLength(2)
1125
+
1126
+ const lastUser = messages.at(-2)
1127
+ const lastAssistant = messages.at(-1)
1128
+ expect(lastUser?.info.role).toBe("user")
1129
+ expect(lastAssistant?.info.role).toBe("assistant")
1130
+ if (lastUser?.info.role === "user" && lastAssistant?.info.role === "assistant") {
1131
+ expect(lastAssistant.info.parentID).toBe(lastUser?.info.id)
1132
+ }
1133
+ }),
1134
+ { config: cfg },
1135
+ 3_000,
1136
+ )
1137
+
1138
+ noLLMServer.instance(
1139
+ "cancel finalizes subtask tool state",
1140
+ () =>
1141
+ Effect.gen(function* () {
1142
+ const ready = yield* Deferred.make<void>()
1143
+ const aborted = yield* Deferred.make<void>()
1144
+ const registry = yield* ToolRegistry.Service
1145
+ const { task } = yield* registry.named()
1146
+ const original = task.execute
1147
+ task.execute = (_args, ctx) =>
1148
+ Effect.callback<never>((_resume) => {
1149
+ ctx.abort.addEventListener("abort", () => succeedVoid(aborted), { once: true })
1150
+ if (ctx.abort.aborted) succeedVoid(aborted)
1151
+ succeedVoid(ready)
1152
+ return Effect.sync(() => succeedVoid(aborted))
1153
+ })
1154
+ yield* Effect.addFinalizer(() => Effect.sync(() => void (task.execute = original)))
1155
+
1156
+ const { prompt, chat } = yield* boot()
1157
+ const msg = yield* user(chat.id, "hello")
1158
+ yield* addSubtask(chat.id, msg.id)
1159
+
1160
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1161
+ yield* awaitWithTimeout(Deferred.await(ready), "timed out waiting for task tool to start", "10 seconds")
1162
+ yield* prompt.cancel(chat.id)
1163
+
1164
+ const exit = yield* Fiber.await(fiber)
1165
+ expect(Exit.isSuccess(exit)).toBe(true)
1166
+ yield* awaitWithTimeout(Deferred.await(aborted), "timed out waiting for task tool abort", "10 seconds")
1167
+
1168
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
1169
+ const taskMsg = msgs.find((item) => item.info.role === "assistant" && item.info.agent === "general")
1170
+ expect(taskMsg?.info.role).toBe("assistant")
1171
+ if (!taskMsg || taskMsg.info.role !== "assistant") return
1172
+
1173
+ const tool = toolPart(taskMsg.parts)
1174
+ expect(tool?.type).toBe("tool")
1175
+ if (!tool) return
1176
+
1177
+ expect(tool.state.status).not.toBe("running")
1178
+ expect(taskMsg.info.time.completed).toBeDefined()
1179
+ expect(taskMsg.info.finish).toBeDefined()
1180
+ }),
1181
+ { config: cfg },
1182
+ 30_000,
1183
+ )
1184
+
1185
+ it.instance(
1186
+ "cancel propagates from slash command subtask to child session",
1187
+ () =>
1188
+ Effect.gen(function* () {
1189
+ const { llm } = yield* useServerConfig(providerCfg)
1190
+ const prompt = yield* SessionPrompt.Service
1191
+ const sessions = yield* Session.Service
1192
+ const status = yield* SessionStatus.Service
1193
+ const chat = yield* sessions.create({ title: "Pinned" })
1194
+ yield* llm.hang
1195
+ const msg = yield* user(chat.id, "hello")
1196
+ yield* addSubtask(chat.id, msg.id)
1197
+
1198
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1199
+ yield* llm.wait(1)
1200
+
1201
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
1202
+ const taskMsg = msgs.find((item) => item.info.role === "assistant" && item.info.agent === "general")
1203
+ const tool = taskMsg ? toolPart(taskMsg.parts) : undefined
1204
+ const sessionID = tool?.state.status === "running" ? tool.state.metadata?.sessionId : undefined
1205
+ expect(typeof sessionID).toBe("string")
1206
+ if (typeof sessionID !== "string") throw new Error("missing child session id")
1207
+ const childID = SessionID.make(sessionID)
1208
+ expect((yield* status.get(childID)).type).toBe("busy")
1209
+
1210
+ yield* prompt.cancel(chat.id)
1211
+ const exit = yield* Fiber.await(fiber)
1212
+ expect(Exit.isSuccess(exit)).toBe(true)
1213
+
1214
+ expect((yield* status.get(chat.id)).type).toBe("idle")
1215
+ expect((yield* status.get(childID)).type).toBe("idle")
1216
+ }),
1217
+ 10_000,
1218
+ )
1219
+
1220
+ it.instance(
1221
+ "cancel with queued callers resolves all cleanly",
1222
+ () =>
1223
+ Effect.gen(function* () {
1224
+ const { llm } = yield* useServerConfig(providerCfg)
1225
+ const prompt = yield* SessionPrompt.Service
1226
+ const sessions = yield* Session.Service
1227
+ const chat = yield* sessions.create({ title: "Pinned" })
1228
+ yield* llm.hang
1229
+ yield* user(chat.id, "hello")
1230
+
1231
+ const a = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1232
+ yield* llm.wait(1)
1233
+ const b = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1234
+ yield* Effect.sleep(50)
1235
+
1236
+ yield* prompt.cancel(chat.id)
1237
+ const [exitA, exitB] = yield* Effect.all([Fiber.await(a), Fiber.await(b)])
1238
+ expect(Exit.isSuccess(exitA)).toBe(true)
1239
+ expect(Exit.isSuccess(exitB)).toBe(true)
1240
+ if (Exit.isSuccess(exitA) && Exit.isSuccess(exitB)) {
1241
+ expect(exitA.value.info.id).toBe(exitB.value.info.id)
1242
+ }
1243
+ }),
1244
+ { git: true },
1245
+ 3_000,
1246
+ )
1247
+
1248
+ // Queue semantics
1249
+
1250
+ noLLMServer.instance("concurrent loop callers get same result", () =>
1251
+ Effect.gen(function* () {
1252
+ const { prompt, run, chat } = yield* boot()
1253
+ yield* seed(chat.id, { finish: "stop" })
1254
+
1255
+ const [a, b] = yield* Effect.all([prompt.loop({ sessionID: chat.id }), prompt.loop({ sessionID: chat.id })], {
1256
+ concurrency: "unbounded",
1257
+ })
1258
+
1259
+ expect(a.info.id).toBe(b.info.id)
1260
+ expect(a.info.role).toBe("assistant")
1261
+ yield* run.assertNotBusy(chat.id)
1262
+ }),
1263
+ )
1264
+
1265
+ it.instance(
1266
+ "concurrent loop callers all receive same error result",
1267
+ () =>
1268
+ Effect.gen(function* () {
1269
+ const { llm } = yield* useServerConfig(providerCfg)
1270
+ const prompt = yield* SessionPrompt.Service
1271
+ const sessions = yield* Session.Service
1272
+ const chat = yield* sessions.create({ title: "Pinned" })
1273
+
1274
+ yield* llm.fail("boom")
1275
+ yield* user(chat.id, "hello")
1276
+
1277
+ const [a, b] = yield* Effect.all([prompt.loop({ sessionID: chat.id }), prompt.loop({ sessionID: chat.id })], {
1278
+ concurrency: "unbounded",
1279
+ })
1280
+ expect(a.info.id).toBe(b.info.id)
1281
+ expect(a.info.role).toBe("assistant")
1282
+ }),
1283
+ 3_000,
1284
+ )
1285
+
1286
+ it.instance(
1287
+ "prompt submitted during an active run is included in the next LLM input",
1288
+ () =>
1289
+ Effect.gen(function* () {
1290
+ const { llm } = yield* useServerConfig(providerCfg)
1291
+ const gate = yield* Deferred.make<void>()
1292
+ const prompt = yield* SessionPrompt.Service
1293
+ const sessions = yield* Session.Service
1294
+ const chat = yield* sessions.create({ title: "Pinned" })
1295
+
1296
+ yield* llm.hold("first", deferredAsPromise(gate))
1297
+ yield* llm.text("second")
1298
+
1299
+ const a = yield* prompt
1300
+ .prompt({
1301
+ sessionID: chat.id,
1302
+ agent: "build",
1303
+ model: ref,
1304
+ parts: [{ type: "text", text: "first" }],
1305
+ })
1306
+ .pipe(Effect.forkChild)
1307
+
1308
+ yield* llm.wait(1)
1309
+
1310
+ const id = MessageID.ascending()
1311
+ const b = yield* prompt
1312
+ .prompt({
1313
+ sessionID: chat.id,
1314
+ messageID: id,
1315
+ agent: "build",
1316
+ model: ref,
1317
+ parts: [{ type: "text", text: "second" }],
1318
+ })
1319
+ .pipe(Effect.forkChild)
1320
+
1321
+ yield* pollWithTimeout(
1322
+ sessions
1323
+ .messages({ sessionID: chat.id })
1324
+ .pipe(
1325
+ Effect.map((msgs) =>
1326
+ msgs.some((msg) => msg.info.role === "user" && msg.info.id === id) ? true : undefined,
1327
+ ),
1328
+ ),
1329
+ "timed out waiting for second prompt to save",
1330
+ )
1331
+
1332
+ yield* Deferred.succeed(gate, void 0)
1333
+
1334
+ const [ea, eb] = yield* Effect.all([Fiber.await(a), Fiber.await(b)])
1335
+ expect(Exit.isSuccess(ea)).toBe(true)
1336
+ expect(Exit.isSuccess(eb)).toBe(true)
1337
+ expect(yield* llm.calls).toBe(2)
1338
+
1339
+ const msgs = yield* sessions.messages({ sessionID: chat.id })
1340
+ const assistants = msgs.filter((msg) => msg.info.role === "assistant")
1341
+ expect(assistants).toHaveLength(2)
1342
+ const last = assistants.at(-1)
1343
+ if (!last || last.info.role !== "assistant") throw new Error("expected second assistant")
1344
+ expect(last.info.parentID).toBe(id)
1345
+ expect(last.parts.some((part) => part.type === "text" && part.text === "second")).toBe(true)
1346
+
1347
+ const inputs = yield* llm.inputs
1348
+ expect(inputs).toHaveLength(2)
1349
+ expect(JSON.stringify(inputs.at(-1)?.messages)).toContain("second")
1350
+ }),
1351
+ 3_000,
1352
+ )
1353
+
1354
+ it.instance(
1355
+ "assertNotBusy fails with BusyError when loop running",
1356
+ () =>
1357
+ Effect.gen(function* () {
1358
+ const { llm } = yield* useServerConfig(providerCfg)
1359
+ const prompt = yield* SessionPrompt.Service
1360
+ const run = yield* SessionRunState.Service
1361
+ const sessions = yield* Session.Service
1362
+ yield* llm.hang
1363
+
1364
+ const chat = yield* sessions.create({})
1365
+ yield* user(chat.id, "hi")
1366
+
1367
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1368
+ yield* llm.wait(1)
1369
+
1370
+ const exit = yield* run.assertNotBusy(chat.id).pipe(Effect.exit)
1371
+ expect(Exit.isFailure(exit)).toBe(true)
1372
+ if (Exit.isFailure(exit)) {
1373
+ expect(Cause.squash(exit.cause)).toBeInstanceOf(Session.BusyError)
1374
+ expect(Cause.squash(exit.cause)).toMatchObject({ _tag: "SessionBusyError", sessionID: chat.id })
1375
+ }
1376
+
1377
+ yield* prompt.cancel(chat.id)
1378
+ yield* Fiber.await(fiber)
1379
+ }),
1380
+ 3_000,
1381
+ )
1382
+
1383
+ noLLMServer.instance("assertNotBusy succeeds when idle", () =>
1384
+ Effect.gen(function* () {
1385
+ const run = yield* SessionRunState.Service
1386
+ const sessions = yield* Session.Service
1387
+
1388
+ const chat = yield* sessions.create({})
1389
+ const exit = yield* run.assertNotBusy(chat.id).pipe(Effect.exit)
1390
+ expect(Exit.isSuccess(exit)).toBe(true)
1391
+ }),
1392
+ )
1393
+
1394
+ // Shell semantics
1395
+
1396
+ it.instance(
1397
+ "shell rejects with BusyError when loop running",
1398
+ () =>
1399
+ Effect.gen(function* () {
1400
+ const { llm } = yield* useServerConfig(providerCfg)
1401
+ const prompt = yield* SessionPrompt.Service
1402
+ const sessions = yield* Session.Service
1403
+ const chat = yield* sessions.create({ title: "Pinned" })
1404
+ yield* llm.hang
1405
+ yield* user(chat.id, "hi")
1406
+
1407
+ const fiber = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1408
+ yield* llm.wait(1)
1409
+
1410
+ const exit = yield* prompt.shell({ sessionID: chat.id, agent: "build", command: "echo hi" }).pipe(Effect.exit)
1411
+ expect(Exit.isFailure(exit)).toBe(true)
1412
+ if (Exit.isFailure(exit)) {
1413
+ expect(Cause.squash(exit.cause)).toBeInstanceOf(Session.BusyError)
1414
+ expect(Cause.squash(exit.cause)).toMatchObject({ _tag: "SessionBusyError", sessionID: chat.id })
1415
+ }
1416
+
1417
+ yield* prompt.cancel(chat.id)
1418
+ yield* Fiber.await(fiber)
1419
+ }),
1420
+ 3_000,
1421
+ )
1422
+
1423
+ unixNoLLMServer(
1424
+ "shell captures stdout and stderr in completed tool output",
1425
+ () =>
1426
+ Effect.gen(function* () {
1427
+ const { prompt, run, chat } = yield* boot()
1428
+ const result = yield* prompt.shell({
1429
+ sessionID: chat.id,
1430
+ agent: "build",
1431
+ command: "printf out && printf err >&2",
1432
+ })
1433
+
1434
+ expect(result.info.role).toBe("assistant")
1435
+ const tool = completedTool(result.parts)
1436
+ if (!tool) return
1437
+
1438
+ expect(tool.state.output).toContain("out")
1439
+ expect(tool.state.output).toContain("err")
1440
+ expect(tool.state.metadata.output).toContain("out")
1441
+ expect(tool.state.metadata.output).toContain("err")
1442
+ yield* run.assertNotBusy(chat.id)
1443
+ }),
1444
+ { config: cfg },
1445
+ )
1446
+
1447
+ unixNoLLMServer(
1448
+ "shell completes a fast command on the preferred shell",
1449
+ () =>
1450
+ Effect.gen(function* () {
1451
+ const { directory: dir } = yield* TestInstance
1452
+ const { prompt, run, chat } = yield* boot()
1453
+ const result = yield* prompt.shell({
1454
+ sessionID: chat.id,
1455
+ agent: "build",
1456
+ command: "pwd",
1457
+ })
1458
+
1459
+ expect(result.info.role).toBe("assistant")
1460
+ const tool = completedTool(result.parts)
1461
+ if (!tool) return
1462
+
1463
+ expect(tool.state.input.command).toBe("pwd")
1464
+ expect(tool.state.output).toContain(dir)
1465
+ expect(tool.state.metadata.output).toContain(dir)
1466
+ yield* run.assertNotBusy(chat.id)
1467
+ }),
1468
+ { config: cfg },
1469
+ )
1470
+
1471
+ unixNoLLMServer(
1472
+ "shell uses configured shell over env shell",
1473
+ () =>
1474
+ withSh(() =>
1475
+ Effect.gen(function* () {
1476
+ if (!(yield* hasBash)) return
1477
+
1478
+ const { prompt, chat } = yield* boot()
1479
+ const result = yield* prompt.shell({
1480
+ sessionID: chat.id,
1481
+ agent: "build",
1482
+ command: "[[ 1 -eq 1 ]] && printf configured",
1483
+ })
1484
+
1485
+ const tool = completedTool(result.parts)
1486
+ if (!tool) return
1487
+ expect(tool.state.output).toContain("configured")
1488
+ }),
1489
+ ),
1490
+ { config: { ...cfg, shell: "bash" } },
1491
+ 30_000,
1492
+ )
1493
+
1494
+ unixNoLLMServer(
1495
+ "shell commands can change directory after startup",
1496
+ () =>
1497
+ withSh(() =>
1498
+ Effect.gen(function* () {
1499
+ const { directory: dir } = yield* TestInstance
1500
+ const { prompt, run, chat } = yield* boot()
1501
+ const parent = path.dirname(dir)
1502
+ const result = yield* prompt.shell({
1503
+ sessionID: chat.id,
1504
+ agent: "build",
1505
+ command: "cd .. && pwd",
1506
+ })
1507
+
1508
+ expect(result.info.role).toBe("assistant")
1509
+ const tool = completedTool(result.parts)
1510
+ if (!tool) return
1511
+
1512
+ expect(tool.state.output).toContain(parent)
1513
+ expect(tool.state.metadata.output).toContain(parent)
1514
+ yield* run.assertNotBusy(chat.id)
1515
+ }),
1516
+ ),
1517
+ { config: cfg },
1518
+ )
1519
+
1520
+ unixNoLLMServer(
1521
+ "shell lists files from the project directory",
1522
+ () =>
1523
+ Effect.gen(function* () {
1524
+ const { directory: dir } = yield* TestInstance
1525
+ const { prompt, run, chat } = yield* boot()
1526
+ yield* writeText(path.join(dir, "README.md"), "# e2e\n")
1527
+
1528
+ const result = yield* prompt.shell({
1529
+ sessionID: chat.id,
1530
+ agent: "build",
1531
+ command: "command ls",
1532
+ })
1533
+
1534
+ expect(result.info.role).toBe("assistant")
1535
+ const tool = completedTool(result.parts)
1536
+ if (!tool) return
1537
+
1538
+ expect(tool.state.input.command).toBe("command ls")
1539
+ expect(tool.state.output).toContain("README.md")
1540
+ expect(tool.state.metadata.output).toContain("README.md")
1541
+ yield* run.assertNotBusy(chat.id)
1542
+ }),
1543
+ { config: cfg },
1544
+ )
1545
+
1546
+ unixNoLLMServer(
1547
+ "shell captures stderr from a failing command",
1548
+ () =>
1549
+ Effect.gen(function* () {
1550
+ const { prompt, run, chat } = yield* boot()
1551
+ const result = yield* prompt.shell({
1552
+ sessionID: chat.id,
1553
+ agent: "build",
1554
+ command: "command -v __nonexistent_cmd_e2e__ || echo 'not found' >&2; exit 1",
1555
+ })
1556
+
1557
+ expect(result.info.role).toBe("assistant")
1558
+ const tool = completedTool(result.parts)
1559
+ if (!tool) return
1560
+
1561
+ expect(tool.state.output).toContain("not found")
1562
+ expect(tool.state.metadata.output).toContain("not found")
1563
+ yield* run.assertNotBusy(chat.id)
1564
+ }),
1565
+ { config: cfg },
1566
+ )
1567
+
1568
+ unixNoLLMServer(
1569
+ "shell updates running metadata before process exit",
1570
+ () =>
1571
+ withSh(() =>
1572
+ Effect.gen(function* () {
1573
+ const { prompt, chat } = yield* boot()
1574
+
1575
+ const fiber = yield* prompt
1576
+ .shell({ sessionID: chat.id, agent: "build", command: "printf first && sleep 0.2 && printf second" })
1577
+ .pipe(Effect.forkChild)
1578
+
1579
+ yield* pollWithTimeout(
1580
+ Effect.gen(function* () {
1581
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
1582
+ const taskMsg = msgs.find((item) => item.info.role === "assistant")
1583
+ const tool = taskMsg ? toolPart(taskMsg.parts) : undefined
1584
+ if (tool?.state.status === "running" && tool.state.metadata?.output.includes("first")) return true
1585
+ }),
1586
+ "timed out waiting for running shell metadata",
1587
+ )
1588
+
1589
+ const exit = yield* Fiber.await(fiber)
1590
+ expect(Exit.isSuccess(exit)).toBe(true)
1591
+ }),
1592
+ ),
1593
+ { config: cfg },
1594
+ 30_000,
1595
+ )
1596
+
1597
+ it.instance(
1598
+ "loop waits while shell runs and starts after shell exits",
1599
+ () =>
1600
+ Effect.gen(function* () {
1601
+ const { llm } = yield* useServerConfig(providerCfg)
1602
+ const prompt = yield* SessionPrompt.Service
1603
+ const sessions = yield* Session.Service
1604
+ const chat = yield* sessions.create({
1605
+ title: "Pinned",
1606
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
1607
+ })
1608
+ yield* llm.text("after-shell")
1609
+
1610
+ const sh = yield* prompt
1611
+ .shell({ sessionID: chat.id, agent: "build", command: "sleep 0.2" })
1612
+ .pipe(Effect.forkChild)
1613
+ yield* waitForBusy(chat.id)
1614
+
1615
+ const loop = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1616
+ yield* Effect.sleep(50)
1617
+
1618
+ expect(yield* llm.calls).toBe(0)
1619
+
1620
+ yield* Fiber.await(sh)
1621
+ const exit = yield* Fiber.await(loop)
1622
+
1623
+ expect(Exit.isSuccess(exit)).toBe(true)
1624
+ if (Exit.isSuccess(exit)) {
1625
+ expect(exit.value.info.role).toBe("assistant")
1626
+ expect(exit.value.parts.some((part) => part.type === "text" && part.text === "after-shell")).toBe(true)
1627
+ }
1628
+ expect(yield* llm.calls).toBe(1)
1629
+ }),
1630
+ { git: true },
1631
+ 3_000,
1632
+ )
1633
+
1634
+ it.instance(
1635
+ "shell completion resumes queued loop callers",
1636
+ () =>
1637
+ Effect.gen(function* () {
1638
+ const { llm } = yield* useServerConfig(providerCfg)
1639
+ const prompt = yield* SessionPrompt.Service
1640
+ const sessions = yield* Session.Service
1641
+ const chat = yield* sessions.create({
1642
+ title: "Pinned",
1643
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
1644
+ })
1645
+ yield* llm.text("done")
1646
+
1647
+ const sh = yield* prompt
1648
+ .shell({ sessionID: chat.id, agent: "build", command: "sleep 0.2" })
1649
+ .pipe(Effect.forkChild)
1650
+ yield* waitForBusy(chat.id)
1651
+
1652
+ const a = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1653
+ const b = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1654
+ yield* Effect.sleep(50)
1655
+
1656
+ expect(yield* llm.calls).toBe(0)
1657
+
1658
+ yield* Fiber.await(sh)
1659
+ const [ea, eb] = yield* Effect.all([Fiber.await(a), Fiber.await(b)])
1660
+
1661
+ expect(Exit.isSuccess(ea)).toBe(true)
1662
+ expect(Exit.isSuccess(eb)).toBe(true)
1663
+ if (Exit.isSuccess(ea) && Exit.isSuccess(eb)) {
1664
+ expect(ea.value.info.id).toBe(eb.value.info.id)
1665
+ expect(ea.value.info.role).toBe("assistant")
1666
+ }
1667
+ expect(yield* llm.calls).toBe(1)
1668
+ }),
1669
+ { git: true },
1670
+ 3_000,
1671
+ )
1672
+
1673
+ unix(
1674
+ "command ! expansion uses configured shell over env shell",
1675
+ () =>
1676
+ withSh(() =>
1677
+ Effect.gen(function* () {
1678
+ if (!(yield* hasBash)) return
1679
+ const { llm } = yield* useServerConfig((url) => ({
1680
+ ...providerCfg(url),
1681
+ shell: "bash",
1682
+ command: {
1683
+ probe: {
1684
+ template: "Probe: !`[[ 1 -eq 1 ]] && printf configured`",
1685
+ },
1686
+ },
1687
+ }))
1688
+
1689
+ const { prompt, chat } = yield* boot()
1690
+ yield* llm.text("done")
1691
+
1692
+ const result = yield* prompt.command({
1693
+ sessionID: chat.id,
1694
+ command: "probe",
1695
+ arguments: "",
1696
+ })
1697
+
1698
+ expect(result.info.role).toBe("assistant")
1699
+ const inputs = yield* llm.inputs
1700
+ expect(JSON.stringify(inputs.at(-1)?.messages)).toContain("configured")
1701
+ }),
1702
+ ),
1703
+ 30_000,
1704
+ )
1705
+
1706
+ unixNoLLMServer(
1707
+ "cancel interrupts shell and resolves cleanly",
1708
+ () =>
1709
+ withSh(() =>
1710
+ Effect.gen(function* () {
1711
+ const { prompt, run, chat } = yield* boot()
1712
+
1713
+ const sh = yield* prompt
1714
+ .shell({ sessionID: chat.id, agent: "build", command: "sleep 30" })
1715
+ .pipe(Effect.forkChild)
1716
+ yield* waitForBusy(chat.id)
1717
+
1718
+ yield* prompt.cancel(chat.id)
1719
+
1720
+ const status = yield* SessionStatus.Service
1721
+ expect((yield* status.get(chat.id)).type).toBe("idle")
1722
+ const busy = yield* run.assertNotBusy(chat.id).pipe(Effect.exit)
1723
+ expect(Exit.isSuccess(busy)).toBe(true)
1724
+
1725
+ const exit = yield* Fiber.await(sh)
1726
+ expect(Exit.isSuccess(exit)).toBe(true)
1727
+ if (Exit.isSuccess(exit)) {
1728
+ expect(exit.value.info.role).toBe("assistant")
1729
+ const tool = completedTool(exit.value.parts)
1730
+ if (tool) {
1731
+ expect(tool.state.output).toContain("User aborted the command")
1732
+ }
1733
+ }
1734
+ }),
1735
+ ),
1736
+ { git: true, config: cfg },
1737
+ 30_000,
1738
+ )
1739
+
1740
+ unixNoLLMServer(
1741
+ "cancel persists aborted shell result when shell ignores TERM",
1742
+ () =>
1743
+ withSh(() =>
1744
+ Effect.gen(function* () {
1745
+ const { prompt, chat } = yield* boot()
1746
+ const { directory: dir } = yield* TestInstance
1747
+ const afs = yield* FSUtil.Service
1748
+ const ready = path.join(dir, ".trap-ready")
1749
+
1750
+ const sh = yield* prompt
1751
+ .shell({
1752
+ sessionID: chat.id,
1753
+ agent: "build",
1754
+ // Touch marker AFTER trap installs so the test waits for the actual
1755
+ // ignore-TERM state before cancelling; otherwise SIGTERM can arrive
1756
+ // before `trap` runs and the escalation path is never exercised.
1757
+ command: `trap '' TERM; touch "${ready}"; sleep 30`,
1758
+ })
1759
+ .pipe(Effect.forkChild)
1760
+
1761
+ yield* Effect.gen(function* () {
1762
+ while (!(yield* afs.existsSafe(ready))) {
1763
+ yield* Effect.sleep(Duration.millis(10))
1764
+ }
1765
+ }).pipe(Effect.timeout(Duration.seconds(5)))
1766
+
1767
+ yield* prompt.cancel(chat.id)
1768
+
1769
+ const exit = yield* Fiber.await(sh)
1770
+ expect(Exit.isSuccess(exit)).toBe(true)
1771
+ if (Exit.isSuccess(exit)) {
1772
+ expect(exit.value.info.role).toBe("assistant")
1773
+ const tool = completedTool(exit.value.parts)
1774
+ if (tool) {
1775
+ expect(tool.state.output).toContain("User aborted the command")
1776
+ }
1777
+ }
1778
+ }),
1779
+ ),
1780
+ { git: true, config: cfg },
1781
+ 30_000,
1782
+ )
1783
+
1784
+ unix(
1785
+ "cancel finalizes interrupted bash tool output through normal truncation",
1786
+ () =>
1787
+ Effect.gen(function* () {
1788
+ const { dir, llm } = yield* useServerConfig(providerCfg)
1789
+ const prompt = yield* SessionPrompt.Service
1790
+ const sessions = yield* Session.Service
1791
+ const chat = yield* sessions.create({
1792
+ title: "Interrupted bash truncation",
1793
+ permission: [{ permission: "*", pattern: "*", action: "allow" }],
1794
+ })
1795
+
1796
+ yield* prompt.prompt({
1797
+ sessionID: chat.id,
1798
+ agent: "build",
1799
+ noReply: true,
1800
+ parts: [{ type: "text", text: "run bash" }],
1801
+ })
1802
+
1803
+ yield* llm.tool("bash", {
1804
+ command:
1805
+ 'i=0; while [ "$i" -lt 4000 ]; do printf "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx %05d\\n" "$i"; i=$((i + 1)); done; printf truncation-ready; sleep 30',
1806
+ description: "Print many lines",
1807
+ timeout: 30_000,
1808
+ workdir: path.resolve(dir),
1809
+ })
1810
+
1811
+ const run = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1812
+ yield* llm.wait(1)
1813
+ yield* pollWithTimeout(
1814
+ Effect.gen(function* () {
1815
+ const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
1816
+ const assistant = msgs.findLast((item) => item.info.role === "assistant")
1817
+ const tool = assistant ? toolPart(assistant.parts) : undefined
1818
+ if (tool?.state.status === "running" && tool.state.metadata?.output.includes("truncation-ready")) return true
1819
+ }),
1820
+ "timed out waiting for truncated shell output",
1821
+ )
1822
+ yield* prompt.cancel(chat.id)
1823
+
1824
+ const exit = yield* Fiber.await(run)
1825
+ expect(Exit.isSuccess(exit)).toBe(true)
1826
+ if (Exit.isFailure(exit)) return
1827
+
1828
+ const tool = completedTool(exit.value.parts)
1829
+ if (!tool) return
1830
+
1831
+ expect(tool.state.metadata.truncated).toBe(true)
1832
+ expect(typeof tool.state.metadata.outputPath).toBe("string")
1833
+ expect(tool.state.output).toMatch(/\.\.\.output truncated\.\.\./)
1834
+ expect(tool.state.output).toMatch(/Full output saved to:\s+\S+/)
1835
+ expect(tool.state.output).not.toContain("Tool execution aborted")
1836
+ }),
1837
+ { git: true },
1838
+ 30_000,
1839
+ )
1840
+
1841
+ unixNoLLMServer(
1842
+ "cancel interrupts loop queued behind shell",
1843
+ () =>
1844
+ Effect.gen(function* () {
1845
+ const { prompt, chat } = yield* boot()
1846
+
1847
+ const sh = yield* prompt.shell({ sessionID: chat.id, agent: "build", command: "sleep 30" }).pipe(Effect.forkChild)
1848
+ yield* waitForBusy(chat.id)
1849
+
1850
+ const loop = yield* prompt.loop({ sessionID: chat.id }).pipe(Effect.forkChild)
1851
+ yield* Effect.sleep(50)
1852
+
1853
+ yield* prompt.cancel(chat.id)
1854
+
1855
+ const exit = yield* Fiber.await(loop)
1856
+ expect(Exit.isSuccess(exit)).toBe(true)
1857
+ if (Exit.isSuccess(exit)) {
1858
+ const tool = completedTool(exit.value.parts)
1859
+ expect(tool?.state.output).toContain("User aborted the command")
1860
+ }
1861
+
1862
+ yield* Fiber.await(sh)
1863
+ }),
1864
+ { git: true, config: cfg },
1865
+ 30_000,
1866
+ )
1867
+
1868
+ unixNoLLMServer(
1869
+ "shell rejects when another shell is already running",
1870
+ () =>
1871
+ withSh(() =>
1872
+ Effect.gen(function* () {
1873
+ const { prompt, chat } = yield* boot()
1874
+
1875
+ const a = yield* prompt
1876
+ .shell({ sessionID: chat.id, agent: "build", command: "sleep 30" })
1877
+ .pipe(Effect.forkChild)
1878
+ yield* waitForBusy(chat.id)
1879
+
1880
+ const exit = yield* prompt.shell({ sessionID: chat.id, agent: "build", command: "echo hi" }).pipe(Effect.exit)
1881
+ expect(Exit.isFailure(exit)).toBe(true)
1882
+ if (Exit.isFailure(exit)) {
1883
+ expect(Cause.squash(exit.cause)).toBeInstanceOf(Session.BusyError)
1884
+ }
1885
+
1886
+ yield* prompt.cancel(chat.id)
1887
+ yield* Fiber.await(a)
1888
+ }),
1889
+ ),
1890
+ { git: true, config: cfg },
1891
+ 30_000,
1892
+ )
1893
+
1894
+ // Abort signal propagation tests for inline tool execution
1895
+
1896
+ function hangUntilAborted(tool: { execute: (...args: any[]) => any }) {
1897
+ return Effect.gen(function* () {
1898
+ const ready = yield* Deferred.make<void>()
1899
+ const aborted = yield* Deferred.make<void>()
1900
+ const original = tool.execute
1901
+ tool.execute = (_args: any, ctx: any) => {
1902
+ ctx.abort.addEventListener("abort", () => succeedVoid(aborted), { once: true })
1903
+ if (ctx.abort.aborted) succeedVoid(aborted)
1904
+ succeedVoid(ready)
1905
+ return Effect.callback<never>(() => Effect.sync(() => succeedVoid(aborted)))
1906
+ }
1907
+ const restore = Effect.addFinalizer(() => Effect.sync(() => void (tool.execute = original)))
1908
+ return { ready, aborted, restore }
1909
+ })
1910
+ }
1911
+
1912
+ noLLMServer.instance(
1913
+ "interrupt propagates abort signal to read tool via file part (text/plain)",
1914
+ () =>
1915
+ Effect.gen(function* () {
1916
+ const { directory: dir } = yield* TestInstance
1917
+ const registry = yield* ToolRegistry.Service
1918
+ const { read } = yield* registry.named()
1919
+ const { ready, restore } = yield* hangUntilAborted(read)
1920
+ yield* restore
1921
+
1922
+ const prompt = yield* SessionPrompt.Service
1923
+ const sessions = yield* Session.Service
1924
+ const chat = yield* sessions.create({ title: "Abort Test" })
1925
+
1926
+ const testFile = path.join(dir, "test.txt")
1927
+ yield* writeText(testFile, "hello world")
1928
+
1929
+ const fiber = yield* prompt
1930
+ .prompt({
1931
+ sessionID: chat.id,
1932
+ agent: "build",
1933
+ parts: [
1934
+ { type: "text", text: "read this" },
1935
+ { type: "file", url: `file://${testFile}`, filename: "test.txt", mime: "text/plain" },
1936
+ ],
1937
+ })
1938
+ .pipe(Effect.forkChild)
1939
+
1940
+ yield* awaitWithTimeout(Deferred.await(ready), "timed out waiting for read tool to start", "10 seconds")
1941
+ yield* prompt.cancel(chat.id)
1942
+ yield* Fiber.interrupt(fiber)
1943
+ const exit = yield* Fiber.await(fiber)
1944
+ expect(Exit.isFailure(exit)).toBe(true)
1945
+ }),
1946
+ { config: cfg },
1947
+ 30_000,
1948
+ )
1949
+
1950
+ noLLMServer.instance(
1951
+ "interrupt propagates abort signal to read tool via file part (directory)",
1952
+ () =>
1953
+ Effect.gen(function* () {
1954
+ const { directory: dir } = yield* TestInstance
1955
+ const registry = yield* ToolRegistry.Service
1956
+ const { read } = yield* registry.named()
1957
+ const { ready, restore } = yield* hangUntilAborted(read)
1958
+ yield* restore
1959
+
1960
+ const prompt = yield* SessionPrompt.Service
1961
+ const sessions = yield* Session.Service
1962
+ const chat = yield* sessions.create({ title: "Abort Test" })
1963
+
1964
+ const fiber = yield* prompt
1965
+ .prompt({
1966
+ sessionID: chat.id,
1967
+ agent: "build",
1968
+ parts: [
1969
+ { type: "text", text: "read this" },
1970
+ { type: "file", url: `file://${dir}`, filename: "dir", mime: "application/x-directory" },
1971
+ ],
1972
+ })
1973
+ .pipe(Effect.forkChild)
1974
+
1975
+ yield* awaitWithTimeout(Deferred.await(ready), "timed out waiting for read tool to start", "10 seconds")
1976
+ yield* prompt.cancel(chat.id)
1977
+ yield* Fiber.interrupt(fiber)
1978
+ const exit = yield* Fiber.await(fiber)
1979
+ expect(Exit.isFailure(exit)).toBe(true)
1980
+ }),
1981
+ { config: cfg },
1982
+ 30_000,
1983
+ )
1984
+
1985
+ // Missing file handling
1986
+
1987
+ noLLMServer.instance(
1988
+ "does not fail the prompt when a file part is missing",
1989
+ () =>
1990
+ Effect.gen(function* () {
1991
+ const { directory: dir } = yield* TestInstance
1992
+ const prompt = yield* SessionPrompt.Service
1993
+ const sessions = yield* Session.Service
1994
+ const session = yield* sessions.create({})
1995
+
1996
+ const missing = path.join(dir, "does-not-exist.ts")
1997
+ const msg = yield* prompt.prompt({
1998
+ sessionID: session.id,
1999
+ agent: "build",
2000
+ noReply: true,
2001
+ parts: [
2002
+ { type: "text", text: "please review @does-not-exist.ts" },
2003
+ {
2004
+ type: "file",
2005
+ mime: "text/plain",
2006
+ url: `file://${missing}`,
2007
+ filename: "does-not-exist.ts",
2008
+ },
2009
+ ],
2010
+ })
2011
+
2012
+ if (msg.info.role !== "user") throw new Error("expected user message")
2013
+ const hasFailure = msg.parts.some(
2014
+ (part) => part.type === "text" && part.synthetic && part.text.includes("Read tool failed to read"),
2015
+ )
2016
+ expect(hasFailure).toBe(true)
2017
+
2018
+ yield* sessions.remove(session.id)
2019
+ }),
2020
+ { config: cfg },
2021
+ )
2022
+
2023
+ noLLMServer.instance(
2024
+ "keeps stored part order stable when file resolution is async",
2025
+ () =>
2026
+ Effect.gen(function* () {
2027
+ const { directory: dir } = yield* TestInstance
2028
+ const prompt = yield* SessionPrompt.Service
2029
+ const sessions = yield* Session.Service
2030
+ const session = yield* sessions.create({})
2031
+
2032
+ const missing = path.join(dir, "still-missing.ts")
2033
+ const msg = yield* prompt.prompt({
2034
+ sessionID: session.id,
2035
+ agent: "build",
2036
+ noReply: true,
2037
+ parts: [
2038
+ {
2039
+ type: "file",
2040
+ mime: "text/plain",
2041
+ url: `file://${missing}`,
2042
+ filename: "still-missing.ts",
2043
+ },
2044
+ { type: "text", text: "after-file" },
2045
+ ],
2046
+ })
2047
+
2048
+ if (msg.info.role !== "user") throw new Error("expected user message")
2049
+
2050
+ const stored = yield* MessageV2.get({
2051
+ sessionID: session.id,
2052
+ messageID: msg.info.id,
2053
+ })
2054
+ const text = stored.parts.filter((part) => part.type === "text").map((part) => part.text)
2055
+
2056
+ expect(text[0]?.startsWith("Called the Read tool with the following input:")).toBe(true)
2057
+ expect(text[1]?.includes("Read tool failed to read")).toBe(true)
2058
+ expect(text[2]).toBe("after-file")
2059
+
2060
+ yield* sessions.remove(session.id)
2061
+ }),
2062
+ { config: cfg },
2063
+ )
2064
+
2065
+ // Special characters in filenames
2066
+
2067
+ noLLMServer.instance(
2068
+ "handles filenames with # character",
2069
+ () =>
2070
+ Effect.gen(function* () {
2071
+ const { directory: dir } = yield* TestInstance
2072
+ yield* writeText(path.join(dir, "file#name.txt"), "special content\n")
2073
+
2074
+ const prompt = yield* SessionPrompt.Service
2075
+ const sessions = yield* Session.Service
2076
+ const session = yield* sessions.create({})
2077
+ const parts = yield* prompt.resolvePromptParts("Read @file#name.txt")
2078
+ const fileParts = parts.filter((part) => part.type === "file")
2079
+
2080
+ expect(fileParts.length).toBe(1)
2081
+ expect(fileParts[0].filename).toBe("file#name.txt")
2082
+ expect(fileParts[0].url).toContain("%23")
2083
+
2084
+ const decodedPath = fileURLToPath(fileParts[0].url)
2085
+ expect(decodedPath).toBe(path.join(dir, "file#name.txt"))
2086
+
2087
+ const message = yield* prompt.prompt({
2088
+ sessionID: session.id,
2089
+ parts,
2090
+ noReply: true,
2091
+ })
2092
+ const stored = yield* MessageV2.get({ sessionID: session.id, messageID: message.info.id })
2093
+ const textParts = stored.parts.filter((part) => part.type === "text")
2094
+ const hasContent = textParts.some((part) => part.text.includes("special content"))
2095
+ expect(hasContent).toBe(true)
2096
+
2097
+ yield* sessions.remove(session.id)
2098
+ }),
2099
+ { git: true, config: cfg },
2100
+ )
2101
+
2102
+ // Regression: empty assistant turn loop
2103
+
2104
+ it.instance("does not loop empty assistant turns for a simple reply", () =>
2105
+ Effect.gen(function* () {
2106
+ const { llm } = yield* useServerConfig(providerCfg)
2107
+ const prompt = yield* SessionPrompt.Service
2108
+ const sessions = yield* Session.Service
2109
+ const session = yield* sessions.create({ title: "Prompt regression" })
2110
+
2111
+ yield* llm.text("packages/miaw/src/session/processor.ts")
2112
+
2113
+ const result = yield* prompt.prompt({
2114
+ sessionID: session.id,
2115
+ agent: "build",
2116
+ parts: [{ type: "text", text: "Where is SessionProcessor?" }],
2117
+ })
2118
+
2119
+ expect(result.info.role).toBe("assistant")
2120
+ expect(result.parts.some((part) => part.type === "text" && part.text.includes("processor.ts"))).toBe(true)
2121
+
2122
+ const msgs = yield* sessions.messages({ sessionID: session.id })
2123
+ expect(msgs.filter((msg) => msg.info.role === "assistant")).toHaveLength(1)
2124
+ expect(yield* llm.calls).toBe(1)
2125
+ }),
2126
+ )
2127
+
2128
+ it.instance(
2129
+ "records aborted errors when prompt is cancelled mid-stream",
2130
+ () =>
2131
+ Effect.gen(function* () {
2132
+ const { llm } = yield* useServerConfig(providerCfg)
2133
+ const prompt = yield* SessionPrompt.Service
2134
+ const sessions = yield* Session.Service
2135
+ const session = yield* sessions.create({ title: "Prompt cancel regression" })
2136
+
2137
+ yield* llm.hang
2138
+
2139
+ const fiber = yield* prompt
2140
+ .prompt({
2141
+ sessionID: session.id,
2142
+ agent: "build",
2143
+ parts: [{ type: "text", text: "Cancel me" }],
2144
+ })
2145
+ .pipe(Effect.forkChild)
2146
+
2147
+ yield* llm.wait(1)
2148
+ yield* prompt.cancel(session.id)
2149
+
2150
+ const exit = yield* Fiber.await(fiber)
2151
+ expect(Exit.isSuccess(exit)).toBe(true)
2152
+ if (Exit.isSuccess(exit)) {
2153
+ expect(exit.value.info.role).toBe("assistant")
2154
+ if (exit.value.info.role === "assistant") {
2155
+ expect(exit.value.info.error?.name).toBe("MessageAbortedError")
2156
+ }
2157
+ }
2158
+
2159
+ const msgs = yield* sessions.messages({ sessionID: session.id })
2160
+ const last = msgs.findLast((msg) => msg.info.role === "assistant")
2161
+ expect(last?.info.role).toBe("assistant")
2162
+ if (last?.info.role === "assistant") {
2163
+ expect(last.info.error?.name).toBe("MessageAbortedError")
2164
+ }
2165
+ }),
2166
+ 3_000,
2167
+ )
2168
+
2169
+ // Agent variant
2170
+
2171
+ noLLMServer.instance(
2172
+ "applies agent variant only when using agent model",
2173
+ () =>
2174
+ Effect.gen(function* () {
2175
+ const prompt = yield* SessionPrompt.Service
2176
+ const sessions = yield* Session.Service
2177
+ const session = yield* sessions.create({})
2178
+
2179
+ const other = yield* prompt.prompt({
2180
+ sessionID: session.id,
2181
+ agent: "build",
2182
+ model: { providerID: ProviderV2.ID.make("miaw"), modelID: ModelV2.ID.make("kimi-k2.5-free") },
2183
+ noReply: true,
2184
+ parts: [{ type: "text", text: "hello" }],
2185
+ })
2186
+ if (other.info.role !== "user") throw new Error("expected user message")
2187
+ expect(other.info.model.variant).toBeUndefined()
2188
+
2189
+ const match = yield* prompt.prompt({
2190
+ sessionID: session.id,
2191
+ agent: "build",
2192
+ noReply: true,
2193
+ parts: [{ type: "text", text: "hello again" }],
2194
+ })
2195
+ if (match.info.role !== "user") throw new Error("expected user message")
2196
+ expect(match.info.model).toEqual({
2197
+ providerID: ProviderV2.ID.make("test"),
2198
+ modelID: ModelV2.ID.make("test-model"),
2199
+ variant: "xhigh",
2200
+ })
2201
+ expect(match.info.model.variant).toBe("xhigh")
2202
+
2203
+ const override = yield* prompt.prompt({
2204
+ sessionID: session.id,
2205
+ agent: "build",
2206
+ noReply: true,
2207
+ variant: "high",
2208
+ parts: [{ type: "text", text: "hello third" }],
2209
+ })
2210
+ if (override.info.role !== "user") throw new Error("expected user message")
2211
+ expect(override.info.model.variant).toBe("high")
2212
+
2213
+ yield* sessions.remove(session.id)
2214
+ }),
2215
+ {
2216
+ config: {
2217
+ ...cfg,
2218
+ provider: {
2219
+ ...cfg.provider,
2220
+ test: {
2221
+ ...cfg.provider.test,
2222
+ models: {
2223
+ "test-model": {
2224
+ ...cfg.provider.test.models["test-model"],
2225
+ variants: { xhigh: {}, high: {} },
2226
+ },
2227
+ },
2228
+ },
2229
+ },
2230
+ agent: {
2231
+ build: {
2232
+ model: "test/test-model",
2233
+ variant: "xhigh",
2234
+ },
2235
+ },
2236
+ },
2237
+ },
2238
+ )
2239
+
2240
+ // Agent / command resolution errors
2241
+
2242
+ noLLMServer.instance(
2243
+ "unknown agent throws typed error",
2244
+ () =>
2245
+ Effect.gen(function* () {
2246
+ const prompt = yield* SessionPrompt.Service
2247
+ const sessions = yield* Session.Service
2248
+ const session = yield* sessions.create({})
2249
+ const exit = yield* prompt
2250
+ .prompt({
2251
+ sessionID: session.id,
2252
+ agent: "nonexistent-agent-xyz",
2253
+ noReply: true,
2254
+ parts: [{ type: "text", text: "hello" }],
2255
+ })
2256
+ .pipe(Effect.exit)
2257
+
2258
+ expect(Exit.isFailure(exit)).toBe(true)
2259
+ if (Exit.isFailure(exit)) {
2260
+ const err = Cause.squash(exit.cause)
2261
+ expect(err).not.toBeInstanceOf(TypeError)
2262
+ expect(NamedError.Unknown.isInstance(err)).toBe(true)
2263
+ if (NamedError.Unknown.isInstance(err)) {
2264
+ expect(err.data.message).toContain('Agent not found: "nonexistent-agent-xyz"')
2265
+ }
2266
+ }
2267
+ }),
2268
+ 30_000,
2269
+ )
2270
+
2271
+ noLLMServer.instance(
2272
+ "unknown agent error includes available agent names",
2273
+ () =>
2274
+ Effect.gen(function* () {
2275
+ const prompt = yield* SessionPrompt.Service
2276
+ const sessions = yield* Session.Service
2277
+ const session = yield* sessions.create({})
2278
+ const exit = yield* prompt
2279
+ .prompt({
2280
+ sessionID: session.id,
2281
+ agent: "nonexistent-agent-xyz",
2282
+ noReply: true,
2283
+ parts: [{ type: "text", text: "hello" }],
2284
+ })
2285
+ .pipe(Effect.exit)
2286
+
2287
+ expect(Exit.isFailure(exit)).toBe(true)
2288
+ if (Exit.isFailure(exit)) {
2289
+ const err = Cause.squash(exit.cause)
2290
+ expect(NamedError.Unknown.isInstance(err)).toBe(true)
2291
+ if (NamedError.Unknown.isInstance(err)) {
2292
+ expect(err.data.message).toContain("build")
2293
+ }
2294
+ }
2295
+ }),
2296
+ 30_000,
2297
+ )
2298
+
2299
+ noLLMServer.instance(
2300
+ "unknown command throws typed error with available names",
2301
+ () =>
2302
+ Effect.gen(function* () {
2303
+ const prompt = yield* SessionPrompt.Service
2304
+ const sessions = yield* Session.Service
2305
+ const session = yield* sessions.create({})
2306
+ const exit = yield* prompt
2307
+ .command({
2308
+ sessionID: session.id,
2309
+ command: "nonexistent-command-xyz",
2310
+ arguments: "",
2311
+ })
2312
+ .pipe(Effect.exit)
2313
+
2314
+ expect(Exit.isFailure(exit)).toBe(true)
2315
+ if (Exit.isFailure(exit)) {
2316
+ const err = Cause.squash(exit.cause)
2317
+ expect(err).not.toBeInstanceOf(TypeError)
2318
+ expect(NamedError.Unknown.isInstance(err)).toBe(true)
2319
+ if (NamedError.Unknown.isInstance(err)) {
2320
+ expect(err.data.message).toContain('Command not found: "nonexistent-command-xyz"')
2321
+ expect(err.data.message).toContain("init")
2322
+ }
2323
+ }
2324
+ }),
2325
+ 30_000,
2326
+ )