@desplega.ai/agent-swarm 2.13.0 → 2.13.2

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 (306) hide show
  1. package/README.md +1 -1
  2. package/dist/acp-adapter-x1qqgzwx.js +17 -0
  3. package/dist/{acp-targets-86f0sh6g.js → acp-targets-mz8c5dnt.js} +10 -10
  4. package/dist/{actions-zv8vcxvr.js → actions-5ft3qp5a.js} +27 -27
  5. package/dist/{agent-fs-provision-jqshb33y.js → agent-fs-provision-6fgz7wvz.js} +4 -4
  6. package/dist/{amp-adapter-gt503ywc.js → amp-adapter-nthn8ezm.js} +3 -3
  7. package/dist/{app-6t4k5rh1.js → app-535m78qw.js} +10 -10
  8. package/dist/{approval-notifications-fcfw063h.js → approval-notifications-dewbk403.js} +11 -11
  9. package/dist/{assistant-9dzybh12.js → assistant-39zyabv2.js} +28 -28
  10. package/dist/{boot-args-schema-xzfp2feg.js → boot-args-schema-bqv5bf77.js} +1 -1
  11. package/dist/{boot-reembed-3jz0p2jk.js → boot-reembed-157c0gcz.js} +1 -1
  12. package/dist/{boot-reembed-r88wngfg.js → boot-reembed-fas7z3zn.js} +1 -1
  13. package/dist/{boot-scrub-sweep-scrqhw48.js → boot-scrub-sweep-tmec0be2.js} +2 -2
  14. package/dist/{boot-seeds-vb2dcrrb.js → boot-seeds-32zm50x2.js} +4 -4
  15. package/dist/{boxd-68n75y1s.js → boxd-hr8rsxzq.js} +1 -1
  16. package/dist/{claude-adapter-h3mp9hgs.js → claude-adapter-gwq7x2nj.js} +9 -9
  17. package/dist/{claude-managed-adapter-kpbyj2vb.js → claude-managed-adapter-rkvw6fvq.js} +4 -4
  18. package/dist/{claude-managed-setup-0efr3wkg.js → claude-managed-setup-0vgz4d1j.js} +6 -6
  19. package/dist/{claude-sdk-session-03dw669q.js → claude-sdk-session-5wbwxy8c.js} +20967 -19390
  20. package/dist/{cli-z64t9pe6.js → cli-0f7n3td3.js} +1 -1
  21. package/dist/{cli-j53hpbsm.js → cli-0xwb7zpt.js} +2 -2
  22. package/dist/{cli-wxwv3t11.js → cli-1f48qdnb.js} +55 -13
  23. package/dist/{cli-gfcv679k.js → cli-1gevjrc1.js} +1 -1
  24. package/dist/{cli-0jkenasr.js → cli-2v4xxnx2.js} +1 -1
  25. package/dist/{cli-hc6e4tac.js → cli-2wde56gv.js} +6 -6
  26. package/dist/{cli-mh7pdxe0.js → cli-31vt7baf.js} +17 -17
  27. package/dist/{cli-ercwc8xn.js → cli-3mf04tkh.js} +1 -1
  28. package/dist/{cli-s6zk31gr.js → cli-43dsqhcp.js} +4 -4
  29. package/dist/{cli-1dbv9mj9.js → cli-4djg31jh.js} +1 -1
  30. package/dist/{cli-tn91wc6e.js → cli-50whymxq.js} +1 -1
  31. package/dist/{cli-js10kdk7.js → cli-5basv0e7.js} +19 -5
  32. package/dist/{cli-b2jh3dyb.js → cli-5k1hvycs.js} +4 -4
  33. package/dist/{cli-dkejt425.js → cli-62fjschk.js} +7 -7
  34. package/dist/{cli-zqmmy073.js → cli-69eq6gdk.js} +18 -18
  35. package/dist/{cli-qm3ntjqs.js → cli-6rmryz03.js} +13 -13
  36. package/dist/{cli-mz34pxbk.js → cli-7m6bbtab.js} +11 -11
  37. package/dist/{cli-wv20kbr3.js → cli-8a4qg44m.js} +5 -5
  38. package/dist/{cli-2m6yaq6b.js → cli-8fj8yfmk.js} +1 -1
  39. package/dist/{cli-9m9kyw77.js → cli-8qvte9hn.js} +2 -2
  40. package/dist/{cli-x05p2d05.js → cli-9tevdxyf.js} +1 -1
  41. package/dist/{cli-qec9bynj.js → cli-a6rzw649.js} +3 -3
  42. package/dist/{cli-ex1y88j3.js → cli-at67kvnp.js} +1 -1
  43. package/dist/{cli-yn4kt85g.js → cli-b0kqw55g.js} +1 -1
  44. package/dist/{cli-n3qe7tyr.js → cli-b0m3bg0f.js} +134 -3
  45. package/dist/{cli-xfjn2kyq.js → cli-bp2rt28p.js} +9 -9
  46. package/dist/{cli-2jk4s7z1.js → cli-c9bwawf9.js} +3 -3
  47. package/dist/{cli-wndegmns.js → cli-cmgdptmx.js} +3 -3
  48. package/dist/{cli-3p288654.js → cli-cpkxh68d.js} +2 -2
  49. package/dist/{cli-117g15t4.js → cli-cs26ed89.js} +8 -8
  50. package/dist/{cli-prf7kz78.js → cli-d0jb2qnt.js} +603 -78
  51. package/dist/{cli-8hp56wat.js → cli-d2epqm0y.js} +1 -1
  52. package/dist/{cli-wrhbym01.js → cli-d528acsw.js} +6 -6
  53. package/dist/{cli-tstj6e8e.js → cli-dnvmwsvc.js} +310 -88
  54. package/dist/{cli-9fsagra4.js → cli-e87fg3en.js} +1 -1
  55. package/dist/{cli-jj3c5nyb.js → cli-erh1rgh4.js} +116 -56
  56. package/dist/{cli-f1952kjy.js → cli-ewb028rs.js} +4 -4
  57. package/dist/{cli-ct8sz3np.js → cli-f1sdh8ca.js} +6 -6
  58. package/dist/{cli-0b655smz.js → cli-fcwrd7bh.js} +5 -5
  59. package/dist/{cli-eb279wn3.js → cli-fgm2mad9.js} +2 -2
  60. package/dist/{cli-bpje8n65.js → cli-fp65jdp2.js} +31 -6
  61. package/dist/{cli-dnh64e8e.js → cli-g0b3ma7r.js} +7 -7
  62. package/dist/{cli-avxh26pd.js → cli-gc7jkf4a.js} +4 -4
  63. package/dist/{cli-2skf1mdf.js → cli-gedf48yw.js} +4 -4
  64. package/dist/{cli-ajjvqhf3.js → cli-getrvmtx.js} +27 -6
  65. package/dist/{cli-c8v2yvej.js → cli-gq6qhmrr.js} +2 -2
  66. package/dist/{cli-mbwmqb5w.js → cli-h0ewec3d.js} +1 -1
  67. package/dist/{cli-tdk7jtka.js → cli-hv3820ez.js} +1 -1
  68. package/dist/{cli-avqkr20b.js → cli-j2ybkdk2.js} +2 -2
  69. package/dist/{cli-pqfecppn.js → cli-je587f74.js} +1 -1
  70. package/dist/{cli-hgsxnjyg.js → cli-jkkcm72j.js} +13 -13
  71. package/dist/{cli-g6j6ac3h.js → cli-ka13xx6b.js} +2 -2
  72. package/dist/{cli-t35hx078.js → cli-m1wddksc.js} +2 -2
  73. package/dist/{cli-50w82h6m.js → cli-mwxez0pz.js} +1 -0
  74. package/dist/{cli-nc6a8b5b.js → cli-n14r8h4n.js} +2 -2
  75. package/dist/{cli-y4a4458j.js → cli-n46d87mj.js} +3 -3
  76. package/dist/{cli-0dg7ytxm.js → cli-nkfv398a.js} +1096 -75
  77. package/dist/{cli-fhvk2nvp.js → cli-nvqq3232.js} +9 -9
  78. package/dist/{cli-bhgrhedp.js → cli-q8aq48v1.js} +1 -1
  79. package/dist/{cli-6a40p4kv.js → cli-qn79645p.js} +1 -1
  80. package/dist/{cli-hbq0kwxz.js → cli-r4fphq38.js} +4 -4
  81. package/dist/{cli-47hz21se.js → cli-r8ddn0hf.js} +4 -5
  82. package/dist/{cli-hpb9x72z.js → cli-rvhaahfv.js} +9 -9
  83. package/dist/{cli-qhhb30e8.js → cli-s08zsqva.js} +9 -9
  84. package/dist/{cli-sdh61g52.js → cli-s6fhqbz1.js} +2 -2
  85. package/dist/{cli-y518qkjg.js → cli-sjk85d7v.js} +13 -12
  86. package/dist/{cli-ytc7fpza.js → cli-t25rq8mg.js} +4 -4
  87. package/dist/{cli-sq913bh1.js → cli-t9nxq30h.js} +8 -8
  88. package/dist/{cli-49f5jyhh.js → cli-tbdw3f92.js} +3 -3
  89. package/dist/{cli-1v82d2w6.js → cli-tceqvv6h.js} +4 -4
  90. package/dist/{cli-fz9pcjsw.js → cli-tgmate57.js} +4 -4
  91. package/dist/{cli-rtmqzat7.js → cli-vdfngx2g.js} +2 -2
  92. package/dist/{cli-9w8712tq.js → cli-vr4eyq6p.js} +43 -14
  93. package/dist/{cli-z4f346g5.js → cli-vx9acp12.js} +1 -1
  94. package/dist/{cli-7dbhnsj9.js → cli-wdtqkqnq.js} +4 -4
  95. package/dist/{cli-kde4ky90.js → cli-x5yb8zc8.js} +2 -2
  96. package/dist/{cli-w14j2z4k.js → cli-x7aqhxj5.js} +2 -2
  97. package/dist/{cli-kspxjftk.js → cli-xerdrnqs.js} +15 -6
  98. package/dist/{cli-48nvk6sb.js → cli-xhkek467.js} +2 -2
  99. package/dist/{cli-dka73bak.js → cli-xysy1g8x.js} +152 -12
  100. package/dist/{cli-7wy8gbwb.js → cli-ya1cj689.js} +1 -1
  101. package/dist/{cli-n85m2wkq.js → cli-zkbz8m2q.js} +3 -2
  102. package/dist/{cli-0pazkmd4.js → cli-zm6bkx3e.js} +4 -4
  103. package/dist/{cli-6h88mn9q.js → cli-zqy28rwx.js} +4 -4
  104. package/dist/cli.js +30 -29
  105. package/dist/{codex-adapter-f3yp0kaj.js → codex-adapter-x25xfbnh.js} +8 -8
  106. package/dist/{codex-hook-262cekfp.js → codex-hook-c0nvm30r.js} +2 -2
  107. package/dist/{codex-login-1ven7yje.js → codex-login-ven5cz5j.js} +1 -1
  108. package/dist/{codex-session-runner-ns4mv70p.js → codex-session-runner-kn5xnrvp.js} +9 -9
  109. package/dist/{commands-5bzf2tfw.js → commands-8n59gxmy.js} +3 -3
  110. package/dist/{controller-5xt7kvfm.js → controller-wn3vd217.js} +3 -3
  111. package/dist/{controllers-connect-0gg13mzp.js → controllers-connect-09gvkrhc.js} +28 -28
  112. package/dist/core-2b8bv6ny.js +42 -0
  113. package/dist/{cursor-adapter-p0c5zv6r.js → cursor-adapter-w1681kp1.js} +2 -2
  114. package/dist/{db-2s68ycq7.js → db-e71keqxk.js} +3 -3
  115. package/dist/{db-q7q639k5.js → db-spg81qtr.js} +2 -2
  116. package/dist/{devin-adapter-t8d86q9x.js → devin-adapter-fs90ab4v.js} +1 -1
  117. package/dist/{dispatcher-j2y1q7ae.js → dispatcher-fr4vawwb.js} +25 -25
  118. package/dist/{docker-1b41eysj.js → docker-1h33jvh9.js} +2 -2
  119. package/dist/{dsh-adapter-pgnkf4st.js → dsh-adapter-g9yqv09y.js} +2 -2
  120. package/dist/{e2b-xm60c8ad.js → e2b-jnk0yeva.js} +2 -2
  121. package/dist/{e2b-ew8c5j5v.js → e2b-y7e5kmzf.js} +2 -2
  122. package/dist/{easter-egg-3d-0kea97jf.js → easter-egg-3d-ac9tv9a6.js} +1 -1
  123. package/dist/{embedding-space-3n6mhhmy.js → embedding-space-an77f45k.js} +6 -6
  124. package/dist/{embeddings-jfmj6yme.js → embeddings-jkrehejr.js} +1 -1
  125. package/dist/{event-bus-v4ywhc2p.js → event-bus-08t2b4y2.js} +1 -1
  126. package/dist/{execute-tjrej979.js → execute-3mys4nta.js} +1 -1
  127. package/dist/{external-channel-jy8w2gg3.js → external-channel-s6zxpts9.js} +2 -2
  128. package/dist/fx-adapter-4yet1c4f.js +20 -0
  129. package/dist/grok-adapter-8ge6tw7m.js +20 -0
  130. package/dist/handlers-0r9evrdj.js +41 -0
  131. package/dist/heartbeat-jjpb44e5.js +50 -0
  132. package/dist/{hook-fv1jwrv7.js → hook-68gbs87k.js} +6 -6
  133. package/dist/{hook-bpnncsec.js → hook-y6n23zzj.js} +8 -8
  134. package/dist/{http-bpa26czn.js → http-8c6y008s.js} +404 -146
  135. package/dist/{index-w216g9y9.js → index-0vthtbc2.js} +38 -22
  136. package/dist/index-1v23363p.js +39 -0
  137. package/dist/index-30qw6vyw.js +44 -0
  138. package/dist/index-6bm3w6cn.js +40 -0
  139. package/dist/{index-s8re7mvq.js → index-6h3r0vpe.js} +1 -1
  140. package/dist/{index-620y7jzq.js → index-7dgxveck.js} +3 -3
  141. package/dist/{index-4k7m5dgj.js → index-maddg9ys.js} +143 -103
  142. package/dist/{index-0h6qd4p1.js → index-mbpxhc4w.js} +3 -4
  143. package/dist/index-rz8ve510.js +569 -0
  144. package/dist/{index-mpj0z9e0.js → index-we3nd2t0.js} +1 -1
  145. package/dist/{index-pe3d8jfy.js → index-whysn1wf.js} +1 -1
  146. package/dist/{index-52tgbhrw.js → index-xcw7hjt5.js} +28 -28
  147. package/dist/{index-8p0j4h4j.js → index-ym9fgxad.js} +94 -89
  148. package/dist/{k8s-fy8hbhkg.js → k8s-8326q0rq.js} +2 -2
  149. package/dist/{keepalive-d6z12s04.js → keepalive-7e9r5dvp.js} +5 -4
  150. package/dist/lead-3jpc7kcr.js +79 -0
  151. package/dist/{maintenance-7kac6g2g.js → maintenance-d3erjvcg.js} +1 -1
  152. package/dist/{oauth-refresh-sweep-t1xjetbh.js → oauth-refresh-sweep-0qh70988.js} +4 -3
  153. package/dist/{object-webhooks-6rdagg0r.js → object-webhooks-ac7v2q5p.js} +7 -7
  154. package/dist/{onboard-32y1cfxy.js → onboard-5yphtken.js} +4 -4
  155. package/dist/{opencode-adapter-enp3v31n.js → opencode-adapter-0xvyba4m.js} +8 -8
  156. package/dist/{otel-impl-k0tm5ptj.js → otel-impl-svqp691q.js} +2 -2
  157. package/dist/{pending-24zebgvs.js → pending-bn4xe5br.js} +26 -26
  158. package/dist/{pi-mono-adapter-yj72xxxe.js → pi-mono-adapter-763s8a3w.js} +20 -18
  159. package/dist/{pricing-refresh-cf25x38j.js → pricing-refresh-kfc215mf.js} +2 -2
  160. package/dist/{rbac-roles-0wydd22m.js → rbac-roles-3bznvkpt.js} +3 -3
  161. package/dist/{rbac-roles-at6crb3r.js → rbac-roles-6r4h2ghj.js} +2 -2
  162. package/dist/{render-v2-nvcw0jd7.js → render-v2-f3qedbpy.js} +10 -10
  163. package/dist/{resume-y4w0k5v3.js → resume-vcag4ann.js} +13 -13
  164. package/dist/{runtime-vpe43hx0.js → runtime-x0s55z2t.js} +1 -1
  165. package/dist/{session-access-gkyvnfye.js → session-access-nwzve8q2.js} +5 -5
  166. package/dist/{session-source-backfill-3w2st4m2.js → session-source-backfill-jpqfzmgz.js} +2 -2
  167. package/dist/{setup-axxvqtys.js → setup-d2smwaem.js} +1 -1
  168. package/dist/thread-buffer-8fc703jc.js +42 -0
  169. package/dist/{tree-visibility-y4fqvab5.js → tree-visibility-dwzc8en0.js} +2 -2
  170. package/dist/{user-merge-jobs-kcmwvrc6.js → user-merge-jobs-4ce7kma2.js} +3 -3
  171. package/dist/{virtual-modules-7d92dct1.js → virtual-modules-78a6yw71.js} +3 -3
  172. package/dist/{work-objects-f708e069.js → work-objects-m0w1e7q8.js} +28 -28
  173. package/dist/worker-3p2vq107.js +79 -0
  174. package/dist/{worker-follow-up-0by8wztc.js → worker-follow-up-e3t6f895.js} +25 -25
  175. package/dist/{x-3dtaf2r9.js → x-asbrnafg.js} +2 -2
  176. package/openapi.json +1795 -1623
  177. package/package.json +13 -12
  178. package/src/apps/catalog.generated.json +726 -0
  179. package/src/apps/definition.ts +24 -7
  180. package/src/apps/page-validator.ts +225 -3
  181. package/src/be/db.ts +38 -10
  182. package/src/be/mcp-proxy.ts +5 -4
  183. package/src/be/migrations/340_api_key_spend_cap.sql +5 -0
  184. package/src/be/migrations/341_user_token_expiry.sql +4 -0
  185. package/src/be/schedules/validate.ts +26 -0
  186. package/src/be/scripts/run-credential.ts +55 -1
  187. package/src/be/scripts/typecheck.ts +4 -4
  188. package/src/be/scripts/user-code-mode.ts +160 -0
  189. package/src/be/swarm-config-guard.ts +4 -0
  190. package/src/be/users.ts +48 -7
  191. package/src/commands/credential-outcome-report.ts +5 -2
  192. package/src/commands/onboard/agent-fs-version.ts +1 -1
  193. package/src/commands/provider-credentials.ts +19 -0
  194. package/src/commands/provider-error-class.ts +4 -1
  195. package/src/commands/rate-limit-outcome.ts +48 -3
  196. package/src/commands/runner.ts +113 -55
  197. package/src/commands/worktree-reaper.ts +600 -0
  198. package/src/extensions/contract-types.generated.ts +1 -1
  199. package/src/http/agents.ts +4 -0
  200. package/src/http/api-keys.ts +27 -3
  201. package/src/http/pages-public.ts +40 -4
  202. package/src/http/pool-keys.ts +21 -2
  203. package/src/http/schedules.ts +28 -3
  204. package/src/http/script-connection-proxy.ts +18 -6
  205. package/src/http/script-connections.ts +12 -4
  206. package/src/http/script-runs.ts +12 -3
  207. package/src/http/scripts.ts +2 -11
  208. package/src/http/tasks.ts +6 -10
  209. package/src/http/users.ts +1 -0
  210. package/src/integrations/chat-sdk/adapters.ts +29 -0
  211. package/src/integrations/chat-sdk/limits.ts +3 -0
  212. package/src/integrations/chat-sdk/rocketchat/README.md +8 -0
  213. package/src/integrations/chat-sdk/rocketchat/index.ts +790 -0
  214. package/src/integrations/chat-sdk/rocketchat/markdown.ts +210 -0
  215. package/src/integrations/chat-sdk/rocketchat/types.ts +249 -0
  216. package/src/integrations/chat-sdk/runtime.ts +11 -5
  217. package/src/integrations/chat-sdk/schema.ts +37 -3
  218. package/src/integrations/chat-sdk/status.ts +9 -0
  219. package/src/mcp-client/http-client.ts +3 -1
  220. package/src/oauth/identity-capture.ts +6 -1
  221. package/src/oauth/mcp-wrapper.ts +10 -3
  222. package/src/oauth/wrapper.ts +15 -3
  223. package/src/prompts/session-templates.ts +1 -0
  224. package/src/providers/acp-targets.ts +2 -2
  225. package/src/providers/amp-adapter.ts +1 -1
  226. package/src/providers/dsh-adapter.ts +1 -1
  227. package/src/providers/pi-mono-adapter.ts +4 -2
  228. package/src/providers/runtime-dependencies.ts +1 -1
  229. package/src/rbac/legacy-policy.ts +3 -0
  230. package/src/rbac/permissions.ts +9 -0
  231. package/src/scripts-runtime/executors/native.ts +225 -67
  232. package/src/scripts-runtime/mcp-client.ts +2 -1
  233. package/src/scripts-runtime/swarm-sdk.ts +2 -1
  234. package/src/scripts-runtime/types/stdlib.d.ts +4 -4
  235. package/src/scripts-runtime/types/swarm-extension.d.ts +7 -7
  236. package/src/scripts-runtime/types/swarm-sdk.d.ts +4 -4
  237. package/src/server-user.ts +98 -0
  238. package/src/slack/enrich.ts +14 -11
  239. package/src/tests/agents-list-model-display.test.ts +23 -0
  240. package/src/tests/apps-spike2.test.ts +35 -0
  241. package/src/tests/base-prompt.test.ts +1 -0
  242. package/src/tests/chat-sdk-rocketchat-vendored.test.ts +67 -0
  243. package/src/tests/chat-sdk-status-route.test.ts +13 -1
  244. package/src/tests/codex-app-server.test.ts +4 -6
  245. package/src/tests/deploy-guard.test.ts +24 -0
  246. package/src/tests/dsh-adapter.test.ts +1 -1
  247. package/src/tests/ensure-token.test.ts +2 -2
  248. package/src/tests/entrypoint-repo-autoclone-args.test.ts +202 -0
  249. package/src/tests/fake-dns.ts +47 -0
  250. package/src/tests/fixtures/base-prompt-baseline.json +12 -12
  251. package/src/tests/latest-model-report.test.ts +138 -0
  252. package/src/tests/mcp-oauth-dcr-reuse.test.ts +5 -2
  253. package/src/tests/mcp-oauth-ensure-token.test.ts +3 -2
  254. package/src/tests/mcp-oauth-manual-client.test.ts +6 -1
  255. package/src/tests/mcp-oauth-wrapper.test.ts +20 -4
  256. package/src/tests/mcp-outbound-fetch-guard.test.ts +169 -0
  257. package/src/tests/mcp-server-ssrf.test.ts +2 -0
  258. package/src/tests/mcp-user-route.test.ts +10 -1
  259. package/src/tests/memory-search-stall.test.ts +5 -0
  260. package/src/tests/oauth-connection-fetch-guard.test.ts +162 -0
  261. package/src/tests/oauth-token-endpoint-fetch-guard.test.ts +121 -0
  262. package/src/tests/oauth-wrapper.test.ts +1 -2
  263. package/src/tests/pages-head-v2.test.ts +2 -1
  264. package/src/tests/script-connections-http.test.ts +8 -3
  265. package/src/tests/script-connections-mcp.test.ts +14 -10
  266. package/src/tests/script-connections-sql.test.ts +6 -2
  267. package/src/tests/script-connections.test.ts +4 -0
  268. package/src/tests/slack-thread-participants.test.ts +14 -3
  269. package/src/tests/spend-cap-credentials.test.ts +34 -0
  270. package/src/tests/spend-cap-outcome.test.ts +67 -0
  271. package/src/tests/subscription-first.test.ts +119 -0
  272. package/src/tests/worktree-reaper.test.ts +424 -0
  273. package/src/tools/get-task-details.ts +247 -5
  274. package/src/tools/schedules/patch-schedule.ts +26 -1
  275. package/src/tools/schedules/update-schedule.ts +28 -2
  276. package/src/tools/script-common.ts +37 -22
  277. package/src/tools/script-query-types.ts +1 -1
  278. package/src/tools/script-run.ts +1 -1
  279. package/src/tools/script-search.ts +12 -10
  280. package/src/tools/utils.ts +7 -1
  281. package/src/utils/credentials.ts +36 -1
  282. package/src/utils/egress-guard.ts +40 -10
  283. package/src/utils/error-tracker.ts +17 -0
  284. package/templates/skills/apps/SKILL.md +191 -2
  285. package/templates/skills/apps/content.md +191 -2
  286. package/templates/skills/boards-and-sheets/content.md +11 -0
  287. package/templates/skills/chat-sdk/content.md +2 -2
  288. package/templates/skills/pages/content.md +11 -0
  289. package/templates/skills/swarm-docs/content.md +4 -0
  290. package/templates/skills/swarm-scripts/SKILL.md +1 -0
  291. package/templates/skills/swarm-scripts/content.md +1 -0
  292. package/templates/workflows/ralph-loop/content.md +6 -6
  293. package/dist/acp-adapter-cn53011z.js +0 -17
  294. package/dist/cli-pr0eze3x.js +0 -149
  295. package/dist/core-0fqtbrxa.js +0 -42
  296. package/dist/fx-adapter-k6w3jvz9.js +0 -20
  297. package/dist/grok-adapter-4q5tssw0.js +0 -20
  298. package/dist/handlers-qxgfvvsf.js +0 -41
  299. package/dist/heartbeat-6tr2w2da.js +0 -50
  300. package/dist/index-0mcxjdsa.js +0 -44
  301. package/dist/index-dz4q23ag.js +0 -40
  302. package/dist/index-s175jckx.js +0 -39
  303. package/dist/lead-p3hx7h35.js +0 -79
  304. package/dist/thread-buffer-rwa7d4dx.js +0 -42
  305. package/dist/worker-8rg9gz74.js +0 -79
  306. /package/dist/{cli-m4ejz4nj.js → cli-cah298e5.js} +0 -0
@@ -11,16 +11,16 @@ import {
11
11
  checkDeepSeekApiKey,
12
12
  checkOpenAICompatibleProvider,
13
13
  writeSkillsToFilesystem
14
- } from "./cli-fz9pcjsw.js";
14
+ } from "./cli-tgmate57.js";
15
15
  import {
16
16
  renderSteeringDelivery
17
- } from "./cli-6a40p4kv.js";
17
+ } from "./cli-qn79645p.js";
18
18
  import {
19
19
  effectiveReasoningEffort
20
- } from "./cli-rtmqzat7.js";
20
+ } from "./cli-vdfngx2g.js";
21
21
  import {
22
22
  validateProviderDependencies
23
- } from "./cli-0pazkmd4.js";
23
+ } from "./cli-zm6bkx3e.js";
24
24
  import {
25
25
  isSkillLoaderCall,
26
26
  skillFromToolArgs,
@@ -28,48 +28,49 @@ import {
28
28
  } from "./cli-77cd6gy8.js";
29
29
  import {
30
30
  MAX_RATE_LIMIT_RESET_MS,
31
+ MAX_SPEND_CAP_HOLD_MS,
31
32
  isRateLimitMessage,
32
33
  isCodexCreditsExhaustedMessage,
33
34
  CODEX_CREDITS_EXHAUSTED_COOLDOWN_MS,
34
35
  resolveCodexCreditsExhaustedCooldownMs,
35
36
  parseRateLimitResetTime
36
- } from "./cli-n85m2wkq.js";
37
+ } from "./cli-zkbz8m2q.js";
37
38
  import {
38
39
  ACP_TARGET_IDS,
39
40
  isAcpTarget
40
- } from "./cli-tdk7jtka.js";
41
+ } from "./cli-hv3820ez.js";
41
42
  import {
42
43
  checkAmpCredentials2,
43
44
  liveTestAmpCredentials2
44
- } from "./cli-wv20kbr3.js";
45
+ } from "./cli-8a4qg44m.js";
45
46
  import {
46
47
  checkClaudeCredentials2
47
- } from "./cli-qhhb30e8.js";
48
+ } from "./cli-s08zsqva.js";
48
49
  import {
49
50
  checkClaudeManagedCredentials2
50
- } from "./cli-dnh64e8e.js";
51
+ } from "./cli-g0b3ma7r.js";
51
52
  import {
52
53
  codexUserHome,
53
54
  checkCodexCredentials2
54
- } from "./cli-qm3ntjqs.js";
55
+ } from "./cli-6rmryz03.js";
55
56
  import {
56
57
  checkCursorCredentials2
57
- } from "./cli-2skf1mdf.js";
58
+ } from "./cli-gedf48yw.js";
58
59
  import {
59
60
  checkDevinCredentials2
60
- } from "./cli-pqfecppn.js";
61
+ } from "./cli-je587f74.js";
61
62
  import {
62
63
  checkDshCredentials2
63
- } from "./cli-ytc7fpza.js";
64
+ } from "./cli-t25rq8mg.js";
64
65
  import {
65
66
  checkOpencodeCredentials2
66
- } from "./cli-hpb9x72z.js";
67
+ } from "./cli-rvhaahfv.js";
67
68
  import {
68
69
  checkFxCredentials2
69
- } from "./cli-f1952kjy.js";
70
+ } from "./cli-ewb028rs.js";
70
71
  import {
71
72
  checkGrokCredentials2
72
- } from "./cli-2jk4s7z1.js";
73
+ } from "./cli-c9bwawf9.js";
73
74
  import {
74
75
  CODEX_OAUTH_POOL_SLOTS_ENV,
75
76
  isCodexOAuthConfigKey,
@@ -79,7 +80,7 @@ import {
79
80
  import {
80
81
  getContextWindowSize,
81
82
  init_context_window
82
- } from "./cli-3p288654.js";
83
+ } from "./cli-cpkxh68d.js";
83
84
  import {
84
85
  isAzureDevOpsUrl,
85
86
  canonicalAzureDevOpsRepoUrl,
@@ -87,7 +88,7 @@ import {
87
88
  init_azure_devops,
88
89
  resolveScriptsOnlyMode,
89
90
  init_scripts_only_mode
90
- } from "./cli-tstj6e8e.js";
91
+ } from "./cli-dnvmwsvc.js";
91
92
  import {
92
93
  terminateRegisteredProcessGroups,
93
94
  init_process_group
@@ -95,14 +96,14 @@ import {
95
96
  import {
96
97
  validateJsonSchema,
97
98
  init_json_schema_validator
98
- } from "./cli-hgsxnjyg.js";
99
+ } from "./cli-jkkcm72j.js";
99
100
  import {
100
101
  authJsonToCredentialSelection,
101
102
  credentialsToAuthJson,
102
103
  init_auth_json,
103
104
  loadAllCodexOAuthSlots,
104
105
  init_storage
105
- } from "./cli-2m6yaq6b.js";
106
+ } from "./cli-8fj8yfmk.js";
106
107
  import {
107
108
  getApiKey,
108
109
  init_api_key
@@ -118,7 +119,7 @@ import {
118
119
  initialize,
119
120
  ensure,
120
121
  init_business_use
121
- } from "./cli-zqmmy073.js";
122
+ } from "./cli-69eq6gdk.js";
122
123
  import {
123
124
  sourceOfKey,
124
125
  init_source_key,
@@ -140,7 +141,7 @@ import {
140
141
  init_vcs_repo_match,
141
142
  resumedTaskModelSelection,
142
143
  init_model_pin
143
- } from "./cli-jj3c5nyb.js";
144
+ } from "./cli-erh1rgh4.js";
144
145
  import {
145
146
  isCodexAuthFailureReason,
146
147
  init_codex_auth_failure
@@ -177,7 +178,7 @@ import {
177
178
  resolveClaudeMdPath,
178
179
  syncProfileFilesToServer,
179
180
  init_profile_sync
180
- } from "./cli-sdh61g52.js";
181
+ } from "./cli-s6fhqbz1.js";
181
182
  import {
182
183
  isSteeringEnabled2,
183
184
  init_steering_enabled
@@ -194,19 +195,20 @@ import {
194
195
  CREDENTIAL_POOL_VARS,
195
196
  normalizeProviderKeyAliases,
196
197
  ModelWindowExhaustedError,
198
+ KeySpendCapError,
197
199
  CredentialAllowlistError,
198
200
  splitCredentialPool,
199
201
  CLAUDE_CREDENTIALS_HINT,
200
202
  resolveCredentialPools,
201
203
  init_credentials2
202
- } from "./cli-js10kdk7.js";
204
+ } from "./cli-5basv0e7.js";
203
205
  import {
204
206
  interpolate,
205
207
  init_template2,
206
208
  configureHttpResolver,
207
209
  resolveTemplateAsync,
208
210
  init_resolver
209
- } from "./cli-50w82h6m.js";
211
+ } from "./cli-mwxez0pz.js";
210
212
  import {
211
213
  isGroupKey,
212
214
  init_key,
@@ -221,7 +223,7 @@ import {
221
223
  runtimeHarnessSections,
222
224
  refreshRuntimeModelCatalog,
223
225
  init_runtime_model_catalog
224
- } from "./cli-bhgrhedp.js";
226
+ } from "./cli-q8aq48v1.js";
225
227
  import {
226
228
  getMcpBaseUrl,
227
229
  init_constants3
@@ -231,7 +233,8 @@ import {
231
233
  init_env_flag
232
234
  } from "./cli-cebvbc9t.js";
233
235
  import {
234
- isChatgptSubscriptionModel,
236
+ chatgptSubscriptionTrait,
237
+ chatgptSubscriptionModel,
235
238
  harnessModelMismatch,
236
239
  openAICompatibleProviders,
237
240
  openAICompatibleKeyVars,
@@ -243,7 +246,7 @@ import {
243
246
  registerEnvSecrets,
244
247
  registerSensitiveKeyName,
245
248
  init_secret_scrubber
246
- } from "./cli-bpje8n65.js";
249
+ } from "./cli-fp65jdp2.js";
247
250
 
248
251
  // src/commands/runner.ts
249
252
  init_src2();
@@ -254,7 +257,7 @@ init_otel();
254
257
  init_base_prompt();
255
258
  init_defaults();
256
259
  import { existsSync, statSync } from "node:fs";
257
- import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
260
+ import { mkdir as mkdir2, readFile, stat as stat2, writeFile } from "node:fs/promises";
258
261
  init_resolver();
259
262
  init_auth_json();
260
263
 
@@ -287,51 +290,51 @@ init_storage();
287
290
  async function createProviderAdapter(provider) {
288
291
  switch (provider) {
289
292
  case "claude": {
290
- const { ClaudeAdapter } = await import("./claude-adapter-h3mp9hgs.js");
293
+ const { ClaudeAdapter } = await import("./claude-adapter-gwq7x2nj.js");
291
294
  return new ClaudeAdapter;
292
295
  }
293
296
  case "pi": {
294
- const { PiMonoAdapter } = await import("./pi-mono-adapter-yj72xxxe.js");
297
+ const { PiMonoAdapter } = await import("./pi-mono-adapter-763s8a3w.js");
295
298
  return new PiMonoAdapter;
296
299
  }
297
300
  case "codex": {
298
- const { CodexAdapter } = await import("./codex-adapter-f3yp0kaj.js");
301
+ const { CodexAdapter } = await import("./codex-adapter-x25xfbnh.js");
299
302
  return new CodexAdapter;
300
303
  }
301
304
  case "claude-managed": {
302
- const { ClaudeManagedAdapter } = await import("./claude-managed-adapter-kpbyj2vb.js");
305
+ const { ClaudeManagedAdapter } = await import("./claude-managed-adapter-rkvw6fvq.js");
303
306
  return new ClaudeManagedAdapter;
304
307
  }
305
308
  case "devin": {
306
- const { DevinAdapter } = await import("./devin-adapter-t8d86q9x.js");
309
+ const { DevinAdapter } = await import("./devin-adapter-fs90ab4v.js");
307
310
  return new DevinAdapter;
308
311
  }
309
312
  case "opencode": {
310
- const { OpencodeAdapter } = await import("./opencode-adapter-enp3v31n.js");
313
+ const { OpencodeAdapter } = await import("./opencode-adapter-0xvyba4m.js");
311
314
  return new OpencodeAdapter;
312
315
  }
313
316
  case "dsh": {
314
- const { DshAdapter } = await import("./dsh-adapter-pgnkf4st.js");
317
+ const { DshAdapter } = await import("./dsh-adapter-g9yqv09y.js");
315
318
  return new DshAdapter;
316
319
  }
317
320
  case "amp": {
318
- const { AmpAdapter } = await import("./amp-adapter-gt503ywc.js");
321
+ const { AmpAdapter } = await import("./amp-adapter-nthn8ezm.js");
319
322
  return new AmpAdapter;
320
323
  }
321
324
  case "cursor": {
322
- const { CursorAdapter } = await import("./cursor-adapter-p0c5zv6r.js");
325
+ const { CursorAdapter } = await import("./cursor-adapter-w1681kp1.js");
323
326
  return new CursorAdapter;
324
327
  }
325
328
  case "grok": {
326
- const { GrokAdapter } = await import("./grok-adapter-4q5tssw0.js");
329
+ const { GrokAdapter } = await import("./grok-adapter-8ge6tw7m.js");
327
330
  return new GrokAdapter;
328
331
  }
329
332
  case "fx": {
330
- const { FxAdapter } = await import("./fx-adapter-k6w3jvz9.js");
333
+ const { FxAdapter } = await import("./fx-adapter-4yet1c4f.js");
331
334
  return new FxAdapter;
332
335
  }
333
336
  case "acp": {
334
- const { ACPAdapter } = await import("./acp-adapter-cn53011z.js");
337
+ const { ACPAdapter } = await import("./acp-adapter-x1qqgzwx.js");
335
338
  return new ACPAdapter;
336
339
  }
337
340
  default:
@@ -1116,11 +1119,27 @@ init_model_rate_limit_windows();
1116
1119
 
1117
1120
  // src/commands/rate-limit-outcome.ts
1118
1121
  init_model_rate_limit_windows();
1119
- function clampMs(candidateMs, nowMs) {
1122
+ function clampMs(candidateMs, nowMs, maxResetMs = MAX_RATE_LIMIT_RESET_MS) {
1120
1123
  const minMs = nowMs + 60000;
1121
- const maxMs = nowMs + MAX_RATE_LIMIT_RESET_MS;
1124
+ const maxMs = nowMs + maxResetMs;
1122
1125
  return Math.min(Math.max(candidateMs, minMs), maxMs);
1123
1126
  }
1127
+ var SPEND_CAP_TEXT = /key limit exceeded|"limit_source"\s*:\s*"openrouter_key_limit"|insufficient credits|requires more credits/i;
1128
+ function numberOf(text, pattern) {
1129
+ const value = Number(text.match(pattern)?.[1]);
1130
+ return Number.isFinite(value) ? value : null;
1131
+ }
1132
+ function parseSpendCapMessage(text) {
1133
+ if (!SPEND_CAP_TEXT.test(text))
1134
+ return null;
1135
+ const resetText = text.match(/"resets_at"\s*:\s*"([^"]+)"/)?.[1] ?? text.match(/resets (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/)?.[1];
1136
+ const resetMs = resetText ? Date.parse(resetText) : Number.NaN;
1137
+ return {
1138
+ limitUsd: numberOf(text, /"limit_usd"\s*:\s*([\d.]+)/) ?? numberOf(text, /of \$([\d.]+) used/),
1139
+ spendUsd: numberOf(text, /"spend_usd"\s*:\s*([\d.]+)/) ?? numberOf(text, /\$([\d.]+) of \$[\d.]+ used/),
1140
+ resetsAt: Number.isFinite(resetMs) ? new Date(resetMs).toISOString() : null
1141
+ };
1142
+ }
1124
1143
  function classifyRateLimitOutcome(result, failureReason, nowMs, codexCreditsExhaustedCooldownMs = CODEX_CREDITS_EXHAUSTED_COOLDOWN_MS, taskModelFamily) {
1125
1144
  const keyRateLimitedUntil = result.rateLimitResetAt ? new Date(clampMs(new Date(result.rateLimitResetAt).getTime(), nowMs)).toISOString() : undefined;
1126
1145
  const keyExtra = keyRateLimitedUntil ? { keyRateLimitedUntil } : {};
@@ -1157,6 +1176,15 @@ function classifyRateLimitOutcome(result, failureReason, nowMs, codexCreditsExha
1157
1176
  return { kind: "model", model: family, window, resetsAtSec, source: "text", ...keyExtra };
1158
1177
  }
1159
1178
  }
1179
+ const spendCap = failureReason != null ? parseSpendCapMessage(failureReason) : null;
1180
+ if (spendCap) {
1181
+ const untilMs = spendCap.resetsAt ? Date.parse(spendCap.resetsAt) : nowMs + MAX_SPEND_CAP_HOLD_MS;
1182
+ return {
1183
+ kind: "key",
1184
+ rateLimitedUntil: new Date(clampMs(untilMs, nowMs, MAX_SPEND_CAP_HOLD_MS)).toISOString(),
1185
+ spendCap
1186
+ };
1187
+ }
1160
1188
  if (result.rateLimitResetAt != null || failureReason != null && isRateLimitMessage(failureReason)) {
1161
1189
  let rateLimitedUntil;
1162
1190
  if (keyRateLimitedUntil) {
@@ -1217,7 +1245,7 @@ async function reportSeatMismatchOutcome(apiUrl, apiKey, credential, model) {
1217
1245
  }
1218
1246
 
1219
1247
  // src/commands/credential-outcome-report.ts
1220
- async function reportKeyRateLimit(apiUrl, apiKey, keyType, keySuffix, keyIndex, rateLimitedUntil) {
1248
+ async function reportKeyRateLimit(apiUrl, apiKey, keyType, keySuffix, keyIndex, rateLimitedUntil, spendCap) {
1221
1249
  try {
1222
1250
  const response = await fetch(`${apiUrl}/api/keys/report-rate-limit`, {
1223
1251
  method: "POST",
@@ -1229,7 +1257,8 @@ async function reportKeyRateLimit(apiUrl, apiKey, keyType, keySuffix, keyIndex,
1229
1257
  keyType,
1230
1258
  keySuffix,
1231
1259
  keyIndex,
1232
- rateLimitedUntil
1260
+ rateLimitedUntil,
1261
+ ...spendCap ? { spendCap } : {}
1233
1262
  }),
1234
1263
  signal: AbortSignal.timeout(1e4)
1235
1264
  });
@@ -1237,7 +1266,7 @@ async function reportKeyRateLimit(apiUrl, apiKey, keyType, keySuffix, keyIndex,
1237
1266
  console.warn(`[credentials] Failed to report key ...${keySuffix} as rate-limited: HTTP ${response.status}`);
1238
1267
  return;
1239
1268
  }
1240
- console.log(`[credentials] Reported key ...${keySuffix} as rate-limited until ${rateLimitedUntil}`);
1269
+ console.log(`[credentials] Reported key ...${keySuffix} as ${spendCap ? "spend-capped" : "rate-limited"} until ${rateLimitedUntil}`);
1241
1270
  } catch (err) {
1242
1271
  console.warn(`[credentials] Failed to report key ...${keySuffix} as rate-limited: ${err instanceof Error ? err.message : String(err)}`);
1243
1272
  }
@@ -1278,7 +1307,7 @@ async function reportCredentialOutcomeThenFinish(input, finish) {
1278
1307
  if (keyRateLimitedUntil) {
1279
1308
  console.log(`[credentials] Rate limit reset: ${keyRateLimitedUntil}`);
1280
1309
  input.modelWindowBlocks.set(`${credentialInfo.keyType}:${credentialInfo.keyIndex}:key`, Date.parse(keyRateLimitedUntil));
1281
- const report = reportKeyRateLimit(apiUrl, apiKey, credentialInfo.keyType, credentialInfo.keySuffix, credentialInfo.keyIndex, keyRateLimitedUntil).catch(() => {});
1310
+ const report = reportKeyRateLimit(apiUrl, apiKey, credentialInfo.keyType, credentialInfo.keySuffix, credentialInfo.keyIndex, keyRateLimitedUntil, outcome.kind === "key" ? outcome.spendCap : undefined).catch(() => {});
1282
1311
  if (outcome.kind === "key")
1283
1312
  await report;
1284
1313
  }
@@ -1354,7 +1383,7 @@ var CREDENTIAL_PROVIDER_CHECKERS = {
1354
1383
  devin: (env) => checkDevinCredentials2(env),
1355
1384
  opencode: (env, opts) => checkOpencodeCredentials2(env, opts),
1356
1385
  pi: async (env, opts) => {
1357
- const { checkPiMonoCredentials, listPiOpencodeGoModelIds } = await import("./pi-mono-adapter-yj72xxxe.js");
1386
+ const { checkPiMonoCredentials, listPiOpencodeGoModelIds } = await import("./pi-mono-adapter-763s8a3w.js");
1358
1387
  return {
1359
1388
  ...await checkPiMonoCredentials(env, opts),
1360
1389
  opencodeGoModels: listPiOpencodeGoModelIds()
@@ -1633,7 +1662,7 @@ async function validateProviderCredentials(provider, env = process.env, presence
1633
1662
  latency_ms: Date.now() - startedAt
1634
1663
  };
1635
1664
  }
1636
- const { liveTestCursorKey } = await import("./cursor-adapter-p0c5zv6r.js");
1665
+ const { liveTestCursorKey } = await import("./cursor-adapter-w1681kp1.js");
1637
1666
  return checkEachKey("CURSOR_API_KEY", apiKey, async (member) => {
1638
1667
  const start = Date.now();
1639
1668
  const result = await liveTestCursorKey(member);
@@ -1777,6 +1806,12 @@ async function reportAcpStatus(apiUrl, apiKey, agentId, acp) {
1777
1806
  console.warn(`[acp-status] POST failed (non-fatal): ${err}`);
1778
1807
  }
1779
1808
  }
1809
+ function taskSelectedModelForReport(opts) {
1810
+ if (opts.resolvedModel) {
1811
+ return opts.modelSource === "profile:agent-default" ? undefined : opts.resolvedModel;
1812
+ }
1813
+ return opts.localModel || undefined;
1814
+ }
1780
1815
  function buildLatestModelReport(opts) {
1781
1816
  const model = opts.model.trim();
1782
1817
  if (!model)
@@ -2078,7 +2113,7 @@ function classifyProviderError(result, failureReason, rateLimitOutcome) {
2078
2113
  return { errorClass: "model_window" };
2079
2114
  case "key":
2080
2115
  return {
2081
- errorClass: isCodexCreditsExhaustedMessage(text) ? "credits" : "rate_limit"
2116
+ errorClass: rateLimitOutcome.spendCap || isCodexCreditsExhaustedMessage(text) ? "credits" : "rate_limit"
2082
2117
  };
2083
2118
  case "none":
2084
2119
  break;
@@ -2264,6 +2299,461 @@ function resolveResumeSession(_currentProvider, candidates) {
2264
2299
 
2265
2300
  // src/commands/runner.ts
2266
2301
  init_templates4();
2302
+
2303
+ // src/commands/worktree-reaper.ts
2304
+ init_types5();
2305
+ import { mkdir, readdir, readlink, realpath, rename, rm, stat, statfs } from "node:fs/promises";
2306
+ import { dirname, join as join2 } from "node:path";
2307
+ var DEFAULT_WORKTREE_TTL_HOURS = 72;
2308
+ var DEFAULT_WORKTREE_SWEEP_INTERVAL_MINUTES = 60;
2309
+ function clampedNumber(raw, fallback, min, max) {
2310
+ const value = Number(raw);
2311
+ if (raw === undefined || raw.trim() === "" || !Number.isFinite(value))
2312
+ return fallback;
2313
+ return Math.min(max, Math.max(min, value));
2314
+ }
2315
+ function resolveWorktreeReaperConfig(env = process.env, hasLocalEnvironment = true) {
2316
+ const rawMode = env.WORKTREE_REAPER_MODE?.trim().toLowerCase();
2317
+ const mode = rawMode === "off" || rawMode === "on" || rawMode === "dry-run" ? rawMode : "dry-run";
2318
+ return {
2319
+ mode: hasLocalEnvironment ? mode : "off",
2320
+ ttlHours: clampedNumber(env.WORKTREE_TTL_HOURS, DEFAULT_WORKTREE_TTL_HOURS, 1, 24 * 90),
2321
+ sweepIntervalMinutes: clampedNumber(env.WORKTREE_SWEEP_INTERVAL_MINUTES, DEFAULT_WORKTREE_SWEEP_INTERVAL_MINUTES, 5, 24 * 60),
2322
+ extraRoots: (env.WORKTREE_REAPER_EXTRA_ROOTS ?? "").split(",").map((root) => root.trim()).filter(Boolean)
2323
+ };
2324
+ }
2325
+ var HOUR_MS = 3600000;
2326
+ async function git(dir, args) {
2327
+ const result = await Bun.$`env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_PREFIX git -C ${dir} ${args}`.quiet().nothrow();
2328
+ return {
2329
+ ok: result.exitCode === 0,
2330
+ stdout: result.stdout.toString().trim(),
2331
+ stderr: result.stderr.toString().trim()
2332
+ };
2333
+ }
2334
+ function parseWorktreeList(porcelain) {
2335
+ const worktrees = [];
2336
+ for (const block of porcelain.split(/\n\s*\n/)) {
2337
+ const lines = block.split(`
2338
+ `).filter(Boolean);
2339
+ const head = lines[0];
2340
+ if (!head?.startsWith("worktree "))
2341
+ continue;
2342
+ const info = {
2343
+ path: head.slice("worktree ".length),
2344
+ detached: false,
2345
+ bare: false,
2346
+ locked: false,
2347
+ prunable: false
2348
+ };
2349
+ for (const line of lines.slice(1)) {
2350
+ if (line.startsWith("branch "))
2351
+ info.branch = line.slice("branch refs/heads/".length);
2352
+ else if (line === "detached")
2353
+ info.detached = true;
2354
+ else if (line === "bare")
2355
+ info.bare = true;
2356
+ else if (line === "locked" || line.startsWith("locked "))
2357
+ info.locked = true;
2358
+ else if (line === "prunable" || line.startsWith("prunable "))
2359
+ info.prunable = true;
2360
+ }
2361
+ worktrees.push(info);
2362
+ }
2363
+ return worktrees;
2364
+ }
2365
+ function isInside(child, parent) {
2366
+ return child === parent || child.startsWith(`${parent}/`);
2367
+ }
2368
+ async function exists(path) {
2369
+ return stat(path).then(() => true, () => false);
2370
+ }
2371
+ async function procCwds() {
2372
+ const pids = await readdir("/proc").catch(() => []);
2373
+ const cwds = await Promise.all(pids.filter((pid) => /^\d+$/.test(pid)).map((pid) => readlink(`/proc/${pid}/cwd`).catch(() => null)));
2374
+ return cwds.filter((cwd) => cwd !== null);
2375
+ }
2376
+
2377
+ class WorktreeReaper {
2378
+ opts;
2379
+ ledger = null;
2380
+ discoveredRoots = [];
2381
+ queue = Promise.resolve();
2382
+ pending = 0;
2383
+ sweepQueued = false;
2384
+ constructor(opts) {
2385
+ this.opts = opts;
2386
+ }
2387
+ now() {
2388
+ return this.opts.now?.() ?? Date.now();
2389
+ }
2390
+ log(fields) {
2391
+ (this.opts.log ?? console.log)(JSON.stringify({ event: "worktree-reaper", ...fields }));
2392
+ }
2393
+ enqueue(fn) {
2394
+ this.pending += 1;
2395
+ const run = this.queue.then(fn).finally(() => {
2396
+ this.pending -= 1;
2397
+ });
2398
+ this.queue = run.catch(() => {
2399
+ return;
2400
+ });
2401
+ return run;
2402
+ }
2403
+ observe(active) {
2404
+ if (this.opts.getConfig().mode === "off" || this.pending > 0)
2405
+ return Promise.resolve();
2406
+ return this.enqueue(async () => {
2407
+ await this.scan(active, false);
2408
+ });
2409
+ }
2410
+ onTaskEnded(taskId, active) {
2411
+ if (this.opts.getConfig().mode === "off")
2412
+ return Promise.resolve({ decisions: [] });
2413
+ return this.enqueue(async () => {
2414
+ const worktrees = await this.scan([...active, { taskId }], false);
2415
+ const ledger = await this.loadLedger();
2416
+ const endedAt = new Date(this.now()).toISOString();
2417
+ for (const entry of Object.values(ledger.entries)) {
2418
+ if (entry.candidateTaskIds.includes(taskId))
2419
+ entry.lastTaskEndAt = endedAt;
2420
+ }
2421
+ await this.saveLedger();
2422
+ const decisions = [];
2423
+ for (const entry of Object.values(ledger.entries)) {
2424
+ if (!entry.candidateTaskIds.includes(taskId))
2425
+ continue;
2426
+ const info = worktrees.get(entry.path);
2427
+ if (info)
2428
+ decisions.push(await this.decideAndAct(entry, info, active, false));
2429
+ }
2430
+ return { decisions };
2431
+ });
2432
+ }
2433
+ sweep(active) {
2434
+ if (this.opts.getConfig().mode === "off" || this.sweepQueued) {
2435
+ return Promise.resolve({ decisions: [] });
2436
+ }
2437
+ this.sweepQueued = true;
2438
+ return this.enqueue(async () => {
2439
+ this.sweepQueued = false;
2440
+ const freeBefore = await this.freeBytes();
2441
+ const worktrees = await this.scan(active, true);
2442
+ const ledger = await this.loadLedger();
2443
+ const decisions = [];
2444
+ for (const entry of Object.values(ledger.entries)) {
2445
+ const info = worktrees.get(entry.path);
2446
+ if (info)
2447
+ decisions.push(await this.decideAndAct(entry, info, active, true));
2448
+ }
2449
+ const count = (...actions) => decisions.filter((d) => actions.includes(d.action)).length;
2450
+ this.log({
2451
+ action: "sweep-summary",
2452
+ mode: this.opts.getConfig().mode,
2453
+ worktrees: decisions.length,
2454
+ removed: count("remove", "would-remove", "finish-remove", "would-finish-remove"),
2455
+ slimmed: count("slim", "would-slim"),
2456
+ errors: count("error"),
2457
+ held: decisions.filter((d) => d.action === "skip" || d.action.endsWith("slim")).map((d) => `${d.path} (${d.reason})`),
2458
+ freeBytesBefore: freeBefore,
2459
+ freeBytesAfter: await this.freeBytes()
2460
+ });
2461
+ return { decisions };
2462
+ });
2463
+ }
2464
+ async freeBytes() {
2465
+ try {
2466
+ const fs = await statfs(dirname(this.opts.ledgerPath));
2467
+ return fs.bavail * fs.bsize;
2468
+ } catch {
2469
+ return null;
2470
+ }
2471
+ }
2472
+ async loadLedger() {
2473
+ if (this.ledger)
2474
+ return this.ledger;
2475
+ const file = Bun.file(this.opts.ledgerPath);
2476
+ const empty = { initialized: false, roots: [], entries: {} };
2477
+ if (!await file.exists()) {
2478
+ this.ledger = empty;
2479
+ return empty;
2480
+ }
2481
+ try {
2482
+ const parsed = await file.json();
2483
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.entries !== "object") {
2484
+ throw new Error("ledger has no entries map");
2485
+ }
2486
+ this.ledger = {
2487
+ initialized: parsed.initialized === true,
2488
+ roots: Array.isArray(parsed.roots) ? parsed.roots : [],
2489
+ entries: parsed.entries ?? {}
2490
+ };
2491
+ } catch (err) {
2492
+ const aside = `${this.opts.ledgerPath}.corrupt-${this.now()}`;
2493
+ await rename(this.opts.ledgerPath, aside).catch(() => {
2494
+ return;
2495
+ });
2496
+ this.log({ action: "ledger-reset", reason: String(err), path: aside });
2497
+ this.ledger = { initialized: false, roots: [], entries: {} };
2498
+ }
2499
+ return this.ledger;
2500
+ }
2501
+ async saveLedger() {
2502
+ if (!this.ledger)
2503
+ return;
2504
+ await mkdir(dirname(this.opts.ledgerPath), { recursive: true });
2505
+ const tmp = `${this.opts.ledgerPath}.tmp`;
2506
+ await Bun.write(tmp, JSON.stringify(this.ledger, null, 2));
2507
+ await rename(tmp, this.opts.ledgerPath);
2508
+ }
2509
+ async mainWorktreeOf(dir) {
2510
+ const common = await git(dir, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
2511
+ if (!common.ok || !common.stdout.endsWith("/.git"))
2512
+ return null;
2513
+ return dirname(common.stdout);
2514
+ }
2515
+ async discoverRoots() {
2516
+ const roots = [];
2517
+ for (const scanRoot of this.opts.scanRoots) {
2518
+ if (!await exists(scanRoot))
2519
+ continue;
2520
+ const found = await Bun.$`find ${scanRoot} -maxdepth 3 -name node_modules -prune -o -name .git -type d -print`.quiet().nothrow();
2521
+ for (const line of found.stdout.toString().split(`
2522
+ `)) {
2523
+ if (line.trim())
2524
+ roots.push(dirname(line.trim()));
2525
+ }
2526
+ }
2527
+ return roots;
2528
+ }
2529
+ async scan(active, refreshRoots) {
2530
+ const ledger = await this.loadLedger();
2531
+ if (refreshRoots || this.discoveredRoots.length === 0) {
2532
+ this.discoveredRoots = await this.discoverRoots();
2533
+ }
2534
+ const taskRoots = await Promise.all(active.flatMap((t) => t.workingDir ? [this.mainWorktreeOf(t.workingDir)] : []));
2535
+ const candidates = new Set([
2536
+ ...this.discoveredRoots,
2537
+ ...ledger.roots,
2538
+ ...this.opts.getConfig().extraRoots,
2539
+ ...taskRoots.filter((root) => root !== null)
2540
+ ]);
2541
+ const roots = new Set;
2542
+ for (const candidate of candidates) {
2543
+ const root = await this.mainWorktreeOf(candidate);
2544
+ if (root)
2545
+ roots.add(root);
2546
+ }
2547
+ const seen = new Map;
2548
+ const firstScan = !ledger.initialized;
2549
+ const nowIso = new Date(this.now()).toISOString();
2550
+ const activeIds = [...new Set(active.map((t) => t.taskId))];
2551
+ for (const root of roots) {
2552
+ const listed = await git(root, ["worktree", "list", "--porcelain"]);
2553
+ if (!listed.ok)
2554
+ continue;
2555
+ const [main, ...linked] = parseWorktreeList(listed.stdout);
2556
+ if (!main || main.bare)
2557
+ continue;
2558
+ for (const info of linked) {
2559
+ seen.set(info.path, info);
2560
+ if (ledger.entries[info.path])
2561
+ continue;
2562
+ ledger.entries[info.path] = {
2563
+ path: info.path,
2564
+ repoRoot: root,
2565
+ firstSeenAt: nowIso,
2566
+ candidateTaskIds: firstScan ? [] : activeIds
2567
+ };
2568
+ }
2569
+ }
2570
+ for (const path of Object.keys(ledger.entries)) {
2571
+ const entry = ledger.entries[path];
2572
+ if (!seen.has(path) && entry && roots.has(entry.repoRoot))
2573
+ delete ledger.entries[path];
2574
+ }
2575
+ ledger.roots = [...roots];
2576
+ ledger.initialized = true;
2577
+ await this.saveLedger();
2578
+ return seen;
2579
+ }
2580
+ async ageHours(entry) {
2581
+ const stamps = [];
2582
+ if (entry.lastTaskEndAt)
2583
+ stamps.push(Date.parse(entry.lastTaskEndAt));
2584
+ const gitDir = await git(entry.path, ["rev-parse", "--absolute-git-dir"]);
2585
+ if (gitDir.ok) {
2586
+ for (const name of ["HEAD", "index", "logs/HEAD"]) {
2587
+ const info = await stat(join2(gitDir.stdout, name)).catch(() => null);
2588
+ if (info)
2589
+ stamps.push(info.mtimeMs);
2590
+ }
2591
+ }
2592
+ if (stamps.length === 0)
2593
+ return null;
2594
+ return (this.now() - Math.max(...stamps)) / HOUR_MS;
2595
+ }
2596
+ async inUse(path, active) {
2597
+ for (const task of active) {
2598
+ if (!task.workingDir)
2599
+ continue;
2600
+ const dir = await realpath(task.workingDir).catch(() => task.workingDir);
2601
+ if (isInside(dir, path) || isInside(path, dir))
2602
+ return true;
2603
+ }
2604
+ const cwds = await (this.opts.processCwds ?? procCwds)();
2605
+ return cwds.some((cwd) => isInside(cwd, path));
2606
+ }
2607
+ async isDefaultUpstream(repoRoot, upstream) {
2608
+ const originHead = await git(repoRoot, [
2609
+ "symbolic-ref",
2610
+ "-q",
2611
+ "--short",
2612
+ "refs/remotes/origin/HEAD"
2613
+ ]);
2614
+ const defaults = new Set(["origin/main", "origin/master"]);
2615
+ if (originHead.ok && originHead.stdout)
2616
+ defaults.add(originHead.stdout);
2617
+ return defaults.has(upstream);
2618
+ }
2619
+ async ownerActive(entry, active) {
2620
+ const activeIds = new Set(active.map((t) => t.taskId));
2621
+ for (const taskId of entry.candidateTaskIds) {
2622
+ if (activeIds.has(taskId))
2623
+ return true;
2624
+ const status = await this.opts.statusOf(taskId);
2625
+ if (!status || !isTerminalTaskStatus(status))
2626
+ return true;
2627
+ }
2628
+ return false;
2629
+ }
2630
+ async decide(entry, info, active, ttlHours, ageHours) {
2631
+ if (info.locked)
2632
+ return { verdict: "skip", reason: "locked" };
2633
+ const real = await realpath(entry.path).catch(() => null);
2634
+ if (await this.inUse(real ?? entry.path, active))
2635
+ return { verdict: "skip", reason: "in-use" };
2636
+ const top = await git(entry.path, ["rev-parse", "--show-toplevel"]);
2637
+ if (info.prunable || real === null || top.stdout !== real) {
2638
+ if (real === null)
2639
+ return { verdict: "finish-remove", reason: "missing" };
2640
+ if (entry.removingAt && !isInside(entry.repoRoot, real)) {
2641
+ return { verdict: "finish-remove", reason: "interrupted-remove" };
2642
+ }
2643
+ return { verdict: "skip", reason: "broken" };
2644
+ }
2645
+ const dirty = await git(entry.path, ["status", "--porcelain", "--untracked-files=no"]);
2646
+ if (!dirty.ok)
2647
+ return { verdict: "skip", reason: "status-failed" };
2648
+ if (dirty.stdout)
2649
+ return { verdict: "held", reason: "dirty" };
2650
+ const unpushed = await git(entry.path, ["rev-list", "-1", "HEAD", "--not", "--remotes"]);
2651
+ if (!unpushed.ok)
2652
+ return { verdict: "skip", reason: "rev-list-failed" };
2653
+ if (unpushed.stdout)
2654
+ return { verdict: "held", reason: "unpushed" };
2655
+ if (await this.ownerActive(entry, active))
2656
+ return { verdict: "skip", reason: "owner-active" };
2657
+ const young = ageHours === null || ageHours < ttlHours;
2658
+ if (info.branch && young) {
2659
+ const upstream = await git(entry.path, [
2660
+ "rev-parse",
2661
+ "--abbrev-ref",
2662
+ `${info.branch}@{upstream}`
2663
+ ]);
2664
+ if (upstream.ok && !await this.isDefaultUpstream(entry.repoRoot, upstream.stdout)) {
2665
+ return { verdict: "keep", reason: "pushed-branch" };
2666
+ }
2667
+ }
2668
+ if (entry.candidateTaskIds.length === 0 && young)
2669
+ return { verdict: "keep", reason: "young" };
2670
+ return { verdict: "remove", reason: entry.candidateTaskIds.length ? "owners-ended" : "ttl" };
2671
+ }
2672
+ async decideAndAct(entry, info, active, isSweep) {
2673
+ const { mode, ttlHours } = this.opts.getConfig();
2674
+ const ageHours = await this.ageHours(entry);
2675
+ const { verdict, reason } = await this.decide(entry, info, active, ttlHours, ageHours);
2676
+ const decision = {
2677
+ path: entry.path,
2678
+ repoRoot: entry.repoRoot,
2679
+ action: verdict === "held" ? "skip" : verdict === "keep" ? "keep" : "skip",
2680
+ reason,
2681
+ taskIds: entry.candidateTaskIds,
2682
+ ageHours: ageHours === null ? null : Math.round(ageHours * 10) / 10
2683
+ };
2684
+ const dryRun = mode !== "on";
2685
+ if (verdict === "held" && isSweep && ageHours !== null && ageHours >= ttlHours) {
2686
+ if (await this.ownerActive(entry, active))
2687
+ return decision;
2688
+ const slimmed = await this.slim(entry.path, dryRun);
2689
+ if (slimmed.length > 0) {
2690
+ decision.action = dryRun ? "would-slim" : "slim";
2691
+ decision.reason = `held-${reason}`;
2692
+ this.log({ ...decision, nodeModules: slimmed });
2693
+ }
2694
+ return decision;
2695
+ }
2696
+ if (verdict === "remove" || verdict === "finish-remove") {
2697
+ decision.action = verdict === "remove" ? "remove" : "finish-remove";
2698
+ if (dryRun) {
2699
+ decision.action = verdict === "remove" ? "would-remove" : "would-finish-remove";
2700
+ this.log({ ...decision });
2701
+ return decision;
2702
+ }
2703
+ if (await this.inUse(await realpath(entry.path).catch(() => entry.path), active)) {
2704
+ decision.action = "skip";
2705
+ decision.reason = "in-use";
2706
+ return decision;
2707
+ }
2708
+ const error = await this.remove(entry, verdict === "finish-remove");
2709
+ if (error) {
2710
+ decision.action = "error";
2711
+ decision.reason = error;
2712
+ }
2713
+ this.log({ ...decision });
2714
+ return decision;
2715
+ }
2716
+ if (!isSweep)
2717
+ this.log({ ...decision });
2718
+ return decision;
2719
+ }
2720
+ async slim(path, dryRun) {
2721
+ const found = await Bun.$`find ${path} -name node_modules -type d -prune -print`.quiet().nothrow();
2722
+ const slimmed = [];
2723
+ for (const dir of found.stdout.toString().split(`
2724
+ `).filter(Boolean)) {
2725
+ if (!(await git(path, ["check-ignore", "-q", dir])).ok)
2726
+ continue;
2727
+ if (!dryRun)
2728
+ await rm(dir, { recursive: true, force: true });
2729
+ slimmed.push(dir);
2730
+ }
2731
+ return slimmed;
2732
+ }
2733
+ async remove(entry, finishInterrupted) {
2734
+ const ledger = await this.loadLedger();
2735
+ entry.removingAt = new Date(this.now()).toISOString();
2736
+ await this.saveLedger();
2737
+ if (finishInterrupted) {
2738
+ await rm(entry.path, { recursive: true, force: true }).catch(() => {
2739
+ return;
2740
+ });
2741
+ } else {
2742
+ const removed = await git(entry.repoRoot, ["worktree", "remove", "--force", entry.path]);
2743
+ if (!removed.ok)
2744
+ return `error:${removed.stderr.split(`
2745
+ `)[0] || "worktree remove failed"}`;
2746
+ }
2747
+ await git(entry.repoRoot, ["worktree", "prune"]);
2748
+ if (await exists(entry.path))
2749
+ return "error:path still present after remove";
2750
+ delete ledger.entries[entry.path];
2751
+ await this.saveLedger();
2752
+ return null;
2753
+ }
2754
+ }
2755
+
2756
+ // src/commands/runner.ts
2267
2757
  var PROGRESS_THROTTLE_MS = 3000;
2268
2758
  var ASSISTANT_TEXT_OUTPUT_CAP = 30000;
2269
2759
  var RUNNER_GC_MIN_INTERVAL_MS = 5 * 60 * 1000;
@@ -2801,7 +3291,11 @@ var RELOADABLE_ENV_KEYS = new Set([
2801
3291
  "PI_TOOL_DEFERRAL",
2802
3292
  "PI_CODEMODE",
2803
3293
  "PI_CODEMODE_MODELS",
2804
- CODEX_OAUTH_POOL_SLOTS_ENV
3294
+ CODEX_OAUTH_POOL_SLOTS_ENV,
3295
+ "WORKTREE_REAPER_MODE",
3296
+ "WORKTREE_TTL_HOURS",
3297
+ "WORKTREE_SWEEP_INTERVAL_MINUTES",
3298
+ "WORKTREE_REAPER_EXTRA_ROOTS"
2805
3299
  ]);
2806
3300
  var BLANK_ROW_IS_STRAY_KEYS = new Set([
2807
3301
  "MODEL_OVERRIDE",
@@ -3357,6 +3851,13 @@ async function resolveCodexOAuthCredentialInfo(apiUrl, apiKey, opts = {}) {
3357
3851
  return null;
3358
3852
  }
3359
3853
  }
3854
+ async function resolveSubscriptionFirst(harness, model, resolvePoolSlot) {
3855
+ const subscriptionModel = chatgptSubscriptionModel(harness, model);
3856
+ if (subscriptionModel === null)
3857
+ return { model, oauthInfo: null };
3858
+ const oauthInfo = await resolvePoolSlot(chatgptSubscriptionTrait(harness).kind !== "native");
3859
+ return oauthInfo ? { model: subscriptionModel, oauthInfo } : { model, oauthInfo: null };
3860
+ }
3360
3861
  var KEY_OUTCOME_REPORT_TIMEOUT_MS = 5000;
3361
3862
  async function reportKeyAuthFailure(apiUrl, apiKey, keyType, keySuffix, keyIndex, taskId, timeoutMs = KEY_OUTCOME_REPORT_TIMEOUT_MS) {
3362
3863
  try {
@@ -3649,6 +4150,12 @@ function setupShutdownHandlers(role, apiConfig, getRunnerState, onShutdown) {
3649
4150
  });
3650
4151
  return beginShutdown;
3651
4152
  }
4153
+ function activeTaskRefs(state) {
4154
+ return [...state.activeTasks.values()].map((t) => ({
4155
+ taskId: t.taskId,
4156
+ workingDir: t.workingDir
4157
+ }));
4158
+ }
3652
4159
  var LOG_BUFFER_SIZE = 50;
3653
4160
  var LOG_FLUSH_INTERVAL_MS = 5000;
3654
4161
  async function flushLogBuffer(buffer, opts) {
@@ -4686,7 +5193,7 @@ async function spawnProviderProcess(adapter, opts, logDir) {
4686
5193
  resolvedProfile: opts.resolvedProfile
4687
5194
  }));
4688
5195
  } catch (err) {
4689
- if ((err instanceof ModelWindowExhaustedError || err instanceof CredentialAllowlistError) && realTaskId) {
5196
+ if ((err instanceof ModelWindowExhaustedError || err instanceof CredentialAllowlistError || err instanceof KeySpendCapError) && realTaskId) {
4690
5197
  const reason = err.message;
4691
5198
  console.warn(`[${opts.role}] ${reason}`);
4692
5199
  const apiConfig = { apiUrl: opts.apiUrl, apiKey: opts.apiKey, agentId: opts.agentId };
@@ -4722,6 +5229,11 @@ async function spawnProviderProcess(adapter, opts, logDir) {
4722
5229
  console.log(`[${opts.role}] model resolution mismatch for task ${opts.taskId ?? "?"}: server=${opts.resolvedModel} (${opts.modelSource ?? "?"}) local=${taskModelSelection.model}; using server value`);
4723
5230
  }
4724
5231
  const taskModel = opts.resolvedModel || taskModelSelection.model || "";
5232
+ const reportTaskModel = taskSelectedModelForReport({
5233
+ resolvedModel: opts.resolvedModel,
5234
+ modelSource: opts.modelSource,
5235
+ localModel: taskModelSelection.model
5236
+ });
4725
5237
  const spawnModel = guardSpawnModel({
4726
5238
  taskModel,
4727
5239
  configModel,
@@ -4737,27 +5249,17 @@ async function spawnProviderProcess(adapter, opts, logDir) {
4737
5249
  }
4738
5250
  if (spawnModel.warning)
4739
5251
  console.warn(spawnModel.warning);
4740
- const model = spawnModel.model;
4741
- const sessionEffort = effectiveReasoningEffort(adapter.name, model, reasoningEffortOverride);
4742
- let oauthSelection;
4743
- let oauthIsPoolBacked = false;
4744
- if (adapter.name === "codex" && !deriveDefaultRoute("codex", freshEnv)) {
4745
- const oauthInfo = await resolveCodexOAuthCredentialInfo(opts.apiUrl, opts.apiKey);
4746
- oauthSelection = oauthInfo?.selection;
4747
- oauthIsPoolBacked = oauthInfo?.isPoolBacked ?? false;
4748
- if (oauthSelection && realTaskId) {
4749
- reportKeyUsage(opts.apiUrl, opts.apiKey, oauthSelection.keyType, oauthSelection, realTaskId).catch(() => {});
4750
- }
4751
- } else if (adapter.name === "pi" && isChatgptSubscriptionModel(model)) {
4752
- const oauthInfo = await resolveCodexOAuthCredentialInfo(opts.apiUrl, opts.apiKey, {
4753
- poolOnly: true
4754
- });
4755
- oauthSelection = oauthInfo?.selection;
4756
- oauthIsPoolBacked = oauthInfo?.isPoolBacked ?? false;
4757
- if (oauthSelection && realTaskId) {
4758
- reportKeyUsage(opts.apiUrl, opts.apiKey, oauthSelection.keyType, oauthSelection, realTaskId).catch(() => {});
4759
- }
5252
+ const subscription = deriveDefaultRoute(adapter.name, freshEnv) ? { model: spawnModel.model, oauthInfo: null } : await resolveSubscriptionFirst(adapter.name, spawnModel.model, (poolOnly) => resolveCodexOAuthCredentialInfo(opts.apiUrl, opts.apiKey, { poolOnly }));
5253
+ const model = subscription.model;
5254
+ if (model !== spawnModel.model) {
5255
+ console.log(`[${opts.role}] ${spawnModel.model} runs on the ChatGPT subscription as ${model}`);
5256
+ }
5257
+ const oauthSelection = subscription.oauthInfo?.selection;
5258
+ const oauthIsPoolBacked = subscription.oauthInfo?.isPoolBacked ?? false;
5259
+ if (oauthSelection && realTaskId) {
5260
+ reportKeyUsage(opts.apiUrl, opts.apiKey, oauthSelection.keyType, oauthSelection, realTaskId).catch(() => {});
4760
5261
  }
5262
+ const sessionEffort = effectiveReasoningEffort(adapter.name, model, reasoningEffortOverride);
4761
5263
  const primarySelection = oauthSelection ?? credentialSelections[0];
4762
5264
  const credentialInfo = primarySelection ? {
4763
5265
  keyType: primarySelection.keyType,
@@ -4831,7 +5333,7 @@ async function spawnProviderProcess(adapter, opts, logDir) {
4831
5333
  }));
4832
5334
  const initialModelReport = buildLatestModelReport({
4833
5335
  model,
4834
- taskModel,
5336
+ taskModel: reportTaskModel,
4835
5337
  configModel,
4836
5338
  taskId: realTaskId,
4837
5339
  harnessProvider: opts.harnessProvider,
@@ -5072,7 +5574,7 @@ async function spawnProviderProcess(adapter, opts, logDir) {
5072
5574
  {
5073
5575
  const latestModel = buildLatestModelReport({
5074
5576
  model: event.cost.model,
5075
- taskModel: opts.model,
5577
+ taskModel: reportTaskModel,
5076
5578
  configModel,
5077
5579
  taskId: realTaskId,
5078
5580
  harnessProvider: opts.harnessProvider,
@@ -5288,7 +5790,7 @@ async function spawnProviderProcess(adapter, opts, logDir) {
5288
5790
  if (result.cost?.model) {
5289
5791
  const finalModelReport = buildLatestModelReport({
5290
5792
  model: result.cost.model,
5291
- taskModel: opts.model,
5793
+ taskModel: reportTaskModel,
5292
5794
  configModel,
5293
5795
  taskId: realTaskId,
5294
5796
  harnessProvider: opts.harnessProvider,
@@ -5641,6 +6143,7 @@ ${bridgeDiagnostics.paneTail}` : undefined;
5641
6143
  if (triggerType === "task_assigned" || triggerType === "task_resumed") {
5642
6144
  state.tasksProcessed += 1;
5643
6145
  }
6146
+ state.worktreeReaper?.onTaskEnded(taskId, activeTaskRefs(state)).catch((err) => console.warn(`[${role}] Worktree reaper failed: ${err}`));
5644
6147
  }
5645
6148
  }
5646
6149
  }));
@@ -5691,7 +6194,7 @@ async function fetchTemplate(templateId, registryUrl, cacheDir) {
5691
6194
  const safeId = templateId.replace(/[^a-zA-Z0-9_-]/g, "_");
5692
6195
  const cachePath = `${cacheDir}/${safeId}.json`;
5693
6196
  try {
5694
- const info = await stat(cachePath);
6197
+ const info = await stat2(cachePath);
5695
6198
  if (Date.now() - info.mtimeMs < TEMPLATE_CACHE_TTL_MS) {
5696
6199
  const cached = await readFile(cachePath, "utf-8");
5697
6200
  return JSON.parse(cached);
@@ -5711,7 +6214,7 @@ async function fetchTemplate(templateId, registryUrl, cacheDir) {
5711
6214
  }
5712
6215
  const template = await resp.json();
5713
6216
  try {
5714
- await mkdir(cacheDir, { recursive: true });
6217
+ await mkdir2(cacheDir, { recursive: true });
5715
6218
  await writeFile(cachePath, JSON.stringify(template), "utf-8");
5716
6219
  } catch {
5717
6220
  console.warn(`[template] Could not cache template to ${cachePath}`);
@@ -5736,7 +6239,7 @@ async function runAgent(config, opts) {
5736
6239
  const sessionId = process.env.SESSION_ID || crypto.randomUUID().slice(0, 8);
5737
6240
  const baseLogDir = opts.logsDir || process.env.LOG_DIR || "/logs";
5738
6241
  const logDir = `${baseLogDir}/${sessionId}`;
5739
- await mkdir(logDir, { recursive: true });
6242
+ await mkdir2(logDir, { recursive: true });
5740
6243
  const prompt = opts.prompt || defaultPrompt;
5741
6244
  const agentId = process.env.AGENT_ID || "unknown";
5742
6245
  const apiUrl = getMcpBaseUrl();
@@ -5922,6 +6425,14 @@ ${additionalSystemPrompt}` : basePrompt;
5922
6425
  codexCreditsExhaustedCooldownMs: bootCooldownMs,
5923
6426
  modelWindowBlocks: new Map
5924
6427
  };
6428
+ const reaperHasWorkspace = existsSync("/workspace/personal");
6429
+ state.worktreeReaper = new WorktreeReaper({
6430
+ ledgerPath: "/workspace/personal/.swarm/worktree-ledger.json",
6431
+ scanRoots: ["/workspace/personal"],
6432
+ getConfig: () => resolveWorktreeReaperConfig(process.env, reaperHasWorkspace && adapter.traits.hasLocalEnvironment),
6433
+ statusOf: (taskId) => fetchTaskStatus(apiUrl, apiKey, taskId)
6434
+ });
6435
+ const reaperFailed = (err) => console.warn(`[${role}] Worktree reaper failed: ${err}`);
5925
6436
  const cancelledSignaled = new Set;
5926
6437
  const steeringDispatchState = isSteeringEnabled2() ? createSteeringDispatchState() : null;
5927
6438
  const credentialRefreshState = {
@@ -6525,7 +7036,9 @@ ${additionalSystemPrompt}` : basePrompt;
6525
7036
  await removeActiveSession(apiConfig, task.id);
6526
7037
  continue;
6527
7038
  }
7039
+ runningTask.workingDir = resumeCwd;
6528
7040
  state.activeTasks.set(task.id, runningTask);
7041
+ state.worktreeReaper?.observe(activeTaskRefs(state)).catch(reaperFailed);
6529
7042
  console.log(`[${role}] Resumed task ${task.id.slice(0, 8)} (${state.activeTasks.size}/${state.maxConcurrent} active)`);
6530
7043
  }
6531
7044
  console.log(`[${role}] All paused tasks resumed. Entering normal polling...`);
@@ -6535,6 +7048,9 @@ ${additionalSystemPrompt}` : basePrompt;
6535
7048
  } catch (error) {
6536
7049
  console.error(`[${role}] Error checking/resuming paused tasks: ${error}`);
6537
7050
  }
7051
+ state.worktreeReaper?.sweep(activeTaskRefs(state)).catch(reaperFailed);
7052
+ let lastWorktreeSweepAt = Date.now();
7053
+ let lastWorktreeObserveAt = 0;
6538
7054
  if (isLead) {
6539
7055
  console.log(`[${role}] Running startup heartbeat sweep...`);
6540
7056
  const swept = await triggerHeartbeatSweep(apiConfig);
@@ -6586,6 +7102,14 @@ ${additionalSystemPrompt}` : basePrompt;
6586
7102
  }
6587
7103
  refreshCredentialStatus(apiConfig, credentialRefreshState, state.harnessProvider, latestCredentialEnv ?? process.env).catch((err) => console.warn(`[${role}] cred_status post_task refresh failed (non-fatal): ${err}`));
6588
7104
  const now = Date.now();
7105
+ if (state.activeTasks.size > 0 && now - lastWorktreeObserveAt >= VCS_CHECK_INTERVAL) {
7106
+ lastWorktreeObserveAt = now;
7107
+ state.worktreeReaper?.observe(activeTaskRefs(state)).catch(reaperFailed);
7108
+ }
7109
+ if (now - lastWorktreeSweepAt >= resolveWorktreeReaperConfig().sweepIntervalMinutes * 60000) {
7110
+ lastWorktreeSweepAt = now;
7111
+ state.worktreeReaper?.sweep(activeTaskRefs(state)).catch(reaperFailed);
7112
+ }
6589
7113
  for (const [taskId, task] of state.activeTasks) {
6590
7114
  if (vcsDetectedTasks.has(taskId))
6591
7115
  continue;
@@ -6934,6 +7458,7 @@ ${additionalSystemPrompt}` : basePrompt;
6934
7458
  runningTask.cursorUpdates = trigger.cursorUpdates;
6935
7459
  }
6936
7460
  state.activeTasks.set(runningTask.taskId, runningTask);
7461
+ state.worktreeReaper?.observe(activeTaskRefs(state)).catch(reaperFailed);
6937
7462
  if (!trigger.taskId) {
6938
7463
  registerActiveSession(apiConfig, {
6939
7464
  taskId: runningTask.taskId,