@sandboxrouter/sdk 0.11.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.
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { ACCOUNT_ERROR, bench, benchMarkdown, NETWORK_ERROR } from "./bench.js";
6
6
  import { TASKS } from "./task.js";
7
7
  import { submitReport } from "./submit.js";
8
8
  import { burst, spreadBurst } from "./burst.js";
9
+ import { compare } from "./compare.js";
9
10
  import { agentBench, AGENT_TASK_VERSION } from "./agent-bench.js";
10
11
  /** Errors that mean the network between here and the provider failed, not the provider. */
11
12
  import { costMarkdown, costRun, settle } from "./cost.js";
@@ -29,6 +30,9 @@ Usage:
29
30
  [--reuse] [--provider a,b] [--json]
30
31
  which provider for a job, from the published benchmarks: per successful run, with start
31
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
32
36
  sandboxrouter run "<cmd>" [spec flags] [route flags] [--keep]
33
37
  sandboxrouter check --provider ID[,ID] | --all [--json] [--save [dir]] [--retry] [--out FILE] [--by GITHUB_USER]
34
38
  test providers for real: exec, env, UTF-8, streaming, files, timeout, pause,
@@ -99,6 +103,8 @@ const { values, positionals } = parseArgs({
99
103
  priority: { type: "string" },
100
104
  reuse: { type: "boolean" },
101
105
  spread: { type: "boolean" },
106
+ setup: { type: "string" },
107
+ seconds: { type: "string" },
102
108
  even: { type: "boolean" },
103
109
  parallel: { type: "string" },
104
110
  n: { type: "string" },
@@ -197,6 +203,27 @@ async function main() {
197
203
  ].join("\n"));
198
204
  return;
199
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
+ }
200
227
  if (cmd === "recommend") {
201
228
  const jobs = ["start", "short", "long", "python", "download", "agent", "repo"];
202
229
  const priorities = ["value", "cost", "speed"];
@@ -437,7 +464,7 @@ async function main() {
437
464
  // One burst over all of them: round-robin, and a provider that says no hands its sandboxes to the next.
438
465
  const r = await spreadBurst({ router, providers: ids, n, weights: values.even ? "even" : undefined, onProgress: (m) => console.error(m) });
439
466
  if (values.out)
440
- writeFileSync(values.out, JSON.stringify({ tool: "sandboxrouter-spread", date: new Date().toISOString(), label: values.label, ...r }, null, 2) + "\n");
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");
441
468
  if (values.json)
442
469
  return console.log(JSON.stringify(r, null, 2));
443
470
  const ms = (v) => (v === undefined ? "n/a" : `${v} ms`);
@@ -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
@@ -5,6 +5,7 @@ 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
7
  export { PUBLISHED } from "./published.js";
8
+ export { compare, type CompareRow } from "./compare.js";
8
9
  export { recommend, type RecJob, type RecPriority, type RecommendOptions, type Recommendation, type RecommendResult, type PublishedData, } from "./recommend.js";
9
10
  export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
10
11
  export { BILLED_VS_LIST } from "./billing.js";
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ 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
7
  export { PUBLISHED } from "./published.js";
8
+ export { compare } from "./compare.js";
8
9
  export { recommend, } from "./recommend.js";
9
10
  export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
10
11
  export { BILLED_VS_LIST } from "./billing.js";
package/dist/results.js CHANGED
@@ -219,6 +219,36 @@ export function validateResult(j, now = Date.now()) {
219
219
  out.push(`${r?.provider}: sandboxes started but no p50Ms`);
220
220
  }
221
221
  }
222
+ else if (j.tool === "sandboxrouter-spread") {
223
+ add(checkDate(j.date, now));
224
+ add(checkLabel(j.label));
225
+ add(checkBy(j.by));
226
+ if (!isNum(j.n, 2, 10_000))
227
+ out.push("n must be between 2 and 10000");
228
+ if (!isNum(j.ok, 0, j.n) || !isNum(j.failed, 0, j.n) || j.ok + j.failed !== j.n)
229
+ out.push("ok and failed must add up to n");
230
+ for (const k of ["p50Ms", "p95Ms", "p99Ms"]) {
231
+ if (j[k] !== undefined && !isNum(j[k], 1, 4 * MAX_MS))
232
+ out.push(`${k} is out of range`);
233
+ }
234
+ if (!isNum(j.wallMs, 1, 4 * MAX_MS))
235
+ out.push("wallMs is out of range");
236
+ if (!isNum(j.usd, 0, 10_000))
237
+ out.push("usd is out of range");
238
+ if (!Array.isArray(j.byProvider) || j.byProvider.length < 2)
239
+ out.push("byProvider must list at least two providers");
240
+ let started = 0;
241
+ for (const b of Array.isArray(j.byProvider) ? j.byProvider : []) {
242
+ provider(b?.provider, "byProvider provider");
243
+ if (noBench(b?.provider))
244
+ out.push(`${b.provider}: ${NO_BENCH}`);
245
+ if (!isNum(b?.ok, 0, j.n) || !isNum(b?.spilledIn, 0, j.n) || !isNum(b?.refused, 0, 100 * j.n))
246
+ out.push(`${b?.provider}: counts out of range`);
247
+ started += b?.ok ?? 0;
248
+ }
249
+ if (started !== j.ok)
250
+ out.push("byProvider ok counts must add up to ok");
251
+ }
222
252
  else if (j.tool === "sandboxrouter-cost") {
223
253
  add(checkDate(j.date, now));
224
254
  add(checkBy(j.by));
@@ -242,7 +272,7 @@ export function validateResult(j, now = Date.now()) {
242
272
  }
243
273
  }
244
274
  else {
245
- out.push(`unknown tool "${String(j.tool)}": expected a bench report, a burst report, an agent report, a saved check or a cost run`);
275
+ out.push(`unknown tool "${String(j.tool)}": expected a bench report, a burst report, a spread report, an agent report, a saved check or a cost run`);
246
276
  }
247
277
  return out;
248
278
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "One API for every sandbox provider: route AI agents' code by price, speed or capability, with automatic fallback. Free and open source.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",