@sandboxrouter/sdk 0.13.0 → 0.14.1
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 +9 -7
- package/dist/billing.js +0 -1
- package/dist/catalog.d.ts +29 -2
- package/dist/catalog.js +73 -15
- package/dist/cli.js +3 -1
- package/dist/client.d.ts +6 -1
- package/dist/client.js +19 -0
- package/dist/cost.d.ts +44 -5
- package/dist/cost.js +54 -24
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/providers/beam.js +5 -4
- 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/digitalocean.d.ts +16 -0
- package/dist/providers/digitalocean.js +174 -0
- package/dist/providers/docker.d.ts +1 -0
- package/dist/providers/docker.js +17 -0
- package/dist/providers/e2b.d.ts +22 -1
- package/dist/providers/e2b.js +50 -3
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +206 -0
- package/dist/providers/hopx.js +12 -0
- package/dist/providers/modal.js +7 -0
- package/dist/providers/morph.js +3 -2
- package/dist/providers/northflank.js +20 -3
- package/dist/providers/novita.js +5 -5
- package/dist/providers/sail.js +4 -4
- package/dist/providers/shell-files.d.ts +12 -0
- package/dist/providers/shell-files.js +52 -0
- package/dist/providers/vercel.js +39 -1
- package/dist/published.js +957 -2
- package/dist/results.d.ts +2 -2
- package/dist/results.js +62 -1
- package/dist/router.d.ts +8 -5
- package/dist/router.js +49 -6
- package/dist/server.d.ts +4 -1
- package/dist/server.js +101 -7
- package/dist/types.d.ts +18 -3
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +18 -1
- package/dist/verified.js +4 -0
- package/package.json +5 -1
package/dist/results.d.ts
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Checks for the files people submit to results/: bench reports, saved `check` runs and `cost` runs.
|
|
3
3
|
*
|
|
4
4
|
* Submissions are self-reported, so nothing here can prove a number is real. What it can do is keep
|
|
5
|
-
* the obvious problems out before a maintainer reviews the PR:
|
|
6
|
-
*
|
|
5
|
+
* the obvious problems out before a maintainer reviews the PR: unsupported formats, unknown
|
|
6
|
+
* providers, impossible numbers, anything that looks like a key, and labels that
|
|
7
7
|
* look like a home address or an email. CI runs it on every push and pull request
|
|
8
8
|
* (`npm run results:check`), and on a pull request it also refuses edits to someone else's bench
|
|
9
9
|
* report: a new run is a new file.
|
package/dist/results.js
CHANGED
|
@@ -306,13 +306,74 @@ export function validateResult(j, now = Date.now()) {
|
|
|
306
306
|
out.push(`${e?.provider}: predictedUsd is out of range`);
|
|
307
307
|
if (e?.bill?.usd !== undefined && !isNum(e.bill.usd, 0, 1000))
|
|
308
308
|
out.push(`${e?.provider}: bill.usd is out of range`);
|
|
309
|
+
if (e?.bill?.kind !== undefined && !["provider-usage", "provider-estimate"].includes(e.bill.kind)) {
|
|
310
|
+
out.push(`${e?.provider}: invalid billing evidence kind`);
|
|
311
|
+
}
|
|
312
|
+
if (e?.bill?.resolutionUsd !== undefined && !isNum(e.bill.resolutionUsd, 0.000001, 1)) {
|
|
313
|
+
out.push(`${e?.provider}: billing resolution is out of range`);
|
|
314
|
+
}
|
|
309
315
|
if (e?.delivered && !(isNum(e.delivered.vcpu, 0.1, 1024) && isNum(e.delivered.memoryMb, 64, 4_194_304))) {
|
|
310
316
|
out.push(`${e?.provider}: delivered size is out of range`);
|
|
311
317
|
}
|
|
312
318
|
}
|
|
313
319
|
}
|
|
320
|
+
else if (j.tool === "sandboxrouter-hosted-ledger") {
|
|
321
|
+
add(checkDate(j.date, now));
|
|
322
|
+
const runFields = new Set(["tool", "date", "entries", "keySpendDeltaUsd"]);
|
|
323
|
+
if (Object.keys(j).some((key) => !runFields.has(key)))
|
|
324
|
+
out.push("hosted ledger reports must contain only public billing fields");
|
|
325
|
+
if (j.keySpendDeltaUsd !== undefined && !isNum(j.keySpendDeltaUsd, 0, 1000))
|
|
326
|
+
out.push("invalid total key spend delta");
|
|
327
|
+
if (!Array.isArray(j.entries) || !j.entries.length)
|
|
328
|
+
out.push("entries is empty");
|
|
329
|
+
const fields = new Set([
|
|
330
|
+
"provider", "requested", "size", "expectedSeconds", "runtimeSeconds", "quoteUsd", "chargeUsd", "quoteAtRecordedRuntimeUsd",
|
|
331
|
+
"balanceDeltaUsd", "keySpendDeltaUsd", "minimumSeconds", "minimumCovers", "incrementSeconds",
|
|
332
|
+
"feePct", "checkedAt", "createMs", "commandMs", "belowQuotedCapRejected", "commandVerified", "deleted",
|
|
333
|
+
]);
|
|
334
|
+
for (const e of Array.isArray(j.entries) ? j.entries : []) {
|
|
335
|
+
provider(e?.provider, "entry provider");
|
|
336
|
+
if (noBench(e?.provider))
|
|
337
|
+
out.push(`${e.provider}: ${NO_BENCH}`);
|
|
338
|
+
if (Object.keys(e ?? {}).some((key) => !fields.has(key)))
|
|
339
|
+
out.push("hosted ledger entries must contain only public billing fields");
|
|
340
|
+
if (![e?.requested, e?.size].every((size) => isSize(size) && Object.keys(size).length === 2)) {
|
|
341
|
+
out.push(`${e?.provider}: sandbox sizes must contain only vcpu and memoryGb`);
|
|
342
|
+
}
|
|
343
|
+
for (const key of ["expectedSeconds", "runtimeSeconds"]) {
|
|
344
|
+
if (!isNum(e?.[key], 0, 24 * 3600))
|
|
345
|
+
out.push(`${e?.provider}: invalid ${key}`);
|
|
346
|
+
}
|
|
347
|
+
for (const key of ["quoteUsd", "chargeUsd", "balanceDeltaUsd"]) {
|
|
348
|
+
if (!isNum(e?.[key], 0, 1000))
|
|
349
|
+
out.push(`${e?.provider}: invalid ${key}`);
|
|
350
|
+
}
|
|
351
|
+
if (e?.keySpendDeltaUsd !== undefined && !isNum(e.keySpendDeltaUsd, 0, 1000))
|
|
352
|
+
out.push(`${e.provider}: invalid keySpendDeltaUsd`);
|
|
353
|
+
if (e?.quoteAtRecordedRuntimeUsd !== undefined && !isNum(e.quoteAtRecordedRuntimeUsd, 0, 1000))
|
|
354
|
+
out.push(`${e.provider}: invalid runtime quote`);
|
|
355
|
+
if (e?.minimumSeconds !== undefined && !isNum(e.minimumSeconds, 0, 24 * 3600))
|
|
356
|
+
out.push(`${e.provider}: invalid minimumSeconds`);
|
|
357
|
+
if (e?.minimumCovers !== undefined && !["all", "memory"].includes(e.minimumCovers))
|
|
358
|
+
out.push(`${e.provider}: invalid minimumCovers`);
|
|
359
|
+
if (e?.incrementSeconds !== undefined && !isNum(e.incrementSeconds, 1, 24 * 3600))
|
|
360
|
+
out.push(`${e.provider}: invalid incrementSeconds`);
|
|
361
|
+
if (!isNum(e?.feePct, 0, 100))
|
|
362
|
+
out.push(`${e?.provider}: invalid feePct`);
|
|
363
|
+
if (e?.checkedAt !== undefined)
|
|
364
|
+
add(checkDate(e.checkedAt, now));
|
|
365
|
+
for (const key of ["createMs", "commandMs"]) {
|
|
366
|
+
if (e?.[key] !== undefined && !isNum(e[key], 0, MAX_MS))
|
|
367
|
+
out.push(`${e.provider}: invalid ${key}`);
|
|
368
|
+
}
|
|
369
|
+
if (e?.belowQuotedCapRejected !== undefined && typeof e.belowQuotedCapRejected !== "boolean")
|
|
370
|
+
out.push(`${e.provider}: invalid cap check`);
|
|
371
|
+
if (e?.commandVerified !== true || e?.deleted !== true)
|
|
372
|
+
out.push(`${e?.provider}: command output and deletion must be verified`);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
314
375
|
else {
|
|
315
|
-
out.push(`unknown tool "${String(j.tool)}": expected a
|
|
376
|
+
out.push(`unknown tool "${String(j.tool)}": expected a benchmark report, saved check, cost run or hosted ledger check`);
|
|
316
377
|
}
|
|
317
378
|
return out;
|
|
318
379
|
}
|
package/dist/router.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type ProviderInfo } from "./catalog.js";
|
|
2
2
|
import { type ComputerRoute, RoutedComputer, type ComputerOs, type ComputerProvider, type ComputerProviderId, type ComputerSpec } from "./computers.js";
|
|
3
3
|
import { Ledger } from "./ledger.js";
|
|
4
|
-
import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxSpec } from "./types.js";
|
|
4
|
+
import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxProcess, type SandboxSpec, type StartOptions } from "./types.js";
|
|
5
5
|
/** vCPUs and memory a sandbox gets. */
|
|
6
6
|
export interface Size {
|
|
7
7
|
vcpu: number;
|
|
@@ -257,10 +257,9 @@ export declare class RoutedSandbox {
|
|
|
257
257
|
attempts: Attempt[], price?: SandboxPrice, ledger?: Ledger | undefined);
|
|
258
258
|
get nativeId(): string;
|
|
259
259
|
/**
|
|
260
|
-
* The provider SDK's own sandbox object
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
* driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
|
|
260
|
+
* The provider SDK's own sandbox object for provider-specific features such as snapshots. Narrow it
|
|
261
|
+
* with the provider's own type. Undefined for providers driven over plain HTTP (use `nativeId` with
|
|
262
|
+
* their API). Calls made through it aren't routed or tracked.
|
|
264
263
|
*/
|
|
265
264
|
get native(): unknown;
|
|
266
265
|
/**
|
|
@@ -270,6 +269,10 @@ export declare class RoutedSandbox {
|
|
|
270
269
|
* always rely on the timeout being bounded and the message being the same on every provider.
|
|
271
270
|
*/
|
|
272
271
|
exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
|
|
272
|
+
/** Get the provider's HTTP preview URL for a service listening on this port. */
|
|
273
|
+
url(port: number): Promise<string>;
|
|
274
|
+
/** Start a command and return a handle that stops it without stopping the sandbox. */
|
|
275
|
+
start(cmd: string, opts?: StartOptions): Promise<SandboxProcess>;
|
|
273
276
|
writeFile(path: string, content: string | Uint8Array): Promise<void>;
|
|
274
277
|
readFile(path: string): Promise<Uint8Array>;
|
|
275
278
|
readText(path: string): Promise<string>;
|
package/dist/router.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, digitalOceanSize, fixedSize, hourlyCost, info, unfit, vercelSandboxSize } from "./catalog.js";
|
|
2
3
|
import { RoutedComputer, createComputer, planComputer, } from "./computers.js";
|
|
3
4
|
import { loadBench, median } from "./bench-store.js";
|
|
4
5
|
import { PUBLISHED } from "./published.js";
|
|
@@ -6,7 +7,7 @@ import { Ledger, defaultLedgerFile } from "./ledger.js";
|
|
|
6
7
|
import { DEFAULT_EXEC_TIMEOUT_S, LIMIT_ERROR, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
|
|
7
8
|
import { BILLED_VS_LIST } from "./billing.js";
|
|
8
9
|
import { FAILING, VERIFIED } from "./verified.js";
|
|
9
|
-
import { validate } from "./validate.js";
|
|
10
|
+
import { isPort, validate, validateStart } from "./validate.js";
|
|
10
11
|
import { DaytonaProvider } from "./providers/daytona.js";
|
|
11
12
|
import { E2BProvider } from "./providers/e2b.js";
|
|
12
13
|
import { MaritimeProvider } from "./providers/maritime.js";
|
|
@@ -24,6 +25,8 @@ import { NorthflankProvider } from "./providers/northflank.js";
|
|
|
24
25
|
import { BoatProvider } from "./providers/boat.js";
|
|
25
26
|
import { ExeDevProvider } from "./providers/exedev.js";
|
|
26
27
|
import { AgentCoreProvider } from "./providers/agentcore.js";
|
|
28
|
+
import { DigitalOceanProvider } from "./providers/digitalocean.js";
|
|
29
|
+
import { GoogleAgentPlatformProvider } from "./providers/google.js";
|
|
27
30
|
import { AzureSessionsProvider } from "./providers/azure.js";
|
|
28
31
|
import { LambdaMicrovmProvider } from "./providers/lambda.js";
|
|
29
32
|
import { AlibabaProvider } from "./providers/alibaba.js";
|
|
@@ -79,6 +82,8 @@ export function defaultProviders() {
|
|
|
79
82
|
new ExeDevProvider(),
|
|
80
83
|
new AgentCoreProvider(),
|
|
81
84
|
new AzureSessionsProvider(),
|
|
85
|
+
new DigitalOceanProvider(),
|
|
86
|
+
new GoogleAgentPlatformProvider(),
|
|
82
87
|
new LambdaMicrovmProvider(),
|
|
83
88
|
new Agent37Provider(),
|
|
84
89
|
new AlibabaProvider(),
|
|
@@ -506,10 +511,9 @@ export class RoutedSandbox {
|
|
|
506
511
|
return this.box.nativeId;
|
|
507
512
|
}
|
|
508
513
|
/**
|
|
509
|
-
* The provider SDK's own sandbox object
|
|
510
|
-
*
|
|
511
|
-
*
|
|
512
|
-
* driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
|
|
514
|
+
* The provider SDK's own sandbox object for provider-specific features such as snapshots. Narrow it
|
|
515
|
+
* with the provider's own type. Undefined for providers driven over plain HTTP (use `nativeId` with
|
|
516
|
+
* their API). Calls made through it aren't routed or tracked.
|
|
513
517
|
*/
|
|
514
518
|
get native() {
|
|
515
519
|
return this.box.native;
|
|
@@ -524,6 +528,40 @@ export class RoutedSandbox {
|
|
|
524
528
|
const seconds = opts.timeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_S;
|
|
525
529
|
return withDeadline(this.box.exec(cmd, opts), (seconds + EXEC_GRACE_S) * 1000, () => timeoutError(this.provider, seconds));
|
|
526
530
|
}
|
|
531
|
+
/** Get the provider's HTTP preview URL for a service listening on this port. */
|
|
532
|
+
async url(port) {
|
|
533
|
+
if (!isPort(port))
|
|
534
|
+
throw new RouterError("port must be an integer from 1 to 65535", [], "bad_request");
|
|
535
|
+
if (!this.box.url)
|
|
536
|
+
throw new RouterError(`${this.provider} does not support port URLs; create with require: ["ports"]`, [], "unsupported");
|
|
537
|
+
const preview = await this.box.url(port);
|
|
538
|
+
if (!/^https?:\/\//i.test(preview) || !URL.canParse(preview)) {
|
|
539
|
+
throw new ProviderError(this.provider, "invalid HTTP preview URL", 502);
|
|
540
|
+
}
|
|
541
|
+
return preview;
|
|
542
|
+
}
|
|
543
|
+
/** Start a command and return a handle that stops it without stopping the sandbox. */
|
|
544
|
+
async start(cmd, opts = {}) {
|
|
545
|
+
validateStart(cmd, opts);
|
|
546
|
+
if (!this.box.start)
|
|
547
|
+
throw new RouterError(`${this.provider} does not support background commands; create with require: ["background"]`, [], "unsupported");
|
|
548
|
+
const pending = this.box.start(cmd, opts);
|
|
549
|
+
const handle = await withDeadline(pending, (DEFAULT_EXEC_TIMEOUT_S + EXEC_GRACE_S) * 1000, () => {
|
|
550
|
+
// The caller has no handle if the provider answers after the start deadline.
|
|
551
|
+
void pending.then((late) => late.kill()).catch(() => { });
|
|
552
|
+
return new ProviderError(this.provider, "background command start timed out", 504);
|
|
553
|
+
});
|
|
554
|
+
let stopping;
|
|
555
|
+
return {
|
|
556
|
+
id: randomUUID(),
|
|
557
|
+
kill: () => stopping ??= Promise.resolve().then(() => handle.kill()).catch((error) => {
|
|
558
|
+
if (errorStatus(error) === 404)
|
|
559
|
+
return;
|
|
560
|
+
stopping = undefined;
|
|
561
|
+
throw error;
|
|
562
|
+
}),
|
|
563
|
+
};
|
|
564
|
+
}
|
|
527
565
|
writeFile(path, content) {
|
|
528
566
|
return this.box.writeFile(path, content);
|
|
529
567
|
}
|
|
@@ -615,5 +653,10 @@ export const EXEC_GRACE_S = 30;
|
|
|
615
653
|
export function sizeOf(id, spec = {}) {
|
|
616
654
|
if (id === "vercel")
|
|
617
655
|
return vercelSandboxSize(spec);
|
|
656
|
+
if (id === "digitalocean") {
|
|
657
|
+
const shape = digitalOceanSize(spec.vcpu ?? DEFAULT_VCPU, spec.memoryGb ?? DEFAULT_MEMORY_GB);
|
|
658
|
+
if (shape)
|
|
659
|
+
return { vcpu: shape.vcpu, memoryGb: shape.memoryGb };
|
|
660
|
+
}
|
|
618
661
|
return fixedSize(id, spec) ?? { vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB };
|
|
619
662
|
}
|
package/dist/server.d.ts
CHANGED
|
@@ -61,11 +61,14 @@ export interface ServerHooks {
|
|
|
61
61
|
* GET /v1/providers
|
|
62
62
|
* POST /v1/route dry run: which providers would be tried, in order
|
|
63
63
|
* POST /v1/quote where a create would land and what the run would cost
|
|
64
|
-
* POST /v1/sandboxes { vcpu, memoryGb, ..., provider, strategy, fallback, require, createTimeoutSeconds }
|
|
64
|
+
* POST /v1/sandboxes { vcpu, memoryGb, ports, ..., provider, strategy, fallback, require, createTimeoutSeconds }
|
|
65
65
|
* POST /v1/sandboxes/:id/exec { cmd, cwd, env, timeoutSeconds, stream }
|
|
66
66
|
* stream: true answers text/event-stream: `stdout`/`stderr` events (JSON string chunks),
|
|
67
67
|
* then one `result` event (the ExecResult), or an `error` event
|
|
68
68
|
* POST /v1/sandboxes/:id/pause keeps the disk; the next call resumes it
|
|
69
|
+
* GET /v1/sandboxes/:id/ports/:port { url }
|
|
70
|
+
* POST /v1/sandboxes/:id/processes { cmd, cwd, env } -> { id }
|
|
71
|
+
* DELETE /v1/sandboxes/:id/processes/:processId
|
|
69
72
|
* PUT /v1/sandboxes/:id/files?path= raw body
|
|
70
73
|
* GET /v1/sandboxes/:id/files?path= raw body
|
|
71
74
|
* DELETE /v1/sandboxes/:id
|
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/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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";
|
|
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" | "digitalocean" | "google";
|
|
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
|
/**
|
|
@@ -28,7 +30,7 @@ export interface SandboxSpec {
|
|
|
28
30
|
expectedSeconds?: number;
|
|
29
31
|
/**
|
|
30
32
|
* 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
|
|
33
|
+
* while it's busy (Vercel, Cloudflare, Tensorlake, AgentCore, DigitalOcean, Sail, Sprites, Deno, Upstash) are priced
|
|
32
34
|
* at this share of their CPU plus their full memory, never below a provider's CPU floor. An agent that
|
|
33
35
|
* mostly waits on model calls uses about 0.1; a build or test run is close to 1.
|
|
34
36
|
*/
|
|
@@ -103,6 +105,15 @@ export interface ExecResult {
|
|
|
103
105
|
stderr: string;
|
|
104
106
|
durationMs: number;
|
|
105
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
|
+
}
|
|
106
117
|
/** A live sandbox as one provider sees it. Adapters implement this. */
|
|
107
118
|
export interface ProviderSandbox {
|
|
108
119
|
readonly nativeId: string;
|
|
@@ -117,6 +128,10 @@ export interface ProviderSandbox {
|
|
|
117
128
|
kill(): Promise<void>;
|
|
118
129
|
/** Present only on adapters with the "pause" capability. */
|
|
119
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>;
|
|
120
135
|
}
|
|
121
136
|
export interface Provider {
|
|
122
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/dist/verified.js
CHANGED
|
@@ -2,6 +2,7 @@ export const VERIFIED = {
|
|
|
2
2
|
agent37: "2026-11-13",
|
|
3
3
|
agentcore: "2026-11-13",
|
|
4
4
|
lambda: "2026-11-13",
|
|
5
|
+
beam: "2026-11-18",
|
|
5
6
|
blaxel: "2026-11-13",
|
|
6
7
|
boat: "2026-11-14",
|
|
7
8
|
cloudflare: "2026-11-13",
|
|
@@ -9,8 +10,11 @@ export const VERIFIED = {
|
|
|
9
10
|
e2b: "2026-11-13",
|
|
10
11
|
sprites: "2026-11-13",
|
|
11
12
|
freestyle: "2026-11-13",
|
|
13
|
+
google: "2026-11-18",
|
|
12
14
|
maritime: "2026-11-13",
|
|
13
15
|
modal: "2026-11-13",
|
|
16
|
+
morph: "2026-11-18",
|
|
17
|
+
northflank: "2026-11-18",
|
|
14
18
|
novita: "2026-11-13",
|
|
15
19
|
openscale: "2026-11-13",
|
|
16
20
|
sail: "2026-11-14",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sandboxrouter/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.1",
|
|
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",
|
|
@@ -88,6 +88,7 @@
|
|
|
88
88
|
"e2b": ">=2",
|
|
89
89
|
"modal": ">=0.11",
|
|
90
90
|
"morphcloud": ">=0.0.20",
|
|
91
|
+
"google-auth-library": "^10.0.0",
|
|
91
92
|
"@mobilerun/sdk": ">=6",
|
|
92
93
|
"@limrun/api": ">=0.69",
|
|
93
94
|
"@aws-sdk/client-appstream": ">=3",
|
|
@@ -116,6 +117,9 @@
|
|
|
116
117
|
"morphcloud": {
|
|
117
118
|
"optional": true
|
|
118
119
|
},
|
|
120
|
+
"google-auth-library": {
|
|
121
|
+
"optional": true
|
|
122
|
+
},
|
|
119
123
|
"@fly/sprites": {
|
|
120
124
|
"optional": true
|
|
121
125
|
},
|