@desplega.ai/agent-swarm 2.8.1 → 2.8.3

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 (318) hide show
  1. package/dist/acp-adapter-xq6s2z6t.js +14 -0
  2. package/dist/{actions-pwjpn0j6.js → actions-ewz7bp4g.js} +20 -19
  3. package/dist/{amp-adapter-cq9jgj6x.js → amp-adapter-f25tqhnf.js} +3 -3
  4. package/dist/{app-cnfffgwg.js → app-mkptw0k7.js} +4 -4
  5. package/dist/{assistant-kpn317y1.js → assistant-c47rfe77.js} +23 -22
  6. package/dist/{boot-args-schema-pbbnhmc3.js → boot-args-schema-4vb0xsat.js} +1 -1
  7. package/dist/{boot-reembed-9m0ysxma.js → boot-reembed-1ghy2sab.js} +1 -1
  8. package/dist/{boot-reembed-majbn53m.js → boot-reembed-htr73hbs.js} +1 -1
  9. package/dist/{boot-scrub-sweep-app8g8ym.js → boot-scrub-sweep-yrytg42z.js} +4 -4
  10. package/dist/{boot-seeds-pbtmvcjm.js → boot-seeds-n2b3dx4e.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-jmfqgkqa.js} +2 -2
  12. package/dist/{claude-adapter-wn1g3qp5.js → claude-adapter-r33pqnzx.js} +8 -9
  13. package/dist/{claude-managed-adapter-jh6c523j.js → claude-managed-adapter-hddmxjyj.js} +4 -4
  14. package/dist/{claude-managed-setup-pd47nzch.js → claude-managed-setup-hfvry1bd.js} +5 -5
  15. package/dist/{claude-sdk-session-3a2a6589.js → claude-sdk-session-0hamqzc7.js} +10 -11
  16. package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
  17. package/dist/{cli-a3b239vq.js → cli-0vksaxvr.js} +2 -2
  18. package/dist/{cli-mrt48bx7.js → cli-15204js0.js} +1 -1
  19. package/dist/{cli-8aes17e4.js → cli-1m96dc36.js} +3 -3
  20. package/dist/{cli-2r0jcc3k.js → cli-2d0cghfn.js} +1 -1
  21. package/dist/{cli-wk18cm92.js → cli-4ax9mvvg.js} +4 -4
  22. package/dist/{cli-9wngrawf.js → cli-4dpkjc2e.js} +6 -6
  23. package/dist/{cli-x1wa213s.js → cli-4e1hfbpq.js} +5 -5
  24. package/dist/{cli-7349va39.js → cli-500c09j9.js} +921 -431
  25. package/dist/{cli-m4dqmnbp.js → cli-54qr8mcd.js} +2 -2
  26. package/dist/{cli-m88rpzkh.js → cli-5a7szzfh.js} +2 -2
  27. package/dist/{cli-bst1vp7e.js → cli-5y2fvw4z.js} +13 -5
  28. package/dist/{cli-vj75tyaw.js → cli-6yygkr0w.js} +7 -7
  29. package/dist/{cli-7b8sbmag.js → cli-7c5tgqhf.js} +5 -5
  30. package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
  31. package/dist/{cli-yncmerje.js → cli-922z7gwm.js} +4 -4
  32. package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
  33. package/dist/{cli-sn7rtnj4.js → cli-9zmb7ptc.js} +9 -9
  34. package/dist/{cli-tk7cjj8h.js → cli-am1ptset.js} +3 -3
  35. package/dist/{cli-cyhbbd1z.js → cli-awwptga4.js} +1 -1
  36. package/dist/{cli-89cqnasv.js → cli-bhsfbmk8.js} +19 -7
  37. package/dist/{cli-9vhebtjz.js → cli-bj6qhgte.js} +15 -32
  38. package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
  39. package/dist/{cli-vqptjbr7.js → cli-c3ng0mb4.js} +14 -14
  40. package/dist/{cli-re4raaj0.js → cli-c71n3bxq.js} +11 -6
  41. package/dist/{cli-7p1kvkck.js → cli-crpf163n.js} +25 -18
  42. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  43. package/dist/{cli-d3p5vwbk.js → cli-dpsfwh7n.js} +13 -21
  44. package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
  45. package/dist/{cli-bb431xey.js → cli-e2w34h6z.js} +231 -68
  46. package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
  47. package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
  48. package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
  49. package/dist/{cli-tqegb8eq.js → cli-gpz1d0t2.js} +4 -4
  50. package/dist/{cli-7w69ne2f.js → cli-h9yy18gy.js} +239 -67
  51. package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
  52. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  53. package/dist/{cli-k26bkr9t.js → cli-k2rw11py.js} +3 -3
  54. package/dist/{cli-93k32c37.js → cli-k96cecs7.js} +377 -61
  55. package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
  56. package/dist/{cli-k0615eh8.js → cli-kmemts3w.js} +13 -13
  57. package/dist/{cli-pcad4cb1.js → cli-knva3nmx.js} +2 -2
  58. package/dist/{cli-b085njxz.js → cli-kw44j53p.js} +15 -14
  59. package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
  60. package/dist/{cli-syybb0p1.js → cli-me0r8gzr.js} +35 -76
  61. package/dist/{cli-4r05hnqa.js → cli-mwwmka77.js} +15 -15
  62. package/dist/{cli-1xh9a7hn.js → cli-n5t077me.js} +2 -2
  63. package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
  64. package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
  65. package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
  66. package/dist/{cli-zcsw143p.js → cli-qmqt520k.js} +2 -2
  67. package/dist/{cli-2zp0et3v.js → cli-qps8je6j.js} +70 -19
  68. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  69. package/dist/{cli-k93bq1wq.js → cli-rjvsf9qa.js} +5 -5
  70. package/dist/{cli-6mma83xa.js → cli-rqfvkx5t.js} +7 -7
  71. package/dist/{cli-dy32zecz.js → cli-s7zz734a.js} +1 -1
  72. package/dist/{cli-yn2bbre9.js → cli-s8p8hhty.js} +2 -2
  73. package/dist/{cli-vbh10fqa.js → cli-sdvcrq5x.js} +5 -5
  74. package/dist/{cli-b5rs97a6.js → cli-sg27rk2t.js} +5 -5
  75. package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
  76. package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
  77. package/dist/{cli-hxpyc9sn.js → cli-t5ys4ebm.js} +3 -3
  78. package/dist/{cli-qmqk2yc2.js → cli-tas6ckky.js} +2 -2
  79. package/dist/{cli-p1w18yhx.js → cli-tf79ryyy.js} +1 -1
  80. package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
  81. package/dist/{cli-gax7fk3t.js → cli-vx421edw.js} +3 -3
  82. package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
  83. package/dist/cli-yss07azk.js +142 -0
  84. package/dist/{cli-0ntbxyaa.js → cli-z8cvws4c.js} +363 -47
  85. package/dist/{cli-tacge1w0.js → cli-zdaypkq9.js} +146 -52
  86. package/dist/{cli-b8e9nb04.js → cli-zeaehgyd.js} +2 -2
  87. package/dist/{cli-jcpr5smb.js → cli-ztq5z4e1.js} +4 -4
  88. package/dist/cli.js +21 -21
  89. package/dist/{codex-adapter-nha71q3n.js → codex-adapter-2brxx5ta.js} +7 -8
  90. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-c930c3ea.js} +2 -2
  91. package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
  92. package/dist/{codex-session-runner-ak9x1k1h.js → codex-session-runner-y9anfj0r.js} +8 -9
  93. package/dist/{commands-f587qpq8.js → commands-wn9q06qr.js} +3 -3
  94. package/dist/{controller-hxx8wwy1.js → controller-fw608czd.js} +4 -4
  95. package/dist/{controllers-connect-k5sg9m9h.js → controllers-connect-63j5rdcm.js} +20 -20
  96. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-6mb9jme8.js} +2 -2
  97. package/dist/{db-nzf8zb5z.js → db-0m6v5tq4.js} +3 -3
  98. package/dist/{db-amm8w15a.js → db-y4wfrzbm.js} +4 -2
  99. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
  100. package/dist/{dispatcher-89zrts8f.js → dispatcher-9tq2zzdj.js} +17 -17
  101. package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
  102. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-t09sv4tq.js} +2 -2
  103. package/dist/{e2b-s16txnpx.js → e2b-7s9dscap.js} +3 -3
  104. package/dist/{e2b-jkwfhbcv.js → e2b-a7vzs2vj.js} +3 -3
  105. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
  106. package/dist/{embedding-space-ezwenjmj.js → embedding-space-wh8de1t9.js} +6 -6
  107. package/dist/{embeddings-np74ht6g.js → embeddings-3hpbdtjr.js} +1 -1
  108. package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
  109. package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
  110. package/dist/{external-channel-z46yx9d7.js → external-channel-ts2fwqh0.js} +2 -2
  111. package/dist/fx-adapter-1rnxnf56.js +17 -0
  112. package/dist/grok-adapter-efhmf1r8.js +17 -0
  113. package/dist/handlers-anrr3py9.js +32 -0
  114. package/dist/{heartbeat-dt9qw9c8.js → heartbeat-2ze5fzpc.js} +20 -20
  115. package/dist/{hook-8k6fbz9b.js → hook-ca54yd4s.js} +5 -5
  116. package/dist/{hook-jgcgygex.js → hook-gaehe2w5.js} +8 -8
  117. package/dist/{http-haw4r8ne.js → http-jfg8t2yk.js} +3839 -122
  118. package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
  119. package/dist/{index-tez78qj3.js → index-3yvzbhxd.js} +100 -23
  120. package/dist/index-8w2aznds.js +33 -0
  121. package/dist/{index-5gk12my8.js → index-csgrxedz.js} +1 -1
  122. package/dist/index-qnjvr362.js +37 -0
  123. package/dist/index-yzxd3sn9.js +32 -0
  124. package/dist/{keepalive-xn6s7rmg.js → keepalive-k2a3qe73.js} +4 -4
  125. package/dist/lead-zhxqbfdv.js +69 -0
  126. package/dist/{maintenance-vdts800b.js → maintenance-gb5sd5nc.js} +1 -1
  127. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  128. package/dist/{oauth-refresh-sweep-094c8wfk.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
  129. package/dist/{onboard-v99eh56m.js → onboard-jmc5qerv.js} +4 -4
  130. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-7eade9ev.js} +6 -7
  131. package/dist/{otel-impl-q7yr9yp0.js → otel-impl-8j1xhxqd.js} +2 -2
  132. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-yqmaf32x.js} +14 -13
  133. package/dist/{pricing-refresh-7dh2yase.js → pricing-refresh-1nj722h6.js} +2 -2
  134. package/dist/{rbac-roles-mdmc96p4.js → rbac-roles-b1mtr6dr.js} +3 -3
  135. package/dist/{rbac-roles-npbmdh77.js → rbac-roles-n1f3frk1.js} +2 -2
  136. package/dist/{render-v2-twhhwmms.js → render-v2-1gfpd8rj.js} +4 -4
  137. package/dist/{resume-5gsrjd5e.js → resume-w1s1eh5v.js} +7 -7
  138. package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
  139. package/dist/{session-access-m191x30x.js → session-access-y6z1txk4.js} +4 -4
  140. package/dist/{session-source-backfill-nt923ask.js → session-source-backfill-gxxwfh12.js} +3 -3
  141. package/dist/{setup-wv467afy.js → setup-r91gstyk.js} +1 -1
  142. package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
  143. package/dist/{work-objects-8zkrpy13.js → work-objects-qcxzg61c.js} +20 -20
  144. package/dist/worker-7j2907g6.js +69 -0
  145. package/dist/{worker-follow-up-cecqszem.js → worker-follow-up-y2d2h7km.js} +19 -17
  146. package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
  147. package/openapi.json +2908 -351
  148. package/package.json +4 -4
  149. package/src/apps/catalog.generated.json +120 -1
  150. package/src/apps/definition.ts +38 -11
  151. package/src/apps/page-validator.ts +88 -0
  152. package/src/be/db/model-profiles.ts +110 -11
  153. package/src/be/db/tasks/read.ts +53 -0
  154. package/src/be/db/workflow-run-definitions.ts +19 -8
  155. package/src/be/db-client.ts +43 -5
  156. package/src/be/db.ts +40 -9
  157. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  158. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  159. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  160. package/src/be/migrations/293_savings_component_links.sql +58 -0
  161. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  162. package/src/be/model-profile-check.ts +53 -20
  163. package/src/be/runtime-pools/routing.ts +1 -0
  164. package/src/be/savings/calibrate.ts +468 -0
  165. package/src/be/savings/compute.ts +677 -0
  166. package/src/be/savings/model.ts +674 -0
  167. package/src/be/savings/read.ts +1500 -0
  168. package/src/be/savings/rollup.ts +571 -0
  169. package/src/be/scripts/run-credential.ts +15 -3
  170. package/src/be/scripts/typecheck.ts +91 -4
  171. package/src/be/seed/agent-fs-provision.ts +48 -11
  172. package/src/be/seed/workflows-seeder.ts +67 -23
  173. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  174. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  175. package/src/be/skill-parser.ts +19 -7
  176. package/src/be/swarm-config-guard.ts +8 -0
  177. package/src/be/users.ts +29 -2
  178. package/src/commands/onboard/agent-fs-version.ts +1 -1
  179. package/src/commands/provider-error-class.ts +97 -0
  180. package/src/commands/runner.ts +258 -58
  181. package/src/extensions/contract-types.generated.ts +1 -1
  182. package/src/http/all-routes.ts +2 -0
  183. package/src/http/fs.ts +8 -2
  184. package/src/http/index.ts +11 -0
  185. package/src/http/model-profiles.ts +43 -10
  186. package/src/http/poll.ts +15 -1
  187. package/src/http/requested-by.ts +97 -1
  188. package/src/http/savings-calibration.ts +277 -0
  189. package/src/http/savings.ts +849 -0
  190. package/src/http/scripts.ts +26 -15
  191. package/src/http/tasks.ts +89 -9
  192. package/src/http/trackers/authorize-gate.ts +41 -0
  193. package/src/http/trackers/jira.ts +26 -4
  194. package/src/http/trackers/linear.ts +26 -4
  195. package/src/integrations/chat-sdk/limits.ts +6 -1
  196. package/src/jira/oauth.ts +7 -1
  197. package/src/linear/README.md +2 -1
  198. package/src/linear/oauth.ts +7 -1
  199. package/src/prompts/session-templates.ts +80 -3
  200. package/src/providers/acp-targets.ts +1 -1
  201. package/src/providers/amp-adapter.ts +1 -1
  202. package/src/providers/claude-adapter.ts +0 -20
  203. package/src/providers/claude-flag-settings.ts +12 -10
  204. package/src/providers/codex-adapter.ts +12 -34
  205. package/src/providers/opencode-adapter.ts +34 -12
  206. package/src/providers/pi-mono-adapter.ts +6 -5
  207. package/src/providers/types.ts +7 -0
  208. package/src/scheduler/scheduler.ts +20 -14
  209. package/src/scripts-runtime/ctx.ts +1 -1
  210. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  211. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  212. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  213. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  214. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  215. package/src/scripts-runtime/stdlib/index.ts +3 -1
  216. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  217. package/src/scripts-runtime/swarm-sdk.ts +192 -17
  218. package/src/scripts-runtime/types/stdlib.d.ts +95 -4
  219. package/src/scripts-runtime/types/swarm-extension.d.ts +60 -0
  220. package/src/scripts-runtime/types/swarm-sdk.d.ts +69 -2
  221. package/src/slack/actions.ts +1 -0
  222. package/src/slack/assistant.ts +2 -0
  223. package/src/slack/enrich.ts +144 -50
  224. package/src/slack/handlers.ts +37 -95
  225. package/src/slack/templates.ts +9 -0
  226. package/src/slack/thread-buffer.ts +45 -71
  227. package/src/slack/thread-participants.ts +187 -0
  228. package/src/tasks/worker-follow-up.ts +142 -3
  229. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  230. package/src/tests/apps-chart-shell.test.ts +170 -0
  231. package/src/tests/apps-icon.test.ts +156 -2
  232. package/src/tests/base-prompt.test.ts +5 -4
  233. package/src/tests/chat-sdk-relay.test.ts +12 -0
  234. package/src/tests/claude-adapter-binary.test.ts +7 -1
  235. package/src/tests/claude-adapter.test.ts +10 -64
  236. package/src/tests/claude-flag-settings.test.ts +15 -11
  237. package/src/tests/claude-hook-credentials.test.ts +0 -1
  238. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  239. package/src/tests/codex-adapter.test.ts +28 -78
  240. package/src/tests/comb-default.test.ts +6 -0
  241. package/src/tests/core-auth.test.ts +7 -6
  242. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  243. package/src/tests/db-client-busy-retry.test.ts +58 -6
  244. package/src/tests/db-task-read-contract.test.ts +2 -0
  245. package/src/tests/db-task-write-contract.test.ts +1 -0
  246. package/src/tests/deploy-guard.test.ts +154 -0
  247. package/src/tests/docs-index-footprint.test.js +3 -3
  248. package/src/tests/dreaming-learnings.test.ts +104 -0
  249. package/src/tests/extensions-pre-task.test.ts +4 -2
  250. package/src/tests/fetch-resolved-env.test.ts +47 -1
  251. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  252. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  253. package/src/tests/model-profiles-api.test.ts +1 -0
  254. package/src/tests/opencode-adapter.test.ts +53 -6
  255. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  256. package/src/tests/prompt-template-session.test.ts +17 -1
  257. package/src/tests/provider-error-class.test.ts +174 -0
  258. package/src/tests/runner-provider-fallback.test.ts +197 -0
  259. package/src/tests/runner-requester-profile.test.ts +139 -1
  260. package/src/tests/savings-calibration-api.test.ts +264 -0
  261. package/src/tests/savings-calibration.test.ts +201 -0
  262. package/src/tests/savings-compound.test.ts +774 -0
  263. package/src/tests/savings-compute.test.ts +215 -0
  264. package/src/tests/savings-fleet-latency.test.ts +143 -0
  265. package/src/tests/savings-fleet-read.test.ts +195 -0
  266. package/src/tests/savings-fleet-scale.test.ts +222 -0
  267. package/src/tests/savings-model.test.ts +499 -0
  268. package/src/tests/savings-read.test.ts +367 -0
  269. package/src/tests/savings-rollup.test.ts +766 -0
  270. package/src/tests/savings-scripts.test.ts +611 -0
  271. package/src/tests/script-connections.test.ts +4 -0
  272. package/src/tests/script-executor-conformance.test.ts +444 -0
  273. package/src/tests/scripts-http.test.ts +55 -0
  274. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  275. package/src/tests/sdk-allowlist.test.ts +40 -0
  276. package/src/tests/secret-rules.test.ts +124 -1
  277. package/src/tests/secret-scrubber.test.ts +1 -1
  278. package/src/tests/seed-workflows.test.ts +167 -11
  279. package/src/tests/skill-parser.test.ts +45 -0
  280. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  281. package/src/tests/slack-identity-resolution.test.ts +23 -0
  282. package/src/tests/slack-inbound-files.test.ts +2 -1
  283. package/src/tests/slack-thread-participants.test.ts +429 -0
  284. package/src/tests/tool-annotations.test.ts +30 -0
  285. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  286. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  287. package/src/tests/workflow-script-principal.test.ts +94 -4
  288. package/src/tools/app-upsert.ts +1 -1
  289. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  290. package/src/tools/update-profile.ts +1 -1
  291. package/src/types.ts +146 -33
  292. package/src/utils/constants.ts +2 -0
  293. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  294. package/src/utils/mcp-server-fetcher.ts +13 -5
  295. package/src/utils/request-auth-context.ts +24 -0
  296. package/src/utils/secret-rules.generated.ts +1 -1
  297. package/src/utils/secret-scrubber.ts +154 -29
  298. package/src/workflows/executors/swarm-script.ts +23 -19
  299. package/templates/skills/apps/SKILL.md +62 -3
  300. package/templates/skills/apps/content.md +62 -3
  301. package/templates/skills/swarm-docs/content.md +2 -0
  302. package/templates/skills/swarm-scripts/SKILL.md +5 -4
  303. package/templates/skills/swarm-scripts/content.md +5 -4
  304. package/templates/skills/work-on-task/SKILL.md +1 -1
  305. package/templates/skills/work-on-task/content.md +1 -1
  306. package/templates/workflows/dreaming/content.md +1 -1
  307. package/dist/acp-adapter-pdy3qsvg.js +0 -15
  308. package/dist/cli-4bd1rck6.js +0 -4
  309. package/dist/cli-jywyhqws.js +0 -104
  310. package/dist/fx-adapter-3q12snn6.js +0 -18
  311. package/dist/grok-adapter-ahb1w033.js +0 -18
  312. package/dist/handlers-vbww69re.js +0 -32
  313. package/dist/index-4xwaf5th.js +0 -32
  314. package/dist/index-f0hcrs8e.js +0 -33
  315. package/dist/index-s4ewdma4.js +0 -37
  316. package/dist/lead-6ygbfhbh.js +0 -70
  317. package/dist/worker-mz5z7kj0.js +0 -70
  318. package/src/providers/ctx-mode-env.ts +0 -10
@@ -54,7 +54,6 @@ import {
54
54
  } from "./claude-flag-settings";
55
55
  import { normalizeClaudeMessage } from "./claude-session-events";
56
56
  import { resolveSlashSkillPrompt } from "./codex-skill-resolver";
57
- import { CTX_MODE_NUDGE_EVERY } from "./ctx-mode-env";
58
57
  import { buildOtelTraceparentEnv, isHarnessOtelEnabled } from "./otel-env";
59
58
  import { applyReasoningEffort, type ReasoningEffort } from "./reasoning-effort";
60
59
  import type {
@@ -648,24 +647,6 @@ export async function createSessionMcpConfig(
648
647
 
649
648
  if (Object.keys(mergedServers).length === 0 && !installedServers) return null;
650
649
 
651
- // Inject the context-mode stdio MCP server so its `ctx_*` tools survive
652
- // `--strict-mcp-config` (which restricts Claude to this file and structurally
653
- // excludes plugin-provided MCP servers). The plugin's hooks still fire via the
654
- // installed Claude plugin — strict-mcp-config only suppresses MCP servers, not
655
- // hooks. Placed BEFORE mergeMcpConfig so an API-installed server can still
656
- // override it (unlikely, but safe). Gated by CONTEXT_MODE_DISABLED so builds
657
- // and deploys without context-mode don't break; the same flag turns the plugin
658
- // (and so its hooks) off via `claudeFlagSettings()`.
659
- //
660
- // Server key uses the plugin naming convention (`plugin_context-mode_context-mode`)
661
- // so that the resulting tool names (`mcp__plugin_context-mode_context-mode__ctx_*`)
662
- // match the names the plugin's hooks reference in guidance text. With the bare
663
- // key `context-mode`, the tools would be `mcp__context-mode__ctx_*` — callable,
664
- // but invisible to the hook nudges that point agents at the plugin-prefixed name.
665
- if (!isEnvFlagEnabled("CONTEXT_MODE_DISABLED", false)) {
666
- mergedServers["plugin_context-mode_context-mode"] = { command: "context-mode" };
667
- }
668
-
669
650
  try {
670
651
  const config = mergeMcpConfig(
671
652
  { mcpServers: mergedServers },
@@ -803,7 +784,6 @@ export function buildClaudeSessionEnvironment(
803
784
  AGENT_SWARM_TASK_ID: config.taskId,
804
785
  AGENT_SWARM_AGENT_ID: config.agentId,
805
786
  AGENT_SWARM_ADAPTER_SESSION_SUMMARY: "1",
806
- CONTEXT_MODE_EXTERNAL_MCP_NUDGE_EVERY: CTX_MODE_NUDGE_EVERY,
807
787
  } as Record<string, string>,
808
788
  appliedReasoningEffort:
809
789
  reasoningApplication.kind === "claude-env" ? (config.reasoningEffort ?? null) : null,
@@ -1,7 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
- import { isEnvFlagEnabled } from "../utils/env-flag";
5
4
  import { scrubSecrets } from "../utils/secret-scrubber";
6
5
 
7
6
  /**
@@ -28,8 +27,13 @@ export function userClaudeMdExclude(home: string = process.env.HOME ?? homedir()
28
27
  return join(home, ".claude", "CLAUDE.md");
29
28
  }
30
29
 
31
- /** Plugin id the worker image installs (`claude plugin install context-mode@context-mode`). */
32
- export const CONTEXT_MODE_CLAUDE_PLUGIN = "context-mode@context-mode";
30
+ /**
31
+ * Plugin id older worker images installed (`claude plugin install
32
+ * context-mode@context-mode`). context-mode is removed, but a HOME carried
33
+ * over from such an image still has the plugin installed, and its hooks
34
+ * would point the session at `ctx_*` tools it no longer gets.
35
+ */
36
+ export const LEGACY_CONTEXT_MODE_CLAUDE_PLUGIN = "context-mode@context-mode";
33
37
 
34
38
  export type ClaudeFlagSettings = Record<string, unknown> & {
35
39
  claudeMdExcludes: string[];
@@ -39,17 +43,15 @@ export type ClaudeFlagSettings = Record<string, unknown> & {
39
43
  /**
40
44
  * Flag-level settings (`--settings` / SDK `settings`) for every Claude session.
41
45
  *
42
- * `CONTEXT_MODE_DISABLED` also turns the context-mode plugin off for the
43
- * session. Dropping only its MCP server left the plugin hooks running: the
44
- * SessionStart block and tool tips pointed at `ctx_*` tools the session did
45
- * not have, and the PreToolUse hook denied WebFetch.
46
+ * Always turns the legacy context-mode plugin off. A stale install would
47
+ * otherwise keep its hooks running: the SessionStart block and tool tips
48
+ * point at `ctx_*` tools the session does not have, and the PreToolUse hook
49
+ * denies WebFetch. Disabling a plugin that is not installed is a no-op.
46
50
  */
47
51
  export function claudeFlagSettings(): ClaudeFlagSettings {
48
52
  return {
49
53
  claudeMdExcludes: [WORKSPACE_CLAUDE_MD_EXCLUDE, userClaudeMdExclude()],
50
- ...(isEnvFlagEnabled("CONTEXT_MODE_DISABLED", false)
51
- ? { enabledPlugins: { [CONTEXT_MODE_CLAUDE_PLUGIN]: false } }
52
- : {}),
54
+ enabledPlugins: { [LEGACY_CONTEXT_MODE_CLAUDE_PLUGIN]: false },
53
55
  };
54
56
  }
55
57
 
@@ -47,7 +47,7 @@ import {
47
47
  computeContextUsedUnified,
48
48
  } from "../utils/context-window";
49
49
  import { selectCredential } from "../utils/credentials";
50
- import { isEnvFlagEnabled, isSessionSummarySkipped } from "../utils/env-flag";
50
+ import { isSessionSummarySkipped } from "../utils/env-flag";
51
51
  import { SessionErrorTracker } from "../utils/error-tracker";
52
52
  import { summarizeSession as runSummarize } from "../utils/internal-ai";
53
53
  import { getMemoryRaterNames } from "../utils/memory-raters";
@@ -72,7 +72,6 @@ import { buildPoolRevalidationFailureReason, getValidCodexOAuth } from "./codex-
72
72
  import { pruneCodexRollouts } from "./codex-rollouts";
73
73
  import { resolveCodexPrompt } from "./codex-skill-resolver";
74
74
  import { createCodexSwarmEventHandler } from "./codex-swarm-events";
75
- import { CTX_MODE_NUDGE_EVERY } from "./ctx-mode-env";
76
75
  import { readPkgVersion } from "./harness-version";
77
76
  import { buildOtelTraceparentEnv } from "./otel-env";
78
77
  import { applyReasoningEffort, type ReasoningEffort } from "./reasoning-effort";
@@ -120,8 +119,12 @@ export function codexGatewayConfig(route: ModelRoute): CodexConfig {
120
119
  };
121
120
  }
122
121
 
123
- /** Plugin id the worker image installs (`codex plugin add context-mode@context-mode`). */
124
- const CONTEXT_MODE_CODEX_PLUGIN = "context-mode@context-mode";
122
+ /**
123
+ * Plugin id older worker images installed (`codex plugin add
124
+ * context-mode@context-mode`). context-mode is removed; every session turns a
125
+ * stale install off so its MCP server, skills and hooks never load.
126
+ */
127
+ const LEGACY_CONTEXT_MODE_CODEX_PLUGIN = "context-mode@context-mode";
125
128
 
126
129
  interface Usage {
127
130
  input_tokens: number;
@@ -567,29 +570,6 @@ export async function buildCodexConfig(
567
570
  }
568
571
  }
569
572
 
570
- // (4) context-mode — pre-installed stdio MCP server providing the `ctx_*`
571
- // context-compression tools. Gated by `CONTEXT_MODE_DISABLED` so builds /
572
- // deploys without the `context-mode` binary on PATH don't break the session.
573
- // Same entry shape as the swarm + installed-server stdio entries above.
574
- // When disabled, the installed Codex plugin is turned off too: it registers
575
- // its own `context-mode` MCP server, skills and hooks.
576
- // Read `config.env` first: production builds this config inside the
577
- // `codex-session-runner` subprocess, whose `process.env` is a minimal
578
- // allowlist. Swarm config rows (agent-scoped included) only arrive there
579
- // through `config.env`.
580
- const contextModeDisabled = isEnvFlagEnabled("CONTEXT_MODE_DISABLED", false, {
581
- ...process.env,
582
- ...config.env,
583
- });
584
- if (!contextModeDisabled) {
585
- mcpServers["context-mode"] = {
586
- command: "context-mode",
587
- enabled: true,
588
- startup_timeout_sec: 30,
589
- tool_timeout_sec: 120,
590
- };
591
- }
592
-
593
573
  // Phase 4 (reasoning-effort plan): translate the normalized level into
594
574
  // `model_reasoning_effort`. `show_raw_agent_reasoning` stays pinned false
595
575
  // regardless — separate, deliberately-pinned knob, not in scope here.
@@ -602,8 +582,7 @@ export async function buildCodexConfig(
602
582
  // (no baseline file) behave identically to the Docker worker.
603
583
  //
604
584
  // Keep ChatGPT apps/connectors disabled because their `codex_apps` tools use
605
- // the worker's host OAuth identity. Hooks remain enabled for Codex steering
606
- // and the installed context-mode plugin.
585
+ // the worker's host OAuth identity. Hooks remain enabled for Codex steering.
607
586
  return {
608
587
  model,
609
588
  approval_policy: "never",
@@ -612,9 +591,7 @@ export async function buildCodexConfig(
612
591
  show_raw_agent_reasoning: false,
613
592
  features: { apps: false, hooks: true, plugin_hooks: true },
614
593
  mcp_servers: mcpServers as CodexConfig,
615
- ...(contextModeDisabled
616
- ? { plugins: { [CONTEXT_MODE_CODEX_PLUGIN]: { enabled: false } } }
617
- : {}),
594
+ plugins: { [LEGACY_CONTEXT_MODE_CODEX_PLUGIN]: { enabled: false } },
618
595
  ...reasoningConfig,
619
596
  };
620
597
  }
@@ -1770,6 +1747,9 @@ export class CodexSession implements ProviderSession {
1770
1747
  sessionId: this._sessionId,
1771
1748
  cost,
1772
1749
  isError: true,
1750
+ // Provider failures arrive as turn.failed / error events (terminalError,
1751
+ // handled above); a throw with none is the app-server or MCP transport.
1752
+ errorOrigin: "harness",
1773
1753
  failureReason: message,
1774
1754
  rateLimitResetAt: this.errorTracker.getRateLimitResetAt(),
1775
1755
  rateLimitWindows: this.errorTracker.getRateLimitWindows(),
@@ -2024,7 +2004,6 @@ export async function createInProcessCodexSession(
2024
2004
  ...(process.env.NODE_EXTRA_CA_CERTS
2025
2005
  ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS }
2026
2006
  : {}),
2027
- CONTEXT_MODE_EXTERNAL_MCP_NUDGE_EVERY: CTX_MODE_NUDGE_EVERY,
2028
2007
  ...(config.env ?? {}),
2029
2008
  // Gated cross-service OTel linking: when SWARM_ENABLE_HARNESS_OTEL (or
2030
2009
  // the deprecated SWARM_ENABLE_CLAUDE_CODE_OTEL alias) is on, inject
@@ -2228,7 +2207,6 @@ class CodexSubprocessSession implements ProviderSession {
2228
2207
  ...(process.env.CODEX_SKILLS_DIR
2229
2208
  ? { CODEX_SKILLS_DIR: process.env.CODEX_SKILLS_DIR }
2230
2209
  : {}),
2231
- CONTEXT_MODE_EXTERNAL_MCP_NUDGE_EVERY: CTX_MODE_NUDGE_EVERY,
2232
2210
  ...(process.env.SKIP_SESSION_SUMMARY
2233
2211
  ? { SKIP_SESSION_SUMMARY: process.env.SKIP_SESSION_SUMMARY }
2234
2212
  : {}),
@@ -32,7 +32,7 @@ import {
32
32
  splitCredentialPool,
33
33
  validateOpencodeCredentials,
34
34
  } from "../utils/credentials";
35
- import { isEnvFlagEnabled, isSessionSummarySkipped } from "../utils/env-flag";
35
+ import { isSessionSummarySkipped } from "../utils/env-flag";
36
36
  import { fetchInstalledMcpServers } from "../utils/mcp-server-fetcher";
37
37
  import { swarmRuntimeInstanceId } from "../utils/multi-runtime";
38
38
  import {
@@ -40,9 +40,9 @@ import {
40
40
  getOpenRouterAttributionHeaders,
41
41
  getOpenRouterBaseUrl,
42
42
  } from "../utils/openrouter-base-url";
43
+ import { snapshotCatalogRows } from "../utils/runtime-model-catalog";
43
44
  import { registerVolatileSecret, scrubSecrets } from "../utils/secret-scrubber";
44
45
  import { resolveSlashSkillPrompt } from "./codex-skill-resolver";
45
- import { CTX_MODE_NUDGE_EVERY } from "./ctx-mode-env";
46
46
  import { OpenRouterBilling } from "./opencode-billing";
47
47
  import { createOpencodeSwarmPlugin, type OpencodeToolLister } from "./opencode-swarm-plugin";
48
48
  import {
@@ -369,6 +369,38 @@ export function applyProviderKeySplice(
369
369
  const slash = model?.indexOf("/") ?? -1;
370
370
  if (!model || slash <= 0) return undefined;
371
371
  const providerId = model.slice(0, slash);
372
+ const modelId = model.slice(slash + 1);
373
+
374
+ // OpenCode's built-in openrouter catalog only lists models.dev's OpenRouter
375
+ // section. A model id reached through a gateway override (OPENROUTER_BASE_URL,
376
+ // e.g. a LiteLLM route) can be absent from it, so OpenCode fails the session
377
+ // instead of running the requested model (the same gap buildOpenAICompatibleProviderBlock
378
+ // already closes for custom-block providers). This runs before any key-splice
379
+ // early return below: a credential opencode reads from its own
380
+ // `~/.local/share/opencode/auth.json` never reaches `pickProviderKey`, so a
381
+ // catalog entry computed only on the success path would never be written for
382
+ // that credential source. Only synthesize a bare entry for ids truly missing
383
+ // from the catalog snapshot; an id the catalog already lists (even one it
384
+ // marks non-tool-calling) keeps its real capability flags instead of a
385
+ // blanket `tool_call: true`.
386
+ if (
387
+ providerId === "openrouter" &&
388
+ modelId &&
389
+ !opencodeConfig.provider?.openrouter?.models?.[modelId] &&
390
+ !snapshotCatalogRows("openrouter")[modelId]
391
+ ) {
392
+ opencodeConfig.provider = {
393
+ ...opencodeConfig.provider,
394
+ openrouter: {
395
+ ...opencodeConfig.provider?.openrouter,
396
+ models: {
397
+ ...opencodeConfig.provider?.openrouter?.models,
398
+ [modelId]: { name: modelId, tool_call: true },
399
+ },
400
+ },
401
+ };
402
+ }
403
+
372
404
  const existing = opencodeConfig.provider?.[providerId];
373
405
 
374
406
  const custom = customBlockProvider(providerId);
@@ -930,16 +962,6 @@ export class OpencodeAdapter implements ProviderAdapter {
930
962
  },
931
963
  ...installedMcp,
932
964
  };
933
- // context-mode ships only a V1 opencode plugin, which OpenCode 2 cannot
934
- // load, so wire its stdio MCP server instead (same as codex).
935
- if (!isEnvFlagEnabled("CONTEXT_MODE_DISABLED", false)) {
936
- mcp["context-mode"] = {
937
- type: "local",
938
- command: ["context-mode"],
939
- environment: { CONTEXT_MODE_EXTERNAL_MCP_NUDGE_EVERY: CTX_MODE_NUDGE_EVERY },
940
- };
941
- }
942
-
943
965
  const opencodeConfig: OpencodeConfig = {
944
966
  $schema: "https://opencode.ai/config.json",
945
967
  model: config.model,
@@ -1466,11 +1466,11 @@ export class PiMonoSession implements ProviderSession {
1466
1466
  appliedReasoningEffort: this.appliedReasoningEffort,
1467
1467
  };
1468
1468
  }
1469
- // Defense-in-depth: AWS SDK failures surface as structured events (handled
1470
- // above in runSession), not thrown exceptions, so this catch is for genuine
1471
- // unexpected throws (MCP / transport / etc). Still classify in case an AWS
1472
- // signature or a rejected subscription login ever reaches here, so the
1473
- // red box fires like sibling adapters.
1469
+ // Provider failures (AWS SDK, a rejected subscription login) arrive as
1470
+ // structured events (the terminalError path above), so a throw here is
1471
+ // MCP, transport or the harness itself. Classify it only for the red
1472
+ // box: an MCP "HTTP 401 Unauthorized" reads like a rejected login but
1473
+ // says nothing about the provider, so the origin stays "harness".
1474
1474
  const classifiedError = this.classifyFailure(errorMessage);
1475
1475
  if (classifiedError) {
1476
1476
  this.emit({
@@ -1488,6 +1488,7 @@ export class PiMonoSession implements ProviderSession {
1488
1488
  cost,
1489
1489
  isError: true,
1490
1490
  errorCategory: classifiedError?.category,
1491
+ errorOrigin: "harness",
1491
1492
  failureReason: scrubSecrets(classifiedError?.message ?? errorMessage),
1492
1493
  appliedReasoningEffort: this.appliedReasoningEffort,
1493
1494
  };
@@ -213,6 +213,13 @@ export interface ProviderResult {
213
213
  output?: string;
214
214
  isError: boolean;
215
215
  errorCategory?: string;
216
+ /**
217
+ * `harness`: the session ended on an exception the adapter did not trace to
218
+ * the model provider (MCP or tool transport, the harness's own IPC). Its
219
+ * text never moves the task to a fallback profile. Unset: a provider
220
+ * response or the adapter's own error tracking decided the failure.
221
+ */
222
+ errorOrigin?: "harness";
216
223
  /** Human-readable failure reason built from error tracking. */
217
224
  failureReason?: string;
218
225
  /**
@@ -91,6 +91,8 @@ export async function executeScheduleScript(schedule: ScheduledTask): Promise<vo
91
91
  const agentId = schedule.createdByAgentId ?? "schedule";
92
92
  const args = schedule.scriptArgs ?? {};
93
93
  const record = {
94
+ // Fixed before the run so rows the script creates can point at it.
95
+ id: crypto.randomUUID(),
94
96
  agentId,
95
97
  scriptName: schedule.scriptName,
96
98
  // A pointer, not a copy: script schedules fire as often as every minute and
@@ -105,19 +107,22 @@ export async function executeScheduleScript(schedule: ScheduledTask): Promise<vo
105
107
  let output: Awaited<ReturnType<typeof runScriptWithRunCredential>>;
106
108
  try {
107
109
  const credentials = await buildScriptCredentialBindingsWithFailures({ agentId });
108
- output = await runScriptWithRunCredential({
109
- source: script.source,
110
- args,
111
- fsMode: "none",
112
- executor: script.executor,
113
- agentId,
114
- egressSecrets: credentials.egressSecrets,
115
- userConfig: credentials.userConfig,
116
- agentFs: credentials.agentFs,
117
- apiConnections: getScriptApiConnectionDescriptors({ agentId }),
118
- mcpConnections: getScriptMcpConnectionDescriptors({ agentId }),
119
- timeoutMs: 60_000,
120
- });
110
+ output = await runScriptWithRunCredential(
111
+ {
112
+ source: script.source,
113
+ args,
114
+ fsMode: "none",
115
+ executor: script.executor,
116
+ agentId,
117
+ egressSecrets: credentials.egressSecrets,
118
+ userConfig: credentials.userConfig,
119
+ agentFs: credentials.agentFs,
120
+ apiConnections: getScriptApiConnectionDescriptors({ agentId }),
121
+ mcpConnections: getScriptMcpConnectionDescriptors({ agentId }),
122
+ timeoutMs: 60_000,
123
+ },
124
+ { sourceScriptRunId: record.id },
125
+ );
121
126
  } catch (err) {
122
127
  await recordScheduleScriptRun({
123
128
  ...record,
@@ -151,6 +156,7 @@ export async function executeScheduleScript(schedule: ScheduledTask): Promise<vo
151
156
  * Best effort: a persistence error never changes the schedule's outcome.
152
157
  */
153
158
  async function recordScheduleScriptRun(run: {
159
+ id: string;
154
160
  agentId: string;
155
161
  scriptName: string;
156
162
  source: string;
@@ -162,7 +168,7 @@ async function recordScheduleScriptRun(run: {
162
168
  }): Promise<void> {
163
169
  try {
164
170
  await recordInlineScriptRun({
165
- id: crypto.randomUUID(),
171
+ id: run.id,
166
172
  agentId: run.agentId,
167
173
  scriptName: run.scriptName,
168
174
  source: run.source,
@@ -45,7 +45,7 @@ export function buildCtx({
45
45
  /** Aborts in-flight `ctx.sh` commands when the run ends (quickjs passes its run signal). */
46
46
  signal?: AbortSignal;
47
47
  }): RuntimeCtx {
48
- const swarm = Object.assign(createSwarmSdk(swarmConfig), { config: swarmConfig });
48
+ const swarm = Object.assign(createSwarmSdk(swarmConfig, { signal }), { config: swarmConfig });
49
49
  const { fs, sh } = createScriptFs(agentFs, signal);
50
50
  return {
51
51
  swarm,
@@ -23,6 +23,7 @@ export const fetchJson = s.fetchJson;
23
23
  export const glob = s.glob;
24
24
  export const grep = s.grep;
25
25
  export const table = s.table;
26
+ export const retry = s.retry;
26
27
  export const Redacted = s.Redacted;
27
28
  `;
28
29
 
@@ -245,15 +245,175 @@ const toRequest = (input, init) => {
245
245
  };
246
246
  const fetch = async (input, init) => new Response(await hostCall("fetch", [toRequest(input, init)]));
247
247
 
248
+ // ── retry (mirrors stdlib/retry.ts; sleeps on the host clock) ──
249
+ const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
250
+ const retryAfterMs = (value) => {
251
+ if (value === null || value === undefined) return undefined;
252
+ const trimmed = String(value).trim();
253
+ if (trimmed === "") return undefined;
254
+ if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.round(Number(trimmed) * 1000);
255
+ const date = Date.parse(trimmed);
256
+ return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
257
+ };
258
+ const failedStatus = (value) => {
259
+ if (!value || typeof value !== "object") return undefined;
260
+ if (typeof value.status !== "number") return undefined;
261
+ if (value.ok !== false && value.success !== false) return undefined;
262
+ const headers = value.headers;
263
+ let retryAfter;
264
+ if (headers && typeof headers.get === "function") retryAfter = headers.get("retry-after");
265
+ else if (headers && typeof headers === "object" && typeof headers["retry-after"] === "string") retryAfter = headers["retry-after"];
266
+ return { status: value.status, retryAfter };
267
+ };
268
+ const checkNumber = (name, value, fallback, integer) => {
269
+ if (value === undefined) return fallback;
270
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
271
+ throw new TypeError("retry: \x60" + name + "\x60 must be a non-negative number");
272
+ }
273
+ if (integer && !Number.isInteger(value)) {
274
+ throw new TypeError("retry: \x60" + name + "\x60 must be a non-negative integer");
275
+ }
276
+ return value;
277
+ };
278
+ // No AbortController in the sandbox, so any object with aborted / reason /
279
+ // addEventListener works as a signal. The host sleep cannot be cancelled; the
280
+ // wait just stops listening to it, and the run's close() ends it.
281
+ const abortReason = (signal) => {
282
+ if (signal.reason !== undefined) return signal.reason;
283
+ const error = new Error("This operation was aborted");
284
+ error.name = "AbortError";
285
+ return error;
286
+ };
287
+ const abortableSleep = (ms, signal) => {
288
+ if (!signal) return __host_sleep(ms);
289
+ return new Promise((resolve, reject) => {
290
+ if (signal.aborted) return reject(abortReason(signal));
291
+ let settled = false;
292
+ const onAbort = () => {
293
+ if (settled) return;
294
+ settled = true;
295
+ reject(abortReason(signal));
296
+ };
297
+ if (typeof signal.addEventListener === "function") signal.addEventListener("abort", onAbort, { once: true });
298
+ __host_sleep(ms).then(() => {
299
+ if (typeof signal.removeEventListener === "function") signal.removeEventListener("abort", onAbort);
300
+ if (settled) return;
301
+ settled = true;
302
+ if (signal.aborted) reject(abortReason(signal));
303
+ else resolve();
304
+ });
305
+ });
306
+ };
307
+ const retryCall = async (fn, options) => {
308
+ if (typeof fn !== "function") throw new TypeError("retry: first argument must be a function");
309
+ const opts = options || {};
310
+ const retries = checkNumber("retries", opts.retries, 3, true);
311
+ const minDelayMs = checkNumber("minDelayMs", opts.minDelayMs, 200, false);
312
+ const maxDelayMs = checkNumber("maxDelayMs", opts.maxDelayMs, 5000, false);
313
+ const budgetMs = checkNumber("budgetMs", opts.budgetMs, 30000, false);
314
+ const retryOn = opts.retryOn;
315
+ if (retryOn !== undefined && typeof retryOn !== "function") {
316
+ throw new TypeError("retry: \x60retryOn\x60 must be a function");
317
+ }
318
+ const signal = opts.signal;
319
+ const started = Date.now();
320
+ for (let attempt = 1; ; attempt++) {
321
+ if (signal && signal.aborted) throw abortReason(signal);
322
+ let threw = false;
323
+ let value;
324
+ try {
325
+ value = await fn(attempt);
326
+ } catch (error) {
327
+ threw = true;
328
+ value = error;
329
+ }
330
+ const settle = () => {
331
+ if (threw) throw value;
332
+ return value;
333
+ };
334
+ if (attempt > retries) return settle();
335
+ const info = threw ? undefined : failedStatus(value);
336
+ const again = retryOn ? await retryOn(value, attempt) : threw || (info !== undefined && RETRYABLE_STATUSES.has(info.status));
337
+ if (!again) return settle();
338
+ const waitFor = info && info.status === 429 ? retryAfterMs(info.retryAfter) : undefined;
339
+ const ceiling = Math.min(maxDelayMs, minDelayMs * 2 ** (attempt - 1));
340
+ const delay = waitFor !== undefined ? Math.min(maxDelayMs, waitFor) : Math.round(ceiling / 2 + (Math.random() * ceiling) / 2);
341
+ if (Date.now() - started + delay > budgetMs) return settle();
342
+ await abortableSleep(delay, signal);
343
+ }
344
+ };
345
+ const retry = Object.assign(retryCall, {
346
+ wrap(fn, options) {
347
+ if (typeof fn !== "function") throw new TypeError("retry.wrap: first argument must be a function");
348
+ return (...args) => retryCall(() => fn(...args), options);
349
+ },
350
+ });
351
+
248
352
  const unavailable = (name) => () => {
249
353
  throw new Error(name + " is not available in the quickjs executor (no filesystem access)");
250
354
  };
355
+ // stdlib.fetch retries in the sandbox, so a retryOn function runs here and the
356
+ // waits use the host clock. Mirrors runtimeFetch in stdlib/fetch.ts. Bodies are
357
+ // serialized once, so every sandbox body can be replayed.
358
+ const IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
359
+ const TRANSIENT_5XX = new Set([502, 503, 504]);
360
+ const stdlibFetch = async (input, options) => {
361
+ const opts = options || {};
362
+ const retryOption = opts.retry;
363
+ let config = {};
364
+ if (retryOption === false) config = { retries: 0 };
365
+ else if (retryOption && typeof retryOption === "object") config = retryOption;
366
+ else if (retryOption === undefined && opts.retries !== undefined) config = { retries: Math.max(0, opts.retries - 1) };
367
+ const { idempotencyKey, retryOn: userRetryOn, ...retryOptions } = config;
368
+ const init = { ...opts };
369
+ delete init.retry;
370
+ delete init.retries;
371
+ const headerMap = new Headers(opts.headers);
372
+ if (idempotencyKey && !headerMap.has("idempotency-key")) {
373
+ headerMap.set("idempotency-key", idempotencyKey === true ? randomUUID() : String(idempotencyKey));
374
+ init.headers = headerMap;
375
+ }
376
+ const method = String(opts.method || "GET").toUpperCase();
377
+ const repeatSafe = IDEMPOTENT_METHODS.has(method) || headerMap.has("idempotency-key");
378
+ const request = toRequest(input, init);
379
+ request.retry = false;
380
+ // The signal cannot reach the host fetch, so an abort lands between attempts.
381
+ const signal = opts.signal || retryOptions.signal;
382
+ return retryCall(async () => {
383
+ let response;
384
+ try {
385
+ response = new Response(await hostCall("stdlib.fetch", [request]));
386
+ } catch (error) {
387
+ if (signal && signal.aborted) throw abortReason(signal);
388
+ throw error;
389
+ }
390
+ if (signal && signal.aborted) throw abortReason(signal);
391
+ return response;
392
+ }, {
393
+ ...retryOptions,
394
+ signal,
395
+ retryOn: async (value, attempt) => {
396
+ if (signal && signal.aborted) return false;
397
+ if (userRetryOn) return userRetryOn(value, attempt);
398
+ if (value instanceof Response) return value.status === 429 || (repeatSafe && TRANSIENT_5XX.has(value.status));
399
+ return repeatSafe;
400
+ },
401
+ });
402
+ };
403
+ const stdlibFetchJson = async (input, options) => {
404
+ const response = await stdlibFetch(input, options);
405
+ const contentType = response.headers.get("content-type") || "";
406
+ const text = await response.text();
407
+ return contentType.includes("application/json") ? JSON.parse(text) : text;
408
+ };
409
+
251
410
  const stdlib = Object.freeze({
252
- fetch: async (input, options) => new Response(await hostCall("stdlib.fetch", [toRequest(input, options)])),
253
- fetchJson: async (input, options) => hostCall("stdlib.fetchJson", [toRequest(input, options)]),
411
+ fetch: stdlibFetch,
412
+ fetchJson: stdlibFetchJson,
254
413
  glob: unavailable("ctx.stdlib.glob"),
255
414
  grep: unavailable("ctx.stdlib.grep"),
256
415
  table: (rows) => hostSync("table", rows),
416
+ retry,
257
417
  Redacted,
258
418
  });
259
419
 
@@ -158,6 +158,8 @@ type SandboxRequest = {
158
158
  /** Binary body, base64-encoded by the sandbox. */
159
159
  bodyBase64?: string;
160
160
  retries?: number;
161
+ /** The sandbox retries stdlib fetches itself and sends `false`: one host attempt each. */
162
+ retry?: boolean;
161
163
  timeoutMs?: number;
162
164
  };
163
165
 
@@ -234,7 +236,8 @@ async function dispatchCall(
234
236
  ? await fetch(request.url, { ...requestInit(request), signal })
235
237
  : await runtimeFetch(request.url, {
236
238
  ...requestInit(request),
237
- retries: request.retries,
239
+ // Only `false` crosses the boundary: retry options hold functions.
240
+ ...(request.retry === false ? { retry: false } : { retries: request.retries }),
238
241
  timeoutMs: request.timeoutMs,
239
242
  signal,
240
243
  });
@@ -211,8 +211,18 @@ export const SDK_ALLOWLIST = Object.keys(SDK_TOOL_NAME_MAP) as Array<
211
211
  /** Set of MCP tool names (values of SDK_TOOL_NAME_MAP) that scripts may call via the bridge. */
212
212
  const MCP_TOOL_NAMES: ReadonlySet<string> = new Set<string>(Object.values(SDK_TOOL_NAME_MAP));
213
213
 
214
+ /**
215
+ * SDK methods backed by a REST route with no MCP tool, mapped in `bridgeRequestFor`.
216
+ * Scripts only: they are not in SDK_TOOL_NAME_MAP, so the MCP bridge, the workflow
217
+ * capability list and the MCP-tool registration check never see them.
218
+ */
219
+ export const REST_ONLY_SDK_METHODS = ["savings_calibrationGet", "savings_calibrationRun"] as const;
220
+
214
221
  export function isSdkToolAllowed(name: string): boolean {
215
- return (SDK_ALLOWLIST as readonly string[]).includes(name);
222
+ return (
223
+ (SDK_ALLOWLIST as readonly string[]).includes(name) ||
224
+ (REST_ONLY_SDK_METHODS as readonly string[]).includes(name)
225
+ );
216
226
  }
217
227
 
218
228
  /** True if `mcpToolName` (e.g. "trigger-workflow") corresponds to an allowlisted SDK method. */