@sandboxrouter/sdk 0.10.0 → 0.12.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 +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 +227 -5
  14. package/dist/compare.d.ts +48 -0
  15. package/dist/compare.js +78 -0
  16. package/dist/index.d.ts +3 -0
  17. package/dist/index.js +3 -0
  18. package/dist/leaderboard.d.ts +74 -2
  19. package/dist/leaderboard.js +117 -7
  20. package/dist/ledger.d.ts +2 -0
  21. package/dist/ledger.js +12 -1
  22. package/dist/price-index.d.ts +54 -0
  23. package/dist/price-index.js +50 -0
  24. package/dist/providers/beam.js +4 -0
  25. package/dist/providers/blaxel.js +4 -0
  26. package/dist/providers/boat.js +3 -1
  27. package/dist/providers/daytona.js +4 -0
  28. package/dist/providers/deno.js +4 -0
  29. package/dist/providers/e2b.d.ts +2 -0
  30. package/dist/providers/e2b.js +4 -0
  31. package/dist/providers/hopx.js +4 -0
  32. package/dist/providers/langsmith.js +4 -0
  33. package/dist/providers/modal.js +11 -2
  34. package/dist/providers/morph.js +4 -0
  35. package/dist/providers/runloop.js +4 -0
  36. package/dist/providers/sprites.js +4 -0
  37. package/dist/providers/tensorlake.js +4 -0
  38. package/dist/providers/vercel.js +4 -0
  39. package/dist/published.d.ts +2 -0
  40. package/dist/published.js +2087 -0
  41. package/dist/recommend.d.ts +117 -0
  42. package/dist/recommend.js +103 -0
  43. package/dist/results.js +93 -1
  44. package/dist/router.d.ts +45 -0
  45. package/dist/router.js +69 -4
  46. package/dist/submit.d.ts +6 -0
  47. package/dist/submit.js +70 -0
  48. package/dist/task.d.ts +17 -2
  49. package/dist/task.js +74 -19
  50. package/dist/types.d.ts +5 -0
  51. package/dist/util.d.ts +2 -0
  52. package/dist/util.js +2 -0
  53. package/package.json +1 -1
package/dist/catalog.js CHANGED
@@ -91,7 +91,7 @@ const ENTRIES = [
91
91
  gbHour: 0.0162,
92
92
  note: "per second, plus disk above 5 GiB",
93
93
  source: "https://www.daytona.io/pricing",
94
- checked: "2026-11-13",
94
+ checked: "2026-11-17",
95
95
  },
96
96
  capabilities: ["pause", "custom-image"],
97
97
  limits: { maxVcpu: 4, maxMemoryGb: 8 },
@@ -105,10 +105,12 @@ const ENTRIES = [
105
105
  name: "Modal",
106
106
  pricing: {
107
107
  vcpuHour: 0.070956,
108
+ reservesCpu: true,
109
+ cpuFloor: 0.125,
108
110
  gbHour: 0.024012,
109
111
  note: "sandbox rates, per second ($0.00003942 per physical core = 2 vCPUs); GPUs extra; region pinning x1.15-1.75; Starter includes $30/mo credit",
110
112
  source: "https://modal.com/pricing",
111
- checked: "2026-11-05",
113
+ checked: "2026-11-17",
112
114
  },
113
115
  capabilities: ["gpu", "custom-image"],
114
116
  limits: { maxVcpu: 64, maxMemoryGb: 256 },
@@ -121,6 +123,7 @@ const ENTRIES = [
121
123
  pricing: {
122
124
  minSeconds: 60,
123
125
  minimumCovers: "memory",
126
+ cpuMeteredPerVm: true,
124
127
  vcpuHour: 0.128,
125
128
  gbHour: 0.0212,
126
129
  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",
@@ -317,7 +320,7 @@ ENTRIES.push({
317
320
  gbHour: 0,
318
321
  note: "flat $0.03 per session-hour (built-in Shell pools), billed per allocated session in 1-hour increments, East US; needs a session pool you create once",
319
322
  source: "https://learn.microsoft.com/en-us/azure/container-apps/billing#dynamic-sessions",
320
- checked: "2026-11-04",
323
+ checked: "2026-11-17",
321
324
  },
322
325
  capabilities: [],
323
326
  // Per-session size isn't published; placeholder until measured with nproc / free.
@@ -368,7 +371,7 @@ ENTRIES.push({
368
371
  gbHour: 0.008928,
369
372
  note: "per second; Default QoS, Hong Kong and regions outside mainland China; disk separately $0.00025308/GiB-h; code-interpreter-v1 template is 2 vCPU / 2 GiB with 10 GiB disk (E2B-compatible API)",
370
373
  source: "https://www.alibabacloud.com/help/en/agent-sandbox/product-overview/billing-overview",
371
- checked: "2026-11-05",
374
+ checked: "2026-11-17",
372
375
  },
373
376
  capabilities: ["custom-image"],
374
377
  // No published maximum; the default template is 2 vCPU / 2 GB, so bigger requests go elsewhere.
@@ -443,7 +446,7 @@ ENTRIES.push({
443
446
  gbHour: 0.001,
444
447
  note: "per second on allocated size; no platform fee or minimum; paused = free; size comes from the template (E2B-compatible API); Singapore only; needs a pay-as-you-go key",
445
448
  source: "https://openscale.so/sandboxes",
446
- checked: "2026-11-05",
449
+ checked: "2026-11-17",
447
450
  },
448
451
  capabilities: ["pause", "custom-image"],
449
452
  limits: { maxVcpu: 8, maxMemoryGb: 16 },
@@ -474,7 +477,7 @@ ENTRIES.push({
474
477
  gbHour: 0.025,
475
478
  note: "billed on CPU time, not wall clock (estimate assumes both vCPUs busy); fixed 2 vCPU, 0.75-4 GB, max 30 min lifetime; needs a paid Deno Deploy plan",
476
479
  source: "https://deno.com/sandbox",
477
- checked: "2026-11-04",
480
+ checked: "2026-11-17",
478
481
  },
479
482
  capabilities: ["custom-image"],
480
483
  limits: { maxVcpu: 2, maxMemoryGb: 4 },
@@ -502,7 +505,7 @@ ENTRIES.push({
502
505
  gbHour: 0.00225,
503
506
  note: "per second while running on fixed sizes (2/4, 4/8, 8/16); paused or stopped boxes bill only /data beyond the included disk ($0.00011/GiB-h); Pro $20/mo includes $20 credits; free plan: 1 box at 4/8",
504
507
  source: "https://instabox.sh/docs/pricing.md",
505
- checked: "2026-11-05",
508
+ checked: "2026-11-17",
506
509
  },
507
510
  capabilities: ["pause", "custom-image"],
508
511
  limits: { maxVcpu: 8, maxMemoryGb: 16 },
@@ -536,7 +539,7 @@ ENTRIES.push({
536
539
  gbHour: 0.01845,
537
540
  note: "per second; memory must be 2 to 6 GiB per vCPU; storage $0.000123/GiB-h; 8 LSU ($8) of sandbox usage a month included; Developer plan max 10 sandboxes",
538
541
  source: "https://www.langchain.com/pricing",
539
- checked: "2026-11-05",
542
+ checked: "2026-11-17",
540
543
  },
541
544
  capabilities: ["pause", "custom-image"],
542
545
  // Not published; 16 vCPU / 96 GiB stays inside the 6 GiB per vCPU band. Real runs will tell.
@@ -568,9 +571,9 @@ ENTRIES.push({
568
571
  pricing: {
569
572
  vcpuHour: 0.1,
570
573
  gbHour: 0,
571
- note: "billed per active CPU core-hour only (memory and idle time free); estimate assumes every core of the box busy; fixed sizes 2/4, 4/8, 8/16",
574
+ note: "billed per active CPU core-hour only (memory and idle time free); estimate assumes every core of the box busy at the Small rate; fixed sizes 2/4, 4/8, 8/16, and the pricing page lists $0.20 (4/8) and $0.40 (8/16) per active CPU hour without saying whether that is per core or per box",
572
575
  source: "https://upstash.com/pricing/box",
573
- checked: "2026-11-04",
576
+ checked: "2026-11-17",
574
577
  },
575
578
  capabilities: [],
576
579
  limits: { maxVcpu: 8, maxMemoryGb: 16 },
@@ -789,7 +792,8 @@ export function hourlyCost(id, spec = {}) {
789
792
  /** The CPU part of the full-use hourly price for an "active-cpu" provider; 0 for providers that bill allocated capacity. */
790
793
  export function cpuHourlyAtFull(id, spec = {}) {
791
794
  const p = info(id);
792
- if (p.billing !== "active-cpu")
795
+ const reserved = p.pricing.reservesCpu && (spec.cpuUtilization ?? 1) < 1;
796
+ if (p.billing !== "active-cpu" && !reserved)
793
797
  return 0;
794
798
  const fixed = fixedSize(id, spec);
795
799
  if (fixed)
package/dist/check.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { Router } from "./router.js";
2
2
  import type { ProviderId, SandboxSpec } from "./types.js";
3
3
  /** Every step `check` runs, in order. Each provider's saved report is scored against this list. */
4
+ /** An account that can't start sandboxes at all: no credit, a frozen workspace, or a key or plan without access. */
5
+ export declare const ACCOUNT_BLOCKED: RegExp;
4
6
  export declare const CHECK_STEPS: readonly ["create", "exec: stdout, stderr, exit code", "exec: env and cwd", "exec: UTF-8 output", "exec: streaming", "files: binary round-trip", "files: 1 MB round-trip", "files: missing file is an error", "files: visible to commands", "exec: command timeout", "exec: timed-out command was stopped", "pause and resume", "kill", "killed sandbox is gone"];
5
7
  export type CheckStatus = "pass" | "fail" | "skip" | "info";
6
8
  export interface CheckResult {
package/dist/check.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { fixedSize } from "./catalog.js";
2
2
  /** Every step `check` runs, in order. Each provider's saved report is scored against this list. */
3
+ /** An account that can't start sandboxes at all: no credit, a frozen workspace, or a key or plan without access. */
4
+ export const ACCOUNT_BLOCKED = /insufficient_credits|insufficient credit|workspace has been frozen|spending limit|HTTP 403|\b403\b.*Forbidden|Payment Required/i;
3
5
  export const CHECK_STEPS = [
4
6
  "create",
5
7
  "exec: stdout, stderr, exit code",
@@ -53,6 +55,12 @@ export async function checkProvider(router, provider, opts = {}) {
53
55
  notRun = "the account running the check can't pay (402)";
54
56
  return { status: "skip", detail: `the account can't pay (402), so this run says nothing about ${provider}: ${msg}` };
55
57
  }
58
+ // The account itself can't start sandboxes (no credit, a frozen workspace, a plan without sandboxes): that's the
59
+ // account running the check, not the provider.
60
+ if (ACCOUNT_BLOCKED.test(msg)) {
61
+ notRun = "the account running the check can't start sandboxes (credit, plan or a frozen workspace)";
62
+ return { status: "skip", detail: `${notRun}, so this run says nothing about ${provider}: ${msg}` };
63
+ }
56
64
  // The provider's SDK isn't installed where the check runs: that says nothing about the provider.
57
65
  const pkg = /needs the "([^"]+)" package/.exec(msg)?.[1];
58
66
  if (!pkg)
package/dist/cli.js CHANGED
@@ -2,8 +2,13 @@
2
2
  import { parseArgs } from "node:util";
3
3
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { platform, arch } from "node:os";
5
- import { bench, benchMarkdown } from "./bench.js";
5
+ import { ACCOUNT_ERROR, bench, benchMarkdown, NETWORK_ERROR } from "./bench.js";
6
6
  import { TASKS } from "./task.js";
7
+ import { submitReport } from "./submit.js";
8
+ import { burst, spreadBurst } from "./burst.js";
9
+ import { compare } from "./compare.js";
10
+ import { agentBench, AGENT_TASK_VERSION } from "./agent-bench.js";
11
+ /** Errors that mean the network between here and the provider failed, not the provider. */
7
12
  import { costMarkdown, costRun, settle } from "./cost.js";
8
13
  import { checkProvider } from "./check.js";
9
14
  import { gc, listOpen } from "./gc.js";
@@ -12,6 +17,8 @@ import { loadReports, makeReport, renderLeaderboard } from "./leaderboard.js";
12
17
  import { DEFAULT_MEMORY_GB, DEFAULT_VCPU, accessLabel, benchmarksPublishable, hourlyCost, listingOrder, planLabel, unfit } from "./catalog.js";
13
18
  import { Router, rankUsd, runHours } from "./router.js";
14
19
  import { createApp } from "./server.js";
20
+ import { PUBLISHED } from "./published.js";
21
+ import { recommend } from "./recommend.js";
15
22
  import { RouterError } from "./types.js";
16
23
  const HELP = `sandboxrouter: one API for every sandbox provider
17
24
 
@@ -19,6 +26,13 @@ Usage:
19
26
  sandboxrouter providers [--vcpu N] [--memory GB] price table + which keys are set
20
27
  sandboxrouter route [spec flags] [route flags] dry run: the order providers would be tried
21
28
  sandboxrouter quote [spec/route flags] [--json] where a create would land and what the run would cost
29
+ sandboxrouter recommend [--job short|long|python|download|agent|repo|start] [--count N] [--priority value|cost|speed]
30
+ [--reuse] [--provider a,b] [--json]
31
+ which provider for a job, from the published benchmarks: per successful run, with start
32
+ times under load for --count 10 and up; --provider limits it to the ones you name
33
+ sandboxrouter compare "<cmd>" [--setup "<cmd>"] [--runs 3] [--provider a,b] [--seconds 600] [--json]
34
+ your own workload on each provider: the same setup and command in a new sandbox, with how
35
+ often it worked, start/setup/command time and the estimated cost; failures are counted
22
36
  sandboxrouter run "<cmd>" [spec flags] [route flags] [--keep]
23
37
  sandboxrouter check --provider ID[,ID] | --all [--json] [--save [dir]] [--retry] [--out FILE] [--by GITHUB_USER]
24
38
  test providers for real: exec, env, UTF-8, streaming, files, timeout, pause,
@@ -29,11 +43,20 @@ Usage:
29
43
  sandboxrouter ls [--json] sandboxes this machine started that weren't killed
30
44
  sandboxrouter gc [--all | --older-than MIN] [--dry-run]
31
45
  kill leaked sandboxes: by default those past their lifetime
32
- sandboxrouter bench [--runs 3] [--provider a,b] [--task [--long]] [--parallel N] [--json] [--share [--label "where you ran it"] [--by GITHUB_USER]]
46
+ sandboxrouter bench [--runs 3] [--provider a,b] [--task [--long]] [--parallel N] [--json] [--share [--label "where you ran it"] [--by GITHUB_USER] [--submit]]
33
47
  --task also runs the same fixed job in each sandbox (hash 512 MB on 1 core,
34
48
  then on 2, write 256 MB to disk) and prices it with each provider's billing rules;
35
49
  --long runs that job 40 times in a row (minutes); --job python (a pure-Python script)
36
50
  or --job download (53 MB over HTTPS) runs another job. --parallel benches N providers at once
51
+ sandboxrouter burst [--n 100] [--provider a,b] [--job python|agent] [--parallel 1] [--share [--label PLACE] [--by GITHUB_USER] [--submit]]
52
+ start --n sandboxes at once on each provider (time to interactive at p50/p95/p99, how many
53
+ started); --job runs a standard job in each: python for RL-style rollouts, agent for parallel agents;
54
+ --spread asks for all N at once over the providers together, moving sandboxes from any provider
55
+ that hits a limit to the next one with room; shares follow each provider's measured capacity
56
+ at once (--even: equal shares)
57
+ sandboxrouter agentbench [--runs 5] [--provider a,b] [--model gemini-3.5-flash] [--parallel 4] [--share ...]
58
+ a real agent (Gemini, GEMINI_API_KEY) does the same task in a sandbox on each provider;
59
+ the key stays here and only its shell commands run in the sandbox
37
60
  sandboxrouter cost run [--provider a,b] [--minutes 10] [--vcpu 2 --memory 4] [--no-load] [--out FILE] [--by GITHUB_USER]
38
61
  start one sandbox per provider for a fixed time with every core busy, record
39
62
  the size it really got and the list-price prediction
@@ -76,7 +99,16 @@ const { values, positionals } = parseArgs({
76
99
  task: { type: "boolean" },
77
100
  long: { type: "boolean" },
78
101
  job: { type: "string" },
102
+ count: { type: "string" },
103
+ priority: { type: "string" },
104
+ reuse: { type: "boolean" },
105
+ spread: { type: "boolean" },
106
+ setup: { type: "string" },
107
+ seconds: { type: "string" },
108
+ even: { type: "boolean" },
79
109
  parallel: { type: "string" },
110
+ n: { type: "string" },
111
+ model: { type: "string" },
80
112
  json: { type: "boolean" },
81
113
  port: { type: "string" },
82
114
  host: { type: "string" },
@@ -86,6 +118,7 @@ const { values, positionals } = parseArgs({
86
118
  control: { type: "boolean" },
87
119
  out: { type: "string" },
88
120
  share: { type: "boolean" },
121
+ submit: { type: "boolean" },
89
122
  cors: { type: "string" },
90
123
  label: { type: "string" },
91
124
  all: { type: "boolean" },
@@ -170,6 +203,52 @@ async function main() {
170
203
  ].join("\n"));
171
204
  return;
172
205
  }
206
+ if (cmd === "compare") {
207
+ const command = rest[0];
208
+ if (!command)
209
+ throw new RouterError('usage: sandboxrouter compare "<cmd>" [--setup "<cmd>"] [--runs 3] [--provider a,b]');
210
+ const ids = providers ?? router.registered().filter((id) => router.isConfigured(id));
211
+ const rows = await compare({ router, providers: ids, command, setup: values.setup, runs: num(values.runs), timeoutSeconds: num(values.seconds), parallel: num(values.parallel), onProgress: (m) => console.error(m) });
212
+ if (values.json)
213
+ return console.log(JSON.stringify(rows, null, 2));
214
+ const s = (v) => (v === undefined ? "n/a" : `${(v / 1000).toFixed(1)} s`);
215
+ const usd = (v) => (v === undefined ? "n/a" : v >= 0.01 ? `$${v.toFixed(3)}` : `$${v.toPrecision(2)}`);
216
+ console.log(`\nsandboxrouter compare: ${JSON.stringify(command)}${values.setup ? `, after setup ${JSON.stringify(values.setup)}` : ""}\n`);
217
+ console.log("| Provider | Worked | Start | Setup | Command | Total | Est. cost per run |\n|---|---|---|---|---|---|---|");
218
+ for (const r of rows) {
219
+ console.log(`| ${r.provider} | ${r.ok}/${r.runs} | ${s(r.medianStartMs)} | ${values.setup ? s(r.medianSetupMs) : "-"} | ${s(r.medianCommandMs)} | ${s(r.medianTotalMs)} | ${usd(r.estimatedUsd)}${r.billMeasured ? " (bill measured)" : ""} |`);
220
+ }
221
+ const bad = rows.filter((r) => r.error);
222
+ if (bad.length)
223
+ console.log(`\nFailures:\n${bad.map((r) => `- ${r.provider}: ${r.startFailed} didn't start, ${r.setupFailed} failed setup, ${r.commandFailed} failed the command. ${r.error}`).join("\n")}`);
224
+ console.log("\nTimes are measured medians of the runs that worked. Costs are estimates from each provider's billing rules for the sandbox's whole life (start, setup, command), not bills.");
225
+ return;
226
+ }
227
+ if (cmd === "recommend") {
228
+ const jobs = ["start", "short", "long", "python", "download", "agent", "repo"];
229
+ const priorities = ["value", "cost", "speed"];
230
+ const job = (values.job ?? "short");
231
+ const priority = (values.priority ?? "value");
232
+ if (!jobs.includes(job))
233
+ throw new RouterError(`--job must be one of ${jobs.join(", ")}`);
234
+ if (!priorities.includes(priority))
235
+ throw new RouterError(`--priority must be one of ${priorities.join(", ")}`);
236
+ const count = values.count === undefined ? 1 : Number(values.count);
237
+ if (!Number.isInteger(count) || count < 1)
238
+ throw new RouterError("--count must be a whole number, 1 or more");
239
+ const r = recommend(PUBLISHED, { job, count, priority, reuse: !!values.reuse, providers: values.provider?.split(",").map((s) => s.trim()) });
240
+ if (values.json)
241
+ return console.log(JSON.stringify(r, null, 2));
242
+ const secs = (s) => (s >= 10 ? `${s.toFixed(0)} s` : `${s.toFixed(1)} s`);
243
+ const money = (n) => (n === undefined ? "n/a" : n >= 1 ? `$${n.toFixed(2)}` : n >= 0.01 ? `$${n.toFixed(3)}` : `$${n.toPrecision(2)}`);
244
+ console.log(r.basis);
245
+ console.log(`Data through ${r.dataThrough.slice(0, 10)}; sandboxrouter.ai/methodology explains how it's measured.\n`);
246
+ for (const x of r.results.slice(0, 10)) {
247
+ const cost = job === "start" ? `${money(x.hourlyUsd)}/h` : count > 1 ? `${money(x.usdTotal)} for ${count}` : money(x.usdEach);
248
+ console.log(`${String(x.rank).padStart(2)}. ${x.name.padEnd(34)} ${secs(x.secondsEach).padStart(6)} ${cost.padStart(14)} value ${x.valueScore.toFixed(2)}${x.notes.length ? ` · ${x.notes.join(" · ")}` : ""}`);
249
+ }
250
+ return;
251
+ }
173
252
  if (cmd === "quote") {
174
253
  const q = router.quote(spec, route);
175
254
  if (values.json)
@@ -324,6 +403,125 @@ async function main() {
324
403
  process.exitCode = 1;
325
404
  return;
326
405
  }
406
+ if (cmd === "agentbench") {
407
+ const apiKey = process.env.GEMINI_API_KEY;
408
+ if (!apiKey)
409
+ return console.error("agentbench needs GEMINI_API_KEY (it stays on this machine; only shell commands reach the sandbox)");
410
+ const model = values.model ?? "gemini-3.5-flash";
411
+ const ids = providers ?? router.registered().filter((id) => router.isConfigured(id));
412
+ const rows = await agentBench({ router, providers: ids, runs: num(values.runs) ?? 5, apiKey, model, parallel: num(values.parallel), onProgress: (m) => console.error(m) });
413
+ if (values.json)
414
+ return console.log(JSON.stringify(rows, null, 2));
415
+ console.log(`\nsandboxrouter agentbench: ${model}, ${num(values.runs) ?? 5} runs each\n`);
416
+ console.log("| Provider | Done right | Wall | Waiting on model | Sandbox CPU | Turns | Sandbox cost |\n|---|---|---|---|---|---|---|");
417
+ const s = (v) => (v === undefined ? "n/a" : `${(v / 1000).toFixed(1)} s`);
418
+ for (const r of rows)
419
+ console.log(`| ${r.provider} | ${r.ok}/${r.runs} | ${s(r.medianWallMs)} | ${s(r.medianModelMs)} | ${s(r.medianCpuMs)} | ${r.medianTurns ?? "n/a"} | ${r.medianUsd === undefined ? "n/a" : `$${r.medianUsd.toFixed(6)}`} |`);
420
+ if (values.share || values.submit) {
421
+ const started = rows.filter((r) => r.medianWallMs !== undefined);
422
+ if (rows.length - started.length >= 3) {
423
+ console.error(`\nnot writing a report: ${rows.length - started.length} providers never started a session, which looks like this machine lost its connection. Run it again.`);
424
+ process.exitCode = 1;
425
+ return;
426
+ }
427
+ const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
428
+ const report = {
429
+ tool: "sandboxrouter-agent",
430
+ version,
431
+ date: new Date().toISOString(),
432
+ ...(values.label ? { label: values.label } : {}),
433
+ ...(by ? { by } : {}),
434
+ task: AGENT_TASK_VERSION,
435
+ model,
436
+ runs: num(values.runs) ?? 5,
437
+ node: process.version,
438
+ platform: `${platform()}-${arch()}`,
439
+ rows: started.filter((r) => benchmarksPublishable(r.provider)),
440
+ };
441
+ const file = values.out ?? `sandboxrouter-agent-${report.date.slice(0, 10)}-${Math.random().toString(36).slice(2, 8)}.json`;
442
+ writeFileSync(file, JSON.stringify(report, null, 2) + "\n");
443
+ if (values.submit) {
444
+ try {
445
+ console.log(`\nwrote ${file} and opened ${submitReport(file, `Real agent (${model}) on ${report.rows.length} providers, from ${report.label ?? "an unlabelled location"}.`)}`);
446
+ }
447
+ catch (err) {
448
+ console.error(`\nwrote ${file}, but couldn't open the pull request: ${err.message}`);
449
+ process.exitCode = 1;
450
+ }
451
+ }
452
+ else
453
+ console.log(`\nwrote ${file}`);
454
+ }
455
+ return;
456
+ }
457
+ if (cmd === "burst") {
458
+ const n = num(values.n) ?? 100;
459
+ const job = values.job;
460
+ if (job && !(job in TASKS))
461
+ return console.error(`--job must be one of: ${Object.keys(TASKS).join(", ")}`);
462
+ const ids = providers ?? router.registered().filter((id) => router.isConfigured(id));
463
+ if (values.spread) {
464
+ // One burst over all of them: round-robin, and a provider that says no hands its sandboxes to the next.
465
+ const r = await spreadBurst({ router, providers: ids, n, weights: values.even ? "even" : undefined, onProgress: (m) => console.error(m) });
466
+ if (values.out)
467
+ writeFileSync(values.out, JSON.stringify({ tool: "sandboxrouter-spread", version: JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version, date: new Date().toISOString(), label: values.label, by: values.by, ...r }, null, 2) + "\n");
468
+ if (values.json)
469
+ return console.log(JSON.stringify(r, null, 2));
470
+ const ms = (v) => (v === undefined ? "n/a" : `${v} ms`);
471
+ console.log(`\nsandboxrouter burst --spread: ${r.ok}/${r.n} started over ${ids.length} providers; p50 ${ms(r.p50Ms)}, p95 ${ms(r.p95Ms)}, p99 ${ms(r.p99Ms)}; all done in ${(r.wallMs / 1000).toFixed(1)} s; $${r.usd.toFixed(4)}`);
472
+ if (r.saturated.length)
473
+ console.log(`hit a limit and handed the rest on: ${r.saturated.join(", ")}`);
474
+ console.log("\n| Provider | Started | Moved in from a full provider | Refused |\n|---|---|---|---|");
475
+ for (const b of r.byProvider)
476
+ console.log(`| ${b.provider} | ${b.ok} | ${b.spilledIn} | ${b.refused} |`);
477
+ return;
478
+ }
479
+ const rows = await burst({ router, providers: ids, n, task: job, parallel: num(values.parallel), onProgress: (m) => console.error(m) });
480
+ if (values.json)
481
+ return console.log(JSON.stringify(rows, null, 2));
482
+ console.log(`\nsandboxrouter burst: ${n} at once${job ? `, each running the ${job} job` : ""}\n`);
483
+ console.log("| Provider | Started | p50 | p95 | p99 | All done | Burst cost |\n|---|---|---|---|---|---|---|");
484
+ for (const r of rows) {
485
+ const ms = (v) => (v === undefined ? "n/a" : `${v} ms`);
486
+ console.log(`| ${r.provider} | ${r.ok}/${r.n}${r.limited ? ` (${r.limited} limited)` : ""} | ${ms(r.p50Ms)} | ${ms(r.p95Ms)} | ${ms(r.p99Ms)} | ${(r.wallMs / 1000).toFixed(1)} s | ${r.usd === undefined ? "n/a" : `$${r.usd.toFixed(4)}`} |`);
487
+ }
488
+ if (values.share || values.submit) {
489
+ // As with bench: nothing from a run where this machine lost its connection, and no provider that never answered.
490
+ const shared = rows.filter((r) => r.ok > 0 || r.limited > 0);
491
+ const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
492
+ const report = {
493
+ tool: "sandboxrouter-burst",
494
+ version,
495
+ date: new Date().toISOString(),
496
+ ...(values.label ? { label: values.label } : {}),
497
+ ...(by ? { by } : {}),
498
+ n,
499
+ ...(job ? { task: TASKS[job].version } : {}),
500
+ node: process.version,
501
+ platform: `${platform()}-${arch()}`,
502
+ rows: shared.filter((r) => benchmarksPublishable(r.provider)),
503
+ };
504
+ if (rows.length - shared.length >= 3) {
505
+ console.error(`\nnot writing a report: ${rows.length - shared.length} providers started nothing, which looks like this machine lost its connection. Run it again.`);
506
+ process.exitCode = 1;
507
+ return;
508
+ }
509
+ const file = values.out ?? `sandboxrouter-burst-${report.date.slice(0, 10)}-${Math.random().toString(36).slice(2, 8)}.json`;
510
+ writeFileSync(file, JSON.stringify(report, null, 2) + "\n");
511
+ if (values.submit) {
512
+ try {
513
+ console.log(`\nwrote ${file} and opened ${submitReport(file, `Burst of ${n}${job ? ` running the ${job} job` : ""} on ${report.rows.length} providers, from ${report.label ?? "an unlabelled location"}.`)}`);
514
+ }
515
+ catch (err) {
516
+ console.error(`\nwrote ${file}, but couldn't open the pull request: ${err.message}`);
517
+ process.exitCode = 1;
518
+ }
519
+ }
520
+ else
521
+ console.log(`\nwrote ${file}`);
522
+ }
523
+ return;
524
+ }
327
525
  if (cmd === "bench") {
328
526
  const job = (values.long ? "long" : values.job ?? "short");
329
527
  if (!(job in TASKS))
@@ -345,15 +543,39 @@ async function main() {
345
543
  console.log(benchMarkdown(rows));
346
544
  for (const r of rows.filter((r) => r.lastError))
347
545
  console.error(`\n${r.provider} last error: ${r.lastError}`);
348
- if (values.share) {
546
+ // Several providers all failing on the network at once is this machine's connection, not theirs: a
547
+ // report from it would mark them down. Refuse to write one.
548
+ const offline = rows.filter((r) => r.failures === r.runs && r.lastError && NETWORK_ERROR.test(r.lastError));
549
+ if ((values.share || values.submit) && offline.length >= 3) {
550
+ console.error(`\nnot writing a report: ${offline.length} providers failed with network errors (${offline.map((r) => r.provider).join(", ")}), which looks like this machine lost its connection. Run it again.`);
551
+ process.exitCode = 1;
552
+ }
553
+ else if (values.share || values.submit) {
349
554
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
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 });
555
+ // A provider whose every run failed on the submitter's own account (bad key, no credit, a limit hit) says
556
+ // nothing about the provider: leave it out of what's shared, and say so.
557
+ const account = rows.filter((r) => r.failures === r.runs && r.lastError && ACCOUNT_ERROR.test(r.lastError));
558
+ if (account.length)
559
+ console.error(`\nleft out of the shared report, every run failed on your account: ${account.map((r) => r.provider).join(", ")}`);
560
+ const report = makeReport(rows.filter((r) => !account.includes(r)), { 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 });
351
561
  const left = rows.filter((r) => !benchmarksPublishable(r.provider)).map((r) => r.provider);
352
562
  if (left.length)
353
563
  console.log(`\nleft out of the shared report: ${left.join(", ")} (their terms don't allow publishing benchmarks)`);
354
564
  const file = values.out ?? `sandboxrouter-bench-${report.date.slice(0, 10)}-${Math.random().toString(36).slice(2, 8)}.json`;
355
565
  writeFileSync(file, JSON.stringify(report, null, 2) + "\n");
356
- console.log(`\nwrote ${file}. Add it to results/ in a PR to github.com/gigialc/sandboxrouter to put it on the leaderboard.`);
566
+ if (values.submit) {
567
+ const summary = `${report.rows.length} providers, ${report.runs} runs each${report.task ? `, job ${report.task}` : ""}, from ${report.label ?? "an unlabelled location"} (${report.platform}).`;
568
+ try {
569
+ console.log(`\nwrote ${file} and opened ${submitReport(file, summary)}`);
570
+ }
571
+ catch (err) {
572
+ console.error(`\nwrote ${file}, but couldn't open the pull request: ${err.message}`);
573
+ process.exitCode = 1;
574
+ }
575
+ }
576
+ else {
577
+ console.log(`\nwrote ${file}. Add it to results/ in a PR to github.com/gigialc/sandboxrouter to put it on the leaderboard, or run again with --submit to open the PR for you.`);
578
+ }
357
579
  }
358
580
  return;
359
581
  }
@@ -0,0 +1,48 @@
1
+ import { Router } from "./router.js";
2
+ import type { ProviderId, SandboxSpec } from "./types.js";
3
+ /**
4
+ * Your own workload on several providers: the same setup and command in a new sandbox on each, a few times.
5
+ * Times are measured; the cost is an estimate from each provider's billing rules for the time the sandbox lived
6
+ * (start, setup and run), with every core priced as busy. Failed attempts count: a provider that can't run your
7
+ * setup, or fails the command, says so instead of dropping out.
8
+ */
9
+ export interface CompareRow {
10
+ provider: ProviderId;
11
+ runs: number;
12
+ /** Runs where the sandbox started, setup exited 0 and the command exited 0. */
13
+ ok: number;
14
+ /** Of the failures: the sandbox didn't start / setup failed / the command failed or timed out. */
15
+ startFailed: number;
16
+ setupFailed: number;
17
+ commandFailed: number;
18
+ /** Medians over the successful runs, in milliseconds. */
19
+ medianStartMs?: number;
20
+ medianSetupMs?: number;
21
+ medianCommandMs?: number;
22
+ medianTotalMs?: number;
23
+ /** Estimated cost of one successful run (not a bill). */
24
+ estimatedUsd?: number;
25
+ /** The estimate uses what this provider really billed against its list price, where we measured it. */
26
+ billMeasured: boolean;
27
+ /** The size it ran at. */
28
+ size: {
29
+ vcpu: number;
30
+ memoryGb: number;
31
+ };
32
+ /** The first failure's message, shortened. */
33
+ error?: string;
34
+ }
35
+ export declare function compare(opts: {
36
+ router?: Router;
37
+ providers: ProviderId[];
38
+ command: string;
39
+ /** Run once in each sandbox before the command: installs, clones. Timed and reported apart. */
40
+ setup?: string;
41
+ runs?: number;
42
+ /** Seconds the setup and the command may each take (default 600). */
43
+ timeoutSeconds?: number;
44
+ /** Providers measured at once (default 4). */
45
+ parallel?: number;
46
+ spec?: SandboxSpec;
47
+ onProgress?: (msg: string) => void;
48
+ }): Promise<CompareRow[]>;
@@ -0,0 +1,78 @@
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 { taskUsd } from "./task.js";
6
+ export async function compare(opts) {
7
+ const router = opts.router ?? new Router();
8
+ const runs = Math.max(1, opts.runs ?? 3);
9
+ const timeoutSeconds = opts.timeoutSeconds ?? 600;
10
+ const log = opts.onProgress ?? (() => { });
11
+ const base = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: Math.ceil((timeoutSeconds * 2) / 60) + 5, ...opts.spec };
12
+ const rows = [];
13
+ const lastLine = (r) => (r.stderr || r.stdout).trim().split("\n").at(-1) ?? "";
14
+ const one = async (id) => {
15
+ const spec = { ...base, ...fixedSize(id, base) };
16
+ const good = [];
17
+ const row = { provider: id, runs, ok: 0, startFailed: 0, setupFailed: 0, commandFailed: 0, billMeasured: BILLED_VS_LIST[id] !== undefined, size: fittingSpec(id) };
18
+ const fail = (kind, msg) => {
19
+ row[kind]++;
20
+ row.error ??= msg.replace(/\s+/g, " ").slice(0, 200);
21
+ };
22
+ for (let i = 0; i < runs; i++) {
23
+ let box;
24
+ const t0 = performance.now();
25
+ try {
26
+ box = await router.create(spec, { provider: id, fallback: false });
27
+ }
28
+ catch (err) {
29
+ fail("startFailed", err.message);
30
+ continue;
31
+ }
32
+ try {
33
+ const start = performance.now() - t0;
34
+ let setup = 0;
35
+ if (opts.setup) {
36
+ const t1 = performance.now();
37
+ const r = await box.exec(opts.setup, { timeoutSeconds }).catch((e) => ({ exitCode: -1, stdout: "", stderr: e.message }));
38
+ setup = performance.now() - t1;
39
+ if (r.exitCode !== 0) {
40
+ fail("setupFailed", `setup exited ${r.exitCode}: ${lastLine(r)}`);
41
+ continue;
42
+ }
43
+ }
44
+ const t2 = performance.now();
45
+ const r = await box.exec(opts.command, { timeoutSeconds }).catch((e) => ({ exitCode: -1, stdout: "", stderr: e.message }));
46
+ const command = performance.now() - t2;
47
+ if (r.exitCode !== 0) {
48
+ fail("commandFailed", `command exited ${r.exitCode}: ${lastLine(r)}`);
49
+ continue;
50
+ }
51
+ good.push({ start, setup, command });
52
+ row.ok++;
53
+ }
54
+ finally {
55
+ await box.kill().catch(() => { });
56
+ }
57
+ }
58
+ if (good.length) {
59
+ const m = (f) => Math.round(median(good.map(f)));
60
+ row.medianStartMs = m((g) => g.start);
61
+ if (opts.setup)
62
+ row.medianSetupMs = m((g) => g.setup);
63
+ row.medianCommandMs = m((g) => g.command);
64
+ row.medianTotalMs = m((g) => g.start + g.setup + g.command);
65
+ row.estimatedUsd = taskUsd(id, row.size, row.medianStartMs, (row.medianSetupMs ?? 0) + row.medianCommandMs, undefined, BILLED_VS_LIST[id]?.ratio ?? 1, false);
66
+ }
67
+ rows.push(row);
68
+ log(`${id}: ${row.ok}/${runs} worked${row.medianTotalMs !== undefined ? `, ${(row.medianTotalMs / 1000).toFixed(1)} s in total` : ""}${row.error ? `; ${row.error.slice(0, 120)}` : ""}`);
69
+ };
70
+ const queue = [...opts.providers];
71
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(opts.parallel ?? 4, queue.length)) }, async () => {
72
+ for (let id = queue.shift(); id; id = queue.shift())
73
+ await one(id);
74
+ }));
75
+ // Most reliable first, then cheapest per successful run.
76
+ const perSuccess = (r) => (r.estimatedUsd === undefined || !r.ok ? Infinity : r.estimatedUsd / (r.ok / r.runs));
77
+ return rows.sort((a, b) => b.ok / b.runs - a.ok / a.runs || perSuccess(a) - perSuccess(b) || a.provider.localeCompare(b.provider));
78
+ }
package/dist/index.d.ts CHANGED
@@ -4,6 +4,9 @@ export { conformanceTable, loadConformance, type ConformanceRow, type SavedCheck
4
4
  export { gc, listOpen, isGone, type GcResult, type OpenSandbox } from "./gc.js";
5
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 { PUBLISHED } from "./published.js";
8
+ export { compare, type CompareRow } from "./compare.js";
9
+ export { recommend, type RecJob, type RecPriority, type RecommendOptions, type Recommendation, type RecommendResult, type PublishedData, } from "./recommend.js";
7
10
  export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
8
11
  export { BILLED_VS_LIST } from "./billing.js";
9
12
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
package/dist/index.js CHANGED
@@ -4,6 +4,9 @@ export { conformanceTable, loadConformance } from "./conformance.js";
4
4
  export { gc, listOpen, isGone } from "./gc.js";
5
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 { PUBLISHED } from "./published.js";
8
+ export { compare } from "./compare.js";
9
+ export { recommend, } from "./recommend.js";
7
10
  export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
8
11
  export { BILLED_VS_LIST } from "./billing.js";
9
12
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";