@sandboxrouter/sdk 0.10.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 (51) hide show
  1. package/README.md +3 -2
  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 +12 -0
  6. package/dist/bench.js +24 -3
  7. package/dist/burst.d.ts +81 -0
  8. package/dist/burst.js +183 -0
  9. package/dist/catalog.d.ts +12 -0
  10. package/dist/catalog.js +15 -11
  11. package/dist/check.d.ts +2 -0
  12. package/dist/check.js +8 -0
  13. package/dist/cli.js +200 -5
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/leaderboard.d.ts +74 -2
  17. package/dist/leaderboard.js +117 -7
  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 +63 -1
  42. package/dist/router.d.ts +45 -0
  43. package/dist/router.js +69 -4
  44. package/dist/submit.d.ts +6 -0
  45. package/dist/submit.js +70 -0
  46. package/dist/task.d.ts +17 -2
  47. package/dist/task.js +74 -19
  48. package/dist/types.d.ts +5 -0
  49. package/dist/util.d.ts +2 -0
  50. package/dist/util.js +2 -0
  51. 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
 
@@ -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
@@ -8,11 +8,18 @@ export interface BenchRow {
8
8
  medianCreateMs?: number;
9
9
  medianExecMs?: number;
10
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;
11
16
  /** With `task`: median time of the standard task (src/task.ts), and of each of its phases. */
12
17
  medianTaskMs?: number;
13
18
  taskPhasesMs?: Record<string, number>;
14
19
  /** With `task`: median CPU time the task used across all vCPUs, where the sandbox shows /proc/stat. */
15
20
  medianTaskCpuMs?: number;
21
+ /** With `task`: median busy time of the busiest core, for providers that meter CPU per VM. */
22
+ medianTaskMaxCoreMs?: number;
16
23
  lastError?: string;
17
24
  }
18
25
  /**
@@ -34,3 +41,8 @@ export declare function bench(opts: {
34
41
  onProgress?: (msg: string) => void;
35
42
  }): Promise<BenchRow[]>;
36
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
@@ -15,7 +15,13 @@ export async function bench(opts) {
15
15
  const given = Object.fromEntries(Object.entries(opts.spec ?? {}).filter(([, v]) => v !== undefined));
16
16
  const kind = opts.task === true ? "short" : opts.task || undefined;
17
17
  // The long task can take minutes on a slow provider: give the sandbox room to finish it.
18
- const spec = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: kind === "long" ? 20 : 5, ...given };
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
+ };
19
25
  const ids = opts.providers ?? router.registered().filter((id) => router.isConfigured(id));
20
26
  const log = opts.onProgress ?? (() => { });
21
27
  const stored = loadBench(opts.benchFile);
@@ -25,6 +31,7 @@ export async function bench(opts) {
25
31
  const execMs = [];
26
32
  const tasks = [];
27
33
  let failures = 0;
34
+ let limited = 0;
28
35
  let lastError;
29
36
  for (let i = 0; i < runs; i++) {
30
37
  log(`${id} run ${i + 1}/${runs}`);
@@ -51,6 +58,8 @@ export async function bench(opts) {
51
58
  catch (err) {
52
59
  failures++;
53
60
  lastError = err.message.slice(0, 200);
61
+ if (LIMITED_ERROR.test(lastError))
62
+ limited++;
54
63
  }
55
64
  finally {
56
65
  await box?.kill().catch(() => { });
@@ -64,6 +73,7 @@ export async function bench(opts) {
64
73
  medianCreateMs: median(createMs),
65
74
  medianExecMs: median(execMs),
66
75
  hourlyUsd: hourlyCost(id, sized(id, spec)),
76
+ ...(limited ? { limited } : {}),
67
77
  ...(tasks.length ? taskSummary(tasks, kind) : {}),
68
78
  lastError,
69
79
  });
@@ -82,7 +92,13 @@ export async function bench(opts) {
82
92
  function taskSummary(tasks, kind) {
83
93
  const phases = Object.fromEntries(TASKS[kind].phases.map((p) => [p.id, median(tasks.map((t) => t.ms[p.id]))]));
84
94
  const cpu = tasks.every((t) => t.cpuMs !== undefined) ? median(tasks.map((t) => t.cpuMs)) : undefined;
85
- return { medianTaskMs: median(tasks.map((t) => taskMs(t.ms))), taskPhasesMs: phases, ...(cpu !== undefined ? { medianTaskCpuMs: cpu } : {}) };
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
+ };
86
102
  }
87
103
  /** The spec a provider is benched at: the asked size, or its fixed default size if its image has one. */
88
104
  function sized(id, spec) {
@@ -93,7 +109,7 @@ export function benchMarkdown(rows) {
93
109
  const ms = (n) => (n === undefined ? "n/a" : `${n} ms`);
94
110
  const task = rows.some((r) => r.taskPhasesMs);
95
111
  const cost = (r) => r.medianTaskMs !== undefined && r.medianCreateMs !== undefined
96
- ? `$${taskUsd(r.provider, fittingSpec(r.provider), r.medianCreateMs, r.medianTaskMs, r.medianTaskCpuMs).toFixed(6)}`
112
+ ? `$${taskUsd(r.provider, fittingSpec(r.provider), r.medianCreateMs, r.medianTaskMs, r.medianTaskCpuMs, 1, false, r.medianTaskMaxCoreMs).toFixed(6)}`
97
113
  : "n/a";
98
114
  const lines = [
99
115
  `| # | Provider | Cold start (median) | Exec round trip |${task ? " Task (median) | Task cost |" : ""} $/hr (list, size run) | Success |`,
@@ -102,3 +118,8 @@ export function benchMarkdown(rows) {
102
118
  ];
103
119
  return lines.join("\n");
104
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>;
package/dist/burst.js ADDED
@@ -0,0 +1,183 @@
1
+ import { BILLED_VS_LIST } from "./billing.js";
2
+ import { fittingSpec, fixedSize, DEFAULT_MEMORY_GB, DEFAULT_VCPU } from "./catalog.js";
3
+ import { Router } from "./router.js";
4
+ import { runTask, taskMs, taskUsd, TASKS } from "./task.js";
5
+ import { PUBLISHED } from "./published.js";
6
+ const LIMIT = /\b429\b|\b402\b|rate limit|too many|limit|quota|concurren|capacity|throttl|trial_exhausted|insufficient_credits/i;
7
+ /** The value at percentile `p` (0 to 1) of sorted numbers, nearest-rank. */
8
+ export function percentile(sorted, p) {
9
+ if (!sorted.length)
10
+ return undefined;
11
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
12
+ }
13
+ export async function burst(opts) {
14
+ const router = opts.router ?? new Router();
15
+ const kind = opts.task;
16
+ const base = {
17
+ vcpu: DEFAULT_VCPU,
18
+ memoryGb: DEFAULT_MEMORY_GB,
19
+ timeoutMinutes: 10,
20
+ ...(kind && TASKS[kind].cpuUtilization ? { cpuUtilization: TASKS[kind].cpuUtilization } : {}),
21
+ };
22
+ const log = opts.onProgress ?? (() => { });
23
+ const rows = [];
24
+ const one = async (id) => {
25
+ log(`${id}: ${opts.n} at once${kind ? `, each running the ${kind} job` : ""}`);
26
+ const spec = { ...base, ...fixedSize(id, base) };
27
+ const t0 = performance.now();
28
+ const results = await Promise.all(Array.from({ length: opts.n }, async () => {
29
+ let box;
30
+ try {
31
+ box = await router.create(spec, { provider: id, fallback: false, deadlineSeconds: 240 });
32
+ const createMs = performance.now() - t0;
33
+ const r = await box.exec("echo ok");
34
+ if (r.exitCode !== 0 || r.stdout.trim() !== "ok")
35
+ throw new Error(`echo returned ${r.exitCode}`);
36
+ const tti = performance.now() - t0;
37
+ const job = kind ? await runTask(box, kind) : undefined;
38
+ return { ok: true, tti, createMs, job, done: performance.now() - t0 };
39
+ }
40
+ catch (err) {
41
+ return { ok: false, error: err.message, done: performance.now() - t0 };
42
+ }
43
+ finally {
44
+ await box?.kill().catch(() => { });
45
+ }
46
+ }));
47
+ const ok = results.filter((r) => r.ok);
48
+ const ttis = ok.map((r) => Math.round(r.tti)).sort((a, b) => a - b);
49
+ const jobs = ok.map((r) => (r.job ? taskMs(r.job.ms) : undefined)).filter((n) => n !== undefined).sort((a, b) => a - b);
50
+ const size = fittingSpec(id);
51
+ const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
52
+ const usd = ok.reduce((sum, r) => sum +
53
+ taskUsd(id, { ...size, ...(spec.cpuUtilization ? { cpuUtilization: spec.cpuUtilization } : {}) }, r.createMs, r.job ? taskMs(r.job.ms) : 0, r.job?.cpuMs, ratio, false, r.job?.maxCoreMs), 0);
54
+ const failed = results.filter((r) => !r.ok);
55
+ rows.push({
56
+ provider: id,
57
+ n: opts.n,
58
+ ok: ok.length,
59
+ limited: failed.filter((f) => LIMIT.test(f.error)).length,
60
+ p50Ms: percentile(ttis, 0.5),
61
+ p95Ms: percentile(ttis, 0.95),
62
+ p99Ms: percentile(ttis, 0.99),
63
+ wallMs: Math.round(Math.max(...results.map((r) => r.done))),
64
+ ...(jobs.length ? { jobP50Ms: percentile(jobs, 0.5) } : {}),
65
+ ...(ok.length ? { usd: Math.round(usd * 1e6) / 1e6 } : {}),
66
+ });
67
+ const sample = failed[0]?.error;
68
+ log(`${id}: ${ok.length}/${opts.n} ready, p50 ${percentile(ttis, 0.5) ?? "-"} ms, p99 ${percentile(ttis, 0.99) ?? "-"} ms${sample ? `; e.g. ${sample.slice(0, 140)}` : ""}`);
69
+ };
70
+ const queue = [...opts.providers];
71
+ const lanes = Array.from({ length: Math.max(1, Math.min(opts.parallel ?? 1, queue.length)) }, async () => {
72
+ for (let id = queue.shift(); id; id = queue.shift())
73
+ await one(id);
74
+ });
75
+ await Promise.all(lanes);
76
+ return rows.sort((a, b) => b.ok - a.ok || (a.p50Ms ?? Infinity) - (b.p50Ms ?? Infinity));
77
+ }
78
+ /**
79
+ * Ask for `n` sandboxes at once, spread round-robin over `providers`. A provider that refuses for a limit or quota
80
+ * is marked full for the rest of the burst, and that sandbox moves to the next provider with room: what a service
81
+ * running at scale needs when one provider's account limit is smaller than its burst. Time to interactive counts
82
+ * from the burst's start, so moving costs show. Every sandbox is killed after.
83
+ */
84
+ /**
85
+ * How many each provider can take at once, from the published bursts: the most it started at the largest size
86
+ * measured (all of them, if it started all). Unmeasured providers get 10, the size every account allows.
87
+ */
88
+ export function publishedCapacity(ids) {
89
+ const loads = PUBLISHED.load.filter((l) => l.job === "start").sort((a, b) => b.n - a.n);
90
+ return Object.fromEntries(ids.map((id) => [id, loads.find((l) => l.rows[id])?.rows[id]?.ok ?? 10]));
91
+ }
92
+ /** `n` slots dealt out in proportion to `weights`, interleaved so every provider gets work from the first moment. */
93
+ export function deal(ids, n, weights) {
94
+ const total = ids.reduce((t, id) => t + Math.max(1, weights[id] ?? 1), 0);
95
+ const want = new Map(ids.map((id) => [id, (Math.max(1, weights[id] ?? 1) / total) * n]));
96
+ const given = new Map(ids.map((id) => [id, 0]));
97
+ const out = [];
98
+ for (let i = 0; i < n; i++) {
99
+ // The provider furthest behind its share goes next (ties by list order).
100
+ let best = ids[0];
101
+ let gap = -Infinity;
102
+ for (const id of ids) {
103
+ const g = (want.get(id) * (i + 1)) / n - given.get(id);
104
+ if (g > gap) {
105
+ gap = g;
106
+ best = id;
107
+ }
108
+ }
109
+ given.set(best, given.get(best) + 1);
110
+ out.push(best);
111
+ }
112
+ return out;
113
+ }
114
+ export async function spreadBurst(opts) {
115
+ const router = opts.router ?? new Router();
116
+ const log = opts.onProgress ?? (() => { });
117
+ const base = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: 10 };
118
+ const full = new Set();
119
+ const stats = new Map(opts.providers.map((p) => [p, { ok: 0, spilledIn: 0, refused: 0, createMs: [] }]));
120
+ const t0 = performance.now();
121
+ const weights = opts.weights === "even" ? Object.fromEntries(opts.providers.map((id) => [id, 1])) : (opts.weights ?? publishedCapacity(opts.providers));
122
+ const first = deal(opts.providers, opts.n, weights);
123
+ log(`${opts.n} at once, spread over ${opts.providers.length} providers by ${opts.weights === "even" ? "equal shares" : "measured capacity"}`);
124
+ const results = await Promise.all(Array.from({ length: opts.n }, async (_, i) => {
125
+ // Start on this sandbox's dealt provider, then walk the rest, biggest capacity first.
126
+ const rest = [...opts.providers].filter((id) => id !== first[i]).sort((a, b) => (weights[b] ?? 1) - (weights[a] ?? 1));
127
+ const order = [first[i], ...rest];
128
+ let moved = false;
129
+ for (const id of order) {
130
+ if (full.has(id)) {
131
+ moved = true;
132
+ continue;
133
+ }
134
+ let box;
135
+ try {
136
+ box = await router.create({ ...base, ...fixedSize(id, base) }, { provider: id, fallback: false, deadlineSeconds: 240 });
137
+ const createMs = performance.now() - t0;
138
+ const r = await box.exec("echo ok");
139
+ if (r.exitCode !== 0 || r.stdout.trim() !== "ok")
140
+ throw new Error(`echo returned ${r.exitCode}`);
141
+ const s = stats.get(id);
142
+ s.ok++;
143
+ s.createMs.push(createMs);
144
+ if (moved)
145
+ s.spilledIn++;
146
+ return { ok: true, tti: performance.now() - t0, done: performance.now() - t0 };
147
+ }
148
+ catch (err) {
149
+ const msg = err.message;
150
+ stats.get(id).refused++;
151
+ if (LIMIT.test(msg)) {
152
+ if (!full.has(id))
153
+ log(`${id}: full (${msg.slice(0, 90)})`);
154
+ full.add(id);
155
+ }
156
+ moved = true;
157
+ }
158
+ finally {
159
+ await box?.kill().catch(() => { });
160
+ }
161
+ }
162
+ return { ok: false, done: performance.now() - t0 };
163
+ }));
164
+ const ttis = results.filter((r) => r.ok).map((r) => Math.round(r.tti)).sort((a, b) => a - b);
165
+ let usd = 0;
166
+ for (const [id, s] of stats) {
167
+ const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
168
+ for (const c of s.createMs)
169
+ usd += taskUsd(id, fittingSpec(id), c, 0, undefined, ratio, false);
170
+ }
171
+ return {
172
+ n: opts.n,
173
+ ok: ttis.length,
174
+ failed: opts.n - ttis.length,
175
+ p50Ms: percentile(ttis, 0.5),
176
+ p95Ms: percentile(ttis, 0.95),
177
+ p99Ms: percentile(ttis, 0.99),
178
+ wallMs: Math.round(Math.max(...results.map((r) => r.done))),
179
+ usd: Math.round(usd * 1e6) / 1e6,
180
+ byProvider: [...stats].map(([provider, s]) => ({ provider, ok: s.ok, spilledIn: s.spilledIn, refused: s.refused })).sort((a, b) => b.ok - a.ok),
181
+ saturated: [...full],
182
+ };
183
+ }
package/dist/catalog.d.ts CHANGED
@@ -22,6 +22,18 @@ export interface ProviderInfo {
22
22
  * on Vercel, where provisioned memory has a one-minute minimum and active CPU has none.
23
23
  */
24
24
  minimumCovers?: "all" | "memory";
25
+ /**
26
+ * Bills the larger of the CPU reserved and the CPU used (Modal). The adapter reserves `cpuUtilization` of
27
+ * the size you ask for (at least `cpuFloor`) and lets the sandbox burst to the full size, so CPU is
28
+ * priced like active CPU when `cpuUtilization` is below 1, and like allocated capacity otherwise.
29
+ */
30
+ reservesCpu?: boolean;
31
+ /**
32
+ * Active CPU is metered for the whole VM: while any core is busy, every vCPU counts (measured on Vercel
33
+ * 2026-11-17: one busy core for 11 s metered 22.7 s on 2 vCPUs; both busy metered 24.1 s for 23.1 s
34
+ * seen inside; idle about 2%). Task pricing then charges vCPUs x the busiest core's time.
35
+ */
36
+ cpuMeteredPerVm?: boolean;
25
37
  note?: string;
26
38
  source: string;
27
39
  checked: string;