@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,1834 @@
1
+ import { afterEach, describe, expect, mock, test } from "bun:test"
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 { EventV2Bridge } from "@/event-v2-bridge"
6
+ import { APICallError } from "ai"
7
+ import { Cause, Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect"
8
+ import * as Stream from "effect/Stream"
9
+ import { Config } from "@/config/config"
10
+ import { Image } from "@/image/image"
11
+ import { Agent } from "../../src/agent/agent"
12
+ import { LLM } from "../../src/session/llm"
13
+ import { SessionCompaction } from "../../src/session/compaction"
14
+ import { Token } from "@/util/token"
15
+ import { Permission } from "../../src/permission"
16
+ import { Plugin } from "../../src/plugin"
17
+ import { provideTmpdirInstance, TestInstance } from "../fixture/fixture"
18
+ import { Session as SessionNs } from "@/session/session"
19
+ import { MessageV2 } from "../../src/session/message-v2"
20
+ import { MessageID, PartID, SessionID } from "../../src/session/schema"
21
+ import { SessionStatus } from "../../src/session/status"
22
+ import { SessionSummary } from "../../src/session/summary"
23
+ import { SessionV2 } from "@miaw/core/session"
24
+ import { SessionExecution } from "@miaw/core/session/execution"
25
+
26
+ import type { Provider } from "@/provider/provider"
27
+ import * as SessionProcessorModule from "../../src/session/processor"
28
+ import { Snapshot } from "../../src/snapshot"
29
+ import { ProviderTest } from "../fake/provider"
30
+ import { testEffect } from "../lib/effect"
31
+ import { CrossSpawnSpawner } from "@miaw/core/cross-spawn-spawner"
32
+ import { TestConfig } from "../fixture/config"
33
+ import { RuntimeFlags } from "@/effect/runtime-flags"
34
+ import { LLMEvent, Usage } from "@miaw/llm"
35
+ import { ProviderV2 } from "@miaw/core/provider"
36
+ import { ModelV2 } from "@miaw/core/model"
37
+
38
+ const summary = Layer.succeed(
39
+ SessionSummary.Service,
40
+ SessionSummary.Service.of({
41
+ summarize: () => Effect.void,
42
+ diff: () => Effect.succeed([]),
43
+ computeDiff: () => Effect.succeed([]),
44
+ }),
45
+ )
46
+
47
+ const ref = {
48
+ providerID: ProviderV2.ID.make("test"),
49
+ modelID: ModelV2.ID.make("test-model"),
50
+ }
51
+
52
+ const usage = (input: ConstructorParameters<typeof Usage>[0]) => new Usage(input)
53
+
54
+ const basicUsage = () => usage({ inputTokens: 1, outputTokens: 1, totalTokens: 2 })
55
+
56
+ afterEach(() => {
57
+ mock.restore()
58
+ })
59
+
60
+ function createModel(opts: {
61
+ context: number
62
+ output: number
63
+ input?: number
64
+ cost?: Provider.Model["cost"]
65
+ npm?: string
66
+ }): Provider.Model {
67
+ return {
68
+ id: "test-model",
69
+ providerID: "test",
70
+ name: "Test",
71
+ limit: {
72
+ context: opts.context,
73
+ input: opts.input,
74
+ output: opts.output,
75
+ },
76
+ cost: opts.cost ?? { input: 0, output: 0, cache: { read: 0, write: 0 } },
77
+ capabilities: {
78
+ toolcall: true,
79
+ attachment: false,
80
+ reasoning: false,
81
+ temperature: true,
82
+ input: { text: true, image: false, audio: false, video: false },
83
+ output: { text: true, image: false, audio: false, video: false },
84
+ },
85
+ api: { npm: opts.npm ?? "@ai-sdk/anthropic" },
86
+ options: {},
87
+ } as Provider.Model
88
+ }
89
+
90
+ const wide = () => ProviderTest.fake({ model: createModel({ context: 100_000, output: 32_000 }) })
91
+
92
+ function createUserMessage(sessionID: SessionID, text: string) {
93
+ return Effect.gen(function* () {
94
+ const ssn = yield* SessionNs.Service
95
+ const msg = yield* ssn.updateMessage({
96
+ id: MessageID.ascending(),
97
+ role: "user",
98
+ sessionID,
99
+ agent: "build",
100
+ model: ref,
101
+ time: { created: Date.now() },
102
+ })
103
+ yield* ssn.updatePart({
104
+ id: PartID.ascending(),
105
+ messageID: msg.id,
106
+ sessionID,
107
+ type: "text",
108
+ text,
109
+ })
110
+ return msg
111
+ })
112
+ }
113
+
114
+ function createAssistantMessage(sessionID: SessionID, parentID: MessageID, root: string) {
115
+ return SessionNs.Service.use((ssn) =>
116
+ ssn.updateMessage({
117
+ id: MessageID.ascending(),
118
+ role: "assistant",
119
+ sessionID,
120
+ mode: "build",
121
+ agent: "build",
122
+ path: { cwd: root, root },
123
+ cost: 0,
124
+ tokens: {
125
+ output: 0,
126
+ input: 0,
127
+ reasoning: 0,
128
+ cache: { read: 0, write: 0 },
129
+ },
130
+ modelID: ref.modelID,
131
+ providerID: ref.providerID,
132
+ parentID,
133
+ time: { created: Date.now() },
134
+ finish: "end_turn",
135
+ }),
136
+ )
137
+ }
138
+
139
+ function createSummaryAssistantMessage(sessionID: SessionID, parentID: MessageID, root: string, text: string) {
140
+ return SessionNs.Service.use((ssn) =>
141
+ Effect.gen(function* () {
142
+ const msg = yield* ssn.updateMessage({
143
+ id: MessageID.ascending(),
144
+ role: "assistant",
145
+ sessionID,
146
+ mode: "compaction",
147
+ agent: "compaction",
148
+ path: { cwd: root, root },
149
+ cost: 0,
150
+ tokens: {
151
+ output: 0,
152
+ input: 0,
153
+ reasoning: 0,
154
+ cache: { read: 0, write: 0 },
155
+ },
156
+ modelID: ref.modelID,
157
+ providerID: ref.providerID,
158
+ parentID,
159
+ summary: true,
160
+ time: { created: Date.now() },
161
+ finish: "end_turn",
162
+ })
163
+ yield* ssn.updatePart({
164
+ id: PartID.ascending(),
165
+ messageID: msg.id,
166
+ sessionID,
167
+ type: "text",
168
+ text,
169
+ })
170
+ return msg
171
+ }),
172
+ )
173
+ }
174
+
175
+ function createCompactionMarker(sessionID: SessionID) {
176
+ return SessionNs.Service.use((ssn) =>
177
+ Effect.gen(function* () {
178
+ const msg = yield* ssn.updateMessage({
179
+ id: MessageID.ascending(),
180
+ role: "user",
181
+ model: ref,
182
+ sessionID,
183
+ agent: "build",
184
+ time: { created: Date.now() },
185
+ })
186
+ yield* ssn.updatePart({
187
+ id: PartID.ascending(),
188
+ messageID: msg.id,
189
+ sessionID: msg.sessionID,
190
+ type: "compaction",
191
+ auto: false,
192
+ })
193
+ }),
194
+ )
195
+ }
196
+
197
+ function fake(
198
+ input: Parameters<SessionProcessorModule.SessionProcessor.Interface["create"]>[0],
199
+ result: "continue" | "compact",
200
+ ) {
201
+ const msg = input.assistantMessage
202
+ return {
203
+ get message() {
204
+ return msg
205
+ },
206
+ updateToolCall: Effect.fn("TestSessionProcessor.updateToolCall")(() => Effect.succeed(undefined)),
207
+ completeToolCall: Effect.fn("TestSessionProcessor.completeToolCall")(() => Effect.void),
208
+ process: Effect.fn("TestSessionProcessor.process")(() => Effect.succeed(result)),
209
+ } satisfies SessionProcessorModule.SessionProcessor.Handle
210
+ }
211
+
212
+ function layer(result: "continue" | "compact") {
213
+ return Layer.succeed(
214
+ SessionProcessorModule.SessionProcessor.Service,
215
+ SessionProcessorModule.SessionProcessor.Service.of({
216
+ create: Effect.fn("TestSessionProcessor.create")((input) => Effect.succeed(fake(input, result))),
217
+ }),
218
+ )
219
+ }
220
+
221
+ function cfg(compaction?: ConfigV1.Info["compaction"]) {
222
+ const base = Schema.decodeUnknownSync(ConfigV1.Info)({}) as ConfigV1.Info
223
+ return TestConfig.layer({
224
+ get: () => Effect.succeed({ ...base, compaction }),
225
+ })
226
+ }
227
+
228
+ const deps = Layer.mergeAll(
229
+ wide().layer,
230
+ layer("continue"),
231
+ Agent.defaultLayer,
232
+ Plugin.defaultLayer,
233
+ EventV2Bridge.defaultLayer,
234
+ Config.defaultLayer,
235
+ RuntimeFlags.layer({ experimentalEventSystem: true }),
236
+ Database.defaultLayer,
237
+ EventV2Bridge.defaultLayer,
238
+ )
239
+
240
+ const env = Layer.mergeAll(
241
+ SessionNs.defaultLayer,
242
+ Database.defaultLayer,
243
+ EventV2Bridge.defaultLayer,
244
+ CrossSpawnSpawner.defaultLayer,
245
+ SessionCompaction.layer.pipe(Layer.provide(SessionNs.defaultLayer), Layer.provideMerge(deps)),
246
+ )
247
+
248
+ const it = testEffect(env)
249
+
250
+ const compactionEnv = Layer.mergeAll(
251
+ SessionNs.defaultLayer,
252
+ Database.defaultLayer,
253
+ EventV2Bridge.defaultLayer,
254
+ CrossSpawnSpawner.defaultLayer,
255
+ )
256
+ const itCompaction = testEffect(compactionEnv)
257
+
258
+ type CompactionProcessOptions = {
259
+ result?: "continue" | "compact"
260
+ llm?: Layer.Layer<LLM.Service>
261
+ plugin?: Layer.Layer<Plugin.Service>
262
+ provider?: ReturnType<typeof ProviderTest.fake>
263
+ config?: Layer.Layer<Config.Service>
264
+ }
265
+
266
+ function withCompaction(options?: CompactionProcessOptions) {
267
+ return Effect.provide(compactionProcessLayer(options))
268
+ }
269
+
270
+ function compactionProcessLayer(options?: CompactionProcessOptions) {
271
+ const events = EventV2Bridge.defaultLayer
272
+ const status = SessionStatus.layer.pipe(Layer.provide(events))
273
+ const processor = options?.llm
274
+ ? SessionProcessorModule.SessionProcessor.layer.pipe(
275
+ Layer.provide(summary),
276
+ Layer.provide(Image.defaultLayer),
277
+ Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })),
278
+ Layer.provide(status),
279
+ )
280
+ : layer(options?.result ?? "continue")
281
+ return Layer.mergeAll(SessionCompaction.layer.pipe(Layer.provide(processor)), processor, events, status).pipe(
282
+ Layer.provide(SessionNs.defaultLayer),
283
+ Layer.provide((options?.provider ?? wide()).layer),
284
+ Layer.provide(Snapshot.defaultLayer),
285
+ Layer.provide(options?.llm ?? LLM.defaultLayer),
286
+ Layer.provide(Permission.defaultLayer),
287
+ Layer.provide(Agent.defaultLayer),
288
+ Layer.provide(options?.plugin ?? Plugin.defaultLayer),
289
+ Layer.provide(status),
290
+ Layer.provide(events),
291
+ Layer.provide(options?.config ?? Config.defaultLayer),
292
+ Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })),
293
+ Layer.provide(EventV2Bridge.defaultLayer),
294
+ )
295
+ }
296
+
297
+ function createSummaryCompaction(sessionID: SessionID) {
298
+ return SessionCompaction.use.create({ sessionID, agent: "build", model: ref, auto: false })
299
+ }
300
+
301
+ function readCompactionPart(sessionID: SessionID) {
302
+ return SessionNs.use
303
+ .messages({ sessionID })
304
+ .pipe(
305
+ Effect.map((messages) =>
306
+ messages.at(-2)?.parts.find((item): item is SessionV1.CompactionPart => item.type === "compaction"),
307
+ ),
308
+ )
309
+ }
310
+
311
+ function llm() {
312
+ const queue: Array<
313
+ Stream.Stream<LLMEvent, unknown> | ((input: LLM.StreamInput) => Stream.Stream<LLMEvent, unknown>)
314
+ > = []
315
+
316
+ return {
317
+ push(stream: Stream.Stream<LLMEvent, unknown> | ((input: LLM.StreamInput) => Stream.Stream<LLMEvent, unknown>)) {
318
+ queue.push(stream)
319
+ },
320
+ layer: Layer.succeed(
321
+ LLM.Service,
322
+ LLM.Service.of({
323
+ stream: (input) => {
324
+ const item = queue.shift() ?? Stream.empty
325
+ const stream = typeof item === "function" ? item(input) : item
326
+ return stream.pipe(Stream.mapEffect((event) => Effect.succeed(event)))
327
+ },
328
+ }),
329
+ ),
330
+ }
331
+ }
332
+
333
+ function reply(
334
+ text: string,
335
+ capture?: (input: LLM.StreamInput) => void,
336
+ ): (input: LLM.StreamInput) => Stream.Stream<LLMEvent, unknown> {
337
+ return (input) => {
338
+ capture?.(input)
339
+ return Stream.make(
340
+ LLMEvent.textStart({ id: "txt-0" }),
341
+ LLMEvent.textDelta({ id: "txt-0", text }),
342
+ LLMEvent.textEnd({ id: "txt-0" }),
343
+ LLMEvent.stepFinish({
344
+ index: 0,
345
+ reason: "stop",
346
+ usage: basicUsage(),
347
+ }),
348
+ LLMEvent.finish({
349
+ reason: "stop",
350
+ usage: basicUsage(),
351
+ }),
352
+ )
353
+ }
354
+ }
355
+
356
+ function plugin(ready: Deferred.Deferred<void>) {
357
+ return Layer.mock(Plugin.Service)({
358
+ trigger: <Name extends string, Input, Output>(name: Name, _input: Input, output: Output) => {
359
+ if (name !== "experimental.session.compacting") return Effect.succeed(output)
360
+ return Effect.sync(() => Deferred.doneUnsafe(ready, Effect.void)).pipe(
361
+ Effect.andThen(Effect.never),
362
+ Effect.as(output),
363
+ )
364
+ },
365
+ list: () => Effect.succeed([]),
366
+ init: () => Effect.void,
367
+ })
368
+ }
369
+
370
+ function autocontinue(enabled: boolean) {
371
+ return Layer.mock(Plugin.Service)({
372
+ trigger: <Name extends string, Input, Output>(name: Name, _input: Input, output: Output) => {
373
+ if (name !== "experimental.compaction.autocontinue") return Effect.succeed(output)
374
+ return Effect.sync(() => {
375
+ ;(output as { enabled: boolean }).enabled = enabled
376
+ return output
377
+ })
378
+ },
379
+ list: () => Effect.succeed([]),
380
+ init: () => Effect.void,
381
+ })
382
+ }
383
+
384
+ describe("session.compaction.isOverflow", () => {
385
+ it.live(
386
+ "returns true when token count exceeds usable context",
387
+ provideTmpdirInstance(() =>
388
+ Effect.gen(function* () {
389
+ const compact = yield* SessionCompaction.Service
390
+ const model = createModel({ context: 100_000, output: 32_000 })
391
+ const tokens = { input: 75_000, output: 5_000, reasoning: 0, cache: { read: 0, write: 0 } }
392
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(true)
393
+ }),
394
+ ),
395
+ )
396
+
397
+ it.live(
398
+ "returns false when token count within usable context",
399
+ provideTmpdirInstance(() =>
400
+ Effect.gen(function* () {
401
+ const compact = yield* SessionCompaction.Service
402
+ const model = createModel({ context: 200_000, output: 32_000 })
403
+ const tokens = { input: 100_000, output: 10_000, reasoning: 0, cache: { read: 0, write: 0 } }
404
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(false)
405
+ }),
406
+ ),
407
+ )
408
+
409
+ it.live(
410
+ "includes cache.read in token count",
411
+ provideTmpdirInstance(() =>
412
+ Effect.gen(function* () {
413
+ const compact = yield* SessionCompaction.Service
414
+ const model = createModel({ context: 100_000, output: 32_000 })
415
+ const tokens = { input: 60_000, output: 10_000, reasoning: 0, cache: { read: 10_000, write: 0 } }
416
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(true)
417
+ }),
418
+ ),
419
+ )
420
+
421
+ it.live(
422
+ "respects input limit for input caps",
423
+ provideTmpdirInstance(() =>
424
+ Effect.gen(function* () {
425
+ const compact = yield* SessionCompaction.Service
426
+ const model = createModel({ context: 400_000, input: 272_000, output: 128_000 })
427
+ const tokens = { input: 271_000, output: 1_000, reasoning: 0, cache: { read: 2_000, write: 0 } }
428
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(true)
429
+ }),
430
+ ),
431
+ )
432
+
433
+ it.live(
434
+ "returns false when input/output are within input caps",
435
+ provideTmpdirInstance(() =>
436
+ Effect.gen(function* () {
437
+ const compact = yield* SessionCompaction.Service
438
+ const model = createModel({ context: 400_000, input: 272_000, output: 128_000 })
439
+ const tokens = { input: 200_000, output: 20_000, reasoning: 0, cache: { read: 10_000, write: 0 } }
440
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(false)
441
+ }),
442
+ ),
443
+ )
444
+
445
+ it.live(
446
+ "returns false when output within limit with input caps",
447
+ provideTmpdirInstance(() =>
448
+ Effect.gen(function* () {
449
+ const compact = yield* SessionCompaction.Service
450
+ const model = createModel({ context: 200_000, input: 120_000, output: 10_000 })
451
+ const tokens = { input: 50_000, output: 9_999, reasoning: 0, cache: { read: 0, write: 0 } }
452
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(false)
453
+ }),
454
+ ),
455
+ )
456
+
457
+ // ─── Bug reproduction tests ───────────────────────────────────────────
458
+ // These tests demonstrate that when limit.input is set, isOverflow()
459
+ // does not subtract any headroom for the next model response. This means
460
+ // compaction only triggers AFTER we've already consumed the full input
461
+ // budget, leaving zero room for the next API call's output tokens.
462
+ //
463
+ // Compare: without limit.input, usable = context - output (reserves space).
464
+ // With limit.input, usable = limit.input (reserves nothing).
465
+ //
466
+ // Related issues: #10634, #8089, #11086, #12621
467
+ // Open PRs: #6875, #12924
468
+
469
+ it.live(
470
+ "BUG: no headroom when limit.input is set — compaction should trigger near boundary but does not",
471
+ provideTmpdirInstance(() =>
472
+ Effect.gen(function* () {
473
+ const compact = yield* SessionCompaction.Service
474
+ // Simulate Claude with prompt caching: input limit = 200K, output limit = 32K
475
+ const model = createModel({ context: 200_000, input: 200_000, output: 32_000 })
476
+
477
+ // We've used 198K tokens total. Only 2K under the input limit.
478
+ // On the next turn, the full conversation (198K) becomes input,
479
+ // plus the model needs room to generate output — this WILL overflow.
480
+ const tokens = { input: 180_000, output: 15_000, reasoning: 0, cache: { read: 3_000, write: 0 } }
481
+ // count = 180K + 3K + 15K = 198K
482
+ // usable = limit.input = 200K (no output subtracted!)
483
+ // 198K > 200K = false → no compaction triggered
484
+
485
+ // WITHOUT limit.input: usable = 200K - 32K = 168K, and 198K > 168K = true ✓
486
+ // WITH limit.input: usable = 200K, and 198K > 200K = false ✗
487
+
488
+ // With 198K used and only 2K headroom, the next turn will overflow.
489
+ // Compaction MUST trigger here.
490
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(true)
491
+ }),
492
+ ),
493
+ )
494
+
495
+ it.live(
496
+ "BUG: without limit.input, same token count correctly triggers compaction",
497
+ provideTmpdirInstance(() =>
498
+ Effect.gen(function* () {
499
+ const compact = yield* SessionCompaction.Service
500
+ // Same model but without limit.input — uses context - output instead
501
+ const model = createModel({ context: 200_000, output: 32_000 })
502
+
503
+ // Same token usage as above
504
+ const tokens = { input: 180_000, output: 15_000, reasoning: 0, cache: { read: 3_000, write: 0 } }
505
+ // count = 198K
506
+ // usable = context - output = 200K - 32K = 168K
507
+ // 198K > 168K = true → compaction correctly triggered
508
+
509
+ const result = yield* compact.isOverflow({ tokens, model })
510
+ expect(result).toBe(true) // ← Correct: headroom is reserved
511
+ }),
512
+ ),
513
+ )
514
+
515
+ it.live(
516
+ "BUG: asymmetry — limit.input model allows 30K more usage before compaction than equivalent model without it",
517
+ provideTmpdirInstance(() =>
518
+ Effect.gen(function* () {
519
+ const compact = yield* SessionCompaction.Service
520
+ // Two models with identical context/output limits, differing only in limit.input
521
+ const withInputLimit = createModel({ context: 200_000, input: 200_000, output: 32_000 })
522
+ const withoutInputLimit = createModel({ context: 200_000, output: 32_000 })
523
+
524
+ // 170K total tokens — well above context-output (168K) but below input limit (200K)
525
+ const tokens = { input: 166_000, output: 10_000, reasoning: 0, cache: { read: 5_000, write: 0 } }
526
+
527
+ const withLimit = yield* compact.isOverflow({ tokens, model: withInputLimit })
528
+ const withoutLimit = yield* compact.isOverflow({ tokens, model: withoutInputLimit })
529
+
530
+ // Both models have identical real capacity — they should agree:
531
+ expect(withLimit).toBe(true) // should compact (170K leaves no room for 32K output)
532
+ expect(withoutLimit).toBe(true) // correctly compacts (170K > 168K)
533
+ }),
534
+ ),
535
+ )
536
+
537
+ it.live(
538
+ "returns false when model context limit is 0",
539
+ provideTmpdirInstance(() =>
540
+ Effect.gen(function* () {
541
+ const compact = yield* SessionCompaction.Service
542
+ const model = createModel({ context: 0, output: 32_000 })
543
+ const tokens = { input: 100_000, output: 10_000, reasoning: 0, cache: { read: 0, write: 0 } }
544
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(false)
545
+ }),
546
+ ),
547
+ )
548
+
549
+ it.live(
550
+ "returns false when compaction.auto is disabled",
551
+ provideTmpdirInstance(
552
+ () =>
553
+ Effect.gen(function* () {
554
+ const compact = yield* SessionCompaction.Service
555
+ const model = createModel({ context: 100_000, output: 32_000 })
556
+ const tokens = { input: 75_000, output: 5_000, reasoning: 0, cache: { read: 0, write: 0 } }
557
+ expect(yield* compact.isOverflow({ tokens, model })).toBe(false)
558
+ }),
559
+ {
560
+ config: {
561
+ compaction: { auto: false },
562
+ },
563
+ },
564
+ ),
565
+ )
566
+ })
567
+
568
+ describe("session.compaction.create", () => {
569
+ it.live(
570
+ "creates a compaction user message and part",
571
+ provideTmpdirInstance(() =>
572
+ Effect.gen(function* () {
573
+ const compact = yield* SessionCompaction.Service
574
+ const ssn = yield* SessionNs.Service
575
+
576
+ const info = yield* ssn.create({})
577
+
578
+ yield* compact.create({
579
+ sessionID: info.id,
580
+ agent: "build",
581
+ model: ref,
582
+ auto: true,
583
+ overflow: true,
584
+ })
585
+
586
+ const msgs = yield* ssn.messages({ sessionID: info.id })
587
+ expect(msgs).toHaveLength(1)
588
+ expect(msgs[0].info.role).toBe("user")
589
+ expect(msgs[0].parts).toHaveLength(1)
590
+ expect(msgs[0].parts[0]).toMatchObject({
591
+ type: "compaction",
592
+ auto: true,
593
+ overflow: true,
594
+ })
595
+ }),
596
+ ),
597
+ )
598
+
599
+ it.live.skip(
600
+ "projects a compaction message to v2 (v2 projector disabled)",
601
+ provideTmpdirInstance(() =>
602
+ Effect.gen(function* () {
603
+ const compact = yield* SessionCompaction.Service
604
+ const ssn = yield* SessionNs.Service
605
+ const info = yield* ssn.create({})
606
+
607
+ yield* compact.create({
608
+ sessionID: info.id,
609
+ agent: "build",
610
+ model: ref,
611
+ auto: true,
612
+ overflow: true,
613
+ })
614
+
615
+ const v2 = yield* SessionV2.Service.use((svc) => svc.messages({ sessionID: info.id })).pipe(
616
+ Effect.provide(SessionExecution.noopLayer),
617
+ Effect.provide(SessionV2.defaultLayer),
618
+ )
619
+ expect(v2.at(-1)).toMatchObject({
620
+ type: "compaction",
621
+ reason: "auto",
622
+ summary: "",
623
+ })
624
+ }),
625
+ ),
626
+ )
627
+ })
628
+
629
+ describe("session.compaction.prune", () => {
630
+ it.live(
631
+ "compacts old completed tool output",
632
+ provideTmpdirInstance(
633
+ (dir) =>
634
+ Effect.gen(function* () {
635
+ const compact = yield* SessionCompaction.Service
636
+ const ssn = yield* SessionNs.Service
637
+ const info = yield* ssn.create({})
638
+ const a = yield* ssn.updateMessage({
639
+ id: MessageID.ascending(),
640
+ role: "user",
641
+ sessionID: info.id,
642
+ agent: "build",
643
+ model: ref,
644
+ time: { created: Date.now() },
645
+ })
646
+ yield* ssn.updatePart({
647
+ id: PartID.ascending(),
648
+ messageID: a.id,
649
+ sessionID: info.id,
650
+ type: "text",
651
+ text: "first",
652
+ })
653
+ const b: SessionV1.Assistant = {
654
+ id: MessageID.ascending(),
655
+ role: "assistant",
656
+ sessionID: info.id,
657
+ mode: "build",
658
+ agent: "build",
659
+ path: { cwd: dir, root: dir },
660
+ cost: 0,
661
+ tokens: {
662
+ output: 0,
663
+ input: 0,
664
+ reasoning: 0,
665
+ cache: { read: 0, write: 0 },
666
+ },
667
+ modelID: ref.modelID,
668
+ providerID: ref.providerID,
669
+ parentID: a.id,
670
+ time: { created: Date.now() },
671
+ finish: "end_turn",
672
+ }
673
+ yield* ssn.updateMessage(b)
674
+ yield* ssn.updatePart({
675
+ id: PartID.ascending(),
676
+ messageID: b.id,
677
+ sessionID: info.id,
678
+ type: "tool",
679
+ callID: crypto.randomUUID(),
680
+ tool: "bash",
681
+ state: {
682
+ status: "completed",
683
+ input: {},
684
+ output: "x".repeat(200_000),
685
+ title: "done",
686
+ metadata: {},
687
+ time: { start: Date.now(), end: Date.now() },
688
+ },
689
+ })
690
+ for (const text of ["second", "third"]) {
691
+ const msg = yield* ssn.updateMessage({
692
+ id: MessageID.ascending(),
693
+ role: "user",
694
+ sessionID: info.id,
695
+ agent: "build",
696
+ model: ref,
697
+ time: { created: Date.now() },
698
+ })
699
+ yield* ssn.updatePart({
700
+ id: PartID.ascending(),
701
+ messageID: msg.id,
702
+ sessionID: info.id,
703
+ type: "text",
704
+ text,
705
+ })
706
+ }
707
+
708
+ yield* compact.prune({ sessionID: info.id })
709
+
710
+ const msgs = yield* ssn.messages({ sessionID: info.id })
711
+ const part = msgs.flatMap((msg) => msg.parts).find((part) => part.type === "tool")
712
+ expect(part?.type).toBe("tool")
713
+ expect(part?.state.status).toBe("completed")
714
+ if (part?.type === "tool" && part.state.status === "completed") {
715
+ expect(part.state.time.compacted).toBeNumber()
716
+ }
717
+ }),
718
+
719
+ {
720
+ config: {
721
+ compaction: { prune: true },
722
+ },
723
+ },
724
+ ),
725
+ )
726
+
727
+ it.live(
728
+ "skips protected skill tool output",
729
+ provideTmpdirInstance((dir) =>
730
+ Effect.gen(function* () {
731
+ const compact = yield* SessionCompaction.Service
732
+ const ssn = yield* SessionNs.Service
733
+ const info = yield* ssn.create({})
734
+ const a = yield* ssn.updateMessage({
735
+ id: MessageID.ascending(),
736
+ role: "user",
737
+ sessionID: info.id,
738
+ agent: "build",
739
+ model: ref,
740
+ time: { created: Date.now() },
741
+ })
742
+ yield* ssn.updatePart({
743
+ id: PartID.ascending(),
744
+ messageID: a.id,
745
+ sessionID: info.id,
746
+ type: "text",
747
+ text: "first",
748
+ })
749
+ const b: SessionV1.Assistant = {
750
+ id: MessageID.ascending(),
751
+ role: "assistant",
752
+ sessionID: info.id,
753
+ mode: "build",
754
+ agent: "build",
755
+ path: { cwd: dir, root: dir },
756
+ cost: 0,
757
+ tokens: {
758
+ output: 0,
759
+ input: 0,
760
+ reasoning: 0,
761
+ cache: { read: 0, write: 0 },
762
+ },
763
+ modelID: ref.modelID,
764
+ providerID: ref.providerID,
765
+ parentID: a.id,
766
+ time: { created: Date.now() },
767
+ finish: "end_turn",
768
+ }
769
+ yield* ssn.updateMessage(b)
770
+ yield* ssn.updatePart({
771
+ id: PartID.ascending(),
772
+ messageID: b.id,
773
+ sessionID: info.id,
774
+ type: "tool",
775
+ callID: crypto.randomUUID(),
776
+ tool: "skill",
777
+ state: {
778
+ status: "completed",
779
+ input: {},
780
+ output: "x".repeat(200_000),
781
+ title: "done",
782
+ metadata: {},
783
+ time: { start: Date.now(), end: Date.now() },
784
+ },
785
+ })
786
+ for (const text of ["second", "third"]) {
787
+ const msg = yield* ssn.updateMessage({
788
+ id: MessageID.ascending(),
789
+ role: "user",
790
+ sessionID: info.id,
791
+ agent: "build",
792
+ model: ref,
793
+ time: { created: Date.now() },
794
+ })
795
+ yield* ssn.updatePart({
796
+ id: PartID.ascending(),
797
+ messageID: msg.id,
798
+ sessionID: info.id,
799
+ type: "text",
800
+ text,
801
+ })
802
+ }
803
+
804
+ yield* compact.prune({ sessionID: info.id })
805
+
806
+ const msgs = yield* ssn.messages({ sessionID: info.id })
807
+ const part = msgs.flatMap((msg) => msg.parts).find((part) => part.type === "tool")
808
+ expect(part?.type).toBe("tool")
809
+ if (part?.type === "tool" && part.state.status === "completed") {
810
+ expect(part.state.time.compacted).toBeUndefined()
811
+ }
812
+ }),
813
+ ),
814
+ )
815
+ })
816
+
817
+ describe("session.compaction.process", () => {
818
+ it.instance(
819
+ "throws when parent is not a user message",
820
+ Effect.gen(function* () {
821
+ const test = yield* TestInstance
822
+ const ssn = yield* SessionNs.Service
823
+ const session = yield* ssn.create({})
824
+ const msg = yield* createUserMessage(session.id, "hello")
825
+ const reply = yield* createAssistantMessage(session.id, msg.id, test.directory)
826
+ const msgs = yield* ssn.messages({ sessionID: session.id })
827
+
828
+ const exit = yield* Effect.exit(
829
+ SessionCompaction.use.process({
830
+ parentID: reply.id,
831
+ messages: msgs,
832
+ sessionID: session.id,
833
+ auto: false,
834
+ }),
835
+ )
836
+
837
+ expect(Exit.isFailure(exit)).toBe(true)
838
+ if (Exit.isFailure(exit)) {
839
+ const error = Cause.squash(exit.cause)
840
+ expect(error).toBeInstanceOf(Error)
841
+ if (error instanceof Error) {
842
+ expect(error.message).toContain(`Compaction parent must be a user message: ${reply.id}`)
843
+ }
844
+ }
845
+ }),
846
+ )
847
+
848
+ it.instance(
849
+ "publishes compacted event on continue",
850
+ Effect.gen(function* () {
851
+ const events = yield* EventV2Bridge.Service
852
+ const ssn = yield* SessionNs.Service
853
+ const session = yield* ssn.create({})
854
+ const msg = yield* createUserMessage(session.id, "hello")
855
+ const msgs = yield* ssn.messages({ sessionID: session.id })
856
+ const done = yield* Deferred.make<void, Error>()
857
+ let seen = false
858
+ const unsub = yield* events.listen((evt) => {
859
+ if (evt.type !== SessionCompaction.Event.Compacted.type) return Effect.void
860
+ if ((evt.data as typeof SessionCompaction.Event.Compacted.data.Type).sessionID !== session.id)
861
+ return Effect.void
862
+ seen = true
863
+ Deferred.doneUnsafe(done, Effect.void)
864
+ return Effect.void
865
+ })
866
+ yield* Effect.addFinalizer(() => unsub)
867
+
868
+ const result = yield* SessionCompaction.use.process({
869
+ parentID: msg.id,
870
+ messages: msgs,
871
+ sessionID: session.id,
872
+ auto: false,
873
+ })
874
+
875
+ yield* Deferred.await(done).pipe(Effect.timeout("500 millis"))
876
+ expect(result).toBe("continue")
877
+ expect(seen).toBe(true)
878
+ }),
879
+ )
880
+
881
+ itCompaction.instance(
882
+ "marks summary message as errored on compact result",
883
+ Effect.gen(function* () {
884
+ const ssn = yield* SessionNs.Service
885
+ const session = yield* ssn.create({})
886
+ const msg = yield* createUserMessage(session.id, "hello")
887
+ const msgs = yield* ssn.messages({ sessionID: session.id })
888
+
889
+ const result = yield* SessionCompaction.use.process({
890
+ parentID: msg.id,
891
+ messages: msgs,
892
+ sessionID: session.id,
893
+ auto: false,
894
+ })
895
+
896
+ const summary = (yield* ssn.messages({ sessionID: session.id })).find(
897
+ (msg) => msg.info.role === "assistant" && msg.info.summary,
898
+ )
899
+
900
+ expect(result).toBe("stop")
901
+ expect(summary?.info.role).toBe("assistant")
902
+ if (summary?.info.role === "assistant") {
903
+ expect(summary.info.finish).toBe("error")
904
+ expect(JSON.stringify(summary.info.error)).toContain("Session too large to compact")
905
+ }
906
+ }).pipe(withCompaction({ result: "compact" })),
907
+ )
908
+
909
+ it.instance(
910
+ "adds synthetic continue prompt when auto is enabled",
911
+ Effect.gen(function* () {
912
+ const ssn = yield* SessionNs.Service
913
+ const session = yield* ssn.create({})
914
+ const msg = yield* createUserMessage(session.id, "hello")
915
+ const msgs = yield* ssn.messages({ sessionID: session.id })
916
+
917
+ const result = yield* SessionCompaction.use.process({
918
+ parentID: msg.id,
919
+ messages: msgs,
920
+ sessionID: session.id,
921
+ auto: true,
922
+ })
923
+
924
+ const all = yield* ssn.messages({ sessionID: session.id })
925
+ const last = all.at(-1)
926
+
927
+ expect(result).toBe("continue")
928
+ expect(last?.info.role).toBe("user")
929
+ expect(last?.parts[0]).toMatchObject({
930
+ type: "text",
931
+ synthetic: true,
932
+ metadata: { compaction_continue: true },
933
+ })
934
+ if (last?.parts[0]?.type === "text") {
935
+ expect(last.parts[0].text).toContain("Continue if you have next steps")
936
+ }
937
+ }),
938
+ )
939
+
940
+ itCompaction.instance(
941
+ "persists tail_start_id for retained recent turns",
942
+ Effect.gen(function* () {
943
+ const ssn = yield* SessionNs.Service
944
+ const session = yield* ssn.create({})
945
+ yield* createUserMessage(session.id, "first")
946
+ const keep = yield* createUserMessage(session.id, "second")
947
+ yield* createUserMessage(session.id, "third")
948
+ yield* createSummaryCompaction(session.id)
949
+
950
+ const msgs = yield* ssn.messages({ sessionID: session.id })
951
+ const parent = msgs.at(-1)?.info.id
952
+ expect(parent).toBeTruthy()
953
+ yield* SessionCompaction.use.process({
954
+ parentID: parent!,
955
+ messages: msgs,
956
+ sessionID: session.id,
957
+ auto: false,
958
+ })
959
+
960
+ const part = yield* readCompactionPart(session.id)
961
+ expect(part?.type).toBe("compaction")
962
+ expect(part?.tail_start_id).toBe(keep.id)
963
+ }).pipe(withCompaction({ config: cfg({ tail_turns: 2, preserve_recent_tokens: 10_000 }) })),
964
+ )
965
+
966
+ itCompaction.instance(
967
+ "shrinks retained tail to fit preserve token budget",
968
+ Effect.gen(function* () {
969
+ const ssn = yield* SessionNs.Service
970
+ const session = yield* ssn.create({})
971
+ yield* createUserMessage(session.id, "first")
972
+ yield* createUserMessage(session.id, "x".repeat(2_000))
973
+ const keep = yield* createUserMessage(session.id, "tiny")
974
+ yield* createSummaryCompaction(session.id)
975
+
976
+ const msgs = yield* ssn.messages({ sessionID: session.id })
977
+ const parent = msgs.at(-1)?.info.id
978
+ expect(parent).toBeTruthy()
979
+ yield* SessionCompaction.use.process({
980
+ parentID: parent!,
981
+ messages: msgs,
982
+ sessionID: session.id,
983
+ auto: false,
984
+ })
985
+
986
+ const part = yield* readCompactionPart(session.id)
987
+ expect(part?.type).toBe("compaction")
988
+ expect(part?.tail_start_id).toBe(keep.id)
989
+ }).pipe(withCompaction({ config: cfg({ tail_turns: 2, preserve_recent_tokens: 100 }) })),
990
+ )
991
+
992
+ itCompaction.instance(
993
+ "falls back to full summary when even one recent turn exceeds preserve token budget",
994
+ () => {
995
+ const stub = llm()
996
+ let captured = ""
997
+ stub.push(reply("summary", (input) => (captured = JSON.stringify(input.messages))))
998
+ return Effect.gen(function* () {
999
+ const ssn = yield* SessionNs.Service
1000
+ const session = yield* ssn.create({})
1001
+ yield* createUserMessage(session.id, "first")
1002
+ yield* createUserMessage(session.id, "y".repeat(2_000))
1003
+ yield* createSummaryCompaction(session.id)
1004
+
1005
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1006
+ const parent = msgs.at(-1)?.info.id
1007
+ expect(parent).toBeTruthy()
1008
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1009
+
1010
+ const part = yield* readCompactionPart(session.id)
1011
+ expect(part?.type).toBe("compaction")
1012
+ expect(part?.tail_start_id).toBeUndefined()
1013
+ expect(captured).toContain("yyyy")
1014
+ }).pipe(withCompaction({ llm: stub.layer, config: cfg({ tail_turns: 1, preserve_recent_tokens: 20 }) }))
1015
+ },
1016
+ { git: true },
1017
+ )
1018
+
1019
+ itCompaction.instance(
1020
+ "falls back to full summary when retained tail media exceeds preserve token budget",
1021
+ () => {
1022
+ const stub = llm()
1023
+ let captured = ""
1024
+ stub.push(reply("summary", (input) => (captured = JSON.stringify(input.messages))))
1025
+ return Effect.gen(function* () {
1026
+ const ssn = yield* SessionNs.Service
1027
+ const session = yield* ssn.create({})
1028
+ yield* createUserMessage(session.id, "older")
1029
+ const recent = yield* createUserMessage(session.id, "recent image turn")
1030
+ yield* ssn.updatePart({
1031
+ id: PartID.ascending(),
1032
+ messageID: recent.id,
1033
+ sessionID: session.id,
1034
+ type: "file",
1035
+ mime: "image/png",
1036
+ filename: "big.png",
1037
+ url: `data:image/png;base64,${"a".repeat(4_000)}`,
1038
+ })
1039
+ yield* createSummaryCompaction(session.id)
1040
+
1041
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1042
+ const parent = msgs.at(-1)?.info.id
1043
+ expect(parent).toBeTruthy()
1044
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1045
+
1046
+ const part = yield* readCompactionPart(session.id)
1047
+ expect(part?.type).toBe("compaction")
1048
+ expect(part?.tail_start_id).toBeUndefined()
1049
+ expect(captured).toContain("recent image turn")
1050
+ expect(captured).toContain("Attached image/png: big.png")
1051
+ }).pipe(withCompaction({ llm: stub.layer, config: cfg({ tail_turns: 1, preserve_recent_tokens: 100 }) }))
1052
+ },
1053
+ { git: true },
1054
+ )
1055
+
1056
+ itCompaction.instance(
1057
+ "retains a split turn suffix when a later message fits the preserve token budget",
1058
+ () => {
1059
+ const stub = llm()
1060
+ let captured = ""
1061
+ stub.push(reply("summary", (input) => (captured = JSON.stringify(input.messages))))
1062
+ return Effect.gen(function* () {
1063
+ const test = yield* TestInstance
1064
+ const ssn = yield* SessionNs.Service
1065
+ const session = yield* ssn.create({})
1066
+ yield* createUserMessage(session.id, "older")
1067
+ const recent = yield* createUserMessage(session.id, "recent turn")
1068
+ const large = yield* createAssistantMessage(session.id, recent.id, test.directory)
1069
+ yield* ssn.updatePart({
1070
+ id: PartID.ascending(),
1071
+ messageID: large.id,
1072
+ sessionID: session.id,
1073
+ type: "text",
1074
+ text: "z".repeat(2_000),
1075
+ })
1076
+ const keep = yield* createAssistantMessage(session.id, recent.id, test.directory)
1077
+ yield* ssn.updatePart({
1078
+ id: PartID.ascending(),
1079
+ messageID: keep.id,
1080
+ sessionID: session.id,
1081
+ type: "text",
1082
+ text: "keep tail",
1083
+ })
1084
+ yield* createSummaryCompaction(session.id)
1085
+
1086
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1087
+ const parent = msgs.at(-1)?.info.id
1088
+ expect(parent).toBeTruthy()
1089
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1090
+
1091
+ const part = yield* readCompactionPart(session.id)
1092
+ expect(part?.type).toBe("compaction")
1093
+ expect(part?.tail_start_id).toBe(keep.id)
1094
+ expect(captured).toContain("zzzz")
1095
+ expect(captured).not.toContain("keep tail")
1096
+
1097
+ const filtered = MessageV2.filterCompacted(yield* MessageV2.stream(session.id))
1098
+ expect(filtered.map((msg) => msg.info.id).slice(0, 3)).toEqual([parent!, expect.any(String), keep.id])
1099
+ expect(filtered[1]?.info.role).toBe("assistant")
1100
+ expect(filtered[1]?.info.role === "assistant" ? filtered[1].info.summary : false).toBe(true)
1101
+ expect(filtered.map((msg) => msg.info.id)).not.toContain(large.id)
1102
+ }).pipe(withCompaction({ llm: stub.layer, config: cfg({ tail_turns: 1, preserve_recent_tokens: 100 }) }))
1103
+ },
1104
+ { git: true },
1105
+ )
1106
+
1107
+ itCompaction.instance(
1108
+ "allows plugins to disable synthetic continue prompt",
1109
+ Effect.gen(function* () {
1110
+ const ssn = yield* SessionNs.Service
1111
+ const session = yield* ssn.create({})
1112
+ const msg = yield* createUserMessage(session.id, "hello")
1113
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1114
+
1115
+ const result = yield* SessionCompaction.use.process({
1116
+ parentID: msg.id,
1117
+ messages: msgs,
1118
+ sessionID: session.id,
1119
+ auto: true,
1120
+ })
1121
+
1122
+ const all = yield* ssn.messages({ sessionID: session.id })
1123
+ const last = all.at(-1)
1124
+
1125
+ expect(result).toBe("continue")
1126
+ expect(last?.info.role).toBe("assistant")
1127
+ expect(
1128
+ all.some(
1129
+ (msg) =>
1130
+ msg.info.role === "user" &&
1131
+ msg.parts.some(
1132
+ (part) => part.type === "text" && part.synthetic && part.text.includes("Continue if you have next steps"),
1133
+ ),
1134
+ ),
1135
+ ).toBe(false)
1136
+ }).pipe(withCompaction({ plugin: autocontinue(false) })),
1137
+ )
1138
+
1139
+ it.instance(
1140
+ "replays the prior user turn on overflow when earlier context exists",
1141
+ Effect.gen(function* () {
1142
+ const ssn = yield* SessionNs.Service
1143
+ const session = yield* ssn.create({})
1144
+ yield* createUserMessage(session.id, "root")
1145
+ const replay = yield* createUserMessage(session.id, "image")
1146
+ yield* ssn.updatePart({
1147
+ id: PartID.ascending(),
1148
+ messageID: replay.id,
1149
+ sessionID: session.id,
1150
+ type: "file",
1151
+ mime: "image/png",
1152
+ filename: "cat.png",
1153
+ url: "https://example.com/cat.png",
1154
+ })
1155
+ const msg = yield* createUserMessage(session.id, "current")
1156
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1157
+
1158
+ const result = yield* SessionCompaction.use.process({
1159
+ parentID: msg.id,
1160
+ messages: msgs,
1161
+ sessionID: session.id,
1162
+ auto: true,
1163
+ overflow: true,
1164
+ })
1165
+
1166
+ const last = (yield* ssn.messages({ sessionID: session.id })).at(-1)
1167
+
1168
+ expect(result).toBe("continue")
1169
+ expect(last?.info.role).toBe("user")
1170
+ expect(last?.parts.some((part) => part.type === "file")).toBe(false)
1171
+ expect(
1172
+ last?.parts.some((part) => part.type === "text" && part.text.includes("Attached image/png: cat.png")),
1173
+ ).toBe(true)
1174
+ }),
1175
+ )
1176
+
1177
+ it.instance(
1178
+ "falls back to overflow guidance when no replayable turn exists",
1179
+ Effect.gen(function* () {
1180
+ const ssn = yield* SessionNs.Service
1181
+ const session = yield* ssn.create({})
1182
+ yield* createUserMessage(session.id, "earlier")
1183
+ const msg = yield* createUserMessage(session.id, "current")
1184
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1185
+
1186
+ const result = yield* SessionCompaction.use.process({
1187
+ parentID: msg.id,
1188
+ messages: msgs,
1189
+ sessionID: session.id,
1190
+ auto: true,
1191
+ overflow: true,
1192
+ })
1193
+
1194
+ const last = (yield* ssn.messages({ sessionID: session.id })).at(-1)
1195
+
1196
+ expect(result).toBe("continue")
1197
+ expect(last?.info.role).toBe("user")
1198
+ if (last?.parts[0]?.type === "text") {
1199
+ expect(last.parts[0].text).toContain("previous request exceeded the provider's size limit")
1200
+ }
1201
+ }),
1202
+ )
1203
+
1204
+ itCompaction.instance(
1205
+ "stops quickly when aborted during retry backoff",
1206
+ () => {
1207
+ const stub = llm()
1208
+ stub.push(
1209
+ Stream.fromAsyncIterable(
1210
+ {
1211
+ async *[Symbol.asyncIterator]() {
1212
+ yield LLMEvent.stepStart({ index: 0 })
1213
+ throw new APICallError({
1214
+ message: "boom",
1215
+ url: "https://example.com/v1/chat/completions",
1216
+ requestBodyValues: {},
1217
+ statusCode: 503,
1218
+ responseHeaders: { "retry-after-ms": "10000" },
1219
+ responseBody: '{"error":"boom"}',
1220
+ isRetryable: true,
1221
+ })
1222
+ },
1223
+ },
1224
+ (err) => err,
1225
+ ),
1226
+ )
1227
+
1228
+ return Effect.gen(function* () {
1229
+ const ssn = yield* SessionNs.Service
1230
+ const events = yield* EventV2Bridge.Service
1231
+ const ready = yield* Deferred.make<void>()
1232
+ const session = yield* ssn.create({})
1233
+ const msg = yield* createUserMessage(session.id, "hello")
1234
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1235
+ const off = yield* events.listen((evt) => {
1236
+ if (evt.type !== SessionStatus.Event.Status.type) return Effect.void
1237
+ const data = evt.data as typeof SessionStatus.Event.Status.data.Type
1238
+ if (data.sessionID !== session.id || data.status.type !== "retry") return Effect.void
1239
+ Deferred.doneUnsafe(ready, Effect.void)
1240
+ return Effect.void
1241
+ })
1242
+ yield* Effect.addFinalizer(() => off)
1243
+
1244
+ const fiber = yield* SessionCompaction.use
1245
+ .process({
1246
+ parentID: msg.id,
1247
+ messages: msgs,
1248
+ sessionID: session.id,
1249
+ auto: false,
1250
+ })
1251
+ .pipe(Effect.forkChild)
1252
+
1253
+ yield* Deferred.await(ready).pipe(Effect.timeout("1 second"))
1254
+ const start = Date.now()
1255
+ yield* Fiber.interrupt(fiber)
1256
+ const exit = yield* Fiber.await(fiber).pipe(Effect.timeout("250 millis"))
1257
+
1258
+ expect(Exit.isFailure(exit)).toBe(true)
1259
+ if (Exit.isFailure(exit)) {
1260
+ expect(Cause.hasInterrupts(exit.cause)).toBe(true)
1261
+ expect(Date.now() - start).toBeLessThan(250)
1262
+ }
1263
+ }).pipe(withCompaction({ llm: stub.layer }))
1264
+ },
1265
+ { git: true },
1266
+ )
1267
+
1268
+ itCompaction.instance(
1269
+ "does not leave a summary assistant when aborted before processor setup",
1270
+ () =>
1271
+ Effect.gen(function* () {
1272
+ const ready = yield* Deferred.make<void>()
1273
+ return yield* Effect.gen(function* () {
1274
+ const ssn = yield* SessionNs.Service
1275
+ const session = yield* ssn.create({})
1276
+ const msg = yield* createUserMessage(session.id, "hello")
1277
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1278
+ const fiber = yield* SessionCompaction.use
1279
+ .process({
1280
+ parentID: msg.id,
1281
+ messages: msgs,
1282
+ sessionID: session.id,
1283
+ auto: false,
1284
+ })
1285
+ .pipe(Effect.forkChild)
1286
+
1287
+ yield* Deferred.await(ready).pipe(Effect.timeout("1 second"))
1288
+ yield* Fiber.interrupt(fiber)
1289
+ const exit = yield* Fiber.await(fiber).pipe(Effect.timeout("250 millis"))
1290
+ const all = yield* ssn.messages({ sessionID: session.id })
1291
+
1292
+ expect(Exit.isFailure(exit)).toBe(true)
1293
+ if (Exit.isFailure(exit)) expect(Cause.hasInterrupts(exit.cause)).toBe(true)
1294
+ expect(all.some((msg) => msg.info.role === "assistant" && msg.info.summary)).toBe(false)
1295
+ }).pipe(withCompaction({ plugin: plugin(ready) }))
1296
+ }),
1297
+ { git: true },
1298
+ )
1299
+
1300
+ itCompaction.instance(
1301
+ "silently drops reasoning-delta arriving without prior reasoning-start",
1302
+ () => {
1303
+ // Regression: PR initially auto-created a reasoning Part for orphan deltas (no preceding
1304
+ // reasoning-start). Reverted to match dev — drop silently. Pinned here so any future
1305
+ // change to processor.ts reasoning-delta handling triggers this test.
1306
+ const stub = llm()
1307
+ stub.push(
1308
+ Stream.make(
1309
+ LLMEvent.reasoningDelta({ id: "orphan-1", text: "stray reasoning" }),
1310
+ LLMEvent.textStart({ id: "txt-0" }),
1311
+ LLMEvent.textDelta({ id: "txt-0", text: "summary" }),
1312
+ LLMEvent.textEnd({ id: "txt-0" }),
1313
+ LLMEvent.stepFinish({ index: 0, reason: "stop", usage: basicUsage() }),
1314
+ LLMEvent.finish({ reason: "stop", usage: basicUsage() }),
1315
+ ),
1316
+ )
1317
+ return Effect.gen(function* () {
1318
+ const ssn = yield* SessionNs.Service
1319
+ const session = yield* ssn.create({})
1320
+ const msg = yield* createUserMessage(session.id, "hello")
1321
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1322
+ yield* SessionCompaction.use.process({
1323
+ parentID: msg.id,
1324
+ messages: msgs,
1325
+ sessionID: session.id,
1326
+ auto: false,
1327
+ })
1328
+
1329
+ const summary = (yield* ssn.messages({ sessionID: session.id })).find(
1330
+ (item) => item.info.role === "assistant" && item.info.summary,
1331
+ )
1332
+ expect(summary?.parts.some((part) => part.type === "reasoning")).toBe(false)
1333
+ // Sanity: the text part still got through.
1334
+ expect(summary?.parts.some((part) => part.type === "text" && part.text === "summary")).toBe(true)
1335
+ }).pipe(withCompaction({ llm: stub.layer }))
1336
+ },
1337
+ { git: true },
1338
+ )
1339
+
1340
+ itCompaction.instance(
1341
+ "does not allow tool calls while generating the summary",
1342
+ () => {
1343
+ const stub = llm()
1344
+ stub.push(
1345
+ Stream.make(
1346
+ LLMEvent.toolCall({ id: "call-1", name: "_noop", input: {} }),
1347
+ LLMEvent.stepFinish({
1348
+ index: 0,
1349
+ reason: "tool-calls",
1350
+ usage: basicUsage(),
1351
+ }),
1352
+ LLMEvent.finish({
1353
+ reason: "tool-calls",
1354
+ usage: basicUsage(),
1355
+ }),
1356
+ ),
1357
+ )
1358
+ return Effect.gen(function* () {
1359
+ const ssn = yield* SessionNs.Service
1360
+ const session = yield* ssn.create({})
1361
+ const msg = yield* createUserMessage(session.id, "hello")
1362
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1363
+ yield* SessionCompaction.use.process({ parentID: msg.id, messages: msgs, sessionID: session.id, auto: false })
1364
+
1365
+ const summary = (yield* ssn.messages({ sessionID: session.id })).find(
1366
+ (item) => item.info.role === "assistant" && item.info.summary,
1367
+ )
1368
+
1369
+ expect(summary?.info.role).toBe("assistant")
1370
+ expect(summary?.parts.some((part) => part.type === "tool")).toBe(false)
1371
+ }).pipe(withCompaction({ llm: stub.layer }))
1372
+ },
1373
+ { git: true },
1374
+ )
1375
+
1376
+ itCompaction.instance(
1377
+ "summarizes only the head while keeping recent tail out of summary input",
1378
+ () => {
1379
+ const stub = llm()
1380
+ let captured = ""
1381
+ stub.push(
1382
+ reply("summary", (input) => {
1383
+ captured = JSON.stringify(input.messages)
1384
+ }),
1385
+ )
1386
+ return Effect.gen(function* () {
1387
+ const ssn = yield* SessionNs.Service
1388
+ const session = yield* ssn.create({})
1389
+ yield* createUserMessage(session.id, "older context")
1390
+ yield* createUserMessage(session.id, "keep this turn")
1391
+ yield* createUserMessage(session.id, "and this one too")
1392
+ yield* createCompactionMarker(session.id)
1393
+
1394
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1395
+ const parent = msgs.at(-1)?.info.id
1396
+ expect(parent).toBeTruthy()
1397
+ yield* SessionCompaction.use.process({
1398
+ parentID: parent!,
1399
+ messages: msgs,
1400
+ sessionID: session.id,
1401
+ auto: false,
1402
+ })
1403
+
1404
+ expect(captured).toContain("older context")
1405
+ expect(captured).not.toContain("keep this turn")
1406
+ expect(captured).not.toContain("and this one too")
1407
+ expect(captured).not.toContain("What did we do so far?")
1408
+ }).pipe(withCompaction({ llm: stub.layer }))
1409
+ },
1410
+ { git: true },
1411
+ )
1412
+
1413
+ itCompaction.instance(
1414
+ "anchors repeated compactions with the previous summary",
1415
+ () => {
1416
+ const stub = llm()
1417
+ let captured = ""
1418
+ stub.push(reply("summary one"))
1419
+ stub.push(
1420
+ reply("summary two", (input) => {
1421
+ captured = JSON.stringify(input.messages)
1422
+ }),
1423
+ )
1424
+
1425
+ return Effect.gen(function* () {
1426
+ const ssn = yield* SessionNs.Service
1427
+ const session = yield* ssn.create({})
1428
+ yield* createUserMessage(session.id, "older context")
1429
+ yield* createUserMessage(session.id, "keep this turn")
1430
+ yield* createCompactionMarker(session.id)
1431
+
1432
+ let msgs = yield* ssn.messages({ sessionID: session.id })
1433
+ let parent = msgs.at(-1)?.info.id
1434
+ expect(parent).toBeTruthy()
1435
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1436
+
1437
+ yield* createUserMessage(session.id, "latest turn")
1438
+ yield* createCompactionMarker(session.id)
1439
+
1440
+ msgs = MessageV2.filterCompacted(yield* MessageV2.stream(session.id))
1441
+ parent = msgs.at(-1)?.info.id
1442
+ expect(parent).toBeTruthy()
1443
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1444
+
1445
+ expect(captured).toContain("<previous-summary>")
1446
+ expect(captured).toContain("summary one")
1447
+ expect(captured.match(/summary one/g)?.length).toBe(1)
1448
+ expect(captured).toContain("## Constraints & Preferences")
1449
+ expect(captured).toContain("## Progress")
1450
+ }).pipe(withCompaction({ llm: stub.layer }))
1451
+ },
1452
+ { git: true },
1453
+ )
1454
+
1455
+ itCompaction.instance("keeps recent pre-compaction turns across repeated compactions", () => {
1456
+ const stub = llm()
1457
+ stub.push(reply("summary one"))
1458
+ stub.push(reply("summary two"))
1459
+
1460
+ return Effect.gen(function* () {
1461
+ const ssn = yield* SessionNs.Service
1462
+ const session = yield* ssn.create({})
1463
+ const u1 = yield* createUserMessage(session.id, "one")
1464
+ const u2 = yield* createUserMessage(session.id, "two")
1465
+ const u3 = yield* createUserMessage(session.id, "three")
1466
+ yield* createCompactionMarker(session.id)
1467
+
1468
+ let msgs = yield* ssn.messages({ sessionID: session.id })
1469
+ let parent = msgs.at(-1)?.info.id
1470
+ expect(parent).toBeTruthy()
1471
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1472
+
1473
+ const u4 = yield* createUserMessage(session.id, "four")
1474
+ yield* createCompactionMarker(session.id)
1475
+
1476
+ msgs = MessageV2.filterCompacted(yield* MessageV2.stream(session.id))
1477
+ parent = msgs.at(-1)?.info.id
1478
+ expect(parent).toBeTruthy()
1479
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1480
+
1481
+ const filtered = MessageV2.filterCompacted(yield* MessageV2.stream(session.id))
1482
+ const ids = filtered.map((msg) => msg.info.id)
1483
+
1484
+ expect(ids).not.toContain(u1.id)
1485
+ expect(ids).not.toContain(u2.id)
1486
+ expect(ids).toContain(u3.id)
1487
+ expect(ids).toContain(u4.id)
1488
+ expect(filtered.some((msg) => msg.info.role === "assistant" && msg.info.summary)).toBe(true)
1489
+ expect(
1490
+ filtered.some((msg) => msg.info.role === "user" && msg.parts.some((part) => part.type === "compaction")),
1491
+ ).toBe(true)
1492
+ }).pipe(withCompaction({ llm: stub.layer, config: cfg({ tail_turns: 2, preserve_recent_tokens: 10_000 }) }))
1493
+ })
1494
+
1495
+ itCompaction.instance(
1496
+ "ignores previous summaries when sizing the retained tail",
1497
+ Effect.gen(function* () {
1498
+ const ssn = yield* SessionNs.Service
1499
+ const test = yield* TestInstance
1500
+ const session = yield* ssn.create({})
1501
+ yield* createUserMessage(session.id, "older")
1502
+ const keep = yield* createUserMessage(session.id, "keep this turn")
1503
+ const keepReply = yield* createAssistantMessage(session.id, keep.id, test.directory)
1504
+ yield* ssn.updatePart({
1505
+ id: PartID.ascending(),
1506
+ messageID: keepReply.id,
1507
+ sessionID: session.id,
1508
+ type: "text",
1509
+ text: "keep reply",
1510
+ })
1511
+
1512
+ yield* createCompactionMarker(session.id)
1513
+ const firstCompaction = (yield* ssn.messages({ sessionID: session.id })).at(-1)?.info.id
1514
+ expect(firstCompaction).toBeTruthy()
1515
+ yield* createSummaryAssistantMessage(session.id, firstCompaction!, test.directory, "summary ".repeat(800))
1516
+
1517
+ const recent = yield* createUserMessage(session.id, "recent turn")
1518
+ const recentReply = yield* createAssistantMessage(session.id, recent.id, test.directory)
1519
+ yield* ssn.updatePart({
1520
+ id: PartID.ascending(),
1521
+ messageID: recentReply.id,
1522
+ sessionID: session.id,
1523
+ type: "text",
1524
+ text: "recent reply",
1525
+ })
1526
+
1527
+ yield* createCompactionMarker(session.id)
1528
+ const msgs = yield* ssn.messages({ sessionID: session.id })
1529
+ const parent = msgs.at(-1)?.info.id
1530
+ expect(parent).toBeTruthy()
1531
+ yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false })
1532
+
1533
+ const part = yield* readCompactionPart(session.id)
1534
+ expect(part?.type).toBe("compaction")
1535
+ expect(part?.tail_start_id).toBe(keep.id)
1536
+ }).pipe(withCompaction({ config: cfg({ tail_turns: 2, preserve_recent_tokens: 500 }) })),
1537
+ )
1538
+ })
1539
+
1540
+ describe("util.token.estimate", () => {
1541
+ test("estimates tokens from text (4 chars per token)", () => {
1542
+ const text = "x".repeat(4000)
1543
+ expect(Token.estimate(text)).toBe(1000)
1544
+ })
1545
+
1546
+ test("estimates tokens from larger text", () => {
1547
+ const text = "y".repeat(20_000)
1548
+ expect(Token.estimate(text)).toBe(5000)
1549
+ })
1550
+
1551
+ test("returns 0 for empty string", () => {
1552
+ expect(Token.estimate("")).toBe(0)
1553
+ })
1554
+ })
1555
+
1556
+ describe("SessionNs.getUsage", () => {
1557
+ test("normalizes standard usage to token format", () => {
1558
+ const model = createModel({ context: 100_000, output: 32_000 })
1559
+ const result = SessionNs.getUsage({
1560
+ model,
1561
+ usage: usage({ inputTokens: 1000, outputTokens: 500, totalTokens: 1500 }),
1562
+ })
1563
+
1564
+ expect(result.tokens.input).toBe(1000)
1565
+ expect(result.tokens.output).toBe(500)
1566
+ expect(result.tokens.reasoning).toBe(0)
1567
+ expect(result.tokens.cache.read).toBe(0)
1568
+ expect(result.tokens.cache.write).toBe(0)
1569
+ })
1570
+
1571
+ test("extracts cached tokens to cache.read", () => {
1572
+ const model = createModel({ context: 100_000, output: 32_000 })
1573
+ const result = SessionNs.getUsage({
1574
+ model,
1575
+ usage: usage({ inputTokens: 1000, outputTokens: 500, totalTokens: 1500, cacheReadInputTokens: 200 }),
1576
+ })
1577
+
1578
+ expect(result.tokens.input).toBe(800)
1579
+ expect(result.tokens.cache.read).toBe(200)
1580
+ })
1581
+
1582
+ test("handles anthropic cache write metadata", () => {
1583
+ const model = createModel({ context: 100_000, output: 32_000 })
1584
+ const result = SessionNs.getUsage({
1585
+ model,
1586
+ usage: usage({ inputTokens: 1000, outputTokens: 500, totalTokens: 1500 }),
1587
+ metadata: {
1588
+ anthropic: {
1589
+ cacheCreationInputTokens: 300,
1590
+ },
1591
+ },
1592
+ })
1593
+
1594
+ expect(result.tokens.cache.write).toBe(300)
1595
+ })
1596
+
1597
+ test("subtracts cached tokens for anthropic provider", () => {
1598
+ const model = createModel({ context: 100_000, output: 32_000 })
1599
+ // AI SDK v6 normalizes inputTokens to include cached tokens for all providers
1600
+ const result = SessionNs.getUsage({
1601
+ model,
1602
+ usage: usage({ inputTokens: 1000, outputTokens: 500, totalTokens: 1500, cacheReadInputTokens: 200 }),
1603
+ metadata: {
1604
+ anthropic: {},
1605
+ },
1606
+ })
1607
+
1608
+ expect(result.tokens.input).toBe(800)
1609
+ expect(result.tokens.cache.read).toBe(200)
1610
+ })
1611
+
1612
+ test("separates reasoning tokens from output tokens", () => {
1613
+ const model = createModel({ context: 100_000, output: 32_000 })
1614
+ const result = SessionNs.getUsage({
1615
+ model,
1616
+ usage: usage({ inputTokens: 1000, outputTokens: 500, reasoningTokens: 100, totalTokens: 1500 }),
1617
+ })
1618
+
1619
+ expect(result.tokens.input).toBe(1000)
1620
+ expect(result.tokens.output).toBe(400)
1621
+ expect(result.tokens.reasoning).toBe(100)
1622
+ expect(result.tokens.total).toBe(1500)
1623
+ })
1624
+
1625
+ test("does not double count reasoning tokens in cost", () => {
1626
+ const model = createModel({
1627
+ context: 100_000,
1628
+ output: 32_000,
1629
+ cost: {
1630
+ input: 0,
1631
+ output: 15,
1632
+ cache: { read: 0, write: 0 },
1633
+ },
1634
+ })
1635
+ const result = SessionNs.getUsage({
1636
+ model,
1637
+ usage: usage({ inputTokens: 0, outputTokens: 1_000_000, reasoningTokens: 250_000, totalTokens: 1_000_000 }),
1638
+ })
1639
+
1640
+ expect(result.tokens.output).toBe(750_000)
1641
+ expect(result.tokens.reasoning).toBe(250_000)
1642
+ expect(result.cost).toBe(15)
1643
+ })
1644
+
1645
+ test("handles undefined optional values gracefully", () => {
1646
+ const model = createModel({ context: 100_000, output: 32_000 })
1647
+ const result = SessionNs.getUsage({
1648
+ model,
1649
+ usage: usage({ inputTokens: 0, outputTokens: 0, totalTokens: 0 }),
1650
+ })
1651
+
1652
+ expect(result.tokens.input).toBe(0)
1653
+ expect(result.tokens.output).toBe(0)
1654
+ expect(result.tokens.reasoning).toBe(0)
1655
+ expect(result.tokens.cache.read).toBe(0)
1656
+ expect(result.tokens.cache.write).toBe(0)
1657
+ expect(Number.isNaN(result.cost)).toBe(false)
1658
+ })
1659
+
1660
+ test("calculates cost correctly", () => {
1661
+ const model = createModel({
1662
+ context: 100_000,
1663
+ output: 32_000,
1664
+ cost: {
1665
+ input: 3,
1666
+ output: 15,
1667
+ cache: { read: 0.3, write: 3.75 },
1668
+ },
1669
+ })
1670
+ const result = SessionNs.getUsage({
1671
+ model,
1672
+ usage: usage({ inputTokens: 1_000_000, outputTokens: 100_000, totalTokens: 1_100_000 }),
1673
+ })
1674
+
1675
+ expect(result.cost).toBe(3 + 1.5)
1676
+ })
1677
+
1678
+ test("uses authoritative Copilot billed cost when provided", () => {
1679
+ const result = SessionNs.getUsage({
1680
+ model: createModel({
1681
+ context: 100_000,
1682
+ output: 32_000,
1683
+ cost: { input: 3, output: 15, cache: { read: 0.3, write: 0.3 } },
1684
+ }),
1685
+ usage: usage({ inputTokens: 11_774, outputTokens: 39, totalTokens: 11_813 }),
1686
+ metadata: { copilot: { totalNanoAiu: 4_473_525_000 } },
1687
+ })
1688
+
1689
+ expect(result.cost).toBe(0.04473525)
1690
+ })
1691
+
1692
+ test("uses matching context cost tier before over-200k fallback", () => {
1693
+ const model = createModel({
1694
+ context: 1_000_000,
1695
+ output: 32_000,
1696
+ cost: {
1697
+ input: 1,
1698
+ output: 2,
1699
+ cache: { read: 0.1, write: 0.5 },
1700
+ tiers: [
1701
+ {
1702
+ input: 3,
1703
+ output: 4,
1704
+ cache: { read: 0.3, write: 1.5 },
1705
+ tier: { type: "context", size: 200_000 },
1706
+ },
1707
+ {
1708
+ input: 5,
1709
+ output: 6,
1710
+ cache: { read: 0.5, write: 2.5 },
1711
+ tier: { type: "context", size: 500_000 },
1712
+ },
1713
+ ],
1714
+ experimentalOver200K: {
1715
+ input: 100,
1716
+ output: 100,
1717
+ cache: { read: 100, write: 100 },
1718
+ },
1719
+ },
1720
+ })
1721
+ const result = SessionNs.getUsage({
1722
+ model,
1723
+ usage: usage({
1724
+ inputTokens: 650_000,
1725
+ outputTokens: 100_000,
1726
+ totalTokens: 750_000,
1727
+ cacheReadInputTokens: 100_000,
1728
+ }),
1729
+ })
1730
+
1731
+ expect(result.tokens.input).toBe(550_000)
1732
+ expect(result.cost).toBe(2.75 + 0.6 + 0.05)
1733
+ })
1734
+
1735
+ test("falls back to over-200k pricing when no cost tier matches", () => {
1736
+ const model = createModel({
1737
+ context: 1_000_000,
1738
+ output: 32_000,
1739
+ cost: {
1740
+ input: 1,
1741
+ output: 2,
1742
+ cache: { read: 0.1, write: 0.5 },
1743
+ tiers: [
1744
+ {
1745
+ input: 5,
1746
+ output: 6,
1747
+ cache: { read: 0.5, write: 2.5 },
1748
+ tier: { type: "context", size: 500_000 },
1749
+ },
1750
+ ],
1751
+ experimentalOver200K: {
1752
+ input: 3,
1753
+ output: 4,
1754
+ cache: { read: 0.3, write: 1.5 },
1755
+ },
1756
+ },
1757
+ })
1758
+ const result = SessionNs.getUsage({
1759
+ model,
1760
+ usage: usage({ inputTokens: 300_000, outputTokens: 100_000, totalTokens: 400_000 }),
1761
+ })
1762
+
1763
+ expect(result.cost).toBe(0.9 + 0.4)
1764
+ })
1765
+
1766
+ test.each(["@ai-sdk/anthropic", "@ai-sdk/amazon-bedrock", "@ai-sdk/google-vertex/anthropic"])(
1767
+ "computes total from components for %s models",
1768
+ (npm) => {
1769
+ const model = createModel({ context: 100_000, output: 32_000, npm })
1770
+ // AI SDK v6: inputTokens includes cached tokens for all providers
1771
+ const item = usage({
1772
+ inputTokens: 1000,
1773
+ outputTokens: 500,
1774
+ totalTokens: 1500,
1775
+ cacheReadInputTokens: 200,
1776
+ })
1777
+ if (npm === "@ai-sdk/amazon-bedrock") {
1778
+ const result = SessionNs.getUsage({
1779
+ model,
1780
+ usage: item,
1781
+ metadata: {
1782
+ bedrock: {
1783
+ usage: {
1784
+ cacheWriteInputTokens: 300,
1785
+ },
1786
+ },
1787
+ },
1788
+ })
1789
+
1790
+ // inputTokens (1000) includes cache, so adjusted = 1000 - 200 - 300 = 500
1791
+ expect(result.tokens.input).toBe(500)
1792
+ expect(result.tokens.cache.read).toBe(200)
1793
+ expect(result.tokens.cache.write).toBe(300)
1794
+ // total = adjusted (500) + output (500) + cacheRead (200) + cacheWrite (300)
1795
+ expect(result.tokens.total).toBe(1500)
1796
+ return
1797
+ }
1798
+
1799
+ const result = SessionNs.getUsage({
1800
+ model,
1801
+ usage: item,
1802
+ metadata: {
1803
+ anthropic: {
1804
+ cacheCreationInputTokens: 300,
1805
+ },
1806
+ },
1807
+ })
1808
+
1809
+ // inputTokens (1000) includes cache, so adjusted = 1000 - 200 - 300 = 500
1810
+ expect(result.tokens.input).toBe(500)
1811
+ expect(result.tokens.cache.read).toBe(200)
1812
+ expect(result.tokens.cache.write).toBe(300)
1813
+ // total = adjusted (500) + output (500) + cacheRead (200) + cacheWrite (300)
1814
+ expect(result.tokens.total).toBe(1500)
1815
+ },
1816
+ )
1817
+
1818
+ test("extracts cache write tokens from vertex metadata key", () => {
1819
+ const model = createModel({ context: 100_000, output: 32_000, npm: "@ai-sdk/google-vertex/anthropic" })
1820
+ const result = SessionNs.getUsage({
1821
+ model,
1822
+ usage: usage({ inputTokens: 1000, outputTokens: 500, totalTokens: 1500, cacheReadInputTokens: 200 }),
1823
+ metadata: {
1824
+ vertex: {
1825
+ cacheCreationInputTokens: 300,
1826
+ },
1827
+ },
1828
+ })
1829
+
1830
+ expect(result.tokens.input).toBe(500)
1831
+ expect(result.tokens.cache.read).toBe(200)
1832
+ expect(result.tokens.cache.write).toBe(300)
1833
+ })
1834
+ })