@sandboxrouter/sdk 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +4 -3
  2. package/dist/agent-bench.d.ts +39 -0
  3. package/dist/agent-bench.js +150 -0
  4. package/dist/bench-store.js +11 -2
  5. package/dist/bench.d.ts +22 -0
  6. package/dist/bench.js +59 -7
  7. package/dist/burst.d.ts +81 -0
  8. package/dist/burst.js +183 -0
  9. package/dist/catalog.d.ts +32 -0
  10. package/dist/catalog.js +58 -15
  11. package/dist/check.d.ts +2 -0
  12. package/dist/check.js +8 -0
  13. package/dist/cli.js +217 -5
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/leaderboard.d.ts +107 -2
  17. package/dist/leaderboard.js +175 -5
  18. package/dist/ledger.d.ts +2 -0
  19. package/dist/ledger.js +12 -1
  20. package/dist/price-index.d.ts +54 -0
  21. package/dist/price-index.js +50 -0
  22. package/dist/providers/beam.js +4 -0
  23. package/dist/providers/blaxel.js +4 -0
  24. package/dist/providers/boat.js +3 -1
  25. package/dist/providers/daytona.js +4 -0
  26. package/dist/providers/deno.js +4 -0
  27. package/dist/providers/e2b.d.ts +2 -0
  28. package/dist/providers/e2b.js +4 -0
  29. package/dist/providers/hopx.js +4 -0
  30. package/dist/providers/langsmith.js +4 -0
  31. package/dist/providers/modal.js +11 -2
  32. package/dist/providers/morph.js +4 -0
  33. package/dist/providers/runloop.js +4 -0
  34. package/dist/providers/sprites.js +4 -0
  35. package/dist/providers/tensorlake.js +4 -0
  36. package/dist/providers/vercel.js +4 -0
  37. package/dist/published.d.ts +2 -0
  38. package/dist/published.js +2087 -0
  39. package/dist/recommend.d.ts +117 -0
  40. package/dist/recommend.js +103 -0
  41. package/dist/results.js +81 -1
  42. package/dist/router.d.ts +50 -0
  43. package/dist/router.js +83 -10
  44. package/dist/submit.d.ts +6 -0
  45. package/dist/submit.js +70 -0
  46. package/dist/task.d.ts +80 -0
  47. package/dist/task.js +173 -0
  48. package/dist/types.d.ts +12 -0
  49. package/dist/util.d.ts +2 -0
  50. package/dist/util.js +2 -0
  51. package/dist/validate.d.ts +1 -1
  52. package/dist/validate.js +4 -1
  53. package/package.json +1 -1
package/dist/submit.js ADDED
@@ -0,0 +1,70 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { basename } from "node:path";
4
+ const UPSTREAM = "gigialc/sandboxrouter";
5
+ /** Runs the GitHub CLI and returns its trimmed output. Throws with gh's own message on failure. */
6
+ function gh(args) {
7
+ return execFileSync("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8
+ }
9
+ /**
10
+ * Sends a saved bench report to the public results as a pull request, with the GitHub CLI (`gh`): forks the
11
+ * repo if needed, puts the file in results/ on a new branch, and opens the PR. Returns the PR's URL.
12
+ * Nothing but the report file is sent; the report holds no keys (makeReport strips errors, and CI checks).
13
+ */
14
+ export function submitReport(file, summary) {
15
+ try {
16
+ gh(["--version"]);
17
+ }
18
+ catch {
19
+ throw new Error("--submit needs the GitHub CLI: install it from https://cli.github.com and run `gh auth login`");
20
+ }
21
+ let login;
22
+ try {
23
+ login = gh(["api", "user", "-q", ".login"]);
24
+ }
25
+ catch {
26
+ throw new Error("--submit needs you signed in to the GitHub CLI: run `gh auth login`");
27
+ }
28
+ const owner = UPSTREAM.split("/")[0];
29
+ const target = login === owner ? UPSTREAM : `${login}/sandboxrouter`;
30
+ if (target !== UPSTREAM) {
31
+ // Idempotent: an existing fork is reused.
32
+ try {
33
+ gh(["repo", "fork", UPSTREAM, "--clone=false"]);
34
+ }
35
+ catch {
36
+ /* already forked */
37
+ }
38
+ }
39
+ const name = basename(file);
40
+ const branch = `results-${name.replace(/\.json$/, "")}`;
41
+ const base = gh(["api", `repos/${UPSTREAM}/git/ref/heads/main`, "-q", ".object.sha"]);
42
+ // A fork shares the upstream's objects, so a branch can start at upstream main even if the fork is behind.
43
+ gh(["api", `repos/${target}/git/refs`, "-f", `ref=refs/heads/${branch}`, "-f", `sha=${base}`]);
44
+ gh([
45
+ "api",
46
+ "-X",
47
+ "PUT",
48
+ `repos/${target}/contents/results/${name}`,
49
+ "-f",
50
+ `message=Add benchmark results: ${name}`,
51
+ "-f",
52
+ `content=${readFileSync(file).toString("base64")}`,
53
+ "-f",
54
+ `branch=${branch}`,
55
+ ]);
56
+ return gh([
57
+ "pr",
58
+ "create",
59
+ "--repo",
60
+ UPSTREAM,
61
+ "--head",
62
+ target === UPSTREAM ? branch : `${login}:${branch}`,
63
+ "--base",
64
+ "main",
65
+ "--title",
66
+ `Benchmark results: ${name}`,
67
+ "--body",
68
+ `${summary}\n\nSent with \`sandboxrouter bench --submit\`.`,
69
+ ]);
70
+ }
package/dist/task.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ import type { ProviderId, ProviderSandbox } from "./types.js";
2
+ /**
3
+ * The standard tasks for `bench --task`: the same fixed piece of work in every sandbox, so providers can be
4
+ * compared on what a job costs, not just on their hourly price. A slower CPU, disk or network makes the job
5
+ * take longer, and a longer job is billed more.
6
+ *
7
+ * Each phase is its own command, timed from here, minus the sandbox's own round trip for an empty command,
8
+ * so network distance to the provider mostly drops out.
9
+ *
10
+ * - "short": hash on one core, then two, then write to disk, once (seconds). Only POSIX shell and tools every
11
+ * Linux image has (coreutils or busybox), so no provider fails for lack of a package.
12
+ * - "long": the short job's phases 40 times in a row (minutes): sustained speed (CPUs that slow down after a
13
+ * burst) and prices once minimum charges stop mattering.
14
+ * - "python": a pure-Python script like a code-interpreter call. Needs python3 in the default image; a
15
+ * provider without it fails the task, which is itself worth knowing.
16
+ * - "download": fetch the 53 MB Node.js release from nodejs.org's CDN, with curl, else wget, else python3:
17
+ * what installing toolchains and packages depends on.
18
+ * - "repo": what a coding agent does first: fetch Node 22 and a pinned commit of a real TypeScript project
19
+ * (sandboxRouter itself, the 0.10.0 release), `npm ci`, then typecheck it. Needs only tar and a way to
20
+ * download (curl, wget or python3), so a bare image can run it.
21
+ * - "agent": an agent loop with simulated model calls: 10 turns of waiting 6 s (the model thinking; the
22
+ * sandbox sits idle) and then a short Python tool call. About a minute, mostly idle, which is where
23
+ * providers that bill active CPU differ from ones that bill what you reserve.
24
+ *
25
+ * Changing a phase changes what the numbers mean: bump that task's version, and older reports stop counting.
26
+ */
27
+ export type TaskKind = "short" | "long" | "python" | "download" | "agent" | "repo";
28
+ export interface TaskPhaseDef {
29
+ id: string;
30
+ label: string;
31
+ cmd: string;
32
+ /** Seconds the phase may take (default 300, or 900 for a repeated phase). */
33
+ timeoutSeconds?: number;
34
+ }
35
+ /** `cpuUtilization`: the hint the job's sandboxes start with (the agent loop is mostly idle), which Modal reserves and pricing uses. */
36
+ export declare const TASKS: Record<TaskKind, {
37
+ version: string;
38
+ repeat: number;
39
+ phases: TaskPhaseDef[];
40
+ cpuUtilization?: number;
41
+ }>;
42
+ /** The short task's version and phases, which is what plain `bench --task` records. */
43
+ export declare const TASK_VERSION: string;
44
+ export declare const TASK_PHASES: TaskPhaseDef[];
45
+ /** Milliseconds per phase, by phase id. */
46
+ export type PhaseMs = Record<string, number>;
47
+ /** The task a report's `task` version names, if it's one this release knows. */
48
+ export declare function taskByVersion(version: unknown): (typeof TASKS)[TaskKind] | undefined;
49
+ /** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
50
+ export declare function phaseCommand(cmd: string, repeat: number): string;
51
+ /** What one run of a task measured: milliseconds per phase, and the CPU time it used across all vCPUs, if the sandbox shows it. */
52
+ export interface TaskRun {
53
+ ms: PhaseMs;
54
+ cpuMs?: number;
55
+ /** The busiest single core's busy time, summed over the phases: what a per-VM CPU meter scales by vCPUs. */
56
+ maxCoreMs?: number;
57
+ }
58
+ /** The busiest core's busy milliseconds between two readings, or undefined without per-core lines. */
59
+ export declare function maxCoreMs(before: string, after: string): number | undefined;
60
+ /** Busy CPU milliseconds between two /proc/stat "cpu" lines: user, nice, system, irq and softirq (not idle, iowait or steal), at 100 ticks a second. */
61
+ export declare function busyMs(before: string, after: string): number | undefined;
62
+ /** Runs a standard task in `box`: milliseconds per phase (network round trip taken out) and CPU time used. Throws if a phase fails. */
63
+ export declare function runTask(box: Pick<ProviderSandbox, "exec">, kind?: TaskKind): Promise<TaskRun>;
64
+ /** The whole task's time: the phases added up. */
65
+ export declare const taskMs: (phases: PhaseMs) => number;
66
+ /**
67
+ * What one task would be billed, USD, on a sandbox of `size`. It's billed from create until the task is
68
+ * done: the start time plus the task, rounded up to the provider's minimum charge and billing increment,
69
+ * plus its per-sandbox charge.
70
+ *
71
+ * Providers that bill CPU only while busy are charged for the CPU time the task really used (`cpuMillis`,
72
+ * at least their CPU floor) plus their memory for the whole time; their minimum charge covers memory only
73
+ * where that's how they bill (Vercel). Without `cpuMillis` they're charged as if every core was busy.
74
+ * `billedVsList` scales the price by what the provider was measured to really bill.
75
+ */
76
+ export declare function taskUsd(provider: ProviderId, size: {
77
+ vcpu: number;
78
+ memoryGb: number;
79
+ cpuUtilization?: number;
80
+ }, createMs: number, taskMillis: number, cpuMillis?: number, billedVsList?: number, reused?: boolean, maxCoreMillis?: number): number;
package/dist/task.js ADDED
@@ -0,0 +1,173 @@
1
+ import { billingRules, cpuHourlyAtFull, hourlyCost, info } from "./catalog.js";
2
+ const HASH_DISK = [
3
+ // One core: hash 512 MB of zeros.
4
+ { id: "cpu", label: "1 core", cmd: "head -c 536870912 /dev/zero | sha256sum > /dev/null" },
5
+ // Two cores at once (bench asks for 2 vCPU), 256 MB each: shows whether the second vCPU is real.
6
+ { id: "cores", label: "2 cores", cmd: "for i in 1 2; do (head -c 268435456 /dev/zero | sha256sum > /dev/null) & done; wait" },
7
+ // Write 256 MB and flush it to disk, then delete it.
8
+ { id: "disk", label: "disk", cmd: "dd if=/dev/zero of=/tmp/sr-task bs=1048576 count=256 conv=fsync 2> /dev/null; rm -f /tmp/sr-task" },
9
+ ];
10
+ // 200,000 small records through JSON, a regex and a sort: the kind of thing a code-interpreter call does.
11
+ const PYTHON = [
12
+ "import json, random, re",
13
+ "random.seed(1)",
14
+ "rows = [{'id': i, 'name': ''.join(random.choice('abcdefghij') for _ in range(16)), 'v': random.random()} for i in range(200000)]",
15
+ "back = json.loads(json.dumps(rows))",
16
+ "hits = sum(1 for r in back if re.search('abc', r['name']))",
17
+ "top = sorted(back, key=lambda r: (r['name'], r['v']))[:10]",
18
+ "print(hits, top[0]['id'])",
19
+ ].join("\n");
20
+ // The Node.js 22.11.0 Linux release (53 MB), from nodejs.org's CDN: a real download, like installing a toolchain.
21
+ const DOWNLOAD_URL = "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-x64.tar.gz";
22
+ const PY_FETCH = `import shutil, urllib.request; shutil.copyfileobj(urllib.request.urlopen('${DOWNLOAD_URL}'), open('/dev/null', 'wb'))`;
23
+ // The real-repo job's sources, pinned so every provider does exactly the same work.
24
+ const REPO_TARBALL = "https://codeload.github.com/gigialc/sandboxrouter/tar.gz/ba2b32a1a403a93acad75a707f55a2eac9368f7a";
25
+ const NODE_BASE = "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux";
26
+ const FETCH = [
27
+ "set -e",
28
+ 'case "$(uname -m)" in aarch64|arm64) A=arm64 ;; *) A=x64 ;; esac',
29
+ `get() { if command -v curl > /dev/null; then curl -sSfL -o "$2" "$1"; elif command -v wget > /dev/null; then wget -q -O "$2" "$1"; else python3 -c "import shutil, sys, urllib.request; shutil.copyfileobj(urllib.request.urlopen(sys.argv[1]), open(sys.argv[2], 'wb'))" "$1" "$2"; fi; }`,
30
+ "rm -rf /tmp/sr-node /tmp/sr-repo && mkdir -p /tmp/sr-node /tmp/sr-repo",
31
+ `get "${NODE_BASE}-$A.tar.gz" /tmp/sr-node.tgz && tar xzf /tmp/sr-node.tgz -C /tmp/sr-node --strip-components=1`,
32
+ `get "${REPO_TARBALL}" /tmp/sr-repo.tgz && tar xzf /tmp/sr-repo.tgz -C /tmp/sr-repo --strip-components=1`,
33
+ "set +e",
34
+ ].join("\n");
35
+ const IN_REPO = "cd /tmp/sr-repo && PATH=/tmp/sr-node/bin:$PATH";
36
+ // One tool call in the agent loop: a little real work, like reading files and running a check.
37
+ const TOOL = "import json, hashlib; d = [{'i': i, 'h': hashlib.sha256(str(i).encode()).hexdigest()} for i in range(40000)]; print(len(json.dumps(d)))";
38
+ /** `cpuUtilization`: the hint the job's sandboxes start with (the agent loop is mostly idle), which Modal reserves and pricing uses. */
39
+ export const TASKS = {
40
+ short: { version: "v1", repeat: 1, phases: HASH_DISK },
41
+ long: { version: "v1-long", repeat: 40, phases: HASH_DISK },
42
+ python: { version: "python-v1", repeat: 1, phases: [{ id: "python", label: "Python", cmd: `python3 -c "${PYTHON}"` }] },
43
+ repo: {
44
+ version: "repo-v1",
45
+ repeat: 1,
46
+ phases: [
47
+ { id: "fetch", label: "fetch Node and the repo", cmd: FETCH, timeoutSeconds: 600 },
48
+ { id: "install", label: "npm ci", cmd: `${IN_REPO} npm ci --no-audit --no-fund --loglevel=error`, timeoutSeconds: 900 },
49
+ { id: "typecheck", label: "typecheck", cmd: `${IN_REPO} ./node_modules/.bin/tsc --noEmit -p .`, timeoutSeconds: 600 },
50
+ ],
51
+ },
52
+ agent: {
53
+ version: "agent-v1",
54
+ repeat: 1,
55
+ cpuUtilization: 0.1,
56
+ phases: [{ id: "agent", label: "10 turns", cmd: `n=0; while [ $n -lt 10 ]; do sleep 6; python3 -c "${TOOL}" > /dev/null; n=$((n+1)); done` }],
57
+ },
58
+ download: {
59
+ version: "download-v1",
60
+ repeat: 1,
61
+ phases: [
62
+ {
63
+ id: "download",
64
+ label: "53 MB download",
65
+ cmd: `if command -v curl > /dev/null; then curl -sSfL -o /dev/null '${DOWNLOAD_URL}'; ` +
66
+ `elif command -v wget > /dev/null; then wget -q -O /dev/null '${DOWNLOAD_URL}'; ` +
67
+ `else python3 -c "${PY_FETCH}"; fi`,
68
+ },
69
+ ],
70
+ },
71
+ };
72
+ /** The short task's version and phases, which is what plain `bench --task` records. */
73
+ export const TASK_VERSION = TASKS.short.version;
74
+ export const TASK_PHASES = TASKS.short.phases;
75
+ /** The task a report's `task` version names, if it's one this release knows. */
76
+ export function taskByVersion(version) {
77
+ return Object.values(TASKS).find((t) => t.version === version);
78
+ }
79
+ /** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
80
+ export function phaseCommand(cmd, repeat) {
81
+ return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do ${cmd}; n=$((n+1)); done`;
82
+ }
83
+ // Wraps a phase to read /proc/stat's total CPU line before and after it, so the run also reports the CPU
84
+ // time it really used: what providers that bill active CPU charge for.
85
+ const MARK = "SRCPU";
86
+ // Every "cpu" line (the total, then one per core), joined with ";" so the reading stays on one output line.
87
+ const STAT = `grep '^cpu' /proc/stat 2> /dev/null | tr '\\n' ';'`;
88
+ const withCpu = (cmd) => `a=$(${STAT}); ${cmd}; rc=$?; b=$(${STAT}); echo "${MARK}|$a|$b"; exit $rc`;
89
+ /** Busy ticks on one /proc/stat cpu line: user, nice, system, irq and softirq (not idle, iowait or steal). */
90
+ const lineTicks = (line) => {
91
+ const f = line.trim().split(/\s+/);
92
+ if (!/^cpu\d*$/.test(f[0] ?? "") || f.length < 8)
93
+ return undefined;
94
+ const n = f.slice(1).map(Number);
95
+ return n[0] + n[1] + n[2] + n[5] + n[6];
96
+ };
97
+ const perCpu = (reading) => new Map(reading.split(";").map((l) => [l.trim().split(/\s+/)[0], lineTicks(l)]).filter(([k, v]) => k && v !== undefined));
98
+ /** The busiest core's busy milliseconds between two readings, or undefined without per-core lines. */
99
+ export function maxCoreMs(before, after) {
100
+ const a = perCpu(before);
101
+ const b = perCpu(after);
102
+ const cores = [...b.keys()].filter((k) => k !== "cpu" && a.has(k));
103
+ if (!cores.length)
104
+ return undefined;
105
+ const deltas = cores.map((k) => (b.get(k) - a.get(k)) * 10);
106
+ return deltas.some((d) => !(d >= 0)) ? undefined : Math.max(...deltas);
107
+ }
108
+ /** Busy CPU milliseconds between two /proc/stat "cpu" lines: user, nice, system, irq and softirq (not idle, iowait or steal), at 100 ticks a second. */
109
+ export function busyMs(before, after) {
110
+ const total = (reading) => perCpu(reading).get("cpu");
111
+ const a = total(before);
112
+ const b = total(after);
113
+ return a === undefined || b === undefined || !(b >= a) ? undefined : (b - a) * 10;
114
+ }
115
+ /** Runs a standard task in `box`: milliseconds per phase (network round trip taken out) and CPU time used. Throws if a phase fails. */
116
+ export async function runTask(box, kind = "short") {
117
+ const { repeat, phases } = TASKS[kind];
118
+ const rtt = [];
119
+ for (let i = 0; i < 3; i++) {
120
+ const t = performance.now();
121
+ await box.exec("true");
122
+ rtt.push(performance.now() - t);
123
+ }
124
+ const overhead = rtt.sort((a, b) => a - b)[1];
125
+ const out = {};
126
+ let cpuMs = 0;
127
+ let coreMs = 0;
128
+ for (const p of phases) {
129
+ const t = performance.now();
130
+ const r = await box.exec(withCpu(phaseCommand(p.cmd, repeat)), { timeoutSeconds: p.timeoutSeconds ?? (repeat > 1 ? 900 : 300) });
131
+ if (r.exitCode !== 0)
132
+ throw new Error(`task phase ${p.id} exited ${r.exitCode}: ${(r.stderr || r.stdout).slice(0, 120)}`);
133
+ out[p.id] = Math.max(1, Math.round(performance.now() - t - overhead));
134
+ const line = r.stdout.split("\n").find((l) => l.startsWith(`${MARK}|`));
135
+ const used = line ? busyMs(line.split("|")[1] ?? "", line.split("|")[2] ?? "") : undefined;
136
+ cpuMs = cpuMs === undefined || used === undefined ? undefined : cpuMs + used;
137
+ const core = line ? maxCoreMs(line.split("|")[1] ?? "", line.split("|")[2] ?? "") : undefined;
138
+ coreMs = coreMs === undefined || core === undefined ? undefined : coreMs + core;
139
+ }
140
+ return { ms: out, ...(cpuMs !== undefined ? { cpuMs } : {}), ...(cpuMs !== undefined && coreMs !== undefined ? { maxCoreMs: coreMs } : {}) };
141
+ }
142
+ /** The whole task's time: the phases added up. */
143
+ export const taskMs = (phases) => Object.values(phases).reduce((s, ms) => s + ms, 0);
144
+ /**
145
+ * What one task would be billed, USD, on a sandbox of `size`. It's billed from create until the task is
146
+ * done: the start time plus the task, rounded up to the provider's minimum charge and billing increment,
147
+ * plus its per-sandbox charge.
148
+ *
149
+ * Providers that bill CPU only while busy are charged for the CPU time the task really used (`cpuMillis`,
150
+ * at least their CPU floor) plus their memory for the whole time; their minimum charge covers memory only
151
+ * where that's how they bill (Vercel). Without `cpuMillis` they're charged as if every core was busy.
152
+ * `billedVsList` scales the price by what the provider was measured to really bill.
153
+ */
154
+ export function taskUsd(provider, size, createMs, taskMillis, cpuMillis, billedVsList = 1, reused = false, maxCoreMillis) {
155
+ const rules = billingRules(provider);
156
+ // Reused: the job runs in a sandbox that's already up, so there's no start, minimum, step or per-sandbox
157
+ // fee to pay for it; only its own time.
158
+ const { minSeconds, incrementSeconds, perSandboxUsd } = reused ? { minSeconds: 0, incrementSeconds: 1e-9, perSandboxUsd: 0 } : rules;
159
+ const seconds = (reused ? 0 : createMs) / 1000 + taskMillis / 1000;
160
+ const billed = reused ? seconds : Math.max(minSeconds, Math.ceil(seconds / incrementSeconds - 1e-9) * incrementSeconds);
161
+ // Every core busy: the CPU part is then charged by what was used (cpuMillis), not by the hint.
162
+ const full = hourlyCost(provider, { ...size, cpuUtilization: 1 });
163
+ const cpuFull = cpuHourlyAtFull(provider, size);
164
+ if (cpuFull === 0 || cpuMillis === undefined)
165
+ return (billedVsList * full * billed) / 3600 + perSandboxUsd;
166
+ const { vcpuHour, cpuFloor = 0, cpuMeteredPerVm } = info(provider).pricing;
167
+ const vcpus = cpuFull / vcpuHour;
168
+ // A per-VM meter counts every vCPU while the busiest core works.
169
+ const perVm = cpuMeteredPerVm && maxCoreMillis !== undefined ? (vcpus * maxCoreMillis) / 1000 : 0;
170
+ const cpuSeconds = Math.max(cpuMillis / 1000, cpuFloor * vcpus * seconds, perVm);
171
+ // Memory (and anything else that isn't CPU) is billed for the whole time, minimum included.
172
+ return (billedVsList * ((full - cpuFull) * billed + vcpuHour * cpuSeconds)) / 3600 + perSandboxUsd;
173
+ }
package/dist/types.d.ts CHANGED
@@ -26,6 +26,13 @@ export interface SandboxSpec {
26
26
  * cheaper per hour but charges a full minute.
27
27
  */
28
28
  expectedSeconds?: number;
29
+ /**
30
+ * How busy the CPU will be, 0 to 1 (default 1). Only a pricing hint: providers that bill CPU only
31
+ * while it's busy (Vercel, Cloudflare, Tensorlake, AgentCore, Sail, Sprites, Deno, Upstash) are priced
32
+ * at this share of their CPU plus their full memory, never below a provider's CPU floor. An agent that
33
+ * mostly waits on model calls uses about 0.1; a build or test run is close to 1.
34
+ */
35
+ cpuUtilization?: number;
29
36
  /**
30
37
  * Provider-specific image/template, keyed by provider, e.g.
31
38
  * { maritime: "python", e2b: "code-interpreter-v1", modal: "python:3.13-slim" }.
@@ -98,6 +105,11 @@ export interface ExecResult {
98
105
  /** A live sandbox as one provider sees it. Adapters implement this. */
99
106
  export interface ProviderSandbox {
100
107
  readonly nativeId: string;
108
+ /**
109
+ * The provider SDK's own sandbox object (an E2B Sandbox, a Daytona Sandbox, a Modal Sandbox, ...), for features
110
+ * the router doesn't cover. Undefined for providers driven over plain HTTP: use `nativeId` with their API.
111
+ */
112
+ readonly native?: unknown;
101
113
  exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
102
114
  writeFile(path: string, content: string | Uint8Array): Promise<void>;
103
115
  readFile(path: string): Promise<Uint8Array>;
package/dist/util.d.ts CHANGED
@@ -49,5 +49,7 @@ export declare function errorStatus(err: unknown, depth?: number): number | unde
49
49
  * sandbox, and the failed attempt stays on `attempts` (the CLI prints it), so it isn't hidden.
50
50
  */
51
51
  export declare const SETUP_ERRORS: Set<number>;
52
+ /** A provider saying no for a limit or quota on the account (rate limits, concurrency caps, spent credit). */
53
+ export declare const LIMIT_ERROR: RegExp;
52
54
  /** Resolve with `work`, or reject with `onExpire()` after `ms`. A late `work` rejection is swallowed. */
53
55
  export declare function withDeadline<T>(work: Promise<T>, ms: number, onExpire: () => Error): Promise<T>;
package/dist/util.js CHANGED
@@ -117,6 +117,8 @@ export function errorStatus(err, depth = 0) {
117
117
  * sandbox, and the failed attempt stays on `attempts` (the CLI prints it), so it isn't hidden.
118
118
  */
119
119
  export const SETUP_ERRORS = new Set([400, 401, 403, 404, 422]);
120
+ /** A provider saying no for a limit or quota on the account (rate limits, concurrency caps, spent credit). */
121
+ export const LIMIT_ERROR = /\b429\b|rate.?limit|too many|quota|concurren|capacity|throttl|creation limit|trial_exhausted|insufficient_credits|limit exceeded/i;
120
122
  /** Resolve with `work`, or reject with `onExpire()` after `ms`. A late `work` rejection is swallowed. */
121
123
  export async function withDeadline(work, ms, onExpire) {
122
124
  let timer;
@@ -1,6 +1,6 @@
1
1
  import { type RouteOptions, type SandboxSpec, type Strategy } from "./types.js";
2
2
  /** Every key a SandboxSpec can have. Anything else in a request is a mistake (e.g. "memory" for "memoryGb"). */
3
- export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "image", "metadata"];
3
+ export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "cpuUtilization", "image", "metadata"];
4
4
  /** Every key RouteOptions can have. */
5
5
  export declare const ROUTE_KEYS: readonly ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"];
6
6
  export declare const STRATEGIES: readonly Strategy[];
package/dist/validate.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CATALOG } from "./catalog.js";
2
2
  import { RouterError } from "./types.js";
3
3
  /** Every key a SandboxSpec can have. Anything else in a request is a mistake (e.g. "memory" for "memoryGb"). */
4
- export const SPEC_KEYS = ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "image", "metadata"];
4
+ export const SPEC_KEYS = ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "cpuUtilization", "image", "metadata"];
5
5
  /** Every key RouteOptions can have. */
6
6
  export const ROUTE_KEYS = ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"];
7
7
  export const STRATEGIES = ["default", "balanced", "verified", "cheapest", "fastest"];
@@ -20,6 +20,9 @@ export function validate(spec = {}, route = {}) {
20
20
  if (spec[k] !== undefined && !positive(spec[k]))
21
21
  throw bad(`${k} must be a positive number, got ${show(spec[k])}`);
22
22
  }
23
+ if (spec.cpuUtilization !== undefined && !(positive(spec.cpuUtilization) && spec.cpuUtilization <= 1)) {
24
+ throw bad(`cpuUtilization must be more than 0 and at most 1, got ${show(spec.cpuUtilization)}`);
25
+ }
23
26
  if (spec.gpu !== undefined && (typeof spec.gpu !== "string" || !spec.gpu))
24
27
  throw bad(`gpu must be a GPU type such as "T4", got ${JSON.stringify(spec.gpu)}`);
25
28
  for (const k of ["env", "image", "metadata"]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.9.0",
3
+ "version": "0.11.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",