@sandboxrouter/sdk 0.13.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/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: files that aren't one of the three
6
- * formats, unknown providers, impossible numbers, anything that looks like a key, and labels that
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 bench report, a burst report, a spread report, an agent report, a saved check or a cost run`);
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, for what the router doesn't cover: ports, background processes,
261
- * snapshots, anything else the provider has. Narrow it with the provider's own type, e.g.
262
- * `if (sbx.provider === "e2b") (sbx.native as import("e2b").Sandbox).getHost(3000)`. Undefined for providers
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,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, 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";
@@ -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";
@@ -506,10 +507,9 @@ export class RoutedSandbox {
506
507
  return this.box.nativeId;
507
508
  }
508
509
  /**
509
- * The provider SDK's own sandbox object, for what the router doesn't cover: ports, background processes,
510
- * snapshots, anything else the provider has. Narrow it with the provider's own type, e.g.
511
- * `if (sbx.provider === "e2b") (sbx.native as import("e2b").Sandbox).getHost(3000)`. Undefined for providers
512
- * driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
510
+ * The provider SDK's own sandbox object for provider-specific features such as snapshots. Narrow it
511
+ * with the provider's own type. Undefined for providers driven over plain HTTP (use `nativeId` with
512
+ * their API). Calls made through it aren't routed or tracked.
513
513
  */
514
514
  get native() {
515
515
  return this.box.native;
@@ -524,6 +524,40 @@ export class RoutedSandbox {
524
524
  const seconds = opts.timeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_S;
525
525
  return withDeadline(this.box.exec(cmd, opts), (seconds + EXEC_GRACE_S) * 1000, () => timeoutError(this.provider, seconds));
526
526
  }
527
+ /** Get the provider's HTTP preview URL for a service listening on this port. */
528
+ async url(port) {
529
+ if (!isPort(port))
530
+ throw new RouterError("port must be an integer from 1 to 65535", [], "bad_request");
531
+ if (!this.box.url)
532
+ throw new RouterError(`${this.provider} does not support port URLs; create with require: ["ports"]`, [], "unsupported");
533
+ const preview = await this.box.url(port);
534
+ if (!/^https?:\/\//i.test(preview) || !URL.canParse(preview)) {
535
+ throw new ProviderError(this.provider, "invalid HTTP preview URL", 502);
536
+ }
537
+ return preview;
538
+ }
539
+ /** Start a command and return a handle that stops it without stopping the sandbox. */
540
+ async start(cmd, opts = {}) {
541
+ validateStart(cmd, opts);
542
+ if (!this.box.start)
543
+ throw new RouterError(`${this.provider} does not support background commands; create with require: ["background"]`, [], "unsupported");
544
+ const pending = this.box.start(cmd, opts);
545
+ const handle = await withDeadline(pending, (DEFAULT_EXEC_TIMEOUT_S + EXEC_GRACE_S) * 1000, () => {
546
+ // The caller has no handle if the provider answers after the start deadline.
547
+ void pending.then((late) => late.kill()).catch(() => { });
548
+ return new ProviderError(this.provider, "background command start timed out", 504);
549
+ });
550
+ let stopping;
551
+ return {
552
+ id: randomUUID(),
553
+ kill: () => stopping ??= Promise.resolve().then(() => handle.kill()).catch((error) => {
554
+ if (errorStatus(error) === 404)
555
+ return;
556
+ stopping = undefined;
557
+ throw error;
558
+ }),
559
+ };
560
+ }
527
561
  writeFile(path, content) {
528
562
  return this.box.writeFile(path, content);
529
563
  }
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 box = async (id) => {
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
- return live.get(id) ?? router.get(id);
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
- await made.kill().catch(() => { });
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
- live.delete(id);
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
- live.delete(id);
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
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
  /**
@@ -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;
@@ -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.13.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",