@desplega.ai/agent-swarm 2.13.1 → 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.
- package/README.md +1 -1
- package/dist/acp-adapter-t2q6nsqv.js +17 -0
- package/dist/{acp-targets-n7vm5atw.js → acp-targets-k8xs4tj8.js} +7 -7
- package/dist/{actions-hq6wp9xv.js → actions-pg5fxjer.js} +25 -25
- package/dist/{agent-fs-provision-y0qc1rdd.js → agent-fs-provision-vbk3fppw.js} +4 -4
- package/dist/{amp-adapter-1qqs6h91.js → amp-adapter-adbhxsz9.js} +2 -2
- package/dist/{app-7m4z44rv.js → app-b267ggx1.js} +8 -8
- package/dist/{approval-notifications-8sr41gjx.js → approval-notifications-evc1a9z5.js} +9 -9
- package/dist/{assistant-hkczwfv6.js → assistant-wgz2ab84.js} +26 -26
- package/dist/{boot-args-schema-8025snev.js → boot-args-schema-6tpk28j4.js} +1 -1
- package/dist/{boot-reembed-15m87nr1.js → boot-reembed-ankp369c.js} +1 -1
- package/dist/{boot-reembed-4bbpxjh1.js → boot-reembed-r1zyvefv.js} +1 -1
- package/dist/{boot-scrub-sweep-eajr97e9.js → boot-scrub-sweep-cgb6r5bd.js} +2 -2
- package/dist/{boot-seeds-9cwy39jx.js → boot-seeds-bjceqg7b.js} +4 -4
- package/dist/{claude-adapter-g61wa4rt.js → claude-adapter-knztdnff.js} +9 -6
- package/dist/{claude-managed-adapter-znkk0prm.js → claude-managed-adapter-qwejzqkk.js} +3 -3
- package/dist/{claude-managed-setup-f1wndkr2.js → claude-managed-setup-0vgz4d1j.js} +4 -4
- package/dist/{claude-sdk-session-687xzf21.js → claude-sdk-session-c3g6dv0g.js} +11984 -11775
- package/dist/{cli-4mj5g29m.js → cli-0j4qmc80.js} +7 -7
- package/dist/{cli-fn8aj7gb.js → cli-1606qw3n.js} +98 -71
- package/dist/{cli-w41bvvms.js → cli-1gnf5c7x.js} +1 -1
- package/dist/{cli-aebswqmz.js → cli-1wew39p0.js} +15 -15
- package/dist/{cli-0fx95c06.js → cli-268b3dgn.js} +2 -2
- package/dist/cli-2ap1the6.js +11 -0
- package/dist/{cli-w6c6dj91.js → cli-4dyhzhpx.js} +1 -1
- package/dist/{cli-grcc2h2g.js → cli-55fqpd9q.js} +8 -8
- package/dist/{cli-p7g7wd9n.js → cli-61fzwtjk.js} +7 -7
- package/dist/{cli-zaate0rd.js → cli-61p7ty8d.js} +2 -2
- package/dist/{cli-cp0m07wb.js → cli-7fa6yv98.js} +2 -2
- package/dist/{cli-5v6b2am8.js → cli-7kv5d674.js} +7 -7
- package/dist/{cli-6r1dwegd.js → cli-80d5g0fa.js} +2 -2
- package/dist/{cli-0xwb7zpt.js → cli-88np9va3.js} +1 -1
- package/dist/{cli-1b5axkt1.js → cli-8m6gqnf1.js} +2 -2
- package/dist/{cli-0a336ze7.js → cli-8pnawt98.js} +3 -3
- package/dist/{cli-7ewre3dm.js → cli-8sayvj48.js} +2 -2
- package/dist/{cli-yeh3g1q6.js → cli-9gmkw6xn.js} +53 -32
- package/dist/{cli-h03j6je3.js → cli-a21cwm89.js} +2 -2
- package/dist/{cli-s6fhqbz1.js → cli-aytna2fm.js} +1 -1
- package/dist/{cli-84xtgbn6.js → cli-b0m3bg0f.js} +100 -2
- package/dist/{cli-mwxez0pz.js → cli-b768ek79.js} +1 -1
- package/dist/{cli-9xx36trj.js → cli-bh53ppqm.js} +2 -2
- package/dist/{cli-1carhg8g.js → cli-czeh7x13.js} +3 -3
- package/dist/{cli-cd9acnvd.js → cli-djwt4mtn.js} +71 -5
- package/dist/{cli-sfajkbd7.js → cli-dq30fq3q.js} +2 -2
- package/dist/{cli-a8ts6x1n.js → cli-dw43pnzp.js} +5 -5
- package/dist/{cli-h9bejmkf.js → cli-e4gx499y.js} +52 -29
- package/dist/{cli-t90k0phh.js → cli-ea367bdn.js} +32 -23
- package/dist/{cli-cmgdptmx.js → cli-ef590376.js} +29 -5
- package/dist/{cli-8rbkw18r.js → cli-fbmgpt72.js} +2 -2
- package/dist/{cli-tzzas8rb.js → cli-g4dhd3pr.js} +2 -2
- package/dist/{cli-snypfjgj.js → cli-gc715jrc.js} +1 -1
- package/dist/{cli-c0tyzt73.js → cli-gkjw33x5.js} +1 -1
- package/dist/{cli-z6m6xzxt.js → cli-grk77aen.js} +26 -5
- package/dist/{cli-hs3mqswp.js → cli-gxqwm3k3.js} +5 -5
- package/dist/{cli-4h90xaet.js → cli-h3drhntp.js} +1 -1
- package/dist/{cli-qn79645p.js → cli-h9d3sdnc.js} +1 -1
- package/dist/{cli-byxsctca.js → cli-hd2a204w.js} +6 -6
- package/dist/{cli-1dr5at77.js → cli-hhb8kbwd.js} +12 -12
- package/dist/{cli-zvpkrgsc.js → cli-hpxcfvdm.js} +3 -3
- package/dist/{cli-cqxwjb93.js → cli-hxj888w3.js} +1 -1
- package/dist/{cli-82j36f2m.js → cli-jjzxsk47.js} +9 -3
- package/dist/{cli-13t0smbk.js → cli-ka4tqjzd.js} +185 -58
- package/dist/{cli-jhtvt7gn.js → cli-kh973792.js} +3 -3
- package/dist/{cli-x5yb8zc8.js → cli-kwm1bek7.js} +1 -1
- package/dist/{cli-bjmq14k9.js → cli-mgr3gatr.js} +4 -4
- package/dist/{cli-c8kqmzzf.js → cli-nbawx3s0.js} +2 -2
- package/dist/{cli-04103ryh.js → cli-ppf9ap9n.js} +1 -1
- package/dist/{cli-dd57p1gd.js → cli-pzsedyb0.js} +4 -4
- package/dist/{cli-32xndx6b.js → cli-r6xnchva.js} +2 -2
- package/dist/{cli-4tbvndmm.js → cli-r8ddn0hf.js} +1 -1
- package/dist/{cli-y6qqbpwc.js → cli-snwz16eg.js} +1 -1
- package/dist/{cli-w24f3j49.js → cli-sy2ge2ye.js} +7 -6
- package/dist/{cli-3m8vqehw.js → cli-syqcny89.js} +3 -3
- package/dist/{cli-qx1dwrr5.js → cli-tjf1bh1v.js} +2 -2
- package/dist/{cli-xhkek467.js → cli-v1v49t36.js} +28 -2
- package/dist/{cli-cn6fpa1p.js → cli-v8rpjrnx.js} +1 -1
- package/dist/{cli-mmw2sjaf.js → cli-vgh5adn9.js} +5 -5
- package/dist/{cli-3zyme1wt.js → cli-w24741sm.js} +3 -3
- package/dist/{cli-gq6qhmrr.js → cli-wsnradtk.js} +3 -3
- package/dist/{cli-nk8swfpx.js → cli-wtffytm8.js} +3 -3
- package/dist/{cli-0m77n7ej.js → cli-xc8m5cjn.js} +54 -12
- package/dist/{cli-8cmjkbvj.js → cli-y0q92v4r.js} +2 -2
- package/dist/{cli-gedf48yw.js → cli-y754psdt.js} +4 -4
- package/dist/cli.js +19 -18
- package/dist/{codex-adapter-ysfg6ty3.js → codex-adapter-493vb8cv.js} +5 -5
- package/dist/{codex-hook-c0nvm30r.js → codex-hook-ej8hn6z5.js} +9 -2
- package/dist/{codex-session-runner-823scr6g.js → codex-session-runner-ps5m4z1g.js} +5 -5
- package/dist/{commands-5rbm07fz.js → commands-shktk0b8.js} +3 -3
- package/dist/{controllers-connect-34jzhfft.js → controllers-connect-yft057ws.js} +24 -24
- package/dist/core-nheayfgm.js +42 -0
- package/dist/{cursor-adapter-w1681kp1.js → cursor-adapter-8fpm4dng.js} +1 -1
- package/dist/{db-6bkgbfwk.js → db-0ezhdhz5.js} +3 -3
- package/dist/{db-hcj16x7z.js → db-84pz2w5c.js} +2 -2
- package/dist/{dispatcher-jgjqrfzv.js → dispatcher-h2rz69f6.js} +23 -23
- package/dist/{easter-egg-3d-w17nsny6.js → easter-egg-3d-m41ad78v.js} +1 -1
- package/dist/{embedding-space-v06fwy7b.js → embedding-space-yam9zwzj.js} +6 -6
- package/dist/{embeddings-g50dxea4.js → embeddings-g2be0y8q.js} +1 -1
- package/dist/{execute-1n36haw1.js → execute-hhdejgzf.js} +1 -1
- package/dist/{external-channel-43tv8pg6.js → external-channel-kjt2yzfj.js} +2 -2
- package/dist/fx-adapter-8g7xsp8q.js +20 -0
- package/dist/{grok-adapter-my5j8mdf.js → grok-adapter-ztk2zkz1.js} +9 -9
- package/dist/handlers-9ywssz71.js +41 -0
- package/dist/{heartbeat-sf3nk937.js → heartbeat-2e5jdexj.js} +25 -25
- package/dist/{hook-dqph1e05.js → hook-34s8cmgn.js} +9 -6
- package/dist/{hook-m1m9dm6w.js → hook-acg9saz7.js} +8 -5
- package/dist/{http-w0th1cz9.js → http-ra2zr2f8.js} +304 -111
- package/dist/{index-pb03vans.js → index-2z1z7qx6.js} +26 -26
- package/dist/{index-p2f5xg64.js → index-3j803vnb.js} +36259 -34299
- package/dist/index-6mgbdtv1.js +44 -0
- package/dist/{index-e8pz8qdg.js → index-7dgxveck.js} +2 -2
- package/dist/{index-gkpfgpg7.js → index-93bw5wds.js} +1 -1
- package/dist/{index-c0e8en64.js → index-9q42cr54.js} +1 -1
- package/dist/{index-ffba0z8q.js → index-9r4j0a60.js} +28 -18
- package/dist/index-hqdsn2t2.js +39 -0
- package/dist/{index-k8ajc0g0.js → index-maddg9ys.js} +1 -1
- package/dist/{index-y4vd4mhn.js → index-mbpxhc4w.js} +1 -1
- package/dist/index-rz8ve510.js +569 -0
- package/dist/index-st231bqv.js +40 -0
- package/dist/{index-ez823q84.js → index-ym9fgxad.js} +1 -1
- package/dist/{keepalive-2v06q2e8.js → keepalive-vjnnqbkm.js} +4 -4
- package/dist/lead-mk0xkth2.js +82 -0
- package/dist/{maintenance-vx7vjhhy.js → maintenance-px2g599e.js} +1 -1
- package/dist/{oauth-refresh-sweep-g06k4bza.js → oauth-refresh-sweep-nkykf09m.js} +3 -3
- package/dist/{object-webhooks-3dzdq4fm.js → object-webhooks-gt9xnq21.js} +7 -7
- package/dist/{onboard-232pazny.js → onboard-1f134p65.js} +3 -3
- package/dist/{opencode-adapter-t0paqbh8.js → opencode-adapter-94976yab.js} +6 -6
- package/dist/{otel-impl-kmpkyp4y.js → otel-impl-5d4p2fqs.js} +1 -1
- package/dist/{pending-x0z3vx1x.js → pending-vkk0vx6n.js} +24 -24
- package/dist/{pi-mono-adapter-7pmypn6d.js → pi-mono-adapter-cyzdv5er.js} +11 -11
- package/dist/{pricing-refresh-ytjmtyd7.js → pricing-refresh-jtmjwss9.js} +2 -2
- package/dist/{rbac-roles-xyaxekh3.js → rbac-roles-1fvmdyeb.js} +2 -2
- package/dist/{rbac-roles-fgm5mxr2.js → rbac-roles-yd1fgpsn.js} +3 -3
- package/dist/{render-v2-ws972g4r.js → render-v2-kb5s3vx4.js} +8 -8
- package/dist/{resume-m6mjzhkp.js → resume-z1vs44n5.js} +11 -11
- package/dist/{runtime-zzpc0c8a.js → runtime-gk6ct7r7.js} +1 -1
- package/dist/{session-access-vp35xs91.js → session-access-nz6nre4d.js} +5 -5
- package/dist/{session-source-backfill-p73e8zbe.js → session-source-backfill-wb60zjkd.js} +1 -1
- package/dist/{setup-r4kd7rxg.js → setup-2x8g8j4s.js} +1 -1
- package/dist/thread-buffer-d50rqpev.js +42 -0
- package/dist/{tree-visibility-07h2tbs2.js → tree-visibility-ts3z30kw.js} +2 -2
- package/dist/{user-merge-jobs-96vg9rpe.js → user-merge-jobs-zetg26e0.js} +3 -3
- package/dist/{virtual-modules-vgn3f2x4.js → virtual-modules-674fka8x.js} +3 -3
- package/dist/{work-objects-74hbcx3e.js → work-objects-w52yyjxm.js} +26 -26
- package/dist/worker-662x1vse.js +82 -0
- package/dist/{worker-follow-up-ezavwn5d.js → worker-follow-up-dyfxyjbj.js} +23 -23
- package/openapi.json +6 -2
- package/package.json +7 -6
- package/src/be/migrations/341_user_token_expiry.sql +4 -0
- package/src/be/scripts/run-credential.ts +55 -1
- package/src/be/scripts/typecheck.ts +4 -4
- package/src/be/scripts/user-code-mode.ts +160 -0
- package/src/be/users.ts +48 -7
- package/src/commands/onboard/agent-fs-version.ts +1 -1
- package/src/commands/runner.ts +62 -6
- package/src/hooks/codex-hook.ts +15 -4
- package/src/hooks/hook.ts +7 -0
- package/src/http/script-connection-proxy.ts +18 -6
- package/src/http/scripts.ts +2 -11
- package/src/http/session-cost-recompute.ts +3 -1
- package/src/http/session-data.ts +3 -0
- package/src/http/users.ts +1 -0
- package/src/integrations/chat-sdk/adapters.ts +29 -0
- package/src/integrations/chat-sdk/limits.ts +3 -0
- package/src/integrations/chat-sdk/rocketchat/README.md +8 -0
- package/src/integrations/chat-sdk/rocketchat/index.ts +790 -0
- package/src/integrations/chat-sdk/rocketchat/markdown.ts +210 -0
- package/src/integrations/chat-sdk/rocketchat/types.ts +249 -0
- package/src/integrations/chat-sdk/runtime.ts +11 -5
- package/src/integrations/chat-sdk/schema.ts +37 -3
- package/src/integrations/chat-sdk/status.ts +9 -0
- package/src/prompts/base-prompt.ts +1 -1
- package/src/prompts/session-templates.ts +1 -1
- package/src/providers/acp-targets.ts +2 -2
- package/src/providers/amp-adapter.ts +1 -1
- package/src/providers/claude-adapter.ts +21 -1
- package/src/providers/claude-sdk-session.ts +22 -3
- package/src/providers/claude-session-events.ts +76 -1
- package/src/providers/cursor-adapter.ts +1 -1
- package/src/providers/fx-adapter.ts +2 -2
- package/src/providers/pricing-sources.md +3 -0
- package/src/providers/types.ts +13 -0
- package/src/rbac/legacy-policy.ts +1 -0
- package/src/rbac/permissions.ts +4 -0
- package/src/scripts-runtime/executors/native.ts +225 -67
- package/src/scripts-runtime/mcp-client.ts +2 -1
- package/src/scripts-runtime/swarm-sdk.ts +2 -1
- package/src/scripts-runtime/types/stdlib.d.ts +4 -4
- package/src/scripts-runtime/types/swarm-sdk.d.ts +4 -4
- package/src/server-user.ts +98 -0
- package/src/slack/render-v2.ts +27 -7
- package/src/tests/base-prompt.test.ts +6 -2
- package/src/tests/chat-sdk-rocketchat-vendored.test.ts +67 -0
- package/src/tests/chat-sdk-status-route.test.ts +13 -1
- package/src/tests/claude-adapter.test.ts +115 -0
- package/src/tests/codex-app-server.test.ts +4 -6
- package/src/tests/fixtures/fx/acp-updates-recorded.jsonl +1 -1
- package/src/tests/internal-ai/complete-structured.test.ts +105 -0
- package/src/tests/internal-ai/credentials.test.ts +149 -0
- package/src/tests/internal-ai/task-title.test.ts +78 -0
- package/src/tests/mcp-input-caps.test.ts +16 -11
- package/src/tests/mcp-user-route.test.ts +10 -1
- package/src/tests/runner-slot-reconcile.test.ts +102 -0
- package/src/tests/script-connections-mcp.test.ts +14 -10
- package/src/tests/script-connections-sql.test.ts +6 -2
- package/src/tests/script-connections.test.ts +2 -0
- package/src/tests/slack-render-v2.test.ts +85 -0
- package/src/tools/script-common.ts +37 -22
- package/src/tools/script-query-types.ts +1 -1
- package/src/tools/script-run.ts +1 -1
- package/src/tools/script-search.ts +12 -10
- package/src/tools/utils.ts +7 -1
- package/src/types.ts +2 -1
- package/src/utils/internal-ai/complete-structured.ts +36 -5
- package/src/utils/internal-ai/credentials.ts +78 -2
- package/src/utils/internal-ai/models.ts +37 -1
- package/src/utils/internal-ai/task-title.ts +31 -1
- package/templates/skills/chat-sdk/content.md +2 -2
- package/templates/skills/swarm-docs/content.md +10 -0
- package/dist/acp-adapter-xtj40wd8.js +0 -17
- package/dist/core-kdehq26g.js +0 -42
- package/dist/fx-adapter-bvh05t4a.js +0 -20
- package/dist/handlers-wyymeeqh.js +0 -41
- package/dist/index-22khdtby.js +0 -44
- package/dist/index-np0582ac.js +0 -40
- package/dist/index-vgkrj1jt.js +0 -39
- package/dist/lead-55z813ng.js +0 -79
- package/dist/thread-buffer-cm2nzq6t.js +0 -42
- package/dist/worker-5pn2vzx6.js +0 -79
- /package/dist/{cli-m4ejz4nj.js → cli-cah298e5.js} +0 -0
|
@@ -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.
|
|
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.
|
|
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.
|
|
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.
|
|
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 `
|
|
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
|
package/src/providers/types.ts
CHANGED
|
@@ -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
|
/**
|
|
@@ -356,6 +356,7 @@ export const LEGACY_POLICY = {
|
|
|
356
356
|
"script.global.write": leadOnly,
|
|
357
357
|
"script.global.delete": leadOnly,
|
|
358
358
|
"script.search": anyAuthenticated,
|
|
359
|
+
"script.run": anyAuthenticated,
|
|
359
360
|
"script.api.read.secrets": leadOnly,
|
|
360
361
|
"script.api.create": leadOnly,
|
|
361
362
|
"script.api.update": leadOnly,
|
package/src/rbac/permissions.ts
CHANGED
|
@@ -386,6 +386,10 @@ export const PERMISSIONS = {
|
|
|
386
386
|
description: "Search reusable scripts visible to the caller.",
|
|
387
387
|
namespace: "script",
|
|
388
388
|
},
|
|
389
|
+
"script.run": {
|
|
390
|
+
description: "Run a global or inline script as yourself from the user MCP.",
|
|
391
|
+
namespace: "script",
|
|
392
|
+
},
|
|
389
393
|
"script.api.read.secrets": {
|
|
390
394
|
description: "Reveal an external script API endpoint bearer token.",
|
|
391
395
|
namespace: "script",
|
|
@@ -247,27 +247,203 @@ async function linkOrWriteBareImportShims(baseTmpDir: string, tmpdir: string): P
|
|
|
247
247
|
}
|
|
248
248
|
}
|
|
249
249
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
|
|
250
|
+
type HarnessProcess = Bun.Subprocess<"pipe", "pipe", "pipe">;
|
|
251
|
+
|
|
252
|
+
/** Everything a harness spawn depends on, apart from its run dir. */
|
|
253
|
+
interface HarnessSpec {
|
|
254
|
+
harnessPath: string;
|
|
255
|
+
baseTmpDir: string;
|
|
256
|
+
runAs: SandboxIdentity | undefined;
|
|
257
|
+
hostValidatedArgs: boolean;
|
|
258
|
+
resources: ExecutorInput["resources"];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function harnessRunPaths(tmpdir: string) {
|
|
262
|
+
return {
|
|
263
|
+
argsFile: `${tmpdir}/args.json`,
|
|
264
|
+
sourceFile: `${tmpdir}/user-module/user-script.ts`,
|
|
265
|
+
resultFile: `${tmpdir}/result.json`,
|
|
266
|
+
errorFile: `${tmpdir}/error.json`,
|
|
267
|
+
startedFile: `${tmpdir}/started.marker`,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function harnessEnvFor(spec: HarnessSpec, tmpdir: string): Record<string, string> {
|
|
272
|
+
const paths = harnessRunPaths(tmpdir);
|
|
273
|
+
return {
|
|
274
|
+
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
275
|
+
// The dropped identity cannot use the API's HOME.
|
|
276
|
+
HOME: spec.runAs ? tmpdir : (process.env.HOME ?? "/tmp"),
|
|
277
|
+
LANG: process.env.LANG ?? "C.UTF-8",
|
|
278
|
+
LC_ALL: process.env.LC_ALL ?? "C.UTF-8",
|
|
279
|
+
TMPDIR: tmpdir,
|
|
280
|
+
SWARM_SCRIPT_TMPDIR: tmpdir,
|
|
281
|
+
SWARM_SCRIPT_ARGS_FILE: paths.argsFile,
|
|
282
|
+
SWARM_SCRIPT_SOURCE_FILE: paths.sourceFile,
|
|
283
|
+
SWARM_SCRIPT_RESULT_FILE: paths.resultFile,
|
|
284
|
+
SWARM_SCRIPT_ERROR_FILE: paths.errorFile,
|
|
285
|
+
SWARM_SCRIPT_STARTED_FILE: paths.startedFile,
|
|
286
|
+
...(spec.hostValidatedArgs ? { SWARM_SCRIPT_HOST_VALIDATED_ARGS: "1" } : {}),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function spawnHarness(spec: HarnessSpec, tmpdir: string): HarnessProcess {
|
|
291
|
+
const harnessEnv = harnessEnvFor(spec, tmpdir);
|
|
292
|
+
const limits = {
|
|
293
|
+
virtualMemoryMb: spec.resources.memoryMb,
|
|
294
|
+
cpuTimeSec: spec.resources.cpuTimeSec,
|
|
295
|
+
maxProcs: spec.resources.maxProcs,
|
|
296
|
+
maxFileKb: Math.floor(spec.resources.maxFileBytes / 1024),
|
|
297
|
+
maxFdCount: spec.resources.maxFdCount,
|
|
298
|
+
};
|
|
299
|
+
return registerProcessGroup(
|
|
300
|
+
Bun.spawn(
|
|
301
|
+
buildSandboxedCommand(
|
|
302
|
+
["bun", "run", spec.harnessPath],
|
|
303
|
+
harnessEnv,
|
|
304
|
+
limits,
|
|
305
|
+
"inline",
|
|
306
|
+
spec.runAs,
|
|
307
|
+
),
|
|
308
|
+
{
|
|
309
|
+
// On POSIX, Bun.spawn only needs PATH itself to locate the `sh`
|
|
310
|
+
// binary for argv[0] — the sandboxed command's `env -i` prelude is
|
|
311
|
+
// what actually scrubs the child's environment down to `harnessEnv`
|
|
312
|
+
// above. On win32 there is no such prelude, so `sandboxSpawnEnv`
|
|
313
|
+
// passes `harnessEnv` through directly instead — see
|
|
314
|
+
// `buildSandboxedCommand`'s win32 doc comment.
|
|
315
|
+
env: sandboxSpawnEnv(harnessEnv),
|
|
316
|
+
cwd: tmpdir,
|
|
317
|
+
detached: detachedProcessGroup,
|
|
318
|
+
stdin: "pipe",
|
|
319
|
+
stdout: "pipe",
|
|
320
|
+
stderr: "pipe",
|
|
321
|
+
},
|
|
322
|
+
),
|
|
268
323
|
);
|
|
269
324
|
}
|
|
270
325
|
|
|
326
|
+
/**
|
|
327
|
+
* Warm harness pool. A harness spends most of a short run loading its own
|
|
328
|
+
* modules (ctx, SDK, zod) before it reads the config payload from stdin, and
|
|
329
|
+
* none of that depends on the run. So after each spawn the executor starts
|
|
330
|
+
* one spare harness with the same spec in a fresh run dir; it loads and then
|
|
331
|
+
* blocks on stdin. The next run with that spec writes its args and source
|
|
332
|
+
* into the spare's run dir and sends the payload, skipping spawn and module
|
|
333
|
+
* load. The script itself still runs once per call, in its own process, with
|
|
334
|
+
* the same env, limits and identity, so outputs and side effects are those of
|
|
335
|
+
* a cold run. A spare holds no credentials (they arrive on stdin), is
|
|
336
|
+
* single-use, and is stopped after WARM_IDLE_MS unused.
|
|
337
|
+
*
|
|
338
|
+
* The user module dir is created only after the spare has started: Bun
|
|
339
|
+
* snapshots the cwd listing at startup, and a subdir created later is
|
|
340
|
+
* resolved from disk (see the note above `userModulePath` in eval-harness.ts).
|
|
341
|
+
*
|
|
342
|
+
* Under a dropped identity the spare's run dir stays owned by the API until a
|
|
343
|
+
* run takes it. Every script shares that identity, so a dir it owned while
|
|
344
|
+
* idle could hold links planted by another script, and the API's writes and
|
|
345
|
+
* chowns below would follow them. The harness writes nothing before it reads
|
|
346
|
+
* stdin, so the spare needs no write access while it waits. A taken spare's
|
|
347
|
+
* dir gets the cold path's order: write as the API, then chown.
|
|
348
|
+
*/
|
|
349
|
+
interface WarmHarness {
|
|
350
|
+
key: string;
|
|
351
|
+
tmpdir: string;
|
|
352
|
+
proc: HarnessProcess;
|
|
353
|
+
idleTimer: ReturnType<typeof setTimeout>;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const WARM_IDLE_MS = 30_000;
|
|
357
|
+
const MAX_WARM_SPECS = 4;
|
|
358
|
+
const warmHarnesses = new Map<string, WarmHarness>();
|
|
359
|
+
const warmingSpecs = new Set<string>();
|
|
360
|
+
|
|
361
|
+
function harnessSpecKey(spec: HarnessSpec): string {
|
|
362
|
+
return JSON.stringify([
|
|
363
|
+
spec.harnessPath,
|
|
364
|
+
spec.baseTmpDir,
|
|
365
|
+
spec.runAs ?? null,
|
|
366
|
+
spec.hostValidatedArgs,
|
|
367
|
+
spec.resources.memoryMb,
|
|
368
|
+
spec.resources.cpuTimeSec,
|
|
369
|
+
spec.resources.maxProcs,
|
|
370
|
+
spec.resources.maxFileBytes,
|
|
371
|
+
spec.resources.maxFdCount,
|
|
372
|
+
process.env.PATH ?? null,
|
|
373
|
+
process.env.HOME ?? null,
|
|
374
|
+
process.env.LANG ?? null,
|
|
375
|
+
process.env.LC_ALL ?? null,
|
|
376
|
+
]);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function harnessAlive(proc: HarnessProcess): boolean {
|
|
380
|
+
return proc.exitCode === null && proc.signalCode === null && !proc.killed;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function discardWarmHarness(entry: WarmHarness): void {
|
|
384
|
+
clearTimeout(entry.idleTimer);
|
|
385
|
+
if (warmHarnesses.get(entry.key) === entry) warmHarnesses.delete(entry.key);
|
|
386
|
+
void terminateProcessGroup(entry.proc.pid)
|
|
387
|
+
.catch(() => {})
|
|
388
|
+
.finally(() => rm(entry.tmpdir, { recursive: true, force: true }).catch(() => {}));
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Removes and returns the spare for `key` when it is still waiting on stdin. */
|
|
392
|
+
function takeWarmHarness(key: string): WarmHarness | undefined {
|
|
393
|
+
const entry = warmHarnesses.get(key);
|
|
394
|
+
if (!entry) return undefined;
|
|
395
|
+
warmHarnesses.delete(key);
|
|
396
|
+
clearTimeout(entry.idleTimer);
|
|
397
|
+
if (!harnessAlive(entry.proc)) {
|
|
398
|
+
discardWarmHarness(entry);
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
entry.proc.ref();
|
|
402
|
+
return entry;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function startWarmHarness(key: string, spec: HarnessSpec): Promise<void> {
|
|
406
|
+
if (process.platform === "win32") return;
|
|
407
|
+
if (warmHarnesses.has(key) || warmingSpecs.has(key)) return;
|
|
408
|
+
warmingSpecs.add(key);
|
|
409
|
+
const tmpdir = `${spec.baseTmpDir}/swarm-script-${crypto.randomUUID()}`;
|
|
410
|
+
let started = false;
|
|
411
|
+
try {
|
|
412
|
+
// The run dir stays owned by the API until a run takes the spare (see
|
|
413
|
+
// above): no chown here.
|
|
414
|
+
await mkdir(tmpdir, { recursive: true, mode: 0o755 });
|
|
415
|
+
await linkOrWriteBareImportShims(spec.baseTmpDir, tmpdir);
|
|
416
|
+
if (warmHarnesses.has(key)) return;
|
|
417
|
+
const proc = spawnHarness(spec, tmpdir);
|
|
418
|
+
// A spare must not keep the API (or a CLI / test process) alive.
|
|
419
|
+
proc.unref();
|
|
420
|
+
started = true;
|
|
421
|
+
const entry: WarmHarness = {
|
|
422
|
+
key,
|
|
423
|
+
tmpdir,
|
|
424
|
+
proc,
|
|
425
|
+
idleTimer: setTimeout(() => discardWarmHarness(entry), WARM_IDLE_MS),
|
|
426
|
+
};
|
|
427
|
+
entry.idleTimer.unref?.();
|
|
428
|
+
if (warmHarnesses.size >= MAX_WARM_SPECS) {
|
|
429
|
+
const oldest = warmHarnesses.values().next().value;
|
|
430
|
+
if (oldest) discardWarmHarness(oldest);
|
|
431
|
+
}
|
|
432
|
+
warmHarnesses.set(key, entry);
|
|
433
|
+
void proc.exited.then(
|
|
434
|
+
() => {
|
|
435
|
+
if (warmHarnesses.get(key) === entry) discardWarmHarness(entry);
|
|
436
|
+
},
|
|
437
|
+
() => {},
|
|
438
|
+
);
|
|
439
|
+
} catch {
|
|
440
|
+
// Best-effort: the next run spawns cold.
|
|
441
|
+
} finally {
|
|
442
|
+
warmingSpecs.delete(key);
|
|
443
|
+
if (!started) await rm(tmpdir, { recursive: true, force: true }).catch(() => {});
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
271
447
|
export class NativeScriptExecutor implements ScriptExecutor {
|
|
272
448
|
readonly name = "native";
|
|
273
449
|
|
|
@@ -278,24 +454,24 @@ export class NativeScriptExecutor implements ScriptExecutor {
|
|
|
278
454
|
|
|
279
455
|
const start = Date.now();
|
|
280
456
|
const baseTmpDir = process.env.TMPDIR ?? (process.platform === "win32" ? osTmpdir() : "/tmp");
|
|
281
|
-
const tmpdir = `${baseTmpDir}/swarm-script-${crypto.randomUUID()}`;
|
|
282
|
-
await mkdir(`${tmpdir}/user-module`, { recursive: true });
|
|
283
|
-
|
|
284
|
-
const argsFile = `${tmpdir}/args.json`;
|
|
285
|
-
const sourceFile = `${tmpdir}/user-module/user-script.ts`;
|
|
286
|
-
const resultFile = `${tmpdir}/result.json`;
|
|
287
|
-
const errorFile = `${tmpdir}/error.json`;
|
|
288
|
-
const startedFile = `${tmpdir}/started.marker`;
|
|
289
457
|
const runAs = resolveSandboxIdentity();
|
|
290
458
|
// In compiled binary mode, import.meta.url points into /$bunfs/ which spawned
|
|
291
459
|
// subprocesses cannot access. Use the pre-built bundle from real filesystem instead.
|
|
292
460
|
const harnessPath = process.env.SCRIPT_RUNTIME_DIR
|
|
293
461
|
? `${process.env.SCRIPT_RUNTIME_DIR}/eval-harness.bundle.js`
|
|
294
462
|
: fileURLToPath(new URL("../eval-harness.ts", import.meta.url));
|
|
463
|
+
const spec: HarnessSpec = {
|
|
464
|
+
harnessPath,
|
|
465
|
+
baseTmpDir,
|
|
466
|
+
runAs,
|
|
467
|
+
hostValidatedArgs: Boolean(input.hostValidatedArgs),
|
|
468
|
+
resources: input.resources,
|
|
469
|
+
};
|
|
470
|
+
const specKey = harnessSpecKey(spec);
|
|
295
471
|
let timedOut = false;
|
|
296
472
|
let killed = input.signal?.aborted ?? false;
|
|
297
473
|
let removeAbortListener: (() => void) | undefined;
|
|
298
|
-
let proc:
|
|
474
|
+
let proc: HarnessProcess | undefined;
|
|
299
475
|
|
|
300
476
|
const killedOutput = (): ExecutorOutput => ({
|
|
301
477
|
result: undefined,
|
|
@@ -307,9 +483,16 @@ export class NativeScriptExecutor implements ScriptExecutor {
|
|
|
307
483
|
error: "killed",
|
|
308
484
|
});
|
|
309
485
|
|
|
310
|
-
|
|
311
|
-
|
|
486
|
+
if (killed) return killedOutput();
|
|
487
|
+
|
|
488
|
+
const warm = takeWarmHarness(specKey);
|
|
489
|
+
const tmpdir = warm?.tmpdir ?? `${baseTmpDir}/swarm-script-${crypto.randomUUID()}`;
|
|
490
|
+
const { argsFile, sourceFile, resultFile, errorFile, startedFile } = harnessRunPaths(tmpdir);
|
|
491
|
+
// A taken spare is this run's process from here on: an abort or error
|
|
492
|
+
// below terminates it and removes its run dir like a cold child's.
|
|
493
|
+
if (warm) proc = warm.proc;
|
|
312
494
|
|
|
495
|
+
try {
|
|
313
496
|
// Listen before the first await: an abort during the file writes below
|
|
314
497
|
// must stop the spawn, not land between the writes and the listener.
|
|
315
498
|
const onExternalAbort = () => {
|
|
@@ -319,11 +502,14 @@ export class NativeScriptExecutor implements ScriptExecutor {
|
|
|
319
502
|
input.signal?.addEventListener("abort", onExternalAbort, { once: true });
|
|
320
503
|
removeAbortListener = () => input.signal?.removeEventListener("abort", onExternalAbort);
|
|
321
504
|
|
|
505
|
+
// A spare's run dir already has its node_modules link, and is still
|
|
506
|
+
// owned by the API: write as the API first, then chown, on both paths.
|
|
507
|
+
await mkdir(`${tmpdir}/user-module`, { recursive: true });
|
|
322
508
|
await Promise.all([
|
|
323
509
|
Bun.write(argsFile, JSON.stringify(input.args ?? null)),
|
|
324
510
|
Bun.write(sourceFile, input.source),
|
|
325
|
-
linkOrWriteBareImportShims(baseTmpDir, tmpdir),
|
|
326
511
|
]);
|
|
512
|
+
if (!warm) await linkOrWriteBareImportShims(baseTmpDir, tmpdir);
|
|
327
513
|
if (runAs) {
|
|
328
514
|
// The child writes its result and marker files into the run dir.
|
|
329
515
|
await Promise.all(
|
|
@@ -341,46 +527,18 @@ export class NativeScriptExecutor implements ScriptExecutor {
|
|
|
341
527
|
if (proc) void terminateProcessGroup(proc.pid);
|
|
342
528
|
}, input.resources.wallClockMs);
|
|
343
529
|
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
LANG: process.env.LANG ?? "C.UTF-8",
|
|
349
|
-
LC_ALL: process.env.LC_ALL ?? "C.UTF-8",
|
|
350
|
-
TMPDIR: tmpdir,
|
|
351
|
-
SWARM_SCRIPT_TMPDIR: tmpdir,
|
|
352
|
-
SWARM_SCRIPT_ARGS_FILE: argsFile,
|
|
353
|
-
SWARM_SCRIPT_SOURCE_FILE: sourceFile,
|
|
354
|
-
SWARM_SCRIPT_RESULT_FILE: resultFile,
|
|
355
|
-
SWARM_SCRIPT_ERROR_FILE: errorFile,
|
|
356
|
-
SWARM_SCRIPT_STARTED_FILE: startedFile,
|
|
357
|
-
...(input.hostValidatedArgs ? { SWARM_SCRIPT_HOST_VALIDATED_ARGS: "1" } : {}),
|
|
358
|
-
};
|
|
530
|
+
const child = proc ?? spawnHarness(spec, tmpdir);
|
|
531
|
+
proc = child;
|
|
532
|
+
// Load the next run's harness while this one runs.
|
|
533
|
+
void startWarmHarness(specKey, spec);
|
|
359
534
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
// On POSIX, Bun.spawn only needs PATH itself to locate the `sh`
|
|
363
|
-
// binary for argv[0] — the sandboxed command's `env -i` prelude is
|
|
364
|
-
// what actually scrubs the child's environment down to `harnessEnv`
|
|
365
|
-
// above. On win32 there is no such prelude, so `sandboxSpawnEnv`
|
|
366
|
-
// passes `harnessEnv` through directly instead — see
|
|
367
|
-
// `buildSandboxedCommand`'s win32 doc comment.
|
|
368
|
-
env: sandboxSpawnEnv(harnessEnv),
|
|
369
|
-
cwd: tmpdir,
|
|
370
|
-
detached: detachedProcessGroup,
|
|
371
|
-
stdin: "pipe",
|
|
372
|
-
stdout: "pipe",
|
|
373
|
-
stderr: "pipe",
|
|
374
|
-
}),
|
|
375
|
-
);
|
|
376
|
-
|
|
377
|
-
proc.stdin.write(JSON.stringify(input.configPayload));
|
|
378
|
-
proc.stdin.end();
|
|
535
|
+
child.stdin.write(JSON.stringify(input.configPayload));
|
|
536
|
+
child.stdin.end();
|
|
379
537
|
|
|
380
538
|
const [stdout, stderr, exitCode] = await Promise.all([
|
|
381
|
-
readStreamCapped(
|
|
382
|
-
readStreamCapped(
|
|
383
|
-
|
|
539
|
+
readStreamCapped(child.stdout, input.resources.maxStdoutBytes),
|
|
540
|
+
readStreamCapped(child.stderr, input.resources.maxStdoutBytes),
|
|
541
|
+
child.exited.catch(() => (timedOut ? 124 : 1)),
|
|
384
542
|
]).finally(() => clearTimeout(timeout));
|
|
385
543
|
// The child owns the run dir: read its files only through the checked reader.
|
|
386
544
|
const runDirCheck: RunDirFileCheck = {
|
|
@@ -35,7 +35,8 @@ function methodNames(
|
|
|
35
35
|
function headers(config: SwarmConfig): Record<string, string> {
|
|
36
36
|
return {
|
|
37
37
|
Authorization: `Bearer ${Redacted.value(config.apiKey)}`,
|
|
38
|
-
|
|
38
|
+
// A user-scoped run has no agent; its user token must not name one.
|
|
39
|
+
...(Redacted.value(config.agentId) ? { "X-Agent-ID": Redacted.value(config.agentId) } : {}),
|
|
39
40
|
// Audit-only header: X-Source-Task-Id would also rescope kv, parent send-task, etc.
|
|
40
41
|
...(config.auditSourceTaskId
|
|
41
42
|
? { "X-Audit-Source-Task-Id": Redacted.value(config.auditSourceTaskId) }
|
|
@@ -23,7 +23,8 @@ type BridgeRequest = {
|
|
|
23
23
|
function headers(config: SwarmConfig): Record<string, string> {
|
|
24
24
|
return {
|
|
25
25
|
Authorization: `Bearer ${Redacted.value(config.apiKey)}`,
|
|
26
|
-
|
|
26
|
+
// A user-scoped run has no agent; its user token must not name one.
|
|
27
|
+
...(Redacted.value(config.agentId) ? { "X-Agent-ID": Redacted.value(config.agentId) } : {}),
|
|
27
28
|
// Per-boot identity of the invoking worker process (system context, not
|
|
28
29
|
// script input) — work-acquisition endpoints gate on it in multi-runtime
|
|
29
30
|
// mode.
|