@desplega.ai/agent-swarm 1.169.0 → 1.171.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 (349) hide show
  1. package/README.md +11 -2
  2. package/dist/{acp-adapter-m47zfx4a.js → acp-adapter-wnhq4ydy.js} +6 -6
  3. package/dist/{actions-ws7k3tvq.js → actions-45eyf0ns.js} +31 -29
  4. package/dist/{amp-adapter-nvv8k8j5.js → amp-adapter-f5dr6dm0.js} +6 -6
  5. package/dist/{anthropic-messages-13yn502s.js → anthropic-messages-etkbxhhy.js} +11 -11
  6. package/dist/{app-80w6qspx.js → app-qv86qhzz.js} +9 -9
  7. package/dist/{artifact-fey7dvj9.js → artifact-eczsknc3.js} +6 -3
  8. package/dist/{assistant-jtq439kw.js → assistant-10yaeebp.js} +34 -32
  9. package/dist/{azure-openai-responses-9st34pfz.js → azure-openai-responses-xap57x4b.js} +7 -7
  10. package/dist/{boot-reembed-feda8wn8.js → boot-reembed-p2wbqxm4.js} +8 -8
  11. package/dist/{boot-reembed-3nc0aaed.js → boot-reembed-wyb785et.js} +8 -8
  12. package/dist/{boot-scrub-sweep-grsa2er0.js → boot-scrub-sweep-daaqcs9t.js} +9 -9
  13. package/dist/{boot-seeds-gcfgq44f.js → boot-seeds-1pvzyx4h.js} +12 -12
  14. package/dist/{claude-adapter-pjv2q7t8.js → claude-adapter-v2py1c6g.js} +15 -15
  15. package/dist/{claude-managed-adapter-0wa8se82.js → claude-managed-adapter-kqqqhp2q.js} +2 -2
  16. package/dist/{claude-managed-setup-zxa9p9tx.js → claude-managed-setup-bnmjarjc.js} +11 -8
  17. package/dist/{claude-sdk-session-c9j6k9kx.js → claude-sdk-session-mk938tpt.js} +15 -15
  18. package/dist/cli-0p3enk35.js +188 -0
  19. package/dist/cli-1srmzpr3.js +16 -0
  20. package/dist/{cli-zzev32jw.js → cli-231av4y6.js} +6 -6
  21. package/dist/{cli-eqfbsxsn.js → cli-2aap68ns.js} +14 -11
  22. package/dist/{cli-mv2520nm.js → cli-2bw3w47j.js} +1 -1
  23. package/dist/{cli-km8559dm.js → cli-2k8gyaey.js} +18 -10
  24. package/dist/{cli-efnd2kce.js → cli-2rbt7at8.js} +6 -1
  25. package/dist/{cli-xvc3q9br.js → cli-451ks6aw.js} +1 -1
  26. package/dist/{cli-7vz49g7h.js → cli-48ve9gsj.js} +101 -4
  27. package/dist/{cli-zp38xvtm.js → cli-5rqrj7q0.js} +1 -1
  28. package/dist/{cli-km4x66j0.js → cli-5y67yrt6.js} +13 -13
  29. package/dist/{cli-3ry5gx4f.js → cli-6pxmb99j.js} +2 -2
  30. package/dist/cli-6zx22mv6.js +0 -0
  31. package/dist/{cli-zp67qg5x.js → cli-7a0sde2x.js} +72 -1
  32. package/dist/{cli-v1w7pbd8.js → cli-7jykv7ef.js} +1 -1
  33. package/dist/{cli-rfphkzh5.js → cli-7pz3b7x5.js} +24 -4
  34. package/dist/{cli-mb75wpxf.js → cli-81r1wjyv.js} +1 -1
  35. package/dist/cli-8ntwbxmm.js +1351 -0
  36. package/dist/{cli-f14fvzag.js → cli-a1b9b32n.js} +6 -1
  37. package/dist/{cli-rg1c8ccw.js → cli-amvnn9wz.js} +497 -73
  38. package/dist/{cli-fyeft04q.js → cli-apnwqe6h.js} +2 -2
  39. package/dist/{cli-m23r88re.js → cli-bkdbswyn.js} +3 -3
  40. package/dist/{cli-qg2zhjfc.js → cli-c9cnsnms.js} +8 -8
  41. package/dist/cli-cd0hv9nh.js +32 -0
  42. package/dist/{cli-wt7ccy4r.js → cli-d161g69q.js} +9 -1
  43. package/dist/{cli-rbr91whd.js → cli-d78fccnb.js} +9 -5
  44. package/dist/cli-db3m6zdt.js +362 -0
  45. package/dist/{cli-hf5s9pgf.js → cli-e3pmyt39.js} +1 -1
  46. package/dist/{cli-91r17hb1.js → cli-ehf1dfay.js} +3 -3
  47. package/dist/{cli-61tbnjpf.js → cli-f3vy7ncj.js} +767 -541
  48. package/dist/{cli-sajr098b.js → cli-f651ypy4.js} +3 -3
  49. package/dist/{cli-9k7mqz00.js → cli-ge593j7e.js} +30 -3
  50. package/dist/cli-h8w3fg83.js +17 -0
  51. package/dist/{cli-dv76vq5d.js → cli-hadkza7w.js} +685 -209
  52. package/dist/{cli-jkfxpg1b.js → cli-hrbedqp0.js} +2 -2
  53. package/dist/{cli-xvdgasgy.js → cli-hsem16hb.js} +114 -9
  54. package/dist/{cli-kp3vfknv.js → cli-j8xzym9k.js} +2 -2
  55. package/dist/{cli-swrz3mj8.js → cli-jn9wk8z8.js} +1 -1
  56. package/dist/{cli-a8vps458.js → cli-jr749y58.js} +17274 -17242
  57. package/dist/{cli-b7y8113e.js → cli-k2v5x13t.js} +1 -1
  58. package/dist/{cli-bqrs5ycj.js → cli-m4csbs67.js} +2 -2
  59. package/dist/{cli-yvxfaem2.js → cli-ndvfgmk8.js} +9 -5
  60. package/dist/{cli-r7eeddkq.js → cli-ph3145b7.js} +3 -3
  61. package/dist/cli-ppy4nnnh.js +168 -0
  62. package/dist/{cli-e5qk3m2a.js → cli-pw9x22wp.js} +19 -19
  63. package/dist/{cli-s0k2j7q9.js → cli-pwnxv8pw.js} +10 -10
  64. package/dist/{cli-jv36y8wz.js → cli-rrbctenq.js} +1 -1
  65. package/dist/{cli-vejds37t.js → cli-tb8p51kg.js} +3 -3
  66. package/dist/cli-tqzk05ty.js +832 -0
  67. package/dist/{cli-rh44xx46.js → cli-vtqrsgnm.js} +15 -15
  68. package/dist/{cli-7mhy3ths.js → cli-x61srfpp.js} +5 -5
  69. package/dist/{cli-n4z21pt8.js → cli-xy6sgy6p.js} +1 -1
  70. package/dist/{cli-w6xa5nf5.js → cli-y1j1ggbf.js} +8 -8
  71. package/dist/{cli-jvmtxqtc.js → cli-ywh2a87k.js} +7 -2
  72. package/dist/{cli-3qhyh31j.js → cli-ywm1azg9.js} +6 -0
  73. package/dist/{cli-8xjst8q2.js → cli-z9cvwx5m.js} +11 -11
  74. package/dist/{cli-ysnkvdx6.js → cli-zh93km01.js} +313 -91
  75. package/dist/{cli-z48ggfyq.js → cli-zxm9p3x4.js} +2 -2
  76. package/dist/cli.js +42 -24
  77. package/dist/{codex-adapter-0kpg09ca.js → codex-adapter-cg8vntj1.js} +13 -13
  78. package/dist/{codex-hook-295jpbfa.js → codex-hook-7ba15hjd.js} +5 -3
  79. package/dist/{codex-login-g1cyt5zm.js → codex-login-841kv5fk.js} +7 -5
  80. package/dist/{codex-session-runner-8n672hxh.js → codex-session-runner-jxs6n1qx.js} +13 -13
  81. package/dist/{commands-mhmg5n0x.js → commands-8zhezbzr.js} +10 -10
  82. package/dist/controller-hq5ggpcp.js +193 -0
  83. package/dist/controllers-connect-q0brsq11.js +265 -0
  84. package/dist/{cursor-adapter-wn8n5zzk.js → cursor-adapter-t4pr1m3c.js} +5 -5
  85. package/dist/db-d80sy99v.js +71 -0
  86. package/dist/{db-wa6s1mwv.js → db-ggc4b127.js} +8 -8
  87. package/dist/{devin-adapter-bffjj5n4.js → devin-adapter-xgtj680j.js} +2 -2
  88. package/dist/{dispatcher-nhs2pkr8.js → dispatcher-eascgc1z.js} +30 -28
  89. package/dist/docker-f503k9p0.js +201 -0
  90. package/dist/{dsh-adapter-5423p70m.js → dsh-adapter-2h8m4cab.js} +5 -5
  91. package/dist/e2b-66xra4az.js +202 -0
  92. package/dist/{e2b-nd50eccg.js → e2b-xwhyj8cw.js} +43 -527
  93. package/dist/{event-bus-vnfthafg.js → event-bus-vjtv82gm.js} +2 -2
  94. package/dist/{grok-adapter-28pkdt80.js → grok-adapter-8ram8zse.js} +7 -7
  95. package/dist/{handlers-5rtf9nng.js → handlers-hypxbg7e.js} +33 -31
  96. package/dist/heartbeat-ge72pt7q.js +124 -0
  97. package/dist/{hook-krjfkpzy.js → hook-grgtyrad.js} +20 -17
  98. package/dist/{hook-qkm73zk6.js → hook-xzwg1zwp.js} +13 -13
  99. package/dist/{http-a397xcn4.js → http-2nf2axqq.js} +1958 -205
  100. package/dist/{index-vvsq7v45.js → index-0h5dd9xg.js} +30 -28
  101. package/dist/{index-ac0v8v9d.js → index-27aez391.js} +8 -8
  102. package/dist/{index-rtxg15ah.js → index-57svck0z.js} +39 -29
  103. package/dist/{index-ytdhtdry.js → index-6zehd2p5.js} +31 -22
  104. package/dist/{index-kqre45fr.js → index-9egx96ey.js} +30 -28
  105. package/dist/{keepalive-psfh8ysx.js → keepalive-5pjbsz8f.js} +10 -10
  106. package/dist/{lead-m6rppjn7.js → lead-g19prqhd.js} +48 -46
  107. package/dist/{maintenance-41f837ke.js → maintenance-1brc7q4c.js} +8 -8
  108. package/dist/{node-8zkdq42h.js → node-c9we95xf.js} +9 -9
  109. package/dist/{oauth-refresh-sweep-6hr55hm8.js → oauth-refresh-sweep-rhe857nd.js} +9 -9
  110. package/dist/{onboard-ktrtd7cz.js → onboard-6bcg69eg.js} +25 -15
  111. package/dist/{openai-codex-responses-jzxkta9b.js → openai-codex-responses-pgvtddvv.js} +3 -3
  112. package/dist/{openai-responses-m3g43rrt.js → openai-responses-9dyzwzkr.js} +9 -9
  113. package/dist/{opencode-adapter-yjyqynzf.js → opencode-adapter-f1zby94p.js} +3 -3
  114. package/dist/{otel-impl-dq4f2k3m.js → otel-impl-y237rck3.js} +5 -5
  115. package/dist/{pi-mono-adapter-e5v9w0hv.js → pi-mono-adapter-fx6k5wwh.js} +38 -27
  116. package/dist/{pricing-refresh-kmk7j1ra.js → pricing-refresh-se1qg8wn.js} +10 -10
  117. package/dist/{rbac-roles-9w1dkkxd.js → rbac-roles-b6ca1n23.js} +11 -11
  118. package/dist/{rbac-roles-9ykx9tc5.js → rbac-roles-c58kydph.js} +10 -10
  119. package/dist/{render-v2-ycqm53np.js → render-v2-gqz7z5xt.js} +9 -9
  120. package/dist/{resume-cq2pkp8q.js → resume-yb3y3vda.js} +16 -16
  121. package/dist/{setup-0dcmdvbn.js → setup-1rbr9x3c.js} +7 -5
  122. package/dist/static-t1gr2cr7.js +30 -0
  123. package/dist/{virtual-modules-1x9k4jcs.js → virtual-modules-rdjmcg7q.js} +3 -3
  124. package/dist/{work-objects-x01x2fh8.js → work-objects-nzcp8srm.js} +35 -33
  125. package/dist/{worker-py1ssb1h.js → worker-wnz1h3g0.js} +48 -46
  126. package/dist/{x-ma4gnfgy.js → x-qfmygqqv.js} +2 -2
  127. package/openapi.json +3382 -167
  128. package/package.json +3 -3
  129. package/src/be/db/agents.ts +6 -0
  130. package/src/be/db/instance-signals.ts +30 -0
  131. package/src/be/db/tasks/read.ts +2 -0
  132. package/src/be/db/tasks/write.ts +39 -5
  133. package/src/be/db/workflow-runs.ts +22 -0
  134. package/src/be/db.ts +96 -40
  135. package/src/be/fleet-benchmark-stats.ts +39 -0
  136. package/src/be/migrations/205_favorites_per_dashboard_user.sql +29 -0
  137. package/src/be/migrations/206_runtime_pools.sql +62 -0
  138. package/src/be/migrations/207_runtime_session_tokens.sql +31 -0
  139. package/src/be/migrations/208_task_runtime_dispatch.sql +4 -0
  140. package/src/be/model-tier-resolution.ts +9 -2
  141. package/src/be/multi-runtime.ts +102 -13
  142. package/src/be/org-profile.ts +35 -0
  143. package/src/be/rbac-audit.ts +4 -0
  144. package/src/be/runtime-pools/controllers.ts +150 -0
  145. package/src/be/runtime-pools/db.ts +526 -0
  146. package/src/be/runtime-pools/demand.ts +65 -0
  147. package/src/be/runtime-pools/e2b-images.ts +109 -0
  148. package/src/be/runtime-pools/errors.ts +8 -0
  149. package/src/be/runtime-pools/lifecycle.ts +44 -0
  150. package/src/be/runtime-pools/reachability.ts +30 -0
  151. package/src/be/runtime-pools/recovery.ts +248 -0
  152. package/src/be/runtime-pools/remote-controller.ts +144 -0
  153. package/src/be/runtime-pools/routing.ts +304 -0
  154. package/src/be/runtime-pools/seed.ts +110 -0
  155. package/src/be/runtime-pools/supervisor.ts +981 -0
  156. package/src/be/runtime-pools/tokens.ts +57 -0
  157. package/src/be/scripts/typecheck.ts +48 -3
  158. package/src/be/secret-registry.ts +17 -1
  159. package/src/be/skill-usage.ts +467 -0
  160. package/src/be/swarm-config-guard.ts +59 -2
  161. package/src/be/telemetry-enable.ts +66 -0
  162. package/src/be/telemetry-ingest-anchor.ts +77 -0
  163. package/src/be/users.ts +173 -23
  164. package/src/be/worker-nudge-listener.ts +28 -0
  165. package/src/be/worker-nudges.ts +22 -0
  166. package/src/cli.tsx +22 -3
  167. package/src/commands/controller.ts +180 -0
  168. package/src/commands/onboard/non-interactive.ts +36 -12
  169. package/src/commands/onboard/types.ts +1 -1
  170. package/src/commands/onboard.tsx +3 -0
  171. package/src/commands/push-delivery.ts +230 -0
  172. package/src/commands/runner.ts +560 -276
  173. package/src/e2b/dispatch.ts +15 -1
  174. package/src/extensions/contract-types.generated.ts +1 -1
  175. package/src/fleet-benchmark.ts +157 -0
  176. package/src/heartbeat/heartbeat.ts +53 -135
  177. package/src/hooks/hook.ts +3 -2
  178. package/src/http/agents.ts +21 -0
  179. package/src/http/all-routes.ts +6 -0
  180. package/src/http/apps.ts +4 -2
  181. package/src/http/auth.ts +4 -7
  182. package/src/http/config.ts +58 -21
  183. package/src/http/controllers-connect.ts +206 -0
  184. package/src/http/core.ts +108 -14
  185. package/src/http/favorite-owner.ts +31 -1
  186. package/src/http/fleet-benchmark.ts +206 -0
  187. package/src/http/index.ts +38 -6
  188. package/src/http/mcp.ts +3 -8
  189. package/src/http/poll.ts +31 -2
  190. package/src/http/realtime.ts +1 -1
  191. package/src/http/request-principal.ts +2 -0
  192. package/src/http/runtime-pools.ts +527 -0
  193. package/src/http/session-data.ts +2 -0
  194. package/src/http/sessions.ts +100 -23
  195. package/src/http/skills.ts +173 -0
  196. package/src/http/status.ts +25 -1
  197. package/src/http/tasks.ts +14 -1
  198. package/src/http/telemetry-ui.ts +102 -0
  199. package/src/http/used-by.ts +140 -0
  200. package/src/http/utils.ts +7 -1
  201. package/src/http/workflows.ts +10 -2
  202. package/src/jira/app.ts +1 -2
  203. package/src/kv-reserved-namespaces.ts +1 -0
  204. package/src/linear/app.ts +1 -2
  205. package/src/providers/acp-target-catalog.ts +75 -1
  206. package/src/providers/acp-targets.ts +114 -0
  207. package/src/providers/amp-adapter.ts +1 -1
  208. package/src/providers/claude-adapter.ts +1 -1
  209. package/src/providers/codex-adapter.ts +5 -1
  210. package/src/providers/opencode-adapter.ts +2 -1
  211. package/src/providers/pi-mono-adapter.ts +41 -26
  212. package/src/providers/pricing-sources.md +2 -0
  213. package/src/providers/skill-invoke.ts +39 -3
  214. package/src/rbac/legacy-policy.ts +8 -0
  215. package/src/rbac/permissions.ts +16 -0
  216. package/src/rbac/types.ts +2 -0
  217. package/src/realtime/auth.ts +13 -0
  218. package/src/realtime/channels.ts +24 -0
  219. package/src/realtime/transport.ts +94 -15
  220. package/src/realtime/worker-client.ts +176 -0
  221. package/src/runtime-providers/controller-protocol.ts +97 -0
  222. package/src/runtime-providers/controller.ts +86 -0
  223. package/src/runtime-providers/docker.ts +235 -0
  224. package/src/runtime-providers/e2b.ts +217 -0
  225. package/src/runtime-providers/index.ts +37 -0
  226. package/src/runtime-providers/static.ts +26 -0
  227. package/src/runtime-providers/types.ts +92 -0
  228. package/src/runtime-providers/worker-api-url.ts +11 -0
  229. package/src/scripts-runtime/sdk-allowlist.ts +6 -0
  230. package/src/scripts-runtime/types/stdlib.d.ts +15 -0
  231. package/src/scripts-runtime/types/swarm-extension.d.ts +1 -0
  232. package/src/scripts-runtime/types/swarm-sdk.d.ts +15 -0
  233. package/src/server.ts +12 -0
  234. package/src/slack/router.ts +7 -5
  235. package/src/tasks/worker-follow-up.ts +80 -52
  236. package/src/telemetry-context.ts +6 -0
  237. package/src/telemetry-contract/EVENTS.md +14 -1
  238. package/src/telemetry-contract/SOURCE.json +4 -4
  239. package/src/telemetry-contract/catalog.json +155 -0
  240. package/src/telemetry-contract/types.gen.ts +248 -4
  241. package/src/telemetry-ui-events.ts +130 -0
  242. package/src/telemetry.ts +43 -3
  243. package/src/tests/acp-adapter.test.ts +129 -0
  244. package/src/tests/claude-adapter.test.ts +6 -2
  245. package/src/tests/codex-adapter.test.ts +6 -2
  246. package/src/tests/config-internal-keys.test.ts +27 -0
  247. package/src/tests/config-session-auth.test.ts +19 -3
  248. package/src/tests/db-retention.test.ts +50 -10
  249. package/src/tests/docs-index-footprint.test.js +3 -3
  250. package/src/tests/e2b-dispatch.test.ts +28 -1
  251. package/src/tests/e2e-runtime-pools.test.ts +51 -0
  252. package/src/tests/entrypoint-acp-target-binary.test.ts +38 -1
  253. package/src/tests/favorites.test.ts +188 -0
  254. package/src/tests/fetch-resolved-env.test.ts +59 -1
  255. package/src/tests/fleet-benchmark.test.ts +453 -0
  256. package/src/tests/harness-model-support.test.ts +70 -2
  257. package/src/tests/heartbeat-orphan-resume.test.ts +24 -0
  258. package/src/tests/heartbeat-reboot-live.test.ts +31 -0
  259. package/src/tests/heartbeat-supersede-resume.test.ts +21 -0
  260. package/src/tests/hook-runtime-close.test.ts +64 -0
  261. package/src/tests/http-task-write-ownership.test.ts +8 -1
  262. package/src/tests/integration-disable-flags.test.ts +45 -0
  263. package/src/tests/migration-206-runtime-pools.test.ts +134 -0
  264. package/src/tests/migration-207-runtime-session-tokens.test.ts +45 -0
  265. package/src/tests/migration-208-task-runtime-dispatch.test.ts +30 -0
  266. package/src/tests/multi-runtime-registration.test.ts +219 -4
  267. package/src/tests/onboard-non-interactive.test.ts +104 -6
  268. package/src/tests/opencode-adapter.test.ts +6 -2
  269. package/src/tests/org-website.test.ts +115 -0
  270. package/src/tests/pi-mono-adapter.test.ts +74 -10
  271. package/src/tests/rbac-admission-e2e.test.ts +4 -4
  272. package/src/tests/rbac-engine.test.ts +8 -1
  273. package/src/tests/realtime-room-auth.test.ts +49 -0
  274. package/src/tests/repo-allow-merge-gate.test.ts +8 -1
  275. package/src/tests/runner-exit-after-tasks.test.ts +163 -0
  276. package/src/tests/runner-finish-retry.test.ts +466 -0
  277. package/src/tests/runner-harness-telemetry-env.test.ts +105 -0
  278. package/src/tests/runner-push-delivery.test.ts +670 -0
  279. package/src/tests/runner-slot-reconcile.test.ts +89 -1
  280. package/src/tests/runtime-child-token-cleanup.test.ts +172 -0
  281. package/src/tests/runtime-controller-token.test.ts +254 -0
  282. package/src/tests/runtime-demand.test.ts +119 -0
  283. package/src/tests/runtime-e2b-pools.test.ts +847 -0
  284. package/src/tests/runtime-pool-reachability.test.ts +328 -0
  285. package/src/tests/runtime-pool-routing.test.ts +817 -0
  286. package/src/tests/runtime-pools-db.test.ts +275 -0
  287. package/src/tests/runtime-pools-http.test.ts +506 -0
  288. package/src/tests/runtime-pools-ownership-guards.test.ts +235 -0
  289. package/src/tests/runtime-pools-seed.test.ts +203 -0
  290. package/src/tests/runtime-pools-test-utils.ts +128 -0
  291. package/src/tests/runtime-provider-registration.test.ts +133 -0
  292. package/src/tests/runtime-providers-docker.test.ts +400 -0
  293. package/src/tests/runtime-providers-e2b-transport.test.ts +50 -0
  294. package/src/tests/runtime-providers-e2b.test.ts +335 -0
  295. package/src/tests/runtime-recovery.test.ts +745 -0
  296. package/src/tests/runtime-remote-controller.test.ts +846 -0
  297. package/src/tests/runtime-supervisor-failures.test.ts +387 -0
  298. package/src/tests/runtime-supervisor.test.ts +1039 -0
  299. package/src/tests/runtime-token-auth.test.ts +897 -0
  300. package/src/tests/script-connections.test.ts +7 -0
  301. package/src/tests/secret-scrubber.test.ts +17 -2
  302. package/src/tests/session-costs-codex-recompute.test.ts +49 -0
  303. package/src/tests/session-tokens.test.ts +13 -3
  304. package/src/tests/skill-invoke.test.ts +142 -0
  305. package/src/tests/skill-usage-cohorts.test.ts +232 -0
  306. package/src/tests/skill-usage.test.ts +348 -0
  307. package/src/tests/slack-attachments-block.test.ts +23 -0
  308. package/src/tests/slack-render-v2.test.ts +6 -0
  309. package/src/tests/status-instance.test.ts +71 -0
  310. package/src/tests/task-supersede-resume.test.ts +87 -4
  311. package/src/tests/telemetry-enable.test.ts +113 -0
  312. package/src/tests/telemetry-ui-route.test.ts +195 -0
  313. package/src/tests/tool-annotations.test.ts +1 -1
  314. package/src/tests/used-by-route.test.ts +237 -0
  315. package/src/tests/worker-nudges.test.ts +653 -0
  316. package/src/tests/worker-realtime-client.test.ts +188 -0
  317. package/src/tests/workflow-sub-workflow.test.ts +22 -0
  318. package/src/tools/app-upsert.ts +1 -1
  319. package/src/tools/runtime-controller-list.ts +28 -0
  320. package/src/tools/runtime-pool-bind-agent.ts +29 -0
  321. package/src/tools/runtime-pool-common.ts +37 -0
  322. package/src/tools/runtime-pool-create-agent.ts +29 -0
  323. package/src/tools/runtime-pool-delete.ts +27 -0
  324. package/src/tools/runtime-pool-list.ts +27 -0
  325. package/src/tools/runtime-pool-upsert.ts +31 -0
  326. package/src/tools/script-common.ts +1 -1
  327. package/src/tools/send-task.ts +3 -2
  328. package/src/tools/tool-config.ts +6 -0
  329. package/src/types.ts +137 -2
  330. package/src/utils/config-secrets.ts +1 -0
  331. package/src/utils/lead-monitor-channels.ts +3 -0
  332. package/src/utils/org-website.ts +104 -0
  333. package/src/utils/request-auth-context.ts +10 -2
  334. package/src/utils/runtime-pools-flag.ts +11 -0
  335. package/src/utils/secret-scrubber.ts +9 -0
  336. package/src/utils/session-token-connections.ts +20 -0
  337. package/templates/skills/apps/content.md +1 -1
  338. package/templates/skills/code-quality/content.md +9 -1
  339. package/templates/skills/db-query-guidance/content.md +9 -0
  340. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  341. package/templates/skills/swarm-scripts/content.md +1 -1
  342. package/templates/skills/work-on-task/SKILL.md +1 -1
  343. package/templates/skills/work-on-task/content.md +1 -1
  344. package/dist/{cli-qd97v6z2.js → cli-1qtgd1h1.js} +3 -3
  345. package/dist/{cli-cmxkbzzs.js → cli-j0w59p15.js} +6 -6
  346. package/dist/{google-generative-ai-b8zxrpax.js → google-generative-ai-pvhm0dq1.js} +1 -1
  347. package/dist/{google-vertex-nrdd697t.js → google-vertex-tek9sqe2.js} +4 -4
  348. package/dist/{mistral-conversations-059y51zt.js → mistral-conversations-rjxa9s1j.js} +3 -3
  349. package/dist/{openai-completions-663yncfq.js → openai-completions-44gb0zsk.js} +12 -12
@@ -0,0 +1,1351 @@
1
+ import {
2
+ BuiltinController,
3
+ CONTROLLER_COMMAND_TIMEOUT_MS,
4
+ ControllerOfflineError,
5
+ ControllerStatusResultSchema,
6
+ RuntimeHandleSchema
7
+ } from "./cli-ppy4nnnh.js";
8
+ import {
9
+ canClaim,
10
+ createWorkerTaskFollowUp,
11
+ getRuntimeInstanceById,
12
+ insertProvisioningRuntime,
13
+ listRuntimeInstancesForAgent,
14
+ listRuntimeInstancesForPool,
15
+ markRuntimeTerminated,
16
+ runtimeStaleThresholdMinutes
17
+ } from "./cli-f3vy7ncj.js";
18
+ import {
19
+ isMultiRuntimeEnabled
20
+ } from "./cli-re8z5p8p.js";
21
+ import {
22
+ checkE2bControllerConfig,
23
+ getPoolForAgent,
24
+ getRuntimeController,
25
+ getRuntimeControllerTarget,
26
+ getRuntimePool,
27
+ init_db,
28
+ init_users,
29
+ listAgentsForPool,
30
+ listRuntimePools,
31
+ mintRuntimeToken,
32
+ resolvePoolDelivery
33
+ } from "./cli-tqzk05ty.js";
34
+ import {
35
+ canProvisionKind,
36
+ createRuntimeProvider,
37
+ init_runtime_providers
38
+ } from "./cli-cd0hv9nh.js";
39
+ import {
40
+ import_websocket
41
+ } from "./cli-76yrvwsa.js";
42
+ import {
43
+ checkDependencies,
44
+ failTask,
45
+ getDbClient,
46
+ getResolvedConfig,
47
+ getSwarmConfigs,
48
+ getTaskById,
49
+ init_db1 as init_db2,
50
+ init_read,
51
+ init_runtime_pools_flag,
52
+ init_swarm_config_guard,
53
+ isRuntimePoolsEnabled,
54
+ rowToAgentTask,
55
+ upsertSwarmConfig,
56
+ validateConfigValue,
57
+ validateControllerGraceSec
58
+ } from "./cli-amvnn9wz.js";
59
+ import {
60
+ TERMINAL_TASK_STATUSES,
61
+ init_types,
62
+ isTerminalTaskStatus
63
+ } from "./cli-hsem16hb.js";
64
+ import {
65
+ init_zod
66
+ } from "./cli-sd0mxa3c.js";
67
+ import {
68
+ exports_external
69
+ } from "./cli-w5e1d1vv.js";
70
+ import {
71
+ init_event_bus,
72
+ workflowEventBus
73
+ } from "./cli-81r1wjyv.js";
74
+ import {
75
+ init_bus,
76
+ realtimeBus
77
+ } from "./cli-zf8jjwex.js";
78
+ import {
79
+ init_worker_api_url,
80
+ resolveWorkerApiUrl
81
+ } from "./cli-h8w3fg83.js";
82
+ import {
83
+ buildImageTemplate,
84
+ init_dispatch
85
+ } from "./cli-db3m6zdt.js";
86
+ import {
87
+ RUNTIME_LABELS,
88
+ init_types as init_types2
89
+ } from "./cli-1srmzpr3.js";
90
+ import {
91
+ init_secret_scrubber,
92
+ registerVolatileSecret,
93
+ scrubSecrets
94
+ } from "./cli-d161g69q.js";
95
+ import {
96
+ __require
97
+ } from "./cli-bc05qbss.js";
98
+
99
+ // src/be/runtime-pools/remote-controller.ts
100
+ init_zod();
101
+ init_secret_scrubber();
102
+ init_swarm_config_guard();
103
+ var sessions = new Map;
104
+ function remoteControllerSession(id) {
105
+ return sessions.get(id);
106
+ }
107
+ function installRemoteController(session) {
108
+ const previous = sessions.get(session.id);
109
+ sessions.set(session.id, session);
110
+ previous?.disconnect("Controller connection replaced");
111
+ }
112
+ function removeRemoteController(session) {
113
+ if (sessions.get(session.id) !== session)
114
+ return false;
115
+ sessions.delete(session.id);
116
+ return true;
117
+ }
118
+
119
+ class RemoteController {
120
+ id;
121
+ ws;
122
+ traits;
123
+ workerApiUrl;
124
+ timeouts;
125
+ pending = new Map;
126
+ closed = false;
127
+ renew;
128
+ pause;
129
+ resume;
130
+ constructor(id, ws, traits, workerApiUrl, timeouts = {}) {
131
+ this.id = id;
132
+ this.ws = ws;
133
+ this.traits = traits;
134
+ this.workerApiUrl = workerApiUrl;
135
+ this.timeouts = timeouts;
136
+ if (traits.maxTtlSec)
137
+ this.renew = async (handle, ttlSec) => exports_external.object({ endAt: exports_external.string() }).parse(await this.call({ op: "renew", payload: { handle, ttlSec } }));
138
+ if (traits.supportsPause) {
139
+ this.pause = async (handle) => {
140
+ await this.call({ op: "pause", payload: { handle } });
141
+ };
142
+ this.resume = async (handle) => {
143
+ await this.call({ op: "resume", payload: { handle } });
144
+ };
145
+ }
146
+ }
147
+ disconnect(reason) {
148
+ if (this.closed)
149
+ return;
150
+ this.closed = true;
151
+ for (const pending of this.pending.values()) {
152
+ clearTimeout(pending.timer);
153
+ pending.reject(new ControllerOfflineError(this.id));
154
+ }
155
+ this.pending.clear();
156
+ this.ws.close(1001, reason);
157
+ setTimeout(() => this.ws.terminate(), 500).unref();
158
+ }
159
+ result(message) {
160
+ const pending = this.pending.get(message.id);
161
+ if (!pending)
162
+ return;
163
+ this.pending.delete(message.id);
164
+ clearTimeout(pending.timer);
165
+ if (message.ok)
166
+ pending.resolve(message.result);
167
+ else
168
+ pending.reject(new Error(scrubSecrets(message.error ?? "Controller command failed")));
169
+ }
170
+ async call(command) {
171
+ if (this.closed || this.ws.readyState !== import_websocket.default.OPEN)
172
+ throw new ControllerOfflineError(this.id);
173
+ const id = crypto.randomUUID();
174
+ const configured = process.env.RUNTIME_PROVISION_TIMEOUT_SEC;
175
+ const timeoutMs = command.op === "provision" ? this.timeouts.provisionTimeoutMs ?? (configured !== undefined && validateConfigValue("RUNTIME_PROVISION_TIMEOUT_SEC", configured) === null ? Number(configured) * 1000 : 300000) : this.timeouts.commandTimeoutMs ?? CONTROLLER_COMMAND_TIMEOUT_MS;
176
+ return await new Promise((resolve, reject) => {
177
+ const timer = setTimeout(() => {
178
+ this.pending.delete(id);
179
+ reject(new ControllerOfflineError(this.id, `Controller command ${command.op} timed out`));
180
+ }, timeoutMs);
181
+ timer.unref();
182
+ this.pending.set(id, { resolve, reject, timer });
183
+ this.ws.send(JSON.stringify({ ...command, type: "cmd", id }), (error) => {
184
+ if (error)
185
+ this.disconnect("Controller connection failed");
186
+ });
187
+ });
188
+ }
189
+ async provision(req) {
190
+ const handle = RuntimeHandleSchema.parse(await this.call({ op: "provision", payload: req }));
191
+ return { ...handle, controllerId: this.id };
192
+ }
193
+ async terminate(handle, reason) {
194
+ await this.call({ op: "terminate", payload: { handle, reason } });
195
+ }
196
+ async status(handles) {
197
+ return ControllerStatusResultSchema.parse(await this.call({ op: "status", payload: { handles } }));
198
+ }
199
+ async list(ownerId) {
200
+ const handles = exports_external.array(RuntimeHandleSchema).parse(await this.call({ op: "list", payload: { ownerId } }));
201
+ return handles.map((handle) => ({ ...handle, controllerId: this.id }));
202
+ }
203
+ }
204
+
205
+ // src/be/runtime-pools/controllers.ts
206
+ init_runtime_providers();
207
+ init_types2();
208
+ init_worker_api_url();
209
+ init_runtime_pools_flag();
210
+ init_secret_scrubber();
211
+ init_db2();
212
+ init_swarm_config_guard();
213
+ init_db();
214
+ var ownerId = null;
215
+ function clearRuntimeOwnerIdCache() {
216
+ ownerId = null;
217
+ }
218
+ async function ensureRuntimeOwnerId() {
219
+ if (!ownerId) {
220
+ ownerId = readRuntimeOwnerId().catch((error) => {
221
+ ownerId = null;
222
+ throw error;
223
+ });
224
+ }
225
+ return await ownerId;
226
+ }
227
+ async function readRuntimeOwnerId() {
228
+ const existing = (await getSwarmConfigs({ scope: "global", key: "runtime_owner_id" }))[0];
229
+ if (existing)
230
+ return existing.value;
231
+ return await getDbClient().transaction(async () => {
232
+ const existing2 = (await getSwarmConfigs({ scope: "global", key: "runtime_owner_id" }))[0];
233
+ if (existing2)
234
+ return existing2.value;
235
+ const row = await upsertSwarmConfig({
236
+ scope: "global",
237
+ key: "runtime_owner_id",
238
+ value: crypto.randomUUID(),
239
+ description: "Owner of provisioned worker runtimes"
240
+ });
241
+ return row.value;
242
+ });
243
+ }
244
+ async function reconcileDisconnectedControllers(recoverRuntime, now = new Date) {
245
+ if (!isRuntimePoolsEnabled())
246
+ return;
247
+ const configured = process.env.RUNTIME_CONTROLLER_GRACE_SEC;
248
+ const graceMs = (validateControllerGraceSec(configured) === null ? Number(configured) : 120) * 1000;
249
+ const rows = await getDbClient().query("SELECT id, status, updated_at, last_seen_at FROM runtime_controllers WHERE placement = 'remote'");
250
+ for (const row of rows) {
251
+ if (row.status === "online" && remoteControllerSession(row.id))
252
+ continue;
253
+ if (row.status === "online") {
254
+ await getDbClient().run("UPDATE runtime_controllers SET status = 'offline', updated_at = ?, last_seen_at = ? WHERE id = ? AND status = 'online'", [now.toISOString(), now.toISOString(), row.id]);
255
+ continue;
256
+ }
257
+ if (now.getTime() - Date.parse(row.last_seen_at ?? row.updated_at) < graceMs)
258
+ continue;
259
+ const runtimes = await getDbClient().query("SELECT id FROM runtime_instances WHERE controller_id = ? AND status != 'offline'", [row.id]);
260
+ for (const runtime of runtimes) {
261
+ if (remoteControllerSession(row.id) && (await getRuntimeController(row.id))?.status === "online")
262
+ break;
263
+ await recoverRuntime(runtime.id, "Remote controller disconnect grace expired");
264
+ }
265
+ }
266
+ }
267
+ async function reconcileRemoteProvisions(controllerId, handles, ownerId2) {
268
+ await getDbClient().transaction(async (tx) => {
269
+ for (const handle of handles) {
270
+ const labels = handle.meta;
271
+ const runtimeId = labels?.[RUNTIME_LABELS.runtimeId];
272
+ if (labels?.[RUNTIME_LABELS.owner] !== ownerId2 || !runtimeId)
273
+ continue;
274
+ await tx.run(`UPDATE runtime_instances SET external_handle = ?, updated_at = ?
275
+ WHERE id = ? AND controller_id = ? AND agent_id = ? AND pool_id = ?
276
+ AND status != 'offline' AND external_handle IS NULL`, [
277
+ JSON.stringify(handle),
278
+ new Date().toISOString(),
279
+ runtimeId,
280
+ controllerId,
281
+ labels[RUNTIME_LABELS.agentId] ?? "",
282
+ labels[RUNTIME_LABELS.poolId] ?? ""
283
+ ]);
284
+ }
285
+ const missing = await tx.query("SELECT id FROM runtime_instances WHERE controller_id = ? AND status = 'provisioning' AND external_handle IS NULL", [controllerId]);
286
+ for (const runtime of missing)
287
+ await markRuntimeTerminated(runtime.id, "Controller list did not report the ambiguous provision");
288
+ });
289
+ }
290
+ async function getControllerCommands(controllerId) {
291
+ try {
292
+ const controller = await getRuntimeController(controllerId);
293
+ if (!controller)
294
+ throw new Error("Runtime controller does not exist");
295
+ if (controller.placement === "remote") {
296
+ const session = remoteControllerSession(controllerId);
297
+ if (!session || controller.status !== "online")
298
+ throw new ControllerOfflineError(controllerId);
299
+ return session;
300
+ }
301
+ const target = await getRuntimeControllerTarget(controller);
302
+ const config = controller.kind === "e2b" ? await checkE2bControllerConfig(controller, target) : (await createRuntimeProvider(controller.kind, target)).checkConfig(target);
303
+ if (!config.ready)
304
+ throw new Error(config.hint ?? `Missing configuration: ${config.missing.join(", ")}`);
305
+ const provider = await createRuntimeProvider(controller.kind, target);
306
+ return new BuiltinController(controllerId, provider, target, resolveWorkerApiUrl(target));
307
+ } catch (error) {
308
+ if (error instanceof ControllerOfflineError)
309
+ throw error;
310
+ throw new Error(scrubSecrets(String(error)));
311
+ }
312
+ }
313
+
314
+ // src/be/runtime-pools/recovery.ts
315
+ init_bus();
316
+ init_runtime_providers();
317
+ import { AsyncLocalStorage } from "node:async_hooks";
318
+ init_runtime_pools_flag();
319
+ init_secret_scrubber();
320
+ init_db2();
321
+ init_db();
322
+
323
+ // src/be/runtime-pools/lifecycle.ts
324
+ init_types();
325
+ init_db2();
326
+ async function rotatingRuntimes(poolId, expiresBy, now, maxContinuousSec) {
327
+ const configured = Number(process.env.RUNTIME_ROTATE_BEFORE_SEC);
328
+ const beforeSec = Number.isInteger(configured) && configured > 0 ? configured : 600;
329
+ const rotateAt = maxContinuousSec === undefined ? null : new Date(now.getTime() - Math.max(0, maxContinuousSec - beforeSec) * 1000).toISOString();
330
+ const rows = await getDbClient().query(`SELECT DISTINCT r.id AS runtimeId FROM runtime_instances r
331
+ LEFT JOIN session_tokens t ON r.id = t.runtimeId
332
+ WHERE r.pool_id = ? AND ((t.revokedAt IS NULL AND t.expiresAt <= ?)
333
+ OR (? IS NOT NULL AND r.created_at <= ?))`, [poolId, expiresBy, rotateAt, rotateAt]);
334
+ return new Set(rows.map((row) => row.runtimeId));
335
+ }
336
+ async function isRuntimeWanted(pool, runtime, rotating, remaining, now) {
337
+ if (!pool.enabled || runtime.draining || rotating)
338
+ return false;
339
+ if (pool.lifecycle === "idle" && pool.idleMinutes !== null && runtime.idleSince && now.getTime() - Date.parse(runtime.idleSince) >= pool.idleMinutes * 60000 && remaining > pool.minRuntimes)
340
+ return false;
341
+ const task = runtime.taskId ? await getTaskById(runtime.taskId) : null;
342
+ return !(pool.lifecycle === "per-task" && task && isTerminalTaskStatus(task.status));
343
+ }
344
+
345
+ // src/be/runtime-pools/supervisor.ts
346
+ init_runtime_providers();
347
+ init_types2();
348
+ init_worker_api_url();
349
+ init_types();
350
+ init_runtime_pools_flag();
351
+ init_secret_scrubber();
352
+ init_event_bus();
353
+ init_db2();
354
+ init_users();
355
+ init_db();
356
+
357
+ // src/be/runtime-pools/demand.ts
358
+ init_db2();
359
+ init_read();
360
+ async function pendingWorkForAgent(agentId) {
361
+ const rows = await getDbClient().query(`SELECT * FROM agent_tasks WHERE (agentId = ? AND status = 'pending')
362
+ OR (offeredTo = ? AND status = 'offered') ORDER BY priority DESC, createdAt, rowid`, [agentId, agentId]);
363
+ const tasks = [];
364
+ for (const row of rows) {
365
+ const task = rowToAgentTask(row);
366
+ if (task.status === "offered" || (await checkDependencies(task.id)).ready)
367
+ tasks.push(task);
368
+ }
369
+ const mentions = await getDbClient().get(`SELECT COUNT(DISTINCT m.channelId) AS count FROM channel_messages m
370
+ JOIN channels c ON c.id = m.channelId
371
+ LEFT JOIN channel_read_state s ON s.channelId = m.channelId AND s.agentId = ?
372
+ WHERE m.mentions LIKE ? AND s.processing_since IS NULL
373
+ AND (s.lastReadAt IS NULL OR m.createdAt > s.lastReadAt)`, [agentId, `%"${agentId}"%`]);
374
+ return { work: tasks.length + (mentions?.count ?? 0), topTask: tasks[0] ?? null };
375
+ }
376
+ function computeDesired(pool, agents) {
377
+ const desired = new Map;
378
+ let remaining = Math.max(0, (pool.maxRuntimes ?? Infinity) - agents.reduce((n, a) => n + a.current, 0));
379
+ for (const agent of agents) {
380
+ const uncovered = Math.max(0, agent.work - agent.freeSlots - agent.provisioning * pool.slotsPerRuntime);
381
+ const limit = Math.floor(agent.maxTasks / pool.slotsPerRuntime);
382
+ const count = Math.min(limit, Math.max(pool.minRuntimes, agent.current + Math.ceil(uncovered / pool.slotsPerRuntime)));
383
+ const added = Math.min(remaining, Math.max(0, count - agent.current));
384
+ desired.set(agent.agentId, Math.min(count, agent.current + added));
385
+ remaining -= added;
386
+ }
387
+ return desired;
388
+ }
389
+
390
+ // src/be/runtime-pools/e2b-images.ts
391
+ init_dispatch();
392
+ init_db2();
393
+ init_db();
394
+ var builds = new Map;
395
+ function stopE2bImageBuilds() {
396
+ for (const build of builds.values())
397
+ build.abort.abort();
398
+ builds.clear();
399
+ }
400
+ async function buildPoolImage(pool, name, signal) {
401
+ const controller = await getRuntimeController(pool.placements[0]);
402
+ if (!controller)
403
+ throw new Error("Runtime controller does not exist");
404
+ const target = await getRuntimeControllerTarget(controller);
405
+ signal.throwIfAborted();
406
+ await buildImageTemplate({
407
+ role: "worker",
408
+ name,
409
+ image: pool.image.slice("docker://".length),
410
+ cpuCount: pool.resources?.cpu ?? 4,
411
+ memoryMb: pool.resources?.memoryMb ?? 8192,
412
+ noCache: false,
413
+ e2bEnv: {
414
+ E2B_API_KEY: target.E2B_API_KEY ?? "",
415
+ E2B_API_URL: target.E2B_API_BASE ?? target.E2B_API_URL ?? "",
416
+ E2B_DOMAIN: target.E2B_DOMAIN ?? "",
417
+ E2B_SANDBOX_URL: target.E2B_SANDBOX_URL ?? ""
418
+ },
419
+ signal
420
+ });
421
+ signal.throwIfAborted();
422
+ const saved = await getDbClient().run(`UPDATE runtime_pools SET resolved_image = ?, updated_at = ? WHERE id = ? AND image = ?
423
+ AND COALESCE(json_extract(resources, '$.cpu'), 4) = ?
424
+ AND COALESCE(json_extract(resources, '$.memoryMb'), 8192) = ?`, [
425
+ name,
426
+ new Date().toISOString(),
427
+ pool.id,
428
+ pool.image,
429
+ pool.resources?.cpu ?? 4,
430
+ pool.resources?.memoryMb ?? 8192
431
+ ]);
432
+ if (!saved.changes)
433
+ throw new Error("E2B pool image or resources changed during template construction");
434
+ }
435
+ async function resolveE2bImage(poolId, tickSignal) {
436
+ const pool = await getRuntimePool(poolId);
437
+ tickSignal?.throwIfAborted();
438
+ if (!pool?.image)
439
+ throw new Error("E2B pool has no image");
440
+ if (!pool.image.startsWith("docker://"))
441
+ return pool.image;
442
+ const image = pool.image.slice("docker://".length);
443
+ if (!image)
444
+ throw new Error("docker:// requires an image reference");
445
+ const input = JSON.stringify([image, pool.resources?.cpu ?? 4, pool.resources?.memoryMb ?? 8192]);
446
+ const name = `swarm-${new Bun.CryptoHasher("sha256").update(input).digest("hex").slice(0, 12)}`;
447
+ const key = `${poolId}:${name}`;
448
+ for (const [oldKey, build2] of builds) {
449
+ if (oldKey.startsWith(`${poolId}:`) && oldKey !== key) {
450
+ build2.abort.abort();
451
+ builds.delete(oldKey);
452
+ }
453
+ }
454
+ if (pool.resolvedImage === name) {
455
+ builds.delete(key);
456
+ return pool.resolvedImage;
457
+ }
458
+ const previous = builds.get(key);
459
+ if (previous) {
460
+ if (previous.done) {
461
+ builds.delete(key);
462
+ throw previous.error;
463
+ }
464
+ return null;
465
+ }
466
+ const build = { abort: new AbortController, done: false };
467
+ builds.set(key, build);
468
+ const configured = Number(process.env.RUNTIME_E2B_BUILD_TIMEOUT_SEC);
469
+ const seconds = Number.isInteger(configured) && configured > 0 ? configured : 600;
470
+ const timeout = setTimeout(() => build.abort.abort(new Error(`E2B template build exceeded ${seconds}s`)), seconds * 1000);
471
+ timeout.unref?.();
472
+ const signal = build.abort.signal;
473
+ let onAbort;
474
+ const aborted = new Promise((_, reject) => {
475
+ onAbort = () => reject(signal.reason);
476
+ signal.addEventListener("abort", onAbort, { once: true });
477
+ });
478
+ Promise.race([buildPoolImage(pool, name, signal), aborted]).catch((error) => {
479
+ build.error = error;
480
+ }).finally(() => {
481
+ clearTimeout(timeout);
482
+ signal.removeEventListener("abort", onAbort);
483
+ build.done = true;
484
+ });
485
+ return null;
486
+ }
487
+
488
+ // src/be/runtime-pools/supervisor.ts
489
+ var timer = null;
490
+ var kickTimer = null;
491
+ var inFlight = null;
492
+ var tickAbort = null;
493
+ var warnedMultiRuntime = false;
494
+ var orphanFirstSeen = new Map;
495
+ var ORPHAN_GRACE_MS = 120000;
496
+ var TERMINAL_TASK_STATUS_PLACEHOLDERS = TERMINAL_TASK_STATUSES.map(() => "?").join(", ");
497
+ var TASKLESS_TRIGGER_SQL = "'unread_mentions', 'pool_tasks_available', 'channel_activity'";
498
+ function runtimeSupervisorStatus() {
499
+ if (!isRuntimePoolsEnabled())
500
+ return "disabled";
501
+ if (!isMultiRuntimeEnabled())
502
+ return "disabled: MULTI_RUNTIME_ENABLED=false";
503
+ return timer ? "running" : "stopped";
504
+ }
505
+ function reportSupervisorError(error) {
506
+ if (error instanceof ControllerOfflineError)
507
+ return;
508
+ console.error("[runtime-pools] Supervisor failed:", scrubSecrets(String(error)));
509
+ }
510
+ function runtimeNumber(key, fallback) {
511
+ const value = Number(process.env[key]);
512
+ return Number.isInteger(value) && value > 0 ? value : fallback;
513
+ }
514
+ function poolLeaseTtl(pool, controller) {
515
+ return Math.min(Math.max(pool.ttlSec ?? 900, runtimeNumber("RUNTIME_LEASE_RENEW_BEFORE_SEC", 300) + 60), controller.traits.maxTtlSec ?? Infinity, controller.traits.maxContinuousSec ?? Infinity);
516
+ }
517
+ async function recordProvisionFailure(runtime, reason, now, countedFailures) {
518
+ const error = scrubSecrets(reason);
519
+ const failedTask = await getDbClient().transaction(async (tx) => {
520
+ if (runtime.id) {
521
+ const retired = await tx.run("UPDATE runtime_instances SET provision_error = ? WHERE id = ? AND status = 'provisioning' AND provision_error IS NULL", [error, runtime.id]);
522
+ if (!retired.changes)
523
+ return null;
524
+ await markRuntimeTerminated(runtime.id, error);
525
+ }
526
+ if (countedFailures.has(runtime.agentId))
527
+ return null;
528
+ countedFailures.add(runtime.agentId);
529
+ const pool = await tx.get(`UPDATE runtime_pools SET consecutive_failures = consecutive_failures + 1,
530
+ last_error = ?, last_error_at = ?, updated_at = ?,
531
+ circuit_open_until = CASE WHEN consecutive_failures + 1 >= ? OR circuit_open_until IS NOT NULL
532
+ THEN ? ELSE circuit_open_until END WHERE id = ? RETURNING circuit_open_until`, [
533
+ error,
534
+ now.toISOString(),
535
+ now.toISOString(),
536
+ runtimeNumber("RUNTIME_CIRCUIT_THRESHOLD", 5),
537
+ new Date(now.getTime() + runtimeNumber("RUNTIME_CIRCUIT_OPEN_MIN", 10) * 60000).toISOString(),
538
+ runtime.poolId ?? null
539
+ ]);
540
+ await tx.run("UPDATE runtime_controllers SET last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ?", [error, now.toISOString(), now.toISOString(), runtime.controllerId ?? null]);
541
+ const state = await tx.get("UPDATE agents SET runtime_provision_attempts = runtime_provision_attempts + 1 WHERE id = ? RETURNING runtime_provision_attempts", [runtime.agentId]);
542
+ const attempts = state.runtime_provision_attempts;
543
+ const delay = [30, 90, 180][Math.min(attempts - 1, 2)];
544
+ await tx.run("UPDATE agents SET runtime_provision_retry_at = ? WHERE id = ?", [
545
+ new Date(now.getTime() + delay * 1000).toISOString(),
546
+ runtime.agentId
547
+ ]);
548
+ if (pool?.circuit_open_until)
549
+ await tx.run("UPDATE agents SET runtime_provision_attempts = 0, runtime_provision_retry_at = NULL WHERE runtime_pool_id = ?", [runtime.poolId ?? null]);
550
+ if (attempts < runtimeNumber("RUNTIME_PROVISION_MAX_ATTEMPTS", 3))
551
+ return null;
552
+ const pending = await tx.query("SELECT id FROM agent_tasks WHERE agentId = ? AND status = 'pending' ORDER BY createdAt, rowid", [runtime.agentId]);
553
+ for (const row of pending) {
554
+ if (!(await checkDependencies(row.id)).ready)
555
+ continue;
556
+ const failed = await failTask(row.id, `provisioning failed after ${attempts} attempts: ${error}`);
557
+ if (!failed)
558
+ continue;
559
+ await tx.run("UPDATE agents SET runtime_provision_attempts = 0, runtime_provision_retry_at = NULL WHERE id = ?", [runtime.agentId]);
560
+ return failed;
561
+ }
562
+ await tx.run("UPDATE agents SET runtime_provision_attempts = 0, runtime_provision_retry_at = NULL WHERE id = ?", [runtime.agentId]);
563
+ return null;
564
+ });
565
+ if (failedTask) {
566
+ try {
567
+ await createWorkerTaskFollowUp({
568
+ task: failedTask,
569
+ status: "failed",
570
+ failureReason: failedTask.failureReason ?? error
571
+ });
572
+ } catch (followUpError) {
573
+ reportSupervisorError(followUpError);
574
+ }
575
+ }
576
+ }
577
+ async function provisionRuntime(pool, agent, controller, ownerId2, now = new Date, options = {}) {
578
+ const { signal, onFailure, countedFailures = new Set } = options;
579
+ const runtimeId = crypto.randomUUID();
580
+ try {
581
+ const image = pool.kind === "e2b" ? await resolveE2bImage(pool.id, signal) : pool.resolvedImage ?? pool.image;
582
+ if (signal?.aborted || image === null)
583
+ return false;
584
+ const token = await getDbClient().transaction(async () => {
585
+ const credential = await mintRuntimeToken(agent.id, runtimeId);
586
+ await insertProvisioningRuntime({
587
+ id: runtimeId,
588
+ agentId: agent.id,
589
+ poolId: pool.id,
590
+ controllerId: pool.placements[0],
591
+ reportedSlots: pool.slotsPerRuntime
592
+ });
593
+ await getDbClient().run(`UPDATE runtime_instances SET provision_attempts =
594
+ (SELECT runtime_provision_attempts + 1 FROM agents WHERE id = ?),
595
+ provision_requested_at = ? WHERE id = ?`, [agent.id, now.toISOString(), runtimeId]);
596
+ signal?.throwIfAborted();
597
+ return credential.plaintext;
598
+ });
599
+ signal?.throwIfAborted();
600
+ registerVolatileSecret(token, `runtime:${runtimeId}`);
601
+ const templateId = (await getResolvedConfig(agent.id)).find((c) => c.key === "TEMPLATE_ID")?.value;
602
+ signal?.throwIfAborted();
603
+ const env = {
604
+ ...pool.env,
605
+ MCP_BASE_URL: resolveWorkerApiUrl({
606
+ WORKER_API_URL: controller.workerApiUrl,
607
+ RUNTIME_WORKER_API_URL: process.env.RUNTIME_WORKER_API_URL
608
+ }),
609
+ AGENT_ID: agent.id,
610
+ AGENT_ROLE: agent.isLead ? "lead" : "worker",
611
+ HARNESS_PROVIDER: agent.harnessProvider ?? "claude",
612
+ API_KEY: token,
613
+ AGENT_SWARM_API_KEY: token,
614
+ SWARM_RUNTIME_INSTANCE_ID: runtimeId,
615
+ MAX_CONCURRENT_TASKS: String(pool.slotsPerRuntime),
616
+ SWARM_DELIVERY_MODE: resolvePoolDelivery(pool)
617
+ };
618
+ delete env.SWARM_EXIT_AFTER_TASKS;
619
+ delete env.TEMPLATE_ID;
620
+ if (pool.lifecycle === "per-task")
621
+ env.SWARM_EXIT_AFTER_TASKS = "1";
622
+ if (templateId)
623
+ env.TEMPLATE_ID = templateId;
624
+ const ttlSec = pool.kind === "e2b" ? poolLeaseTtl(pool, controller) : undefined;
625
+ signal?.throwIfAborted();
626
+ const handle = await controller.provision({
627
+ runtimeId,
628
+ agentId: agent.id,
629
+ poolId: pool.id,
630
+ ownerId: ownerId2,
631
+ image,
632
+ ...ttlSec === undefined ? {} : { ttlSec },
633
+ env,
634
+ resources: pool.resources ?? undefined,
635
+ labels: {
636
+ [RUNTIME_LABELS.runtimeId]: runtimeId,
637
+ [RUNTIME_LABELS.poolId]: pool.id,
638
+ [RUNTIME_LABELS.agentId]: agent.id,
639
+ [RUNTIME_LABELS.owner]: ownerId2
640
+ }
641
+ });
642
+ if (signal?.aborted) {
643
+ await controller.terminate(handle, "Supervisor stopped during provision");
644
+ await markRuntimeTerminated(runtimeId, "Supervisor stopped during provision");
645
+ return false;
646
+ }
647
+ await getDbClient().run("UPDATE runtime_instances SET external_handle = ?, lease_expires_at = ?, created_at = COALESCE(?, created_at), updated_at = ? WHERE id = ?", [
648
+ JSON.stringify(handle),
649
+ ttlSec === undefined ? null : handle.meta?.leaseExpiresAt ?? new Date(now.getTime() + ttlSec * 1000).toISOString(),
650
+ pool.kind === "e2b" ? handle.createdAt ?? now.toISOString() : null,
651
+ new Date().toISOString(),
652
+ runtimeId
653
+ ]);
654
+ return true;
655
+ } catch (error) {
656
+ onFailure?.();
657
+ if (signal?.aborted) {
658
+ await markRuntimeTerminated(runtimeId, "Supervisor stopped during provision");
659
+ return false;
660
+ }
661
+ reportSupervisorError(error);
662
+ if (error instanceof ControllerOfflineError)
663
+ return false;
664
+ try {
665
+ const runtime = await getRuntimeInstanceById(runtimeId);
666
+ await recordProvisionFailure(runtime ?? {
667
+ id: null,
668
+ agentId: agent.id,
669
+ poolId: pool.id,
670
+ controllerId: pool.placements[0]
671
+ }, String(error), now, countedFailures);
672
+ } catch (cleanupError) {
673
+ reportSupervisorError(cleanupError);
674
+ }
675
+ return false;
676
+ }
677
+ }
678
+ function runtimeHandle(runtime) {
679
+ return runtime.externalHandle ? RuntimeHandleSchema.parse(runtime.externalHandle) : null;
680
+ }
681
+ async function terminateRuntime(runtime, controller, reason) {
682
+ const handle = runtimeHandle(runtime);
683
+ try {
684
+ if (handle)
685
+ await controller.terminate(handle, reason);
686
+ } catch (error) {
687
+ reportSupervisorError(error);
688
+ }
689
+ await markRuntimeTerminated(runtime.id, reason);
690
+ }
691
+ async function reapPoolRuntimes(pool, runtimes, controller, now, listedHandles, rotatingIds, countedFailures = new Set, controllers = new Map([
692
+ [pool.placements[0], controller]
693
+ ]), listings = new Map([
694
+ [pool.placements[0], listedHandles]
695
+ ])) {
696
+ const rotations = rotatingIds ?? await rotatingRuntimes(pool.id, new Date(now.getTime() + runtimeNumber("RUNTIME_TOKEN_ROTATE_BEFORE_MIN", 60) * 60000).toISOString(), now, controller.traits.maxContinuousSec);
697
+ const cutoff = now.getTime() - runtimeStaleThresholdMinutes() * 60000;
698
+ const sessionCutoff = new Date(now.getTime() - runtimeNumber("HEARTBEAT_STALE_CLEANUP_MIN", 30) * 60000).toISOString();
699
+ const remaining = new Map;
700
+ const statusesByController = new Map;
701
+ for (const [controllerId, controller2] of controllers) {
702
+ const handles = runtimes.filter((r) => (r.controllerId ?? pool.placements[0]) === controllerId && r.status !== "offline" && (runtimeHandle(r)?.kind === "e2b" || Date.parse(r.lastSeenAt) >= cutoff)).map(runtimeHandle).filter((h) => h !== null);
703
+ let statuses = {};
704
+ try {
705
+ if (handles.length)
706
+ statuses = await controller2.status(handles);
707
+ } catch (error) {
708
+ reportSupervisorError(error);
709
+ for (const handle of handles) {
710
+ try {
711
+ Object.assign(statuses, await controller2.status([handle]));
712
+ } catch (lookupError) {
713
+ reportSupervisorError(lookupError);
714
+ }
715
+ }
716
+ }
717
+ statusesByController.set(controllerId, statuses);
718
+ }
719
+ for (const runtime of runtimes)
720
+ if (runtime.status === "provisioning" || runtime.status === "active" && (Date.parse(runtime.lastSeenAt) >= cutoff || runtimeHandle(runtime)?.kind === "e2b" && statusesByController.get(runtime.controllerId ?? pool.placements[0])?.[runtimeHandle(runtime)?.externalId ?? ""] === "paused"))
721
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 0) + 1);
722
+ for (const candidate of runtimes) {
723
+ try {
724
+ await serializeRuntimeAction(candidate.id, async () => {
725
+ const runtime = await getRuntimeInstanceById(candidate.id);
726
+ if (!runtime)
727
+ return;
728
+ const staleSession = pool.lifecycle === "per-task" && runtime.status !== "offline" ? null : await getDbClient().get(`SELECT id FROM active_sessions WHERE runtimeInstanceId = ? AND NOT EXISTS (
729
+ SELECT 1 FROM agent_tasks WHERE id = active_sessions.taskId
730
+ AND status NOT IN (${TERMINAL_TASK_STATUS_PLACEHOLDERS})
731
+ ) AND (EXISTS (SELECT 1 FROM agent_tasks WHERE id = active_sessions.taskId)
732
+ OR triggerType NOT IN (${TASKLESS_TRIGGER_SQL}) OR lastHeartbeatAt < ?) LIMIT 1`, [runtime.id, ...TERMINAL_TASK_STATUSES, sessionCutoff]);
733
+ if (staleSession)
734
+ await getDbClient().run(`DELETE FROM active_sessions WHERE runtimeInstanceId = ? AND NOT EXISTS (
735
+ SELECT 1 FROM agent_tasks WHERE id = active_sessions.taskId
736
+ AND status NOT IN (${TERMINAL_TASK_STATUS_PLACEHOLDERS})
737
+ ) AND (EXISTS (SELECT 1 FROM agent_tasks WHERE id = active_sessions.taskId)
738
+ OR triggerType NOT IN (${TASKLESS_TRIGGER_SQL}) OR lastHeartbeatAt < ?)`, [runtime.id, ...TERMINAL_TASK_STATUSES, sessionCutoff]);
739
+ if (runtime.status === "offline") {
740
+ const session = await getDbClient().get("SELECT taskId FROM active_sessions WHERE runtimeInstanceId = ? LIMIT 1", [runtime.id]);
741
+ if (session)
742
+ await recoverRuntime(runtime.id, runtime.provisionError ?? "Runtime offline");
743
+ return;
744
+ }
745
+ const controllerId = runtime.controllerId ?? pool.placements[0];
746
+ const controller2 = controllers.get(controllerId);
747
+ if (!controller2)
748
+ return;
749
+ const listedHandles2 = listings.get(controllerId);
750
+ const handle = runtimeHandle(runtime);
751
+ let status = handle ? statusesByController.get(controllerId)?.[handle.externalId] : undefined;
752
+ const isE2b = handle?.kind === "e2b";
753
+ if (isE2b && status === "paused" && handle)
754
+ status = (await controller2.status([handle]))[handle.externalId];
755
+ const stale = runtime.status === "active" && Date.parse(runtime.lastSeenAt) < cutoff && !(isE2b && status === "paused");
756
+ const missing = handle && listedHandles2 && !listedHandles2.some((h) => h.externalId === handle.externalId) && !(isE2b && status === "paused");
757
+ const timeoutSec = runtimeNumber("RUNTIME_PROVISION_TIMEOUT_SEC", 300);
758
+ const timedOut = runtime.status === "provisioning" && now.getTime() - Date.parse(runtime.provisionRequestedAt ?? runtime.createdAt) >= timeoutSec * 1000;
759
+ if (status === "exited" || status === "failed" || stale || missing || timedOut) {
760
+ const reason = timedOut ? `runtime did not register within ${timeoutSec}s (image may lack the swarm runner, or WORKER_API_URL is unreachable)` : stale ? "Runtime stopped pinging" : missing ? "Runtime missing from provider list" : `Runtime ${status}`;
761
+ if (runtime.status === "provisioning") {
762
+ await recordProvisionFailure(runtime, reason, now, countedFailures);
763
+ if ((await getRuntimeInstanceById(runtime.id))?.status !== "offline")
764
+ return;
765
+ }
766
+ await terminateRuntime(runtime, controller2, reason);
767
+ await recoverRuntime(runtime.id, reason);
768
+ if (!stale)
769
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 1) - 1);
770
+ return;
771
+ }
772
+ const busy = await getDbClient().get(`SELECT s.taskId FROM active_sessions s LEFT JOIN agent_tasks t ON t.id = s.taskId
773
+ WHERE s.runtimeInstanceId = ? AND (t.status NOT IN (${TERMINAL_TASK_STATUS_PLACEHOLDERS})
774
+ OR (t.id IS NULL AND s.triggerType IN (${TASKLESS_TRIGGER_SQL}) AND s.lastHeartbeatAt >= ?)) LIMIT 1`, [runtime.id, ...TERMINAL_TASK_STATUSES, sessionCutoff]);
775
+ const task = runtime.taskId ? await getTaskById(runtime.taskId) : null;
776
+ const taskRunning = task?.status === "in_progress" || task?.status === "reviewing";
777
+ const rotating = rotations.has(runtime.id);
778
+ if (status === "paused" && isE2b) {
779
+ await recoverPausedRuntime(runtime, controller2, await isRuntimeWanted(pool, runtime, rotating, remaining.get(runtime.agentId) ?? 0, now), !!busy || taskRunning, now);
780
+ if ((await getRuntimeInstanceById(runtime.id))?.status === "offline")
781
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 1) - 1);
782
+ return;
783
+ }
784
+ if (runtime.status !== "active" && pool.enabled)
785
+ return;
786
+ if (busy || taskRunning) {
787
+ await getDbClient().run("UPDATE runtime_instances SET idle_since = NULL, draining = ?, task_id = COALESCE((SELECT id FROM agent_tasks WHERE id = ?), task_id) WHERE id = ?", [rotating || !pool.enabled ? 1 : 0, busy?.taskId ?? null, runtime.id]);
788
+ return;
789
+ }
790
+ if (pool.lifecycle === "per-task" && task && isTerminalTaskStatus(task.status)) {
791
+ const finishedAt = task.finishedAt ?? runtime.idleSince ?? now.toISOString();
792
+ if (!runtime.idleSince)
793
+ await getDbClient().run("UPDATE runtime_instances SET idle_since = ? WHERE id = ?", [
794
+ finishedAt,
795
+ runtime.id
796
+ ]);
797
+ if (now.getTime() - Date.parse(finishedAt) < runtimeNumber("RUNTIME_PER_TASK_EXIT_GRACE_SEC", 60) * 1000)
798
+ return;
799
+ await terminateRuntime(runtime, controller2, "Task exit grace expired");
800
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 1) - 1);
801
+ return;
802
+ }
803
+ if (rotating) {
804
+ if (!runtime.draining) {
805
+ await getDbClient().run("UPDATE runtime_instances SET draining = 1 WHERE id = ?", [
806
+ runtime.id
807
+ ]);
808
+ } else {
809
+ await terminateRuntime(runtime, controller2, controller2.traits.maxContinuousSec === undefined ? "Runtime token expires soon" : "Runtime rotation due");
810
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 1) - 1);
811
+ }
812
+ return;
813
+ }
814
+ if (!pool.enabled) {
815
+ if (!runtime.draining) {
816
+ await getDbClient().run("UPDATE runtime_instances SET draining = 1 WHERE id = ?", [
817
+ runtime.id
818
+ ]);
819
+ } else {
820
+ await terminateRuntime(runtime, controller2, "Pool disabled");
821
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 1) - 1);
822
+ }
823
+ return;
824
+ }
825
+ const idleSince = runtime.idleSince ?? now.toISOString();
826
+ if (!runtime.idleSince)
827
+ await getDbClient().run("UPDATE runtime_instances SET idle_since = ? WHERE id = ?", [
828
+ idleSince,
829
+ runtime.id
830
+ ]);
831
+ if (pool.lifecycle !== "idle" || pool.idleMinutes === null)
832
+ return;
833
+ if ((remaining.get(runtime.agentId) ?? 0) <= pool.minRuntimes) {
834
+ if (runtime.draining)
835
+ await getDbClient().run("UPDATE runtime_instances SET draining = 0 WHERE id = ?", [
836
+ runtime.id
837
+ ]);
838
+ return;
839
+ }
840
+ if (now.getTime() - Date.parse(idleSince) < pool.idleMinutes * 60000)
841
+ return;
842
+ if (!runtime.draining) {
843
+ await getDbClient().run("UPDATE runtime_instances SET draining = 1 WHERE id = ?", [
844
+ runtime.id
845
+ ]);
846
+ } else {
847
+ await terminateRuntime(runtime, controller2, "Idle timeout");
848
+ remaining.set(runtime.agentId, (remaining.get(runtime.agentId) ?? 1) - 1);
849
+ }
850
+ });
851
+ } catch (error) {
852
+ reportSupervisorError(error);
853
+ }
854
+ }
855
+ }
856
+ async function renewPoolLeases(pool, controllers, now) {
857
+ for (const runtime of await listRuntimeInstancesForPool(pool.id)) {
858
+ const controller = controllers.get(runtime.controllerId ?? pool.placements[0]);
859
+ const handle = runtimeHandle(runtime);
860
+ if (handle?.kind !== "e2b" || !controller?.renew)
861
+ continue;
862
+ const renewBy = now.getTime() + Math.min(runtimeNumber("RUNTIME_LEASE_RENEW_BEFORE_SEC", 300), poolLeaseTtl(pool, controller) - Math.min(60, poolLeaseTtl(pool, controller) / 2)) * 1000;
863
+ if (runtime.status === "offline" || runtime.leaseExpiresAt && Date.parse(runtime.leaseExpiresAt) > renewBy)
864
+ continue;
865
+ try {
866
+ const { endAt } = await controller.renew(handle, poolLeaseTtl(pool, controller));
867
+ if (!Number.isFinite(Date.parse(endAt)))
868
+ throw new Error("Provider returned an invalid lease expiry");
869
+ await getDbClient().run("UPDATE runtime_instances SET lease_expires_at = ?, updated_at = ? WHERE id = ? AND status != 'offline'", [endAt, now.toISOString(), runtime.id]);
870
+ console.debug(scrubSecrets(`[runtime-pools] Runtime ${runtime.id} lease renewed until ${endAt}`));
871
+ } catch (error) {
872
+ reportSupervisorError(error);
873
+ }
874
+ }
875
+ }
876
+ async function reconcileControllerOrphans(controllerId, controller, ownerId2, now = new Date, listedHandles) {
877
+ const rows = await getDbClient().query("SELECT id, status, external_handle FROM runtime_instances WHERE controller_id = ?", [
878
+ controllerId
879
+ ]);
880
+ const known = new Map;
881
+ for (const row of rows) {
882
+ if (!row.external_handle)
883
+ continue;
884
+ try {
885
+ known.set(RuntimeHandleSchema.parse(JSON.parse(row.external_handle)).externalId, row);
886
+ } catch (error) {
887
+ reportSupervisorError(error);
888
+ }
889
+ }
890
+ const handles = listedHandles ?? await controller.list(ownerId2);
891
+ const listed = new Set(handles.map((handle) => `${controllerId}:${handle.externalId}`));
892
+ for (const key of orphanFirstSeen.keys())
893
+ if (key.startsWith(`${controllerId}:`) && !listed.has(key))
894
+ orphanFirstSeen.delete(key);
895
+ for (const handle of handles) {
896
+ try {
897
+ const row = known.get(handle.externalId);
898
+ const key = `${controllerId}:${handle.externalId}`;
899
+ if (row && row.status !== "offline") {
900
+ orphanFirstSeen.delete(key);
901
+ continue;
902
+ }
903
+ if (!row) {
904
+ const created = handle.createdAt ? Date.parse(handle.createdAt) : NaN;
905
+ const firstSeen = Number.isFinite(created) ? created : orphanFirstSeen.get(key) ?? now.getTime();
906
+ orphanFirstSeen.set(key, firstSeen);
907
+ if (now.getTime() - firstSeen < ORPHAN_GRACE_MS)
908
+ continue;
909
+ }
910
+ await controller.terminate(handle, "Orphan runtime");
911
+ if (row)
912
+ await markRuntimeTerminated(row.id, "Runtime closed");
913
+ orphanFirstSeen.delete(key);
914
+ } catch (error) {
915
+ reportSupervisorError(error);
916
+ }
917
+ }
918
+ }
919
+ async function reconcilePools(now, commands, signal) {
920
+ await reconcileDisconnectedControllers(recoverRuntime, now);
921
+ const ownerId2 = await ensureRuntimeOwnerId();
922
+ const controllers = new Map;
923
+ const listed = new Map;
924
+ const countedFailures = new Set;
925
+ const rotationCutoff = new Date(now.getTime() + runtimeNumber("RUNTIME_TOKEN_ROTATE_BEFORE_MIN", 60) * 60000).toISOString();
926
+ for (const pool of await listRuntimePools()) {
927
+ if (signal.aborted)
928
+ return;
929
+ if (!canProvisionKind(pool.kind))
930
+ continue;
931
+ const controllerId = pool.placements[0];
932
+ try {
933
+ const poolRuntimes = await listRuntimeInstancesForPool(pool.id);
934
+ const poolControllerIds = new Set([
935
+ controllerId,
936
+ ...poolRuntimes.map((r) => r.controllerId ?? controllerId)
937
+ ]);
938
+ const rotatingIds = new Set;
939
+ for (const id of poolControllerIds) {
940
+ try {
941
+ const controller2 = controllers.get(id) ?? await commands(id);
942
+ controllers.set(id, controller2);
943
+ if (!controller2.traits.canProvision)
944
+ continue;
945
+ if (!listed.has(id)) {
946
+ try {
947
+ listed.set(id, await controller2.list(ownerId2));
948
+ } catch (error) {
949
+ reportSupervisorError(error);
950
+ listed.set(id, null);
951
+ }
952
+ const handles = listed.get(id);
953
+ if (handles && remoteControllerSession(id) === controller2)
954
+ await reconcileRemoteProvisions(id, handles, ownerId2);
955
+ if (handles)
956
+ await reconcileControllerOrphans(id, controller2, ownerId2, now, handles);
957
+ }
958
+ const rotations = await rotatingRuntimes(pool.id, rotationCutoff, now, controller2.traits.maxContinuousSec);
959
+ for (const runtime of poolRuntimes)
960
+ if ((runtime.controllerId ?? controllerId) === id && rotations.has(runtime.id))
961
+ rotatingIds.add(runtime.id);
962
+ } catch (error) {
963
+ reportSupervisorError(error);
964
+ }
965
+ }
966
+ const controller = controllers.get(controllerId);
967
+ const existingController = controller ?? [...poolControllerIds].map((id) => controllers.get(id)).find((c) => c?.traits.canProvision);
968
+ if (!existingController)
969
+ continue;
970
+ await reapPoolRuntimes(pool, await listRuntimeInstancesForPool(pool.id), existingController, now, listed.get(controllerId), rotatingIds, countedFailures, controllers, listed);
971
+ await renewPoolLeases(pool, controllers, now);
972
+ if (signal.aborted)
973
+ return;
974
+ if (!controller?.traits.canProvision)
975
+ continue;
976
+ const currentPool = await getRuntimePool(pool.id);
977
+ const agents = await listAgentsForPool(pool.id);
978
+ const demands = [];
979
+ const work = new Map;
980
+ for (const agent of agents) {
981
+ if (signal.aborted)
982
+ return;
983
+ const pending = await pendingWorkForAgent(agent.id);
984
+ work.set(agent.id, pending);
985
+ if (!pending.work && (agent.runtimeProvisionAttempts || agent.runtimeProvisionRetryAt))
986
+ await getDbClient().run("UPDATE agents SET runtime_provision_attempts = 0, runtime_provision_retry_at = NULL WHERE id = ?", [agent.id]);
987
+ const runtimes = await listRuntimeInstancesForAgent(agent.id);
988
+ let freeSlots = 0;
989
+ let provisioning = 0;
990
+ for (const runtime of runtimes) {
991
+ if (runtime.status === "provisioning")
992
+ provisioning++;
993
+ if (!runtime.isLive || runtime.draining || runtime.credentialReady === false)
994
+ continue;
995
+ const task = runtime.taskId ? await getTaskById(runtime.taskId) : null;
996
+ if (pool.lifecycle === "per-task" && task && isTerminalTaskStatus(task.status))
997
+ continue;
998
+ const sessions2 = await getDbClient().get("SELECT COUNT(*) AS count FROM active_sessions WHERE runtimeInstanceId = ?", [runtime.id]);
999
+ let occupied = sessions2?.count ?? 0;
1000
+ if (occupied === 0 && runtime.taskId) {
1001
+ if (task?.status === "in_progress" || task?.status === "reviewing")
1002
+ occupied = 1;
1003
+ }
1004
+ freeSlots += Math.max(0, runtime.reportedSlots - occupied);
1005
+ }
1006
+ demands.push({
1007
+ agentId: agent.id,
1008
+ maxTasks: agent.maxTasks ?? 1,
1009
+ work: pending.work,
1010
+ current: runtimes.filter((r) => r.status === "provisioning" || r.isLive && !(r.draining && rotatingIds.has(r.id))).length,
1011
+ freeSlots,
1012
+ provisioning
1013
+ });
1014
+ }
1015
+ if (!pool.enabled || currentPool?.circuitOpenUntil && Date.parse(currentPool.circuitOpenUntil) > now.getTime())
1016
+ continue;
1017
+ const poolCount = (await listRuntimeInstancesForPool(pool.id)).filter((r) => r.status === "provisioning" || r.status === "active" && Date.parse(r.lastSeenAt) >= now.getTime() - runtimeStaleThresholdMinutes() * 60000).length;
1018
+ const counted = demands.reduce((n, d) => n + d.current, 0);
1019
+ const desired = computeDesired({
1020
+ ...pool,
1021
+ maxRuntimes: pool.maxRuntimes === null ? null : Math.max(0, pool.maxRuntimes - Math.max(0, poolCount - counted))
1022
+ }, demands);
1023
+ const provisions = new Set;
1024
+ const failedAgents = new Set;
1025
+ const concurrency = runtimeNumber("RUNTIME_PROVISION_CONCURRENCY", 8);
1026
+ try {
1027
+ for (const agent of agents) {
1028
+ const demand = demands.find((d) => d.agentId === agent.id);
1029
+ const pending = work.get(agent.id);
1030
+ for (let count = demand.current;count < (desired.get(agent.id) ?? 0); count++) {
1031
+ if (provisions.size >= concurrency)
1032
+ await Promise.race(provisions);
1033
+ if (signal.aborted)
1034
+ return;
1035
+ if (failedAgents.has(agent.id))
1036
+ break;
1037
+ if (!(pool.resolvedImage ?? pool.image))
1038
+ break;
1039
+ if (!(await canClaim(agent.id, now, pending.topTask?.requestedByUserId)).allowed)
1040
+ break;
1041
+ if (signal.aborted)
1042
+ return;
1043
+ const retry = await getDbClient().get("SELECT runtime_provision_retry_at, runtime_provision_attempts FROM agents WHERE id = ?", [agent.id]);
1044
+ if (retry?.runtime_provision_retry_at && Date.parse(retry.runtime_provision_retry_at) > now.getTime())
1045
+ break;
1046
+ const retrying = (retry?.runtime_provision_attempts ?? 0) > 0;
1047
+ if (retrying && demand.provisioning > 0)
1048
+ break;
1049
+ const freshPool = await getRuntimePool(pool.id);
1050
+ if (!freshPool?.enabled)
1051
+ break;
1052
+ if (freshPool.circuitOpenUntil) {
1053
+ if (Date.parse(freshPool.circuitOpenUntil) > now.getTime())
1054
+ break;
1055
+ if (provisions.size || (await listRuntimeInstancesForPool(pool.id)).some((r) => r.status === "provisioning"))
1056
+ break;
1057
+ }
1058
+ if (signal.aborted)
1059
+ return;
1060
+ if (failedAgents.has(agent.id))
1061
+ break;
1062
+ const provision = provisionRuntime(pool, agent, controller, ownerId2, now, {
1063
+ signal,
1064
+ countedFailures,
1065
+ onFailure: () => {
1066
+ failedAgents.add(agent.id);
1067
+ }
1068
+ }).then((success) => {
1069
+ provisions.delete(provision);
1070
+ if (!success)
1071
+ failedAgents.add(agent.id);
1072
+ }, (error) => {
1073
+ provisions.delete(provision);
1074
+ failedAgents.add(agent.id);
1075
+ reportSupervisorError(error);
1076
+ });
1077
+ provisions.add(provision);
1078
+ if (retrying)
1079
+ break;
1080
+ }
1081
+ }
1082
+ } finally {
1083
+ await Promise.all(provisions);
1084
+ }
1085
+ } catch (error) {
1086
+ reportSupervisorError(error);
1087
+ }
1088
+ }
1089
+ }
1090
+ async function reconcileOnce(opts = {}) {
1091
+ if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled() || inFlight)
1092
+ return;
1093
+ tickAbort = new AbortController;
1094
+ inFlight = reconcilePools(opts.now ?? new Date, opts.getControllerCommands ?? getControllerCommands, tickAbort.signal);
1095
+ try {
1096
+ await inFlight;
1097
+ } catch (error) {
1098
+ reportSupervisorError(error);
1099
+ } finally {
1100
+ inFlight = null;
1101
+ tickAbort = null;
1102
+ }
1103
+ }
1104
+ var onTaskCreated = (data) => {
1105
+ const taskId = data?.taskId;
1106
+ if (typeof taskId !== "string" || !timer || !isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
1107
+ return;
1108
+ (async () => {
1109
+ const task = await getTaskById(taskId);
1110
+ const agentId = task?.status === "offered" ? task.offeredTo : task?.status === "pending" ? task.agentId : null;
1111
+ if (!agentId || !await getPoolForAgent(agentId) || !timer)
1112
+ return;
1113
+ if (kickTimer)
1114
+ clearTimeout(kickTimer);
1115
+ kickTimer = setTimeout(() => {
1116
+ kickTimer = null;
1117
+ reconcileOnce().catch(reportSupervisorError);
1118
+ }, 250);
1119
+ kickTimer.unref?.();
1120
+ })().catch(reportSupervisorError);
1121
+ };
1122
+ function startRuntimeSupervisor(intervalMs = Number(process.env.RUNTIME_SUPERVISOR_INTERVAL_MS) || 5000) {
1123
+ if (timer || !isRuntimePoolsEnabled())
1124
+ return;
1125
+ if (!isMultiRuntimeEnabled()) {
1126
+ if (!warnedMultiRuntime) {
1127
+ console.error("[runtime-pools] Supervisor requires MULTI_RUNTIME_ENABLED=true.");
1128
+ warnedMultiRuntime = true;
1129
+ }
1130
+ return;
1131
+ }
1132
+ workflowEventBus.on("task.created", onTaskCreated);
1133
+ startRuntimeRecovery();
1134
+ timer = setInterval(() => {
1135
+ reconcileOnce().catch(reportSupervisorError);
1136
+ }, Math.max(1, intervalMs));
1137
+ timer.unref?.();
1138
+ }
1139
+ async function stopRuntimeSupervisor(timeoutMs = 1e4) {
1140
+ if (timer)
1141
+ clearInterval(timer);
1142
+ if (kickTimer)
1143
+ clearTimeout(kickTimer);
1144
+ timer = null;
1145
+ kickTimer = null;
1146
+ workflowEventBus.off("task.created", onTaskCreated);
1147
+ stopRuntimeRecovery();
1148
+ tickAbort?.abort();
1149
+ stopE2bImageBuilds();
1150
+ let timeout;
1151
+ try {
1152
+ if (inFlight) {
1153
+ await Promise.race([
1154
+ inFlight.catch(reportSupervisorError),
1155
+ new Promise((resolve) => {
1156
+ timeout = setTimeout(() => {
1157
+ console.error("[runtime-pools] Supervisor shutdown timed out.");
1158
+ resolve();
1159
+ }, Math.min(1e4, Math.max(0, timeoutMs)));
1160
+ })
1161
+ ]);
1162
+ }
1163
+ } catch (error) {
1164
+ reportSupervisorError(error);
1165
+ } finally {
1166
+ if (timeout)
1167
+ clearTimeout(timeout);
1168
+ clearRuntimeOwnerIdCache();
1169
+ orphanFirstSeen.clear();
1170
+ }
1171
+ }
1172
+
1173
+ // src/be/runtime-pools/recovery.ts
1174
+ var recovering = new Map;
1175
+ var currentAction = new AsyncLocalStorage;
1176
+ var socketChecks = new Map;
1177
+ var sockets = new Map;
1178
+ var subscriptions = [];
1179
+ function reportRecoveryError(error) {
1180
+ console.error("[runtime-pools] Recovery failed:", scrubSecrets(String(error)));
1181
+ }
1182
+ async function serializeRuntimeAction(runtimeId, action) {
1183
+ if (currentAction.getStore() === runtimeId)
1184
+ return action();
1185
+ const previous = recovering.get(runtimeId) ?? Promise.resolve();
1186
+ const recovery = previous.catch(reportRecoveryError).then(() => currentAction.run(runtimeId, action));
1187
+ recovering.set(runtimeId, recovery);
1188
+ try {
1189
+ await recovery;
1190
+ } finally {
1191
+ if (recovering.get(runtimeId) === recovery)
1192
+ recovering.delete(runtimeId);
1193
+ }
1194
+ }
1195
+ async function recoverSessions(runtimeId, reason) {
1196
+ const sessions2 = await getDbClient().query("SELECT taskId FROM active_sessions WHERE runtimeInstanceId = ?", [runtimeId]);
1197
+ if (isRuntimePoolsEnabled()) {
1198
+ const dispatched = await getDbClient().query(`SELECT t.id AS taskId FROM agent_tasks t
1199
+ WHERE (t.runtime_instance_id = ? OR t.id IN (
1200
+ SELECT task_id FROM runtime_instances WHERE id = ? AND agent_id = t.agentId
1201
+ )) AND t.status = 'in_progress'
1202
+ AND NOT EXISTS (SELECT 1 FROM active_sessions s WHERE s.taskId = t.id)`, [runtimeId, runtimeId]);
1203
+ sessions2.push(...dispatched);
1204
+ }
1205
+ if (!sessions2.length)
1206
+ return;
1207
+ const { remediateTaskForDeadRuntime } = await import("./heartbeat-ge72pt7q.js");
1208
+ for (const session of sessions2) {
1209
+ try {
1210
+ const task = await getTaskById(session.taskId);
1211
+ if (task?.status === "in_progress")
1212
+ await remediateTaskForDeadRuntime(task, reason);
1213
+ else
1214
+ await getDbClient().run("DELETE FROM active_sessions WHERE taskId = ? AND runtimeInstanceId = ?", [session.taskId, runtimeId]);
1215
+ } catch (error) {
1216
+ reportRecoveryError(error);
1217
+ }
1218
+ }
1219
+ }
1220
+ async function recoverRuntime(runtimeId, reason) {
1221
+ await serializeRuntimeAction(runtimeId, async () => {
1222
+ await markRuntimeTerminated(runtimeId, scrubSecrets(reason));
1223
+ await recoverSessions(runtimeId, reason);
1224
+ });
1225
+ }
1226
+ async function recoverPausedRuntime(runtime, controller, wanted, busy, now = new Date) {
1227
+ if (busy) {
1228
+ await terminateRuntime(runtime, controller, "Runtime paused during a task");
1229
+ await recoverRuntime(runtime.id, "Runtime paused during a task");
1230
+ } else if (!wanted) {
1231
+ await terminateRuntime(runtime, controller, "Paused runtime no longer wanted");
1232
+ } else {
1233
+ const handle = runtimeHandle(runtime);
1234
+ if (!handle || !controller.resume)
1235
+ throw new Error("Controller cannot resume a paused runtime");
1236
+ await controller.resume(handle);
1237
+ await getDbClient().run("UPDATE runtime_instances SET last_seen_at = ?, lease_expires_at = NULL WHERE id = ? AND status != 'offline'", [now.toISOString(), runtime.id]);
1238
+ }
1239
+ }
1240
+ async function remediateStalledRuntime(runtimeId, reason, remediate) {
1241
+ if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
1242
+ return false;
1243
+ const runtime = await getRuntimeInstanceById(runtimeId);
1244
+ const pool = runtime?.poolId ? await getRuntimePool(runtime.poolId) : null;
1245
+ if (!runtime || !pool || !canProvisionKind(pool.kind))
1246
+ return false;
1247
+ await serializeRuntimeAction(runtimeId, async () => {
1248
+ if (await remediate(() => fenceStalledRuntime(runtime, reason)))
1249
+ await recoverSessions(runtimeId, reason);
1250
+ });
1251
+ return true;
1252
+ }
1253
+ async function fenceStalledRuntime(runtime, reason) {
1254
+ await markRuntimeTerminated(runtime.id, scrubSecrets(reason));
1255
+ try {
1256
+ if (runtime.controllerId)
1257
+ await terminateRuntime(runtime, await getControllerCommands(runtime.controllerId), reason);
1258
+ } catch (error) {
1259
+ reportRecoveryError(error);
1260
+ }
1261
+ }
1262
+ async function checkDisconnectedRuntime(runtimeId) {
1263
+ if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
1264
+ return;
1265
+ await serializeRuntimeAction(runtimeId, async () => {
1266
+ const runtime = await getRuntimeInstanceById(runtimeId);
1267
+ if (!runtime || runtime.status !== "active" || !runtime.poolId || !runtime.controllerId)
1268
+ return;
1269
+ const pool = await getRuntimePool(runtime.poolId);
1270
+ if (!pool || !canProvisionKind(pool.kind) || resolvePoolDelivery(pool) !== "push")
1271
+ return;
1272
+ const handle = runtimeHandle(runtime);
1273
+ if (!handle)
1274
+ return;
1275
+ const controller = await getControllerCommands(runtime.controllerId);
1276
+ const status = (await controller.status([handle]))[handle.externalId];
1277
+ if (status === "paused" && pool.kind === "e2b") {
1278
+ const session = await getDbClient().get("SELECT taskId FROM active_sessions WHERE runtimeInstanceId = ? LIMIT 1", [runtimeId]);
1279
+ const task = runtime.taskId ? await getTaskById(runtime.taskId) : null;
1280
+ const now = new Date;
1281
+ const configured = Number(process.env.RUNTIME_TOKEN_ROTATE_BEFORE_MIN);
1282
+ const beforeMin = Number.isInteger(configured) && configured > 0 ? configured : 60;
1283
+ const rotations = await rotatingRuntimes(pool.id, new Date(now.getTime() + beforeMin * 60000).toISOString(), now, controller.traits.maxContinuousSec);
1284
+ const siblings = (await listRuntimeInstancesForPool(pool.id)).filter((r) => r.agentId === runtime.agentId);
1285
+ const cutoff = now.getTime() - runtimeStaleThresholdMinutes() * 60000;
1286
+ const staleHandles = siblings.filter((r) => r.id !== runtimeId && r.status === "active" && Date.parse(r.lastSeenAt) < cutoff).map(runtimeHandle).filter((h) => h !== null);
1287
+ const statuses = staleHandles.length ? await controller.status(staleHandles) : {};
1288
+ const remaining = siblings.filter((r) => r.status === "provisioning" || r.status === "active" && (Date.parse(r.lastSeenAt) >= cutoff || r.id === runtimeId || statuses[runtimeHandle(r)?.externalId ?? ""] === "paused")).length;
1289
+ await recoverPausedRuntime(runtime, controller, await isRuntimeWanted(pool, runtime, rotations.has(runtime.id), remaining, now), !!session || task?.status === "in_progress" || task?.status === "reviewing");
1290
+ return;
1291
+ }
1292
+ if (status === "running" || status === "starting" || status === "paused")
1293
+ return;
1294
+ if (status === "exited" || status === "failed" || !(await controller.list(await ensureRuntimeOwnerId())).some((h) => h.externalId === handle.externalId)) {
1295
+ await terminateRuntime(runtime, controller, "Runtime died after socket disconnect");
1296
+ await recoverRuntime(runtimeId, "Runtime died after socket disconnect");
1297
+ }
1298
+ });
1299
+ }
1300
+ function socketRuntimeId(data) {
1301
+ const runtimeId = data?.runtimeId;
1302
+ return typeof runtimeId === "string" ? runtimeId : null;
1303
+ }
1304
+ function startRuntimeRecovery() {
1305
+ if (subscriptions.length)
1306
+ return;
1307
+ subscriptions = [
1308
+ realtimeBus.subscribe("worker.socket.connected", (data) => {
1309
+ const id = socketRuntimeId(data);
1310
+ if (!id)
1311
+ return;
1312
+ sockets.set(id, (sockets.get(id) ?? 0) + 1);
1313
+ clearTimeout(socketChecks.get(id));
1314
+ socketChecks.delete(id);
1315
+ }),
1316
+ realtimeBus.subscribe("worker.socket.disconnected", (data) => {
1317
+ const id = socketRuntimeId(data);
1318
+ if (!id)
1319
+ return;
1320
+ const count = Math.max(0, (sockets.get(id) ?? 1) - 1);
1321
+ if (count) {
1322
+ sockets.set(id, count);
1323
+ return;
1324
+ }
1325
+ sockets.delete(id);
1326
+ if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
1327
+ return;
1328
+ if (socketChecks.has(id))
1329
+ return;
1330
+ const seconds = Number(process.env.RUNTIME_SOCKET_GRACE_SEC);
1331
+ const delay = Number.isInteger(seconds) && seconds >= 0 ? seconds : 60;
1332
+ const timer2 = setTimeout(() => {
1333
+ socketChecks.delete(id);
1334
+ checkDisconnectedRuntime(id).catch(reportRecoveryError);
1335
+ }, delay * 1000);
1336
+ timer2.unref?.();
1337
+ socketChecks.set(id, timer2);
1338
+ })
1339
+ ];
1340
+ }
1341
+ function stopRuntimeRecovery() {
1342
+ for (const unsubscribe of subscriptions)
1343
+ unsubscribe();
1344
+ subscriptions = [];
1345
+ for (const timer2 of socketChecks.values())
1346
+ clearTimeout(timer2);
1347
+ socketChecks.clear();
1348
+ sockets.clear();
1349
+ }
1350
+
1351
+ export { remoteControllerSession, installRemoteController, removeRemoteController, RemoteController, ensureRuntimeOwnerId, reconcileRemoteProvisions, remediateStalledRuntime, runtimeSupervisorStatus, reconcileControllerOrphans, startRuntimeSupervisor, stopRuntimeSupervisor };