mccode-ai 1.18.21

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