@desplega.ai/agent-swarm 2.8.2 → 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 (258) hide show
  1. package/dist/acp-adapter-xq6s2z6t.js +14 -0
  2. package/dist/{actions-kxek041g.js → actions-ewz7bp4g.js} +20 -19
  3. package/dist/{amp-adapter-ce7jjke4.js → amp-adapter-f25tqhnf.js} +3 -3
  4. package/dist/{app-v6zz8yh0.js → app-mkptw0k7.js} +4 -4
  5. package/dist/{assistant-m0sw9xx2.js → assistant-c47rfe77.js} +23 -22
  6. package/dist/{boot-args-schema-66bk37wv.js → boot-args-schema-4vb0xsat.js} +1 -1
  7. package/dist/{boot-reembed-edjpwsc1.js → boot-reembed-1ghy2sab.js} +1 -1
  8. package/dist/{boot-reembed-y27n09tz.js → boot-reembed-htr73hbs.js} +1 -1
  9. package/dist/{boot-scrub-sweep-1xc35965.js → boot-scrub-sweep-yrytg42z.js} +4 -4
  10. package/dist/{boot-seeds-7hjj91qj.js → boot-seeds-n2b3dx4e.js} +4 -4
  11. package/dist/{boxd-ent8ch04.js → boxd-jmfqgkqa.js} +1 -1
  12. package/dist/{claude-adapter-stw7jdcf.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-y6z2perp.js → claude-managed-setup-hfvry1bd.js} +5 -5
  15. package/dist/{claude-sdk-session-vvya8wqk.js → claude-sdk-session-0hamqzc7.js} +10 -11
  16. package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
  17. package/dist/{cli-t2tma8gb.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-0cq8y6m7.js → cli-4ax9mvvg.js} +4 -4
  22. package/dist/{cli-tekytdq9.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-9mb2q6pb.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-kjtwrhea.js → cli-7c5tgqhf.js} +5 -5
  30. package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
  31. package/dist/{cli-zh9rsbqf.js → cli-922z7gwm.js} +3 -3
  32. package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
  33. package/dist/{cli-gyt3zydq.js → cli-9zmb7ptc.js} +9 -9
  34. package/dist/{cli-dzpc6en0.js → cli-am1ptset.js} +2 -2
  35. package/dist/{cli-w401b9tq.js → cli-awwptga4.js} +1 -1
  36. package/dist/{cli-26ctbcdp.js → cli-bhsfbmk8.js} +3 -3
  37. package/dist/{cli-mxn1qvbn.js → cli-bj6qhgte.js} +14 -32
  38. package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
  39. package/dist/{cli-jdknh18m.js → cli-c3ng0mb4.js} +13 -13
  40. package/dist/{cli-f4e8r23x.js → cli-c71n3bxq.js} +11 -6
  41. package/dist/{cli-6rc5frdm.js → cli-crpf163n.js} +25 -18
  42. package/dist/{cli-1qkz151v.js → cli-dpsfwh7n.js} +13 -21
  43. package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
  44. package/dist/{cli-a0z912j7.js → cli-e2w34h6z.js} +137 -62
  45. package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
  46. package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
  47. package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
  48. package/dist/{cli-vdektqgf.js → cli-gpz1d0t2.js} +4 -4
  49. package/dist/{cli-rcecc3yq.js → cli-h9yy18gy.js} +84 -36
  50. package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
  51. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  52. package/dist/{cli-b98a65ed.js → cli-k2rw11py.js} +3 -3
  53. package/dist/{cli-3e875j5p.js → cli-k96cecs7.js} +276 -47
  54. package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
  55. package/dist/{cli-3sy2xags.js → cli-kmemts3w.js} +12 -12
  56. package/dist/{cli-f6bahpn5.js → cli-knva3nmx.js} +2 -2
  57. package/dist/{cli-959kp5h2.js → cli-kw44j53p.js} +13 -13
  58. package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
  59. package/dist/{cli-2kvhc7x8.js → cli-me0r8gzr.js} +35 -76
  60. package/dist/{cli-4vzgeta4.js → cli-mwwmka77.js} +14 -14
  61. package/dist/{cli-q24n86d2.js → cli-n5t077me.js} +2 -2
  62. package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
  63. package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
  64. package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
  65. package/dist/{cli-n6vtrcht.js → cli-qmqt520k.js} +2 -2
  66. package/dist/{cli-pchypa1s.js → cli-qps8je6j.js} +17 -2
  67. package/dist/{cli-97ae65rz.js → cli-rjvsf9qa.js} +5 -5
  68. package/dist/{cli-e1p3n5gq.js → cli-rqfvkx5t.js} +6 -6
  69. package/dist/{cli-3vmb0n58.js → cli-s7zz734a.js} +1 -1
  70. package/dist/{cli-rmzsadkf.js → cli-s8p8hhty.js} +2 -2
  71. package/dist/{cli-j24zbska.js → cli-sdvcrq5x.js} +5 -5
  72. package/dist/{cli-5y340nzn.js → cli-sg27rk2t.js} +5 -5
  73. package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
  74. package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
  75. package/dist/{cli-z1w943va.js → cli-t5ys4ebm.js} +3 -3
  76. package/dist/{cli-f4r3g076.js → cli-tas6ckky.js} +2 -2
  77. package/dist/{cli-1pz0330a.js → cli-tf79ryyy.js} +1 -1
  78. package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
  79. package/dist/{cli-pfs8adn4.js → cli-vx421edw.js} +3 -3
  80. package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
  81. package/dist/cli-yss07azk.js +142 -0
  82. package/dist/{cli-fwy8kfd6.js → cli-z8cvws4c.js} +98 -16
  83. package/dist/{cli-g5mtmf6t.js → cli-zdaypkq9.js} +146 -52
  84. package/dist/{cli-fpjmegdb.js → cli-zeaehgyd.js} +2 -2
  85. package/dist/{cli-837vfs2x.js → cli-ztq5z4e1.js} +4 -4
  86. package/dist/cli.js +20 -20
  87. package/dist/{codex-adapter-zerf5qsp.js → codex-adapter-2brxx5ta.js} +7 -8
  88. package/dist/{codex-hook-30gyhzxe.js → codex-hook-c930c3ea.js} +1 -1
  89. package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
  90. package/dist/{codex-session-runner-89s304py.js → codex-session-runner-y9anfj0r.js} +8 -9
  91. package/dist/{commands-jeh1b51j.js → commands-wn9q06qr.js} +3 -3
  92. package/dist/{controller-mctfbrse.js → controller-fw608czd.js} +4 -4
  93. package/dist/{controllers-connect-nxa1ddwn.js → controllers-connect-63j5rdcm.js} +20 -20
  94. package/dist/{cursor-adapter-qj8vehv6.js → cursor-adapter-6mb9jme8.js} +2 -2
  95. package/dist/{db-2dvay0es.js → db-0m6v5tq4.js} +3 -3
  96. package/dist/{db-b36qn6k3.js → db-y4wfrzbm.js} +4 -2
  97. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
  98. package/dist/{dispatcher-gndbta01.js → dispatcher-9tq2zzdj.js} +17 -17
  99. package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
  100. package/dist/{dsh-adapter-f75sz821.js → dsh-adapter-t09sv4tq.js} +2 -2
  101. package/dist/{e2b-jbm7mj93.js → e2b-7s9dscap.js} +2 -2
  102. package/dist/{e2b-3gpc2n3w.js → e2b-a7vzs2vj.js} +2 -2
  103. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
  104. package/dist/{embedding-space-4p05vb2x.js → embedding-space-wh8de1t9.js} +6 -6
  105. package/dist/{embeddings-m6768mgh.js → embeddings-3hpbdtjr.js} +1 -1
  106. package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
  107. package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
  108. package/dist/{external-channel-gjv3jne3.js → external-channel-ts2fwqh0.js} +2 -2
  109. package/dist/fx-adapter-1rnxnf56.js +17 -0
  110. package/dist/grok-adapter-efhmf1r8.js +17 -0
  111. package/dist/handlers-anrr3py9.js +32 -0
  112. package/dist/{heartbeat-a1tv60gt.js → heartbeat-2ze5fzpc.js} +20 -20
  113. package/dist/{hook-8h5dzcgq.js → hook-ca54yd4s.js} +5 -5
  114. package/dist/{hook-cyaps9ba.js → hook-gaehe2w5.js} +7 -7
  115. package/dist/{http-t15mhbd9.js → http-jfg8t2yk.js} +3861 -1798
  116. package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
  117. package/dist/{index-qav6455f.js → index-3yvzbhxd.js} +97 -22
  118. package/dist/index-8w2aznds.js +33 -0
  119. package/dist/{index-w1zqf680.js → index-csgrxedz.js} +1 -1
  120. package/dist/index-qnjvr362.js +37 -0
  121. package/dist/index-yzxd3sn9.js +32 -0
  122. package/dist/{keepalive-91s7hzrb.js → keepalive-k2a3qe73.js} +4 -4
  123. package/dist/lead-zhxqbfdv.js +69 -0
  124. package/dist/{maintenance-7pjmy5xy.js → maintenance-gb5sd5nc.js} +1 -1
  125. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  126. package/dist/{oauth-refresh-sweep-rzqfm94j.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
  127. package/dist/{onboard-74st7pag.js → onboard-jmc5qerv.js} +3 -3
  128. package/dist/{opencode-adapter-arn7gm8q.js → opencode-adapter-7eade9ev.js} +6 -7
  129. package/dist/{otel-impl-rnzey8cb.js → otel-impl-8j1xhxqd.js} +2 -2
  130. package/dist/{pi-mono-adapter-6mkwq64n.js → pi-mono-adapter-yqmaf32x.js} +13 -13
  131. package/dist/{pricing-refresh-ha21jhk7.js → pricing-refresh-1nj722h6.js} +2 -2
  132. package/dist/{rbac-roles-wqhma4dr.js → rbac-roles-b1mtr6dr.js} +3 -3
  133. package/dist/{rbac-roles-59dxachk.js → rbac-roles-n1f3frk1.js} +2 -2
  134. package/dist/{render-v2-14kpzx12.js → render-v2-1gfpd8rj.js} +4 -4
  135. package/dist/{resume-gsa5fb5f.js → resume-w1s1eh5v.js} +7 -7
  136. package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
  137. package/dist/{session-access-skm7bnp6.js → session-access-y6z1txk4.js} +4 -4
  138. package/dist/{session-source-backfill-pbqzbncv.js → session-source-backfill-gxxwfh12.js} +3 -3
  139. package/dist/{setup-5yermsem.js → setup-r91gstyk.js} +1 -1
  140. package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
  141. package/dist/{work-objects-xj0ck0w4.js → work-objects-qcxzg61c.js} +20 -20
  142. package/dist/worker-7j2907g6.js +69 -0
  143. package/dist/{worker-follow-up-911xc0b8.js → worker-follow-up-y2d2h7km.js} +17 -17
  144. package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
  145. package/openapi.json +1214 -108
  146. package/package.json +3 -3
  147. package/src/be/db/tasks/read.ts +33 -0
  148. package/src/be/db.ts +32 -7
  149. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  150. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  151. package/src/be/migrations/293_savings_component_links.sql +58 -0
  152. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  153. package/src/be/model-profile-check.ts +10 -2
  154. package/src/be/savings/compute.ts +511 -16
  155. package/src/be/savings/model.ts +282 -14
  156. package/src/be/savings/read.ts +1500 -0
  157. package/src/be/savings/rollup.ts +571 -0
  158. package/src/be/scripts/run-credential.ts +15 -3
  159. package/src/be/scripts/typecheck.ts +86 -4
  160. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  161. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  162. package/src/be/swarm-config-guard.ts +8 -0
  163. package/src/be/users.ts +29 -2
  164. package/src/commands/runner.ts +159 -41
  165. package/src/extensions/contract-types.generated.ts +1 -1
  166. package/src/http/index.ts +8 -1
  167. package/src/http/poll.ts +14 -1
  168. package/src/http/requested-by.ts +97 -1
  169. package/src/http/savings.ts +676 -190
  170. package/src/http/scripts.ts +26 -15
  171. package/src/http/tasks.ts +43 -5
  172. package/src/prompts/session-templates.ts +80 -3
  173. package/src/providers/acp-targets.ts +1 -1
  174. package/src/providers/amp-adapter.ts +1 -1
  175. package/src/providers/claude-adapter.ts +0 -20
  176. package/src/providers/claude-flag-settings.ts +12 -10
  177. package/src/providers/codex-adapter.ts +9 -34
  178. package/src/providers/opencode-adapter.ts +34 -12
  179. package/src/scheduler/scheduler.ts +20 -14
  180. package/src/scripts-runtime/ctx.ts +1 -1
  181. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  182. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  183. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  184. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  185. package/src/scripts-runtime/stdlib/index.ts +3 -1
  186. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  187. package/src/scripts-runtime/swarm-sdk.ts +186 -17
  188. package/src/scripts-runtime/types/stdlib.d.ts +86 -4
  189. package/src/scripts-runtime/types/swarm-extension.d.ts +26 -0
  190. package/src/scripts-runtime/types/swarm-sdk.d.ts +60 -2
  191. package/src/slack/actions.ts +1 -0
  192. package/src/slack/assistant.ts +2 -0
  193. package/src/slack/enrich.ts +144 -50
  194. package/src/slack/handlers.ts +37 -95
  195. package/src/slack/templates.ts +9 -0
  196. package/src/slack/thread-buffer.ts +45 -71
  197. package/src/slack/thread-participants.ts +187 -0
  198. package/src/tests/base-prompt.test.ts +5 -4
  199. package/src/tests/claude-adapter-binary.test.ts +7 -1
  200. package/src/tests/claude-adapter.test.ts +10 -64
  201. package/src/tests/claude-flag-settings.test.ts +15 -11
  202. package/src/tests/claude-hook-credentials.test.ts +0 -1
  203. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  204. package/src/tests/codex-adapter.test.ts +17 -78
  205. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  206. package/src/tests/db-task-read-contract.test.ts +2 -0
  207. package/src/tests/db-task-write-contract.test.ts +1 -0
  208. package/src/tests/docs-index-footprint.test.js +3 -3
  209. package/src/tests/dreaming-learnings.test.ts +104 -0
  210. package/src/tests/extensions-pre-task.test.ts +4 -2
  211. package/src/tests/fetch-resolved-env.test.ts +47 -1
  212. package/src/tests/opencode-adapter.test.ts +53 -6
  213. package/src/tests/prompt-template-session.test.ts +17 -1
  214. package/src/tests/runner-requester-profile.test.ts +139 -1
  215. package/src/tests/savings-compound.test.ts +774 -0
  216. package/src/tests/savings-compute.test.ts +7 -198
  217. package/src/tests/savings-fleet-latency.test.ts +143 -0
  218. package/src/tests/savings-fleet-read.test.ts +195 -0
  219. package/src/tests/savings-fleet-scale.test.ts +222 -0
  220. package/src/tests/savings-model.test.ts +212 -0
  221. package/src/tests/savings-read.test.ts +367 -0
  222. package/src/tests/savings-rollup.test.ts +766 -0
  223. package/src/tests/savings-scripts.test.ts +611 -0
  224. package/src/tests/script-connections.test.ts +2 -0
  225. package/src/tests/script-executor-conformance.test.ts +444 -0
  226. package/src/tests/scripts-http.test.ts +55 -0
  227. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  228. package/src/tests/secret-rules.test.ts +124 -1
  229. package/src/tests/secret-scrubber.test.ts +1 -1
  230. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  231. package/src/tests/slack-identity-resolution.test.ts +23 -0
  232. package/src/tests/slack-inbound-files.test.ts +2 -1
  233. package/src/tests/slack-thread-participants.test.ts +429 -0
  234. package/src/tests/tool-annotations.test.ts +30 -0
  235. package/src/types.ts +31 -0
  236. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  237. package/src/utils/mcp-server-fetcher.ts +13 -5
  238. package/src/utils/request-auth-context.ts +24 -0
  239. package/src/utils/secret-rules.generated.ts +1 -1
  240. package/src/utils/secret-scrubber.ts +154 -29
  241. package/src/workflows/executors/swarm-script.ts +23 -19
  242. package/templates/skills/swarm-scripts/SKILL.md +5 -4
  243. package/templates/skills/swarm-scripts/content.md +5 -4
  244. package/templates/skills/work-on-task/SKILL.md +1 -1
  245. package/templates/skills/work-on-task/content.md +1 -1
  246. package/templates/workflows/dreaming/content.md +1 -1
  247. package/dist/acp-adapter-fqzkxyra.js +0 -15
  248. package/dist/cli-4bd1rck6.js +0 -4
  249. package/dist/cli-xf3qw745.js +0 -104
  250. package/dist/fx-adapter-rpsgb1tw.js +0 -18
  251. package/dist/grok-adapter-n2m3zjg1.js +0 -18
  252. package/dist/handlers-nv8edn19.js +0 -32
  253. package/dist/index-ksmyd6kc.js +0 -37
  254. package/dist/index-rjnrje98.js +0 -32
  255. package/dist/index-tv3413wy.js +0 -33
  256. package/dist/lead-3hmddvrm.js +0 -70
  257. package/dist/worker-qgg0m2gw.js +0 -70
  258. package/src/providers/ctx-mode-env.ts +0 -10
@@ -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
  });
@@ -1,16 +1,112 @@
1
+ import { type RetryOptions, retry } from "./retry";
2
+
3
+ export type FetchRetryOptions = RetryOptions & {
4
+ /**
5
+ * Sends an `Idempotency-Key` header, the same value on every attempt: `true`
6
+ * generates a UUID per call, a string is used as is. A POST or PATCH with
7
+ * the header also retries 502/503/504 and network errors. The key only
8
+ * prevents a duplicate when the server dedupes by it.
9
+ */
10
+ idempotencyKey?: boolean | string;
11
+ };
12
+
1
13
  export type RuntimeFetchOptions = RequestInit & {
14
+ /** `false`: one attempt. `true` or omitted: method-aware defaults. An object tunes them. */
15
+ retry?: boolean | FetchRetryOptions;
16
+ /** @deprecated Use `retry: { retries }`. Total attempts, so `retries: 1` is one attempt. */
2
17
  retries?: number;
18
+ /** Per-attempt timeout. Default 30000. */
3
19
  timeoutMs?: number;
4
20
  };
5
21
 
22
+ /** Methods a server must treat as idempotent, so a repeat after a 5xx is safe. */
23
+ export const IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([
24
+ "GET",
25
+ "HEAD",
26
+ "OPTIONS",
27
+ "PUT",
28
+ "DELETE",
29
+ ]);
30
+ const TRANSIENT_5XX = new Set([502, 503, 504]);
31
+
32
+ /**
33
+ * Default fetch retry rule. 429 always retries (the server refused before any
34
+ * work). 502/503/504 and network errors retry only when a repeat is safe: an
35
+ * idempotent method, or a request carrying an `Idempotency-Key`.
36
+ */
37
+ export function shouldRetryFetch(value: unknown, repeatSafe: boolean): boolean {
38
+ if (value instanceof Response) {
39
+ return value.status === 429 || (repeatSafe && TRANSIENT_5XX.has(value.status));
40
+ }
41
+ return repeatSafe;
42
+ }
43
+
44
+ /** A body that fetch can send again. A stream or async iterable is read once. */
45
+ function isReplayableBody(body: unknown): boolean {
46
+ return (
47
+ body === undefined ||
48
+ body === null ||
49
+ typeof body === "string" ||
50
+ body instanceof URLSearchParams ||
51
+ body instanceof ArrayBuffer ||
52
+ ArrayBuffer.isView(body) ||
53
+ body instanceof Blob ||
54
+ body instanceof FormData
55
+ );
56
+ }
57
+
58
+ function resolveRetry(
59
+ option: RuntimeFetchOptions["retry"],
60
+ legacyAttempts: number | undefined,
61
+ ): FetchRetryOptions {
62
+ if (option === false) return { retries: 0 };
63
+ if (option && typeof option === "object") return option;
64
+ if (option === undefined && legacyAttempts !== undefined) {
65
+ return { retries: Math.max(0, legacyAttempts - 1) };
66
+ }
67
+ return {};
68
+ }
69
+
6
70
  export async function runtimeFetch(
7
71
  input: string | URL | Request,
8
72
  options: RuntimeFetchOptions = {},
9
73
  ): Promise<Response> {
10
- const { retries = 3, timeoutMs = 30_000, signal, ...init } = options;
11
- let lastError: unknown;
74
+ const {
75
+ retry: retryOption,
76
+ retries: legacyAttempts,
77
+ timeoutMs = 30_000,
78
+ signal,
79
+ ...init
80
+ } = options;
81
+ const {
82
+ idempotencyKey,
83
+ retryOn: userRetryOn,
84
+ ...retryOptions
85
+ } = resolveRetry(retryOption, legacyAttempts);
86
+ const inputRequest = input instanceof Request ? input : undefined;
87
+
88
+ if (idempotencyKey) {
89
+ const headers = new Headers(init.headers ?? inputRequest?.headers);
90
+ if (!headers.has("idempotency-key")) {
91
+ headers.set(
92
+ "idempotency-key",
93
+ idempotencyKey === true ? crypto.randomUUID() : String(idempotencyKey),
94
+ );
95
+ }
96
+ init.headers = headers;
97
+ }
98
+ const method = (init.method ?? inputRequest?.method ?? "GET").toUpperCase();
99
+ const hasKey = new Headers(init.headers ?? inputRequest?.headers).has("idempotency-key");
100
+ const repeatSafe = IDEMPOTENT_METHODS.has(method) || hasKey;
101
+ const replayable =
102
+ init.body !== undefined
103
+ ? isReplayableBody(init.body)
104
+ : !inputRequest || inputRequest.body === null || !inputRequest.bodyUsed;
105
+ // A Request with an unread body is cloned per attempt; the clone tees it.
106
+ const target = (): string | URL | Request =>
107
+ inputRequest && inputRequest.body !== null ? (inputRequest.clone() as Request) : input;
12
108
 
13
- for (let attempt = 0; attempt < retries; attempt++) {
109
+ const attempt = async (): Promise<Response> => {
14
110
  if (signal?.aborted) {
15
111
  throw signal.reason ?? new DOMException("This operation was aborted", "AbortError");
16
112
  }
@@ -19,26 +115,28 @@ export async function runtimeFetch(
19
115
  const onAbort = () => controller.abort();
20
116
  signal?.addEventListener("abort", onAbort, { once: true });
21
117
  if (signal?.aborted) controller.abort();
22
-
23
118
  try {
24
- const res = await fetch(input, { ...init, signal: controller.signal });
25
- if (!res.ok && attempt < retries - 1 && res.status >= 500) {
26
- lastError = new Error(`fetch failed with ${res.status}`);
27
- continue;
28
- }
29
- return res;
119
+ return await fetch(target(), { ...init, signal: controller.signal });
30
120
  } catch (error) {
31
- // Caller abort is terminal — only the controller's own timeout abort retries.
121
+ // Caller abort is terminal; the retry rule below sees `signal.aborted`.
32
122
  if (signal?.aborted) throw signal.reason ?? error;
33
- lastError = error;
34
- if (attempt === retries - 1) break;
123
+ throw error;
35
124
  } finally {
36
125
  clearTimeout(timeout);
37
126
  signal?.removeEventListener("abort", onAbort);
38
127
  }
39
- }
128
+ };
40
129
 
41
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
130
+ if (!replayable) return attempt();
131
+ return retry(attempt, {
132
+ ...retryOptions,
133
+ signal: signal ?? retryOptions.signal,
134
+ retryOn: async (value, attemptNumber) => {
135
+ if (signal?.aborted) return false;
136
+ if (userRetryOn) return userRetryOn(value, attemptNumber);
137
+ return shouldRetryFetch(value, repeatSafe);
138
+ },
139
+ });
42
140
  }
43
141
 
44
142
  export async function runtimeFetchJson(
@@ -2,6 +2,7 @@ import { Redacted } from "../redacted";
2
2
  import { runtimeFetch, runtimeFetchJson } from "./fetch";
3
3
  import { glob } from "./glob";
4
4
  import { grep } from "./grep";
5
+ import { retry } from "./retry";
5
6
  import { table } from "./table";
6
7
 
7
8
  export const stdlib = {
@@ -10,7 +11,8 @@ export const stdlib = {
10
11
  grep,
11
12
  glob,
12
13
  table,
14
+ retry,
13
15
  Redacted,
14
16
  };
15
17
 
16
- export { runtimeFetch as fetch, runtimeFetchJson as fetchJson, glob, grep, table, Redacted };
18
+ export { runtimeFetch as fetch, runtimeFetchJson as fetchJson, glob, grep, table, retry, Redacted };
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `retry` for scripts: calls a sync or async function until it succeeds, a
3
+ * retry is not warranted, attempts run out, or the time budget is spent.
4
+ *
5
+ * The quickjs executor has its own copy in `executors/quickjs-prelude.ts`
6
+ * (it sleeps through `__host_sleep`). Keep the two in step; the executor
7
+ * conformance tests run the same scripts against both.
8
+ */
9
+
10
+ export type RetryOptions = {
11
+ /** Retries after the first call. Default 3, so at most 4 calls. */
12
+ retries?: number;
13
+ /** First backoff delay in ms. Doubles on each retry, with jitter. Default 200. */
14
+ minDelayMs?: number;
15
+ /** Cap on a single wait, including a `Retry-After` wait. Default 5000. */
16
+ maxDelayMs?: number;
17
+ /** Total time across all calls and waits, in ms. Default 30000. */
18
+ budgetMs?: number;
19
+ /**
20
+ * Decides whether to retry. Gets the thrown error or the returned value and
21
+ * the 1-based attempt number. Replaces the default rule.
22
+ */
23
+ retryOn?: (errorOrResult: unknown, attempt: number) => boolean | Promise<boolean>;
24
+ /** Stops the retries: once it aborts, the wait ends and `retry` rejects with its reason. */
25
+ signal?: AbortSignal;
26
+ };
27
+
28
+ /** Statuses the default rule (and the swarm bridge) treat as transient. */
29
+ export const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([429, 502, 503, 504]);
30
+
31
+ const DEFAULTS = { retries: 3, minDelayMs: 200, maxDelayMs: 5_000, budgetMs: 30_000 };
32
+
33
+ /** Parses a `Retry-After` header (seconds or HTTP date) into ms; undefined if absent or invalid. */
34
+ export function retryAfterMs(
35
+ value: string | null | undefined,
36
+ now = Date.now(),
37
+ ): number | undefined {
38
+ if (value === null || value === undefined) return undefined;
39
+ const trimmed = String(value).trim();
40
+ if (trimmed === "") return undefined;
41
+ if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.round(Number(trimmed) * 1000);
42
+ const date = Date.parse(trimmed);
43
+ return Number.isNaN(date) ? undefined : Math.max(0, date - now);
44
+ }
45
+
46
+ /** Exponential backoff with equal jitter: a value in [d/2, d], d = min(max, min * 2^(attempt-1)). */
47
+ export function backoffMs(attempt: number, minDelayMs: number, maxDelayMs: number): number {
48
+ const ceiling = Math.min(maxDelayMs, minDelayMs * 2 ** (attempt - 1));
49
+ return Math.round(ceiling / 2 + (Math.random() * ceiling) / 2);
50
+ }
51
+
52
+ type StatusInfo = { status: number; retryAfter?: string | null };
53
+
54
+ /**
55
+ * Reads the status of a failed fetch `Response`, a `ctx.api` raw result
56
+ * (`ok: false`), or a `ctx.swarm` envelope (`success: false`).
57
+ */
58
+ function failedStatus(value: unknown): StatusInfo | undefined {
59
+ if (!value || typeof value !== "object") return undefined;
60
+ const candidate = value as {
61
+ status?: unknown;
62
+ ok?: unknown;
63
+ success?: unknown;
64
+ headers?: unknown;
65
+ };
66
+ if (typeof candidate.status !== "number") return undefined;
67
+ if (candidate.ok !== false && candidate.success !== false) return undefined;
68
+ const headers = candidate.headers as
69
+ | { get?: (name: string) => string | null }
70
+ | Record<string, unknown>
71
+ | undefined;
72
+ let retryAfter: string | null | undefined;
73
+ if (headers && typeof headers.get === "function") {
74
+ retryAfter = (headers as { get: (name: string) => string | null }).get("retry-after");
75
+ } else if (headers && typeof headers === "object") {
76
+ const raw = (headers as Record<string, unknown>)["retry-after"];
77
+ retryAfter = typeof raw === "string" ? raw : undefined;
78
+ }
79
+ return { status: candidate.status, retryAfter };
80
+ }
81
+
82
+ /** The default rule for a returned value: a failed response with a transient status. */
83
+ export function isRetryableResult(value: unknown): boolean {
84
+ const info = failedStatus(value);
85
+ return info !== undefined && RETRYABLE_STATUSES.has(info.status);
86
+ }
87
+
88
+ function checkNumber(name: string, value: unknown, fallback: number, integer = false): number {
89
+ if (value === undefined) return fallback;
90
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
91
+ throw new TypeError(`retry: \`${name}\` must be a non-negative number`);
92
+ }
93
+ if (integer && !Number.isInteger(value)) {
94
+ throw new TypeError(`retry: \`${name}\` must be a non-negative integer`);
95
+ }
96
+ return value;
97
+ }
98
+
99
+ function abortReason(signal: AbortSignal): unknown {
100
+ return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
101
+ }
102
+
103
+ /** Waits `ms`, or rejects with the signal's reason as soon as it aborts. */
104
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
105
+ return new Promise((resolve, reject) => {
106
+ if (signal?.aborted) return reject(abortReason(signal));
107
+ const onAbort = () => {
108
+ clearTimeout(timer);
109
+ reject(abortReason(signal as AbortSignal));
110
+ };
111
+ const timer = setTimeout(() => {
112
+ signal?.removeEventListener("abort", onAbort);
113
+ resolve();
114
+ }, ms);
115
+ signal?.addEventListener("abort", onAbort, { once: true });
116
+ });
117
+ }
118
+
119
+ async function retryCall<T>(
120
+ fn: (attempt: number) => T | Promise<T>,
121
+ options: RetryOptions = {},
122
+ ): Promise<Awaited<T>> {
123
+ if (typeof fn !== "function") throw new TypeError("retry: first argument must be a function");
124
+ const retries = checkNumber("retries", options.retries, DEFAULTS.retries, true);
125
+ const minDelayMs = checkNumber("minDelayMs", options.minDelayMs, DEFAULTS.minDelayMs);
126
+ const maxDelayMs = checkNumber("maxDelayMs", options.maxDelayMs, DEFAULTS.maxDelayMs);
127
+ const budgetMs = checkNumber("budgetMs", options.budgetMs, DEFAULTS.budgetMs);
128
+ const retryOn = options.retryOn;
129
+ if (retryOn !== undefined && typeof retryOn !== "function") {
130
+ throw new TypeError("retry: `retryOn` must be a function");
131
+ }
132
+ const signal = options.signal;
133
+ const started = Date.now();
134
+
135
+ for (let attempt = 1; ; attempt++) {
136
+ if (signal?.aborted) throw abortReason(signal);
137
+ let threw = false;
138
+ let value: unknown;
139
+ try {
140
+ // `await` turns a sync throw and an async rejection into the same catch.
141
+ value = await fn(attempt);
142
+ } catch (error) {
143
+ threw = true;
144
+ value = error;
145
+ }
146
+ const settle = (): Awaited<T> => {
147
+ if (threw) throw value;
148
+ return value as Awaited<T>;
149
+ };
150
+ if (attempt > retries) return settle();
151
+ const again = retryOn ? await retryOn(value, attempt) : threw || isRetryableResult(value);
152
+ if (!again) return settle();
153
+
154
+ const info = threw ? undefined : failedStatus(value);
155
+ const waitFor = info?.status === 429 ? retryAfterMs(info.retryAfter) : undefined;
156
+ const delay =
157
+ waitFor !== undefined
158
+ ? Math.min(maxDelayMs, waitFor)
159
+ : backoffMs(attempt, minDelayMs, maxDelayMs);
160
+ if (Date.now() - started + delay > budgetMs) return settle();
161
+ await sleep(delay, signal);
162
+ }
163
+ }
164
+
165
+ function wrap<A extends unknown[], T>(
166
+ fn: (...args: A) => T | Promise<T>,
167
+ options?: RetryOptions,
168
+ ): (...args: A) => Promise<Awaited<T>> {
169
+ if (typeof fn !== "function")
170
+ throw new TypeError("retry.wrap: first argument must be a function");
171
+ return (...args: A) => retryCall(() => fn(...args), options);
172
+ }
173
+
174
+ export const retry = Object.assign(retryCall, { wrap });