@sandboxrouter/sdk 0.8.3 → 0.10.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.
package/README.md CHANGED
@@ -30,7 +30,7 @@ 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
- - **Cheapest real cost, then speed, with fallback.** Or `cheapest` for list price alone, `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.
33
+ - **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
34
  - **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
35
  - **Your keys.** Your accounts and your bills; nothing is proxied through anyone else.
36
36
  - **Cleanup.** A local ledger of every sandbox started, so `sandboxrouter gc` kills what a crashed script left behind.
@@ -61,7 +61,7 @@ List price while running, 2 vCPU / 4 GB, cheapest first; waitlisted sign-ups fol
61
61
  | [Upstash Box](https://sandboxrouter.ai/providers/upstash) | up to $0.200 | none | not run yet | [pricing](https://upstash.com/pricing/box) |
62
62
  | [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
63
  | [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) |
64
+ | [Modal](https://sandboxrouter.ai/providers/modal) | $0.238 | none | passed (2026-11-13) | [pricing](https://modal.com/pricing) |
65
65
  | [AWS Lambda MicroVMs](https://sandboxrouter.ai/providers/lambda) | $0.252 | none | passed (2026-11-13) | [pricing](https://aws.amazon.com/lambda/pricing/) |
66
66
  | [Deno Sandbox](https://sandboxrouter.ai/providers/deno) | up to $0.300 | $20/mo | not run yet | [pricing](https://deno.com/sandbox) |
67
67
  | [Runloop](https://sandboxrouter.ai/providers/runloop) | $0.317 | none | not run yet | [pricing](https://www.runloop.ai/pricing) |
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,11 @@ export interface BenchRow {
7
8
  medianCreateMs?: number;
8
9
  medianExecMs?: number;
9
10
  hourlyUsd: number;
11
+ /** With `task`: median time of the standard task (src/task.ts), and of each of its phases. */
12
+ medianTaskMs?: number;
13
+ taskPhasesMs?: Record<string, number>;
14
+ /** With `task`: median CPU time the task used across all vCPUs, where the sandbox shows /proc/stat. */
15
+ medianTaskCpuMs?: number;
10
16
  lastError?: string;
11
17
  }
12
18
  /**
@@ -21,6 +27,10 @@ export declare function bench(opts: {
21
27
  runs?: number;
22
28
  spec?: SandboxSpec;
23
29
  benchFile?: string;
30
+ /** Also run a standard task (src/task.ts) in each sandbox, to price a fixed piece of work: true or "short", "long", "python", "download". */
31
+ task?: boolean | TaskKind;
32
+ /** Providers benched at once (default 1). Each provider's own runs stay one after another. */
33
+ parallel?: number;
24
34
  onProgress?: (msg: string) => void;
25
35
  }): Promise<BenchRow[]>;
26
36
  export declare function benchMarkdown(rows: BenchRow[]): string;
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,14 +13,17 @@ 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 = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: kind === "long" ? 20 : 5, ...given };
16
19
  const ids = opts.providers ?? router.registered().filter((id) => router.isConfigured(id));
17
20
  const log = opts.onProgress ?? (() => { });
18
21
  const stored = loadBench(opts.benchFile);
19
22
  const rows = [];
20
- for (const id of ids) {
23
+ const one = async (id) => {
21
24
  const createMs = [];
22
25
  const execMs = [];
26
+ const tasks = [];
23
27
  let failures = 0;
24
28
  let lastError;
25
29
  for (let i = 0; i < runs; i++) {
@@ -34,6 +38,15 @@ export async function bench(opts) {
34
38
  if (r.exitCode !== 0 || r.stdout.trim() !== "ok")
35
39
  throw new Error(`echo returned ${r.exitCode}: ${r.stdout}${r.stderr}`);
36
40
  execMs.push(Math.round(performance.now() - t1));
41
+ if (kind) {
42
+ // A failed task doesn't fail the run: the start time still counts, the task just has no time.
43
+ try {
44
+ tasks.push(await runTask(box, kind));
45
+ }
46
+ catch (err) {
47
+ lastError = `task: ${err.message.slice(0, 180)}`;
48
+ }
49
+ }
37
50
  }
38
51
  catch (err) {
39
52
  failures++;
@@ -51,12 +64,26 @@ export async function bench(opts) {
51
64
  medianCreateMs: median(createMs),
52
65
  medianExecMs: median(execMs),
53
66
  hourlyUsd: hourlyCost(id, sized(id, spec)),
67
+ ...(tasks.length ? taskSummary(tasks, kind) : {}),
54
68
  lastError,
55
69
  });
56
- }
70
+ };
71
+ // A small pool: `parallel` providers at a time, each taking the next id when it finishes.
72
+ const queue = [...ids];
73
+ const lanes = Array.from({ length: Math.max(1, Math.min(opts.parallel ?? 1, ids.length)) }, async () => {
74
+ for (let id = queue.shift(); id; id = queue.shift())
75
+ await one(id);
76
+ });
77
+ await Promise.all(lanes);
57
78
  saveBench(stored, opts.benchFile);
58
79
  return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
59
80
  }
81
+ /** Medians of the task runs that finished: the whole task, and each phase. */
82
+ function taskSummary(tasks, kind) {
83
+ const phases = Object.fromEntries(TASKS[kind].phases.map((p) => [p.id, median(tasks.map((t) => t.ms[p.id]))]));
84
+ 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 } : {}) };
86
+ }
60
87
  /** The spec a provider is benched at: the asked size, or its fixed default size if its image has one. */
61
88
  function sized(id, spec) {
62
89
  return { ...spec, ...fixedSize(id, spec) };
@@ -64,10 +91,14 @@ function sized(id, spec) {
64
91
  export function benchMarkdown(rows) {
65
92
  const name = (id) => CATALOG.find((c) => c.id === id).name;
66
93
  const ms = (n) => (n === undefined ? "n/a" : `${n} ms`);
94
+ const task = rows.some((r) => r.taskPhasesMs);
95
+ const cost = (r) => r.medianTaskMs !== undefined && r.medianCreateMs !== undefined
96
+ ? `$${taskUsd(r.provider, fittingSpec(r.provider), r.medianCreateMs, r.medianTaskMs, r.medianTaskCpuMs).toFixed(6)}`
97
+ : "n/a";
67
98
  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} |`),
99
+ `| # | Provider | Cold start (median) | Exec round trip |${task ? " Task (median) | Task cost |" : ""} $/hr (list, size run) | Success |`,
100
+ `|---|---|---|---|${task ? "---|---|" : ""}---|---|`,
101
+ ...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
102
  ];
72
103
  return lines.join("\n");
73
104
  }
package/dist/catalog.d.ts CHANGED
@@ -12,6 +12,16 @@ export interface ProviderInfo {
12
12
  incrementSeconds?: number;
13
13
  /** A fixed charge per sandbox created, USD, on top of running time. */
14
14
  perSandboxUsd?: number;
15
+ /**
16
+ * Active-CPU billing only: the share of the allocated CPU billed even when idle (Tensorlake bills at
17
+ * least 20%). Default 0.
18
+ */
19
+ cpuFloor?: number;
20
+ /**
21
+ * What `minSeconds` applies to. "all" (default): the whole price. "memory": only the non-CPU part, as
22
+ * on Vercel, where provisioned memory has a one-minute minimum and active CPU has none.
23
+ */
24
+ minimumCovers?: "all" | "memory";
15
25
  note?: string;
16
26
  source: string;
17
27
  checked: string;
@@ -269,6 +279,7 @@ export declare function billingRules(id: ProviderId): {
269
279
  minSeconds: number;
270
280
  incrementSeconds: number;
271
281
  perSandboxUsd: number;
282
+ minimumCovers: "all" | "memory";
272
283
  };
273
284
  /**
274
285
  * What a provider bills for one sandbox that ran `seconds` at `hourlyUsd`: running time rounded up to
@@ -289,6 +300,15 @@ export declare function fittingSpec(id: ProviderId): {
289
300
  vcpu: number;
290
301
  memoryGb: number;
291
302
  };
303
+ /**
304
+ * Estimated USD per hour for this spec on this provider (list price, while running). For providers that
305
+ * bill CPU only while it's busy ("active-cpu"), the CPU part is scaled by `spec.cpuUtilization` (default
306
+ * 1, every core busy, so the price is the most an hour costs), never below the provider's `cpuFloor`.
307
+ */
292
308
  export declare function hourlyCost(id: ProviderId, spec?: SandboxSpec): number;
309
+ /** The CPU part of the full-use hourly price for an "active-cpu" provider; 0 for providers that bill allocated capacity. */
310
+ export declare function cpuHourlyAtFull(id: ProviderId, spec?: SandboxSpec): number;
311
+ /** Share of an "active-cpu" provider's CPU that gets billed: `cpuUtilization` (default 1), at least its `cpuFloor`. */
312
+ export declare function billedCpuShare(id: ProviderId, spec?: SandboxSpec): number;
293
313
  /** Why a provider can't take this spec, or null if it can. */
294
314
  export declare function unfit(id: ProviderId, spec: SandboxSpec, require?: Capability[]): string | null;
package/dist/catalog.js CHANGED
@@ -120,9 +120,10 @@ const ENTRIES = [
120
120
  name: "Vercel Sandbox",
121
121
  pricing: {
122
122
  minSeconds: 60,
123
+ minimumCovers: "memory",
123
124
  vcpuHour: 0.128,
124
125
  gbHour: 0.0212,
125
- note: "iad1; active CPU, provisioned RAM in minimum 1-minute increments (2 GB/vCPU); full-CPU estimate; Hobby free within quotas, Pro $20/mo usage credit; creations $0.60/million and retained snapshots $0.08/GB-month extra",
126
+ note: "iad1; active CPU (I/O wait free), provisioned RAM in minimum 1-minute increments (2 GB/vCPU); listed at full CPU, cpuUtilization lowers it; Hobby free within quotas, Pro $20/mo usage credit; creations $0.60/million and retained snapshots $0.08/GB-month extra",
126
127
  source: "https://vercel.com/docs/vercel-sandbox/pricing",
127
128
  checked: "2026-11-05",
128
129
  },
@@ -189,7 +190,8 @@ const ENTRIES = [
189
190
  pricing: {
190
191
  vcpuHour: 0.07,
191
192
  gbHour: 0.015,
192
- note: "bills active CPU (floor 20% of allocation); this is the full-use price; Pro plan is lower",
193
+ cpuFloor: 0.2,
194
+ note: "bills active CPU (floor 20% of allocation); listed at full CPU, cpuUtilization lowers it; Pro plan is lower",
193
195
  source: "https://www.tensorlake.ai/pricing",
194
196
  checked: "2026-11-04",
195
197
  },
@@ -610,7 +612,8 @@ const BILLING = {
610
612
  lambda: { billing: "allocated" },
611
613
  langsmith: { billing: "allocated" },
612
614
  maritime: { billing: "allocated", plan: { usdMonth: 20, credited: true, note: "Starter plan; no free tier; 7-day trial needs a card", checked: P } },
613
- modal: { billing: "active-cpu" },
615
+ // Modal bills the larger of the reservation and actual use, and the adapter reserves the size you ask for.
616
+ modal: { billing: "allocated" },
614
617
  morph: { billing: "allocated" },
615
618
  northflank: { billing: "allocated" },
616
619
  novita: { billing: "allocated" },
@@ -672,7 +675,12 @@ export function cloudflareInstance(vcpu, memoryGb) {
672
675
  /** How a provider turns running time into a bill: minimum, rounding and fixed per-sandbox charge. */
673
676
  export function billingRules(id) {
674
677
  const p = CATALOG.find((c) => c.id === id)?.pricing;
675
- return { minSeconds: p?.minSeconds ?? 0, incrementSeconds: p?.incrementSeconds ?? 1, perSandboxUsd: p?.perSandboxUsd ?? 0 };
678
+ return {
679
+ minSeconds: p?.minSeconds ?? 0,
680
+ incrementSeconds: p?.incrementSeconds ?? 1,
681
+ perSandboxUsd: p?.perSandboxUsd ?? 0,
682
+ minimumCovers: p?.minimumCovers ?? "all",
683
+ };
676
684
  }
677
685
  /**
678
686
  * What a provider bills for one sandbox that ran `seconds` at `hourlyUsd`: running time rounded up to
@@ -701,7 +709,7 @@ export function fixedSize(id, spec = {}) {
701
709
  export function fittingSpec(id) {
702
710
  return fixedSize(id) ?? { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB };
703
711
  }
704
- export function hourlyCost(id, spec = {}) {
712
+ function fullHourlyCost(id, spec = {}) {
705
713
  const { pricing } = info(id);
706
714
  // You get, and pay for, the default image's size whatever you asked for.
707
715
  const fixed = fixedSize(id, spec);
@@ -769,6 +777,37 @@ export function hourlyCost(id, spec = {}) {
769
777
  return Math.max(vcpu, Math.ceil(mem / 4)) * pricing.vcpuHour;
770
778
  return vcpu * pricing.vcpuHour + mem * pricing.gbHour;
771
779
  }
780
+ /**
781
+ * Estimated USD per hour for this spec on this provider (list price, while running). For providers that
782
+ * bill CPU only while it's busy ("active-cpu"), the CPU part is scaled by `spec.cpuUtilization` (default
783
+ * 1, every core busy, so the price is the most an hour costs), never below the provider's `cpuFloor`.
784
+ */
785
+ export function hourlyCost(id, spec = {}) {
786
+ const cpu = cpuHourlyAtFull(id, spec);
787
+ return fullHourlyCost(id, spec) - cpu * (1 - billedCpuShare(id, spec));
788
+ }
789
+ /** The CPU part of the full-use hourly price for an "active-cpu" provider; 0 for providers that bill allocated capacity. */
790
+ export function cpuHourlyAtFull(id, spec = {}) {
791
+ const p = info(id);
792
+ if (p.billing !== "active-cpu")
793
+ return 0;
794
+ const fixed = fixedSize(id, spec);
795
+ if (fixed)
796
+ return fixed.vcpu * p.pricing.vcpuHour;
797
+ const vcpu = spec.vcpu ?? DEFAULT_VCPU;
798
+ const mem = spec.memoryGb ?? DEFAULT_MEMORY_GB;
799
+ if (id === "cloudflare")
800
+ return cloudflareInstance(vcpu, mem).vcpu * p.pricing.vcpuHour;
801
+ if (id === "upstash")
802
+ return fullHourlyCost(id, spec);
803
+ if (id === "deno")
804
+ return 2 * p.pricing.vcpuHour;
805
+ return vcpu * p.pricing.vcpuHour;
806
+ }
807
+ /** Share of an "active-cpu" provider's CPU that gets billed: `cpuUtilization` (default 1), at least its `cpuFloor`. */
808
+ export function billedCpuShare(id, spec = {}) {
809
+ return Math.min(1, Math.max(spec.cpuUtilization ?? 1, info(id).pricing.cpuFloor ?? 0));
810
+ }
772
811
  /** Why a provider can't take this spec, or null if it can. */
773
812
  export function unfit(id, spec, require = []) {
774
813
  const p = info(id);
package/dist/cli.js CHANGED
@@ -3,6 +3,7 @@ import { parseArgs } from "node:util";
3
3
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { platform, arch } from "node:os";
5
5
  import { bench, benchMarkdown } from "./bench.js";
6
+ import { TASKS } from "./task.js";
6
7
  import { costMarkdown, costRun, settle } from "./cost.js";
7
8
  import { checkProvider } from "./check.js";
8
9
  import { gc, listOpen } from "./gc.js";
@@ -17,6 +18,7 @@ const HELP = `sandboxrouter: one API for every sandbox provider
17
18
  Usage:
18
19
  sandboxrouter providers [--vcpu N] [--memory GB] price table + which keys are set
19
20
  sandboxrouter route [spec flags] [route flags] dry run: the order providers would be tried
21
+ sandboxrouter quote [spec/route flags] [--json] where a create would land and what the run would cost
20
22
  sandboxrouter run "<cmd>" [spec flags] [route flags] [--keep]
21
23
  sandboxrouter check --provider ID[,ID] | --all [--json] [--save [dir]] [--retry] [--out FILE] [--by GITHUB_USER]
22
24
  test providers for real: exec, env, UTF-8, streaming, files, timeout, pause,
@@ -27,7 +29,11 @@ Usage:
27
29
  sandboxrouter ls [--json] sandboxes this machine started that weren't killed
28
30
  sandboxrouter gc [--all | --older-than MIN] [--dry-run]
29
31
  kill leaked sandboxes: by default those past their lifetime
30
- sandboxrouter bench [--runs 3] [--provider a,b] [--json] [--share [--label "where you ran it"] [--by GITHUB_USER]]
32
+ sandboxrouter bench [--runs 3] [--provider a,b] [--task [--long]] [--parallel N] [--json] [--share [--label "where you ran it"] [--by GITHUB_USER]]
33
+ --task also runs the same fixed job in each sandbox (hash 512 MB on 1 core,
34
+ then on 2, write 256 MB to disk) and prices it with each provider's billing rules;
35
+ --long runs that job 40 times in a row (minutes); --job python (a pure-Python script)
36
+ or --job download (53 MB over HTTPS) runs another job. --parallel benches N providers at once
31
37
  sandboxrouter cost run [--provider a,b] [--minutes 10] [--vcpu 2 --memory 4] [--no-load] [--out FILE] [--by GITHUB_USER]
32
38
  start one sandbox per provider for a fixed time with every core busy, record
33
39
  the size it really got and the list-price prediction
@@ -41,7 +47,9 @@ Usage:
41
47
  sandboxrouter serve [--port 8787] [--host 127.0.0.1] [--cors https://site.example,http://localhost:3000]
42
48
 
43
49
  Spec flags: --vcpu N --memory GB --gpu T4 --timeout MIN --expect SEC (how long you'll use it; ranks by the real bill)
50
+ --cpu 0.1 (how busy the CPU is, 0-1; lowers providers that bill active CPU)
44
51
  Route flags: --provider e2b[,modal,...] --strategy balanced|verified|cheapest|fastest (default balanced: cheapest real cost, speed breaks near-ties)
52
+ --max-price USD (per hour, for this run: skip providers that would cost more)
45
53
  --no-fallback --fallback-any (also on setup errors like a bad key)
46
54
  --create-timeout SEC (per provider, default 120) --require gpu,custom-image
47
55
 
@@ -55,14 +63,20 @@ const { values, positionals } = parseArgs({
55
63
  gpu: { type: "string" },
56
64
  timeout: { type: "string" },
57
65
  expect: { type: "string" },
66
+ cpu: { type: "string" },
58
67
  provider: { type: "string" },
59
68
  strategy: { type: "string" },
69
+ "max-price": { type: "string" },
60
70
  "no-fallback": { type: "boolean" },
61
71
  "fallback-any": { type: "boolean" },
62
72
  "create-timeout": { type: "string" },
63
73
  require: { type: "string" },
64
74
  keep: { type: "boolean" },
65
75
  runs: { type: "string" },
76
+ task: { type: "boolean" },
77
+ long: { type: "boolean" },
78
+ job: { type: "string" },
79
+ parallel: { type: "string" },
66
80
  json: { type: "boolean" },
67
81
  port: { type: "string" },
68
82
  host: { type: "string" },
@@ -98,6 +112,7 @@ const spec = {
98
112
  gpu: values.gpu,
99
113
  timeoutMinutes: num(values.timeout),
100
114
  expectedSeconds: num(values.expect),
115
+ cpuUtilization: num(values.cpu),
101
116
  };
102
117
  const providers = list(values.provider);
103
118
  const by = (() => {
@@ -115,6 +130,7 @@ const route = {
115
130
  fallback: values["no-fallback"] ? false : values["fallback-any"] ? "any" : undefined,
116
131
  createTimeoutSeconds: num(values["create-timeout"]),
117
132
  require: list(values.require),
133
+ maxHourlyUsd: num(values["max-price"]),
118
134
  };
119
135
  async function main() {
120
136
  const [cmd, ...rest] = positionals;
@@ -154,6 +170,23 @@ async function main() {
154
170
  ].join("\n"));
155
171
  return;
156
172
  }
173
+ if (cmd === "quote") {
174
+ const q = router.quote(spec, route);
175
+ if (values.json)
176
+ return console.log(JSON.stringify({ ...q, candidates: undefined }, null, 2));
177
+ const rules = [
178
+ q.minimumSeconds ? `at least ${q.minimumSeconds} s billed` : "",
179
+ q.billedInSecondsOf ? `billed in steps of ${q.billedInSecondsOf} s` : "",
180
+ q.perSandboxUsd ? `$${q.perSandboxUsd} per sandbox` : "",
181
+ ].filter(Boolean);
182
+ console.log(`${q.provider}, ${q.size.vcpu} vCPU / ${q.size.memoryGb} GB`);
183
+ console.log(`price $${q.hourlyUsd.toFixed(4)}/hr${rules.length ? ` (${rules.join(", ")})` : ""}`);
184
+ console.log(`this run ${q.runSeconds} s ≈ $${q.estimatedUsd.toFixed(6)} ($${q.runHourlyUsd.toFixed(4)}/hr)`);
185
+ const next = q.candidates.filter((c) => !c.skip && c.provider !== q.provider).slice(0, 3).map((c) => c.provider);
186
+ if (next.length)
187
+ console.log(`fallback ${next.join(" → ")}`);
188
+ return;
189
+ }
157
190
  if (cmd === "route") {
158
191
  const plan = router.plan(spec, route);
159
192
  if (values.json)
@@ -292,10 +325,15 @@ async function main() {
292
325
  return;
293
326
  }
294
327
  if (cmd === "bench") {
328
+ const job = (values.long ? "long" : values.job ?? "short");
329
+ if (!(job in TASKS))
330
+ return console.error(`--job must be one of: ${Object.keys(TASKS).join(", ")}`);
295
331
  const rows = await bench({
296
332
  router,
297
333
  providers,
298
334
  runs: num(values.runs) ?? 3,
335
+ task: values.task ? job : undefined,
336
+ parallel: num(values.parallel),
299
337
  spec: { ...spec, timeoutMinutes: spec.timeoutMinutes ?? 5 },
300
338
  onProgress: (m) => console.error(m),
301
339
  });
@@ -309,7 +347,7 @@ async function main() {
309
347
  console.error(`\n${r.provider} last error: ${r.lastError}`);
310
348
  if (values.share) {
311
349
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
312
- const report = makeReport(rows, { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by });
350
+ const report = makeReport(rows, { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by, task: values.task ? TASKS[job].version : undefined });
313
351
  const left = rows.filter((r) => !benchmarksPublishable(r.provider)).map((r) => r.provider);
314
352
  if (left.length)
315
353
  console.log(`\nleft out of the shared report: ${left.join(", ")} (their terms don't allow publishing benchmarks)`);
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Candidate, Size } from "./router.js";
1
+ import type { Candidate, Quote, Size } from "./router.js";
2
2
  import type { Attempt, ExecOptions, ExecResult, RouteOptions, RouterErrorCode, SandboxSpec } from "./types.js";
3
3
  /**
4
4
  * Client for the sandboxrouter HTTP API: the hosted service (one key, prepaid credits) or your own
@@ -31,6 +31,8 @@ export declare class Client {
31
31
  }[]>;
32
32
  /** Dry run: which providers would be tried, in order, each with its price, size and any reason it's skipped. */
33
33
  route(spec?: SandboxSpec, route?: RouteOptions): Promise<Candidate[]>;
34
+ /** Where a create would land and what the run would cost, without starting anything (a hosted service includes its fee). */
35
+ quote(spec?: SandboxSpec, route?: RouteOptions): Promise<Quote>;
34
36
  /**
35
37
  * Start a sandbox on the first provider that works, as the server routes it. With `idempotencyKey`,
36
38
  * sending the same create again (say, after a timeout) returns the same sandbox instead of starting
package/dist/client.js CHANGED
@@ -51,6 +51,10 @@ export class Client {
51
51
  async route(spec = {}, route = {}) {
52
52
  return (await this.json("POST", "/v1/route", { ...spec, ...route })).candidates;
53
53
  }
54
+ /** Where a create would land and what the run would cost, without starting anything (a hosted service includes its fee). */
55
+ async quote(spec = {}, route = {}) {
56
+ return this.json("POST", "/v1/quote", { ...spec, ...route });
57
+ }
54
58
  /**
55
59
  * Start a sandbox on the first provider that works, as the server routes it. With `idempotencyKey`,
56
60
  * sending the same create again (say, after a timeout) returns the same sandbox instead of starting
package/dist/index.d.ts CHANGED
@@ -2,8 +2,9 @@ export { checkProvider, CHECK_STEPS, type CheckReport, type CheckResult, type Ch
2
2
  export { Ledger, defaultLedgerFile, type LedgerEntry } from "./ledger.js";
3
3
  export { conformanceTable, loadConformance, type ConformanceRow, type SavedCheck } from "./conformance.js";
4
4
  export { gc, listOpen, isGone, type GcResult, type OpenSandbox } from "./gc.js";
5
- export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, type Candidate, type RouterOptions, type SandboxPrice, type Size, } from "./router.js";
5
+ export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, rankUsd, runHours, usdPerHour, type Candidate, type Quote, type RouterOptions, type SandboxPrice, type Size, } from "./router.js";
6
6
  export { VERIFIED, FAILING } from "./verified.js";
7
+ export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
7
8
  export { BILLED_VS_LIST } from "./billing.js";
8
9
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
9
10
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd, type ProviderInfo } from "./catalog.js";
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@ export { checkProvider, CHECK_STEPS } from "./check.js";
2
2
  export { Ledger, defaultLedgerFile } from "./ledger.js";
3
3
  export { conformanceTable, loadConformance } from "./conformance.js";
4
4
  export { gc, listOpen, isGone } from "./gc.js";
5
- export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, } from "./router.js";
5
+ export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, rankUsd, runHours, usdPerHour, } from "./router.js";
6
6
  export { VERIFIED, FAILING } from "./verified.js";
7
+ export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
7
8
  export { BILLED_VS_LIST } from "./billing.js";
8
9
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
9
10
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd } from "./catalog.js";
@@ -0,0 +1,5 @@
1
+ import type { Provider, ProviderId } from "./types.js";
2
+ /** Ids `providerWithKey` takes. */
3
+ export declare const KEYED_PROVIDERS: ProviderId[];
4
+ /** An adapter for `id` that uses `key` and no key from the environment. Throws for other providers or an empty key. */
5
+ export declare function providerWithKey(id: ProviderId, key: string): Provider;
package/dist/keyed.js ADDED
@@ -0,0 +1,44 @@
1
+ import { Agent37Provider } from "./providers/agent37.js";
2
+ import { BoatProvider } from "./providers/boat.js";
3
+ import { DaytonaProvider } from "./providers/daytona.js";
4
+ import { E2BProvider } from "./providers/e2b.js";
5
+ import { FreestyleProvider } from "./providers/freestyle.js";
6
+ import { MaritimeProvider } from "./providers/maritime.js";
7
+ import { NovitaProvider } from "./providers/novita.js";
8
+ import { OpenScaleProvider } from "./providers/openscale.js";
9
+ import { SailProvider } from "./providers/sail.js";
10
+ import { SpritesProvider } from "./providers/sprites.js";
11
+ import { SuperserveProvider } from "./providers/superserve.js";
12
+ import { TensorlakeProvider } from "./providers/tensorlake.js";
13
+ /**
14
+ * Providers whose adapter takes a single API key and sends only that key: given one here, nothing it
15
+ * does reads a key from this process's environment. A service running sandboxes on its own accounts can
16
+ * let a user bring their own key for these without ever charging the service's account for that user's
17
+ * sandboxes (test/keyed.test.ts checks every request carries the key given). Base URLs still come from
18
+ * the environment, as the operator set them; a user can't point the service at another host.
19
+ */
20
+ const KEYED = {
21
+ agent37: (k) => new Agent37Provider(k),
22
+ boat: (k) => new BoatProvider(k),
23
+ daytona: (k) => new DaytonaProvider(k),
24
+ e2b: (k) => new E2BProvider(k),
25
+ freestyle: (k) => new FreestyleProvider(k),
26
+ maritime: (k) => new MaritimeProvider(k),
27
+ novita: (k) => new NovitaProvider(k),
28
+ openscale: (k) => new OpenScaleProvider(k),
29
+ sail: (k) => new SailProvider(k),
30
+ sprites: (k) => new SpritesProvider(k),
31
+ superserve: (k) => new SuperserveProvider(k),
32
+ tensorlake: (k) => new TensorlakeProvider(k),
33
+ };
34
+ /** Ids `providerWithKey` takes. */
35
+ export const KEYED_PROVIDERS = Object.keys(KEYED);
36
+ /** An adapter for `id` that uses `key` and no key from the environment. Throws for other providers or an empty key. */
37
+ export function providerWithKey(id, key) {
38
+ const make = KEYED[id];
39
+ if (!make)
40
+ throw new Error(`${id} can't take a key this way; it takes: ${KEYED_PROVIDERS.join(", ")}`);
41
+ if (typeof key !== "string" || !key.trim())
42
+ throw new Error(`the ${id} key is empty`);
43
+ return make(key.trim());
44
+ }
@@ -1,3 +1,4 @@
1
+ import { type PhaseMs } from "./task.js";
1
2
  import type { BenchRow } from "./bench.js";
2
3
  import type { ProviderId, SandboxSpec } from "./types.js";
3
4
  /**
@@ -15,6 +16,8 @@ export interface BenchReport {
15
16
  by?: string;
16
17
  runs: number;
17
18
  spec: SandboxSpec;
19
+ /** Set when the run also timed the standard task (`bench --task`): which version of it (src/task.ts). */
20
+ task?: string;
18
21
  node: string;
19
22
  platform: string;
20
23
  rows: BenchRow[];
@@ -25,6 +28,7 @@ export declare function makeReport(rows: BenchRow[], opts: {
25
28
  spec: SandboxSpec;
26
29
  label?: string;
27
30
  by?: string;
31
+ task?: string;
28
32
  }): BenchReport;
29
33
  export declare function loadReports(dir: string): BenchReport[];
30
34
  export interface LeaderRow {
@@ -49,5 +53,34 @@ export interface LeaderRow {
49
53
  * an old run can't outvote a newer one and one heavy submitter can't skew a provider.
50
54
  */
51
55
  export declare function aggregate(reports: BenchReport[]): LeaderRow[];
56
+ export interface TaskRow {
57
+ provider: ProviderId;
58
+ name: string;
59
+ /** The size it ran at: 2 vCPU / 4 GB, or the provider's fixed default size. */
60
+ size: {
61
+ vcpu: number;
62
+ memoryGb: number;
63
+ };
64
+ createMs: number;
65
+ taskMs: number;
66
+ phasesMs: PhaseMs;
67
+ /** USD per hour at that size: list price, corrected by measured bills (`BILLED_VS_LIST`). */
68
+ hourlyUsd: number;
69
+ /** What one task is billed: start plus task, with the minimum charge, billing step and per-sandbox fee; active-CPU providers by the CPU time it used. */
70
+ taskUsd: number;
71
+ /** CPU time the task used across all vCPUs (median), where the sandbox shows /proc/stat. */
72
+ cpuMs?: number;
73
+ /** True when the provider bills CPU only while busy, so `taskUsd` counts `cpuMs` rather than every core. */
74
+ activeCpu: boolean;
75
+ minimumSeconds: number;
76
+ perSandboxUsd: number;
77
+ measuredAt: string;
78
+ }
79
+ /**
80
+ * Cost of the standard task (src/task.ts) per provider, from reports made with `bench --task` at
81
+ * `version` (the short task's by default; TASKS.long.version for `--long`): each provider's latest run
82
+ * from each location, then the median across locations (as `aggregate` does). Cheapest task first.
83
+ */
84
+ export declare function taskTable(reports: BenchReport[], version?: string): TaskRow[];
52
85
  /** One self-contained HTML page: a sorted table with an inline bar per measure, each on its own scale. */
53
86
  export declare function renderLeaderboard(reports: BenchReport[]): string;
@@ -1,6 +1,8 @@
1
1
  import { readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { benchmarksPublishable, CATALOG, fittingSpec, hourlyCost } from "./catalog.js";
3
+ import { benchmarksPublishable, billingRules, CATALOG, cpuHourlyAtFull, fittingSpec, hourlyCost } from "./catalog.js";
4
+ import { BILLED_VS_LIST } from "./billing.js";
5
+ import { TASK_VERSION, taskByVersion, taskUsd } from "./task.js";
4
6
  import { median } from "./bench-store.js";
5
7
  export function makeReport(rows, opts) {
6
8
  return {
@@ -12,6 +14,7 @@ export function makeReport(rows, opts) {
12
14
  runs: opts.runs,
13
15
  // Only the shape matters for comparison; never ship env or metadata.
14
16
  spec: { vcpu: opts.spec.vcpu, memoryGb: opts.spec.memoryGb },
17
+ ...(opts.task ? { task: opts.task } : {}),
15
18
  node: process.version,
16
19
  platform: `${process.platform}-${process.arch}`,
17
20
  // Providers whose terms forbid publishing benchmarks stay out of anything meant to be shared.
@@ -77,6 +80,63 @@ export function aggregate(reports) {
77
80
  });
78
81
  return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
79
82
  }
83
+ /**
84
+ * Cost of the standard task (src/task.ts) per provider, from reports made with `bench --task` at
85
+ * `version` (the short task's by default; TASKS.long.version for `--long`): each provider's latest run
86
+ * from each location, then the median across locations (as `aggregate` does). Cheapest task first.
87
+ */
88
+ export function taskTable(reports, version = TASK_VERSION) {
89
+ const def = taskByVersion(version);
90
+ if (!def)
91
+ return [];
92
+ const latest = new Map();
93
+ for (const rep of reports) {
94
+ if (rep.task !== version)
95
+ continue;
96
+ for (const r of rep.rows) {
97
+ if (!KNOWN.has(r.provider) || !r.taskPhasesMs || r.medianTaskMs === undefined || r.medianCreateMs === undefined)
98
+ continue;
99
+ const key = `${r.provider}\u0000${rep.label ?? ""}`;
100
+ const seen = latest.get(key);
101
+ if (!seen || rep.date > seen.date)
102
+ latest.set(key, { row: r, date: rep.date });
103
+ }
104
+ }
105
+ const by = new Map();
106
+ for (const x of latest.values())
107
+ by.set(x.row.provider, [...(by.get(x.row.provider) ?? []), x]);
108
+ const rows = [...by.entries()].map(([id, xs]) => {
109
+ const rs = xs.map((x) => x.row);
110
+ const createMs = median(rs.map((r) => r.medianCreateMs));
111
+ const taskMillis = median(rs.map((r) => r.medianTaskMs));
112
+ const phasesMs = Object.fromEntries(def.phases.map((p) => [p.id, median(rs.map((r) => r.taskPhasesMs[p.id]))]));
113
+ const size = fittingSpec(id);
114
+ const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
115
+ const hourlyUsd = hourlyCost(id, size) * ratio;
116
+ const rules = billingRules(id);
117
+ const cpus = rs.map((r) => r.medianTaskCpuMs).filter((n) => typeof n === "number");
118
+ // A container can show the whole host's /proc/stat (Daytona does): a reading beyond what the sandbox's
119
+ // own vCPUs could do in that time isn't the sandbox's, so it's dropped and the task is priced at full CPU.
120
+ const read = cpus.length === rs.length ? median(cpus) : undefined;
121
+ const cpuMs = read !== undefined && read <= size.vcpu * taskMillis * 1.1 ? read : undefined;
122
+ return {
123
+ provider: id,
124
+ name: CATALOG.find((c) => c.id === id).name,
125
+ size,
126
+ createMs,
127
+ taskMs: taskMillis,
128
+ phasesMs,
129
+ hourlyUsd,
130
+ taskUsd: taskUsd(id, size, createMs, taskMillis, cpuMs, ratio),
131
+ ...(cpuMs !== undefined ? { cpuMs } : {}),
132
+ activeCpu: cpuHourlyAtFull(id, size) > 0,
133
+ minimumSeconds: rules.minSeconds,
134
+ perSandboxUsd: rules.perSandboxUsd,
135
+ measuredAt: xs.map((x) => x.date).sort().at(-1),
136
+ };
137
+ });
138
+ return rows.sort((a, b) => a.taskUsd - b.taskUsd || a.provider.localeCompare(b.provider));
139
+ }
80
140
  const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
81
141
  function bar(value, max, text, tip) {
82
142
  if (value === undefined)