@desplega.ai/agent-swarm 2.8.1 → 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 (194) hide show
  1. package/dist/{acp-adapter-pdy3qsvg.js → acp-adapter-fqzkxyra.js} +3 -3
  2. package/dist/{actions-pwjpn0j6.js → actions-kxek041g.js} +17 -17
  3. package/dist/{amp-adapter-cq9jgj6x.js → amp-adapter-ce7jjke4.js} +1 -1
  4. package/dist/{app-cnfffgwg.js → app-v6zz8yh0.js} +3 -3
  5. package/dist/{assistant-kpn317y1.js → assistant-m0sw9xx2.js} +18 -18
  6. package/dist/{boot-args-schema-pbbnhmc3.js → boot-args-schema-66bk37wv.js} +1 -1
  7. package/dist/{boot-reembed-9m0ysxma.js → boot-reembed-edjpwsc1.js} +1 -1
  8. package/dist/{boot-reembed-majbn53m.js → boot-reembed-y27n09tz.js} +1 -1
  9. package/dist/{boot-scrub-sweep-app8g8ym.js → boot-scrub-sweep-1xc35965.js} +3 -3
  10. package/dist/{boot-seeds-pbtmvcjm.js → boot-seeds-7hjj91qj.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-ent8ch04.js} +1 -1
  12. package/dist/{claude-adapter-wn1g3qp5.js → claude-adapter-stw7jdcf.js} +3 -3
  13. package/dist/{claude-managed-setup-pd47nzch.js → claude-managed-setup-y6z2perp.js} +1 -1
  14. package/dist/{claude-sdk-session-3a2a6589.js → claude-sdk-session-vvya8wqk.js} +3 -3
  15. package/dist/{cli-wk18cm92.js → cli-0cq8y6m7.js} +1 -1
  16. package/dist/{cli-p1w18yhx.js → cli-1pz0330a.js} +1 -1
  17. package/dist/{cli-d3p5vwbk.js → cli-1qkz151v.js} +3 -3
  18. package/dist/{cli-89cqnasv.js → cli-26ctbcdp.js} +18 -6
  19. package/dist/{cli-syybb0p1.js → cli-2kvhc7x8.js} +7 -7
  20. package/dist/{cli-93k32c37.js → cli-3e875j5p.js} +128 -41
  21. package/dist/{cli-k0615eh8.js → cli-3sy2xags.js} +10 -10
  22. package/dist/{cli-dy32zecz.js → cli-3vmb0n58.js} +1 -1
  23. package/dist/{cli-4r05hnqa.js → cli-4vzgeta4.js} +13 -13
  24. package/dist/{cli-b5rs97a6.js → cli-5y340nzn.js} +4 -4
  25. package/dist/{cli-7p1kvkck.js → cli-6rc5frdm.js} +1 -1
  26. package/dist/{cli-jcpr5smb.js → cli-837vfs2x.js} +2 -2
  27. package/dist/{cli-b085njxz.js → cli-959kp5h2.js} +12 -11
  28. package/dist/{cli-k93bq1wq.js → cli-97ae65rz.js} +4 -4
  29. package/dist/{cli-m4dqmnbp.js → cli-9mb2q6pb.js} +1 -1
  30. package/dist/{cli-bb431xey.js → cli-a0z912j7.js} +121 -33
  31. package/dist/{cli-k26bkr9t.js → cli-b98a65ed.js} +3 -3
  32. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  33. package/dist/{cli-tk7cjj8h.js → cli-dzpc6en0.js} +1 -1
  34. package/dist/{cli-6mma83xa.js → cli-e1p3n5gq.js} +4 -4
  35. package/dist/{cli-re4raaj0.js → cli-f4e8r23x.js} +1 -1
  36. package/dist/{cli-qmqk2yc2.js → cli-f4r3g076.js} +1 -1
  37. package/dist/{cli-pcad4cb1.js → cli-f6bahpn5.js} +1 -1
  38. package/dist/{cli-b8e9nb04.js → cli-fpjmegdb.js} +1 -1
  39. package/dist/{cli-0ntbxyaa.js → cli-fwy8kfd6.js} +271 -37
  40. package/dist/{cli-tacge1w0.js → cli-g5mtmf6t.js} +6 -6
  41. package/dist/{cli-sn7rtnj4.js → cli-gyt3zydq.js} +3 -3
  42. package/dist/{cli-vbh10fqa.js → cli-j24zbska.js} +3 -3
  43. package/dist/{cli-vqptjbr7.js → cli-jdknh18m.js} +10 -10
  44. package/dist/{cli-7b8sbmag.js → cli-kjtwrhea.js} +1 -1
  45. package/dist/{cli-9vhebtjz.js → cli-mxn1qvbn.js} +3 -2
  46. package/dist/{cli-zcsw143p.js → cli-n6vtrcht.js} +1 -1
  47. package/dist/{cli-2zp0et3v.js → cli-pchypa1s.js} +55 -19
  48. package/dist/{cli-gax7fk3t.js → cli-pfs8adn4.js} +1 -1
  49. package/dist/{cli-1xh9a7hn.js → cli-q24n86d2.js} +2 -2
  50. package/dist/{cli-7w69ne2f.js → cli-rcecc3yq.js} +167 -43
  51. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  52. package/dist/{cli-yn2bbre9.js → cli-rmzsadkf.js} +1 -1
  53. package/dist/{cli-a3b239vq.js → cli-t2tma8gb.js} +1 -1
  54. package/dist/{cli-9wngrawf.js → cli-tekytdq9.js} +2 -2
  55. package/dist/{cli-tqegb8eq.js → cli-vdektqgf.js} +1 -1
  56. package/dist/{cli-cyhbbd1z.js → cli-w401b9tq.js} +1 -1
  57. package/dist/{cli-jywyhqws.js → cli-xf3qw745.js} +3 -3
  58. package/dist/{cli-hxpyc9sn.js → cli-z1w943va.js} +2 -2
  59. package/dist/{cli-yncmerje.js → cli-zh9rsbqf.js} +2 -2
  60. package/dist/cli.js +16 -16
  61. package/dist/{codex-adapter-nha71q3n.js → codex-adapter-zerf5qsp.js} +1 -1
  62. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-30gyhzxe.js} +1 -1
  63. package/dist/{codex-session-runner-ak9x1k1h.js → codex-session-runner-89s304py.js} +1 -1
  64. package/dist/{commands-f587qpq8.js → commands-jeh1b51j.js} +3 -3
  65. package/dist/{controller-hxx8wwy1.js → controller-mctfbrse.js} +3 -3
  66. package/dist/{controllers-connect-k5sg9m9h.js → controllers-connect-nxa1ddwn.js} +18 -18
  67. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-qj8vehv6.js} +1 -1
  68. package/dist/{db-nzf8zb5z.js → db-2dvay0es.js} +3 -3
  69. package/dist/{db-amm8w15a.js → db-b36qn6k3.js} +2 -2
  70. package/dist/{dispatcher-89zrts8f.js → dispatcher-gndbta01.js} +16 -16
  71. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-f75sz821.js} +1 -1
  72. package/dist/{e2b-jkwfhbcv.js → e2b-3gpc2n3w.js} +1 -1
  73. package/dist/{e2b-s16txnpx.js → e2b-jbm7mj93.js} +1 -1
  74. package/dist/{embedding-space-ezwenjmj.js → embedding-space-4p05vb2x.js} +6 -6
  75. package/dist/{embeddings-np74ht6g.js → embeddings-m6768mgh.js} +1 -1
  76. package/dist/{external-channel-z46yx9d7.js → external-channel-gjv3jne3.js} +2 -2
  77. package/dist/{fx-adapter-3q12snn6.js → fx-adapter-rpsgb1tw.js} +4 -4
  78. package/dist/{grok-adapter-ahb1w033.js → grok-adapter-n2m3zjg1.js} +4 -4
  79. package/dist/handlers-nv8edn19.js +32 -0
  80. package/dist/{heartbeat-dt9qw9c8.js → heartbeat-a1tv60gt.js} +19 -19
  81. package/dist/{hook-8k6fbz9b.js → hook-8h5dzcgq.js} +2 -2
  82. package/dist/{hook-jgcgygex.js → hook-cyaps9ba.js} +4 -4
  83. package/dist/{http-haw4r8ne.js → http-t15mhbd9.js} +1731 -77
  84. package/dist/{index-s4ewdma4.js → index-ksmyd6kc.js} +16 -16
  85. package/dist/{index-tez78qj3.js → index-qav6455f.js} +13 -11
  86. package/dist/index-rjnrje98.js +32 -0
  87. package/dist/index-tv3413wy.js +33 -0
  88. package/dist/{index-5gk12my8.js → index-w1zqf680.js} +1 -1
  89. package/dist/{keepalive-xn6s7rmg.js → keepalive-91s7hzrb.js} +3 -3
  90. package/dist/{lead-6ygbfhbh.js → lead-3hmddvrm.js} +30 -30
  91. package/dist/{maintenance-vdts800b.js → maintenance-7pjmy5xy.js} +1 -1
  92. package/dist/{oauth-refresh-sweep-094c8wfk.js → oauth-refresh-sweep-rzqfm94j.js} +2 -2
  93. package/dist/{onboard-v99eh56m.js → onboard-74st7pag.js} +3 -3
  94. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-arn7gm8q.js} +2 -2
  95. package/dist/{otel-impl-q7yr9yp0.js → otel-impl-rnzey8cb.js} +1 -1
  96. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-6mkwq64n.js} +3 -2
  97. package/dist/{pricing-refresh-7dh2yase.js → pricing-refresh-ha21jhk7.js} +2 -2
  98. package/dist/{rbac-roles-npbmdh77.js → rbac-roles-59dxachk.js} +2 -2
  99. package/dist/{rbac-roles-mdmc96p4.js → rbac-roles-wqhma4dr.js} +3 -3
  100. package/dist/{render-v2-twhhwmms.js → render-v2-14kpzx12.js} +3 -3
  101. package/dist/{resume-5gsrjd5e.js → resume-gsa5fb5f.js} +6 -6
  102. package/dist/{session-access-m191x30x.js → session-access-skm7bnp6.js} +4 -4
  103. package/dist/{session-source-backfill-nt923ask.js → session-source-backfill-pbqzbncv.js} +2 -2
  104. package/dist/{setup-wv467afy.js → setup-5yermsem.js} +1 -1
  105. package/dist/{work-objects-8zkrpy13.js → work-objects-xj0ck0w4.js} +19 -19
  106. package/dist/{worker-follow-up-cecqszem.js → worker-follow-up-911xc0b8.js} +18 -16
  107. package/dist/{worker-mz5z7kj0.js → worker-qgg0m2gw.js} +30 -30
  108. package/openapi.json +1741 -290
  109. package/package.json +2 -2
  110. package/src/apps/catalog.generated.json +120 -1
  111. package/src/apps/definition.ts +38 -11
  112. package/src/apps/page-validator.ts +88 -0
  113. package/src/be/db/model-profiles.ts +110 -11
  114. package/src/be/db/tasks/read.ts +20 -0
  115. package/src/be/db/workflow-run-definitions.ts +19 -8
  116. package/src/be/db-client.ts +43 -5
  117. package/src/be/db.ts +9 -3
  118. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  119. package/src/be/model-profile-check.ts +43 -18
  120. package/src/be/runtime-pools/routing.ts +1 -0
  121. package/src/be/savings/calibrate.ts +468 -0
  122. package/src/be/savings/compute.ts +182 -0
  123. package/src/be/savings/model.ts +406 -0
  124. package/src/be/scripts/typecheck.ts +5 -0
  125. package/src/be/seed/agent-fs-provision.ts +48 -11
  126. package/src/be/seed/workflows-seeder.ts +67 -23
  127. package/src/be/skill-parser.ts +19 -7
  128. package/src/commands/onboard/agent-fs-version.ts +1 -1
  129. package/src/commands/provider-error-class.ts +97 -0
  130. package/src/commands/runner.ts +99 -17
  131. package/src/extensions/contract-types.generated.ts +1 -1
  132. package/src/http/all-routes.ts +2 -0
  133. package/src/http/fs.ts +8 -2
  134. package/src/http/index.ts +4 -0
  135. package/src/http/model-profiles.ts +43 -10
  136. package/src/http/poll.ts +1 -0
  137. package/src/http/savings-calibration.ts +277 -0
  138. package/src/http/savings.ts +363 -0
  139. package/src/http/tasks.ts +46 -4
  140. package/src/http/trackers/authorize-gate.ts +41 -0
  141. package/src/http/trackers/jira.ts +26 -4
  142. package/src/http/trackers/linear.ts +26 -4
  143. package/src/integrations/chat-sdk/limits.ts +6 -1
  144. package/src/jira/oauth.ts +7 -1
  145. package/src/linear/README.md +2 -1
  146. package/src/linear/oauth.ts +7 -1
  147. package/src/providers/amp-adapter.ts +1 -1
  148. package/src/providers/codex-adapter.ts +3 -0
  149. package/src/providers/pi-mono-adapter.ts +6 -5
  150. package/src/providers/types.ts +7 -0
  151. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  152. package/src/scripts-runtime/swarm-sdk.ts +6 -0
  153. package/src/scripts-runtime/types/stdlib.d.ts +9 -0
  154. package/src/scripts-runtime/types/swarm-extension.d.ts +34 -0
  155. package/src/scripts-runtime/types/swarm-sdk.d.ts +9 -0
  156. package/src/tasks/worker-follow-up.ts +142 -3
  157. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  158. package/src/tests/apps-chart-shell.test.ts +170 -0
  159. package/src/tests/apps-icon.test.ts +156 -2
  160. package/src/tests/chat-sdk-relay.test.ts +12 -0
  161. package/src/tests/codex-adapter.test.ts +11 -0
  162. package/src/tests/comb-default.test.ts +6 -0
  163. package/src/tests/core-auth.test.ts +7 -6
  164. package/src/tests/db-client-busy-retry.test.ts +58 -6
  165. package/src/tests/deploy-guard.test.ts +154 -0
  166. package/src/tests/docs-index-footprint.test.js +3 -3
  167. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  168. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  169. package/src/tests/model-profiles-api.test.ts +1 -0
  170. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  171. package/src/tests/provider-error-class.test.ts +174 -0
  172. package/src/tests/runner-provider-fallback.test.ts +197 -0
  173. package/src/tests/savings-calibration-api.test.ts +264 -0
  174. package/src/tests/savings-calibration.test.ts +201 -0
  175. package/src/tests/savings-compute.test.ts +406 -0
  176. package/src/tests/savings-model.test.ts +287 -0
  177. package/src/tests/script-connections.test.ts +2 -0
  178. package/src/tests/sdk-allowlist.test.ts +40 -0
  179. package/src/tests/seed-workflows.test.ts +167 -11
  180. package/src/tests/skill-parser.test.ts +45 -0
  181. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  182. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  183. package/src/tests/workflow-script-principal.test.ts +94 -4
  184. package/src/tools/app-upsert.ts +1 -1
  185. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  186. package/src/tools/update-profile.ts +1 -1
  187. package/src/types.ts +115 -33
  188. package/src/utils/constants.ts +2 -0
  189. package/templates/skills/apps/SKILL.md +62 -3
  190. package/templates/skills/apps/content.md +62 -3
  191. package/templates/skills/swarm-docs/content.md +2 -0
  192. package/dist/handlers-vbww69re.js +0 -32
  193. package/dist/index-4xwaf5th.js +0 -32
  194. package/dist/index-f0hcrs8e.js +0 -33
@@ -31,20 +31,32 @@ export function parseSkillContent(content: string): ParsedSkill {
31
31
  throw new Error("Skill content has unterminated frontmatter. Missing closing ---.");
32
32
  }
33
33
 
34
- const frontmatterRaw = trimmed.slice(3, secondDelimiter).trim();
34
+ const frontmatterRaw = trimmed.slice(3, secondDelimiter);
35
35
  const body = trimmed.slice(secondDelimiter + 3).trim();
36
36
 
37
- // Parse simple YAML key-value pairs
37
+ // Keep permissive single-line values; delegate block scalar semantics to YAML.
38
38
  const metadata: Record<string, string> = {};
39
- for (const line of frontmatterRaw.split("\n")) {
39
+ const lines = frontmatterRaw.split("\n");
40
+ for (let i = 0; i < lines.length; i++) {
41
+ const line = lines[i] as string;
40
42
  const colonIdx = line.indexOf(":");
41
43
  if (colonIdx === -1) continue;
42
44
  const key = line.slice(0, colonIdx).trim();
43
45
  let value = line.slice(colonIdx + 1).trim();
44
- // YAML double-quoted scalars (emitted by buildSkillContent for values a
45
- // plain scalar can't carry, and common in hand-written frontmatter): strip
46
- // the quotes and JSON escapes. Malformed quoting falls back to the raw text.
47
- if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
46
+ if (/^[>|][-+]?$/.test(value)) {
47
+ const start = i;
48
+ const indentation = line.length - line.trimStart().length;
49
+ while (i + 1 < lines.length) {
50
+ const next = lines[i + 1] as string;
51
+ if (next.trim() && next.length - next.trimStart().length <= indentation) break;
52
+ i++;
53
+ }
54
+ // The final split entry already represents the frontmatter's terminating newline.
55
+ const scalar = lines.slice(start, i + 1).join("\n") + (i < lines.length - 1 ? "\n" : "");
56
+ const block = Bun.YAML.parse(scalar) as Record<string, string>;
57
+ value = block[key] ?? "";
58
+ } else if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
59
+ // Preserve the existing JSON-unescaping and malformed-quote fallback.
48
60
  try {
49
61
  value = JSON.parse(value) as string;
50
62
  } catch {
@@ -2,4 +2,4 @@
2
2
  * agent-fs image tag bundled by `agent-swarm onboard --yes`.
3
3
  * `bun run bump:agent-fs` rewrites it together with the other pins.
4
4
  */
5
- export const AGENT_FS_VERSION = "0.18.18";
5
+ export const AGENT_FS_VERSION = "0.18.22";
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Which provider errors move a task to its next fallback profile
3
+ * (runbooks/model-tiers.md § Fallbacks on provider errors).
4
+ *
5
+ * Pure and worker-side: the runner classifies a finished session, and the API
6
+ * picks the next profile. A hit means another profile on the same agent may
7
+ * run the work where this one cannot right now. Task failures, tool errors,
8
+ * harness-side exceptions (`errorOrigin: "harness"`), context overflow,
9
+ * cancellation and budget refusals never hit.
10
+ */
11
+ import type { ProviderResult } from "../providers/types";
12
+ import type { ProviderErrorClass } from "../types";
13
+ import { isCodexAuthFailureReason } from "../utils/codex-auth-failure";
14
+ import { isCodexCreditsExhaustedMessage } from "../utils/error-tracker";
15
+ import { modelFamilyOf } from "../utils/model-rate-limit-windows";
16
+ import { classifyRateLimitOutcome, type RateLimitOutcome } from "./rate-limit-outcome";
17
+
18
+ type ClassifiableProviderResult = Parameters<typeof classifyRateLimitOutcome>[0] & {
19
+ exitCode: number;
20
+ errorCategory?: string;
21
+ errorOrigin?: ProviderResult["errorOrigin"];
22
+ };
23
+
24
+ /** Endings that are the task's own, whatever the text around them says. */
25
+ const NEVER_FALLBACK =
26
+ /max turns exceeded|budget limit exceeded|error_max_budget|context (window|length|limit)|prompt is too long|maximum context length|context_length_exceeded/i;
27
+
28
+ /** Claude stream `authentication_failed`, plus the usual 401 texts of every harness. */
29
+ const AUTH_FAILURE =
30
+ /authentication[ _](?:failed|error)|invalid[ _]api[ _]key|\bhttp 401\b|\b401 unauthori[sz]ed/i;
31
+
32
+ /** Anthropic 529 and every "overloaded" text. */
33
+ const OVERLOADED = /overloaded|\b529\b/i;
34
+
35
+ /** Any 5xx status (500-599) or a 5xx reason phrase. */
36
+ const SERVER_ERROR =
37
+ /\b(?:status|http|error|code)[ :]*5\d\d\b|internal server error|bad gateway|service unavailable|gateway time-?out|insufficient storage|server_error/i;
38
+
39
+ /**
40
+ * The fallback class of a finished session, or null when it is not a provider
41
+ * error. `rateLimitOutcome` is the runner's `classifyRateLimitOutcome` result
42
+ * for the same session.
43
+ */
44
+ export function classifyProviderError(
45
+ result: ClassifiableProviderResult,
46
+ failureReason: string | undefined,
47
+ rateLimitOutcome: RateLimitOutcome,
48
+ ): { errorClass: ProviderErrorClass } | null {
49
+ if (result.exitCode === 0) return null;
50
+ if (result.errorCategory === "cancelled") return null;
51
+ // A harness-side exception (MCP, transport): its text may quote a tool's
52
+ // HTTP status or rate limit, which says nothing about the provider.
53
+ if (result.errorOrigin === "harness") return null;
54
+ const text = failureReason ?? "";
55
+ if (NEVER_FALLBACK.test(text)) return null;
56
+
57
+ switch (rateLimitOutcome.kind) {
58
+ case "seat":
59
+ return { errorClass: "seat" };
60
+ case "model":
61
+ return { errorClass: "model_window" };
62
+ case "key":
63
+ return {
64
+ errorClass: isCodexCreditsExhaustedMessage(text) ? "credits" : "rate_limit",
65
+ };
66
+ case "none":
67
+ break;
68
+ }
69
+ if (!text) return null;
70
+ if (isCodexAuthFailureReason(text) || AUTH_FAILURE.test(text)) return { errorClass: "auth" };
71
+ if (OVERLOADED.test(text)) return { errorClass: "overloaded" };
72
+ if (SERVER_ERROR.test(text)) return { errorClass: "server_error" };
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * `classifyProviderError` with the runner's own rate-limit classification of
78
+ * the session (the same one its credential report uses). Returns the class
79
+ * alone, or null.
80
+ */
81
+ export function classifyProviderErrorOf(
82
+ result: ClassifiableProviderResult,
83
+ failureReason: string | undefined,
84
+ model: string | undefined,
85
+ codexCreditsExhaustedCooldownMs?: number,
86
+ nowMs = Date.now(),
87
+ ): ProviderErrorClass | null {
88
+ if (result.exitCode === 0) return null;
89
+ const outcome = classifyRateLimitOutcome(
90
+ result,
91
+ failureReason,
92
+ nowMs,
93
+ codexCreditsExhaustedCooldownMs,
94
+ modelFamilyOf(model),
95
+ );
96
+ return classifyProviderError(result, failureReason, outcome)?.errorClass ?? null;
97
+ }
@@ -66,6 +66,7 @@ import {
66
66
  type DeliveryMode,
67
67
  isTerminalTaskStatus,
68
68
  type ModelTierOverrides,
69
+ type ProviderErrorClass,
69
70
  type ProviderName,
70
71
  parseWorkerModelTierOverrides,
71
72
  type ReasoningEffort,
@@ -154,6 +155,7 @@ import {
154
155
  reportLatestModel,
155
156
  sendCredStatusReport,
156
157
  } from "./provider-credentials.ts";
158
+ import { classifyProviderErrorOf } from "./provider-error-class.ts";
157
159
  import {
158
160
  RunnerPushDelivery,
159
161
  shouldRunDeliveryLoop,
@@ -2357,12 +2359,57 @@ export async function createSessionReportingAuthFailure(
2357
2359
  * back to the legacy `pauseTaskViaAPI` (handles partial-deploy windows where
2358
2360
  * the API is older than the worker).
2359
2361
  */
2362
+ /**
2363
+ * Ask the API to move a task that hit a provider error to its next fallback
2364
+ * profile (runbooks/model-tiers.md § Fallbacks on provider errors). Only a
2365
+ * task claim gave a profile (`resolvedProfile`) can hop. `superseded`: the
2366
+ * task is terminal and its resume runs the fallback, so the caller must not
2367
+ * finish it. Otherwise the caller fails it as usual, led by `failureReason`
2368
+ * when the API says why the chain ended. An older API rejects the reason
2369
+ * (4xx) and the task fails as before.
2370
+ */
2371
+ export async function requestProviderFallback(
2372
+ config: ApiConfig,
2373
+ role: string,
2374
+ taskId: string,
2375
+ input: {
2376
+ resolvedProfile?: string;
2377
+ errorClass: ProviderErrorClass | null;
2378
+ failureReason?: string;
2379
+ },
2380
+ ): Promise<{ superseded: boolean; failureReason?: string }> {
2381
+ if (!input.resolvedProfile || !input.errorClass) return { superseded: false };
2382
+ const outcome = await supersedeTaskViaAPI(config, role, taskId, "provider_fallback", {
2383
+ errorClass: input.errorClass,
2384
+ });
2385
+ if (!outcome.ok) return { superseded: false };
2386
+ if (outcome.kind === "resumed") {
2387
+ console.log(
2388
+ `[${role}] Task ${taskId.slice(0, 8)} hit ${input.errorClass} on ${input.resolvedProfile}; resuming on the next fallback profile`,
2389
+ );
2390
+ return { superseded: true };
2391
+ }
2392
+ if (outcome.kind === "noFallback" && outcome.failureReason) {
2393
+ return {
2394
+ superseded: false,
2395
+ failureReason: input.failureReason
2396
+ ? `${outcome.failureReason}\n\n${input.failureReason}`
2397
+ : outcome.failureReason,
2398
+ };
2399
+ }
2400
+ return { superseded: false };
2401
+ }
2402
+
2360
2403
  async function supersedeTaskViaAPI(
2361
2404
  config: ApiConfig,
2362
2405
  role: string,
2363
2406
  taskId: string,
2364
- reason: "graceful_shutdown" | "context_limits" | "manual_supersede",
2365
- ): Promise<{ ok: true; resumeTaskId: string | null; kind: string } | { ok: false }> {
2407
+ reason: "graceful_shutdown" | "context_limits" | "manual_supersede" | "provider_fallback",
2408
+ extra: { errorClass?: ProviderErrorClass } = {},
2409
+ ): Promise<
2410
+ | { ok: true; resumeTaskId: string | null; kind: string; failureReason?: string | null }
2411
+ | { ok: false }
2412
+ > {
2366
2413
  const headers: Record<string, string> = {
2367
2414
  "X-Agent-ID": config.agentId,
2368
2415
  "Content-Type": "application/json",
@@ -2375,13 +2422,14 @@ async function supersedeTaskViaAPI(
2375
2422
  const response = await fetch(`${config.apiUrl}/api/tasks/${taskId}/supersede`, {
2376
2423
  method: "POST",
2377
2424
  headers,
2378
- body: JSON.stringify({ reason }),
2425
+ body: JSON.stringify({ reason, ...extra }),
2379
2426
  });
2380
2427
 
2381
2428
  if (response.ok) {
2382
2429
  const body = (await response.json().catch(() => null)) as {
2383
2430
  resumeTaskId?: string | null;
2384
2431
  kind?: string;
2432
+ failureReason?: string | null;
2385
2433
  } | null;
2386
2434
  const resumeTaskId = body?.resumeTaskId ?? null;
2387
2435
  const kind = body?.kind ?? "resumed";
@@ -2390,7 +2438,7 @@ async function supersedeTaskViaAPI(
2390
2438
  resumeTaskId ? resumeTaskId.slice(0, 8) : "none"
2391
2439
  })`,
2392
2440
  );
2393
- return { ok: true, resumeTaskId, kind };
2441
+ return { ok: true, resumeTaskId, kind, failureReason: body?.failureReason ?? null };
2394
2442
  }
2395
2443
 
2396
2444
  // 404 / 405 — the route doesn't exist on this API server. Happens during
@@ -2778,6 +2826,11 @@ export interface RunningTask {
2778
2826
  harnessVariantMeta?: Record<string, unknown>;
2779
2827
  /** Resolved model used for the provider session, when configured */
2780
2828
  model?: string;
2829
+ /**
2830
+ * The profile claim applied (`task.resolvedProfile`). A provider error on a
2831
+ * task with one asks the API for the next fallback profile.
2832
+ */
2833
+ resolvedProfile?: string;
2781
2834
  /**
2782
2835
  * Last non-empty assistant text captured from `message` events, shared by
2783
2836
  * reference with the `onEvent` closure. Fallback `providerOutput` when the
@@ -4318,15 +4371,24 @@ export async function spawnProviderProcess(
4318
4371
  ) {
4319
4372
  const reason = err.message;
4320
4373
  console.warn(`[${opts.role}] ${reason}`);
4321
- await ensureTaskFinished(
4322
- { apiUrl: opts.apiUrl, apiKey: opts.apiKey, agentId: opts.agentId },
4323
- opts.role,
4324
- realTaskId,
4325
- 1,
4326
- reason,
4327
- undefined,
4328
- opts.harnessProvider,
4329
- );
4374
+ const apiConfig = { apiUrl: opts.apiUrl, apiKey: opts.apiKey, agentId: opts.agentId };
4375
+ // No usable key for this profile right now: its fallback may have one.
4376
+ const fallback = await requestProviderFallback(apiConfig, opts.role, realTaskId, {
4377
+ resolvedProfile: opts.resolvedProfile,
4378
+ errorClass: "pool_empty",
4379
+ failureReason: reason,
4380
+ });
4381
+ if (!fallback.superseded) {
4382
+ await ensureTaskFinished(
4383
+ apiConfig,
4384
+ opts.role,
4385
+ realTaskId,
4386
+ 1,
4387
+ fallback.failureReason ?? reason,
4388
+ undefined,
4389
+ opts.harnessProvider,
4390
+ );
4391
+ }
4330
4392
  }
4331
4393
  throw err;
4332
4394
  }
@@ -5264,6 +5326,7 @@ export async function spawnProviderProcess(
5264
5326
  harnessProvider: opts.harnessProvider,
5265
5327
  hasLocalEnvironment: adapter.traits.hasLocalEnvironment,
5266
5328
  model: model || undefined,
5329
+ resolvedProfile: opts.resolvedProfile,
5267
5330
  assistantText: assistantTextHolder,
5268
5331
  finalProgress: finalProgressHolder,
5269
5332
  lastCost: lastCostHolder,
@@ -5504,6 +5567,7 @@ export async function checkCompletedProcesses(
5504
5567
  harnessVariant?: string;
5505
5568
  harnessVariantMeta?: Record<string, unknown>;
5506
5569
  model?: string;
5570
+ resolvedProfile?: string;
5507
5571
  durationMs: number;
5508
5572
  assistantText?: RunningTask["assistantText"];
5509
5573
  finalProgress?: RunningTask["finalProgress"];
@@ -5530,6 +5594,7 @@ export async function checkCompletedProcesses(
5530
5594
  harnessVariant: task.harnessVariant,
5531
5595
  harnessVariantMeta: task.harnessVariantMeta,
5532
5596
  model: task.model,
5597
+ resolvedProfile: task.resolvedProfile,
5533
5598
  durationMs: Date.now() - task.startTime.getTime(),
5534
5599
  assistantText: task.assistantText,
5535
5600
  finalProgress: task.finalProgress,
@@ -5555,6 +5620,7 @@ export async function checkCompletedProcesses(
5555
5620
  harnessVariant,
5556
5621
  harnessVariantMeta,
5557
5622
  model,
5623
+ resolvedProfile,
5558
5624
  durationMs,
5559
5625
  assistantText,
5560
5626
  finalProgress,
@@ -5660,13 +5726,28 @@ export async function checkCompletedProcesses(
5660
5726
  codexCreditsExhaustedCooldownMs: state.codexCreditsExhaustedCooldownMs,
5661
5727
  modelWindowBlocks: state.modelWindowBlocks,
5662
5728
  },
5663
- () =>
5664
- ensureTaskFinished(
5729
+ async () => {
5730
+ // A provider error on a profile task: the API resumes it on
5731
+ // the next fallback profile, or says why none is left.
5732
+ const fallback = await requestProviderFallback(apiConfig, role, taskId, {
5733
+ resolvedProfile,
5734
+ failureReason,
5735
+ errorClass: resolvedProfile
5736
+ ? classifyProviderErrorOf(
5737
+ result,
5738
+ failureReason,
5739
+ model,
5740
+ state.codexCreditsExhaustedCooldownMs,
5741
+ )
5742
+ : null,
5743
+ });
5744
+ if (fallback.superseded) return;
5745
+ await ensureTaskFinished(
5665
5746
  apiConfig,
5666
5747
  role,
5667
5748
  taskId,
5668
5749
  result.exitCode,
5669
- failureReason,
5750
+ fallback.failureReason ?? failureReason,
5670
5751
  // Runner-buffered last assistant text is a harness-agnostic fallback
5671
5752
  // for adapters that never populate `ProviderResult.output` (Codex
5672
5753
  // today, any future adapter). Empty buffer -> `undefined`, byte
@@ -5676,7 +5757,8 @@ export async function checkCompletedProcesses(
5676
5757
  bridgeFailureDiagnostics,
5677
5758
  finalProgress?.value,
5678
5759
  deadline,
5679
- ),
5760
+ );
5761
+ },
5680
5762
  );
5681
5763
 
5682
5764
  const sessionTriggerSurface = workerTriggerSurface(triggerSurface);
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/bundle-extension-types.ts. Do not edit.
2
2
  // biome-ignore-all lint/suspicious/noTemplateCurlyInString: Type declarations contain literal template placeholders.
3
3
  export const EXTENSION_TYPE_DEFINITIONS =
4
- '// biome-ignore-all lint/suspicious/noConfusingVoidType: Extension handlers may explicitly return no result.\ndeclare module "swarm-extension" {\n export type CreateTaskOptions = {\n key?: string | undefined;\n agentId?: string | null | undefined;\n creatorAgentId?: string | undefined;\n source?:\n | "chat"\n | "workflow"\n | "schedule"\n | "slack"\n | "agentmail"\n | "github"\n | "gitlab"\n | "azure-devops"\n | "bitbucket"\n | "linear"\n | "jira"\n | "mcp"\n | "api"\n | "ui"\n | "system"\n | "comb"\n | undefined;\n routingReason?:\n | "skill"\n | "continuity"\n | "overflow"\n | "human_pinned"\n | "reroute_fault"\n | undefined;\n routingSource?: "declared" | "engine_default" | undefined;\n routingNote?: string | undefined;\n taskType?: string | undefined;\n tags?: string[] | undefined;\n priority?: number | undefined;\n dependsOn?: string[] | undefined;\n offeredTo?: string | undefined;\n status?: "draft" | "backlog" | "unassigned" | undefined;\n slackChannelId?: string | undefined;\n slackThreadTs?: string | undefined;\n slackTriggerMessageTs?: string | undefined;\n slackUserId?: string | undefined;\n overrideSlackContext?: boolean | undefined;\n vcsProvider?: "github" | "gitlab" | "azure-devops" | "bitbucket" | undefined;\n vcsRepo?: string | undefined;\n vcsEventType?: string | undefined;\n vcsNumber?: number | undefined;\n vcsCommentId?: number | undefined;\n vcsAuthor?: string | undefined;\n vcsUrl?: string | undefined;\n vcsInstallationId?: number | undefined;\n vcsNodeId?: string | undefined;\n agentmailInboxId?: string | undefined;\n agentmailMessageId?: string | undefined;\n agentmailThreadId?: string | undefined;\n mentionMessageId?: string | undefined;\n mentionChannelId?: string | undefined;\n dir?: string | undefined;\n parentTaskId?: string | undefined;\n model?: string | undefined;\n modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;\n effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;\n profile?: string | undefined;\n scheduleId?: string | undefined;\n workflowRunId?: string | undefined;\n workflowRunStepId?: string | undefined;\n sourceTaskId?: string | undefined;\n dispatchedByTaskId?: string | undefined;\n outputSchema?: Record<string, unknown> | undefined;\n inheritParentOutputSchema?: boolean | undefined;\n inheritParentRequester?: boolean | undefined;\n inheritParentRoutingAffinity?: boolean | undefined;\n inheritParentFollowUpConfig?: boolean | undefined;\n followUpConfig?:\n | {\n disabled?: boolean | undefined;\n onCompleted?: string | undefined;\n onFailed?: string | undefined;\n }\n | undefined;\n requestedByUserId?: string | undefined;\n contextKey?: string | undefined;\n bypassTrackerContextDedup?: boolean | undefined;\n routingAffinity?:\n | {\n capabilities: string[];\n sourceAgentId?: string | undefined;\n role?: string | undefined;\n harnessProvider?:\n | "pi"\n | "claude"\n | "claude-managed"\n | "codex"\n | "grok"\n | "fx"\n | "opencode"\n | "dsh"\n | "cursor"\n | "amp"\n | "devin"\n | "acp"\n | undefined;\n leadOnly?: boolean | undefined;\n }\n | undefined;\n };\n\n export type AgentTask = {\n id: string;\n key: string;\n agentId: string | null;\n task: string;\n status:\n | "skipped"\n | "draft"\n | "backlog"\n | "unassigned"\n | "offered"\n | "reviewing"\n | "pending"\n | "in_progress"\n | "paused"\n | "completed"\n | "failed"\n | "cancelled"\n | "superseded";\n source:\n | "chat"\n | "workflow"\n | "schedule"\n | "slack"\n | "agentmail"\n | "github"\n | "gitlab"\n | "azure-devops"\n | "bitbucket"\n | "linear"\n | "jira"\n | "mcp"\n | "api"\n | "ui"\n | "system"\n | "comb";\n tags: string[];\n priority: number;\n dependsOn: string[];\n createdAt: string;\n lastUpdatedAt: string;\n slackReplySent: boolean;\n wasPaused: boolean;\n creatorAgentId?: string | undefined;\n title?: string | undefined;\n routingReason?:\n | "skill"\n | "continuity"\n | "overflow"\n | "human_pinned"\n | "reroute_fault"\n | undefined;\n routingSource?: "declared" | "engine_default" | undefined;\n routingNote?: string | undefined;\n poolWakeAt?: string | undefined;\n taskType?: string | undefined;\n offeredTo?: string | undefined;\n offeredAt?: string | undefined;\n acceptedAt?: string | undefined;\n rejectionReason?: string | undefined;\n finishedAt?: string | undefined;\n notifiedAt?: string | undefined;\n failureReason?: string | undefined;\n output?: string | undefined;\n progress?: string | undefined;\n slackChannelId?: string | undefined;\n slackThreadTs?: string | undefined;\n slackTriggerMessageTs?: string | undefined;\n slackUserId?: string | undefined;\n slackProgressMessageTs?: string | undefined;\n slackTreeRootMessageTs?: string | undefined;\n vcsProvider?: "github" | "gitlab" | "azure-devops" | "bitbucket" | undefined;\n vcsRepo?: string | undefined;\n vcsEventType?: string | undefined;\n vcsNumber?: number | undefined;\n vcsCommentId?: number | undefined;\n vcsAuthor?: string | undefined;\n vcsUrl?: string | undefined;\n vcsInstallationId?: number | undefined;\n vcsNodeId?: string | undefined;\n agentmailInboxId?: string | undefined;\n agentmailMessageId?: string | undefined;\n agentmailThreadId?: string | undefined;\n mentionMessageId?: string | undefined;\n mentionChannelId?: string | undefined;\n dir?: string | undefined;\n parentTaskId?: string | undefined;\n dispatchedByTaskId?: string | undefined;\n claudeSessionId?: string | undefined;\n model?: string | undefined;\n modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;\n effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;\n resolvedModel?: string | undefined;\n modelSource?: string | undefined;\n modelAlias?: string | undefined;\n resolvedEffort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;\n profile?: string | undefined;\n resolvedProfile?: string | undefined;\n scheduleId?: string | undefined;\n workflowRunId?: string | null | undefined;\n workflowRunStepId?: string | null | undefined;\n contextKey?: string | undefined;\n outputSchema?: Record<string, unknown> | undefined;\n followUpConfig?:\n | {\n disabled?: boolean | undefined;\n onCompleted?: string | undefined;\n onFailed?: string | undefined;\n }\n | undefined;\n deferredAt?: string | undefined;\n compactionCount?: number | undefined;\n peakContextPercent?: number | undefined;\n peakContextTokens?: number | undefined;\n contextWindowSize?: number | undefined;\n credentialKeySuffix?: string | undefined;\n credentialKeyType?: string | undefined;\n requestedByUserId?: string | undefined;\n swarmVersion?: string | undefined;\n provider?:\n | "pi"\n | "claude"\n | "claude-managed"\n | "codex"\n | "grok"\n | "fx"\n | "opencode"\n | "dsh"\n | "cursor"\n | "amp"\n | "devin"\n | "acp"\n | undefined;\n providerMeta?: Record<string, unknown> | undefined;\n harnessVariant?: string | undefined;\n harnessVariantMeta?: Record<string, unknown> | undefined;\n totalCostUsd?: number | undefined;\n routingAffinity?:\n | {\n capabilities: string[];\n sourceAgentId?: string | undefined;\n role?: string | undefined;\n harnessProvider?:\n | "pi"\n | "claude"\n | "claude-managed"\n | "codex"\n | "grok"\n | "fx"\n | "opencode"\n | "dsh"\n | "cursor"\n | "amp"\n | "devin"\n | "acp"\n | undefined;\n leadOnly?: boolean | undefined;\n }\n | undefined;\n routingAffinityInvalid?: boolean | undefined;\n };\n\n export type ActiveSession = {\n id: string;\n agentId: string;\n taskId: string | null;\n triggerType: string;\n inboxMessageId: string | null;\n taskDescription: string | null;\n runnerSessionId: string | null;\n providerSessionId: string | null;\n startedAt: string;\n lastHeartbeatAt: string;\n runtimeInstanceId?: string | null | undefined;\n };\n\n export type SteerMode = "steer" | "queue";\n\n export type SteeringSource = "chat" | "script" | "slack" | "mcp" | "api" | "ui";\n\n export type RequestInfo = {\n sessionId: string | undefined;\n agentId: string | undefined;\n runtimeInstanceId: string | undefined;\n sourceTaskId: string | undefined;\n contextKey: string | undefined;\n callOrigin: "mcp" | "extension" | "script-sdk";\n };\n\n import type { SwarmSdk } from "swarm-sdk";\n import type { z } from "zod";\n export type Runtime = "api" | "worker";\n export interface ExtensionScriptAsset {\n name: string;\n file: string;\n description: string;\n intent?: string;\n }\n export interface ExtensionScheduleAsset {\n name: string;\n description?: string;\n script: string;\n cronExpression?: string;\n intervalMs?: number;\n timezone?: string;\n args?: Record<string, unknown>;\n }\n export interface ExtensionWorkflowAsset {\n file: string;\n }\n export interface ExtensionSkillAsset {\n dir: string;\n }\n export interface ExtensionManifest {\n $schema?: string;\n name: string;\n description: string;\n version: string;\n runtime: Runtime;\n assets: {\n hooks: string;\n scripts?: readonly ExtensionScriptAsset[];\n schedules?: readonly ExtensionScheduleAsset[];\n workflows?: readonly ExtensionWorkflowAsset[];\n skills?: readonly ExtensionSkillAsset[];\n };\n homepage?: string;\n author?: string;\n }\n export interface HooksModule {\n default: SwarmExtension;\n config?: z.ZodTypeAny;\n }\n export interface ExtensionState {\n get<T = unknown>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n incr(key: string, by?: number): Promise<number>;\n del(key: string): Promise<void>;\n }\n export interface ExtensionLogger {\n debug(message: string, data?: unknown): void;\n info(message: string, data?: unknown): void;\n warn(message: string, data?: unknown): void;\n error(message: string, data?: unknown): void;\n }\n type ConfigFor<M extends ExtensionManifest> = M extends {\n config: infer C extends z.ZodTypeAny;\n }\n ? z.infer<C>\n : Record<string, unknown>;\n export interface ApiCtx<Config = Record<string, unknown>> {\n swarm: SwarmSdk;\n state: ExtensionState;\n config: Config;\n log: ExtensionLogger;\n signal: AbortSignal;\n event: {\n name: keyof SwarmEventMap;\n at: string;\n extension: {\n id: string;\n version: number;\n };\n };\n }\n export interface WorkerCtx<Config = Record<string, unknown>>\n extends Omit<ApiCtx<Config>, "swarm"> {\n swarm: SwarmSdk;\n worker: {\n agentId: string;\n taskId: string;\n harness: string;\n };\n }\n export type CtxFor<M extends ExtensionManifest> = M["runtime"] extends "api"\n ? ApiCtx<ConfigFor<M>>\n : WorkerCtx<ConfigFor<M>>;\n export type PreResult<Modify> =\n | void\n | {\n action: "continue";\n }\n | {\n action: "modify";\n data: Modify;\n }\n | {\n action: "block";\n reason: string;\n };\n export type TaskCreateOrigin =\n | "rest"\n | "app"\n | "mcp"\n | "slack"\n | "schedule"\n | "workflow"\n | "webhook"\n | "followUp"\n | `extension:${string}`;\n export interface TaskCreateEvent {\n options: CreateTaskOptions;\n description: string;\n origin: TaskCreateOrigin;\n requestInfo?: RequestInfo;\n /** Slack ingress metadata; not persisted or writable through modify. */\n slack?: {\n trigger: "mention" | "thread-buffer";\n messages: {\n ts: string;\n userId: string;\n text: string;\n }[];\n };\n }\n /** A pre.task.create hook blocked a task before it was created. */\n export interface TaskBlockedEvent {\n /** The extension that blocked, or whose model/agent rewrite was rejected. */\n extension: {\n id: string;\n name: string;\n };\n /** The scrubbed block reason. */\n reason: string;\n origin: TaskCreateOrigin;\n source?: AgentTask["source"];\n requester: {\n userId?: string;\n agentId?: string;\n slackUserId?: string;\n };\n context?: {\n contextKey?: string;\n scheduleId?: string;\n workflowRunId?: string;\n workflowRunStepId?: string;\n parentTaskId?: string;\n vcsRepo?: string;\n vcsNumber?: number;\n slackChannelId?: string;\n slackThreadTs?: string;\n };\n /** The original task description, scrubbed and cut to 500 characters. */\n description: string;\n }\n export type TaskCreateModify = Partial<\n Pick<\n CreateTaskOptions,\n | "agentId"\n | "creatorAgentId"\n | "source"\n | "taskType"\n | "tags"\n | "priority"\n | "dependsOn"\n | "offeredTo"\n | "vcsProvider"\n | "vcsRepo"\n | "vcsEventType"\n | "vcsNumber"\n | "vcsCommentId"\n | "vcsAuthor"\n | "vcsUrl"\n | "vcsInstallationId"\n | "vcsNodeId"\n | "agentmailInboxId"\n | "agentmailMessageId"\n | "agentmailThreadId"\n | "mentionMessageId"\n | "mentionChannelId"\n | "dir"\n | "model"\n | "modelTier"\n | "effort"\n | "outputSchema"\n | "followUpConfig"\n | "bypassTrackerContextDedup"\n >\n > & {\n description?: string;\n };\n export interface TaskFollowUpEvent {\n completedTask: AgentTask;\n status: "completed" | "failed";\n output?: string;\n failureReason?: string;\n workerAgentId: string;\n leadAgentId: string;\n summary: string;\n }\n export interface TaskSteerEvent {\n task: AgentTask;\n message: string;\n mode: SteerMode;\n source: SteeringSource;\n sender: {\n kind: "user" | "agent" | "system";\n userId?: string;\n agentId?: string;\n };\n messageTimestamps?: string[];\n /** Slack ingress metadata; not persisted or writable through modify. */\n slack?: {\n channelId: string;\n threadTs: string;\n userId?: string;\n };\n }\n export interface TaskSteerModify {\n message: string;\n }\n export type TaskFollowUpModify = Partial<\n Pick<CreateTaskOptions, "agentId" | "priority" | "followUpConfig">\n > & {\n description?: string;\n };\n export interface SlackRouteEvent {\n channelId: string;\n userId: string;\n text: string;\n threadTs?: string;\n botMentioned: boolean;\n threadContext?: {\n channelId: string;\n threadTs: string;\n };\n }\n export interface SlackRouteModify {\n target:\n | {\n kind: "agent";\n agentId: string;\n }\n | {\n kind: "lead";\n }\n | {\n kind: "broadcast";\n };\n }\n /** A Chat SDK message after its thread buffer flushed, before routing. */\n export interface ChatRouteEvent {\n /** Adapter name, such as `telegram` or `slack`. */\n adapter: string;\n channelId: string;\n /** The Chat SDK thread id, prefixed with the adapter name. */\n threadId: string;\n /** The first buffered sender. */\n userId: string;\n userName?: string;\n /** The buffered messages, joined. */\n text: string;\n /** True for an @mention and for a reply to one of the bot\'s messages. */\n botMentioned: boolean;\n isDirectMessage: boolean;\n /** Platform chat type, such as Telegram `private`, `group`, `supergroup` or `channel`. */\n chatType?: string;\n /** Set for a Telegram supergroup with topics. */\n isForum?: boolean;\n /** A buffered message replies to one of the bot\'s own messages. */\n replyToBot: boolean;\n /** Set when earlier swarm tasks exist in this thread. */\n threadContext?: {\n adapter: string;\n threadId: string;\n };\n }\n export interface ChatRouteModify {\n target:\n | {\n kind: "agent";\n agentId: string;\n }\n | {\n kind: "lead";\n }\n | {\n kind: "broadcast";\n }\n | {\n kind: "workflow";\n workflowId: string;\n };\n }\n export type HeartbeatClassification = "no-session" | "stale-session" | "fresh-stalled";\n export type HeartbeatAction = "supersede-resume" | "fail" | "record";\n export interface HeartbeatRemediateEvent {\n task: AgentTask;\n session?: ActiveSession;\n classification: HeartbeatClassification;\n proposedAction: HeartbeatAction;\n reason: string;\n taskAgeMs: number;\n sessionHeartbeatAgeMs?: number;\n }\n export interface HeartbeatRemediateModify {\n proposedAction: HeartbeatAction;\n }\n export interface ToolCallEvent {\n tool: string;\n args: unknown;\n requestInfo: RequestInfo;\n }\n export interface ToolCallModify {\n args: unknown;\n }\n export interface TaskEvent {\n task: AgentTask;\n }\n export interface TaskCompletedEvent extends TaskEvent {\n output: string;\n }\n export interface TaskFailedEvent extends TaskEvent {\n failureReason: string;\n }\n export interface TaskSupersededEvent extends TaskEvent {\n supersededBy: string;\n }\n export interface TaskProgressEvent extends TaskEvent {\n progress: string;\n }\n export interface SlackMessageEvent {\n channelId: string;\n userId: string;\n text: string;\n threadTs?: string;\n taskId?: string;\n }\n /** A Chat SDK message the swarm received or sent. */\n export interface ChatMessageEvent {\n adapter: string;\n channelId: string;\n threadId: string;\n /** The sender, for an inbound message. */\n userId?: string;\n text: string;\n direction: "inbound" | "outbound";\n taskId?: string;\n messageId?: string;\n }\n /**\n * A person answered an approval request. Fires for workflow and standalone\n * requests. Timeouts and cancellations do not emit it today.\n */\n export interface ApprovalResolvedEvent {\n requestId: string;\n status: "approved" | "rejected" | "timeout" | "cancelled";\n responses: Record<string, unknown> | null;\n /** Set when a workflow human-in-the-loop step asked. Absent for a standalone request. */\n workflowRunId?: string;\n workflowRunStepId?: string;\n /** The task whose agent asked, for a standalone request. */\n sourceTaskId?: string;\n }\n /** A task was refused because a daily spend budget is used up. */\n export interface TaskBudgetRefusedEvent extends TaskEvent {\n /** The agent the task was refused for. */\n agentId: string;\n /** Which budget refused it. The matching spend and budget fields are set. */\n cause: "agent" | "global" | "user";\n agentSpendUsd?: number;\n agentBudgetUsd?: number;\n globalSpendUsd?: number;\n globalBudgetUsd?: number;\n userSpendUsd?: number;\n userBudgetUsd?: number;\n /** ISO 8601 time the daily budget resets. */\n resetAt: string;\n }\n /** An inbound AgentMail message. */\n export interface EmailReceivedEvent {\n inboxId: string;\n /** The From header as sent. */\n from: string;\n subject: string;\n /** The text body, or the HTML when there is no text, cut to 500 characters with `...` appended. */\n body: string;\n threadId: string;\n messageId: string;\n }\n /** An inbound Kapso (WhatsApp) message. */\n export interface KapsoMessageEvent {\n phoneNumberId: string;\n conversationId?: string;\n messageId: string;\n from?: string;\n /** Kapso message type, such as `text` or `image`. */\n type?: string;\n /** The text, or a placeholder naming the type for a non-text message. */\n text: string;\n }\n export type VcsProvider = "github" | "gitlab" | "azure-devops" | "bitbucket";\n /**\n * The provider object the event is about, as the provider names it. GitLab\n * calls a pull request a merge request, and a comment a `note`.\n */\n export type VcsEventKind =\n | "pull_request"\n | "merge_request"\n | "issue"\n | "issue_comment"\n | "note"\n | "pull_request_review"\n | "pipeline";\n /**\n * A webhook event from a connected code host. `action` is the provider\'s own\n * value: `opened`, `closed`, `synchronize`, `merge`, `created`, `commented`, or,\n * for a pipeline, its status such as `success` or `failed`. Fields a kind does\n * not carry are absent.\n */\n export interface VcsEvent {\n provider: VcsProvider;\n kind: VcsEventKind;\n action: string;\n /** `owner/name` on GitHub and GitLab, `workspace/repo_slug` on Bitbucket, the repository URL on Azure DevOps. */\n repo: string;\n /** The PR, merge request, or issue number. Absent for a pipeline outside a merge request. */\n number?: number;\n title?: string;\n body?: string | null;\n /** Login of the user behind the event. Set for pull requests, merge requests, and Azure DevOps comments. */\n author?: string;\n url?: string;\n merged?: boolean;\n changedFiles?: number;\n /** The review verdict, on a pull request review. */\n reviewState?: string;\n }\n export interface ToolCallCompletedEvent extends ToolCallEvent {\n result: unknown;\n durationMs: number;\n }\n export interface SwarmEventMap {\n "pre.task.create": {\n event: TaskCreateEvent;\n modify: TaskCreateModify;\n result: PreResult<TaskCreateModify>;\n };\n "pre.task.followUp": {\n event: TaskFollowUpEvent;\n modify: TaskFollowUpModify;\n result: PreResult<TaskFollowUpModify>;\n };\n "pre.task.steer": {\n event: TaskSteerEvent;\n modify: TaskSteerModify;\n result: PreResult<TaskSteerModify>;\n };\n "pre.slack.route": {\n event: SlackRouteEvent;\n modify: SlackRouteModify;\n result: PreResult<SlackRouteModify>;\n };\n "pre.chat.route": {\n event: ChatRouteEvent;\n modify: ChatRouteModify;\n result: PreResult<ChatRouteModify>;\n };\n "pre.heartbeat.remediate": {\n event: HeartbeatRemediateEvent;\n modify: HeartbeatRemediateModify;\n result: PreResult<HeartbeatRemediateModify>;\n };\n "pre.tool.call": {\n event: ToolCallEvent;\n modify: ToolCallModify;\n result: PreResult<ToolCallModify>;\n };\n "post.task.created": {\n event: TaskEvent;\n modify: never;\n result: void;\n };\n "post.task.blocked": {\n event: TaskBlockedEvent;\n modify: never;\n result: void;\n };\n "post.task.completed": {\n event: TaskCompletedEvent;\n modify: never;\n result: void;\n };\n "post.task.failed": {\n event: TaskFailedEvent;\n modify: never;\n result: void;\n };\n "post.task.cancelled": {\n event: TaskEvent;\n modify: never;\n result: void;\n };\n "post.task.superseded": {\n event: TaskSupersededEvent;\n modify: never;\n result: void;\n };\n "post.task.progress": {\n event: TaskProgressEvent;\n modify: never;\n result: void;\n };\n "post.slack.message": {\n event: SlackMessageEvent;\n modify: never;\n result: void;\n };\n "post.chat.message": {\n event: ChatMessageEvent;\n modify: never;\n result: void;\n };\n "post.approval.resolved": {\n event: ApprovalResolvedEvent;\n modify: never;\n result: void;\n };\n "post.task.budgetRefused": {\n event: TaskBudgetRefusedEvent;\n modify: never;\n result: void;\n };\n "post.email.received": {\n event: EmailReceivedEvent;\n modify: never;\n result: void;\n };\n "post.kapso.message": {\n event: KapsoMessageEvent;\n modify: never;\n result: void;\n };\n "post.vcs.event": {\n event: VcsEvent;\n modify: never;\n result: void;\n };\n "post.tool.call": {\n event: ToolCallCompletedEvent;\n modify: never;\n result: void;\n };\n }\n export interface ExtensionApi<\n M extends ExtensionManifest = ExtensionManifest & {\n runtime: "api";\n },\n > {\n on<E extends keyof SwarmEventMap>(\n event: E,\n handler: (\n event: SwarmEventMap[E]["event"],\n ctx: CtxFor<M>,\n ) => Promise<SwarmEventMap[E]["result"]> | SwarmEventMap[E]["result"],\n opts?: {\n priority?: number;\n },\n ): void;\n }\n export type SwarmExtension<\n M extends ExtensionManifest = ExtensionManifest & {\n runtime: "api";\n },\n > = (api: ExtensionApi<M>) => void;\n export { block, modify } from "./contract-runtime";\n}\n';
4
+ '// biome-ignore-all lint/suspicious/noConfusingVoidType: Extension handlers may explicitly return no result.\ndeclare module "swarm-extension" {\n export type CreateTaskOptions = {\n key?: string | undefined;\n agentId?: string | null | undefined;\n creatorAgentId?: string | undefined;\n source?:\n | "chat"\n | "workflow"\n | "schedule"\n | "slack"\n | "agentmail"\n | "github"\n | "gitlab"\n | "azure-devops"\n | "bitbucket"\n | "linear"\n | "jira"\n | "mcp"\n | "api"\n | "ui"\n | "system"\n | "comb"\n | undefined;\n routingReason?:\n | "skill"\n | "continuity"\n | "overflow"\n | "human_pinned"\n | "reroute_fault"\n | undefined;\n routingSource?: "declared" | "engine_default" | undefined;\n routingNote?: string | undefined;\n taskType?: string | undefined;\n tags?: string[] | undefined;\n priority?: number | undefined;\n dependsOn?: string[] | undefined;\n offeredTo?: string | undefined;\n status?: "draft" | "backlog" | "unassigned" | undefined;\n slackChannelId?: string | undefined;\n slackThreadTs?: string | undefined;\n slackTriggerMessageTs?: string | undefined;\n slackUserId?: string | undefined;\n overrideSlackContext?: boolean | undefined;\n vcsProvider?: "github" | "gitlab" | "azure-devops" | "bitbucket" | undefined;\n vcsRepo?: string | undefined;\n vcsEventType?: string | undefined;\n vcsNumber?: number | undefined;\n vcsCommentId?: number | undefined;\n vcsAuthor?: string | undefined;\n vcsUrl?: string | undefined;\n vcsInstallationId?: number | undefined;\n vcsNodeId?: string | undefined;\n agentmailInboxId?: string | undefined;\n agentmailMessageId?: string | undefined;\n agentmailThreadId?: string | undefined;\n mentionMessageId?: string | undefined;\n mentionChannelId?: string | undefined;\n dir?: string | undefined;\n parentTaskId?: string | undefined;\n model?: string | undefined;\n modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;\n effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;\n profile?: string | undefined;\n fallbackHops?:\n | {\n from: string;\n profile: string;\n errorClass:\n | "rate_limit"\n | "model_window"\n | "seat"\n | "credits"\n | "overloaded"\n | "server_error"\n | "auth"\n | "pool_empty";\n at: string;\n skipped?: { profile: string; reason: string }[] | undefined;\n }[]\n | undefined;\n scheduleId?: string | undefined;\n workflowRunId?: string | undefined;\n workflowRunStepId?: string | undefined;\n sourceTaskId?: string | undefined;\n dispatchedByTaskId?: string | undefined;\n outputSchema?: Record<string, unknown> | undefined;\n inheritParentOutputSchema?: boolean | undefined;\n inheritParentRequester?: boolean | undefined;\n inheritParentRoutingAffinity?: boolean | undefined;\n inheritParentFollowUpConfig?: boolean | undefined;\n followUpConfig?:\n | {\n disabled?: boolean | undefined;\n onCompleted?: string | undefined;\n onFailed?: string | undefined;\n }\n | undefined;\n requestedByUserId?: string | undefined;\n contextKey?: string | undefined;\n bypassTrackerContextDedup?: boolean | undefined;\n routingAffinity?:\n | {\n capabilities: string[];\n sourceAgentId?: string | undefined;\n role?: string | undefined;\n harnessProvider?:\n | "pi"\n | "claude"\n | "claude-managed"\n | "codex"\n | "grok"\n | "fx"\n | "opencode"\n | "dsh"\n | "cursor"\n | "amp"\n | "devin"\n | "acp"\n | undefined;\n leadOnly?: boolean | undefined;\n }\n | undefined;\n };\n\n export type AgentTask = {\n id: string;\n key: string;\n agentId: string | null;\n task: string;\n status:\n | "skipped"\n | "draft"\n | "backlog"\n | "unassigned"\n | "offered"\n | "reviewing"\n | "pending"\n | "in_progress"\n | "paused"\n | "completed"\n | "failed"\n | "cancelled"\n | "superseded";\n source:\n | "chat"\n | "workflow"\n | "schedule"\n | "slack"\n | "agentmail"\n | "github"\n | "gitlab"\n | "azure-devops"\n | "bitbucket"\n | "linear"\n | "jira"\n | "mcp"\n | "api"\n | "ui"\n | "system"\n | "comb";\n tags: string[];\n priority: number;\n dependsOn: string[];\n createdAt: string;\n lastUpdatedAt: string;\n slackReplySent: boolean;\n wasPaused: boolean;\n creatorAgentId?: string | undefined;\n title?: string | undefined;\n routingReason?:\n | "skill"\n | "continuity"\n | "overflow"\n | "human_pinned"\n | "reroute_fault"\n | undefined;\n routingSource?: "declared" | "engine_default" | undefined;\n routingNote?: string | undefined;\n poolWakeAt?: string | undefined;\n taskType?: string | undefined;\n offeredTo?: string | undefined;\n offeredAt?: string | undefined;\n acceptedAt?: string | undefined;\n rejectionReason?: string | undefined;\n finishedAt?: string | undefined;\n notifiedAt?: string | undefined;\n failureReason?: string | undefined;\n output?: string | undefined;\n progress?: string | undefined;\n slackChannelId?: string | undefined;\n slackThreadTs?: string | undefined;\n slackTriggerMessageTs?: string | undefined;\n slackUserId?: string | undefined;\n slackProgressMessageTs?: string | undefined;\n slackTreeRootMessageTs?: string | undefined;\n vcsProvider?: "github" | "gitlab" | "azure-devops" | "bitbucket" | undefined;\n vcsRepo?: string | undefined;\n vcsEventType?: string | undefined;\n vcsNumber?: number | undefined;\n vcsCommentId?: number | undefined;\n vcsAuthor?: string | undefined;\n vcsUrl?: string | undefined;\n vcsInstallationId?: number | undefined;\n vcsNodeId?: string | undefined;\n agentmailInboxId?: string | undefined;\n agentmailMessageId?: string | undefined;\n agentmailThreadId?: string | undefined;\n mentionMessageId?: string | undefined;\n mentionChannelId?: string | undefined;\n dir?: string | undefined;\n parentTaskId?: string | undefined;\n dispatchedByTaskId?: string | undefined;\n claudeSessionId?: string | undefined;\n model?: string | undefined;\n modelTier?: "smol" | "regular" | "smart" | "ultra" | undefined;\n effort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;\n resolvedModel?: string | undefined;\n modelSource?: string | undefined;\n modelAlias?: string | undefined;\n resolvedEffort?: "low" | "medium" | "high" | "max" | "off" | "xhigh" | undefined;\n profile?: string | undefined;\n resolvedProfile?: string | undefined;\n fallbackHops?:\n | {\n from: string;\n profile: string;\n errorClass:\n | "rate_limit"\n | "model_window"\n | "seat"\n | "credits"\n | "overloaded"\n | "server_error"\n | "auth"\n | "pool_empty";\n at: string;\n skipped?: { profile: string; reason: string }[] | undefined;\n }[]\n | undefined;\n scheduleId?: string | undefined;\n workflowRunId?: string | null | undefined;\n workflowRunStepId?: string | null | undefined;\n contextKey?: string | undefined;\n outputSchema?: Record<string, unknown> | undefined;\n followUpConfig?:\n | {\n disabled?: boolean | undefined;\n onCompleted?: string | undefined;\n onFailed?: string | undefined;\n }\n | undefined;\n deferredAt?: string | undefined;\n compactionCount?: number | undefined;\n peakContextPercent?: number | undefined;\n peakContextTokens?: number | undefined;\n contextWindowSize?: number | undefined;\n credentialKeySuffix?: string | undefined;\n credentialKeyType?: string | undefined;\n requestedByUserId?: string | undefined;\n swarmVersion?: string | undefined;\n provider?:\n | "pi"\n | "claude"\n | "claude-managed"\n | "codex"\n | "grok"\n | "fx"\n | "opencode"\n | "dsh"\n | "cursor"\n | "amp"\n | "devin"\n | "acp"\n | undefined;\n providerMeta?: Record<string, unknown> | undefined;\n harnessVariant?: string | undefined;\n harnessVariantMeta?: Record<string, unknown> | undefined;\n totalCostUsd?: number | undefined;\n routingAffinity?:\n | {\n capabilities: string[];\n sourceAgentId?: string | undefined;\n role?: string | undefined;\n harnessProvider?:\n | "pi"\n | "claude"\n | "claude-managed"\n | "codex"\n | "grok"\n | "fx"\n | "opencode"\n | "dsh"\n | "cursor"\n | "amp"\n | "devin"\n | "acp"\n | undefined;\n leadOnly?: boolean | undefined;\n }\n | undefined;\n routingAffinityInvalid?: boolean | undefined;\n };\n\n export type ActiveSession = {\n id: string;\n agentId: string;\n taskId: string | null;\n triggerType: string;\n inboxMessageId: string | null;\n taskDescription: string | null;\n runnerSessionId: string | null;\n providerSessionId: string | null;\n startedAt: string;\n lastHeartbeatAt: string;\n runtimeInstanceId?: string | null | undefined;\n };\n\n export type SteerMode = "steer" | "queue";\n\n export type SteeringSource = "chat" | "script" | "slack" | "mcp" | "api" | "ui";\n\n export type RequestInfo = {\n sessionId: string | undefined;\n agentId: string | undefined;\n runtimeInstanceId: string | undefined;\n sourceTaskId: string | undefined;\n contextKey: string | undefined;\n callOrigin: "mcp" | "extension" | "script-sdk";\n };\n\n import type { SwarmSdk } from "swarm-sdk";\n import type { z } from "zod";\n export type Runtime = "api" | "worker";\n export interface ExtensionScriptAsset {\n name: string;\n file: string;\n description: string;\n intent?: string;\n }\n export interface ExtensionScheduleAsset {\n name: string;\n description?: string;\n script: string;\n cronExpression?: string;\n intervalMs?: number;\n timezone?: string;\n args?: Record<string, unknown>;\n }\n export interface ExtensionWorkflowAsset {\n file: string;\n }\n export interface ExtensionSkillAsset {\n dir: string;\n }\n export interface ExtensionManifest {\n $schema?: string;\n name: string;\n description: string;\n version: string;\n runtime: Runtime;\n assets: {\n hooks: string;\n scripts?: readonly ExtensionScriptAsset[];\n schedules?: readonly ExtensionScheduleAsset[];\n workflows?: readonly ExtensionWorkflowAsset[];\n skills?: readonly ExtensionSkillAsset[];\n };\n homepage?: string;\n author?: string;\n }\n export interface HooksModule {\n default: SwarmExtension;\n config?: z.ZodTypeAny;\n }\n export interface ExtensionState {\n get<T = unknown>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n incr(key: string, by?: number): Promise<number>;\n del(key: string): Promise<void>;\n }\n export interface ExtensionLogger {\n debug(message: string, data?: unknown): void;\n info(message: string, data?: unknown): void;\n warn(message: string, data?: unknown): void;\n error(message: string, data?: unknown): void;\n }\n type ConfigFor<M extends ExtensionManifest> = M extends {\n config: infer C extends z.ZodTypeAny;\n }\n ? z.infer<C>\n : Record<string, unknown>;\n export interface ApiCtx<Config = Record<string, unknown>> {\n swarm: SwarmSdk;\n state: ExtensionState;\n config: Config;\n log: ExtensionLogger;\n signal: AbortSignal;\n event: {\n name: keyof SwarmEventMap;\n at: string;\n extension: {\n id: string;\n version: number;\n };\n };\n }\n export interface WorkerCtx<Config = Record<string, unknown>>\n extends Omit<ApiCtx<Config>, "swarm"> {\n swarm: SwarmSdk;\n worker: {\n agentId: string;\n taskId: string;\n harness: string;\n };\n }\n export type CtxFor<M extends ExtensionManifest> = M["runtime"] extends "api"\n ? ApiCtx<ConfigFor<M>>\n : WorkerCtx<ConfigFor<M>>;\n export type PreResult<Modify> =\n | void\n | {\n action: "continue";\n }\n | {\n action: "modify";\n data: Modify;\n }\n | {\n action: "block";\n reason: string;\n };\n export type TaskCreateOrigin =\n | "rest"\n | "app"\n | "mcp"\n | "slack"\n | "schedule"\n | "workflow"\n | "webhook"\n | "followUp"\n | `extension:${string}`;\n export interface TaskCreateEvent {\n options: CreateTaskOptions;\n description: string;\n origin: TaskCreateOrigin;\n requestInfo?: RequestInfo;\n /** Slack ingress metadata; not persisted or writable through modify. */\n slack?: {\n trigger: "mention" | "thread-buffer";\n messages: {\n ts: string;\n userId: string;\n text: string;\n }[];\n };\n }\n /** A pre.task.create hook blocked a task before it was created. */\n export interface TaskBlockedEvent {\n /** The extension that blocked, or whose model/agent rewrite was rejected. */\n extension: {\n id: string;\n name: string;\n };\n /** The scrubbed block reason. */\n reason: string;\n origin: TaskCreateOrigin;\n source?: AgentTask["source"];\n requester: {\n userId?: string;\n agentId?: string;\n slackUserId?: string;\n };\n context?: {\n contextKey?: string;\n scheduleId?: string;\n workflowRunId?: string;\n workflowRunStepId?: string;\n parentTaskId?: string;\n vcsRepo?: string;\n vcsNumber?: number;\n slackChannelId?: string;\n slackThreadTs?: string;\n };\n /** The original task description, scrubbed and cut to 500 characters. */\n description: string;\n }\n export type TaskCreateModify = Partial<\n Pick<\n CreateTaskOptions,\n | "agentId"\n | "creatorAgentId"\n | "source"\n | "taskType"\n | "tags"\n | "priority"\n | "dependsOn"\n | "offeredTo"\n | "vcsProvider"\n | "vcsRepo"\n | "vcsEventType"\n | "vcsNumber"\n | "vcsCommentId"\n | "vcsAuthor"\n | "vcsUrl"\n | "vcsInstallationId"\n | "vcsNodeId"\n | "agentmailInboxId"\n | "agentmailMessageId"\n | "agentmailThreadId"\n | "mentionMessageId"\n | "mentionChannelId"\n | "dir"\n | "model"\n | "modelTier"\n | "effort"\n | "outputSchema"\n | "followUpConfig"\n | "bypassTrackerContextDedup"\n >\n > & {\n description?: string;\n };\n export interface TaskFollowUpEvent {\n completedTask: AgentTask;\n status: "completed" | "failed";\n output?: string;\n failureReason?: string;\n workerAgentId: string;\n leadAgentId: string;\n summary: string;\n }\n export interface TaskSteerEvent {\n task: AgentTask;\n message: string;\n mode: SteerMode;\n source: SteeringSource;\n sender: {\n kind: "user" | "agent" | "system";\n userId?: string;\n agentId?: string;\n };\n messageTimestamps?: string[];\n /** Slack ingress metadata; not persisted or writable through modify. */\n slack?: {\n channelId: string;\n threadTs: string;\n userId?: string;\n };\n }\n export interface TaskSteerModify {\n message: string;\n }\n export type TaskFollowUpModify = Partial<\n Pick<CreateTaskOptions, "agentId" | "priority" | "followUpConfig">\n > & {\n description?: string;\n };\n export interface SlackRouteEvent {\n channelId: string;\n userId: string;\n text: string;\n threadTs?: string;\n botMentioned: boolean;\n threadContext?: {\n channelId: string;\n threadTs: string;\n };\n }\n export interface SlackRouteModify {\n target:\n | {\n kind: "agent";\n agentId: string;\n }\n | {\n kind: "lead";\n }\n | {\n kind: "broadcast";\n };\n }\n /** A Chat SDK message after its thread buffer flushed, before routing. */\n export interface ChatRouteEvent {\n /** Adapter name, such as `telegram` or `slack`. */\n adapter: string;\n channelId: string;\n /** The Chat SDK thread id, prefixed with the adapter name. */\n threadId: string;\n /** The first buffered sender. */\n userId: string;\n userName?: string;\n /** The buffered messages, joined. */\n text: string;\n /** True for an @mention and for a reply to one of the bot\'s messages. */\n botMentioned: boolean;\n isDirectMessage: boolean;\n /** Platform chat type, such as Telegram `private`, `group`, `supergroup` or `channel`. */\n chatType?: string;\n /** Set for a Telegram supergroup with topics. */\n isForum?: boolean;\n /** A buffered message replies to one of the bot\'s own messages. */\n replyToBot: boolean;\n /** Set when earlier swarm tasks exist in this thread. */\n threadContext?: {\n adapter: string;\n threadId: string;\n };\n }\n export interface ChatRouteModify {\n target:\n | {\n kind: "agent";\n agentId: string;\n }\n | {\n kind: "lead";\n }\n | {\n kind: "broadcast";\n }\n | {\n kind: "workflow";\n workflowId: string;\n };\n }\n export type HeartbeatClassification = "no-session" | "stale-session" | "fresh-stalled";\n export type HeartbeatAction = "supersede-resume" | "fail" | "record";\n export interface HeartbeatRemediateEvent {\n task: AgentTask;\n session?: ActiveSession;\n classification: HeartbeatClassification;\n proposedAction: HeartbeatAction;\n reason: string;\n taskAgeMs: number;\n sessionHeartbeatAgeMs?: number;\n }\n export interface HeartbeatRemediateModify {\n proposedAction: HeartbeatAction;\n }\n export interface ToolCallEvent {\n tool: string;\n args: unknown;\n requestInfo: RequestInfo;\n }\n export interface ToolCallModify {\n args: unknown;\n }\n export interface TaskEvent {\n task: AgentTask;\n }\n export interface TaskCompletedEvent extends TaskEvent {\n output: string;\n }\n export interface TaskFailedEvent extends TaskEvent {\n failureReason: string;\n }\n export interface TaskSupersededEvent extends TaskEvent {\n supersededBy: string;\n }\n export interface TaskProgressEvent extends TaskEvent {\n progress: string;\n }\n export interface SlackMessageEvent {\n channelId: string;\n userId: string;\n text: string;\n threadTs?: string;\n taskId?: string;\n }\n /** A Chat SDK message the swarm received or sent. */\n export interface ChatMessageEvent {\n adapter: string;\n channelId: string;\n threadId: string;\n /** The sender, for an inbound message. */\n userId?: string;\n text: string;\n direction: "inbound" | "outbound";\n taskId?: string;\n messageId?: string;\n }\n /**\n * A person answered an approval request. Fires for workflow and standalone\n * requests. Timeouts and cancellations do not emit it today.\n */\n export interface ApprovalResolvedEvent {\n requestId: string;\n status: "approved" | "rejected" | "timeout" | "cancelled";\n responses: Record<string, unknown> | null;\n /** Set when a workflow human-in-the-loop step asked. Absent for a standalone request. */\n workflowRunId?: string;\n workflowRunStepId?: string;\n /** The task whose agent asked, for a standalone request. */\n sourceTaskId?: string;\n }\n /** A task was refused because a daily spend budget is used up. */\n export interface TaskBudgetRefusedEvent extends TaskEvent {\n /** The agent the task was refused for. */\n agentId: string;\n /** Which budget refused it. The matching spend and budget fields are set. */\n cause: "agent" | "global" | "user";\n agentSpendUsd?: number;\n agentBudgetUsd?: number;\n globalSpendUsd?: number;\n globalBudgetUsd?: number;\n userSpendUsd?: number;\n userBudgetUsd?: number;\n /** ISO 8601 time the daily budget resets. */\n resetAt: string;\n }\n /** An inbound AgentMail message. */\n export interface EmailReceivedEvent {\n inboxId: string;\n /** The From header as sent. */\n from: string;\n subject: string;\n /** The text body, or the HTML when there is no text, cut to 500 characters with `...` appended. */\n body: string;\n threadId: string;\n messageId: string;\n }\n /** An inbound Kapso (WhatsApp) message. */\n export interface KapsoMessageEvent {\n phoneNumberId: string;\n conversationId?: string;\n messageId: string;\n from?: string;\n /** Kapso message type, such as `text` or `image`. */\n type?: string;\n /** The text, or a placeholder naming the type for a non-text message. */\n text: string;\n }\n export type VcsProvider = "github" | "gitlab" | "azure-devops" | "bitbucket";\n /**\n * The provider object the event is about, as the provider names it. GitLab\n * calls a pull request a merge request, and a comment a `note`.\n */\n export type VcsEventKind =\n | "pull_request"\n | "merge_request"\n | "issue"\n | "issue_comment"\n | "note"\n | "pull_request_review"\n | "pipeline";\n /**\n * A webhook event from a connected code host. `action` is the provider\'s own\n * value: `opened`, `closed`, `synchronize`, `merge`, `created`, `commented`, or,\n * for a pipeline, its status such as `success` or `failed`. Fields a kind does\n * not carry are absent.\n */\n export interface VcsEvent {\n provider: VcsProvider;\n kind: VcsEventKind;\n action: string;\n /** `owner/name` on GitHub and GitLab, `workspace/repo_slug` on Bitbucket, the repository URL on Azure DevOps. */\n repo: string;\n /** The PR, merge request, or issue number. Absent for a pipeline outside a merge request. */\n number?: number;\n title?: string;\n body?: string | null;\n /** Login of the user behind the event. Set for pull requests, merge requests, and Azure DevOps comments. */\n author?: string;\n url?: string;\n merged?: boolean;\n changedFiles?: number;\n /** The review verdict, on a pull request review. */\n reviewState?: string;\n }\n export interface ToolCallCompletedEvent extends ToolCallEvent {\n result: unknown;\n durationMs: number;\n }\n export interface SwarmEventMap {\n "pre.task.create": {\n event: TaskCreateEvent;\n modify: TaskCreateModify;\n result: PreResult<TaskCreateModify>;\n };\n "pre.task.followUp": {\n event: TaskFollowUpEvent;\n modify: TaskFollowUpModify;\n result: PreResult<TaskFollowUpModify>;\n };\n "pre.task.steer": {\n event: TaskSteerEvent;\n modify: TaskSteerModify;\n result: PreResult<TaskSteerModify>;\n };\n "pre.slack.route": {\n event: SlackRouteEvent;\n modify: SlackRouteModify;\n result: PreResult<SlackRouteModify>;\n };\n "pre.chat.route": {\n event: ChatRouteEvent;\n modify: ChatRouteModify;\n result: PreResult<ChatRouteModify>;\n };\n "pre.heartbeat.remediate": {\n event: HeartbeatRemediateEvent;\n modify: HeartbeatRemediateModify;\n result: PreResult<HeartbeatRemediateModify>;\n };\n "pre.tool.call": {\n event: ToolCallEvent;\n modify: ToolCallModify;\n result: PreResult<ToolCallModify>;\n };\n "post.task.created": {\n event: TaskEvent;\n modify: never;\n result: void;\n };\n "post.task.blocked": {\n event: TaskBlockedEvent;\n modify: never;\n result: void;\n };\n "post.task.completed": {\n event: TaskCompletedEvent;\n modify: never;\n result: void;\n };\n "post.task.failed": {\n event: TaskFailedEvent;\n modify: never;\n result: void;\n };\n "post.task.cancelled": {\n event: TaskEvent;\n modify: never;\n result: void;\n };\n "post.task.superseded": {\n event: TaskSupersededEvent;\n modify: never;\n result: void;\n };\n "post.task.progress": {\n event: TaskProgressEvent;\n modify: never;\n result: void;\n };\n "post.slack.message": {\n event: SlackMessageEvent;\n modify: never;\n result: void;\n };\n "post.chat.message": {\n event: ChatMessageEvent;\n modify: never;\n result: void;\n };\n "post.approval.resolved": {\n event: ApprovalResolvedEvent;\n modify: never;\n result: void;\n };\n "post.task.budgetRefused": {\n event: TaskBudgetRefusedEvent;\n modify: never;\n result: void;\n };\n "post.email.received": {\n event: EmailReceivedEvent;\n modify: never;\n result: void;\n };\n "post.kapso.message": {\n event: KapsoMessageEvent;\n modify: never;\n result: void;\n };\n "post.vcs.event": {\n event: VcsEvent;\n modify: never;\n result: void;\n };\n "post.tool.call": {\n event: ToolCallCompletedEvent;\n modify: never;\n result: void;\n };\n }\n export interface ExtensionApi<\n M extends ExtensionManifest = ExtensionManifest & {\n runtime: "api";\n },\n > {\n on<E extends keyof SwarmEventMap>(\n event: E,\n handler: (\n event: SwarmEventMap[E]["event"],\n ctx: CtxFor<M>,\n ) => Promise<SwarmEventMap[E]["result"]> | SwarmEventMap[E]["result"],\n opts?: {\n priority?: number;\n },\n ): void;\n }\n export type SwarmExtension<\n M extends ExtensionManifest = ExtensionManifest & {\n runtime: "api";\n },\n > = (api: ExtensionApi<M>) => void;\n export { block, modify } from "./contract-runtime";\n}\n';
@@ -56,6 +56,8 @@ import "./script-connections";
56
56
  import "./script-runs";
57
57
  import "./script-connection-proxy";
58
58
  import "./session-data";
59
+ import "./savings";
60
+ import "./savings-calibration";
59
61
  import "./sessions";
60
62
  import "./skills";
61
63
  import "./slack-inbound";
package/src/http/fs.ts CHANGED
@@ -71,7 +71,7 @@ const agentFsInviteStateSchema = z.object({
71
71
  status: z
72
72
  .enum(["already_member", "added", "pending"])
73
73
  .describe(
74
- "already_member: no change. added: an existing agent-fs account joined the org. pending: the email has no account, so agent-fs created an invite the person must accept.",
74
+ "already_member: no change. added: the email was already in the org and holds the role now. pending: agent-fs created an invite the person must accept (agent-fs >= 0.18.19 does this for every email not yet in the org, with or without an account).",
75
75
  ),
76
76
  inviteId: z.string().optional().describe("Pending invite id (status pending)."),
77
77
  expiresAt: z.string().optional().describe("ISO time the accept link expires (status pending)."),
@@ -81,6 +81,12 @@ const agentFsInviteStateSchema = z.object({
81
81
  .describe(
82
82
  "Link the invitee opens to accept (status pending). agent-fs sends no email, so hand it to the person. Absent when agent-fs has no app URL configured.",
83
83
  ),
84
+ token: z
85
+ .string()
86
+ .optional()
87
+ .describe(
88
+ "Accept token (status pending). Only the invited account can redeem it, with its own key: agent-fs POST /invites/{token}/accept.",
89
+ ),
84
90
  });
85
91
 
86
92
  const signedUrlResponseSchema = z.object({
@@ -126,7 +132,7 @@ const inviteMemberRoute = route({
126
132
  pattern: ["api", "fs", "members", "invite"],
127
133
  summary: "Invite an external member into the agent-fs shared org",
128
134
  description:
129
- "The API server performs the invite with its own bootstrap credentials (which are API-only and never served over HTTP), provisioning the shared org/drive first when needed. Intended for the cloud control plane's Connect-to-Drive flow. An email with an agent-fs account is added directly (status added). An email without one gets a pending invite (status pending) with an acceptUrl when agent-fs returns one; agent-fs sends no email, so the caller must hand the link to the invitee. No keys are returned; the invitee obtains their own key via agent-fs registration.",
135
+ "The API server performs the invite with its own bootstrap credentials (which are API-only and never served over HTTP), provisioning the shared org/drive first when needed. Intended for the cloud control plane's Connect-to-Drive flow. An email already in the org gets the grant directly (status added). Any other email gets a pending invite (status pending) with its accept token, and an acceptUrl when agent-fs returns one; agent-fs sends no email, so the caller must hand the link to the invitee, or accept with the invitee's own key. No keys are returned; the invitee obtains their own key via agent-fs registration.",
130
136
  tags: ["FS"],
131
137
  body: z.object({
132
138
  email: z.email(),
package/src/http/index.ts CHANGED
@@ -131,6 +131,8 @@ import { handleRepos } from "./repos";
131
131
  import { handleRooms } from "./rooms";
132
132
  import { describeRequestRoute } from "./route-def";
133
133
  import { handleRuntimePools } from "./runtime-pools";
134
+ import { handleSavings } from "./savings";
135
+ import { handleSavingsCalibration } from "./savings-calibration";
134
136
  import { handleSchedules } from "./schedules";
135
137
  import { handleScriptConnectionProxy } from "./script-connection-proxy";
136
138
  import { handleScriptConnections } from "./script-connections";
@@ -428,6 +430,8 @@ const httpServer = createHttpServer(async (req, res) => {
428
430
  () => handleImprovements(req, res, pathSegments, queryParams),
429
431
  () => handleRanking(req, res, pathSegments, queryParams),
430
432
  () => handleFleetBenchmark(req, res, pathSegments, queryParams),
433
+ () => handleSavings(req, res, pathSegments, queryParams),
434
+ () => handleSavingsCalibration(req, res, pathSegments, queryParams),
431
435
  () => handleTaskTemplates(req, res, pathSegments, queryParams),
432
436
  () => handleMcp(req, res, transports, transportActivity, mcpSessionAgents),
433
437
  () => handleMcpUser(req, res, transportsUser, sessionUsers, transportActivityUser),