@sandboxrouter/sdk 0.12.0 → 0.14.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 +13 -8
- package/dist/agent-bench.d.ts +12 -1
- package/dist/agent-bench.js +46 -7
- package/dist/bench.d.ts +13 -1
- package/dist/bench.js +39 -17
- package/dist/billing.js +0 -1
- package/dist/burst.d.ts +10 -0
- package/dist/burst.js +21 -10
- package/dist/catalog.d.ts +13 -0
- package/dist/catalog.js +34 -16
- package/dist/cli.js +47 -37
- package/dist/client.d.ts +6 -1
- package/dist/client.js +19 -0
- package/dist/computers.d.ts +2 -2
- package/dist/cost.d.ts +44 -5
- package/dist/cost.js +54 -24
- package/dist/leaderboard.d.ts +30 -8
- package/dist/leaderboard.js +89 -50
- package/dist/price-index.d.ts +3 -3
- package/dist/price-index.js +3 -3
- package/dist/providers/blaxel.d.ts +1 -0
- package/dist/providers/blaxel.js +56 -1
- package/dist/providers/daytona.js +33 -1
- package/dist/providers/deno.d.ts +3 -0
- package/dist/providers/deno.js +14 -0
- package/dist/providers/docker.d.ts +1 -0
- package/dist/providers/docker.js +30 -3
- package/dist/providers/e2b.d.ts +22 -1
- package/dist/providers/e2b.js +50 -3
- package/dist/providers/hopx.js +12 -0
- package/dist/providers/limrun.d.ts +1 -8
- package/dist/providers/limrun.js +0 -1
- package/dist/providers/mobilerun.d.ts +1 -5
- package/dist/providers/mobilerun.js +18 -26
- package/dist/providers/modal.js +7 -0
- package/dist/providers/novita.js +5 -5
- package/dist/providers/sail.js +4 -4
- package/dist/providers/vercel.js +41 -3
- package/dist/published.js +639 -1283
- package/dist/recommend.d.ts +17 -0
- package/dist/recommend.js +17 -11
- package/dist/results.d.ts +2 -2
- package/dist/results.js +104 -3
- package/dist/router.d.ts +22 -8
- package/dist/router.js +58 -11
- package/dist/server.d.ts +4 -1
- package/dist/server.js +101 -7
- package/dist/task.d.ts +2 -1
- package/dist/task.js +38 -19
- package/dist/types.d.ts +20 -4
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +18 -1
- package/package.json +18 -3
package/dist/server.js
CHANGED
|
@@ -5,7 +5,7 @@ import { Router } from "./router.js";
|
|
|
5
5
|
import { splitComputerRequest } from "./computers.js";
|
|
6
6
|
import { ProviderError, RouterError } from "./types.js";
|
|
7
7
|
import { errorStatus } from "./util.js";
|
|
8
|
-
import { splitRequest } from "./validate.js";
|
|
8
|
+
import { isPort, splitRequest, validateStart } from "./validate.js";
|
|
9
9
|
/**
|
|
10
10
|
* OpenRouter-style HTTP API in front of every provider. One token for your clients; provider keys
|
|
11
11
|
* stay on this host.
|
|
@@ -13,11 +13,14 @@ import { splitRequest } from "./validate.js";
|
|
|
13
13
|
* GET /v1/providers
|
|
14
14
|
* POST /v1/route dry run: which providers would be tried, in order
|
|
15
15
|
* POST /v1/quote where a create would land and what the run would cost
|
|
16
|
-
* POST /v1/sandboxes { vcpu, memoryGb, ..., provider, strategy, fallback, require, createTimeoutSeconds }
|
|
16
|
+
* POST /v1/sandboxes { vcpu, memoryGb, ports, ..., provider, strategy, fallback, require, createTimeoutSeconds }
|
|
17
17
|
* POST /v1/sandboxes/:id/exec { cmd, cwd, env, timeoutSeconds, stream }
|
|
18
18
|
* stream: true answers text/event-stream: `stdout`/`stderr` events (JSON string chunks),
|
|
19
19
|
* then one `result` event (the ExecResult), or an `error` event
|
|
20
20
|
* POST /v1/sandboxes/:id/pause keeps the disk; the next call resumes it
|
|
21
|
+
* GET /v1/sandboxes/:id/ports/:port { url }
|
|
22
|
+
* POST /v1/sandboxes/:id/processes { cmd, cwd, env } -> { id }
|
|
23
|
+
* DELETE /v1/sandboxes/:id/processes/:processId
|
|
21
24
|
* PUT /v1/sandboxes/:id/files?path= raw body
|
|
22
25
|
* GET /v1/sandboxes/:id/files?path= raw body
|
|
23
26
|
* DELETE /v1/sandboxes/:id
|
|
@@ -50,6 +53,30 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
|
|
|
50
53
|
return got.length === expected.length && timingSafeEqual(got, expected);
|
|
51
54
|
};
|
|
52
55
|
const live = new Map();
|
|
56
|
+
// IDs and handles are local to this server. A process can only be stopped under its sandbox ID.
|
|
57
|
+
const processes = new Map();
|
|
58
|
+
const clearSandbox = (id) => {
|
|
59
|
+
live.delete(id);
|
|
60
|
+
processes.delete(id);
|
|
61
|
+
};
|
|
62
|
+
const dropEmptyScope = (id, scope) => {
|
|
63
|
+
if (scope.starting === 0 && scope.entries.size === 0 && processes.get(id) === scope)
|
|
64
|
+
processes.delete(id);
|
|
65
|
+
};
|
|
66
|
+
const stopProcess = (id, scope, entry) => {
|
|
67
|
+
entry.stopping ??= (async () => {
|
|
68
|
+
try {
|
|
69
|
+
await entry.handle.kill();
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
if (errorStatus(err) !== 404)
|
|
73
|
+
throw err;
|
|
74
|
+
}
|
|
75
|
+
scope.entries.delete(entry.handle.id);
|
|
76
|
+
dropEmptyScope(id, scope);
|
|
77
|
+
})().finally(() => { entry.stopping = undefined; });
|
|
78
|
+
return entry.stopping;
|
|
79
|
+
};
|
|
53
80
|
const computersOn = hooks.computers ?? !hooks.authorize;
|
|
54
81
|
/**
|
|
55
82
|
* Idempotency-Key: a create retried with the same key (by the same caller, to the same path) gets the
|
|
@@ -146,10 +173,14 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
|
|
|
146
173
|
if (parts[0] !== "v1")
|
|
147
174
|
return json(res, 404, { error: "not found" });
|
|
148
175
|
const router = hooks.routerFor ? await hooks.routerFor(caller) : defaultRouter;
|
|
149
|
-
const
|
|
176
|
+
const checkOwns = async (id) => {
|
|
150
177
|
if (hooks.owns && !(await hooks.owns(caller, id)))
|
|
151
178
|
throw new HttpError(404, "no such sandbox");
|
|
152
|
-
|
|
179
|
+
};
|
|
180
|
+
const resolveSandbox = (id) => live.get(id) ?? router.get(id);
|
|
181
|
+
const box = async (id) => {
|
|
182
|
+
await checkOwns(id);
|
|
183
|
+
return resolveSandbox(id);
|
|
153
184
|
};
|
|
154
185
|
// GET /v1/providers
|
|
155
186
|
if (req.method === "GET" && parts[1] === "providers" && parts.length === 2) {
|
|
@@ -222,7 +253,14 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
|
|
|
222
253
|
},
|
|
223
254
|
discard: async () => {
|
|
224
255
|
live.delete(made.id);
|
|
225
|
-
|
|
256
|
+
try {
|
|
257
|
+
await made.kill();
|
|
258
|
+
processes.delete(made.id);
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
if (errorStatus(err) === 404)
|
|
262
|
+
processes.delete(made.id);
|
|
263
|
+
}
|
|
226
264
|
await hooks.afterKill?.(caller, made.id);
|
|
227
265
|
},
|
|
228
266
|
};
|
|
@@ -231,6 +269,62 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
|
|
|
231
269
|
const id = parts[2] ? decodeURIComponent(parts[2]) : "";
|
|
232
270
|
if (!id)
|
|
233
271
|
return json(res, 404, { error: "not found" });
|
|
272
|
+
// A preview URL can contain a provider credential. The API returns it as data without proxying it.
|
|
273
|
+
if (req.method === "GET" && parts[3] === "ports" && parts.length === 5) {
|
|
274
|
+
res.setHeader("Cache-Control", "no-store");
|
|
275
|
+
const port = Number(parts[4]);
|
|
276
|
+
if (!/^[1-9]\d*$/.test(parts[4]) || !isPort(port)) {
|
|
277
|
+
throw new RouterError("port must be an integer from 1 to 65535", [], "bad_request");
|
|
278
|
+
}
|
|
279
|
+
return json(res, 200, { url: await (await box(id)).url(port) });
|
|
280
|
+
}
|
|
281
|
+
if (req.method === "POST" && parts[3] === "processes" && parts.length === 4) {
|
|
282
|
+
res.setHeader("Cache-Control", "no-store");
|
|
283
|
+
const body = await readJson(req);
|
|
284
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
285
|
+
throw new RouterError("a background process takes cmd, cwd and env", [], "bad_request");
|
|
286
|
+
}
|
|
287
|
+
const { cmd, ...opts } = body;
|
|
288
|
+
validateStart(cmd, opts);
|
|
289
|
+
await checkOwns(id);
|
|
290
|
+
const scope = processes.get(id) ?? { entries: new Map(), starting: 0 };
|
|
291
|
+
processes.set(id, scope);
|
|
292
|
+
scope.starting++;
|
|
293
|
+
try {
|
|
294
|
+
const sbx = await resolveSandbox(id);
|
|
295
|
+
if (processes.get(id) !== scope)
|
|
296
|
+
throw new HttpError(404, "no such sandbox");
|
|
297
|
+
const handle = await sbx.start(cmd, opts);
|
|
298
|
+
// A concurrent sandbox deletion discards the scope. An interrupted client has no process
|
|
299
|
+
// ID to stop, so try to stop the process rather than leave it running without a handle.
|
|
300
|
+
const deleted = processes.get(id) !== scope;
|
|
301
|
+
const entry = { handle };
|
|
302
|
+
if (!deleted)
|
|
303
|
+
scope.entries.set(handle.id, entry);
|
|
304
|
+
if (deleted || res.destroyed || !res.writable) {
|
|
305
|
+
await stopProcess(id, scope, entry);
|
|
306
|
+
if (deleted)
|
|
307
|
+
throw new HttpError(404, "no such sandbox");
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
return json(res, 201, { id: handle.id });
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
scope.starting--;
|
|
314
|
+
dropEmptyScope(id, scope);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (req.method === "DELETE" && parts[3] === "processes" && parts.length === 5) {
|
|
318
|
+
res.setHeader("Cache-Control", "no-store");
|
|
319
|
+
await checkOwns(id);
|
|
320
|
+
const processId = parts[4];
|
|
321
|
+
const scope = processes.get(id);
|
|
322
|
+
const entry = scope?.entries.get(processId);
|
|
323
|
+
if (!scope || !entry)
|
|
324
|
+
throw new HttpError(404, "no such process in this sandbox");
|
|
325
|
+
await stopProcess(id, scope, entry);
|
|
326
|
+
return json(res, 200, { id: processId, killed: true });
|
|
327
|
+
}
|
|
234
328
|
// POST /v1/sandboxes/:id/exec
|
|
235
329
|
if (req.method === "POST" && parts[3] === "exec") {
|
|
236
330
|
const body = await readJson(req);
|
|
@@ -284,7 +378,7 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
|
|
|
284
378
|
catch (err) {
|
|
285
379
|
// Already gone at the provider: that's what the caller wanted.
|
|
286
380
|
if (!(err instanceof HttpError) && errorStatus(err) === 404) {
|
|
287
|
-
|
|
381
|
+
clearSandbox(id);
|
|
288
382
|
await hooks.afterKill?.(caller, id);
|
|
289
383
|
return json(res, 200, { id, killed: true });
|
|
290
384
|
}
|
|
@@ -292,7 +386,7 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
|
|
|
292
386
|
await hooks.afterKill?.(caller, id, { error: err });
|
|
293
387
|
throw err;
|
|
294
388
|
}
|
|
295
|
-
|
|
389
|
+
clearSandbox(id);
|
|
296
390
|
await hooks.afterKill?.(caller, id);
|
|
297
391
|
return json(res, 200, { id, killed: true });
|
|
298
392
|
}
|
package/dist/task.d.ts
CHANGED
|
@@ -44,7 +44,8 @@ export declare const TASK_VERSION: string;
|
|
|
44
44
|
export declare const TASK_PHASES: TaskPhaseDef[];
|
|
45
45
|
/** Milliseconds per phase, by phase id. */
|
|
46
46
|
export type PhaseMs = Record<string, number>;
|
|
47
|
-
|
|
47
|
+
export declare const isCurrentTask: (version: unknown) => boolean;
|
|
48
|
+
/** Legacy reports keep their original phase schema for validation and archival. */
|
|
48
49
|
export declare function taskByVersion(version: unknown): (typeof TASKS)[TaskKind] | undefined;
|
|
49
50
|
/** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
|
|
50
51
|
export declare function phaseCommand(cmd: string, repeat: number): string;
|
package/dist/task.js
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import { billingRules, cpuHourlyAtFull, hourlyCost, info } from "./catalog.js";
|
|
2
|
+
const ZERO_256_SHA256 = "a6d72ac7690f53be6ae46ba88506bd97302a093f7108472bd9efc3cefda06484";
|
|
3
|
+
const ZERO_512_SHA256 = "9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767";
|
|
4
|
+
const hashZeros = (count, hash) => `hash=$(head -c ${count} /dev/zero | sha256sum) && [ "${'${hash%% *}'}" = "${hash}" ]`;
|
|
2
5
|
const HASH_DISK = [
|
|
3
6
|
// One core: hash 512 MB of zeros.
|
|
4
|
-
{ id: "cpu", label: "1 core", cmd:
|
|
7
|
+
{ id: "cpu", label: "1 core", cmd: hashZeros(536870912, ZERO_512_SHA256) },
|
|
5
8
|
// Two cores at once (bench asks for 2 vCPU), 256 MB each: shows whether the second vCPU is real.
|
|
6
|
-
{
|
|
9
|
+
{
|
|
10
|
+
id: "cores",
|
|
11
|
+
label: "2 cores",
|
|
12
|
+
cmd: `(${hashZeros(268435456, ZERO_256_SHA256)}) & left=$!; (${hashZeros(268435456, ZERO_256_SHA256)}) & right=$!; wait "$left"; l=$?; wait "$right"; r=$?; [ "$l" = 0 ] && [ "$r" = 0 ]`,
|
|
13
|
+
},
|
|
7
14
|
// Write 256 MB and flush it to disk, then delete it.
|
|
8
|
-
{
|
|
15
|
+
{
|
|
16
|
+
id: "disk",
|
|
17
|
+
label: "disk",
|
|
18
|
+
cmd: 'f=$(mktemp /tmp/sr-task.XXXXXX) || exit $?; dd if=/dev/zero of="$f" bs=1048576 count=256 conv=fsync 2> /dev/null && [ "$(wc -c < "$f")" -eq 268435456 ]; rc=$?; rm -f "$f" || exit $?; exit "$rc"',
|
|
19
|
+
},
|
|
9
20
|
];
|
|
10
21
|
// 200,000 small records through JSON, a regex and a sort: the kind of thing a code-interpreter call does.
|
|
11
22
|
const PYTHON = [
|
|
@@ -15,7 +26,7 @@ const PYTHON = [
|
|
|
15
26
|
"back = json.loads(json.dumps(rows))",
|
|
16
27
|
"hits = sum(1 for r in back if re.search('abc', r['name']))",
|
|
17
28
|
"top = sorted(back, key=lambda r: (r['name'], r['v']))[:10]",
|
|
18
|
-
"
|
|
29
|
+
"if (hits, top[0]['id']) != (2837, 68550): raise SystemExit('Python output check failed')",
|
|
19
30
|
].join("\n");
|
|
20
31
|
// The Node.js 22.11.0 Linux release (53 MB), from nodejs.org's CDN: a real download, like installing a toolchain.
|
|
21
32
|
const DOWNLOAD_URL = "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-x64.tar.gz";
|
|
@@ -28,20 +39,22 @@ const FETCH = [
|
|
|
28
39
|
'case "$(uname -m)" in aarch64|arm64) A=arm64 ;; *) A=x64 ;; esac',
|
|
29
40
|
`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
41
|
"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
|
|
32
|
-
|
|
33
|
-
"
|
|
42
|
+
`get "${NODE_BASE}-$A.tar.gz" /tmp/sr-node.tgz || exit $?`,
|
|
43
|
+
"tar xzf /tmp/sr-node.tgz -C /tmp/sr-node --strip-components=1",
|
|
44
|
+
`get "${REPO_TARBALL}" /tmp/sr-repo.tgz || exit $?`,
|
|
45
|
+
"tar xzf /tmp/sr-repo.tgz -C /tmp/sr-repo --strip-components=1",
|
|
46
|
+
"test -x /tmp/sr-node/bin/node && test -f /tmp/sr-repo/package-lock.json",
|
|
34
47
|
].join("\n");
|
|
35
48
|
const IN_REPO = "cd /tmp/sr-repo && PATH=/tmp/sr-node/bin:$PATH";
|
|
36
49
|
// One tool call in the agent loop: a little real work, like reading files and running a check.
|
|
37
50
|
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
51
|
/** `cpuUtilization`: the hint the job's sandboxes start with (the agent loop is mostly idle), which Modal reserves and pricing uses. */
|
|
39
52
|
export const TASKS = {
|
|
40
|
-
short: { version: "
|
|
41
|
-
long: { version: "
|
|
42
|
-
python: { version: "python-
|
|
53
|
+
short: { version: "v2", repeat: 1, phases: HASH_DISK },
|
|
54
|
+
long: { version: "v2-long", repeat: 40, phases: HASH_DISK },
|
|
55
|
+
python: { version: "python-v2", repeat: 1, phases: [{ id: "python", label: "Python", cmd: `python3 -c "${PYTHON}"` }] },
|
|
43
56
|
repo: {
|
|
44
|
-
version: "repo-
|
|
57
|
+
version: "repo-v2",
|
|
45
58
|
repeat: 1,
|
|
46
59
|
phases: [
|
|
47
60
|
{ id: "fetch", label: "fetch Node and the repo", cmd: FETCH, timeoutSeconds: 600 },
|
|
@@ -50,13 +63,13 @@ export const TASKS = {
|
|
|
50
63
|
],
|
|
51
64
|
},
|
|
52
65
|
agent: {
|
|
53
|
-
version: "agent-
|
|
66
|
+
version: "agent-v2",
|
|
54
67
|
repeat: 1,
|
|
55
68
|
cpuUtilization: 0.1,
|
|
56
|
-
phases: [{ id: "agent", label: "10 turns", cmd: `n=0; while [ $n -lt 10 ]; do sleep 6
|
|
69
|
+
phases: [{ id: "agent", label: "10 turns", cmd: `n=0; while [ $n -lt 10 ]; do sleep 6 && python3 -c "${TOOL}" > /dev/null || exit $?; n=$((n+1)); done` }],
|
|
57
70
|
},
|
|
58
71
|
download: {
|
|
59
|
-
version: "download-
|
|
72
|
+
version: "download-v2",
|
|
60
73
|
repeat: 1,
|
|
61
74
|
phases: [
|
|
62
75
|
{
|
|
@@ -72,20 +85,25 @@ export const TASKS = {
|
|
|
72
85
|
/** The short task's version and phases, which is what plain `bench --task` records. */
|
|
73
86
|
export const TASK_VERSION = TASKS.short.version;
|
|
74
87
|
export const TASK_PHASES = TASKS.short.phases;
|
|
75
|
-
|
|
88
|
+
const LEGACY_TASKS = {
|
|
89
|
+
v1: "short", "v1-long": "long", "python-v1": "python", "repo-v1": "repo", "agent-v1": "agent", "download-v1": "download",
|
|
90
|
+
};
|
|
91
|
+
export const isCurrentTask = (version) => Object.values(TASKS).some((t) => t.version === version);
|
|
92
|
+
/** Legacy reports keep their original phase schema for validation and archival. */
|
|
76
93
|
export function taskByVersion(version) {
|
|
77
|
-
return Object.values(TASKS).find((t) => t.version === version)
|
|
94
|
+
return Object.values(TASKS).find((t) => t.version === version) ??
|
|
95
|
+
(typeof version === "string" && Object.hasOwn(LEGACY_TASKS, version) ? TASKS[LEGACY_TASKS[version]] : undefined);
|
|
78
96
|
}
|
|
79
97
|
/** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
|
|
80
98
|
export function phaseCommand(cmd, repeat) {
|
|
81
|
-
return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do ${cmd}
|
|
99
|
+
return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do (${cmd}) || exit $?; n=$((n+1)); done`;
|
|
82
100
|
}
|
|
83
101
|
// Wraps a phase to read /proc/stat's total CPU line before and after it, so the run also reports the CPU
|
|
84
102
|
// time it really used: what providers that bill active CPU charge for.
|
|
85
103
|
const MARK = "SRCPU";
|
|
86
104
|
// Every "cpu" line (the total, then one per core), joined with ";" so the reading stays on one output line.
|
|
87
105
|
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`;
|
|
106
|
+
const withCpu = (cmd) => `a=$(${STAT}); (${cmd}); rc=$?; b=$(${STAT}); echo "${MARK}|$a|$b"; exit $rc`;
|
|
89
107
|
/** Busy ticks on one /proc/stat cpu line: user, nice, system, irq and softirq (not idle, iowait or steal). */
|
|
90
108
|
const lineTicks = (line) => {
|
|
91
109
|
const f = line.trim().split(/\s+/);
|
|
@@ -118,7 +136,8 @@ export async function runTask(box, kind = "short") {
|
|
|
118
136
|
const rtt = [];
|
|
119
137
|
for (let i = 0; i < 3; i++) {
|
|
120
138
|
const t = performance.now();
|
|
121
|
-
await box.exec("true")
|
|
139
|
+
if ((await box.exec("true")).exitCode !== 0)
|
|
140
|
+
throw new Error("task round-trip probe failed");
|
|
122
141
|
rtt.push(performance.now() - t);
|
|
123
142
|
}
|
|
124
143
|
const overhead = rtt.sort((a, b) => a - b)[1];
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type ProviderId = "maritime" | "e2b" | "daytona" | "modal" | "vercel" | "morph" | "sprites" | "blaxel" | "tensorlake" | "runloop" | "hopx" | "cloudflare" | "northflank" | "boat" | "exedev" | "docker" | "novita" | "langsmith" | "alibaba" | "upstash" | "koyeb" | "freestyle" | "deno" | "beam" | "codesandbox" | "azure" | "agentcore" | "lambda" | "dedalus" | "agent37" | "superserve" | "instabox" | "openscale" | "sail";
|
|
2
2
|
/** Things a caller can require of a provider. The router skips providers that lack one. */
|
|
3
|
-
export type Capability = "gpu" | "pause" | "custom-image";
|
|
3
|
+
export type Capability = "gpu" | "pause" | "ports" | "background" | "custom-image";
|
|
4
4
|
/** What the caller wants. Every field is optional; providers map it to their own knobs. */
|
|
5
5
|
export interface SandboxSpec {
|
|
6
6
|
/**
|
|
@@ -16,6 +16,8 @@ export interface SandboxSpec {
|
|
|
16
16
|
gpu?: string;
|
|
17
17
|
/** Env vars set for every command. */
|
|
18
18
|
env?: Record<string, string>;
|
|
19
|
+
/** HTTP ports to make available for previews. Some providers need these when the sandbox is created. */
|
|
20
|
+
ports?: number[];
|
|
19
21
|
/** Hard lifetime in minutes (default 30). */
|
|
20
22
|
timeoutMinutes?: number;
|
|
21
23
|
/**
|
|
@@ -79,10 +81,11 @@ export interface RouteOptions {
|
|
|
79
81
|
/** Capabilities every candidate must have. */
|
|
80
82
|
require?: Capability[];
|
|
81
83
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
+
* An estimated effective hourly price limit for routing, in USD. A provider is skipped when this run
|
|
85
|
+
* is estimated to cost more there: hourly price, minimum charge and billing increment over
|
|
84
86
|
* `expectedSeconds` (else `timeoutMinutes`, default 30), plus any per-sandbox charge, divided by the
|
|
85
|
-
* run's hours.
|
|
87
|
+
* run's hours. This does not stop the sandbox or enforce a budget. Requests with unpriced GPU
|
|
88
|
+
* charges cannot use this limit. Omit for no cap.
|
|
86
89
|
*/
|
|
87
90
|
maxHourlyUsd?: number;
|
|
88
91
|
}
|
|
@@ -102,6 +105,15 @@ export interface ExecResult {
|
|
|
102
105
|
stderr: string;
|
|
103
106
|
durationMs: number;
|
|
104
107
|
}
|
|
108
|
+
/** A background command uses the sandbox lifetime and returns once the provider starts it. */
|
|
109
|
+
export type StartOptions = Pick<ExecOptions, "cwd" | "env">;
|
|
110
|
+
export interface ProviderProcess {
|
|
111
|
+
kill(): Promise<void>;
|
|
112
|
+
}
|
|
113
|
+
/** A background command started by a routed sandbox. */
|
|
114
|
+
export interface SandboxProcess extends ProviderProcess {
|
|
115
|
+
readonly id: string;
|
|
116
|
+
}
|
|
105
117
|
/** A live sandbox as one provider sees it. Adapters implement this. */
|
|
106
118
|
export interface ProviderSandbox {
|
|
107
119
|
readonly nativeId: string;
|
|
@@ -116,6 +128,10 @@ export interface ProviderSandbox {
|
|
|
116
128
|
kill(): Promise<void>;
|
|
117
129
|
/** Present only on adapters with the "pause" capability. */
|
|
118
130
|
pause?(): Promise<void>;
|
|
131
|
+
/** Present on adapters with the "ports" capability. */
|
|
132
|
+
url?(port: number): string | Promise<string>;
|
|
133
|
+
/** Present on adapters with the "background" capability. */
|
|
134
|
+
start?(cmd: string, opts?: StartOptions): Promise<ProviderProcess>;
|
|
119
135
|
}
|
|
120
136
|
export interface Provider {
|
|
121
137
|
readonly id: ProviderId;
|
package/dist/validate.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { type RouteOptions, type SandboxSpec, type Strategy } from "./types.js";
|
|
1
|
+
import { type RouteOptions, type SandboxSpec, type StartOptions, 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", "cpuUtilization", "image", "metadata"];
|
|
3
|
+
export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "ports", "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[];
|
|
7
|
+
export declare function isPort(value: unknown): value is number;
|
|
8
|
+
export declare function validateStart(cmd: unknown, opts?: StartOptions): asserts cmd is string;
|
|
7
9
|
/**
|
|
8
10
|
* Throws RouterError("bad_request") for a spec or route a provider couldn't make sense of: sizes and
|
|
9
11
|
* times that aren't positive numbers, an unknown strategy or fallback, maps that aren't string maps.
|
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", "cpuUtilization", "image", "metadata"];
|
|
4
|
+
export const SPEC_KEYS = ["vcpu", "memoryGb", "gpu", "env", "ports", "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"];
|
|
@@ -10,6 +10,20 @@ const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
|
10
10
|
/** How a bad value is shown: numbers as-is (NaN, Infinity), anything else as JSON. */
|
|
11
11
|
const show = (v) => (typeof v === "number" ? String(v) : JSON.stringify(v));
|
|
12
12
|
const stringMap = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
|
|
13
|
+
export function isPort(value) {
|
|
14
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
15
|
+
}
|
|
16
|
+
export function validateStart(cmd, opts = {}) {
|
|
17
|
+
if (typeof cmd !== "string" || !cmd.trim() || cmd.includes("\0"))
|
|
18
|
+
throw bad("cmd must be a non-empty command string");
|
|
19
|
+
if (!opts || typeof opts !== "object" || Array.isArray(opts) || Object.keys(opts).some((key) => key !== "cwd" && key !== "env")) {
|
|
20
|
+
throw bad("background command options are cwd and env");
|
|
21
|
+
}
|
|
22
|
+
if (opts.cwd !== undefined && (typeof opts.cwd !== "string" || !opts.cwd || opts.cwd.includes("\0")))
|
|
23
|
+
throw bad("cwd must be a non-empty path string");
|
|
24
|
+
if (opts.env !== undefined && !stringMap(opts.env))
|
|
25
|
+
throw bad("env must be an object of strings");
|
|
26
|
+
}
|
|
13
27
|
/**
|
|
14
28
|
* Throws RouterError("bad_request") for a spec or route a provider couldn't make sense of: sizes and
|
|
15
29
|
* times that aren't positive numbers, an unknown strategy or fallback, maps that aren't string maps.
|
|
@@ -25,6 +39,9 @@ export function validate(spec = {}, route = {}) {
|
|
|
25
39
|
}
|
|
26
40
|
if (spec.gpu !== undefined && (typeof spec.gpu !== "string" || !spec.gpu))
|
|
27
41
|
throw bad(`gpu must be a GPU type such as "T4", got ${JSON.stringify(spec.gpu)}`);
|
|
42
|
+
if (spec.ports !== undefined && (!Array.isArray(spec.ports) || ![...spec.ports].every(isPort) || new Set(spec.ports).size !== spec.ports.length)) {
|
|
43
|
+
throw bad("ports must be an array of distinct integers from 1 to 65535");
|
|
44
|
+
}
|
|
28
45
|
for (const k of ["env", "image", "metadata"]) {
|
|
29
46
|
if (spec[k] !== undefined && !stringMap(spec[k]))
|
|
30
47
|
throw bad(`${k} must be an object of strings`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sandboxrouter/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.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",
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"test": "vitest run",
|
|
25
25
|
"typecheck": "tsc --noEmit",
|
|
26
26
|
"dev": "tsx src/cli.ts",
|
|
27
|
-
"prepublishOnly": "npm run
|
|
27
|
+
"prepublishOnly": "npm run test:package && npm test",
|
|
28
|
+
"test:package": "npm run build && node scripts/check-package.mjs",
|
|
28
29
|
"test:py": "python3 -m unittest discover -s python/tests -v",
|
|
29
30
|
"site:data": "node --import tsx scripts/site-data.ts",
|
|
30
31
|
"price:check": "node --import tsx scripts/price-watch.ts",
|
|
@@ -201,5 +202,19 @@
|
|
|
201
202
|
"type": "git",
|
|
202
203
|
"url": "git+https://github.com/gigialc/sandboxrouter.git"
|
|
203
204
|
},
|
|
204
|
-
"homepage": "https://sandboxrouter.ai"
|
|
205
|
+
"homepage": "https://sandboxrouter.ai",
|
|
206
|
+
"overrides": {
|
|
207
|
+
"@hey-api/json-schema-ref-parser": {
|
|
208
|
+
"js-yaml": "^4.3.2"
|
|
209
|
+
},
|
|
210
|
+
"@hopx-ai/sdk": {
|
|
211
|
+
"glob": "^14.0.2"
|
|
212
|
+
},
|
|
213
|
+
"@vercel/cli-config": {
|
|
214
|
+
"zod": "^4.6.6"
|
|
215
|
+
},
|
|
216
|
+
"archiver-utils": {
|
|
217
|
+
"glob": "^14.0.2"
|
|
218
|
+
}
|
|
219
|
+
}
|
|
205
220
|
}
|