@sandboxrouter/sdk 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +4 -3
  2. package/dist/agent-bench.d.ts +39 -0
  3. package/dist/agent-bench.js +150 -0
  4. package/dist/bench-store.js +11 -2
  5. package/dist/bench.d.ts +22 -0
  6. package/dist/bench.js +59 -7
  7. package/dist/burst.d.ts +81 -0
  8. package/dist/burst.js +183 -0
  9. package/dist/catalog.d.ts +32 -0
  10. package/dist/catalog.js +58 -15
  11. package/dist/check.d.ts +2 -0
  12. package/dist/check.js +8 -0
  13. package/dist/cli.js +217 -5
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/leaderboard.d.ts +107 -2
  17. package/dist/leaderboard.js +175 -5
  18. package/dist/ledger.d.ts +2 -0
  19. package/dist/ledger.js +12 -1
  20. package/dist/price-index.d.ts +54 -0
  21. package/dist/price-index.js +50 -0
  22. package/dist/providers/beam.js +4 -0
  23. package/dist/providers/blaxel.js +4 -0
  24. package/dist/providers/boat.js +3 -1
  25. package/dist/providers/daytona.js +4 -0
  26. package/dist/providers/deno.js +4 -0
  27. package/dist/providers/e2b.d.ts +2 -0
  28. package/dist/providers/e2b.js +4 -0
  29. package/dist/providers/hopx.js +4 -0
  30. package/dist/providers/langsmith.js +4 -0
  31. package/dist/providers/modal.js +11 -2
  32. package/dist/providers/morph.js +4 -0
  33. package/dist/providers/runloop.js +4 -0
  34. package/dist/providers/sprites.js +4 -0
  35. package/dist/providers/tensorlake.js +4 -0
  36. package/dist/providers/vercel.js +4 -0
  37. package/dist/published.d.ts +2 -0
  38. package/dist/published.js +2087 -0
  39. package/dist/recommend.d.ts +117 -0
  40. package/dist/recommend.js +103 -0
  41. package/dist/results.js +81 -1
  42. package/dist/router.d.ts +50 -0
  43. package/dist/router.js +83 -10
  44. package/dist/submit.d.ts +6 -0
  45. package/dist/submit.js +70 -0
  46. package/dist/task.d.ts +80 -0
  47. package/dist/task.js +173 -0
  48. package/dist/types.d.ts +12 -0
  49. package/dist/util.d.ts +2 -0
  50. package/dist/util.js +2 -0
  51. package/dist/validate.d.ts +1 -1
  52. package/dist/validate.js +4 -1
  53. package/package.json +1 -1
package/README.md CHANGED
@@ -30,9 +30,10 @@ Site and docs: [sandboxrouter.ai](https://sandboxrouter.ai) · npm: [`@sandboxro
30
30
  AI agents need a disposable computer to run code a model wrote: install packages, run tests, do an RL rollout. Dozens of providers sell one, each with its own SDK and auth, and the same 2 vCPU / 4 GB sandbox costs from under a cent to over thirty cents an hour. sandboxRouter is one interface over all of them:
31
31
 
32
32
  - **Same code everywhere.** `create`, `exec` (streamed), `writeFile`, `readFile`, `pause`, `kill`. Switch providers by changing which keys are set.
33
+ - **The provider's own SDK is still there.** `sbx.native` is the provider's own sandbox object (an E2B `Sandbox`, a Daytona `Sandbox`, a Modal `Sandbox`, ...), already connected, for ports, background processes, snapshots and anything else the router doesn't cover. See [Using a provider's own features](https://sandboxrouter.ai/docs#native).
33
34
  - **Cheapest real cost, then speed, with fallback.** A `maxHourlyUsd` price cap and `quote()` to see where a sandbox would land and what the run costs before starting it. Or `cheapest` for strictly lowest cost for the run, `fastest` by start times, `verified` for tested providers first, or a list of providers you name. `requireVerified` limits a router to providers that passed the real-account check.
34
35
  - **Errors you can act on.** Every failure has a `code` (`no_provider`, `setup`, `all_failed`, `timeout`, ...), an HTTP status, and the list of providers tried.
35
- - **Your keys.** Your accounts and your bills; nothing is proxied through anyone else.
36
+ - **Your keys, or one hosted key.** With your own provider keys, sandboxes run on your accounts and nothing passes through anyone else. The optional hosted key (api.sandboxrouter.ai) runs them on sandboxRouter's provider accounts instead, so its requests go through that server; see [Security](https://www.sandboxrouter.ai/security).
36
37
  - **Cleanup.** A local ledger of every sandbox started, so `sandboxrouter gc` kills what a crashed script left behind.
37
38
  - **TypeScript, Python, HTTP and a CLI.** Plus desktops and phones for computer-use models.
38
39
 
@@ -61,7 +62,7 @@ List price while running, 2 vCPU / 4 GB, cheapest first; waitlisted sign-ups fol
61
62
  | [Upstash Box](https://sandboxrouter.ai/providers/upstash) | up to $0.200 | none | not run yet | [pricing](https://upstash.com/pricing/box) |
62
63
  | [Cloudflare Sandbox](https://sandboxrouter.ai/providers/cloudflare) | up to $0.216 | $5/mo | passed (2026-11-13) | [pricing](https://developers.cloudflare.com/containers/platform/pricing/) |
63
64
  | [Amazon Bedrock AgentCore Code Interpreter](https://sandboxrouter.ai/providers/agentcore) | up to $0.217 | none | passed (2026-11-13) | [pricing](https://aws.amazon.com/bedrock/agentcore/pricing/) |
64
- | [Modal](https://sandboxrouter.ai/providers/modal) | up to $0.238 | none | passed (2026-11-13) | [pricing](https://modal.com/pricing) |
65
+ | [Modal](https://sandboxrouter.ai/providers/modal) | $0.238 | none | passed (2026-11-13) | [pricing](https://modal.com/pricing) |
65
66
  | [AWS Lambda MicroVMs](https://sandboxrouter.ai/providers/lambda) | $0.252 | none | passed (2026-11-13) | [pricing](https://aws.amazon.com/lambda/pricing/) |
66
67
  | [Deno Sandbox](https://sandboxrouter.ai/providers/deno) | up to $0.300 | $20/mo | not run yet | [pricing](https://deno.com/sandbox) |
67
68
  | [Runloop](https://sandboxrouter.ai/providers/runloop) | $0.317 | none | not run yet | [pricing](https://www.runloop.ai/pricing) |
@@ -77,7 +78,7 @@ List price while running, 2 vCPU / 4 GB, cheapest first; waitlisted sign-ups fol
77
78
  | [E2B](https://sandboxrouter.ai/providers/e2b) | skipped (default image is 2 vCPU / 0.5 GB; a bigger size needs image.e2b) | none | passed (2026-11-13) | [pricing](https://e2b.dev/pricing) |
78
79
  | [Docker (local)](https://sandboxrouter.ai/providers/docker) | free | none | passed (2026-11-13) | [pricing](https://docs.docker.com/engine/) |
79
80
 
80
- Checked 2026-11-04 to 2026-11-13.
81
+ Checked 2026-11-04 to 2026-11-17.
81
82
 
82
83
  ## Install
83
84
 
@@ -0,0 +1,39 @@
1
+ import { Router } from "./router.js";
2
+ import type { ProviderId } from "./types.js";
3
+ /**
4
+ * A real agent in every sandbox: the same model gets the same task, with one tool that runs a shell command in
5
+ * the sandbox. The model runs here (its key never enters the sandbox), so the sandbox waits while it thinks,
6
+ * as with any real agent. Afterwards the result is checked independently inside the sandbox.
7
+ *
8
+ * Measures, per provider: how often the task was done right, wall time, time spent waiting on the model, the
9
+ * sandbox CPU used, turns, and what the sandbox was billed (start, minimum, fee, active CPU where it applies).
10
+ */
11
+ export declare const AGENT_TASK_VERSION = "gemini-primes-v1";
12
+ export declare const AGENT_TASK: string;
13
+ export interface AgentRow {
14
+ provider: ProviderId;
15
+ /** Sessions that started (the ones refused for an account limit are counted in `limited` instead). */
16
+ runs: number;
17
+ /** Sessions the provider refused to start for a limit or quota on the benchmarking account. */
18
+ limited?: number;
19
+ /** Runs where the task checked out. */
20
+ ok: number;
21
+ medianWallMs?: number;
22
+ /** Time spent waiting on the model: the sandbox sat idle. */
23
+ medianModelMs?: number;
24
+ medianCpuMs?: number;
25
+ medianTurns?: number;
26
+ /** What the sandbox was billed for one run, median. */
27
+ medianUsd?: number;
28
+ medianTokens?: number;
29
+ }
30
+ export declare function agentBench(opts: {
31
+ router?: Router;
32
+ providers: ProviderId[];
33
+ runs: number;
34
+ apiKey: string;
35
+ model: string;
36
+ maxTurns?: number;
37
+ parallel?: number;
38
+ onProgress?: (msg: string) => void;
39
+ }): Promise<AgentRow[]>;
@@ -0,0 +1,150 @@
1
+ import { BILLED_VS_LIST } from "./billing.js";
2
+ import { DEFAULT_MEMORY_GB, DEFAULT_VCPU, fittingSpec, fixedSize } from "./catalog.js";
3
+ import { median } from "./bench-store.js";
4
+ import { Router } from "./router.js";
5
+ import { busyMs, maxCoreMs, taskUsd } from "./task.js";
6
+ import { LIMITED_ERROR } from "./bench.js";
7
+ /**
8
+ * A real agent in every sandbox: the same model gets the same task, with one tool that runs a shell command in
9
+ * the sandbox. The model runs here (its key never enters the sandbox), so the sandbox waits while it thinks,
10
+ * as with any real agent. Afterwards the result is checked independently inside the sandbox.
11
+ *
12
+ * Measures, per provider: how often the task was done right, wall time, time spent waiting on the model, the
13
+ * sandbox CPU used, turns, and what the sandbox was billed (start, minimum, fee, active CPU where it applies).
14
+ */
15
+ export const AGENT_TASK_VERSION = "gemini-primes-v1";
16
+ export const AGENT_TASK = [
17
+ "You are working in a fresh Linux sandbox through a tool that runs shell commands.",
18
+ "Write /tmp/work/primes.py: it computes the first 5000 prime numbers without using the network, writes them to",
19
+ "/tmp/work/primes.txt one per line, and prints their sum. Run it and fix it until it works.",
20
+ "When it works, reply with DONE and the sum.",
21
+ ].join(" ");
22
+ /** Checked after the agent stops: the file has 5000 primes ending in 48611, and the script prints the right sum. */
23
+ const VERIFY = `test "$(wc -l < /tmp/work/primes.txt)" -eq 5000 && test "$(tail -n 1 /tmp/work/primes.txt)" = 48611 && python3 /tmp/work/primes.py | grep -q 114455259 && echo VERIFIED`;
24
+ const STAT = `grep '^cpu' /proc/stat 2> /dev/null | tr '\\n' ';'`;
25
+ async function gemini(model, apiKey, contents) {
26
+ const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, {
27
+ method: "POST",
28
+ headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
29
+ body: JSON.stringify({
30
+ contents,
31
+ tools: [
32
+ {
33
+ functionDeclarations: [
34
+ {
35
+ name: "run_shell",
36
+ description: "Run a shell command in the sandbox and get its exit code, stdout and stderr.",
37
+ parameters: { type: "OBJECT", properties: { command: { type: "STRING" } }, required: ["command"] },
38
+ },
39
+ ],
40
+ },
41
+ ],
42
+ generationConfig: { temperature: 0 },
43
+ }),
44
+ signal: AbortSignal.timeout(120_000),
45
+ });
46
+ const j = (await res.json());
47
+ if (!res.ok || j.error)
48
+ throw new Error(`gemini ${res.status}: ${j.error?.message?.slice(0, 160) ?? "no answer"}`);
49
+ return { content: j.candidates?.[0]?.content ?? { role: "model", parts: [] }, tokens: j.usageMetadata?.totalTokenCount ?? 0 };
50
+ }
51
+ /** One agent session on one provider. */
52
+ async function session(router, id, model, apiKey, maxTurns) {
53
+ const spec = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: 15, cpuUtilization: 0.1 };
54
+ const sized = { ...spec, ...fixedSize(id, spec) };
55
+ const t0 = performance.now();
56
+ const box = await router.create(sized, { provider: id, fallback: false, deadlineSeconds: 180 });
57
+ const createMs = performance.now() - t0;
58
+ try {
59
+ await box.exec("mkdir -p /tmp/work");
60
+ const a = (await box.exec(STAT)).stdout;
61
+ const s0 = performance.now();
62
+ const contents = [{ role: "user", parts: [{ text: AGENT_TASK }] }];
63
+ let modelMs = 0;
64
+ let tokens = 0;
65
+ let turns = 0;
66
+ for (; turns < maxTurns; turns++) {
67
+ const m0 = performance.now();
68
+ const { content, tokens: t } = await gemini(model, apiKey, contents);
69
+ modelMs += performance.now() - m0;
70
+ tokens += t;
71
+ contents.push({ role: "model", parts: content.parts ?? [] });
72
+ const calls = (content.parts ?? []).filter((p) => p.functionCall);
73
+ if (!calls.length)
74
+ break;
75
+ const responses = [];
76
+ for (const c of calls) {
77
+ const r = await box.exec(String(c.functionCall.args?.command ?? ""), { timeoutSeconds: 60 }).catch((err) => ({
78
+ exitCode: -1,
79
+ stdout: "",
80
+ stderr: err.message,
81
+ }));
82
+ responses.push({
83
+ functionResponse: {
84
+ name: "run_shell",
85
+ response: { exitCode: r.exitCode, stdout: r.stdout.slice(-3000), stderr: r.stderr.slice(-2000) },
86
+ },
87
+ });
88
+ }
89
+ contents.push({ role: "user", parts: responses });
90
+ }
91
+ const sessionMs = performance.now() - s0;
92
+ const b = (await box.exec(STAT)).stdout;
93
+ const verified = (await box.exec(VERIFY, { timeoutSeconds: 120 })).stdout.includes("VERIFIED");
94
+ const cpu = busyMs(a, b);
95
+ const plausible = cpu !== undefined && cpu <= sized.vcpu * sessionMs * 1.1;
96
+ return { verified, createMs, sessionMs, modelMs, turns: turns + 1, tokens, cpuMs: plausible ? cpu : undefined, coreMs: plausible ? maxCoreMs(a, b) : undefined, spec: sized };
97
+ }
98
+ finally {
99
+ await box.kill().catch(() => { });
100
+ }
101
+ }
102
+ export async function agentBench(opts) {
103
+ const router = opts.router ?? new Router();
104
+ const log = opts.onProgress ?? (() => { });
105
+ const rows = [];
106
+ const one = async (id) => {
107
+ const done = [];
108
+ let failures = 0;
109
+ let limited = 0;
110
+ for (let i = 0; i < opts.runs; i++) {
111
+ try {
112
+ const s = await session(router, id, opts.model, opts.apiKey, opts.maxTurns ?? 15);
113
+ done.push(s);
114
+ log(`${id} run ${i + 1}/${opts.runs}: ${s.verified ? "done" : "not done"} in ${(s.sessionMs / 1000).toFixed(1)} s, ${s.turns} turns`);
115
+ }
116
+ catch (err) {
117
+ failures++;
118
+ if (LIMITED_ERROR.test(err.message))
119
+ limited++;
120
+ log(`${id} run ${i + 1}/${opts.runs} failed: ${err.message.slice(0, 160)}`);
121
+ }
122
+ }
123
+ const ok = done.filter((s) => s.verified);
124
+ const size = fittingSpec(id);
125
+ const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
126
+ const usd = (s) => taskUsd(id, { ...size, cpuUtilization: 0.1 }, s.createMs, s.sessionMs, s.cpuMs, ratio, false, s.coreMs);
127
+ const m = (xs) => (xs.length ? median(xs.map(Math.round)) : undefined);
128
+ rows.push({
129
+ provider: id,
130
+ runs: opts.runs - limited,
131
+ ...(limited ? { limited } : {}),
132
+ ok: ok.length,
133
+ medianWallMs: m(done.map((s) => s.sessionMs)),
134
+ medianModelMs: m(done.map((s) => s.modelMs)),
135
+ medianCpuMs: m(done.map((s) => s.cpuMs).filter((n) => n !== undefined)),
136
+ medianTurns: m(done.map((s) => s.turns)),
137
+ ...(done.length ? { medianUsd: Math.round((median(done.map((s) => Math.round(usd(s) * 1e9))) / 1e9) * 1e9) / 1e9 } : {}),
138
+ medianTokens: m(done.map((s) => s.tokens)),
139
+ });
140
+ if (failures)
141
+ log(`${id}: ${failures} of ${opts.runs} sessions failed to start or crashed`);
142
+ };
143
+ const queue = [...opts.providers];
144
+ const lanes = Array.from({ length: Math.max(1, Math.min(opts.parallel ?? 1, queue.length)) }, async () => {
145
+ for (let id = queue.shift(); id; id = queue.shift())
146
+ await one(id);
147
+ });
148
+ await Promise.all(lanes);
149
+ return rows.sort((a, b) => b.ok - a.ok || (a.medianUsd ?? Infinity) - (b.medianUsd ?? Infinity));
150
+ }
@@ -1,13 +1,21 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  /** $SANDBOXROUTER_BENCH_FILE, else bench.json next to the ledger: $SANDBOXROUTER_HOME, else ~/.sandboxrouter/. */
5
5
  export function defaultBenchFile() {
6
6
  return process.env.SANDBOXROUTER_BENCH_FILE || join(process.env.SANDBOXROUTER_HOME || join(homedir(), ".sandboxrouter"), "bench.json");
7
7
  }
8
+ // Ranking reads the bench file on every create: keep what was read, and read again only when it changed.
9
+ const cache = new Map();
8
10
  export function loadBench(file = defaultBenchFile()) {
9
11
  try {
10
- return JSON.parse(readFileSync(file, "utf8"));
12
+ const { mtimeMs, size } = statSync(file);
13
+ const hit = cache.get(file);
14
+ if (hit && hit.mtimeMs === mtimeMs && hit.size === size)
15
+ return hit.data;
16
+ const data = JSON.parse(readFileSync(file, "utf8"));
17
+ cache.set(file, { mtimeMs, size, data });
18
+ return data;
11
19
  }
12
20
  catch {
13
21
  return {};
@@ -16,6 +24,7 @@ export function loadBench(file = defaultBenchFile()) {
16
24
  export function saveBench(data, file = defaultBenchFile()) {
17
25
  mkdirSync(dirname(file), { recursive: true });
18
26
  writeFileSync(file, JSON.stringify(data, null, 2));
27
+ cache.delete(file);
19
28
  }
20
29
  export function median(xs) {
21
30
  if (!xs || xs.length === 0)
package/dist/bench.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Router } from "./router.js";
2
+ import { type TaskKind } from "./task.js";
2
3
  import type { ProviderId, SandboxSpec } from "./types.js";
3
4
  export interface BenchRow {
4
5
  provider: ProviderId;
@@ -7,6 +8,18 @@ export interface BenchRow {
7
8
  medianCreateMs?: number;
8
9
  medianExecMs?: number;
9
10
  hourlyUsd: number;
11
+ /**
12
+ * Of the failures, how many the provider refused for a limit or quota on the benchmarking account (a rate limit,
13
+ * a concurrency or service quota): the account's plan, not the provider's reliability. Success rates leave them out.
14
+ */
15
+ limited?: number;
16
+ /** With `task`: median time of the standard task (src/task.ts), and of each of its phases. */
17
+ medianTaskMs?: number;
18
+ taskPhasesMs?: Record<string, number>;
19
+ /** With `task`: median CPU time the task used across all vCPUs, where the sandbox shows /proc/stat. */
20
+ medianTaskCpuMs?: number;
21
+ /** With `task`: median busy time of the busiest core, for providers that meter CPU per VM. */
22
+ medianTaskMaxCoreMs?: number;
10
23
  lastError?: string;
11
24
  }
12
25
  /**
@@ -21,6 +34,15 @@ export declare function bench(opts: {
21
34
  runs?: number;
22
35
  spec?: SandboxSpec;
23
36
  benchFile?: string;
37
+ /** Also run a standard task (src/task.ts) in each sandbox, to price a fixed piece of work: true or "short", "long", "python", "download". */
38
+ task?: boolean | TaskKind;
39
+ /** Providers benched at once (default 1). Each provider's own runs stay one after another. */
40
+ parallel?: number;
24
41
  onProgress?: (msg: string) => void;
25
42
  }): Promise<BenchRow[]>;
26
43
  export declare function benchMarkdown(rows: BenchRow[]): string;
44
+ /** Errors that are about the account running the benchmark, not the provider: setup problems, payment, limits. */
45
+ export declare const ACCOUNT_ERROR: RegExp;
46
+ export declare const NETWORK_ERROR: RegExp;
47
+ /** A refusal for a limit or quota on the account running the benchmark: rate limits, concurrency and service quotas. */
48
+ export declare const LIMITED_ERROR: RegExp;
package/dist/bench.js CHANGED
@@ -1,6 +1,7 @@
1
- import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost } from "./catalog.js";
1
+ import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fittingSpec, fixedSize, hourlyCost } from "./catalog.js";
2
2
  import { loadBench, median, saveBench } from "./bench-store.js";
3
3
  import { Router } from "./router.js";
4
+ import { runTask, taskMs, taskUsd, TASKS } from "./task.js";
4
5
  /**
5
6
  * Cold start = time from create() call to a usable sandbox. Exec = round trip of `echo ok`.
6
7
  * Measured from wherever you run it, so network distance to each provider counts. Every provider is
@@ -12,15 +13,25 @@ export async function bench(opts) {
12
13
  const runs = opts.runs ?? 3;
13
14
  // The CLI passes unset flags as undefined: drop them so they don't wipe the defaults.
14
15
  const given = Object.fromEntries(Object.entries(opts.spec ?? {}).filter(([, v]) => v !== undefined));
15
- const spec = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: 5, ...given };
16
+ const kind = opts.task === true ? "short" : opts.task || undefined;
17
+ // The long task can take minutes on a slow provider: give the sandbox room to finish it.
18
+ const spec = {
19
+ vcpu: DEFAULT_VCPU,
20
+ memoryGb: DEFAULT_MEMORY_GB,
21
+ timeoutMinutes: kind === "long" ? 20 : 5,
22
+ ...(kind && TASKS[kind].cpuUtilization ? { cpuUtilization: TASKS[kind].cpuUtilization } : {}),
23
+ ...given,
24
+ };
16
25
  const ids = opts.providers ?? router.registered().filter((id) => router.isConfigured(id));
17
26
  const log = opts.onProgress ?? (() => { });
18
27
  const stored = loadBench(opts.benchFile);
19
28
  const rows = [];
20
- for (const id of ids) {
29
+ const one = async (id) => {
21
30
  const createMs = [];
22
31
  const execMs = [];
32
+ const tasks = [];
23
33
  let failures = 0;
34
+ let limited = 0;
24
35
  let lastError;
25
36
  for (let i = 0; i < runs; i++) {
26
37
  log(`${id} run ${i + 1}/${runs}`);
@@ -34,10 +45,21 @@ export async function bench(opts) {
34
45
  if (r.exitCode !== 0 || r.stdout.trim() !== "ok")
35
46
  throw new Error(`echo returned ${r.exitCode}: ${r.stdout}${r.stderr}`);
36
47
  execMs.push(Math.round(performance.now() - t1));
48
+ if (kind) {
49
+ // A failed task doesn't fail the run: the start time still counts, the task just has no time.
50
+ try {
51
+ tasks.push(await runTask(box, kind));
52
+ }
53
+ catch (err) {
54
+ lastError = `task: ${err.message.slice(0, 180)}`;
55
+ }
56
+ }
37
57
  }
38
58
  catch (err) {
39
59
  failures++;
40
60
  lastError = err.message.slice(0, 200);
61
+ if (LIMITED_ERROR.test(lastError))
62
+ limited++;
41
63
  }
42
64
  finally {
43
65
  await box?.kill().catch(() => { });
@@ -51,12 +73,33 @@ export async function bench(opts) {
51
73
  medianCreateMs: median(createMs),
52
74
  medianExecMs: median(execMs),
53
75
  hourlyUsd: hourlyCost(id, sized(id, spec)),
76
+ ...(limited ? { limited } : {}),
77
+ ...(tasks.length ? taskSummary(tasks, kind) : {}),
54
78
  lastError,
55
79
  });
56
- }
80
+ };
81
+ // A small pool: `parallel` providers at a time, each taking the next id when it finishes.
82
+ const queue = [...ids];
83
+ const lanes = Array.from({ length: Math.max(1, Math.min(opts.parallel ?? 1, ids.length)) }, async () => {
84
+ for (let id = queue.shift(); id; id = queue.shift())
85
+ await one(id);
86
+ });
87
+ await Promise.all(lanes);
57
88
  saveBench(stored, opts.benchFile);
58
89
  return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
59
90
  }
91
+ /** Medians of the task runs that finished: the whole task, and each phase. */
92
+ function taskSummary(tasks, kind) {
93
+ const phases = Object.fromEntries(TASKS[kind].phases.map((p) => [p.id, median(tasks.map((t) => t.ms[p.id]))]));
94
+ const cpu = tasks.every((t) => t.cpuMs !== undefined) ? median(tasks.map((t) => t.cpuMs)) : undefined;
95
+ const core = tasks.every((t) => t.maxCoreMs !== undefined) ? median(tasks.map((t) => t.maxCoreMs)) : undefined;
96
+ return {
97
+ medianTaskMs: median(tasks.map((t) => taskMs(t.ms))),
98
+ taskPhasesMs: phases,
99
+ ...(cpu !== undefined ? { medianTaskCpuMs: cpu } : {}),
100
+ ...(core !== undefined ? { medianTaskMaxCoreMs: core } : {}),
101
+ };
102
+ }
60
103
  /** The spec a provider is benched at: the asked size, or its fixed default size if its image has one. */
61
104
  function sized(id, spec) {
62
105
  return { ...spec, ...fixedSize(id, spec) };
@@ -64,10 +107,19 @@ function sized(id, spec) {
64
107
  export function benchMarkdown(rows) {
65
108
  const name = (id) => CATALOG.find((c) => c.id === id).name;
66
109
  const ms = (n) => (n === undefined ? "n/a" : `${n} ms`);
110
+ const task = rows.some((r) => r.taskPhasesMs);
111
+ const cost = (r) => r.medianTaskMs !== undefined && r.medianCreateMs !== undefined
112
+ ? `$${taskUsd(r.provider, fittingSpec(r.provider), r.medianCreateMs, r.medianTaskMs, r.medianTaskCpuMs, 1, false, r.medianTaskMaxCoreMs).toFixed(6)}`
113
+ : "n/a";
67
114
  const lines = [
68
- "| # | Provider | Cold start (median) | Exec round trip | $/hr (list, size run) | Success |",
69
- "|---|---|---|---|---|---|",
70
- ...rows.map((r, i) => `| ${i + 1} | ${name(r.provider)} | ${ms(r.medianCreateMs)} | ${ms(r.medianExecMs)} | $${r.hourlyUsd.toFixed(3)} | ${r.runs - r.failures}/${r.runs} |`),
115
+ `| # | Provider | Cold start (median) | Exec round trip |${task ? " Task (median) | Task cost |" : ""} $/hr (list, size run) | Success |`,
116
+ `|---|---|---|---|${task ? "---|---|" : ""}---|---|`,
117
+ ...rows.map((r, i) => `| ${i + 1} | ${name(r.provider)} | ${ms(r.medianCreateMs)} | ${ms(r.medianExecMs)} |${task ? ` ${ms(r.medianTaskMs)} | ${cost(r)} |` : ""} $${r.hourlyUsd.toFixed(3)} | ${r.runs - r.failures}/${r.runs} |`),
71
118
  ];
72
119
  return lines.join("\n");
73
120
  }
121
+ /** Errors that are about the account running the benchmark, not the provider: setup problems, payment, limits. */
122
+ export const ACCOUNT_ERROR = /setup problem|Payment Required|\b40[123]\b|creation limit|quota|insufficient (?:credit|balance|funds)/i;
123
+ export const NETWORK_ERROR = /fetch failed|ENOTFOUND|EAI_AGAIN|ENETUNREACH|ECONNRESET|ETIMEDOUT|Name resolution failed|getaddrinfo/i;
124
+ /** A refusal for a limit or quota on the account running the benchmark: rate limits, concurrency and service quotas. */
125
+ export const LIMITED_ERROR = /\b429\b|\b402\b|rate.?limit|ServiceQuotaExceeded|quota|too many|concurrency limit|creation limit|trial_exhausted|insufficient_credits|Payment Required|throttl/i;
@@ -0,0 +1,81 @@
1
+ import { Router } from "./router.js";
2
+ import { type TaskKind } from "./task.js";
3
+ import type { ProviderId } from "./types.js";
4
+ /**
5
+ * One provider under load: `n` sandboxes asked for at the same moment, the way parallel agents or an RL run
6
+ * start them. Each must answer a command (time to interactive, measured from the moment they were all asked
7
+ * for, so queueing on the provider counts); with a job, each then runs it. Every sandbox is killed after.
8
+ */
9
+ export interface BurstRow {
10
+ provider: ProviderId;
11
+ /** Sandboxes asked for at once. */
12
+ n: number;
13
+ /** How many were ready and (with a job) finished it. */
14
+ ok: number;
15
+ /** Of the failures, how many the provider refused for a limit or quota on this account (429, "limit", ...). */
16
+ limited: number;
17
+ /** Time to interactive across the ready ones: create plus first command, from the burst's start. */
18
+ p50Ms?: number;
19
+ p95Ms?: number;
20
+ p99Ms?: number;
21
+ /** From the burst's start until the last sandbox finished (its job, with one). */
22
+ wallMs: number;
23
+ /** Median time of the job inside each sandbox, with one. */
24
+ jobP50Ms?: number;
25
+ /** What the whole burst would be billed: each finished sandbox priced as a new one (start, job, minimum, fee). */
26
+ usd?: number;
27
+ }
28
+ /** The value at percentile `p` (0 to 1) of sorted numbers, nearest-rank. */
29
+ export declare function percentile(sorted: number[], p: number): number | undefined;
30
+ export declare function burst(opts: {
31
+ router?: Router;
32
+ providers: ProviderId[];
33
+ n: number;
34
+ /** A standard job to run in every sandbox (src/task.ts): "python" for RL-style rollouts, "agent" for parallel agents. */
35
+ task?: TaskKind;
36
+ /** Providers loaded at once (default 1: a burst of 100 is enough load for this machine). */
37
+ parallel?: number;
38
+ onProgress?: (msg: string) => void;
39
+ }): Promise<BurstRow[]>;
40
+ /** One burst spread over several providers, with spillover when one says no. */
41
+ export interface SpreadResult {
42
+ n: number;
43
+ ok: number;
44
+ /** Sandboxes that found no provider with room. */
45
+ failed: number;
46
+ p50Ms?: number;
47
+ p95Ms?: number;
48
+ p99Ms?: number;
49
+ wallMs: number;
50
+ usd: number;
51
+ /** Where the sandboxes ran, and how many moved there after another provider refused. */
52
+ byProvider: {
53
+ provider: ProviderId;
54
+ ok: number;
55
+ spilledIn: number;
56
+ refused: number;
57
+ }[];
58
+ /** Providers that hit a limit during the burst (and were skipped for the rest of it). */
59
+ saturated: ProviderId[];
60
+ }
61
+ /**
62
+ * Ask for `n` sandboxes at once, spread round-robin over `providers`. A provider that refuses for a limit or quota
63
+ * is marked full for the rest of the burst, and that sandbox moves to the next provider with room: what a service
64
+ * running at scale needs when one provider's account limit is smaller than its burst. Time to interactive counts
65
+ * from the burst's start, so moving costs show. Every sandbox is killed after.
66
+ */
67
+ /**
68
+ * How many each provider can take at once, from the published bursts: the most it started at the largest size
69
+ * measured (all of them, if it started all). Unmeasured providers get 10, the size every account allows.
70
+ */
71
+ export declare function publishedCapacity(ids: ProviderId[]): Record<string, number>;
72
+ /** `n` slots dealt out in proportion to `weights`, interleaved so every provider gets work from the first moment. */
73
+ export declare function deal(ids: ProviderId[], n: number, weights: Record<string, number>): ProviderId[];
74
+ export declare function spreadBurst(opts: {
75
+ router?: Router;
76
+ providers: ProviderId[];
77
+ n: number;
78
+ /** How much each provider gets, relative; default: each one's measured capacity at once (publishedCapacity). */
79
+ weights?: Record<string, number> | "even";
80
+ onProgress?: (msg: string) => void;
81
+ }): Promise<SpreadResult>;