@desplega.ai/agent-swarm 2.13.2 → 2.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/acp-adapter-t2q6nsqv.js +17 -0
  2. package/dist/{acp-targets-mz8c5dnt.js → acp-targets-k8xs4tj8.js} +7 -7
  3. package/dist/{actions-5ft3qp5a.js → actions-pg5fxjer.js} +23 -23
  4. package/dist/{agent-fs-provision-6fgz7wvz.js → agent-fs-provision-vbk3fppw.js} +4 -4
  5. package/dist/{amp-adapter-nthn8ezm.js → amp-adapter-adbhxsz9.js} +2 -2
  6. package/dist/{app-535m78qw.js → app-b267ggx1.js} +6 -6
  7. package/dist/{approval-notifications-dewbk403.js → approval-notifications-evc1a9z5.js} +7 -7
  8. package/dist/{assistant-39zyabv2.js → assistant-wgz2ab84.js} +24 -24
  9. package/dist/{boot-args-schema-bqv5bf77.js → boot-args-schema-6tpk28j4.js} +1 -1
  10. package/dist/{boot-reembed-fas7z3zn.js → boot-reembed-ankp369c.js} +1 -1
  11. package/dist/{boot-reembed-157c0gcz.js → boot-reembed-r1zyvefv.js} +1 -1
  12. package/dist/{boot-scrub-sweep-tmec0be2.js → boot-scrub-sweep-cgb6r5bd.js} +2 -2
  13. package/dist/{boot-seeds-32zm50x2.js → boot-seeds-bjceqg7b.js} +4 -4
  14. package/dist/{claude-adapter-gwq7x2nj.js → claude-adapter-knztdnff.js} +9 -6
  15. package/dist/{claude-managed-adapter-rkvw6fvq.js → claude-managed-adapter-qwejzqkk.js} +2 -2
  16. package/dist/{claude-sdk-session-5wbwxy8c.js → claude-sdk-session-c3g6dv0g.js} +22 -8
  17. package/dist/{cli-cs26ed89.js → cli-0j4qmc80.js} +7 -7
  18. package/dist/{cli-dnvmwsvc.js → cli-1606qw3n.js} +32 -32
  19. package/dist/{cli-b0kqw55g.js → cli-1gnf5c7x.js} +1 -1
  20. package/dist/{cli-31vt7baf.js → cli-1wew39p0.js} +10 -10
  21. package/dist/{cli-tceqvv6h.js → cli-268b3dgn.js} +2 -2
  22. package/dist/cli-2ap1the6.js +11 -0
  23. package/dist/{cli-e87fg3en.js → cli-4dyhzhpx.js} +1 -1
  24. package/dist/{cli-t9nxq30h.js → cli-55fqpd9q.js} +8 -8
  25. package/dist/{cli-nvqq3232.js → cli-61fzwtjk.js} +7 -7
  26. package/dist/{cli-c9bwawf9.js → cli-61p7ty8d.js} +2 -2
  27. package/dist/{cli-d528acsw.js → cli-7fa6yv98.js} +2 -2
  28. package/dist/{cli-bp2rt28p.js → cli-7kv5d674.js} +3 -3
  29. package/dist/{cli-tbdw3f92.js → cli-80d5g0fa.js} +2 -2
  30. package/dist/{cli-0xwb7zpt.js → cli-88np9va3.js} +1 -1
  31. package/dist/{cli-zm6bkx3e.js → cli-8m6gqnf1.js} +2 -2
  32. package/dist/{cli-r4fphq38.js → cli-8pnawt98.js} +3 -3
  33. package/dist/{cli-xerdrnqs.js → cli-8sayvj48.js} +2 -2
  34. package/dist/{cli-d0jb2qnt.js → cli-9gmkw6xn.js} +53 -32
  35. package/dist/{cli-a6rzw649.js → cli-a21cwm89.js} +2 -2
  36. package/dist/{cli-s6fhqbz1.js → cli-aytna2fm.js} +1 -1
  37. package/dist/{cli-mwxez0pz.js → cli-b768ek79.js} +1 -1
  38. package/dist/{cli-ewb028rs.js → cli-bh53ppqm.js} +2 -2
  39. package/dist/{cli-zqy28rwx.js → cli-czeh7x13.js} +3 -3
  40. package/dist/{cli-s08zsqva.js → cli-djwt4mtn.js} +71 -5
  41. package/dist/{cli-fgm2mad9.js → cli-dq30fq3q.js} +2 -2
  42. package/dist/{cli-2wde56gv.js → cli-dw43pnzp.js} +5 -5
  43. package/dist/{cli-erh1rgh4.js → cli-e4gx499y.js} +12 -12
  44. package/dist/{cli-69eq6gdk.js → cli-ea367bdn.js} +31 -22
  45. package/dist/{cli-cmgdptmx.js → cli-ef590376.js} +29 -5
  46. package/dist/{cli-8qvte9hn.js → cli-fbmgpt72.js} +2 -2
  47. package/dist/{cli-tgmate57.js → cli-g4dhd3pr.js} +2 -2
  48. package/dist/{cli-0f7n3td3.js → cli-gc715jrc.js} +1 -1
  49. package/dist/{cli-xysy1g8x.js → cli-gkjw33x5.js} +1 -1
  50. package/dist/{cli-getrvmtx.js → cli-grk77aen.js} +1 -1
  51. package/dist/{cli-f1sdh8ca.js → cli-gxqwm3k3.js} +5 -5
  52. package/dist/{cli-m1wddksc.js → cli-h3drhntp.js} +1 -1
  53. package/dist/{cli-qn79645p.js → cli-h9d3sdnc.js} +1 -1
  54. package/dist/{cli-7m6bbtab.js → cli-hd2a204w.js} +6 -6
  55. package/dist/{cli-jkkcm72j.js → cli-hhb8kbwd.js} +9 -9
  56. package/dist/{cli-fcwrd7bh.js → cli-hpxcfvdm.js} +3 -3
  57. package/dist/{cli-ka13xx6b.js → cli-hxj888w3.js} +1 -1
  58. package/dist/{cli-82j36f2m.js → cli-jjzxsk47.js} +9 -3
  59. package/dist/{cli-nkfv398a.js → cli-ka4tqjzd.js} +6 -6
  60. package/dist/{cli-n46d87mj.js → cli-kh973792.js} +3 -3
  61. package/dist/{cli-x5yb8zc8.js → cli-kwm1bek7.js} +1 -1
  62. package/dist/{cli-5k1hvycs.js → cli-mgr3gatr.js} +4 -4
  63. package/dist/{cli-8a4qg44m.js → cli-nbawx3s0.js} +2 -2
  64. package/dist/{cli-1gevjrc1.js → cli-ppf9ap9n.js} +1 -1
  65. package/dist/{cli-6rmryz03.js → cli-pzsedyb0.js} +4 -4
  66. package/dist/{cli-g0b3ma7r.js → cli-r6xnchva.js} +1 -1
  67. package/dist/{cli-j2ybkdk2.js → cli-snwz16eg.js} +1 -1
  68. package/dist/{cli-sjk85d7v.js → cli-sy2ge2ye.js} +3 -3
  69. package/dist/{cli-rvhaahfv.js → cli-syqcny89.js} +3 -3
  70. package/dist/{cli-n14r8h4n.js → cli-tjf1bh1v.js} +2 -2
  71. package/dist/{cli-xhkek467.js → cli-v1v49t36.js} +28 -2
  72. package/dist/{cli-4djg31jh.js → cli-v8rpjrnx.js} +1 -1
  73. package/dist/{cli-62fjschk.js → cli-vgh5adn9.js} +5 -5
  74. package/dist/{cli-wdtqkqnq.js → cli-w24741sm.js} +3 -3
  75. package/dist/{cli-gq6qhmrr.js → cli-wsnradtk.js} +3 -3
  76. package/dist/{cli-gc7jkf4a.js → cli-wtffytm8.js} +3 -3
  77. package/dist/{cli-1f48qdnb.js → cli-xc8m5cjn.js} +2 -2
  78. package/dist/{cli-x7aqhxj5.js → cli-y0q92v4r.js} +2 -2
  79. package/dist/{cli-gedf48yw.js → cli-y754psdt.js} +4 -4
  80. package/dist/cli.js +14 -14
  81. package/dist/{codex-adapter-x25xfbnh.js → codex-adapter-493vb8cv.js} +5 -5
  82. package/dist/{codex-hook-c0nvm30r.js → codex-hook-ej8hn6z5.js} +9 -2
  83. package/dist/{codex-session-runner-kn5xnrvp.js → codex-session-runner-ps5m4z1g.js} +5 -5
  84. package/dist/{commands-8n59gxmy.js → commands-shktk0b8.js} +3 -3
  85. package/dist/{controllers-connect-09gvkrhc.js → controllers-connect-yft057ws.js} +22 -22
  86. package/dist/{core-2b8bv6ny.js → core-nheayfgm.js} +21 -21
  87. package/dist/{cursor-adapter-w1681kp1.js → cursor-adapter-8fpm4dng.js} +1 -1
  88. package/dist/{db-e71keqxk.js → db-0ezhdhz5.js} +3 -3
  89. package/dist/{db-spg81qtr.js → db-84pz2w5c.js} +2 -2
  90. package/dist/{dispatcher-fr4vawwb.js → dispatcher-h2rz69f6.js} +21 -21
  91. package/dist/{easter-egg-3d-ac9tv9a6.js → easter-egg-3d-m41ad78v.js} +1 -1
  92. package/dist/{embedding-space-an77f45k.js → embedding-space-yam9zwzj.js} +6 -6
  93. package/dist/{embeddings-jkrehejr.js → embeddings-g2be0y8q.js} +1 -1
  94. package/dist/{execute-3mys4nta.js → execute-hhdejgzf.js} +1 -1
  95. package/dist/{external-channel-s6zxpts9.js → external-channel-kjt2yzfj.js} +2 -2
  96. package/dist/fx-adapter-8g7xsp8q.js +20 -0
  97. package/dist/{grok-adapter-8ge6tw7m.js → grok-adapter-ztk2zkz1.js} +9 -9
  98. package/dist/handlers-9ywssz71.js +41 -0
  99. package/dist/{heartbeat-jjpb44e5.js → heartbeat-2e5jdexj.js} +23 -23
  100. package/dist/{hook-y6n23zzj.js → hook-34s8cmgn.js} +9 -6
  101. package/dist/{hook-68gbs87k.js → hook-acg9saz7.js} +8 -5
  102. package/dist/{http-8c6y008s.js → http-ra2zr2f8.js} +58 -65
  103. package/dist/{index-xcw7hjt5.js → index-2z1z7qx6.js} +24 -24
  104. package/dist/{index-p2f5xg64.js → index-3j803vnb.js} +36259 -34299
  105. package/dist/index-6mgbdtv1.js +44 -0
  106. package/dist/{index-6h3r0vpe.js → index-93bw5wds.js} +1 -1
  107. package/dist/{index-we3nd2t0.js → index-9q42cr54.js} +1 -1
  108. package/dist/{index-0vthtbc2.js → index-9r4j0a60.js} +23 -15
  109. package/dist/index-hqdsn2t2.js +39 -0
  110. package/dist/index-st231bqv.js +40 -0
  111. package/dist/{keepalive-7e9r5dvp.js → keepalive-vjnnqbkm.js} +4 -4
  112. package/dist/lead-mk0xkth2.js +82 -0
  113. package/dist/{maintenance-d3erjvcg.js → maintenance-px2g599e.js} +1 -1
  114. package/dist/{oauth-refresh-sweep-0qh70988.js → oauth-refresh-sweep-nkykf09m.js} +3 -3
  115. package/dist/{object-webhooks-ac7v2q5p.js → object-webhooks-gt9xnq21.js} +7 -7
  116. package/dist/{onboard-5yphtken.js → onboard-1f134p65.js} +3 -3
  117. package/dist/{opencode-adapter-0xvyba4m.js → opencode-adapter-94976yab.js} +6 -6
  118. package/dist/{otel-impl-svqp691q.js → otel-impl-5d4p2fqs.js} +1 -1
  119. package/dist/{pending-bn4xe5br.js → pending-vkk0vx6n.js} +22 -22
  120. package/dist/{pi-mono-adapter-763s8a3w.js → pi-mono-adapter-cyzdv5er.js} +8 -8
  121. package/dist/{pricing-refresh-kfc215mf.js → pricing-refresh-jtmjwss9.js} +2 -2
  122. package/dist/{rbac-roles-6r4h2ghj.js → rbac-roles-1fvmdyeb.js} +2 -2
  123. package/dist/{rbac-roles-3bznvkpt.js → rbac-roles-yd1fgpsn.js} +3 -3
  124. package/dist/{render-v2-f3qedbpy.js → render-v2-kb5s3vx4.js} +6 -6
  125. package/dist/{resume-vcag4ann.js → resume-z1vs44n5.js} +9 -9
  126. package/dist/{runtime-x0s55z2t.js → runtime-gk6ct7r7.js} +1 -1
  127. package/dist/{session-access-nwzve8q2.js → session-access-nz6nre4d.js} +5 -5
  128. package/dist/{session-source-backfill-jpqfzmgz.js → session-source-backfill-wb60zjkd.js} +1 -1
  129. package/dist/{setup-d2smwaem.js → setup-2x8g8j4s.js} +1 -1
  130. package/dist/thread-buffer-d50rqpev.js +42 -0
  131. package/dist/{tree-visibility-dwzc8en0.js → tree-visibility-ts3z30kw.js} +2 -2
  132. package/dist/{user-merge-jobs-4ce7kma2.js → user-merge-jobs-zetg26e0.js} +3 -3
  133. package/dist/{virtual-modules-78a6yw71.js → virtual-modules-674fka8x.js} +3 -3
  134. package/dist/{work-objects-m0w1e7q8.js → work-objects-w52yyjxm.js} +24 -24
  135. package/dist/worker-662x1vse.js +82 -0
  136. package/dist/{worker-follow-up-e3t6f895.js → worker-follow-up-dyfxyjbj.js} +21 -21
  137. package/openapi.json +4 -1
  138. package/package.json +3 -3
  139. package/src/commands/onboard/agent-fs-version.ts +1 -1
  140. package/src/commands/runner.ts +62 -6
  141. package/src/hooks/codex-hook.ts +15 -4
  142. package/src/hooks/hook.ts +7 -0
  143. package/src/http/session-cost-recompute.ts +3 -1
  144. package/src/http/session-data.ts +3 -0
  145. package/src/prompts/base-prompt.ts +1 -1
  146. package/src/prompts/session-templates.ts +1 -1
  147. package/src/providers/acp-targets.ts +2 -2
  148. package/src/providers/amp-adapter.ts +1 -1
  149. package/src/providers/claude-adapter.ts +21 -1
  150. package/src/providers/claude-sdk-session.ts +22 -3
  151. package/src/providers/claude-session-events.ts +76 -1
  152. package/src/providers/cursor-adapter.ts +1 -1
  153. package/src/providers/fx-adapter.ts +2 -2
  154. package/src/providers/pricing-sources.md +3 -0
  155. package/src/providers/types.ts +13 -0
  156. package/src/slack/render-v2.ts +27 -7
  157. package/src/tests/base-prompt.test.ts +6 -2
  158. package/src/tests/claude-adapter.test.ts +115 -0
  159. package/src/tests/fixtures/fx/acp-updates-recorded.jsonl +1 -1
  160. package/src/tests/internal-ai/complete-structured.test.ts +105 -0
  161. package/src/tests/internal-ai/credentials.test.ts +149 -0
  162. package/src/tests/internal-ai/task-title.test.ts +78 -0
  163. package/src/tests/mcp-input-caps.test.ts +16 -11
  164. package/src/tests/runner-slot-reconcile.test.ts +102 -0
  165. package/src/tests/slack-render-v2.test.ts +85 -0
  166. package/src/types.ts +2 -1
  167. package/src/utils/internal-ai/complete-structured.ts +36 -5
  168. package/src/utils/internal-ai/credentials.ts +78 -2
  169. package/src/utils/internal-ai/models.ts +37 -1
  170. package/src/utils/internal-ai/task-title.ts +31 -1
  171. package/templates/skills/swarm-docs/content.md +8 -0
  172. package/dist/acp-adapter-x1qqgzwx.js +0 -17
  173. package/dist/fx-adapter-4yet1c4f.js +0 -20
  174. package/dist/handlers-0r9evrdj.js +0 -41
  175. package/dist/index-1v23363p.js +0 -39
  176. package/dist/index-30qw6vyw.js +0 -44
  177. package/dist/index-6bm3w6cn.js +0 -40
  178. package/dist/lead-3jpc7kcr.js +0 -79
  179. package/dist/thread-buffer-8fc703jc.js +0 -42
  180. package/dist/worker-3p2vq107.js +0 -79
@@ -427,7 +427,7 @@ const copilotTargetProfile: AcpTargetProfile = {
427
427
  },
428
428
  };
429
429
 
430
- /** Qwen Code's `--auth-type` choices (0.27.3). `qwen-oauth` and `qwen-subscription` need an interactive sign-in, so they are left out. */
430
+ /** Qwen Code's `--auth-type` choices (0.27.4). `qwen-oauth` and `qwen-subscription` need an interactive sign-in, so they are left out. */
431
431
  const QWEN_AUTH_TYPES = ["openai", "openai-responses", "anthropic", "gemini", "vertex-ai"] as const;
432
432
 
433
433
  // Qwen Code is a Gemini CLI fork: QWEN_SYSTEM_MD replaces its built-in prompt
@@ -844,7 +844,7 @@ type FxToolCallMeta = { fx?: { toolCall?: { mcp?: { server?: unknown; tool?: unk
844
844
 
845
845
  /**
846
846
  * fx's display adjustments:
847
- * - The `[context] … capability_search` notice arrives as its own assistant
847
+ * - The `[context] … toolbox` notice arrives as its own assistant
848
848
  * chunk. It becomes an `fx_context_notice` custom event, so it never reaches
849
849
  * the task output.
850
850
  * - A `tool_call` titles the action ("Running", "Get the agent swarm") and
@@ -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.1794657642-gc1e41b";
48
+ export const AMP_PACKAGE = "@ampcode/cli@0.0.1794744038-ga74b43";
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";
@@ -54,7 +54,7 @@ import {
54
54
  MIN_CLAUDE_THINKING_DISPLAY_VERSION,
55
55
  mergeClaudeSettingsArgs,
56
56
  } from "./claude-flag-settings";
57
- import { normalizeClaudeMessage } from "./claude-session-events";
57
+ import { ClaudeUsageAccumulator, normalizeClaudeMessage } from "./claude-session-events";
58
58
  import { resolveSlashSkillPrompt } from "./codex-skill-resolver";
59
59
  import { buildOtelTraceparentEnv, isHarnessOtelEnabled } from "./otel-env";
60
60
  import { applyReasoningEffort, type ReasoningEffort } from "./reasoning-effort";
@@ -917,6 +917,9 @@ class ClaudeSession implements ProviderSession {
917
917
  private transcript: string[];
918
918
  /** Keeps the session heartbeat fresh while Claude idles on background tasks. */
919
919
  private backgroundKeepalive: ClaudeBackgroundKeepalive;
920
+ /** Per-message usage, the cost fallback for a session killed before its result. */
921
+ private usage = new ClaudeUsageAccumulator();
922
+ private readonly startedAt = Date.now();
920
923
  readonly deliverSteering?: (delivery: SteerDelivery) => Promise<SteerDeliveryResult>;
921
924
 
922
925
  constructor(
@@ -1216,6 +1219,13 @@ class ClaudeSession implements ProviderSession {
1216
1219
  );
1217
1220
  }
1218
1221
 
1222
+ // A session killed before its `result` event (its task turned terminal
1223
+ // and the grace ran out) still bills its tokens: report them as estimated.
1224
+ lastCost ??= this.usage.toCost(
1225
+ { taskId: this.config.taskId, agentId: this.config.agentId, model: this.model },
1226
+ { durationMs: Date.now() - this.startedAt, isError: (exitCode ?? 1) !== 0 },
1227
+ );
1228
+
1219
1229
  let failureReason: string | undefined;
1220
1230
  if (exitCode !== 0 && this.errorTracker.hasErrors()) {
1221
1231
  failureReason = this.errorTracker.buildFailureReason(exitCode ?? 1);
@@ -1241,6 +1251,7 @@ class ClaudeSession implements ProviderSession {
1241
1251
  const json = JSON.parse(trimmed);
1242
1252
 
1243
1253
  this.backgroundKeepalive.observe(json);
1254
+ this.usage.observe(json, this.model);
1244
1255
  // In stream-json input mode Claude waits for EOF even after emitting a
1245
1256
  // successful result. End stdin at that turn boundary so normal tasks can
1246
1257
  // exit; steering messages written during the turn are already buffered
@@ -1304,6 +1315,15 @@ class ClaudeSession implements ProviderSession {
1304
1315
  return this.completionPromise;
1305
1316
  }
1306
1317
 
1318
+ /**
1319
+ * End input so Claude exits after its current turn and emits its `result`
1320
+ * (the cost report). Used when the task already turned terminal server-side.
1321
+ */
1322
+ finishInput(): void {
1323
+ this.backgroundKeepalive.stop();
1324
+ this.closeStdin();
1325
+ }
1326
+
1307
1327
  async abort(): Promise<void> {
1308
1328
  this.closeStdin();
1309
1329
  try {
@@ -33,7 +33,7 @@ import {
33
33
  import { ClaudeBackgroundKeepalive } from "./claude-background-keepalive";
34
34
  import type { ClaudeFlagSettings } from "./claude-flag-settings";
35
35
  import type { ClaudeProtocolMessage } from "./claude-session-events";
36
- import { normalizeClaudeMessage } from "./claude-session-events";
36
+ import { ClaudeUsageAccumulator, normalizeClaudeMessage } from "./claude-session-events";
37
37
  import type {
38
38
  CostData,
39
39
  ProviderEvent,
@@ -321,6 +321,9 @@ class ClaudeSdkSession implements ProviderSession {
321
321
  /** Last value written to the context state file read by the context-bound note hook. */
322
322
  private lastContextTokens: number | undefined;
323
323
  private lastCost: CostData | undefined;
324
+ /** Per-message usage, the cost fallback for a session aborted before its result. */
325
+ private usage = new ClaudeUsageAccumulator();
326
+ private readonly startedAt = Date.now();
324
327
  private aborted = false;
325
328
  private abortReason = "cancelled";
326
329
  private acceptingInput = true;
@@ -363,6 +366,21 @@ class ClaudeSdkSession implements ProviderSession {
363
366
  return this.completionPromise;
364
367
  }
365
368
 
369
+ /** The result's cost, else per-message usage reported as estimated. */
370
+ private costOrEstimate(isError: boolean): CostData | undefined {
371
+ return (
372
+ this.lastCost ??
373
+ this.usage.toCost(
374
+ {
375
+ taskId: this.options.config.taskId,
376
+ agentId: this.options.config.agentId,
377
+ model: this.model,
378
+ },
379
+ { durationMs: Date.now() - this.startedAt, isError },
380
+ )
381
+ );
382
+ }
383
+
366
384
  async abort(reason?: string): Promise<void> {
367
385
  if (this.aborted) return;
368
386
  this.aborted = true;
@@ -533,6 +551,7 @@ class ClaudeSdkSession implements ProviderSession {
533
551
  this.turnActive = true;
534
552
  }
535
553
  this.backgroundKeepalive.observe(json);
554
+ this.usage.observe(json, this.model);
536
555
  const normalized = normalizeClaudeMessage(json, {
537
556
  taskId: this.options.config.taskId,
538
557
  agentId: this.options.config.agentId,
@@ -682,7 +701,7 @@ class ClaudeSdkSession implements ProviderSession {
682
701
  return {
683
702
  exitCode: 130,
684
703
  sessionId: this._sessionId,
685
- cost: this.lastCost,
704
+ cost: this.costOrEstimate(true),
686
705
  output: this.lastAssistantText || undefined,
687
706
  isError: true,
688
707
  errorCategory: "cancelled",
@@ -712,7 +731,7 @@ class ClaudeSdkSession implements ProviderSession {
712
731
  return {
713
732
  exitCode: resultIsError ? 1 : 0,
714
733
  sessionId: this._sessionId,
715
- cost: this.lastCost,
734
+ cost: this.costOrEstimate(resultIsError),
716
735
  output:
717
736
  this.lastAssistantText ||
718
737
  (terminalResult && "result" in terminalResult ? terminalResult.result : undefined),
@@ -49,7 +49,7 @@ export type ClaudeProtocolMessage = {
49
49
  num_turns?: number;
50
50
  is_error?: boolean;
51
51
  parent_tool_use_id?: string | null;
52
- message?: { content?: ClaudeContentBlock[]; usage?: ClaudeUsage };
52
+ message?: { id?: string; model?: string; content?: ClaudeContentBlock[]; usage?: ClaudeUsage };
53
53
  };
54
54
 
55
55
  export type NormalizedClaudeMessage = {
@@ -145,6 +145,81 @@ function costFromResult(
145
145
  };
146
146
  }
147
147
 
148
+ /**
149
+ * Sums the usage of every assistant message so a session that ends without a
150
+ * `result` event (killed after its task turned terminal) still reports cost.
151
+ * Claude splits one API message across stream lines that share `message.id`
152
+ * and repeat its usage, so the last usage seen per id wins. Subagent messages
153
+ * are billed too, so they count.
154
+ */
155
+ export class ClaudeUsageAccumulator {
156
+ private readonly byMessage = new Map<string, { model: string; usage: ClaudeUsage }>();
157
+ private unnamed = 0;
158
+
159
+ observe(json: ClaudeProtocolMessage, fallbackModel: string): void {
160
+ if (json.type !== "assistant" || !json.message?.usage) return;
161
+ const id = json.message.id || `unnamed-${this.unnamed++}`;
162
+ const model = json.message.model || fallbackModel;
163
+ this.byMessage.set(id, { model, usage: json.message.usage });
164
+ }
165
+
166
+ /** Estimated cost for the session, or undefined when no message carried usage. */
167
+ toCost(
168
+ state: Pick<ClaudeMessageState, "taskId" | "agentId" | "model">,
169
+ opts: { durationMs: number; isError: boolean },
170
+ ): CostData | undefined {
171
+ const perModel = new Map<string, NonNullable<CostData["models"]>[number]>();
172
+ let cacheWrite5mTokens = 0;
173
+ let cacheWrite1hTokens = 0;
174
+ let thinkingTokens = 0;
175
+ for (const { model, usage } of this.byMessage.values()) {
176
+ const entry = perModel.get(model) ?? {
177
+ model,
178
+ inputTokens: 0,
179
+ outputTokens: 0,
180
+ cacheReadTokens: 0,
181
+ cacheWriteTokens: 0,
182
+ };
183
+ entry.inputTokens += tokenCount(usage.input_tokens) ?? 0;
184
+ entry.outputTokens += tokenCount(usage.output_tokens) ?? 0;
185
+ entry.cacheReadTokens += tokenCount(usage.cache_read_input_tokens) ?? 0;
186
+ entry.cacheWriteTokens += tokenCount(usage.cache_creation_input_tokens) ?? 0;
187
+ perModel.set(model, entry);
188
+ cacheWrite5mTokens += tokenCount(usage.cache_creation?.ephemeral_5m_input_tokens) ?? 0;
189
+ cacheWrite1hTokens += tokenCount(usage.cache_creation?.ephemeral_1h_input_tokens) ?? 0;
190
+ thinkingTokens += tokenCount(usage.output_tokens_details?.thinking_tokens) ?? 0;
191
+ }
192
+ // Claude's local error messages (model "<synthetic>") carry all-zero usage.
193
+ const models = [...perModel.values()].filter(
194
+ (m) => m.inputTokens + m.outputTokens + m.cacheReadTokens + m.cacheWriteTokens > 0,
195
+ );
196
+ if (models.length === 0) return undefined;
197
+ const sum = (key: "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens") =>
198
+ models.reduce((total, m) => total + m[key], 0);
199
+ return {
200
+ sessionId: "",
201
+ taskId: state.taskId,
202
+ agentId: state.agentId,
203
+ totalCostUsd: 0,
204
+ estimated: true,
205
+ inputTokens: sum("inputTokens"),
206
+ outputTokens: sum("outputTokens"),
207
+ cacheReadTokens: sum("cacheReadTokens"),
208
+ cacheWriteTokens: sum("cacheWriteTokens"),
209
+ ...(cacheWrite5mTokens + cacheWrite1hTokens > 0
210
+ ? { cacheWrite5mTokens, cacheWrite1hTokens }
211
+ : {}),
212
+ thinkingTokens,
213
+ models,
214
+ durationMs: opts.durationMs,
215
+ numTurns: null,
216
+ model: state.model,
217
+ isError: opts.isError,
218
+ provider: "claude",
219
+ };
220
+ }
221
+ }
222
+
148
223
  export function normalizeClaudeMessage(
149
224
  json: ClaudeProtocolMessage,
150
225
  state: ClaudeMessageState,
@@ -35,7 +35,7 @@ import type {
35
35
  } from "./types";
36
36
 
37
37
  /** Pinned in package.json and Dockerfile.worker; bump all three together. */
38
- export const CURSOR_SDK_VERSION = "1.3.1";
38
+ export const CURSOR_SDK_VERSION = "1.4.0";
39
39
 
40
40
  /** MCP server name; Cursor reports its tools as `mcp` calls with this `providerIdentifier`. */
41
41
  const CURSOR_MCP_SERVER_NAME = "agent-swarm";
@@ -21,7 +21,7 @@ import type {
21
21
  * Dockerfile.worker; bump the two together). Every ACP shape this adapter
22
22
  * relies on was measured against it.
23
23
  */
24
- export const FX_PINNED_VERSION = "0.0.16";
24
+ export const FX_PINNED_VERSION = "0.0.17";
25
25
 
26
26
  /** OpenAI's Chat Completions prefix; fx appends `/chat/completions`. */
27
27
  export const FX_OPENAI_BASE_URL = "https://api.openai.com/v1";
@@ -165,7 +165,7 @@ export class FxAdapter implements ProviderAdapter {
165
165
 
166
166
  readonly traits: ProviderTraits = {
167
167
  hasMcp: true,
168
- // fx defers swarm tools behind its own `capability_search`; the prompt
168
+ // fx defers swarm tools behind its own `toolbox` (search/run); the prompt
169
169
  // uses the fx-specific discovery line, not the generic tool-search one.
170
170
  hasToolSearch: false,
171
171
  // `~/.claude/skills` is a native fx skill root (verified: a planted skill loaded).
@@ -47,6 +47,9 @@ rate by hand should also update this file.
47
47
  Shortnames (`opus`, `sonnet`, `haiku`) ALSO get rows keyed by the current
48
48
  default full id (e.g. `opus → claude-opus-4-7`). Pi-mono uses the same
49
49
  shortname forms, so they're projected under `provider='pi'` as well.
50
+ A `claude` row posted with `estimated: true` (the session was killed
51
+ before its `result` event) carries per-message usage summed per model;
52
+ it is priced from these rows and tagged `estimated`, never recorded as $0.
50
53
  - OpenAI models → rows under `provider='codex'`, and `provider='pi'` for
51
54
  the ChatGPT subscription route. Pricing accepts `openai-codex/<id>`;
52
55
  `session_costs.model` and its per-model breakdown store the bare OpenAI
@@ -25,6 +25,12 @@ export interface CostData {
25
25
  * so it wins over the pricing table (opencode on OpenRouter).
26
26
  */
27
27
  harnessCostBilled?: boolean;
28
+ /**
29
+ * The token counts were summed from per-message usage because the session
30
+ * ended without its final cost report (Claude killed before its `result`
31
+ * event). The API prices them and tags the row `costSource: 'estimated'`.
32
+ */
33
+ estimated?: boolean;
28
34
  inputTokens?: number;
29
35
  outputTokens?: number;
30
36
  cacheReadTokens?: number;
@@ -207,6 +213,13 @@ export interface ProviderSession {
207
213
  onEvent(listener: (event: ProviderEvent) => void): void;
208
214
  waitForCompletion(): Promise<ProviderResult>;
209
215
  abort(reason?: string): Promise<void>;
216
+ /**
217
+ * Optional. Stop taking input so the session ends after its current turn and
218
+ * still emits its final report (Claude's `result` carries the cost). The
219
+ * runner calls it when the task already turned terminal server-side, then
220
+ * aborts once `RUNNER_TERMINAL_TASK_GRACE_MS` passes. Absent: abort at once.
221
+ */
222
+ finishInput?(): void;
210
223
  /** Optional. Absent means the provider cannot accept mid-run input. */
211
224
  deliverSteering?(delivery: SteerDelivery): Promise<SteerDeliveryResult>;
212
225
  /**
@@ -342,9 +342,29 @@ async function clearAssistantStatus(
342
342
  });
343
343
  }
344
344
 
345
+ /**
346
+ * A Slack timing window from the environment, or `fallback` when the configured
347
+ * value is not a finite number greater than zero. `Number(raw) || fallback` is
348
+ * not enough: it lets a negative or `Infinity` value through, and
349
+ * `closureState` compares elapsed time straight against the window, so a
350
+ * negative one settles or times out a closure on its very first tick instead of
351
+ * waiting out the window.
352
+ */
353
+ function positiveEnvNumber(raw: string | undefined, fallback: number): number {
354
+ const value = Number(raw);
355
+ return Number.isFinite(value) && value > 0 ? value : fallback;
356
+ }
357
+
345
358
  function slackTreeStallMinutes(): number {
346
- const minutes = Number(process.env.SLACK_TREE_STALL_MIN);
347
- return Number.isFinite(minutes) && minutes > 0 ? minutes : 15;
359
+ return positiveEnvNumber(process.env.SLACK_TREE_STALL_MIN, 15);
360
+ }
361
+
362
+ function slackConclusionSettleSeconds(): number {
363
+ return positiveEnvNumber(process.env.SLACK_CONCLUSION_SETTLE_SEC, 10);
364
+ }
365
+
366
+ function slackConclusionTimeoutMinutes(): number {
367
+ return positiveEnvNumber(process.env.SLACK_CONCLUSION_TIMEOUT_MIN, 240);
348
368
  }
349
369
 
350
370
  function isStalledMember(task: AgentTask, now: Date): boolean {
@@ -538,8 +558,8 @@ function normalizeV2Text(value: string): string {
538
558
  * so "concluded" here means "the engine gave up waiting", not "nothing left".
539
559
  */
540
560
  function threadHeaderText(tasks: AgentTask[], now: Date, duration: string): string {
541
- const settleSec = Number(process.env.SLACK_CONCLUSION_SETTLE_SEC) || 10;
542
- const timeoutMin = Number(process.env.SLACK_CONCLUSION_TIMEOUT_MIN) || 240;
561
+ const settleSec = slackConclusionSettleSeconds();
562
+ const timeoutMin = slackConclusionTimeoutMinutes();
543
563
  const asks = tasks.filter((task) => task.source === "slack");
544
564
  const timedOut = asks.some(
545
565
  (ask) =>
@@ -1934,7 +1954,7 @@ type RenderPassContext = {
1934
1954
  * window starts after that.
1935
1955
  */
1936
1956
  function slackOutcomeWindow(delegationEnabled: boolean, now = Date.now()): SlackOutcomeWindow {
1937
- const timeoutMs = (Number(process.env.SLACK_CONCLUSION_TIMEOUT_MIN) || 240) * 60_000;
1957
+ const timeoutMs = slackConclusionTimeoutMinutes() * 60_000;
1938
1958
  const windowMs = Math.max(timeoutMs, 60 * 60_000);
1939
1959
  return {
1940
1960
  finishedAfter: new Date(now - windowMs).toISOString(),
@@ -1984,8 +2004,8 @@ async function processSlackThread(
1984
2004
  ) {
1985
2005
  return "closed";
1986
2006
  }
1987
- const settleSec = Number(process.env.SLACK_CONCLUSION_SETTLE_SEC) || 10;
1988
- const timeoutMin = Number(process.env.SLACK_CONCLUSION_TIMEOUT_MIN) || 240;
2007
+ const settleSec = slackConclusionSettleSeconds();
2008
+ const timeoutMin = slackConclusionTimeoutMinutes();
1989
2009
  const closuresByAskId = new Map<string, AgentTask[]>();
1990
2010
  const ownerAskId = new Map<string, string>();
1991
2011
  if (delegationEnabled) {
@@ -1491,7 +1491,7 @@ describe("getBasePrompt: harness tool discovery", () => {
1491
1491
  expect(result).toContain('import { store_progress } from "agent-swarm"');
1492
1492
  });
1493
1493
 
1494
- test("fx gets capability_search guidance with mcp_swarm_ tool names", async () => {
1494
+ test("fx gets toolbox guidance with mcp_swarm_ tool names", async () => {
1495
1495
  const result = await getBasePrompt({
1496
1496
  ...minimalArgs,
1497
1497
  provider: "fx",
@@ -1499,7 +1499,11 @@ describe("getBasePrompt: harness tool discovery", () => {
1499
1499
  });
1500
1500
  expect(result).not.toContain(deferred);
1501
1501
  expect(result).not.toContain("already in your tool list");
1502
- expect(result).toContain("`capability_search`");
1502
+ // fx 0.0.17 removed `capability_search` and rejects a direct call to a
1503
+ // deferred tool; it runs only through `toolbox` with `run` + `arguments`.
1504
+ expect(result).not.toContain("capability_search");
1505
+ expect(result).toContain("deferred behind `toolbox`");
1506
+ expect(result).toContain("call `toolbox` with `run` set to its name and `arguments`");
1503
1507
  expect(result).toContain("`store-progress` is `mcp_swarm_store-progress`");
1504
1508
  });
1505
1509
 
@@ -426,6 +426,121 @@ describe("ClaudeSession processStreams — ProviderResult.output capture", () =>
426
426
  expect(result.output).toBeUndefined();
427
427
  });
428
428
 
429
+ test("a session that ends without a result reports per-message usage as an estimated cost", async () => {
430
+ const usageA = {
431
+ input_tokens: 10,
432
+ output_tokens: 5,
433
+ cache_read_input_tokens: 100,
434
+ cache_creation_input_tokens: 50,
435
+ cache_creation: { ephemeral_5m_input_tokens: 20, ephemeral_1h_input_tokens: 30 },
436
+ };
437
+ const lines = [
438
+ JSON.stringify({ type: "system", subtype: "init", session_id: "sess-1" }),
439
+ // One API message split over two lines: its usage counts once.
440
+ JSON.stringify({
441
+ type: "assistant",
442
+ message: { id: "msg-a", model: "claude-sonnet-5-5", content: [], usage: usageA },
443
+ }),
444
+ JSON.stringify({
445
+ type: "assistant",
446
+ message: { id: "msg-a", model: "claude-sonnet-5-5", content: [], usage: usageA },
447
+ }),
448
+ JSON.stringify({
449
+ type: "assistant",
450
+ message: {
451
+ id: "msg-b",
452
+ model: "claude-sonnet-5-5",
453
+ content: [],
454
+ usage: { input_tokens: 1, output_tokens: 7, cache_read_input_tokens: 200 },
455
+ },
456
+ }),
457
+ // A subagent on another model is billed too.
458
+ JSON.stringify({
459
+ type: "assistant",
460
+ parent_tool_use_id: "tool-1",
461
+ message: {
462
+ id: "msg-c",
463
+ model: "claude-haiku-4-5",
464
+ content: [],
465
+ usage: { input_tokens: 3, output_tokens: 4 },
466
+ },
467
+ }),
468
+ // Claude's local error message carries zero usage and is dropped.
469
+ JSON.stringify({
470
+ type: "assistant",
471
+ message: {
472
+ id: "msg-d",
473
+ model: "<synthetic>",
474
+ content: [],
475
+ usage: { input_tokens: 0, output_tokens: 0 },
476
+ },
477
+ }),
478
+ ];
479
+ spawnSpy.mockImplementation((() => makeStreamingFakeProc(lines)) as typeof Bun.spawn);
480
+
481
+ const adapter = new ClaudeAdapter(async () => {});
482
+ const session = await adapter.createSession(makeConfig({ env: CLEAN_ENV }));
483
+ const result = await session.waitForCompletion();
484
+
485
+ expect(result.cost).toMatchObject({
486
+ totalCostUsd: 0,
487
+ estimated: true,
488
+ provider: "claude",
489
+ numTurns: null,
490
+ inputTokens: 14,
491
+ outputTokens: 16,
492
+ cacheReadTokens: 300,
493
+ cacheWriteTokens: 50,
494
+ cacheWrite5mTokens: 20,
495
+ cacheWrite1hTokens: 30,
496
+ models: [
497
+ {
498
+ model: "claude-sonnet-5-5",
499
+ inputTokens: 11,
500
+ outputTokens: 12,
501
+ cacheReadTokens: 300,
502
+ cacheWriteTokens: 50,
503
+ },
504
+ {
505
+ model: "claude-haiku-4-5",
506
+ inputTokens: 3,
507
+ outputTokens: 4,
508
+ cacheReadTokens: 0,
509
+ cacheWriteTokens: 0,
510
+ },
511
+ ],
512
+ });
513
+ });
514
+
515
+ test("the result event's cost wins over the per-message estimate", async () => {
516
+ const lines = [
517
+ JSON.stringify({
518
+ type: "assistant",
519
+ message: { id: "msg-a", content: [], usage: { input_tokens: 10, output_tokens: 5 } },
520
+ }),
521
+ JSON.stringify({ type: "result", total_cost_usd: 0.01, duration_ms: 100, num_turns: 1 }),
522
+ ];
523
+ spawnSpy.mockImplementation((() => makeStreamingFakeProc(lines)) as typeof Bun.spawn);
524
+
525
+ const adapter = new ClaudeAdapter(async () => {});
526
+ const session = await adapter.createSession(makeConfig({ env: CLEAN_ENV }));
527
+ const result = await session.waitForCompletion();
528
+
529
+ expect(result.cost?.totalCostUsd).toBe(0.01);
530
+ expect(result.cost?.estimated).toBeUndefined();
531
+ });
532
+
533
+ test("a session with no usage at all reports no cost", async () => {
534
+ const lines = [JSON.stringify({ type: "system", subtype: "init", session_id: "sess-1" })];
535
+ spawnSpy.mockImplementation((() => makeStreamingFakeProc(lines)) as typeof Bun.spawn);
536
+
537
+ const adapter = new ClaudeAdapter(async () => {});
538
+ const session = await adapter.createSession(makeConfig({ env: CLEAN_ENV }));
539
+ const result = await session.waitForCompletion();
540
+
541
+ expect(result.cost).toBeUndefined();
542
+ });
543
+
429
544
  test("result cost includes Claude cache TTL split and complete per-model usage", async () => {
430
545
  const lines = [
431
546
  JSON.stringify({
@@ -1,4 +1,4 @@
1
- {"sessionUpdate":"agent_message_chunk","messageId":"b86bad695b6f80234f85a6ae84770a00","content":{"type":"text","text":"[context] 114 always-loaded MCP tools exceeded the mcp_selected_schema_bytes budget and stay available through capability_search"}}
1
+ {"sessionUpdate":"agent_message_chunk","messageId":"b86bad695b6f80234f85a6ae84770a00","content":{"type":"text","text":"[context] 114 always-loaded MCP tools exceeded the mcp_selected_schema_bytes budget and stay available through toolbox"}}
2
2
  {"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"**Following developer instructions**\n\nI need to ensure I follow the developer's instructions perfectly. First, I’ll send a brief update to the user about the goal and the next step. Then, I’ll call th…"}}
3
3
  {"sessionUpdate":"agent_message_chunk","messageId":"e6788e35f07ecb7d4b22767ec6028538","content":{"type":"text","text":"Goal: fetch the swarm agent list with mcp_swarm_get-swarm as the next step, then run the sleep command. I'll call mcp_swarm_get-swarm now."}}
4
4
  {"sessionUpdate":"tool_call","toolCallId":"call_kK1rqCaYaXn16uKH9e6fmb7v","name":"mcp_swarm_get-swarm","title":"Get the agent swarm","kind":"other","status":"pending","rawInput":{},"_meta":{"fx":{"toolCall":{"internal":false,"mcp":{"server":"swarm","tool":"get-swarm"}}}}}
@@ -623,3 +623,108 @@ describe("completeStructuredWithModel", () => {
623
623
  expect(result).toEqual({ data: { summary: "cli", count: 1 }, model: "haiku" });
624
624
  });
625
625
  });
626
+
627
+ describe("credential kinds added for fireworks and amazon-bedrock", () => {
628
+ const baseOpts = {
629
+ zodSchema: ResultZodSchema,
630
+ toolSchema: ResultToolSchema,
631
+ toolName: "record_result",
632
+ toolDescription: "Record the result.",
633
+ systemPrompt: "sys",
634
+ userPrompt: "user",
635
+ };
636
+ const toolCallMsg = () =>
637
+ makeMsg([
638
+ {
639
+ type: "toolCall",
640
+ id: "call_1",
641
+ name: "record_result",
642
+ arguments: { summary: "ok", count: 1 },
643
+ },
644
+ ]);
645
+
646
+ test("fireworks goes through the pi-ai path with its own key", async () => {
647
+ let seenApiKey: unknown;
648
+ const result = await completeStructuredWithModel({
649
+ ...baseOpts,
650
+ _credentialOverride: {
651
+ kind: "fireworks",
652
+ apiKey: "fw-key",
653
+ modelDefault: "fireworks/accounts/fireworks/models/deepseek-v4p1-flash",
654
+ },
655
+ _complete: async (_model, _ctx, options) => {
656
+ seenApiKey = (options as { apiKey?: unknown })?.apiKey;
657
+ return toolCallMsg();
658
+ },
659
+ });
660
+ expect(result).toEqual({
661
+ data: { summary: "ok", count: 1 },
662
+ model: "fireworks/accounts/fireworks/models/deepseek-v4p1-flash",
663
+ });
664
+ expect(seenApiKey).toBe("fw-key");
665
+ });
666
+
667
+ test("bedrock sends the region, forces the tool, and never sends an apiKey", async () => {
668
+ let options: Record<string, unknown> | undefined;
669
+ let model: { api?: string; id?: string } | undefined;
670
+ const result = await completeStructuredWithModel({
671
+ ...baseOpts,
672
+ _credentialOverride: {
673
+ kind: "amazon-bedrock",
674
+ modelDefault: "amazon-bedrock/global.anthropic.claude-haiku-5-5",
675
+ region: "eu-west-1",
676
+ },
677
+ _complete: async (m, _ctx, opts) => {
678
+ model = m as { api?: string; id?: string };
679
+ options = opts as Record<string, unknown>;
680
+ return toolCallMsg();
681
+ },
682
+ });
683
+
684
+ expect(result).toEqual({
685
+ data: { summary: "ok", count: 1 },
686
+ model: "amazon-bedrock/global.anthropic.claude-haiku-5-5",
687
+ });
688
+ // The catalog entry resolves, which is the whole reason the model default is
689
+ // written in pi-ai's own id form.
690
+ expect(model?.api).toBe("bedrock-converse-stream");
691
+ expect(model?.id).toBe("global.anthropic.claude-haiku-5-5");
692
+ expect(options?.apiKey).toBeUndefined();
693
+ // The resolver's region travels as the adapter's own option, which is what
694
+ // keeps the catalog's us-east-1 base URL from overriding it.
695
+ expect(options?.region).toBe("eu-west-1");
696
+ // The adapter needs the tool forced, same as the Anthropic adapter.
697
+ expect(options?.toolChoice).toEqual({ type: "tool", name: "record_result" });
698
+ });
699
+
700
+ test("non-bedrock kinds get no provider-specific options", async () => {
701
+ let options: Record<string, unknown> | undefined;
702
+ await completeStructuredWithModel({
703
+ ...baseOpts,
704
+ _credentialOverride: {
705
+ kind: "fireworks",
706
+ apiKey: "fw-key",
707
+ modelDefault: "fireworks/accounts/fireworks/models/deepseek-v4p1-flash",
708
+ },
709
+ _complete: async (_m, _ctx, opts) => {
710
+ options = opts as Record<string, unknown>;
711
+ return toolCallMsg();
712
+ },
713
+ });
714
+ expect(options?.region).toBeUndefined();
715
+ expect(options?.env).toBeUndefined();
716
+ });
717
+
718
+ test("a bedrock catalog miss is a clean null, not a throw", async () => {
719
+ const result = await completeStructuredWithModel({
720
+ ...baseOpts,
721
+ _credentialOverride: {
722
+ kind: "amazon-bedrock",
723
+ modelDefault: "amazon-bedrock/not-a-real-model",
724
+ region: "us-east-1",
725
+ },
726
+ _complete: async () => toolCallMsg(),
727
+ });
728
+ expect(result).toBeNull();
729
+ });
730
+ });