@desplega.ai/agent-swarm 2.13.0 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/dist/acp-adapter-xtj40wd8.js +17 -0
  2. package/dist/{acp-targets-86f0sh6g.js → acp-targets-n7vm5atw.js} +10 -10
  3. package/dist/{actions-zv8vcxvr.js → actions-hq6wp9xv.js} +27 -27
  4. package/dist/{agent-fs-provision-jqshb33y.js → agent-fs-provision-y0qc1rdd.js} +4 -4
  5. package/dist/{amp-adapter-gt503ywc.js → amp-adapter-1qqs6h91.js} +3 -3
  6. package/dist/{app-6t4k5rh1.js → app-7m4z44rv.js} +10 -10
  7. package/dist/{approval-notifications-fcfw063h.js → approval-notifications-8sr41gjx.js} +11 -11
  8. package/dist/{assistant-9dzybh12.js → assistant-hkczwfv6.js} +28 -28
  9. package/dist/{boot-args-schema-xzfp2feg.js → boot-args-schema-8025snev.js} +1 -1
  10. package/dist/{boot-reembed-r88wngfg.js → boot-reembed-15m87nr1.js} +1 -1
  11. package/dist/{boot-reembed-3jz0p2jk.js → boot-reembed-4bbpxjh1.js} +1 -1
  12. package/dist/{boot-scrub-sweep-scrqhw48.js → boot-scrub-sweep-eajr97e9.js} +2 -2
  13. package/dist/{boot-seeds-vb2dcrrb.js → boot-seeds-9cwy39jx.js} +4 -4
  14. package/dist/{boxd-68n75y1s.js → boxd-hr8rsxzq.js} +1 -1
  15. package/dist/{claude-adapter-h3mp9hgs.js → claude-adapter-g61wa4rt.js} +9 -9
  16. package/dist/{claude-managed-adapter-kpbyj2vb.js → claude-managed-adapter-znkk0prm.js} +3 -3
  17. package/dist/{claude-managed-setup-0efr3wkg.js → claude-managed-setup-f1wndkr2.js} +2 -2
  18. package/dist/{claude-sdk-session-03dw669q.js → claude-sdk-session-687xzf21.js} +20763 -19381
  19. package/dist/{cli-gfcv679k.js → cli-04103ryh.js} +1 -1
  20. package/dist/{cli-hbq0kwxz.js → cli-0a336ze7.js} +4 -4
  21. package/dist/{cli-1v82d2w6.js → cli-0fx95c06.js} +4 -4
  22. package/dist/{cli-wxwv3t11.js → cli-0m77n7ej.js} +3 -3
  23. package/dist/{cli-j53hpbsm.js → cli-0xwb7zpt.js} +2 -2
  24. package/dist/{cli-0dg7ytxm.js → cli-13t0smbk.js} +917 -23
  25. package/dist/{cli-0pazkmd4.js → cli-1b5axkt1.js} +4 -4
  26. package/dist/{cli-6h88mn9q.js → cli-1carhg8g.js} +4 -4
  27. package/dist/{cli-hgsxnjyg.js → cli-1dr5at77.js} +10 -10
  28. package/dist/{cli-0jkenasr.js → cli-2v4xxnx2.js} +1 -1
  29. package/dist/{cli-dnh64e8e.js → cli-32xndx6b.js} +6 -6
  30. package/dist/{cli-hpb9x72z.js → cli-3m8vqehw.js} +9 -9
  31. package/dist/{cli-ercwc8xn.js → cli-3mf04tkh.js} +1 -1
  32. package/dist/{cli-7dbhnsj9.js → cli-3zyme1wt.js} +4 -4
  33. package/dist/{cli-s6zk31gr.js → cli-43dsqhcp.js} +4 -4
  34. package/dist/{cli-t35hx078.js → cli-4h90xaet.js} +2 -2
  35. package/dist/{cli-117g15t4.js → cli-4mj5g29m.js} +8 -8
  36. package/dist/{cli-47hz21se.js → cli-4tbvndmm.js} +4 -5
  37. package/dist/{cli-tn91wc6e.js → cli-50whymxq.js} +1 -1
  38. package/dist/{cli-js10kdk7.js → cli-5basv0e7.js} +19 -5
  39. package/dist/{cli-xfjn2kyq.js → cli-5v6b2am8.js} +5 -5
  40. package/dist/{cli-49f5jyhh.js → cli-6r1dwegd.js} +3 -3
  41. package/dist/{cli-kspxjftk.js → cli-7ewre3dm.js} +15 -6
  42. package/dist/{cli-n3qe7tyr.js → cli-84xtgbn6.js} +35 -2
  43. package/dist/{cli-w14j2z4k.js → cli-8cmjkbvj.js} +2 -2
  44. package/dist/{cli-2m6yaq6b.js → cli-8fj8yfmk.js} +1 -1
  45. package/dist/{cli-9m9kyw77.js → cli-8rbkw18r.js} +2 -2
  46. package/dist/{cli-x05p2d05.js → cli-9tevdxyf.js} +1 -1
  47. package/dist/{cli-f1952kjy.js → cli-9xx36trj.js} +4 -4
  48. package/dist/{cli-hc6e4tac.js → cli-a8ts6x1n.js} +6 -6
  49. package/dist/{cli-mh7pdxe0.js → cli-aebswqmz.js} +12 -12
  50. package/dist/{cli-ex1y88j3.js → cli-at67kvnp.js} +1 -1
  51. package/dist/{cli-b2jh3dyb.js → cli-bjmq14k9.js} +4 -4
  52. package/dist/{cli-mz34pxbk.js → cli-byxsctca.js} +11 -11
  53. package/dist/{cli-dka73bak.js → cli-c0tyzt73.js} +152 -12
  54. package/dist/{cli-wv20kbr3.js → cli-c8kqmzzf.js} +5 -5
  55. package/dist/{cli-qhhb30e8.js → cli-cd9acnvd.js} +9 -9
  56. package/dist/{cli-wndegmns.js → cli-cmgdptmx.js} +3 -3
  57. package/dist/{cli-1dbv9mj9.js → cli-cn6fpa1p.js} +1 -1
  58. package/dist/{cli-wrhbym01.js → cli-cp0m07wb.js} +6 -6
  59. package/dist/{cli-3p288654.js → cli-cpkxh68d.js} +2 -2
  60. package/dist/{cli-g6j6ac3h.js → cli-cqxwjb93.js} +2 -2
  61. package/dist/{cli-8hp56wat.js → cli-d2epqm0y.js} +1 -1
  62. package/dist/{cli-qm3ntjqs.js → cli-dd57p1gd.js} +13 -13
  63. package/dist/{cli-tstj6e8e.js → cli-fn8aj7gb.js} +250 -55
  64. package/dist/{cli-bpje8n65.js → cli-fp65jdp2.js} +31 -6
  65. package/dist/{cli-2skf1mdf.js → cli-gedf48yw.js} +4 -4
  66. package/dist/{cli-c8v2yvej.js → cli-gq6qhmrr.js} +2 -2
  67. package/dist/{cli-sq913bh1.js → cli-grcc2h2g.js} +8 -8
  68. package/dist/{cli-qec9bynj.js → cli-h03j6je3.js} +3 -3
  69. package/dist/{cli-mbwmqb5w.js → cli-h0ewec3d.js} +1 -1
  70. package/dist/{cli-jj3c5nyb.js → cli-h9bejmkf.js} +76 -39
  71. package/dist/{cli-ct8sz3np.js → cli-hs3mqswp.js} +6 -6
  72. package/dist/{cli-tdk7jtka.js → cli-hv3820ez.js} +1 -1
  73. package/dist/{cli-pqfecppn.js → cli-je587f74.js} +1 -1
  74. package/dist/{cli-y4a4458j.js → cli-jhtvt7gn.js} +3 -3
  75. package/dist/{cli-dkejt425.js → cli-mmw2sjaf.js} +7 -7
  76. package/dist/{cli-50w82h6m.js → cli-mwxez0pz.js} +1 -0
  77. package/dist/{cli-avxh26pd.js → cli-nk8swfpx.js} +4 -4
  78. package/dist/{cli-fhvk2nvp.js → cli-p7g7wd9n.js} +9 -9
  79. package/dist/{cli-bhgrhedp.js → cli-q8aq48v1.js} +1 -1
  80. package/dist/{cli-6a40p4kv.js → cli-qn79645p.js} +1 -1
  81. package/dist/{cli-nc6a8b5b.js → cli-qx1dwrr5.js} +2 -2
  82. package/dist/{cli-sdh61g52.js → cli-s6fhqbz1.js} +2 -2
  83. package/dist/{cli-eb279wn3.js → cli-sfajkbd7.js} +2 -2
  84. package/dist/{cli-z64t9pe6.js → cli-snypfjgj.js} +1 -1
  85. package/dist/{cli-ytc7fpza.js → cli-t25rq8mg.js} +4 -4
  86. package/dist/{cli-zqmmy073.js → cli-t90k0phh.js} +18 -18
  87. package/dist/{cli-fz9pcjsw.js → cli-tzzas8rb.js} +4 -4
  88. package/dist/{cli-rtmqzat7.js → cli-vdfngx2g.js} +2 -2
  89. package/dist/{cli-9w8712tq.js → cli-vr4eyq6p.js} +43 -14
  90. package/dist/{cli-z4f346g5.js → cli-vx9acp12.js} +1 -1
  91. package/dist/{cli-y518qkjg.js → cli-w24f3j49.js} +10 -10
  92. package/dist/{cli-yn4kt85g.js → cli-w41bvvms.js} +1 -1
  93. package/dist/{cli-9fsagra4.js → cli-w6c6dj91.js} +1 -1
  94. package/dist/{cli-kde4ky90.js → cli-x5yb8zc8.js} +2 -2
  95. package/dist/{cli-48nvk6sb.js → cli-xhkek467.js} +2 -2
  96. package/dist/{cli-avqkr20b.js → cli-y6qqbpwc.js} +2 -2
  97. package/dist/{cli-7wy8gbwb.js → cli-ya1cj689.js} +1 -1
  98. package/dist/{cli-prf7kz78.js → cli-yeh3g1q6.js} +603 -78
  99. package/dist/{cli-ajjvqhf3.js → cli-z6m6xzxt.js} +2 -2
  100. package/dist/{cli-2jk4s7z1.js → cli-zaate0rd.js} +3 -3
  101. package/dist/{cli-n85m2wkq.js → cli-zkbz8m2q.js} +3 -2
  102. package/dist/{cli-0b655smz.js → cli-zvpkrgsc.js} +5 -5
  103. package/dist/cli.js +27 -27
  104. package/dist/{codex-adapter-f3yp0kaj.js → codex-adapter-ysfg6ty3.js} +8 -8
  105. package/dist/{codex-hook-262cekfp.js → codex-hook-c0nvm30r.js} +2 -2
  106. package/dist/{codex-login-1ven7yje.js → codex-login-ven5cz5j.js} +1 -1
  107. package/dist/{codex-session-runner-ns4mv70p.js → codex-session-runner-823scr6g.js} +9 -9
  108. package/dist/{commands-5bzf2tfw.js → commands-5rbm07fz.js} +3 -3
  109. package/dist/{controller-5xt7kvfm.js → controller-wn3vd217.js} +3 -3
  110. package/dist/{controllers-connect-0gg13mzp.js → controllers-connect-34jzhfft.js} +28 -28
  111. package/dist/core-kdehq26g.js +42 -0
  112. package/dist/{cursor-adapter-p0c5zv6r.js → cursor-adapter-w1681kp1.js} +2 -2
  113. package/dist/{db-2s68ycq7.js → db-6bkgbfwk.js} +3 -3
  114. package/dist/{db-q7q639k5.js → db-hcj16x7z.js} +2 -2
  115. package/dist/{devin-adapter-t8d86q9x.js → devin-adapter-fs90ab4v.js} +1 -1
  116. package/dist/{dispatcher-j2y1q7ae.js → dispatcher-jgjqrfzv.js} +25 -25
  117. package/dist/{docker-1b41eysj.js → docker-1h33jvh9.js} +2 -2
  118. package/dist/{dsh-adapter-pgnkf4st.js → dsh-adapter-g9yqv09y.js} +2 -2
  119. package/dist/{e2b-xm60c8ad.js → e2b-jnk0yeva.js} +2 -2
  120. package/dist/{e2b-ew8c5j5v.js → e2b-y7e5kmzf.js} +2 -2
  121. package/dist/{easter-egg-3d-0kea97jf.js → easter-egg-3d-w17nsny6.js} +1 -1
  122. package/dist/{embedding-space-3n6mhhmy.js → embedding-space-v06fwy7b.js} +6 -6
  123. package/dist/{embeddings-jfmj6yme.js → embeddings-g50dxea4.js} +1 -1
  124. package/dist/{event-bus-v4ywhc2p.js → event-bus-08t2b4y2.js} +1 -1
  125. package/dist/{execute-tjrej979.js → execute-1n36haw1.js} +1 -1
  126. package/dist/{external-channel-jy8w2gg3.js → external-channel-43tv8pg6.js} +2 -2
  127. package/dist/fx-adapter-bvh05t4a.js +20 -0
  128. package/dist/grok-adapter-my5j8mdf.js +20 -0
  129. package/dist/handlers-wyymeeqh.js +41 -0
  130. package/dist/heartbeat-sf3nk937.js +50 -0
  131. package/dist/{hook-bpnncsec.js → hook-dqph1e05.js} +8 -8
  132. package/dist/{hook-fv1jwrv7.js → hook-m1m9dm6w.js} +6 -6
  133. package/dist/{http-bpa26czn.js → http-w0th1cz9.js} +160 -102
  134. package/dist/index-22khdtby.js +44 -0
  135. package/dist/{index-mpj0z9e0.js → index-c0e8en64.js} +1 -1
  136. package/dist/{index-620y7jzq.js → index-e8pz8qdg.js} +3 -3
  137. package/dist/{index-8p0j4h4j.js → index-ez823q84.js} +94 -89
  138. package/dist/{index-w216g9y9.js → index-ffba0z8q.js} +35 -21
  139. package/dist/{index-s8re7mvq.js → index-gkpfgpg7.js} +1 -1
  140. package/dist/{index-4k7m5dgj.js → index-k8ajc0g0.js} +143 -103
  141. package/dist/index-np0582ac.js +40 -0
  142. package/dist/{index-52tgbhrw.js → index-pb03vans.js} +28 -28
  143. package/dist/index-vgkrj1jt.js +39 -0
  144. package/dist/{index-pe3d8jfy.js → index-whysn1wf.js} +1 -1
  145. package/dist/{index-0h6qd4p1.js → index-y4vd4mhn.js} +3 -4
  146. package/dist/{k8s-fy8hbhkg.js → k8s-8326q0rq.js} +2 -2
  147. package/dist/{keepalive-d6z12s04.js → keepalive-2v06q2e8.js} +5 -4
  148. package/dist/lead-55z813ng.js +79 -0
  149. package/dist/{maintenance-7kac6g2g.js → maintenance-vx7vjhhy.js} +1 -1
  150. package/dist/{oauth-refresh-sweep-t1xjetbh.js → oauth-refresh-sweep-g06k4bza.js} +4 -3
  151. package/dist/{object-webhooks-6rdagg0r.js → object-webhooks-3dzdq4fm.js} +7 -7
  152. package/dist/{onboard-32y1cfxy.js → onboard-232pazny.js} +4 -4
  153. package/dist/{opencode-adapter-enp3v31n.js → opencode-adapter-t0paqbh8.js} +8 -8
  154. package/dist/{otel-impl-k0tm5ptj.js → otel-impl-kmpkyp4y.js} +2 -2
  155. package/dist/{pending-24zebgvs.js → pending-x0z3vx1x.js} +26 -26
  156. package/dist/{pi-mono-adapter-yj72xxxe.js → pi-mono-adapter-7pmypn6d.js} +17 -15
  157. package/dist/{pricing-refresh-cf25x38j.js → pricing-refresh-ytjmtyd7.js} +2 -2
  158. package/dist/{rbac-roles-0wydd22m.js → rbac-roles-fgm5mxr2.js} +3 -3
  159. package/dist/{rbac-roles-at6crb3r.js → rbac-roles-xyaxekh3.js} +2 -2
  160. package/dist/{render-v2-nvcw0jd7.js → render-v2-ws972g4r.js} +10 -10
  161. package/dist/{resume-y4w0k5v3.js → resume-m6mjzhkp.js} +13 -13
  162. package/dist/{runtime-vpe43hx0.js → runtime-zzpc0c8a.js} +1 -1
  163. package/dist/{session-access-gkyvnfye.js → session-access-vp35xs91.js} +5 -5
  164. package/dist/{session-source-backfill-3w2st4m2.js → session-source-backfill-p73e8zbe.js} +2 -2
  165. package/dist/{setup-axxvqtys.js → setup-r4kd7rxg.js} +1 -1
  166. package/dist/thread-buffer-cm2nzq6t.js +42 -0
  167. package/dist/{tree-visibility-y4fqvab5.js → tree-visibility-07h2tbs2.js} +2 -2
  168. package/dist/{user-merge-jobs-kcmwvrc6.js → user-merge-jobs-96vg9rpe.js} +3 -3
  169. package/dist/{virtual-modules-7d92dct1.js → virtual-modules-vgn3f2x4.js} +3 -3
  170. package/dist/{work-objects-f708e069.js → work-objects-74hbcx3e.js} +28 -28
  171. package/dist/worker-5pn2vzx6.js +79 -0
  172. package/dist/{worker-follow-up-0by8wztc.js → worker-follow-up-ezavwn5d.js} +25 -25
  173. package/dist/{x-3dtaf2r9.js → x-asbrnafg.js} +2 -2
  174. package/openapi.json +1793 -1622
  175. package/package.json +10 -10
  176. package/src/apps/catalog.generated.json +726 -0
  177. package/src/apps/definition.ts +24 -7
  178. package/src/apps/page-validator.ts +225 -3
  179. package/src/be/db.ts +38 -10
  180. package/src/be/mcp-proxy.ts +5 -4
  181. package/src/be/migrations/340_api_key_spend_cap.sql +5 -0
  182. package/src/be/schedules/validate.ts +26 -0
  183. package/src/be/swarm-config-guard.ts +4 -0
  184. package/src/commands/credential-outcome-report.ts +5 -2
  185. package/src/commands/onboard/agent-fs-version.ts +1 -1
  186. package/src/commands/provider-credentials.ts +19 -0
  187. package/src/commands/provider-error-class.ts +4 -1
  188. package/src/commands/rate-limit-outcome.ts +48 -3
  189. package/src/commands/runner.ts +113 -55
  190. package/src/commands/worktree-reaper.ts +600 -0
  191. package/src/extensions/contract-types.generated.ts +1 -1
  192. package/src/http/agents.ts +4 -0
  193. package/src/http/api-keys.ts +27 -3
  194. package/src/http/pages-public.ts +40 -4
  195. package/src/http/pool-keys.ts +21 -2
  196. package/src/http/schedules.ts +28 -3
  197. package/src/http/script-connections.ts +12 -4
  198. package/src/http/script-runs.ts +12 -3
  199. package/src/http/tasks.ts +6 -10
  200. package/src/mcp-client/http-client.ts +3 -1
  201. package/src/oauth/identity-capture.ts +6 -1
  202. package/src/oauth/mcp-wrapper.ts +10 -3
  203. package/src/oauth/wrapper.ts +15 -3
  204. package/src/prompts/session-templates.ts +1 -0
  205. package/src/providers/acp-targets.ts +2 -2
  206. package/src/providers/amp-adapter.ts +1 -1
  207. package/src/providers/dsh-adapter.ts +1 -1
  208. package/src/providers/pi-mono-adapter.ts +4 -2
  209. package/src/providers/runtime-dependencies.ts +1 -1
  210. package/src/rbac/legacy-policy.ts +2 -0
  211. package/src/rbac/permissions.ts +5 -0
  212. package/src/scripts-runtime/types/swarm-extension.d.ts +7 -7
  213. package/src/slack/enrich.ts +14 -11
  214. package/src/tests/agents-list-model-display.test.ts +23 -0
  215. package/src/tests/apps-spike2.test.ts +35 -0
  216. package/src/tests/base-prompt.test.ts +1 -0
  217. package/src/tests/deploy-guard.test.ts +24 -0
  218. package/src/tests/dsh-adapter.test.ts +1 -1
  219. package/src/tests/ensure-token.test.ts +2 -2
  220. package/src/tests/entrypoint-repo-autoclone-args.test.ts +202 -0
  221. package/src/tests/fake-dns.ts +47 -0
  222. package/src/tests/fixtures/base-prompt-baseline.json +12 -12
  223. package/src/tests/latest-model-report.test.ts +138 -0
  224. package/src/tests/mcp-oauth-dcr-reuse.test.ts +5 -2
  225. package/src/tests/mcp-oauth-ensure-token.test.ts +3 -2
  226. package/src/tests/mcp-oauth-manual-client.test.ts +6 -1
  227. package/src/tests/mcp-oauth-wrapper.test.ts +20 -4
  228. package/src/tests/mcp-outbound-fetch-guard.test.ts +169 -0
  229. package/src/tests/mcp-server-ssrf.test.ts +2 -0
  230. package/src/tests/memory-search-stall.test.ts +5 -0
  231. package/src/tests/oauth-connection-fetch-guard.test.ts +162 -0
  232. package/src/tests/oauth-token-endpoint-fetch-guard.test.ts +121 -0
  233. package/src/tests/oauth-wrapper.test.ts +1 -2
  234. package/src/tests/pages-head-v2.test.ts +2 -1
  235. package/src/tests/script-connections-http.test.ts +8 -3
  236. package/src/tests/script-connections.test.ts +2 -0
  237. package/src/tests/slack-thread-participants.test.ts +14 -3
  238. package/src/tests/spend-cap-credentials.test.ts +34 -0
  239. package/src/tests/spend-cap-outcome.test.ts +67 -0
  240. package/src/tests/subscription-first.test.ts +119 -0
  241. package/src/tests/worktree-reaper.test.ts +424 -0
  242. package/src/tools/get-task-details.ts +247 -5
  243. package/src/tools/schedules/patch-schedule.ts +26 -1
  244. package/src/tools/schedules/update-schedule.ts +28 -2
  245. package/src/utils/credentials.ts +36 -1
  246. package/src/utils/egress-guard.ts +40 -10
  247. package/src/utils/error-tracker.ts +17 -0
  248. package/templates/skills/apps/SKILL.md +191 -2
  249. package/templates/skills/apps/content.md +191 -2
  250. package/templates/skills/boards-and-sheets/content.md +11 -0
  251. package/templates/skills/pages/content.md +11 -0
  252. package/templates/skills/swarm-docs/content.md +2 -0
  253. package/templates/skills/swarm-scripts/SKILL.md +1 -0
  254. package/templates/skills/swarm-scripts/content.md +1 -0
  255. package/templates/workflows/ralph-loop/content.md +6 -6
  256. package/dist/acp-adapter-cn53011z.js +0 -17
  257. package/dist/cli-pr0eze3x.js +0 -149
  258. package/dist/core-0fqtbrxa.js +0 -42
  259. package/dist/fx-adapter-k6w3jvz9.js +0 -20
  260. package/dist/grok-adapter-4q5tssw0.js +0 -20
  261. package/dist/handlers-qxgfvvsf.js +0 -41
  262. package/dist/heartbeat-6tr2w2da.js +0 -50
  263. package/dist/index-0mcxjdsa.js +0 -44
  264. package/dist/index-dz4q23ag.js +0 -40
  265. package/dist/index-s175jckx.js +0 -39
  266. package/dist/lead-p3hx7h35.js +0 -79
  267. package/dist/thread-buffer-rwa7d4dx.js +0 -42
  268. package/dist/worker-8rg9gz74.js +0 -79
@@ -61,7 +61,10 @@ export function classifyProviderError(
61
61
  return { errorClass: "model_window" };
62
62
  case "key":
63
63
  return {
64
- errorClass: isCodexCreditsExhaustedMessage(text) ? "credits" : "rate_limit",
64
+ errorClass:
65
+ rateLimitOutcome.spendCap || isCodexCreditsExhaustedMessage(text)
66
+ ? "credits"
67
+ : "rate_limit",
65
68
  };
66
69
  case "none":
67
70
  break;
@@ -3,8 +3,10 @@ import {
3
3
  isCodexCreditsExhaustedMessage,
4
4
  isRateLimitMessage,
5
5
  MAX_RATE_LIMIT_RESET_MS,
6
+ MAX_SPEND_CAP_HOLD_MS,
6
7
  parseRateLimitResetTime,
7
8
  type RateLimitWindowTelemetry,
9
+ type SpendCap,
8
10
  } from "../utils/error-tracker";
9
11
  import {
10
12
  type ModelFamily,
@@ -19,7 +21,7 @@ import type {
19
21
 
20
22
  export type RateLimitOutcome =
21
23
  | { kind: "none" }
22
- | { kind: "key"; rateLimitedUntil: string }
24
+ | { kind: "key"; rateLimitedUntil: string; spendCap?: SpendCap }
23
25
  /**
24
26
  * The key's seat cannot run the model (`credits_required`). Not a rate
25
27
  * limit: the seat rejection never marks the key by itself.
@@ -62,12 +64,40 @@ interface ClassifiableResult {
62
64
  creditsRequired?: { observedAt: string; overageDisabledReason?: string };
63
65
  }
64
66
 
65
- function clampMs(candidateMs: number, nowMs: number): number {
67
+ function clampMs(candidateMs: number, nowMs: number, maxResetMs = MAX_RATE_LIMIT_RESET_MS): number {
66
68
  const minMs = nowMs + 60_000;
67
- const maxMs = nowMs + MAX_RATE_LIMIT_RESET_MS;
69
+ const maxMs = nowMs + maxResetMs;
68
70
  return Math.min(Math.max(candidateMs, minMs), maxMs);
69
71
  }
70
72
 
73
+ /** OpenRouter's key spend limit (403 `openrouter_key_limit`) and its out-of-credits 402. */
74
+ const SPEND_CAP_TEXT =
75
+ /key limit exceeded|"limit_source"\s*:\s*"openrouter_key_limit"|insufficient credits|requires more credits/i;
76
+
77
+ function numberOf(text: string, pattern: RegExp): number | null {
78
+ const value = Number(text.match(pattern)?.[1]);
79
+ return Number.isFinite(value) ? value : null;
80
+ }
81
+
82
+ /**
83
+ * The spend cap a failure text reports, or null when it is not a spend cap.
84
+ * Reads the JSON metadata first (`limit_usd`, `spend_usd`, `resets_at`), then
85
+ * the message ("$1.07 of $1.00 used; resets <ISO>").
86
+ */
87
+ export function parseSpendCapMessage(text: string): SpendCap | null {
88
+ if (!SPEND_CAP_TEXT.test(text)) return null;
89
+ const resetText =
90
+ text.match(/"resets_at"\s*:\s*"([^"]+)"/)?.[1] ??
91
+ text.match(/resets (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/)?.[1];
92
+ const resetMs = resetText ? Date.parse(resetText) : Number.NaN;
93
+ return {
94
+ limitUsd: numberOf(text, /"limit_usd"\s*:\s*([\d.]+)/) ?? numberOf(text, /of \$([\d.]+) used/),
95
+ spendUsd:
96
+ numberOf(text, /"spend_usd"\s*:\s*([\d.]+)/) ?? numberOf(text, /\$([\d.]+) of \$[\d.]+ used/),
97
+ resetsAt: Number.isFinite(resetMs) ? new Date(resetMs).toISOString() : null,
98
+ };
99
+ }
100
+
71
101
  /**
72
102
  * Classifies a finished provider session's rate-limit signal into one of
73
103
  * four outcomes: no rate limit, a key-wide rate limit (legacy path), a
@@ -134,6 +164,21 @@ export function classifyRateLimitOutcome(
134
164
  }
135
165
  }
136
166
 
167
+ // Before the rate-limit text check: OpenRouter's cap body says "usage limit",
168
+ // which would read as a short rate limit and re-hand the key every 5 minutes.
169
+ const spendCap = failureReason != null ? parseSpendCapMessage(failureReason) : null;
170
+ if (spendCap) {
171
+ // shortcut: a cap with no reset holds for MAX_SPEND_CAP_HOLD_MS, not forever; editing the key re-creates its status row.
172
+ const untilMs = spendCap.resetsAt
173
+ ? Date.parse(spendCap.resetsAt)
174
+ : nowMs + MAX_SPEND_CAP_HOLD_MS;
175
+ return {
176
+ kind: "key",
177
+ rateLimitedUntil: new Date(clampMs(untilMs, nowMs, MAX_SPEND_CAP_HOLD_MS)).toISOString(),
178
+ spendCap,
179
+ };
180
+ }
181
+
137
182
  if (
138
183
  result.rateLimitResetAt != null ||
139
184
  (failureReason != null && isRateLimitMessage(failureReason))
@@ -1,6 +1,6 @@
1
1
  import { existsSync, statSync } from "node:fs";
2
2
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
3
- import { isChatgptSubscriptionModel } from "@desplega/model-catalog";
3
+ import { chatgptSubscriptionModel, chatgptSubscriptionTrait } from "@desplega/model-catalog";
4
4
  import { deriveDefaultRoute } from "@desplega/model-routing";
5
5
  import type { TemplateResponse } from "../../templates/schema.ts";
6
6
  import { isGroupKey } from "../assets/key.ts";
@@ -92,6 +92,7 @@ import { getContextWindowSize } from "../utils/context-window.ts";
92
92
  import {
93
93
  CredentialAllowlistError,
94
94
  type CredentialSelection,
95
+ KeySpendCapError,
95
96
  ModelWindowExhaustedError,
96
97
  normalizeProviderKeyAliases,
97
98
  resolveCredentialPools,
@@ -161,6 +162,7 @@ import {
161
162
  reportAcpStatus,
162
163
  reportLatestModel,
163
164
  sendCredStatusReport,
165
+ taskSelectedModelForReport,
164
166
  } from "./provider-credentials.ts";
165
167
  import { classifyProviderErrorOf } from "./provider-error-class.ts";
166
168
  import {
@@ -177,6 +179,7 @@ import {
177
179
  } from "./resume-session.ts";
178
180
  // Side-effect import: registers runner trigger/resumption templates
179
181
  import "./templates.ts";
182
+ import { type ActiveTaskRef, resolveWorktreeReaperConfig, WorktreeReaper } from "./worktree-reaper";
180
183
 
181
184
  export { buildAttachmentsSection } from "./attachments-section.ts";
182
185
  export { reportKeyRateLimitWindows } from "./credential-outcome-report.ts";
@@ -1292,6 +1295,11 @@ export const RELOADABLE_ENV_KEYS: ReadonlySet<string> = new Set([
1292
1295
  // Non-secret pool-slot count; `checkCodexCredentials` reads it from
1293
1296
  // process.env at boot and during the credential wait.
1294
1297
  CODEX_OAUTH_POOL_SLOTS_ENV,
1298
+ // The worktree reaper reads these on every call (resolveWorktreeReaperConfig).
1299
+ "WORKTREE_REAPER_MODE",
1300
+ "WORKTREE_TTL_HOURS",
1301
+ "WORKTREE_SWEEP_INTERVAL_MINUTES",
1302
+ "WORKTREE_REAPER_EXTRA_ROOTS",
1295
1303
  ]);
1296
1304
 
1297
1305
  /**
@@ -2216,6 +2224,25 @@ export async function resolveCodexOAuthCredentialInfo(
2216
2224
  }
2217
2225
  }
2218
2226
 
2227
+ /**
2228
+ * The one subscription-first resolver for every harness. When the harness's
2229
+ * trait serves `model` on the ChatGPT subscription and the pool has a slot,
2230
+ * the session runs that model on the slot; otherwise the model is unchanged
2231
+ * and keeps its API key. An `openai-codex/<id>` model without a slot stays as
2232
+ * is, so the adapter fails it instead of billing a key. `poolOnly`: only codex
2233
+ * may fall back to a standalone `~/.codex/auth.json`.
2234
+ */
2235
+ export async function resolveSubscriptionFirst(
2236
+ harness: string,
2237
+ model: string,
2238
+ resolvePoolSlot: (poolOnly: boolean) => Promise<CodexOAuthCredentialInfo | null>,
2239
+ ): Promise<{ model: string; oauthInfo: CodexOAuthCredentialInfo | null }> {
2240
+ const subscriptionModel = chatgptSubscriptionModel(harness, model);
2241
+ if (subscriptionModel === null) return { model, oauthInfo: null };
2242
+ const oauthInfo = await resolvePoolSlot(chatgptSubscriptionTrait(harness).kind !== "native");
2243
+ return oauthInfo ? { model: subscriptionModel, oauthInfo } : { model, oauthInfo: null };
2244
+ }
2245
+
2219
2246
  /** Upper bound on each awaited credential-outcome report, so a slow API never stalls completions. */
2220
2247
  const KEY_OUTCOME_REPORT_TIMEOUT_MS = 5000;
2221
2248
 
@@ -2916,6 +2943,16 @@ export interface RunnerState {
2916
2943
  * Unset against an API that never drains.
2917
2944
  */
2918
2945
  apiDraining?: boolean;
2946
+ /** Removes worktrees agents leave behind; unset in callers that never reap. */
2947
+ worktreeReaper?: WorktreeReaper;
2948
+ }
2949
+
2950
+ /** The active tasks as the worktree reaper sees them: id plus working dir. */
2951
+ export function activeTaskRefs(state: RunnerState): ActiveTaskRef[] {
2952
+ return [...state.activeTasks.values()].map((t) => ({
2953
+ taskId: t.taskId,
2954
+ workingDir: t.workingDir,
2955
+ }));
2919
2956
  }
2920
2957
 
2921
2958
  /** Buffer for session logs */
@@ -4620,7 +4657,9 @@ export async function spawnProviderProcess(
4620
4657
  ));
4621
4658
  } catch (err) {
4622
4659
  if (
4623
- (err instanceof ModelWindowExhaustedError || err instanceof CredentialAllowlistError) &&
4660
+ (err instanceof ModelWindowExhaustedError ||
4661
+ err instanceof CredentialAllowlistError ||
4662
+ err instanceof KeySpendCapError) &&
4624
4663
  realTaskId
4625
4664
  ) {
4626
4665
  const reason = err.message;
@@ -4691,6 +4730,13 @@ export async function spawnProviderProcess(
4691
4730
  );
4692
4731
  }
4693
4732
  const taskModel = opts.resolvedModel || taskModelSelection.model || "";
4733
+ // What the task itself selected, for the latest-model reports: the same value in the initial,
4734
+ // result and final reports, so a tier or profile run keeps source "task" until it ends.
4735
+ const reportTaskModel = taskSelectedModelForReport({
4736
+ resolvedModel: opts.resolvedModel,
4737
+ modelSource: opts.modelSource,
4738
+ localModel: taskModelSelection.model,
4739
+ });
4694
4740
  // Never start a CLI with a model from another harness family (runbooks/model-tiers.md).
4695
4741
  const spawnModel = guardSpawnModel({
4696
4742
  taskModel,
@@ -4714,60 +4760,39 @@ export async function spawnProviderProcess(
4714
4760
  throw new Error(spawnModel.reason);
4715
4761
  }
4716
4762
  if (spawnModel.warning) console.warn(spawnModel.warning);
4717
- const model = spawnModel.model;
4718
- // Recorded on the task at session start, like the model: what the adapter
4719
- // applies, not just what was asked for.
4720
- const sessionEffort = effectiveReasoningEffort(adapter.name, model, reasoningEffortOverride);
4721
-
4722
- // Resolve Codex OAuth pool slot BEFORE building ProviderSessionConfig so we
4723
- // can pass codexSlot through and the adapter writes token refreshes back to
4724
- // the correct slot key (codex_oauth_<slot>) instead of defaulting to slot 0.
4725
- //
4726
- // Always resolve for codex (not just when credentialSelections is empty) so
4727
- // that if the OPENAI_API_KEY credential is rate-limited we can fail over to
4728
- // a CODEX_OAUTH slot — even though the keyType differs.
4729
- let oauthSelection: CredentialSelection | undefined;
4763
+ // Subscription first (the harness's `chatgptSubscriptionTrait`): a
4764
+ // codex_oauth pool slot serves OpenAI models before OPENAI_API_KEY does. It
4765
+ // is resolved BEFORE ProviderSessionConfig so `codexSlot` reaches the adapter,
4766
+ // which refreshes back to that slot key (codex_oauth_<slot>). A gateway route
4767
+ // uses no OAuth: no slot is picked and no auth.json is materialised.
4768
+ const subscription = deriveDefaultRoute(adapter.name, freshEnv)
4769
+ ? { model: spawnModel.model, oauthInfo: null }
4770
+ : await resolveSubscriptionFirst(adapter.name, spawnModel.model, (poolOnly) =>
4771
+ resolveCodexOAuthCredentialInfo(opts.apiUrl, opts.apiKey, { poolOnly }),
4772
+ );
4773
+ const model = subscription.model;
4774
+ if (model !== spawnModel.model) {
4775
+ console.log(`[${opts.role}] ${spawnModel.model} runs on the ChatGPT subscription as ${model}`);
4776
+ }
4777
+ const oauthSelection: CredentialSelection | undefined = subscription.oauthInfo?.selection;
4730
4778
  // True only when `oauthSelection` came from an actual `codex_oauth_<n>`
4731
4779
  // config-store slot — gates whether `codexSlot` is set below (see
4732
4780
  // `CodexOAuthCredentialInfo`).
4733
- let oauthIsPoolBacked = false;
4734
- // A gateway route uses no OAuth: no pool slot is picked, so no auth.json is
4735
- // materialised for a session whose traffic goes to the gateway.
4736
- if (adapter.name === "codex" && !deriveDefaultRoute("codex", freshEnv)) {
4737
- const oauthInfo = await resolveCodexOAuthCredentialInfo(opts.apiUrl, opts.apiKey);
4738
- oauthSelection = oauthInfo?.selection;
4739
- oauthIsPoolBacked = oauthInfo?.isPoolBacked ?? false;
4740
- // Both pool credentials and standalone ChatGPT auth suppress OPENAI_API_KEY
4741
- // in the adapter. Report the same credential that authenticates the session.
4742
- if (oauthSelection && realTaskId) {
4743
- reportKeyUsage(
4744
- opts.apiUrl,
4745
- opts.apiKey,
4746
- oauthSelection.keyType,
4747
- oauthSelection,
4748
- realTaskId,
4749
- ).catch(() => {});
4750
- }
4751
- } else if (adapter.name === "pi" && isChatgptSubscriptionModel(model)) {
4752
- // An `openai-codex/<id>` model runs on the same pool, with the same slot
4753
- // pick and usage bookkeeping. The adapter revalidates `codexSlot` through
4754
- // the refresh lock and hands the harness the access token only
4755
- // (`loadChatgptSubscriptionCredential`); no slot fails the session there.
4756
- const oauthInfo = await resolveCodexOAuthCredentialInfo(opts.apiUrl, opts.apiKey, {
4757
- poolOnly: true,
4758
- });
4759
- oauthSelection = oauthInfo?.selection;
4760
- oauthIsPoolBacked = oauthInfo?.isPoolBacked ?? false;
4761
- if (oauthSelection && realTaskId) {
4762
- reportKeyUsage(
4763
- opts.apiUrl,
4764
- opts.apiKey,
4765
- oauthSelection.keyType,
4766
- oauthSelection,
4767
- realTaskId,
4768
- ).catch(() => {});
4769
- }
4781
+ const oauthIsPoolBacked = subscription.oauthInfo?.isPoolBacked ?? false;
4782
+ // The subscription credential suppresses OPENAI_API_KEY in the adapter.
4783
+ // Report the same credential that authenticates the session.
4784
+ if (oauthSelection && realTaskId) {
4785
+ reportKeyUsage(
4786
+ opts.apiUrl,
4787
+ opts.apiKey,
4788
+ oauthSelection.keyType,
4789
+ oauthSelection,
4790
+ realTaskId,
4791
+ ).catch(() => {});
4770
4792
  }
4793
+ // Recorded on the task at session start, like the model: what the adapter
4794
+ // applies, not just what was asked for.
4795
+ const sessionEffort = effectiveReasoningEffort(adapter.name, model, reasoningEffortOverride);
4771
4796
 
4772
4797
  // Match harness authentication for both cost attribution and failure reports.
4773
4798
  // isPoolBacked controls slot revalidation, not whether ChatGPT auth wins.
@@ -4883,7 +4908,7 @@ export async function spawnProviderProcess(
4883
4908
  );
4884
4909
  const initialModelReport = buildLatestModelReport({
4885
4910
  model,
4886
- taskModel,
4911
+ taskModel: reportTaskModel,
4887
4912
  configModel,
4888
4913
  taskId: realTaskId,
4889
4914
  harnessProvider: opts.harnessProvider,
@@ -5233,7 +5258,7 @@ export async function spawnProviderProcess(
5233
5258
  // final adapter-confirmed report below once the session completes.
5234
5259
  const latestModel = buildLatestModelReport({
5235
5260
  model: event.cost.model,
5236
- taskModel: opts.model,
5261
+ taskModel: reportTaskModel,
5237
5262
  configModel,
5238
5263
  taskId: realTaskId,
5239
5264
  harnessProvider: opts.harnessProvider,
@@ -5513,7 +5538,7 @@ export async function spawnProviderProcess(
5513
5538
  if (result.cost?.model) {
5514
5539
  const finalModelReport = buildLatestModelReport({
5515
5540
  model: result.cost.model,
5516
- taskModel: opts.model,
5541
+ taskModel: reportTaskModel,
5517
5542
  configModel,
5518
5543
  taskId: realTaskId,
5519
5544
  harnessProvider: opts.harnessProvider,
@@ -6096,6 +6121,10 @@ export async function checkCompletedProcesses(
6096
6121
  if (triggerType === "task_assigned" || triggerType === "task_resumed") {
6097
6122
  state.tasksProcessed += 1;
6098
6123
  }
6124
+ // Fire-and-forget: a large removal must never hold the loop or shutdown.
6125
+ state.worktreeReaper
6126
+ ?.onTaskEnded(taskId, activeTaskRefs(state))
6127
+ .catch((err) => console.warn(`[${role}] Worktree reaper failed: ${err}`));
6099
6128
  }
6100
6129
  }
6101
6130
  },
@@ -6524,6 +6553,19 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
6524
6553
  codexCreditsExhaustedCooldownMs: bootCooldownMs,
6525
6554
  modelWindowBlocks: new Map(),
6526
6555
  };
6556
+ // Agents create worktrees under /workspace/personal; without it (local dev) the reaper stays off.
6557
+ const reaperHasWorkspace = existsSync("/workspace/personal");
6558
+ state.worktreeReaper = new WorktreeReaper({
6559
+ ledgerPath: "/workspace/personal/.swarm/worktree-ledger.json",
6560
+ scanRoots: ["/workspace/personal"],
6561
+ getConfig: () =>
6562
+ resolveWorktreeReaperConfig(
6563
+ process.env,
6564
+ reaperHasWorkspace && adapter.traits.hasLocalEnvironment,
6565
+ ),
6566
+ statusOf: (taskId) => fetchTaskStatus(apiUrl, apiKey, taskId),
6567
+ });
6568
+ const reaperFailed = (err: unknown) => console.warn(`[${role}] Worktree reaper failed: ${err}`);
6527
6569
 
6528
6570
  // Track tasks already signaled for cancellation to avoid repeated SIGTERM
6529
6571
  const cancelledSignaled = new Set<string>();
@@ -7465,7 +7507,9 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7465
7507
  continue;
7466
7508
  }
7467
7509
 
7510
+ runningTask.workingDir = resumeCwd;
7468
7511
  state.activeTasks.set(task.id, runningTask);
7512
+ state.worktreeReaper?.observe(activeTaskRefs(state)).catch(reaperFailed);
7469
7513
  console.log(
7470
7514
  `[${role}] Resumed task ${task.id.slice(0, 8)} (${state.activeTasks.size}/${state.maxConcurrent} active)`,
7471
7515
  );
@@ -7481,6 +7525,11 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7481
7525
  }
7482
7526
  // ========== END: Resume paused tasks ==========
7483
7527
 
7528
+ // Boot sweep: finishes interrupted removals and reaps what ended while we were down.
7529
+ state.worktreeReaper?.sweep(activeTaskRefs(state)).catch(reaperFailed);
7530
+ let lastWorktreeSweepAt = Date.now();
7531
+ let lastWorktreeObserveAt = 0;
7532
+
7484
7533
  // ========== Lead startup self-check ==========
7485
7534
  if (isLead) {
7486
7535
  console.log(`[${role}] Running startup heartbeat sweep...`);
@@ -7580,6 +7629,14 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7580
7629
 
7581
7630
  // Periodic VCS detection for running tasks (fire-and-forget, throttled per task)
7582
7631
  const now = Date.now();
7632
+ if (state.activeTasks.size > 0 && now - lastWorktreeObserveAt >= VCS_CHECK_INTERVAL) {
7633
+ lastWorktreeObserveAt = now;
7634
+ state.worktreeReaper?.observe(activeTaskRefs(state)).catch(reaperFailed);
7635
+ }
7636
+ if (now - lastWorktreeSweepAt >= resolveWorktreeReaperConfig().sweepIntervalMinutes * 60_000) {
7637
+ lastWorktreeSweepAt = now;
7638
+ state.worktreeReaper?.sweep(activeTaskRefs(state)).catch(reaperFailed);
7639
+ }
7583
7640
  for (const [taskId, task] of state.activeTasks) {
7584
7641
  if (vcsDetectedTasks.has(taskId)) continue;
7585
7642
  const lastCheck = vcsCheckTimestamps.get(taskId) ?? 0;
@@ -8130,6 +8187,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
8130
8187
  }
8131
8188
 
8132
8189
  state.activeTasks.set(runningTask.taskId, runningTask);
8190
+ state.worktreeReaper?.observe(activeTaskRefs(state)).catch(reaperFailed);
8133
8191
 
8134
8192
  // Pool triggers have no task id before the spawn; their session is
8135
8193
  // keyed on the synthetic id `spawnProviderProcess` minted.