@tangle-network/sandbox 0.54.2 → 0.55.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.
@@ -1,7 +1,7 @@
1
- import { E as backendTypeSchema, _ as parseSSEStream, g as encodeTextForWire, h as encodePromptForWire, p as SANDBOX_PROXY_REQUEST_MAX_BYTES, v as applyRequestedModel, x as normalizeRuntimeBackendConfig, y as assertCurrentBackendType } from "./runtime-api-BARzSO0x.js";
1
+ import { C as normalizeRuntimeBackendConfig, O as backendTypeSchema, _ as encodePromptForWire, b as applyRequestedModel, h as SANDBOX_PROXY_REQUEST_MAX_BYTES, v as encodeTextForWire, x as assertCurrentBackendType, y as parseSSEStream } from "./runtime-api-DoZsOiOR.js";
2
2
  import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, l as PartialFailureError, p as ServerError, s as NetworkError, t as AuthError } from "./errors-CmYPVl-k.js";
3
3
  import { n as combineAbortSignals } from "./abort-signal-si1WMfJb.js";
4
- import { D as normalizeSandboxShape, E as normalizeConnection, N as exportTraceBundle, O as LinesClient, b as requestInteractiveSessionToken, i as normalizeStartupDiagnostics, j as rewrapResponse, n as createSandboxInstanceFromResponse, r as normalizeSandboxCreateReceipt } from "./sandbox-CaLpJBSf.js";
4
+ import { D as normalizeSandboxShape, E as normalizeConnection, N as exportTraceBundle, O as LinesClient, b as requestInteractiveSessionToken, i as normalizeStartupDiagnostics, j as rewrapResponse, n as createSandboxInstanceFromResponse, r as normalizeSandboxCreateReceipt } from "./sandbox-DzSE1u7d.js";
5
5
  import { agentProfileSchema } from "@tangle-network/agent-interface";
6
6
  import { z } from "zod";
7
7
  //#region src/backend-registry.ts
@@ -1175,6 +1175,133 @@ async function deleteMatchingSandboxes(client, filter, options) {
1175
1175
  sandboxes
1176
1176
  };
1177
1177
  }
1178
+ /**
1179
+ * Resident memory one agent's harness holds in a long session, per harness,
1180
+ * measured on production. Placement sizes for the long-session peak.
1181
+ *
1182
+ * - `opencode`: about 310 MiB at the first turn and 510-570 MiB RSS later
1183
+ * (2026-09-24); six agents measured 450-495 MiB each after two turns and
1184
+ * one `opencode serve` measured 508 MiB (2026-09-25). A 4 GiB sandbox that
1185
+ * held 12 agents had 4 of them OOM-killed.
1186
+ *
1187
+ * - `codex`: one `codex exec` process per turn, released when the turn ends.
1188
+ * Three concurrent turns peaked at 331 MiB together (about 110 MiB each,
1189
+ * 2026-09-25); placement doubles that for longer tool-using turns.
1190
+ *
1191
+ * A harness missing here has no production measurement: on 2026-09-25 the
1192
+ * Claude Code, Hermes, Pi, Kimi Code and OpenClaw harnesses failed before
1193
+ * their first model call, so none held memory to measure. `auto` placement
1194
+ * gives such an agent a sandbox of its own rather than guess.
1195
+ */
1196
+ const HARNESS_MEMORY_MB = {
1197
+ opencode: 570,
1198
+ codex: 256
1199
+ };
1200
+ /**
1201
+ * The runtime materializes a profile's skills, instructions and config into
1202
+ * the sandbox's shared home by harness, and every session in a sandbox shares
1203
+ * that directory (measured 2026-09-25: two OpenCode agents with different
1204
+ * skills in one sandbox both read the same `~/.opencode/skills`, and one
1205
+ * answered with the other's skill). Harnesses in one family write the same
1206
+ * files: codex, pi, kimi-code, prime and openclaw all read `AGENTS.md`.
1207
+ */
1208
+ function materializationFamily(harness) {
1209
+ switch (harness) {
1210
+ case "claude-code":
1211
+ case "nanoclaw": return "claude";
1212
+ case "codex":
1213
+ case "pi":
1214
+ case "kimi-code":
1215
+ case "prime":
1216
+ case "openclaw": return "agents-md";
1217
+ default: return harness;
1218
+ }
1219
+ }
1220
+ /** Stable JSON: object keys sorted, so equal profiles give equal keys. */
1221
+ function canonicalProfileKey(identity) {
1222
+ return JSON.stringify(identity, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : entry);
1223
+ }
1224
+ /**
1225
+ * Assign agents to machines in order. A dedicated agent gets a machine of its
1226
+ * own. Under `auto`, shared agents fill a machine while the measured memory of
1227
+ * their harnesses fits, so agents of different harnesses can share; an agent
1228
+ * whose harness has no measurement is placed alone. Under
1229
+ * `{ agentsPerSandbox }`, shared agents fill machines by count. Under every
1230
+ * mode, two agents of one materialization family share a sandbox only when
1231
+ * their profiles are identical, so no agent reads another agent's skills.
1232
+ */
1233
+ function placeAgents(agents, placement, memoryMB) {
1234
+ assertMemory(memoryMB);
1235
+ const perSandbox = resolveAgentsPerSandbox(placement);
1236
+ const budgetMb = memoryMB - 180;
1237
+ const machines = [];
1238
+ const nextMachineId = () => `m-${machines.length}`;
1239
+ const open = [];
1240
+ for (const agent of agents) {
1241
+ const agentMb = placement === "auto" ? HARNESS_MEMORY_MB[agent.harness] : void 0;
1242
+ if (agent.placement === "dedicated" || perSandbox === 1 || placement === "auto" && agentMb === void 0) {
1243
+ machines.push({
1244
+ machineId: nextMachineId(),
1245
+ agentIds: [agent.agentId]
1246
+ });
1247
+ continue;
1248
+ }
1249
+ const family = materializationFamily(agent.harness);
1250
+ const fits = (candidate) => {
1251
+ const held = candidate.families.get(family);
1252
+ if (held !== void 0 && held !== agent.profileKey) return false;
1253
+ return perSandbox !== void 0 ? candidate.machine.agentIds.length < perSandbox : candidate.usedMb + (agentMb ?? 0) <= budgetMb;
1254
+ };
1255
+ let target = open.find(fits);
1256
+ if (!target) {
1257
+ target = {
1258
+ machine: {
1259
+ machineId: nextMachineId(),
1260
+ agentIds: []
1261
+ },
1262
+ usedMb: 0,
1263
+ families: /* @__PURE__ */ new Map()
1264
+ };
1265
+ open.push(target);
1266
+ machines.push(target.machine);
1267
+ }
1268
+ target.machine.agentIds.push(agent.agentId);
1269
+ target.usedMb += agentMb ?? 0;
1270
+ target.families.set(family, agent.profileKey);
1271
+ }
1272
+ return machines;
1273
+ }
1274
+ /** A count for `{ agentsPerSandbox }`, 1 for dedicated, undefined for memory packing. */
1275
+ function resolveAgentsPerSandbox(placement) {
1276
+ if (placement === "dedicated") return 1;
1277
+ if (placement === "auto") return void 0;
1278
+ const count = placement.agentsPerSandbox;
1279
+ if (!Number.isSafeInteger(count) || count < 1) throw new ValidationError("placement.agentsPerSandbox must be a positive integer", { "placement.agentsPerSandbox": "invalid" });
1280
+ return count;
1281
+ }
1282
+ function assertMemory(memoryMB) {
1283
+ if (!Number.isFinite(memoryMB) || memoryMB <= 0) throw new ValidationError("Sandbox memoryMB must be a positive number", { memoryMB: "invalid" });
1284
+ }
1285
+ /** Expand `agents: N` or an agent list into specs with ids and placement set. */
1286
+ function normalizeAgentSpecs(agents) {
1287
+ const specs = typeof agents === "number" ? Array.from({ length: assertAgentCount(agents) }, () => ({})) : [...agents];
1288
+ if (specs.length === 0) throw new ValidationError("A fleet needs at least one agent", { agents: "empty" });
1289
+ const seen = /* @__PURE__ */ new Set();
1290
+ return specs.map((spec, index) => {
1291
+ const agentId = spec.agentId ?? `agent-${index}`;
1292
+ if (seen.has(agentId)) throw new ValidationError(`Duplicate agentId '${agentId}'`, { agentId: "duplicate" });
1293
+ seen.add(agentId);
1294
+ return {
1295
+ ...spec,
1296
+ agentId,
1297
+ placement: spec.placement ?? "shared"
1298
+ };
1299
+ });
1300
+ }
1301
+ function assertAgentCount(count) {
1302
+ if (!Number.isSafeInteger(count) || count < 1) throw new ValidationError("agents must be a positive integer", { agents: "invalid" });
1303
+ return count;
1304
+ }
1178
1305
  //#endregion
1179
1306
  //#region src/fleet.ts
1180
1307
  const FLEET_ID_META = "tangle.fleet.id";
@@ -1185,11 +1312,28 @@ const WORKSPACE_MODE_META = "tangle.fleet.workspace.mode";
1185
1312
  const WORKSPACE_ID_META = "tangle.fleet.workspace.id";
1186
1313
  const WORKSPACE_QUOTA_META = "tangle.fleet.workspace.quota_mb";
1187
1314
  const WORKSPACE_MOUNT_META = "tangle.fleet.workspace.mount_path";
1315
+ /** Comma-separated ids of the agents a machine hosts. */
1316
+ const AGENTS_META = "tangle.fleet.agents";
1317
+ /**
1318
+ * JSON of the per-agent specs a machine hosts (harness, model, resolved
1319
+ * profile, runtime attachments, task), so any process that lists the fleet
1320
+ * runs each agent with its own profile. A saved profile is stored resolved,
1321
+ * with its catalog id and revision, so a later catalog edit does not change
1322
+ * a running fleet.
1323
+ */
1324
+ const AGENT_SPECS_META = "tangle.fleet.agent_specs";
1325
+ /** Model the fleet's agents run by default; prices their spend. */
1326
+ const MODEL_META = "tangle.fleet.model";
1327
+ /** Id of the budgeted Platform key a capped fleet's sandboxes charge. */
1328
+ const KEY_ID_META = "tangle.fleet.key_id";
1188
1329
  const RESERVED_METADATA_PREFIX = "tangle.";
1189
1330
  const DEFAULT_MACHINE_LIFETIME_SECONDS = 3600;
1190
- const DEFAULT_MAX_CONCURRENT_CREATES = 4;
1191
- const MAX_CONCURRENT_ARTIFACT_READS = 8;
1331
+ const DEFAULT_MAX_CONCURRENT_CREATES = 8;
1192
1332
  const MAX_CONCURRENT_DRIVE_TURNS = 4;
1333
+ const DELETE_RETRY_DELAYS_MS = [1e3, 3e3];
1334
+ const FLEET_KEY_GRACE_MS = 3600 * 1e3;
1335
+ const MAX_CONCURRENT_ARTIFACT_READS = 8;
1336
+ const COLD_STARTS_PER_SANDBOX = 3;
1193
1337
  const DEFAULT_ARTIFACT_ROOT = "/workspace";
1194
1338
  const DEFAULT_MAX_ARTIFACT_BYTES = 10 * 1024 * 1024;
1195
1339
  const MAX_MACHINE_ID_LENGTH = 64;
@@ -1399,10 +1543,62 @@ function promptDispatchBody(message, options) {
1399
1543
  };
1400
1544
  }
1401
1545
  var SandboxFleet = class {
1402
- constructor(client, fleetId, machines) {
1546
+ boxes = /* @__PURE__ */ new Map();
1547
+ activeRuns = /* @__PURE__ */ new Set();
1548
+ warmAgents = /* @__PURE__ */ new Set();
1549
+ coldStarts = /* @__PURE__ */ new Map();
1550
+ constructor(client, fleetId, machines, record = {}) {
1403
1551
  this.client = client;
1404
1552
  this.fleetId = fleetId;
1405
1553
  this.machines = machines;
1554
+ this.record = record;
1555
+ }
1556
+ get policy() {
1557
+ return this.record.policy;
1558
+ }
1559
+ get parent() {
1560
+ return this.record.parent;
1561
+ }
1562
+ /** Id of the Platform key the fleet's sandboxes charge; set when the fleet has a cap. */
1563
+ get keyId() {
1564
+ return this.record.keyId;
1565
+ }
1566
+ /** Every agent of the fleet, in machine order. */
1567
+ get agents() {
1568
+ const agents = [];
1569
+ for (const [machineId, info] of this.machines) {
1570
+ const specs = getAgentSpecs(info);
1571
+ for (const agentId of getAgentIds(info)) {
1572
+ const spec = specs[agentId];
1573
+ agents.push({
1574
+ agentId,
1575
+ machineId,
1576
+ sandboxId: info.id,
1577
+ sessionId: agentId,
1578
+ ...spec?.harness ? { harness: spec.harness } : {},
1579
+ ...spec?.model?.model ? { model: spec.model.model } : {},
1580
+ ...spec?.profile?.name ? { profileName: spec.profile.name } : {}
1581
+ });
1582
+ }
1583
+ }
1584
+ return agents;
1585
+ }
1586
+ agent(agentId) {
1587
+ const agent = this.agents.find((candidate) => candidate.agentId === agentId);
1588
+ if (!agent) throw new ValidationError(`Unknown fleet agent '${agentId}'`);
1589
+ return agent;
1590
+ }
1591
+ agentSpecs() {
1592
+ const specs = {};
1593
+ for (const info of this.machines.values()) Object.assign(specs, getAgentSpecs(info));
1594
+ return specs;
1595
+ }
1596
+ /** The model of agents that set none: the fleet's `defaults.backend.model`. */
1597
+ get model() {
1598
+ for (const info of this.machines.values()) {
1599
+ const model = info.metadata?.[MODEL_META];
1600
+ if (typeof model === "string" && model.length > 0) return model;
1601
+ }
1406
1602
  }
1407
1603
  get ids() {
1408
1604
  return [...this.machines.keys()];
@@ -1413,21 +1609,13 @@ var SandboxFleet = class {
1413
1609
  return machine;
1414
1610
  }
1415
1611
  sandbox(machineId) {
1416
- return this.requireSandbox(machineId);
1612
+ return this.sandboxFor(machineId);
1417
1613
  }
1418
1614
  async collectArtifacts(artifacts) {
1419
- const sandboxes = /* @__PURE__ */ new Map();
1420
- const sandboxFor = (machineId) => {
1421
- const existing = sandboxes.get(machineId);
1422
- if (existing) return existing;
1423
- const pending = this.requireSandbox(machineId);
1424
- sandboxes.set(machineId, pending);
1425
- return pending;
1426
- };
1427
1615
  return mapConcurrent(artifacts, Math.min(MAX_CONCURRENT_ARTIFACT_READS, artifacts.length || 1), async (artifact) => {
1428
1616
  assertArtifactPath(artifact.path);
1429
1617
  const machine = this.get(artifact.machineId);
1430
- const content = await (await sandboxFor(artifact.machineId)).read(artifact.path);
1618
+ const content = await (await this.sandboxFor(artifact.machineId)).read(artifact.path);
1431
1619
  assertArtifactSize(content, artifact);
1432
1620
  return {
1433
1621
  ...artifact,
@@ -1459,7 +1647,13 @@ var SandboxFleet = class {
1459
1647
  }
1460
1648
  return await response.json();
1461
1649
  }
1650
+ /**
1651
+ * Run one prompt on one machine's default agent through the API's fleet
1652
+ * dispatch. For agent fleets, `run()` and `runAll()` run each agent in its
1653
+ * own session through the sandbox runtime path.
1654
+ */
1462
1655
  async prompt(machineId, message, options) {
1656
+ if (this.keyId) return (await this.sandboxFor(machineId)).prompt(message, options);
1463
1657
  const [result] = await this.dispatchPrompt(message, {
1464
1658
  ...options,
1465
1659
  machines: [machineId]
@@ -1472,6 +1666,7 @@ var SandboxFleet = class {
1472
1666
  return (await this.dispatchPromptDetailed(message, options)).results;
1473
1667
  }
1474
1668
  async dispatchPromptDetailed(message, options) {
1669
+ this.assertUnbudgetedDispatch();
1475
1670
  const response = await this.client.fetch(`/v1/fleets/${this.fleetId}/dispatch`, {
1476
1671
  method: "POST",
1477
1672
  body: JSON.stringify(promptDispatchBody(message, options))
@@ -1483,39 +1678,228 @@ var SandboxFleet = class {
1483
1678
  return await response.json();
1484
1679
  }
1485
1680
  /**
1486
- * Drive one settle → poll → dispatch pass across N machines at once — the
1487
- * fleet counterpart of `box.driveTurn()` for tick-based callers (Workflows
1488
- * steps, queue consumers, crons) that re-invoke on their own schedule. One
1681
+ * Run one turn on each selected agent, all at once, and yield each agent's
1682
+ * start and result as they happen. Every turn goes through the same
1683
+ * per-sandbox runtime path as `box.prompt()`: the managed model
1684
+ * credential, access audit, metering and trace id all apply per agent.
1685
+ *
1686
+ * A fleet created with `budgetUsd` drives every turn with its budgeted
1687
+ * key, so the Platform refuses each charge past the budget; such a turn
1688
+ * ends `budget_exhausted`. Turns already running are not aborted: each is
1689
+ * refused at its own next charge.
1690
+ */
1691
+ async *run(message, options = {}) {
1692
+ const startedAt = Date.now();
1693
+ const targets = options.agents ? options.agents.map((agentId) => this.agent(agentId)) : this.agents;
1694
+ if (targets.length === 0) throw new ValidationError("Fleet run selected no agents", { agents: "empty" });
1695
+ const specs = this.agentSpecs();
1696
+ const messageFor = (agent) => {
1697
+ const resolved = (typeof message === "function" ? message(agent) : message) ?? specs[agent.agentId]?.task;
1698
+ if (resolved === void 0) throw new ValidationError(`Fleet agent '${agent.agentId}' has no task and the run passed no message`, { message: "required" });
1699
+ return resolved;
1700
+ };
1701
+ const messages = new Map(targets.map((agent) => [agent.agentId, messageFor(agent)]));
1702
+ const controller = new AbortController();
1703
+ const onCallerAbort = () => controller.abort();
1704
+ options.signal?.addEventListener("abort", onCallerAbort, { once: true });
1705
+ if (options.signal?.aborted) controller.abort();
1706
+ this.activeRuns.add(controller);
1707
+ let budgetExhausted = false;
1708
+ const queue = new EventQueue();
1709
+ const results = /* @__PURE__ */ new Map();
1710
+ const runAgent = async (agent) => {
1711
+ const agentStartedAt = Date.now();
1712
+ const finish = (result) => {
1713
+ const finished = {
1714
+ ...agent,
1715
+ ...result,
1716
+ durationMs: Date.now() - agentStartedAt
1717
+ };
1718
+ results.set(agent.agentId, finished);
1719
+ queue.push({
1720
+ type: "agent.finished",
1721
+ result: finished
1722
+ });
1723
+ };
1724
+ if (budgetExhausted || controller.signal.aborted) {
1725
+ finish({ status: budgetExhausted ? "budget_exhausted" : "cancelled" });
1726
+ return;
1727
+ }
1728
+ const traceId = mintFleetTraceId();
1729
+ queue.push({
1730
+ type: "agent.started",
1731
+ ...agent,
1732
+ traceId
1733
+ });
1734
+ const gate = !this.warmAgents.has(agent.agentId) ? this.coldStartGate(agent.machineId) : void 0;
1735
+ let holdsGate = false;
1736
+ try {
1737
+ const box = await this.sandboxFor(agent.machineId);
1738
+ if (gate) {
1739
+ await gate.acquire(controller.signal);
1740
+ holdsGate = true;
1741
+ }
1742
+ if (budgetExhausted) {
1743
+ finish({ status: "budget_exhausted" });
1744
+ return;
1745
+ }
1746
+ const backend = agentBackend(specs[agent.agentId]);
1747
+ const result = await box.prompt(messages.get(agent.agentId) ?? "", {
1748
+ sessionId: agent.sessionId,
1749
+ traceId,
1750
+ ...backend ? { backend } : {},
1751
+ timeoutMs: options.timeoutMs,
1752
+ context: options.context,
1753
+ signal: controller.signal
1754
+ });
1755
+ if (result.success) this.warmAgents.add(agent.agentId);
1756
+ const refused = !result.success && isBudgetRefusal(result.error);
1757
+ if (refused) budgetExhausted = true;
1758
+ finish({
1759
+ status: result.success ? "completed" : refused ? "budget_exhausted" : controller.signal.aborted ? "cancelled" : "failed",
1760
+ result,
1761
+ ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : {},
1762
+ ...result.error ? { error: result.error } : {}
1763
+ });
1764
+ } catch (error) {
1765
+ const message = error instanceof Error ? error.message : String(error);
1766
+ const refused = isBudgetRefusal(message);
1767
+ if (refused) budgetExhausted = true;
1768
+ finish({
1769
+ status: refused ? "budget_exhausted" : controller.signal.aborted ? "cancelled" : "failed",
1770
+ error: message
1771
+ });
1772
+ } finally {
1773
+ if (holdsGate) gate?.release();
1774
+ }
1775
+ };
1776
+ Promise.all(targets.map(runAgent)).finally(() => queue.close());
1777
+ try {
1778
+ for await (const event of queue) yield event;
1779
+ } finally {
1780
+ controller.abort();
1781
+ this.activeRuns.delete(controller);
1782
+ options.signal?.removeEventListener("abort", onCallerAbort);
1783
+ }
1784
+ const ordered = targets.flatMap((agent) => {
1785
+ const result = results.get(agent.agentId);
1786
+ return result ? [result] : [];
1787
+ });
1788
+ let spend;
1789
+ let spendError;
1790
+ if (this.keyId) try {
1791
+ spend = await this.spend();
1792
+ } catch (error) {
1793
+ spendError = error instanceof Error ? error.message : String(error);
1794
+ }
1795
+ yield {
1796
+ type: "fleet.finished",
1797
+ results: ordered,
1798
+ ...spend ? { spend } : {},
1799
+ ...spendError ? { spendError } : {},
1800
+ durationMs: Date.now() - startedAt
1801
+ };
1802
+ }
1803
+ /** Run one turn on each selected agent and return every agent's result. */
1804
+ async runAll(message, options = {}) {
1805
+ for await (const event of this.run(message, options)) if (event.type === "fleet.finished") return event.results;
1806
+ throw new Error("Fleet run ended without a result");
1807
+ }
1808
+ /**
1809
+ * Stop the fleet's work: abort the runs this handle started, interrupt every
1810
+ * agent's session on its sandbox (so turns started by another process stop
1811
+ * too), and cancel every child fleet. One unreachable sandbox or child does
1812
+ * not stop the rest; each failure is reported. Sandboxes keep running;
1813
+ * `delete()` removes them.
1814
+ */
1815
+ async cancel() {
1816
+ for (const controller of this.activeRuns) controller.abort();
1817
+ const failures = [];
1818
+ const interrupts = await Promise.allSettled(this.agents.map(async (agent) => {
1819
+ return (await (await this.sandboxFor(agent.machineId, { control: true })).session(agent.sessionId).interrupt()).cancelled;
1820
+ }));
1821
+ for (const outcome of interrupts) if (outcome.status === "rejected") failures.push(outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason));
1822
+ let children = [];
1823
+ try {
1824
+ children = await this.children();
1825
+ } catch (error) {
1826
+ failures.push(`listing child fleets: ${error instanceof Error ? error.message : String(error)}`);
1827
+ }
1828
+ const cancels = await Promise.allSettled(children.map((child) => child.cancel()));
1829
+ for (const outcome of cancels) if (outcome.status === "rejected") failures.push(outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason));
1830
+ else failures.push(...outcome.value.failures);
1831
+ return {
1832
+ interrupted: interrupts.filter((outcome) => outcome.status === "fulfilled" && outcome.value).length,
1833
+ children: children.length,
1834
+ failures
1835
+ };
1836
+ }
1837
+ /** Fleets whose `parent.fleetId` is this fleet. */
1838
+ children() {
1839
+ return this.client.fleets.children(this.fleetId);
1840
+ }
1841
+ /**
1842
+ * The fleet's spend as the Platform metered it on the fleet's budgeted key:
1843
+ * every router call and compute charge of its sandboxes, from any process.
1844
+ * Only a capped fleet has a key; an uncapped fleet has nothing to meter.
1845
+ */
1846
+ async spend() {
1847
+ if (!this.keyId) throw new ValidationError(`Fleet ${this.fleetId} has no spend cap, so it has no metered key`, { policy: "uncapped" });
1848
+ return this.client.fleets.keySpend(this.keyId);
1849
+ }
1850
+ /**
1851
+ * Drive one settle → poll → dispatch pass across agents — the fleet
1852
+ * counterpart of `box.driveTurn()` for tick-based callers (Workflows steps,
1853
+ * queue consumers, crons) that re-invoke on their own schedule. One
1489
1854
  * invocation never loops, never sleeps, and never holds a connection: each
1490
- * machine gets exactly one pass, and a per-machine failure is captured in
1491
- * that machine's outcome instead of failing the batch, so the caller
1492
- * re-drives survivors on its next tick and only escalates the errors.
1855
+ * agent gets exactly one pass in its own session, and a per-agent failure is
1856
+ * captured in that agent's outcome instead of failing the batch. At most
1857
+ * `concurrency` passes run at once, and an agent's first turn waits on the
1858
+ * same per-sandbox cold-start limit as `run()`.
1493
1859
  */
1494
1860
  async driveTurns(turns, options) {
1495
1861
  const concurrency = options?.concurrency ?? MAX_CONCURRENT_DRIVE_TURNS;
1496
1862
  if (!Number.isInteger(concurrency) || concurrency <= 0) throw new ValidationError("driveTurns concurrency must be a positive integer");
1497
- const sandboxes = /* @__PURE__ */ new Map();
1498
- const sandboxFor = (machineId) => {
1499
- const existing = sandboxes.get(machineId);
1500
- if (existing) return existing;
1501
- const pending = this.requireSandbox(machineId);
1502
- sandboxes.set(machineId, pending);
1503
- return pending;
1504
- };
1863
+ const specs = this.agentSpecs();
1864
+ const never = new AbortController().signal;
1505
1865
  return mapConcurrent(turns, Math.min(concurrency, turns.length || 1), async (turn) => {
1866
+ const key = "agentId" in turn ? { agentId: turn.agentId } : { machineId: turn.machineId };
1867
+ let gate;
1506
1868
  try {
1507
- const result = await (await sandboxFor(turn.machineId)).driveTurn(turn.message, turn.options);
1869
+ if ("machineId" in turn) {
1870
+ const result = await (await this.sandboxFor(turn.machineId)).driveTurn(turn.message, turn.options);
1871
+ return {
1872
+ ...key,
1873
+ outcome: "driven",
1874
+ result
1875
+ };
1876
+ }
1877
+ const agent = this.agent(turn.agentId);
1878
+ const box = await this.sandboxFor(agent.machineId);
1879
+ if (!this.warmAgents.has(agent.agentId)) {
1880
+ gate = this.coldStartGate(agent.machineId);
1881
+ await gate.acquire(never);
1882
+ }
1883
+ const backend = agentBackend(specs[agent.agentId]);
1884
+ const result = await box.driveTurn(turn.message, {
1885
+ ...turn.options,
1886
+ sessionId: agent.sessionId,
1887
+ ...backend && turn.options.backend === void 0 ? { backend } : {}
1888
+ });
1889
+ this.warmAgents.add(agent.agentId);
1508
1890
  return {
1509
- machineId: turn.machineId,
1891
+ ...key,
1510
1892
  outcome: "driven",
1511
1893
  result
1512
1894
  };
1513
1895
  } catch (error) {
1514
1896
  return {
1515
- machineId: turn.machineId,
1897
+ ...key,
1516
1898
  outcome: "error",
1517
1899
  error: error instanceof Error ? error.message : String(error)
1518
1900
  };
1901
+ } finally {
1902
+ gate?.release();
1519
1903
  }
1520
1904
  });
1521
1905
  }
@@ -1547,22 +1931,23 @@ var SandboxFleet = class {
1547
1931
  return this.client.fleets.dispatchExecStream(this.fleetId, command, options);
1548
1932
  }
1549
1933
  dispatchPromptStream(message, options) {
1934
+ this.assertUnbudgetedDispatch();
1550
1935
  return this.client.fleets.dispatchPromptStream(this.fleetId, message, options);
1551
1936
  }
1937
+ /**
1938
+ * Delete the fleet with its child fleets. The API deprovisions children
1939
+ * first, then this fleet's sandboxes, and keeps a fleet's record while any
1940
+ * machine of it or its descendants remains, so nothing is left billing
1941
+ * without an owner. A failed delete is retried; after the tree is gone the
1942
+ * fleet's budgeted key is revoked. Revoking returns only unspent budget: a
1943
+ * child's spend stays counted against its parent.
1944
+ */
1552
1945
  async delete(options) {
1553
- const errors = [];
1554
- await Promise.all([...this.machines.values()].map(async (machine) => {
1555
- const box = await this.client.get(machine.id);
1556
- if (!box) return;
1557
- try {
1558
- await box.delete();
1559
- } catch (err) {
1560
- errors.push(err instanceof Error ? err : new Error(String(err)));
1561
- }
1562
- }));
1563
- await this.client.fleets.deleteRecord(this.fleetId);
1564
- if (errors.length > 0) {
1565
- if (!options?.continueOnError) throw errors[0];
1946
+ try {
1947
+ await this.client.fleets.deleteTree(this.fleetId, [...this.machines.values()]);
1948
+ if (this.keyId) await this.client.fleets.revokeKey(this.keyId);
1949
+ } catch (error) {
1950
+ if (!options?.continueOnError) throw error;
1566
1951
  }
1567
1952
  }
1568
1953
  async usage() {
@@ -1616,17 +2001,175 @@ var SandboxFleet = class {
1616
2001
  async createToken(options) {
1617
2002
  return this.client.fleets.createToken(this.fleetId, options);
1618
2003
  }
1619
- async requireSandbox(machineId) {
2004
+ /**
2005
+ * The API's prompt dispatch bills the calling key, so a budgeted fleet
2006
+ * refuses it: its turns run through `run()`, `runAll()` or `prompt()`.
2007
+ */
2008
+ assertUnbudgetedDispatch() {
2009
+ if (this.keyId) throw new ValidationError(`Fleet ${this.fleetId} has a budget; prompt dispatch would bill outside it. Use run(), runAll() or prompt(machineId, …)`, { fleet: "budgeted" });
2010
+ }
2011
+ /** @internal */
2012
+ coldStartGate(machineId) {
2013
+ let gate = this.coldStarts.get(machineId);
2014
+ if (!gate) {
2015
+ gate = new Semaphore(COLD_STARTS_PER_SANDBOX);
2016
+ this.coldStarts.set(machineId, gate);
2017
+ }
2018
+ return gate;
2019
+ }
2020
+ sandboxFor(machineId, options) {
1620
2021
  const machine = this.get(machineId);
1621
- const box = await this.client.get(machine.id);
1622
- if (!box) throw new ValidationError(`Fleet machine '${machineId}' no longer exists`, { machineId: "not_found" });
1623
- return box;
2022
+ if (options?.control) return this.client.get(machine.id).then((box) => {
2023
+ if (!box) throw new ValidationError(`Fleet machine '${machineId}' no longer exists`, { machineId: "not_found" });
2024
+ return box;
2025
+ });
2026
+ const cached = this.boxes.get(machineId);
2027
+ if (cached) return cached;
2028
+ const pending = (this.keyId ? this.client.fleets.hostFor(this.fleetId) : this.client).get(machine.id).then((box) => {
2029
+ if (!box) throw new ValidationError(`Fleet machine '${machineId}' no longer exists`, { machineId: "not_found" });
2030
+ return box;
2031
+ });
2032
+ pending.catch(() => this.boxes.delete(machineId));
2033
+ this.boxes.set(machineId, pending);
2034
+ return pending;
1624
2035
  }
1625
2036
  };
1626
2037
  var SandboxFleetClient = class {
2038
+ /**
2039
+ * Budgeted keys of the capped fleets this client created, by fleet id. A
2040
+ * key's secret exists only here; a child fleet under a capped parent is
2041
+ * minted with the parent's key, so it must be created by this client.
2042
+ */
2043
+ fleetKeys = /* @__PURE__ */ new Map();
1627
2044
  constructor(client) {
1628
2045
  this.client = client;
1629
2046
  }
2047
+ /** Mint the key a capped fleet's sandboxes charge, under `issuerKey`. */
2048
+ async mintFleetKey(fleetId, capUsd, lifetimeSeconds, issuerKey) {
2049
+ const response = await this.client.platformFetch("/v1/keys", {
2050
+ method: "POST",
2051
+ headers: {
2052
+ "content-type": "application/json",
2053
+ ...issuerKey ? { Authorization: `Bearer ${issuerKey}` } : {}
2054
+ },
2055
+ body: JSON.stringify({
2056
+ name: `fleet-${fleetId}`,
2057
+ product: "sandbox",
2058
+ budgetUsd: capUsd,
2059
+ expiresAt: new Date(Date.now() + lifetimeSeconds * 1e3 + FLEET_KEY_GRACE_MS).toISOString()
2060
+ })
2061
+ });
2062
+ const body = await response.text();
2063
+ if (!response.ok) throw parseErrorResponse(response.status, body, void 0, response.headers);
2064
+ const data = JSON.parse(body);
2065
+ if (!data.data?.id || !data.data.key) throw new ValidationError("Platform minted a fleet key without an id", { key: "invalid" });
2066
+ return {
2067
+ id: data.data.id,
2068
+ key: data.data.key
2069
+ };
2070
+ }
2071
+ /**
2072
+ * @internal The host that authenticates as a capped fleet's budgeted key.
2073
+ * Only the client that created the fleet holds the key; any other caller
2074
+ * would spend outside the cap, so it is refused.
2075
+ */
2076
+ hostFor(fleetId) {
2077
+ const key = this.fleetKeys.get(fleetId);
2078
+ if (!key) throw new ValidationError(`Fleet ${fleetId} is capped; drive its agents from the client that created it, so every charge counts against the cap`, { fleet: "key_unavailable" });
2079
+ return this.client.withApiKey(key.key);
2080
+ }
2081
+ /** The budgeted key id a fleet's sandboxes carry, read from one of them. */
2082
+ async budgetKeyIdOf(fleet) {
2083
+ for (const machine of fleet?.machines ?? []) {
2084
+ const box = await this.client.get(machine.sandboxId);
2085
+ const keyId = box?.toJSON().metadata?.[KEY_ID_META];
2086
+ if (typeof keyId === "string") return keyId;
2087
+ if (box) return void 0;
2088
+ }
2089
+ }
2090
+ /** @internal Revoke a fleet's budgeted key; an absent key is already revoked. */
2091
+ async revokeKey(keyId) {
2092
+ const response = await this.client.platformFetch(`/v1/keys/${encodeURIComponent(keyId)}`, { method: "DELETE" });
2093
+ if (!response.ok && response.status !== 404) {
2094
+ const body = await response.text();
2095
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
2096
+ }
2097
+ }
2098
+ /** @internal Read a fleet key's metered spend from the Platform. */
2099
+ async keySpend(keyId) {
2100
+ const response = await this.client.platformFetch(`/v1/keys/${encodeURIComponent(keyId)}`);
2101
+ const body = await response.text();
2102
+ if (!response.ok) throw parseErrorResponse(response.status, body, void 0, response.headers);
2103
+ const key = JSON.parse(body).data;
2104
+ const capUsd = Number(key?.budgetUsd);
2105
+ const spentUsd = Number(key?.budgetSpent);
2106
+ const reservedForChildrenUsd = Number(key?.budgetReserved ?? 0);
2107
+ if (![
2108
+ capUsd,
2109
+ spentUsd,
2110
+ reservedForChildrenUsd
2111
+ ].every(Number.isFinite)) throw new ValidationError(`Platform key ${keyId} returned no readable budget`, { key: "invalid" });
2112
+ return {
2113
+ capUsd,
2114
+ spentUsd,
2115
+ reservedForChildrenUsd,
2116
+ remainingUsd: Math.max(0, capUsd - spentUsd - reservedForChildrenUsd)
2117
+ };
2118
+ }
2119
+ /**
2120
+ * @internal Delete a fleet and its children through the API, retrying a
2121
+ * transient failure. A fleet with no server record is deleted machine by
2122
+ * machine from the caller's handle.
2123
+ */
2124
+ async deleteTree(fleetId, machines) {
2125
+ assertSafeId(fleetId, "fleetId");
2126
+ const descendantKeys = await this.descendantKeyIds(fleetId).catch(() => []);
2127
+ await this.deleteTreeOnce(fleetId, machines);
2128
+ for (const keyId of descendantKeys) await this.revokeKey(keyId).catch(() => void 0);
2129
+ }
2130
+ async descendantKeyIds(fleetId) {
2131
+ const response = await this.client.fetch("/v1/fleets");
2132
+ if (!response.ok) return [];
2133
+ const fleets = (await response.json()).fleets ?? [];
2134
+ const keyIds = [];
2135
+ const visit = async (parentId) => {
2136
+ for (const child of fleets.filter((f) => f.parent?.fleetId === parentId)) {
2137
+ const keyId = await this.budgetKeyIdOf(child);
2138
+ if (keyId) keyIds.push(keyId);
2139
+ await visit(child.id);
2140
+ }
2141
+ };
2142
+ await visit(fleetId);
2143
+ return keyIds;
2144
+ }
2145
+ async deleteTreeOnce(fleetId, machines) {
2146
+ for (let attempt = 0;; attempt += 1) {
2147
+ const response = await this.client.fetch(`/v1/fleets/${fleetId}`, { method: "DELETE" });
2148
+ if (response.ok) {
2149
+ if ((await response.json().catch(() => ({}))).success !== false) break;
2150
+ }
2151
+ if (response.status === 404) {
2152
+ await this.deleteMachines(machines);
2153
+ return;
2154
+ }
2155
+ if (!(response.status >= 500 || response.status === 429) || attempt >= DELETE_RETRY_DELAYS_MS.length) {
2156
+ const body = await response.text().catch(() => "");
2157
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
2158
+ }
2159
+ await new Promise((resolve) => setTimeout(resolve, DELETE_RETRY_DELAYS_MS[attempt]));
2160
+ }
2161
+ }
2162
+ async deleteMachines(machines) {
2163
+ const failures = [];
2164
+ await mapConcurrent(machines, DEFAULT_MAX_CONCURRENT_CREATES, async (machine) => {
2165
+ try {
2166
+ await (await this.client.get(machine.id))?.delete();
2167
+ } catch (error) {
2168
+ failures.push(error);
2169
+ }
2170
+ });
2171
+ if (failures.length > 0) throw failures[0];
2172
+ }
1630
2173
  async capabilities() {
1631
2174
  const response = await this.client.fetch("/v1/fleets/capabilities");
1632
2175
  if (!response.ok) {
@@ -1673,11 +2216,24 @@ var SandboxFleetClient = class {
1673
2216
  }
1674
2217
  return (await response.json()).estimate;
1675
2218
  }
1676
- async create(options) {
1677
- const fleetId = options.fleetId ?? createFleetId();
2219
+ async create(input) {
2220
+ const fleetId = input.fleetId ?? createFleetId();
1678
2221
  assertSafeId(fleetId, "fleetId");
1679
- if (options.machines.length === 0) throw new ValidationError("Fleet create requires at least one machine");
1680
- assertUniqueMachineIds(options.machines);
2222
+ const { machines, agentIdsByMachine, agentSpecs } = await this.resolveFleetMachines(input);
2223
+ if (input.parent) {
2224
+ assertSafeId(input.parent.fleetId, "parent.fleetId");
2225
+ assertSafeId(input.parent.agentId, "parent.agentId");
2226
+ }
2227
+ if (input.budgetUsd !== void 0 && (!Number.isFinite(input.budgetUsd) || input.budgetUsd <= 0)) throw new ValidationError("budgetUsd must be a positive number", { budgetUsd: "invalid" });
2228
+ const options = {
2229
+ ...input,
2230
+ machines,
2231
+ ...input.budgetUsd !== void 0 ? { policy: {
2232
+ ...input.policy,
2233
+ maxSpendUsd: Math.min(input.policy?.maxSpendUsd ?? input.budgetUsd, input.budgetUsd)
2234
+ } } : {}
2235
+ };
2236
+ assertUniqueMachineIds(machines);
1681
2237
  assertNoReservedMetadata(options.metadata, "Fleet");
1682
2238
  for (const machine of options.machines) assertNoReservedMetadata(machine.metadata, `Fleet machine '${machine.machineId}'`);
1683
2239
  assertPolicy(options.machines, options.defaults, options.policy);
@@ -1692,34 +2248,140 @@ var SandboxFleetClient = class {
1692
2248
  });
1693
2249
  if (estimate.estimatedMaxLifetimeUsd > options.policy.maxSpendUsd) throw new ValidationError(`Fleet estimated max lifetime cost $${estimate.estimatedMaxLifetimeUsd} exceeds policy.maxSpendUsd $${options.policy.maxSpendUsd}`, { "policy.maxSpendUsd": "exceeded" });
1694
2250
  }
2251
+ let fleetKey;
2252
+ const capUsd = options.budgetUsd;
2253
+ const parentKey = options.parent ? this.fleetKeys.get(options.parent.fleetId) : void 0;
2254
+ if (options.parent && !parentKey) {
2255
+ const parentFleet = await this.getServerFleet(options.parent.fleetId);
2256
+ if (await this.budgetKeyIdOf(parentFleet) !== void 0) throw new ValidationError(`Parent fleet ${options.parent.fleetId} has a budget; create its child fleets with the client that created it`, { parent: "key_unavailable" });
2257
+ }
2258
+ if (parentKey && capUsd === void 0) throw new ValidationError(`Parent fleet ${options.parent?.fleetId} has a budget, so its child fleets must set budgetUsd`, { budgetUsd: "required" });
2259
+ if (capUsd !== void 0) fleetKey = await this.mintFleetKey(fleetId, capUsd, Math.max(...machines.map((machine) => mergeCreateOptions(options.defaults, machine).maxLifetimeSeconds ?? DEFAULT_MACHINE_LIFETIME_SECONDS)), parentKey?.key);
2260
+ const host = fleetKey ? this.client.withApiKey(fleetKey.key) : this.client;
2261
+ const releaseKey = async () => {
2262
+ if (fleetKey) await this.revokeKey(fleetKey.id).catch(() => void 0);
2263
+ };
1695
2264
  const created = [];
1696
2265
  try {
1697
- for (let i = 0; i < options.machines.length; i += maxConcurrentCreates) {
1698
- const batch = options.machines.slice(i, i + maxConcurrentCreates);
1699
- const results = await Promise.allSettled(batch.map((machine) => this.createMachine(fleetId, machine, options)));
1700
- const rejected = results.find((result) => result.status === "rejected");
1701
- for (const result of results) if (result.status === "fulfilled") created.push(result.value);
1702
- if (rejected) throw rejected.reason;
1703
- }
2266
+ let failure;
2267
+ await mapConcurrent(machines, maxConcurrentCreates, async (machine) => {
2268
+ if (failure) return;
2269
+ try {
2270
+ created.push(await this.createMachine(host, fleetId, machine, options, agentIdsByMachine.get(machine.machineId), agentSpecs, fleetKey?.id));
2271
+ } catch (reason) {
2272
+ failure ??= { reason };
2273
+ }
2274
+ });
2275
+ if (failure) throw failure.reason;
2276
+ const order = new Map(machines.map((m, index) => [m.machineId, index]));
2277
+ created.sort((a, b) => (order.get(a.machineId) ?? 0) - (order.get(b.machineId) ?? 0));
1704
2278
  } catch (err) {
1705
- if (options.cleanupOnFailure !== false) await Promise.allSettled(created.map(async (machine) => {
1706
- await (await this.client.get(machine.sandbox.id))?.delete();
1707
- }));
2279
+ if (options.cleanupOnFailure !== false) {
2280
+ await Promise.allSettled(created.map(async (machine) => {
2281
+ await (await this.client.get(machine.sandbox.id))?.delete();
2282
+ }));
2283
+ await releaseKey();
2284
+ }
1708
2285
  throw err;
1709
2286
  }
2287
+ let record;
1710
2288
  try {
1711
- await this.persistFleet(fleetId, created, options);
2289
+ record = await this.persistFleet(host, fleetId, created, options);
2290
+ const recorded = new Set((record?.machines ?? []).map((machine) => machine.sandboxId));
2291
+ if (record?.machines !== void 0 && created.some((machine) => !recorded.has(machine.sandbox.id))) throw new ValidationError(`Fleet ${fleetId} already exists from an earlier create with the same idempotency key; load it with fleets.list({ fleetId })`, { fleetId: "exists" });
1712
2292
  } catch (err) {
1713
- if (options.cleanupOnFailure !== false) await Promise.allSettled(created.map(async (machine) => {
1714
- await (await this.client.get(machine.sandbox.id))?.delete();
1715
- }));
2293
+ if (options.cleanupOnFailure !== false) {
2294
+ await Promise.allSettled(created.map(async (machine) => {
2295
+ await (await this.client.get(machine.sandbox.id))?.delete();
2296
+ }));
2297
+ await releaseKey();
2298
+ }
1716
2299
  throw err;
1717
2300
  }
2301
+ if (fleetKey) this.fleetKeys.set(fleetId, fleetKey);
1718
2302
  return this.fromInfo({
1719
2303
  fleetId,
1720
- machines: created
2304
+ machines: created,
2305
+ policy: record?.policy ?? options.policy,
2306
+ parent: record?.parent ?? options.parent,
2307
+ createdAt: record?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2308
+ ...fleetKey ? { keyId: fleetKey.id } : {}
1721
2309
  });
1722
2310
  }
2311
+ /**
2312
+ * Turn `agents`/`placement` into machine specs, or pass explicit machines
2313
+ * through. Each agent's harness, model and profile resolve from its spec,
2314
+ * then its profile, then `defaults.backend`; saved profiles are fetched from
2315
+ * the Platform catalog here, before any sandbox exists.
2316
+ */
2317
+ async resolveFleetMachines(options) {
2318
+ if (options.agents !== void 0 && options.machines !== void 0) throw new ValidationError("Set either machines or agents, not both", { agents: "conflicts_with_machines" });
2319
+ if (options.agents === void 0) {
2320
+ const machines = options.machines ?? [];
2321
+ if (machines.length === 0) throw new ValidationError("Fleet create requires machines or agents");
2322
+ return {
2323
+ machines,
2324
+ agentIdsByMachine: /* @__PURE__ */ new Map(),
2325
+ agentSpecs: /* @__PURE__ */ new Map()
2326
+ };
2327
+ }
2328
+ const agents = normalizeAgentSpecs(options.agents);
2329
+ const saved = /* @__PURE__ */ new Map();
2330
+ const agentSpecs = /* @__PURE__ */ new Map();
2331
+ const fallback = options.defaults?.backend;
2332
+ for (const agent of agents) {
2333
+ assertSafeId(agent.agentId, "agentId");
2334
+ let profile;
2335
+ let profileRef;
2336
+ if (isProfileRef(agent.profile)) {
2337
+ profileRef = agent.profile;
2338
+ const key = `${profileRef.profileId}@${profileRef.revision ?? ""}`;
2339
+ if (!saved.has(key)) saved.set(key, this.savedProfile(profileRef));
2340
+ profile = await saved.get(key);
2341
+ } else profile = agent.profile;
2342
+ const own = agent.harness !== void 0 || agent.model !== void 0 || agent.profile !== void 0 || agent.runtimeAttachments !== void 0;
2343
+ const harness = agent.harness ?? profile?.harness ?? (own ? fallback?.type : void 0);
2344
+ const requested = typeof agent.model === "string" ? { model: agent.model } : agent.model && withoutModelSecrets(agent.model, agent.agentId);
2345
+ const profileModel = profile?.model?.default;
2346
+ const model = requested ?? (profileModel ? { model: profileModel } : void 0) ?? (own && fallback?.model ? withoutModelSecrets(fallback.model) : void 0);
2347
+ profile ??= own ? fallback?.profile : void 0;
2348
+ agentSpecs.set(agent.agentId, {
2349
+ ...harness ? { harness } : {},
2350
+ ...model ? { model } : {},
2351
+ ...profile ? { profile } : {},
2352
+ ...profileRef ? { profileRef } : {},
2353
+ ...agent.runtimeAttachments ? { runtimeAttachments: agent.runtimeAttachments } : {},
2354
+ ...agent.task !== void 0 ? { task: agent.task } : {}
2355
+ });
2356
+ }
2357
+ const placed = placeAgents(agents.map((agent) => ({
2358
+ agentId: agent.agentId,
2359
+ placement: agent.placement,
2360
+ harness: agentSpecs.get(agent.agentId)?.harness ?? fallback?.type ?? "opencode",
2361
+ profileKey: canonicalProfileKey({
2362
+ profile: agentSpecs.get(agent.agentId)?.profile,
2363
+ runtimeAttachments: agentSpecs.get(agent.agentId)?.runtimeAttachments
2364
+ })
2365
+ })), options.placement ?? "auto", options.defaults?.resources?.memoryMB ?? 2048);
2366
+ return {
2367
+ machines: placed.map(({ machineId }) => ({ machineId })),
2368
+ agentIdsByMachine: new Map(placed.map(({ machineId, agentIds }) => [machineId, agentIds])),
2369
+ agentSpecs
2370
+ };
2371
+ }
2372
+ /** Read a saved profile's definition from the Platform catalog. */
2373
+ async savedProfile(ref) {
2374
+ const response = await this.client.platformFetch(`/v1/agent-profiles/${encodeURIComponent(ref.profileId)}`);
2375
+ if (!response.ok) {
2376
+ const body = await response.text();
2377
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
2378
+ }
2379
+ const data = await response.json();
2380
+ const definition = data.data?.definition;
2381
+ if (!definition) throw new ValidationError(`Saved profile '${ref.profileId}' returned no definition`, { profile: "invalid" });
2382
+ if (ref.revision !== void 0 && data.data?.revision !== ref.revision) throw new ValidationError(`Saved profile '${ref.profileId}' is at revision ${data.data?.revision ?? "unknown"}, not ${ref.revision}`, { profile: "revision_mismatch" });
2383
+ return definition;
2384
+ }
1723
2385
  async createWithCoordinator(options) {
1724
2386
  const { coordinator: coordinatorOptions, workers, ...createOptions } = options;
1725
2387
  const coordinator = {
@@ -1735,9 +2397,14 @@ var SandboxFleetClient = class {
1735
2397
  }))]
1736
2398
  });
1737
2399
  }
1738
- async createMachine(fleetId, machine, options) {
2400
+ async createMachine(host, fleetId, machine, options, agentIds, agentSpecs, keyId) {
1739
2401
  const merged = mergeCreateOptions(options.defaults, machine);
1740
- const sandbox = await this.client.create({
2402
+ const model = merged.backend?.model?.model;
2403
+ const hosted = Object.fromEntries((agentIds ?? []).flatMap((agentId) => {
2404
+ const spec = agentSpecs.get(agentId);
2405
+ return spec && Object.keys(spec).length > 0 ? [[agentId, spec]] : [];
2406
+ }));
2407
+ const sandbox = await host.create({
1741
2408
  ...merged,
1742
2409
  name: machine.name ?? `${fleetId}-${machine.machineId}`,
1743
2410
  maxLifetimeSeconds: merged.maxLifetimeSeconds ?? DEFAULT_MACHINE_LIFETIME_SECONDS,
@@ -1748,7 +2415,11 @@ var SandboxFleetClient = class {
1748
2415
  [MACHINE_ID_META]: machine.machineId,
1749
2416
  [MACHINE_ROLE_META]: machine.role ?? "worker",
1750
2417
  [FLEET_CREATED_BY_META]: "@tangle-network/sandbox",
1751
- ...workspaceMetadata(options.workspace)
2418
+ ...workspaceMetadata(options.workspace),
2419
+ ...agentIds ? { [AGENTS_META]: agentIds.join(",") } : {},
2420
+ ...Object.keys(hosted).length > 0 ? { [AGENT_SPECS_META]: JSON.stringify(hosted) } : {},
2421
+ ...model ? { [MODEL_META]: model } : {},
2422
+ ...keyId ? { [KEY_ID_META]: keyId } : {}
1752
2423
  }
1753
2424
  });
1754
2425
  return {
@@ -1764,18 +2435,38 @@ var SandboxFleetClient = class {
1764
2435
  return this.listBySandboxMetadata(options);
1765
2436
  }
1766
2437
  async delete(fleetId, options) {
1767
- await (await this.list({
1768
- ...options,
1769
- fleetId
1770
- })).delete({ continueOnError: options?.continueOnError });
2438
+ try {
2439
+ const serverFleet = await this.getServerFleet(fleetId);
2440
+ const keyId = await this.budgetKeyIdOf(serverFleet).catch(() => void 0);
2441
+ const fallback = serverFleet === null ? (await this.listBySandboxMetadata({
2442
+ ...options,
2443
+ fleetId
2444
+ })).machines : /* @__PURE__ */ new Map();
2445
+ await this.deleteTree(fleetId, [...fallback.values()]);
2446
+ if (keyId) await this.revokeKey(keyId);
2447
+ } catch (error) {
2448
+ if (!options?.continueOnError) throw error;
2449
+ }
1771
2450
  }
1772
2451
  fromInfo(info) {
1773
2452
  const machines = /* @__PURE__ */ new Map();
1774
2453
  for (const machine of info.machines) machines.set(machine.machineId, machine.sandbox);
1775
- return new SandboxFleet(this.client, info.fleetId, machines);
2454
+ const { fleetId, machines: _machines, ...record } = info;
2455
+ return new SandboxFleet(this.client, fleetId, machines, record);
1776
2456
  }
1777
- async persistFleet(fleetId, machines, options) {
1778
- const response = await this.client.fetch("/v1/fleets", {
2457
+ /** Fleets spawned by `fleetId`, from the API's `parent` lineage. */
2458
+ async children(fleetId) {
2459
+ assertSafeId(fleetId, "fleetId");
2460
+ const response = await this.client.fetch("/v1/fleets");
2461
+ if (!response.ok) {
2462
+ const body = await response.text();
2463
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
2464
+ }
2465
+ const children = ((await response.json()).fleets ?? []).filter((fleet) => fleet.parent?.fleetId === fleetId);
2466
+ return Promise.all(children.map(async (fleet) => this.fromInfo(await this.hydrateServerFleet(fleet, { fleetId: fleet.id }))));
2467
+ }
2468
+ async persistFleet(host, fleetId, machines, options) {
2469
+ const response = await host.fetch("/v1/fleets", {
1779
2470
  method: "POST",
1780
2471
  headers: { "Idempotency-Key": options.idempotencyKey ?? fleetId },
1781
2472
  body: JSON.stringify({
@@ -1786,6 +2477,7 @@ var SandboxFleetClient = class {
1786
2477
  },
1787
2478
  workspace: options.workspace,
1788
2479
  policy: options.policy,
2480
+ ...options.parent ? { parent: options.parent } : {},
1789
2481
  resources: calculateResourceTotals(options.machines, options.defaults),
1790
2482
  maxConcurrentCreates: options.maxConcurrentCreates,
1791
2483
  machines: machines.map((machine) => ({
@@ -1801,6 +2493,7 @@ var SandboxFleetClient = class {
1801
2493
  const body = await response.text();
1802
2494
  throw parseErrorResponse(response.status, body, void 0, response.headers);
1803
2495
  }
2496
+ return (await response.json()).fleet;
1804
2497
  }
1805
2498
  async getServerFleet(fleetId) {
1806
2499
  const response = await this.client.fetch(`/v1/fleets/${fleetId}`);
@@ -2020,9 +2713,14 @@ var SandboxFleetClient = class {
2020
2713
  };
2021
2714
  }));
2022
2715
  const filtered = options.status ? machines.filter((machine) => machine.sandbox.status === options.status) : machines;
2716
+ const keyId = filtered.map((machine) => machine.sandbox.metadata?.[KEY_ID_META]).find((value) => typeof value === "string");
2023
2717
  return {
2024
2718
  fleetId: fleet.id,
2025
- machines: filtered
2719
+ machines: filtered,
2720
+ policy: fleet.policy,
2721
+ parent: fleet.parent,
2722
+ createdAt: fleet.createdAt,
2723
+ ...typeof keyId === "string" ? { keyId } : {}
2026
2724
  };
2027
2725
  }
2028
2726
  async listBySandboxMetadata(options) {
@@ -2034,9 +2732,11 @@ var SandboxFleetClient = class {
2034
2732
  role: getMachineRole(info)
2035
2733
  }] : [];
2036
2734
  });
2735
+ const keyId = machines.map((machine) => machine.sandbox.metadata?.[KEY_ID_META]).find((value) => typeof value === "string");
2037
2736
  return this.fromInfo({
2038
2737
  fleetId: options.fleetId,
2039
- machines
2738
+ machines,
2739
+ ...typeof keyId === "string" ? { keyId } : {}
2040
2740
  });
2041
2741
  }
2042
2742
  };
@@ -2080,6 +2780,120 @@ function getMachineRole(info) {
2080
2780
  const value = info.metadata?.[MACHINE_ROLE_META];
2081
2781
  return value === "coordinator" || value === "worker" ? value : void 0;
2082
2782
  }
2783
+ function getAgentIds(info) {
2784
+ const value = info.metadata?.[AGENTS_META];
2785
+ return typeof value === "string" && value.length > 0 ? value.split(",") : [];
2786
+ }
2787
+ function getAgentSpecs(info) {
2788
+ const value = info.metadata?.[AGENT_SPECS_META];
2789
+ if (typeof value !== "string" || value.length === 0) return {};
2790
+ try {
2791
+ return JSON.parse(value);
2792
+ } catch {
2793
+ throw new ValidationError(`Fleet sandbox ${info.id} has unreadable agent specs`, { metadata: "invalid" });
2794
+ }
2795
+ }
2796
+ /** The per-turn backend for an agent: only what its spec sets. */
2797
+ function agentBackend(spec) {
2798
+ if (!spec) return void 0;
2799
+ const backend = {
2800
+ ...spec.harness ? { type: spec.harness } : {},
2801
+ ...spec.model ? { model: spec.model } : {},
2802
+ ...spec.profile ? { profile: spec.profile } : {},
2803
+ ...spec.runtimeAttachments ? { runtimeAttachments: spec.runtimeAttachments } : {}
2804
+ };
2805
+ return Object.keys(backend).length > 0 ? backend : void 0;
2806
+ }
2807
+ /**
2808
+ * Agent specs are stored in sandbox metadata, which is not a secret store. An
2809
+ * agent's own model config may not carry a key (name one with `apiKeyEnv`);
2810
+ * a key inherited from `defaults` stays on the sandbox's create-time backend.
2811
+ */
2812
+ function withoutModelSecrets(model, agentId) {
2813
+ const { apiKey, authFiles, ...rest } = model;
2814
+ if (agentId !== void 0 && (apiKey !== void 0 || authFiles !== void 0)) throw new ValidationError(`Fleet agent '${agentId}' model carries a secret; name the sandbox env var that holds it with apiKeyEnv`, { model: "secret" });
2815
+ return rest;
2816
+ }
2817
+ function isProfileRef(profile) {
2818
+ return profile !== void 0 && typeof profile.profileId === "string";
2819
+ }
2820
+ /** A trace id in the platform's accepted form, one per agent turn. */
2821
+ function mintFleetTraceId() {
2822
+ const crypto = globalThis.crypto;
2823
+ if (!crypto?.randomUUID) throw new ValidationError("Fleet trace ids require global crypto");
2824
+ return `ptid_${crypto.randomUUID()}`;
2825
+ }
2826
+ /** Single-consumer queue that turns concurrent pushes into an async iterator. */
2827
+ var EventQueue = class {
2828
+ items = [];
2829
+ waiter;
2830
+ closed = false;
2831
+ push(item) {
2832
+ this.items.push(item);
2833
+ this.wake();
2834
+ }
2835
+ close() {
2836
+ this.closed = true;
2837
+ this.wake();
2838
+ }
2839
+ wake() {
2840
+ const waiter = this.waiter;
2841
+ this.waiter = void 0;
2842
+ waiter?.();
2843
+ }
2844
+ async *[Symbol.asyncIterator]() {
2845
+ while (true) {
2846
+ const item = this.items.shift();
2847
+ if (item !== void 0) {
2848
+ yield item;
2849
+ continue;
2850
+ }
2851
+ if (this.closed) return;
2852
+ await new Promise((resolve) => {
2853
+ this.waiter = resolve;
2854
+ });
2855
+ }
2856
+ }
2857
+ };
2858
+ /** Counting semaphore whose waiters leave the queue when their signal aborts. */
2859
+ var Semaphore = class {
2860
+ waiters = [];
2861
+ constructor(available) {
2862
+ this.available = available;
2863
+ }
2864
+ async acquire(signal) {
2865
+ signal.throwIfAborted();
2866
+ if (this.available > 0) {
2867
+ this.available -= 1;
2868
+ return;
2869
+ }
2870
+ await new Promise((resolve, reject) => {
2871
+ const onAbort = () => {
2872
+ const index = this.waiters.indexOf(grant);
2873
+ if (index >= 0) this.waiters.splice(index, 1);
2874
+ reject(signal.reason);
2875
+ };
2876
+ const grant = () => {
2877
+ signal.removeEventListener("abort", onAbort);
2878
+ resolve();
2879
+ };
2880
+ this.waiters.push(grant);
2881
+ signal.addEventListener("abort", onAbort, { once: true });
2882
+ });
2883
+ }
2884
+ release() {
2885
+ const next = this.waiters.shift();
2886
+ if (next) next();
2887
+ else this.available += 1;
2888
+ }
2889
+ };
2890
+ /**
2891
+ * A turn the Platform refused for a spent budget: the router answers 402 and
2892
+ * the key verify refuses with KEY_BUDGET_EXHAUSTED; harnesses surface either.
2893
+ */
2894
+ function isBudgetRefusal(message) {
2895
+ return message !== void 0 && /KEY_BUDGET_EXHAUSTED|budget[_ ]exhausted|APIError 402|status(?: code)? 402|402 Payment Required/i.test(message);
2896
+ }
2083
2897
  //#endregion
2084
2898
  //#region src/instances.ts
2085
2899
  /**
@@ -3014,8 +3828,11 @@ async function hydrateLocalCliBackendAuth(backend, baseUrl, trustLocalCliAuth) {
3014
3828
  * await box.delete();
3015
3829
  * ```
3016
3830
  */
3017
- var Sandbox = class {
3831
+ const DEFAULT_PLATFORM_URL = "https://id.tangle.tools";
3832
+ const PRODUCTION_BASE_URL = "https://sandbox.tangle.tools";
3833
+ var Sandbox = class Sandbox {
3018
3834
  baseUrl;
3835
+ platformUrl;
3019
3836
  apiKey;
3020
3837
  timeoutMs;
3021
3838
  trustLocalCliAuth;
@@ -3029,6 +3846,8 @@ var Sandbox = class {
3029
3846
  if (!config.apiKey) throw new AuthError("API key is required");
3030
3847
  if (!config.baseUrl) throw new ValidationError("Base URL is required");
3031
3848
  this.baseUrl = config.baseUrl.replace(/\/$/, "");
3849
+ const platformUrl = config.platformUrl ?? (this.baseUrl === PRODUCTION_BASE_URL ? DEFAULT_PLATFORM_URL : void 0);
3850
+ this.platformUrl = platformUrl?.replace(/\/+$/, "");
3032
3851
  this.apiKey = config.apiKey;
3033
3852
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3034
3853
  this.trustLocalCliAuth = config.trustLocalCliAuth === true;
@@ -3069,6 +3888,27 @@ var Sandbox = class {
3069
3888
  getApiKey() {
3070
3889
  return this.apiKey;
3071
3890
  }
3891
+ /** A client with this one's settings that authenticates with `apiKey`. */
3892
+ withApiKey(apiKey) {
3893
+ return new Sandbox({
3894
+ apiKey,
3895
+ baseUrl: this.baseUrl,
3896
+ platformUrl: this.platformUrl,
3897
+ timeoutMs: this.timeoutMs,
3898
+ trustLocalCliAuth: this.trustLocalCliAuth
3899
+ });
3900
+ }
3901
+ /** Fetch a Platform API path (e.g. the agent-profile catalog) with this key. */
3902
+ async platformFetch(path, options) {
3903
+ if (!this.platformUrl) throw new ValidationError("platformUrl is required for Platform calls when baseUrl is not https://sandbox.tangle.tools", { platformUrl: "required" });
3904
+ const headers = new Headers(options?.headers);
3905
+ if (!headers.has("Authorization")) headers.set("Authorization", `Bearer ${this.apiKey}`);
3906
+ return fetch(`${this.platformUrl}${path}`, {
3907
+ ...options,
3908
+ headers,
3909
+ signal: options?.signal ?? AbortSignal.timeout(this.timeoutMs)
3910
+ });
3911
+ }
3072
3912
  /**
3073
3913
  * Access the secrets manager for storing and retrieving encrypted secrets.
3074
3914
  *