@desplega.ai/agent-swarm 2.8.0 → 2.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/dist/{acp-adapter-t949vbbp.js → acp-adapter-fqzkxyra.js} +3 -3
  2. package/dist/{actions-7e9czc7s.js → actions-kxek041g.js} +18 -18
  3. package/dist/{amp-adapter-gv6cbb7d.js → amp-adapter-ce7jjke4.js} +1 -1
  4. package/dist/{app-b9fbkp9v.js → app-v6zz8yh0.js} +3 -3
  5. package/dist/{assistant-wjb7v4c7.js → assistant-m0sw9xx2.js} +19 -19
  6. package/dist/{boot-args-schema-2t37e0fe.js → boot-args-schema-66bk37wv.js} +1 -1
  7. package/dist/{boot-reembed-gka3zas7.js → boot-reembed-edjpwsc1.js} +1 -1
  8. package/dist/{boot-reembed-a35nkyr1.js → boot-reembed-y27n09tz.js} +1 -1
  9. package/dist/{boot-scrub-sweep-65sdnp6c.js → boot-scrub-sweep-1xc35965.js} +3 -3
  10. package/dist/{boot-seeds-x42tzytw.js → boot-seeds-7hjj91qj.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-ent8ch04.js} +1 -1
  12. package/dist/{claude-adapter-v221b2fd.js → claude-adapter-stw7jdcf.js} +3 -3
  13. package/dist/{claude-managed-adapter-29eq09wd.js → claude-managed-adapter-jh6c523j.js} +2 -2
  14. package/dist/{claude-managed-setup-9m6450zk.js → claude-managed-setup-y6z2perp.js} +5 -5
  15. package/dist/{claude-sdk-session-0q0ptaba.js → claude-sdk-session-vvya8wqk.js} +3 -3
  16. package/dist/{cli-wk18cm92.js → cli-0cq8y6m7.js} +1 -1
  17. package/dist/{cli-p1w18yhx.js → cli-1pz0330a.js} +1 -1
  18. package/dist/{cli-y97qxcfx.js → cli-1qkz151v.js} +3 -3
  19. package/dist/{cli-qwca7s44.js → cli-26ctbcdp.js} +18 -6
  20. package/dist/{cli-8fknbnhw.js → cli-2kvhc7x8.js} +7 -7
  21. package/dist/{cli-rfywm85n.js → cli-3e875j5p.js} +136 -49
  22. package/dist/{cli-6wxjceza.js → cli-3sy2xags.js} +10 -10
  23. package/dist/{cli-a7wvp2km.js → cli-3vmb0n58.js} +1 -1
  24. package/dist/{cli-p1bq50aa.js → cli-4vzgeta4.js} +13 -13
  25. package/dist/{cli-m28atx8q.js → cli-5y340nzn.js} +4 -4
  26. package/dist/{cli-7p1kvkck.js → cli-6rc5frdm.js} +1 -1
  27. package/dist/{cli-tph5wt3y.js → cli-6wj7p986.js} +1 -1
  28. package/dist/{cli-t73cas91.js → cli-7349va39.js} +8100 -7620
  29. package/dist/{cli-ee0b971j.js → cli-837vfs2x.js} +2 -2
  30. package/dist/{cli-abejgen1.js → cli-959kp5h2.js} +12 -11
  31. package/dist/{cli-8kzasymh.js → cli-97ae65rz.js} +4 -4
  32. package/dist/{cli-m4dqmnbp.js → cli-9mb2q6pb.js} +1 -1
  33. package/dist/{cli-p2gfst4m.js → cli-a0z912j7.js} +123 -35
  34. package/dist/{cli-4txa0ter.js → cli-b98a65ed.js} +3 -3
  35. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  36. package/dist/{cli-tk7cjj8h.js → cli-dzpc6en0.js} +1 -1
  37. package/dist/{cli-qa4wdgsy.js → cli-e1p3n5gq.js} +4 -4
  38. package/dist/{cli-gxkx0zzp.js → cli-f4e8r23x.js} +1 -1
  39. package/dist/{cli-qmqk2yc2.js → cli-f4r3g076.js} +1 -1
  40. package/dist/{cli-wcg8x116.js → cli-f6bahpn5.js} +1 -1
  41. package/dist/{cli-qsnnd04k.js → cli-fpjmegdb.js} +1 -1
  42. package/dist/{cli-j790gp2w.js → cli-fwy8kfd6.js} +271 -37
  43. package/dist/{cli-rmmpt0wm.js → cli-g5mtmf6t.js} +6 -6
  44. package/dist/{cli-rzsy6nc6.js → cli-gyt3zydq.js} +3 -3
  45. package/dist/{cli-pasjcnmj.js → cli-j24zbska.js} +3 -3
  46. package/dist/{cli-qfedvmcr.js → cli-jdknh18m.js} +10 -10
  47. package/dist/{cli-7b8sbmag.js → cli-kjtwrhea.js} +1 -1
  48. package/dist/{cli-gpwhbgx0.js → cli-m9s2qff2.js} +57 -25
  49. package/dist/{cli-2wnq8jkz.js → cli-mxn1qvbn.js} +3 -2
  50. package/dist/{cli-s7t6p9my.js → cli-n6vtrcht.js} +1 -1
  51. package/dist/{cli-2zp0et3v.js → cli-pchypa1s.js} +55 -19
  52. package/dist/{cli-yq3zak69.js → cli-pfs8adn4.js} +1 -1
  53. package/dist/{cli-c55z5chy.js → cli-q24n86d2.js} +2 -2
  54. package/dist/{cli-h38x262p.js → cli-rcecc3yq.js} +167 -43
  55. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  56. package/dist/{cli-sdtt3men.js → cli-rmzsadkf.js} +1 -1
  57. package/dist/{cli-f3vq58d2.js → cli-t2tma8gb.js} +1 -1
  58. package/dist/{cli-m23zjcy2.js → cli-tekytdq9.js} +2 -2
  59. package/dist/{cli-tqegb8eq.js → cli-vdektqgf.js} +1 -1
  60. package/dist/{cli-ffhtssbp.js → cli-vj75tyaw.js} +1 -1
  61. package/dist/{cli-deefvewm.js → cli-w401b9tq.js} +1 -1
  62. package/dist/{cli-n9ftpys4.js → cli-x6t50dmw.js} +7 -7
  63. package/dist/{cli-6t09sdhy.js → cli-xf3qw745.js} +3 -3
  64. package/dist/{cli-hxpyc9sn.js → cli-z1w943va.js} +2 -2
  65. package/dist/{cli-334z18y3.js → cli-zh9rsbqf.js} +3 -3
  66. package/dist/cli.js +17 -17
  67. package/dist/{codex-adapter-30j9bpzd.js → codex-adapter-zerf5qsp.js} +1 -1
  68. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-30gyhzxe.js} +1 -1
  69. package/dist/{codex-session-runner-8vp57v8w.js → codex-session-runner-89s304py.js} +1 -1
  70. package/dist/{commands-bngnz9g7.js → commands-jeh1b51j.js} +3 -3
  71. package/dist/{controller-hxx8wwy1.js → controller-mctfbrse.js} +3 -3
  72. package/dist/{controllers-connect-e2b4gyxc.js → controllers-connect-nxa1ddwn.js} +19 -19
  73. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-qj8vehv6.js} +1 -1
  74. package/dist/{db-bgm7vkc0.js → db-2dvay0es.js} +3 -3
  75. package/dist/{db-c6np41ca.js → db-b36qn6k3.js} +2 -2
  76. package/dist/{dispatcher-jnybck15.js → dispatcher-gndbta01.js} +17 -17
  77. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-f75sz821.js} +1 -1
  78. package/dist/{e2b-jkwfhbcv.js → e2b-3gpc2n3w.js} +1 -1
  79. package/dist/{e2b-s16txnpx.js → e2b-jbm7mj93.js} +1 -1
  80. package/dist/{embedding-space-crsm2zp0.js → embedding-space-4p05vb2x.js} +6 -6
  81. package/dist/{embeddings-e7z3f27f.js → embeddings-m6768mgh.js} +1 -1
  82. package/dist/{external-channel-m77wf5z3.js → external-channel-gjv3jne3.js} +2 -2
  83. package/dist/{fx-adapter-b6w0kf56.js → fx-adapter-rpsgb1tw.js} +4 -4
  84. package/dist/{grok-adapter-4sqtebdk.js → grok-adapter-n2m3zjg1.js} +4 -4
  85. package/dist/handlers-nv8edn19.js +32 -0
  86. package/dist/{heartbeat-xgb036sx.js → heartbeat-a1tv60gt.js} +20 -20
  87. package/dist/{hook-xsk1jbha.js → hook-8h5dzcgq.js} +2 -2
  88. package/dist/{hook-5h02c9ga.js → hook-cyaps9ba.js} +4 -4
  89. package/dist/{http-txe7qhvn.js → http-t15mhbd9.js} +1733 -79
  90. package/dist/{index-0eny15vj.js → index-2skqtd76.js} +2 -2
  91. package/dist/{index-w7em4ktq.js → index-d6wkh8ar.js} +2 -2
  92. package/dist/{index-rvccek1w.js → index-gjwaqaq8.js} +5 -5
  93. package/dist/{index-e5pfbsys.js → index-hjhfk3ra.js} +3 -3
  94. package/dist/{index-1qw6f2dc.js → index-khe3gp0k.js} +4 -4
  95. package/dist/index-ksmyd6kc.js +37 -0
  96. package/dist/{index-vk63emp7.js → index-qav6455f.js} +14 -12
  97. package/dist/index-rjnrje98.js +32 -0
  98. package/dist/index-tv3413wy.js +33 -0
  99. package/dist/{index-ysvbhg5m.js → index-w1zqf680.js} +1 -1
  100. package/dist/{keepalive-4zsrce78.js → keepalive-91s7hzrb.js} +3 -3
  101. package/dist/lead-3hmddvrm.js +70 -0
  102. package/dist/{maintenance-86jvartk.js → maintenance-7pjmy5xy.js} +1 -1
  103. package/dist/{node-je82wjet.js → node-4c5jqxr3.js} +1 -1
  104. package/dist/{oauth-refresh-sweep-j52kg9pr.js → oauth-refresh-sweep-rzqfm94j.js} +2 -2
  105. package/dist/{onboard-c2aj5p8q.js → onboard-74st7pag.js} +3 -3
  106. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-arn7gm8q.js} +2 -2
  107. package/dist/{otel-impl-yyy203z8.js → otel-impl-rnzey8cb.js} +1 -1
  108. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-6mkwq64n.js} +3 -2
  109. package/dist/{pricing-refresh-1rgzqyzz.js → pricing-refresh-ha21jhk7.js} +2 -2
  110. package/dist/{rbac-roles-e70xfeyj.js → rbac-roles-59dxachk.js} +2 -2
  111. package/dist/{rbac-roles-q89qe8er.js → rbac-roles-wqhma4dr.js} +3 -3
  112. package/dist/{render-v2-k6tt107q.js → render-v2-14kpzx12.js} +3 -3
  113. package/dist/{resume-cnnrjfxa.js → resume-gsa5fb5f.js} +6 -6
  114. package/dist/{session-access-xkxkjw3n.js → session-access-skm7bnp6.js} +4 -4
  115. package/dist/{session-source-backfill-1d5pdwww.js → session-source-backfill-pbqzbncv.js} +2 -2
  116. package/dist/{setup-se8q7gkc.js → setup-5yermsem.js} +1 -1
  117. package/dist/{work-objects-1kxnbzy5.js → work-objects-xj0ck0w4.js} +20 -20
  118. package/dist/{worker-follow-up-zqm8apt4.js → worker-follow-up-911xc0b8.js} +19 -17
  119. package/dist/worker-qgg0m2gw.js +70 -0
  120. package/openapi.json +1741 -290
  121. package/package.json +3 -3
  122. package/src/apps/catalog.generated.json +120 -1
  123. package/src/apps/definition.ts +38 -11
  124. package/src/apps/page-validator.ts +88 -0
  125. package/src/be/db/model-profiles.ts +110 -11
  126. package/src/be/db/tasks/read.ts +20 -0
  127. package/src/be/db/workflow-run-definitions.ts +19 -8
  128. package/src/be/db-client.ts +43 -5
  129. package/src/be/db.ts +9 -3
  130. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  131. package/src/be/model-profile-check.ts +43 -18
  132. package/src/be/runtime-pools/routing.ts +1 -0
  133. package/src/be/savings/calibrate.ts +468 -0
  134. package/src/be/savings/compute.ts +182 -0
  135. package/src/be/savings/model.ts +406 -0
  136. package/src/be/scripts/typecheck.ts +5 -0
  137. package/src/be/seed/agent-fs-provision.ts +48 -11
  138. package/src/be/seed/workflows-seeder.ts +67 -23
  139. package/src/be/skill-parser.ts +19 -7
  140. package/src/commands/onboard/agent-fs-version.ts +1 -1
  141. package/src/commands/provider-error-class.ts +97 -0
  142. package/src/commands/runner.ts +99 -17
  143. package/src/extensions/contract-types.generated.ts +1 -1
  144. package/src/http/all-routes.ts +2 -0
  145. package/src/http/fs.ts +8 -2
  146. package/src/http/index.ts +4 -0
  147. package/src/http/model-profiles.ts +43 -10
  148. package/src/http/poll.ts +1 -0
  149. package/src/http/savings-calibration.ts +277 -0
  150. package/src/http/savings.ts +363 -0
  151. package/src/http/tasks.ts +46 -4
  152. package/src/http/trackers/authorize-gate.ts +41 -0
  153. package/src/http/trackers/jira.ts +26 -4
  154. package/src/http/trackers/linear.ts +26 -4
  155. package/src/integrations/chat-sdk/limits.ts +6 -1
  156. package/src/jira/oauth.ts +7 -1
  157. package/src/linear/README.md +2 -1
  158. package/src/linear/oauth.ts +7 -1
  159. package/src/providers/amp-adapter.ts +1 -1
  160. package/src/providers/codex-adapter.ts +3 -0
  161. package/src/providers/pi-mono-adapter.ts +6 -5
  162. package/src/providers/types.ts +7 -0
  163. package/src/scripts-runtime/eval-harness.ts +14 -1
  164. package/src/scripts-runtime/executors/types.ts +3 -0
  165. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  166. package/src/scripts-runtime/swarm-sdk.ts +6 -0
  167. package/src/scripts-runtime/types/stdlib.d.ts +9 -0
  168. package/src/scripts-runtime/types/swarm-extension.d.ts +34 -0
  169. package/src/scripts-runtime/types/swarm-sdk.d.ts +9 -0
  170. package/src/tasks/worker-follow-up.ts +142 -3
  171. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  172. package/src/tests/apps-chart-shell.test.ts +170 -0
  173. package/src/tests/apps-icon.test.ts +156 -2
  174. package/src/tests/chat-sdk-relay.test.ts +12 -0
  175. package/src/tests/codex-adapter.test.ts +11 -0
  176. package/src/tests/comb-default.test.ts +6 -0
  177. package/src/tests/core-auth.test.ts +7 -6
  178. package/src/tests/db-client-busy-retry.test.ts +58 -6
  179. package/src/tests/deploy-guard.test.ts +154 -0
  180. package/src/tests/docs-index-footprint.test.js +3 -3
  181. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  182. package/src/tests/mcp-tools.test.ts +1 -1
  183. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  184. package/src/tests/model-profiles-api.test.ts +1 -0
  185. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  186. package/src/tests/provider-error-class.test.ts +174 -0
  187. package/src/tests/runner-provider-fallback.test.ts +197 -0
  188. package/src/tests/savings-calibration-api.test.ts +264 -0
  189. package/src/tests/savings-calibration.test.ts +201 -0
  190. package/src/tests/savings-compute.test.ts +406 -0
  191. package/src/tests/savings-model.test.ts +287 -0
  192. package/src/tests/script-connections.test.ts +2 -0
  193. package/src/tests/script-native-unawaited-drain.test.ts +167 -0
  194. package/src/tests/sdk-allowlist.test.ts +40 -0
  195. package/src/tests/seed-workflows.test.ts +167 -11
  196. package/src/tests/skill-parser.test.ts +45 -0
  197. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  198. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  199. package/src/tests/workflow-script-principal.test.ts +94 -4
  200. package/src/tools/app-upsert.ts +1 -1
  201. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  202. package/src/tools/script-run.ts +1 -1
  203. package/src/tools/update-profile.ts +1 -1
  204. package/src/types.ts +115 -33
  205. package/src/utils/constants.ts +2 -0
  206. package/templates/skills/apps/SKILL.md +62 -3
  207. package/templates/skills/apps/content.md +62 -3
  208. package/templates/skills/swarm-docs/content.md +2 -0
  209. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  210. package/templates/skills/swarm-scripts/content.md +1 -1
  211. package/dist/handlers-kdjcyzdj.js +0 -32
  212. package/dist/index-835xdgnm.js +0 -33
  213. package/dist/index-d469300x.js +0 -37
  214. package/dist/index-rzqwp11g.js +0 -32
  215. package/dist/lead-yqt47dkr.js +0 -70
  216. package/dist/worker-j6xxtq7p.js +0 -70
@@ -18,7 +18,8 @@ Bidirectional sync between Agent Swarm and Linear. Webhook-driven inbound (Linea
18
18
  # LINEAR_TEAM_ID=<optional: scope to a specific team>
19
19
  ```
20
20
  6. **Start server**: `bun run start:http`
21
- 7. **Run OAuth flow**: visit `http://localhost:3013/api/trackers/linear/authorize` in your browser
21
+ 7. **Run OAuth flow**: click **Connect to Linear** in the dashboard, or fetch the consent URL with the API key and open it in your browser:
22
+ `curl -s -H "Authorization: Bearer $API_KEY" "http://localhost:3013/api/trackers/linear/authorize?format=json" | jq -r .authorizeUrl`
22
23
  8. **Verify connection**:
23
24
  ```bash
24
25
  curl -H "Authorization: Bearer $API_KEY" http://localhost:3013/api/trackers/linear/status
@@ -16,7 +16,10 @@ export async function getLinearOAuthConfig(): Promise<OAuthProviderConfig | null
16
16
  return app ? oauthAppRowToProviderConfig(app) : null;
17
17
  }
18
18
 
19
- export async function getLinearAuthorizationUrl(finalRedirect?: string): Promise<string | null> {
19
+ export async function getLinearAuthorizationUrl(
20
+ finalRedirect?: string,
21
+ userId?: string | null,
22
+ ): Promise<string | null> {
20
23
  const config = await getLinearOAuthConfig();
21
24
  if (!config) return null;
22
25
  // flow='tracker' so the unified state-keyed callback runs the tracker
@@ -26,6 +29,9 @@ export async function getLinearAuthorizationUrl(finalRedirect?: string): Promise
26
29
  flow: "tracker",
27
30
  label: "default",
28
31
  ...(finalRedirect ? { finalRedirect } : {}),
32
+ // The initiating user, recorded on the pending row and then on the
33
+ // authorization (connectedByUserId), same as the generic authorize-url route.
34
+ ...(userId ? { userId } : {}),
29
35
  });
30
36
  return result.url;
31
37
  }
@@ -45,7 +45,7 @@ import type {
45
45
  * default; the image installs exactly this version and the per-task settings
46
46
  * set `amp.updates.mode: "disabled"`. Bump it deliberately, with a live run.
47
47
  */
48
- export const AMP_PACKAGE = "@ampcode/cli@0.0.1793804260-g12625e";
48
+ export const AMP_PACKAGE = "@ampcode/cli@0.0.1793887133-gbf8b08";
49
49
 
50
50
  /** MCP server name. Amp exposes its tools as `agent_swarm` / `store_progress` (dashes become underscores). */
51
51
  const AMP_MCP_SERVER_NAME = "agent-swarm";
@@ -1770,6 +1770,9 @@ export class CodexSession implements ProviderSession {
1770
1770
  sessionId: this._sessionId,
1771
1771
  cost,
1772
1772
  isError: true,
1773
+ // Provider failures arrive as turn.failed / error events (terminalError,
1774
+ // handled above); a throw with none is the app-server or MCP transport.
1775
+ errorOrigin: "harness",
1773
1776
  failureReason: message,
1774
1777
  rateLimitResetAt: this.errorTracker.getRateLimitResetAt(),
1775
1778
  rateLimitWindows: this.errorTracker.getRateLimitWindows(),
@@ -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
  /**
@@ -1,6 +1,6 @@
1
1
  import { buildCtx } from "./ctx";
2
2
  import { patchFetchWithEgressSubstitution } from "./egress-secrets";
3
- import type { SwarmConfigPayload } from "./executors/types";
3
+ import { type SwarmConfigPayload, UNAWAITED_WORK_DRAIN_MS } from "./executors/types";
4
4
  import { isHostValidationEquivalent } from "./host-validated-args";
5
5
  import { ctxSignatureHintFor } from "./script-error-hints";
6
6
  import { SwarmConfig } from "./swarm-config";
@@ -167,6 +167,19 @@ try {
167
167
 
168
168
  const result = await mod.default(validatedArgs, ctx);
169
169
  await Bun.write(requiredEnv("SWARM_SCRIPT_RESULT_FILE"), JSON.stringify(result ?? null));
170
+ // The run settles once the entry function resolves. Bun would otherwise keep
171
+ // the process alive while any call the script did not await is pending (a
172
+ // nested script_run that lost a Promise.race, a fire-and-forget kv_set), so
173
+ // the executor kept waiting until that call settled or the wall-clock
174
+ // watchdog killed the run and discarded the result. The timer is unref'd:
175
+ // with nothing pending the process exits at once, as before. Un-awaited work
176
+ // gets this window to finish; whatever is still pending then is stopped.
177
+ setTimeout(() => {
178
+ console.error(
179
+ `[swarm-script] the script returned, but un-awaited calls were still pending ${UNAWAITED_WORK_DRAIN_MS} ms later; they were stopped. Await every call whose effect must land.`,
180
+ );
181
+ process.exit(0);
182
+ }, UNAWAITED_WORK_DRAIN_MS).unref();
170
183
  } catch (error) {
171
184
  await emitError(error);
172
185
  process.exit(1);
@@ -121,6 +121,9 @@ export interface ScriptExecutor {
121
121
  }
122
122
 
123
123
  export const MIN_SCRIPT_WALL_CLOCK_MS = 1_000;
124
+ // native: how long calls a script did not await may keep running after its
125
+ // default export resolves, before the harness exits (see eval-harness.ts).
126
+ export const UNAWAITED_WORK_DRAIN_MS = 2_000;
124
127
  // Above 2m, steer authors toward durable journaled steps before they reach the
125
128
  // 5m hard cap and keep a blocking workflow node open for several minutes.
126
129
  export const SCRIPT_LONG_TIMEOUT_HINT_MS = 120_000;
@@ -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. */
@@ -237,6 +237,12 @@ function bridgeRequestFor(name: string, args: unknown): BridgeRequest | null {
237
237
  case "script_run":
238
238
  return { method: "POST", path: "/api/scripts/run", body };
239
239
 
240
+ // ── savings calibration (REST only, no MCP tool) ──
241
+ case "savings_calibrationGet":
242
+ return { method: "GET", path: "/api/savings/calibration" };
243
+ case "savings_calibrationRun":
244
+ return { method: "POST", path: "/api/savings/calibration", body };
245
+
240
246
  // ── swarm / agent ──
241
247
  case "db_query":
242
248
  return { method: "POST", path: "/api/db-query", body };
@@ -310,6 +310,15 @@ declare module "swarm-sdk" {
310
310
  executor?: ScriptExecutorName | null;
311
311
  idempotencyKey?: string;
312
312
  }): Promise<unknown>;
313
+ // --- savings calibration (REST only) ---
314
+ /** The savings curve in use (shipped or derived from this deployment) and the stored row's metadata. */
315
+ savings_calibrationGet(): Promise<unknown>;
316
+ /** Derive the curve from the last `days` of sessions. Read-only unless `apply` is true (needs config write access). One run at a time; takes up to 120 s, so call it from a script with a long enough timeout. */
317
+ savings_calibrationRun(args?: {
318
+ days?: number;
319
+ end?: string;
320
+ apply?: boolean;
321
+ }): Promise<unknown>;
313
322
  // --- swarm / agent ---
314
323
  swarm_get(args?: { includeFull?: boolean }): Promise<unknown>;
315
324
  agent_info(args?: Record<string, unknown>): Promise<unknown>;
@@ -62,6 +62,23 @@ declare module "swarm-extension" {
62
62
  modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;
63
63
  effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;
64
64
  profile?: string | undefined;
65
+ fallbackHops?:
66
+ | {
67
+ from: string;
68
+ profile: string;
69
+ errorClass:
70
+ | "rate_limit"
71
+ | "model_window"
72
+ | "seat"
73
+ | "credits"
74
+ | "overloaded"
75
+ | "server_error"
76
+ | "auth"
77
+ | "pool_empty";
78
+ at: string;
79
+ skipped?: { profile: string; reason: string }[] | undefined;
80
+ }[]
81
+ | undefined;
65
82
  scheduleId?: string | undefined;
66
83
  workflowRunId?: string | undefined;
67
84
  workflowRunStepId?: string | undefined;
@@ -204,6 +221,23 @@ declare module "swarm-extension" {
204
221
  resolvedEffort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;
205
222
  profile?: string | undefined;
206
223
  resolvedProfile?: string | undefined;
224
+ fallbackHops?:
225
+ | {
226
+ from: string;
227
+ profile: string;
228
+ errorClass:
229
+ | "rate_limit"
230
+ | "model_window"
231
+ | "seat"
232
+ | "credits"
233
+ | "overloaded"
234
+ | "server_error"
235
+ | "auth"
236
+ | "pool_empty";
237
+ at: string;
238
+ skipped?: { profile: string; reason: string }[] | undefined;
239
+ }[]
240
+ | undefined;
207
241
  scheduleId?: string | undefined;
208
242
  workflowRunId?: string | null | undefined;
209
243
  workflowRunStepId?: string | null | undefined;
@@ -292,6 +292,15 @@ declare module "swarm-sdk" {
292
292
  executor?: ScriptExecutorName | null;
293
293
  idempotencyKey?: string;
294
294
  }): Promise<unknown>;
295
+ // --- savings calibration (REST only) ---
296
+ /** The savings curve in use (shipped or derived from this deployment) and the stored row's metadata. */
297
+ savings_calibrationGet(): Promise<unknown>;
298
+ /** Derive the curve from the last `days` of sessions. Read-only unless `apply` is true (needs config write access). One run at a time; takes up to 120 s, so call it from a script with a long enough timeout. */
299
+ savings_calibrationRun(args?: {
300
+ days?: number;
301
+ end?: string;
302
+ apply?: boolean;
303
+ }): Promise<unknown>;
295
304
  // --- swarm / agent ---
296
305
  swarm_get(args?: { includeFull?: boolean }): Promise<unknown>;
297
306
  agent_info(args?: Record<string, unknown>): Promise<unknown>;
@@ -13,7 +13,9 @@ import {
13
13
  hasNonTerminalRerouteDecisionChild,
14
14
  isAgentEligibleForTask,
15
15
  } from "../be/db";
16
+ import { getModelProfileByName } from "../be/db/model-profiles";
16
17
  import { repointTrackerSyncBySwarmId } from "../be/db-queries/tracker";
18
+ import { checkProfileForAgent } from "../be/model-profile-check";
17
19
  import { isAgentReachable } from "../be/runtime-pools/reachability";
18
20
  import { carryUnhandledSteering } from "../be/steering";
19
21
  import { dispatchPre } from "../extensions/dispatcher";
@@ -27,6 +29,8 @@ import {
27
29
  type AgentTask,
28
30
  type CreateTaskOptions,
29
31
  CreateTaskOptionsSchema,
32
+ type FallbackHop,
33
+ type ProviderErrorClass,
30
34
  type ResumeReason,
31
35
  type RoutingAffinity,
32
36
  type TaskAttachment,
@@ -201,6 +205,109 @@ export function inheritedModelSelection(
201
205
  };
202
206
  }
203
207
 
208
+ /** Result of `nextFallback`. */
209
+ export type FallbackPick =
210
+ | { kind: "picked"; profile: string; hop: FallbackHop }
211
+ /** `message` is null when no fallback was ever configured: the task fails as before. */
212
+ | { kind: "none"; message: string | null };
213
+
214
+ /**
215
+ * The next profile a task that hit a provider error should resume on, on the
216
+ * same agent (runbooks/model-tiers.md § Fallbacks on provider errors).
217
+ *
218
+ * The chain starts at the profile claim applied (`resolvedProfile`). It walks
219
+ * the fallback lists of the profiles this work already ran on, the current
220
+ * one first and then back toward the first, so a fallback's own fallbacks
221
+ * come before its siblings'. A profile the work already ran on is never
222
+ * picked again. A candidate that fails `checkProfileForAgent` on the agent
223
+ * is skipped and recorded on the hop. There is no hop cap: every hop adds a
224
+ * profile to the visited set and the saved fallback graph is acyclic, so the
225
+ * walk ends once every reachable profile has run.
226
+ *
227
+ * The pick is judged against this agent only, so the resume is always pinned
228
+ * to it (`createResumeFollowUp`). Lead-only work on an agent that cannot hold
229
+ * a lead-only pin would be rerouted to another agent, so it never hops.
230
+ */
231
+ export async function nextFallback(
232
+ parent: Pick<
233
+ AgentTask,
234
+ | "agentId"
235
+ | "resolvedProfile"
236
+ | "fallbackHops"
237
+ | "vcsRepo"
238
+ | "routingAffinity"
239
+ | "routingAffinityInvalid"
240
+ >,
241
+ errorClass: ProviderErrorClass,
242
+ options: { includeRepoSecrets?: boolean } = {},
243
+ ): Promise<FallbackPick> {
244
+ const current = parent.resolvedProfile;
245
+ if (!current || !parent.agentId) return { kind: "none", message: null };
246
+ const hops = parent.fallbackHops ?? [];
247
+ const path = hops.length > 0 ? [hops[0]!.from, ...hops.map((hop) => hop.profile)] : [current];
248
+ if (path[path.length - 1] !== current) path.push(current);
249
+ const visited = new Set(path);
250
+ const skipped: { profile: string; reason: string }[] = [];
251
+ const judged = new Set<string>();
252
+ let configured = hops.length > 0;
253
+
254
+ if (parent.routingAffinity?.leadOnly) {
255
+ const agent = await getAgentById(parent.agentId);
256
+ if (!agent?.isLead || !isAgentEligibleForTask(agent, parent)) {
257
+ const listsFallbacks = (await getModelProfileByName(current))?.fallbacks.length ?? 0;
258
+ if (!configured && listsFallbacks === 0) return { kind: "none", message: null };
259
+ return {
260
+ kind: "none",
261
+ message: `${errorClass} on ${current}; no fallback: lead-only work cannot resume on agent ${parent.agentId}`,
262
+ };
263
+ }
264
+ }
265
+
266
+ for (let i = path.length - 1; i >= 0; i--) {
267
+ const profile = await getModelProfileByName(path[i]!);
268
+ for (const name of profile?.fallbacks ?? []) {
269
+ configured = true;
270
+ if (visited.has(name) || judged.has(name)) continue;
271
+ judged.add(name);
272
+ const result = await checkProfileForAgent(parent.agentId, name, {
273
+ vcsRepo: parent.vcsRepo,
274
+ includeRepoSecrets: options.includeRepoSecrets,
275
+ fallbacks: false,
276
+ });
277
+ if (result?.ok) {
278
+ return {
279
+ kind: "picked",
280
+ profile: name,
281
+ hop: {
282
+ from: current,
283
+ profile: name,
284
+ errorClass,
285
+ at: new Date().toISOString(),
286
+ ...(skipped.length > 0 ? { skipped } : {}),
287
+ },
288
+ };
289
+ }
290
+ skipped.push({ profile: name, reason: result ? firstFailingRow(result) : "not found" });
291
+ }
292
+ }
293
+ if (!configured) return { kind: "none", message: null };
294
+ const skippedText =
295
+ skipped.length > 0
296
+ ? `; skipped: ${skipped.map((s) => `${s.profile} (${s.reason})`).join(", ")}`
297
+ : "";
298
+ return {
299
+ kind: "none",
300
+ message: `${errorClass} on ${current}; no fallback left (tried: ${path.join(" → ")})${skippedText}`,
301
+ };
302
+ }
303
+
304
+ /** "check: detail" of the primary's first failing row. */
305
+ function firstFailingRow(result: NonNullable<Awaited<ReturnType<typeof checkProfileForAgent>>>) {
306
+ const row = result.profiles[0]?.checks.find((check) => check.state === "fail");
307
+ if (!row) return "failed the profile check";
308
+ return row.detail ? `${row.check}: ${row.detail}` : row.check;
309
+ }
310
+
204
311
  function attachmentPointer(a: TaskAttachment): string {
205
312
  return taskAttachmentDisplayUrl(a);
206
313
  }
@@ -605,6 +712,11 @@ export type CreateResumeFollowUpResult =
605
712
  export async function createResumeFollowUp(args: {
606
713
  parentId: string;
607
714
  reason: ResumeReason;
715
+ /**
716
+ * With `provider_fallback`: the profile the resume runs and the hop that
717
+ * records why (`nextFallback`).
718
+ */
719
+ fallback?: { profile: string; hop: FallbackHop };
608
720
  }): Promise<CreateResumeFollowUpResult> {
609
721
  const parent = await getTaskById(args.parentId);
610
722
  if (!parent) return { kind: "skipped", reason: "parent_not_found" };
@@ -627,7 +739,19 @@ export async function createResumeFollowUp(args: {
627
739
  | "escalated_unassigned"
628
740
  | undefined;
629
741
  const leadOnly = parent.routingAffinity?.leadOnly === true;
630
- if (parent.agentId) {
742
+ // A fallback profile was judged against this agent alone (`nextFallback`,
743
+ // which also refuses lead-only work a non-Lead holds), so its resume never
744
+ // leaves it: not for a full slot (another claim can take the parent's freed
745
+ // one first), and not for a stale status, since the agent that asked for
746
+ // the fallback is alive. The pending pin waits for a free slot.
747
+ const fallbackPin =
748
+ args.reason === "provider_fallback" && args.fallback !== undefined && parent.agentId
749
+ ? parent.agentId
750
+ : undefined;
751
+ if (fallbackPin) {
752
+ preferredAgentId = fallbackPin;
753
+ if (leadOnly) authorizationDecision = "source_lead_pin";
754
+ } else if (parent.agentId) {
631
755
  const candidate = await getPinCandidateAgent(parent.agentId);
632
756
  if (candidate) {
633
757
  const lastActivity = candidate.lastActivityAt ? Date.parse(candidate.lastActivityAt) : 0;
@@ -662,7 +786,7 @@ export async function createResumeFollowUp(args: {
662
786
  // Apply the same Lead-only recovery decision used by reboot recovery. A
663
787
  // non-Lead source can never win the earlier pin attempt, so this chooses a
664
788
  // Lead reroute or an authorization-gated unassigned fallback.
665
- if (leadOnly) {
789
+ if (leadOnly && !fallbackPin) {
666
790
  const source = preferredAgentId ? await getAgentById(preferredAgentId) : null;
667
791
  const resolution = await resolveLeadOnlyRecoveryAssignment(parent, source);
668
792
  preferredAgentId = resolution.agentId;
@@ -747,7 +871,7 @@ export async function createResumeFollowUp(args: {
747
871
  // fire when this resume finishes.
748
872
  inheritParentFollowUpConfig: true,
749
873
  routingAffinity,
750
- ...inheritedModelSelection(parent),
874
+ ...resumeModelSelection(parent, args.fallback),
751
875
  });
752
876
  // The resume continues the work, so it takes over unaccepted steering.
753
877
  await carryUnhandledSteering(parent.id, created.id);
@@ -785,6 +909,21 @@ export async function createResumeFollowUp(args: {
785
909
  return { kind: "created", task: created };
786
910
  }
787
911
 
912
+ /**
913
+ * The resume's model fields: the parent's own selection, or with a fallback
914
+ * the picked profile alone (a profile wins over `model` and `modelTier` at
915
+ * claim, and the hop replaces whatever the parent ran). The hop list carries
916
+ * over either way, so a later hop never picks a profile the work already ran.
917
+ */
918
+ function resumeModelSelection(
919
+ parent: AgentTask,
920
+ fallback: { profile: string; hop: FallbackHop } | undefined,
921
+ ): Pick<CreateTaskOptions, "model" | "modelTier" | "profile" | "fallbackHops"> {
922
+ const hops = [...(parent.fallbackHops ?? []), ...(fallback ? [fallback.hop] : [])];
923
+ const selection = fallback ? { profile: fallback.profile } : inheritedModelSelection(parent);
924
+ return { ...selection, ...(hops.length > 0 ? { fallbackHops: hops } : {}) };
925
+ }
926
+
788
927
  /** Result of `createRerouteDecisionTask`. */
789
928
  export type CreateRerouteDecisionResult =
790
929
  | { kind: "created"; task: AgentTask }
@@ -95,6 +95,8 @@ function createFetchStub(
95
95
  registerConflictEmail?: string;
96
96
  /** A body to send, or a function of the invited email (undefined: the default). */
97
97
  inviteResponse?: Record<string, unknown> | ((email: string) => Response | undefined);
98
+ /** Status for `POST /invites/:token/accept` (default 200). */
99
+ acceptStatus?: number;
98
100
  } = {},
99
101
  ): typeof fetch {
100
102
  return (async (input, init) => {
@@ -167,6 +169,12 @@ function createFetchStub(
167
169
  const email = body && typeof body === "object" && "email" in body ? String(body.email) : "";
168
170
  return invite(email) ?? Response.json({ ok: true });
169
171
  }
172
+ if (/^\/invites\/[^/]+\/accept$/.test(url.pathname) && method === "POST") {
173
+ const status = options.acceptStatus ?? 200;
174
+ return status === 200
175
+ ? Response.json({ ok: true, orgId: "shared-org" })
176
+ : Response.json({ error: "invite not found" }, { status });
177
+ }
170
178
 
171
179
  return Response.json(
172
180
  { error: "unexpected route", path: url.pathname, method },
@@ -607,6 +615,77 @@ describe("agent-fs provisioning seeder", () => {
607
615
  ]);
608
616
  });
609
617
 
618
+ test("accepts a pending shared-org invite with the new agent's own key", async () => {
619
+ const suffix = crypto.randomUUID().slice(0, 8);
620
+ process.env.AGENT_FS_API_URL = "https://agent-fs.example.test";
621
+ await upsertSwarmConfig({
622
+ scope: "global",
623
+ key: "API_AGENT_FS_API_KEY",
624
+ value: "example-afs-admin-key",
625
+ isSecret: true,
626
+ });
627
+ await upsertSwarmConfig({
628
+ scope: "global",
629
+ key: "AGENT_FS_DEFAULT_ORG_ID",
630
+ value: "shared-org",
631
+ });
632
+ await upsertSwarmConfig({
633
+ scope: "global",
634
+ key: "AGENT_FS_DEFAULT_DRIVE_ID",
635
+ value: "shared-drive",
636
+ });
637
+
638
+ const token = "b".repeat(43);
639
+ const pendingInvite = { ok: true, status: "pending", inviteId: "invite-agent", token };
640
+ const provision = async (acceptStatus?: number) => {
641
+ const worker = await createAgent({
642
+ name: `Pending Worker ${acceptStatus ?? 200}`,
643
+ description: "Joins the shared org through an invite",
644
+ role: "worker",
645
+ isLead: false,
646
+ status: "idle",
647
+ maxTasks: 1,
648
+ capabilities: [],
649
+ });
650
+ await upsertSwarmConfig({
651
+ scope: "agent",
652
+ scopeId: worker.id,
653
+ key: "AGENT_EMAIL",
654
+ value: `pending-worker-${acceptStatus ?? 200}-${suffix}@example.test`,
655
+ });
656
+ const records: RequestRecord[] = [];
657
+ setAgentFsProvisionFetchForTests(
658
+ createFetchStub(records, { inviteResponse: pendingInvite, acceptStatus }),
659
+ );
660
+ const result = await ensureAgentFsCredentialsForAgent(worker.id);
661
+ return { result, records };
662
+ };
663
+
664
+ const accepted = await provision();
665
+ expect(accepted.result.created).toBe(true);
666
+ const accept = accepted.records.find((r) => r.path === `/invites/${token}/accept`);
667
+ expect(accept).toMatchObject({
668
+ method: "POST",
669
+ authorization: "Bearer example-afs-agent-key",
670
+ body: undefined,
671
+ });
672
+ const invitePos = accepted.records.findIndex((r) => r.path.endsWith("/members/invite"));
673
+ expect(accepted.records.indexOf(accept!)).toBeGreaterThan(invitePos);
674
+
675
+ // A failed accept keeps the stored key (as a failed invite does) and logs
676
+ // the status without the token.
677
+ const warn = spyOn(console, "warn").mockImplementation(() => {});
678
+ try {
679
+ const failed = await provision(404);
680
+ expect(failed.result.created).toBe(true);
681
+ const logged = warn.mock.calls.map((call) => String(call[0])).join("\n");
682
+ expect(logged).toContain("agent-fs invite accept failed: HTTP 404");
683
+ expect(logged).not.toContain(token);
684
+ } finally {
685
+ warn.mockRestore();
686
+ }
687
+ });
688
+
610
689
  test("profile sync failures leave existing credentials usable and retry later", async () => {
611
690
  process.env.AGENT_FS_API_URL = "https://agent-fs.example.test";
612
691
  const worker = await createAgent({
@@ -805,6 +884,7 @@ describe("agent-fs provisioning seeder", () => {
805
884
  inviteId: "invite-1",
806
885
  expiresAt: "2026-11-03T00:00:00.000Z",
807
886
  acceptUrl: `https://live.agent-fs.example.test/invite/${token}`,
887
+ token,
808
888
  });
809
889
  });
810
890
 
@@ -835,6 +915,7 @@ describe("agent-fs provisioning seeder", () => {
835
915
  status: "pending",
836
916
  inviteId: "invite-2",
837
917
  expiresAt: "2026-11-03T00:00:00.000Z",
918
+ token: "b".repeat(43),
838
919
  });
839
920
  });
840
921
  });