@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.
Files changed (46) hide show
  1. package/README.md +9 -7
  2. package/dist/billing.js +0 -1
  3. package/dist/catalog.d.ts +29 -2
  4. package/dist/catalog.js +73 -15
  5. package/dist/cli.js +3 -1
  6. package/dist/client.d.ts +6 -1
  7. package/dist/client.js +19 -0
  8. package/dist/cost.d.ts +44 -5
  9. package/dist/cost.js +54 -24
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.js +2 -0
  12. package/dist/providers/beam.js +5 -4
  13. package/dist/providers/blaxel.d.ts +1 -0
  14. package/dist/providers/blaxel.js +56 -1
  15. package/dist/providers/daytona.js +33 -1
  16. package/dist/providers/deno.d.ts +3 -0
  17. package/dist/providers/deno.js +14 -0
  18. package/dist/providers/digitalocean.d.ts +16 -0
  19. package/dist/providers/digitalocean.js +174 -0
  20. package/dist/providers/docker.d.ts +1 -0
  21. package/dist/providers/docker.js +17 -0
  22. package/dist/providers/e2b.d.ts +22 -1
  23. package/dist/providers/e2b.js +50 -3
  24. package/dist/providers/google.d.ts +23 -0
  25. package/dist/providers/google.js +206 -0
  26. package/dist/providers/hopx.js +12 -0
  27. package/dist/providers/modal.js +7 -0
  28. package/dist/providers/morph.js +3 -2
  29. package/dist/providers/northflank.js +20 -3
  30. package/dist/providers/novita.js +5 -5
  31. package/dist/providers/sail.js +4 -4
  32. package/dist/providers/shell-files.d.ts +12 -0
  33. package/dist/providers/shell-files.js +52 -0
  34. package/dist/providers/vercel.js +39 -1
  35. package/dist/published.js +957 -2
  36. package/dist/results.d.ts +2 -2
  37. package/dist/results.js +62 -1
  38. package/dist/router.d.ts +8 -5
  39. package/dist/router.js +49 -6
  40. package/dist/server.d.ts +4 -1
  41. package/dist/server.js +101 -7
  42. package/dist/types.d.ts +18 -3
  43. package/dist/validate.d.ts +4 -2
  44. package/dist/validate.js +18 -1
  45. package/dist/verified.js +4 -0
  46. package/package.json +5 -1
@@ -0,0 +1,206 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { GOOGLE_SHELL_SIZE } from "../catalog.js";
3
+ import { ProviderError } from "../types.js";
4
+ import { DEFAULT_EXEC_TIMEOUT_S, killedByTimeout, optionalImport, timeoutError, wrapCommand } from "../util.js";
5
+ import { ShellFiles } from "./shell-files.js";
6
+ /**
7
+ * Gemini Enterprise Agent Platform shell sandboxes, using the Agent Platform regional REST API.
8
+ * Reuse a default shell template so that creating a sandbox does not leave behind a new template.
9
+ * The optional google-auth-library package supplies Application Default Credentials.
10
+ * https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/sandbox/shell-sandbox-quickstart
11
+ * https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/sandbox/manage-templates
12
+ * Wire reference: https://github.com/googleapis/python-aiplatform/blob/main/agentplatform/_genai/sandboxes.py
13
+ */
14
+ const ID = "google";
15
+ const ENGINE_NAME = /^projects\/([\w-]+)\/locations\/([\w-]+)\/reasoningEngines\/[\w-]+$/;
16
+ const RESOURCE_NAME = /^(?:[\w-]+\/)*[\w-]+$/;
17
+ const OPERATION_TIMEOUT_MS = 110_000;
18
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
19
+ function dataChunk(mimeType, text) {
20
+ return { mimeType, data: Buffer.from(text).toString("base64") };
21
+ }
22
+ export class GoogleAgentPlatformProvider {
23
+ engine;
24
+ template;
25
+ token;
26
+ baseUrl;
27
+ id = ID;
28
+ auth;
29
+ constructor(engine = process.env.GOOGLE_SANDBOX_ENGINE, template = process.env.GOOGLE_SANDBOX_TEMPLATE, token = process.env.GOOGLE_SANDBOX_ACCESS_TOKEN, baseUrl) {
30
+ this.engine = engine;
31
+ this.template = template;
32
+ this.token = token;
33
+ this.baseUrl = baseUrl;
34
+ }
35
+ configured() {
36
+ return !!this.engine && !!this.template;
37
+ }
38
+ engineName() {
39
+ if (!this.engine || !ENGINE_NAME.test(this.engine) || !this.template || !RESOURCE_NAME.test(this.template)) {
40
+ throw new ProviderError(ID, "set GOOGLE_SANDBOX_ENGINE to projects/PROJECT/locations/LOCATION/reasoningEngines/ID and GOOGLE_SANDBOX_TEMPLATE to a shell template resource name");
41
+ }
42
+ return this.engine;
43
+ }
44
+ async headers(url) {
45
+ if (this.token)
46
+ return new Headers({ Authorization: `Bearer ${this.token}` });
47
+ this.auth ??= optionalImport("google-auth-library", ID).then(({ GoogleAuth }) => new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] }));
48
+ return new Headers(await (await this.auth).getRequestHeaders(url));
49
+ }
50
+ /** @internal */
51
+ async request(method, resource, body, timeoutMs = 30_000) {
52
+ const engine = this.engineName();
53
+ const [, project, location] = ENGINE_NAME.exec(engine);
54
+ const prefix = `projects/${project}/locations/${location}/`;
55
+ // Limit both user-supplied IDs and returned operation names to this project and region.
56
+ if (!resource.startsWith(prefix) || !RESOURCE_NAME.test(resource.replace(/\/:(?:execute|pause|resume)$/, ""))) {
57
+ throw new ProviderError(ID, "resource is outside the configured Agent Platform location");
58
+ }
59
+ const host = this.baseUrl ?? `https://${location}-aiplatform.googleapis.com`;
60
+ const url = `${host.replace(/\/$/, "")}/v1beta1/${resource}`;
61
+ const headers = await this.headers(url);
62
+ headers.set("Accept", "application/json");
63
+ if (body !== undefined)
64
+ headers.set("Content-Type", "application/json");
65
+ const response = await fetch(url, {
66
+ method,
67
+ headers,
68
+ body: body === undefined ? undefined : JSON.stringify(body),
69
+ redirect: "error",
70
+ signal: AbortSignal.timeout(timeoutMs),
71
+ });
72
+ const text = await response.text();
73
+ if (!response.ok) {
74
+ let detail = text.slice(0, 280);
75
+ try {
76
+ detail = JSON.parse(text).error?.message ?? detail;
77
+ }
78
+ catch { /* non-JSON error */ }
79
+ throw new ProviderError(ID, `${method}: HTTP ${response.status} ${detail}`, response.status);
80
+ }
81
+ return (text ? JSON.parse(text) : {});
82
+ }
83
+ sandboxName(id) {
84
+ const parent = `${this.engineName()}/sandboxEnvironments/`;
85
+ if (!id.startsWith(parent) || !/^[\w-]+$/.test(id.slice(parent.length))) {
86
+ throw new ProviderError(ID, "invalid sandbox name for the configured Agent Platform instance", 404);
87
+ }
88
+ return id;
89
+ }
90
+ async create(spec) {
91
+ const engine = this.engineName();
92
+ if ((spec.vcpu ?? 0) > GOOGLE_SHELL_SIZE.vcpu || (spec.memoryGb ?? 0) > GOOGLE_SHELL_SIZE.memoryGb) {
93
+ throw new ProviderError(ID, "the standard shell sandbox is 1 vCPU / 2 GiB");
94
+ }
95
+ const { response } = await this.wait(await this.request("POST", `${engine}/sandboxEnvironments`, {
96
+ displayName: `sbr-${randomBytes(8).toString("hex")}`,
97
+ spec: { shellEnvironment: {} },
98
+ sandboxEnvironmentTemplate: this.template,
99
+ ttl: `${Math.max(60, Math.ceil((spec.timeoutMinutes ?? 30) * 60))}s`,
100
+ }));
101
+ if (!response?.name)
102
+ throw new ProviderError(ID, "create operation returned no sandbox name");
103
+ const name = this.sandboxName(response.name);
104
+ try {
105
+ const resource = await this.request("GET", name);
106
+ if (resource.state !== "STATE_RUNNING")
107
+ throw new ProviderError(ID, `sandbox is ${resource.state ?? "not running"}`);
108
+ return new GoogleBox(this, name, spec.env);
109
+ }
110
+ catch (err) {
111
+ await this.remove(name).catch(() => { });
112
+ throw err;
113
+ }
114
+ }
115
+ async connect(nativeId) {
116
+ const name = this.sandboxName(nativeId);
117
+ const sandbox = await this.request("GET", name);
118
+ if (sandbox.state === "STATE_PAUSED")
119
+ await this.action(name, "resume");
120
+ else if (sandbox.state !== "STATE_RUNNING")
121
+ throw new ProviderError(ID, `sandbox is ${sandbox.state ?? "not running"}`);
122
+ return new GoogleBox(this, name);
123
+ }
124
+ /** @internal */
125
+ async action(name, action) {
126
+ await this.wait(await this.request("POST", `${this.sandboxName(name)}/:${action}`, {}));
127
+ }
128
+ /** @internal */
129
+ async remove(name) {
130
+ try {
131
+ await this.wait(await this.request("DELETE", this.sandboxName(name)));
132
+ }
133
+ catch (err) {
134
+ if (!(err instanceof ProviderError) || err.status !== 404)
135
+ throw err;
136
+ }
137
+ }
138
+ async wait(operation) {
139
+ // Some delete responses have an empty body.
140
+ const until = Date.now() + OPERATION_TIMEOUT_MS;
141
+ while (!operation.done && operation.name && Date.now() < until) {
142
+ await delay(500);
143
+ operation = await this.request("GET", operation.name);
144
+ }
145
+ if (operation.error) {
146
+ const status = { 5: 404, 7: 403, 8: 429, 16: 401 }[operation.error.code ?? 0];
147
+ throw new ProviderError(ID, operation.error.message ?? "sandbox operation failed", status);
148
+ }
149
+ if (operation.name && !operation.done)
150
+ throw new ProviderError(ID, "sandbox operation timed out", 504);
151
+ return operation;
152
+ }
153
+ }
154
+ class GoogleBox {
155
+ provider;
156
+ nativeId;
157
+ env;
158
+ files = new ShellFiles(ID, (command) => this.exec(command));
159
+ constructor(provider, nativeId, env) {
160
+ this.provider = provider;
161
+ this.nativeId = nativeId;
162
+ this.env = env;
163
+ }
164
+ async exec(command, opts = {}) {
165
+ const t0 = Date.now();
166
+ const seconds = Math.max(1, Math.ceil(opts.timeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_S));
167
+ const cmd = wrapCommand(command, { env: { ...this.env, ...opts.env } });
168
+ const inputs = [
169
+ dataChunk("application/x.sandbox-request-uri", "/exec"),
170
+ dataChunk("application/x.sandbox-request-port", "8080"),
171
+ dataChunk("application/json", JSON.stringify({ command: cmd, cwd: opts.cwd, timeout: seconds })),
172
+ ];
173
+ let result;
174
+ try {
175
+ result = await this.provider.request("POST", `${this.nativeId}/:execute`, { inputs }, (seconds + 15) * 1000);
176
+ }
177
+ catch (err) {
178
+ // Agent Platform wraps confirmed guest command kills in a 400 DEADLINE_EXCEEDED response.
179
+ if (err instanceof ProviderError &&
180
+ err.status === 400 &&
181
+ /\bDEADLINE_EXCEEDED\b/.test(err.message) &&
182
+ /\bcommand exceeded \d+(?:\.\d+)?s and was killed\b/i.test(err.message)) {
183
+ throw timeoutError(ID, seconds);
184
+ }
185
+ throw err;
186
+ }
187
+ const out = result.outputs?.find((chunk) => chunk.data)?.data;
188
+ if (!out)
189
+ throw new ProviderError(ID, "shell sandbox returned no output");
190
+ const { returncode, stdout = "", stderr = "", duration_ms } = JSON.parse(Buffer.from(out, "base64").toString("utf8"));
191
+ if (typeof returncode !== "number" || !Number.isInteger(returncode))
192
+ throw new ProviderError(ID, "shell sandbox returned no exit code");
193
+ const durationMs = duration_ms ?? Date.now() - t0;
194
+ if (killedByTimeout(returncode, durationMs, seconds))
195
+ throw timeoutError(ID, seconds);
196
+ if (stdout)
197
+ opts.onStdout?.(stdout);
198
+ if (stderr)
199
+ opts.onStderr?.(stderr);
200
+ return { stdout, stderr, exitCode: returncode, durationMs };
201
+ }
202
+ readFile(path) { return this.files.readFile(path); }
203
+ writeFile(path, data) { return this.files.writeFile(path, data); }
204
+ pause() { return this.provider.action(this.nativeId, "pause"); }
205
+ kill() { return this.provider.remove(this.nativeId); }
206
+ }
@@ -1,3 +1,4 @@
1
+ import { info } from "../catalog.js";
1
2
  import { ProviderError } from "../types.js";
2
3
  import { DEFAULT_EXEC_TIMEOUT_S, optionalImport, timeoutError, toBytes } from "../util.js";
3
4
  /** Public template used when spec.image.hopx is not set. */
@@ -54,6 +55,17 @@ class HopxBox {
54
55
  this.sbx = sbx;
55
56
  this.nativeId = sbx.sandboxId;
56
57
  }
58
+ async url(port) {
59
+ if (info("hopx").limits.reservedPorts?.includes(port)) {
60
+ throw new ProviderError("hopx", `port ${port} is reserved for the sandbox agent`, 400);
61
+ }
62
+ try {
63
+ return await this.sbx.getPreviewUrl(port);
64
+ }
65
+ catch (err) {
66
+ throw fail(err);
67
+ }
68
+ }
57
69
  async exec(cmd, opts = {}) {
58
70
  if (opts.onStdout || opts.onStderr)
59
71
  return this.execStreaming(cmd, opts);
@@ -35,6 +35,7 @@ export class ModalProvider {
35
35
  gpu: spec.gpu,
36
36
  timeoutMs: (spec.timeoutMinutes ?? 30) * 60_000,
37
37
  env: spec.env,
38
+ ...(spec.ports?.length ? { encryptedPorts: spec.ports } : {}),
38
39
  });
39
40
  return new ModalBox(sb);
40
41
  }
@@ -91,6 +92,12 @@ class ModalBox {
91
92
  throw new ProviderError("modal", message);
92
93
  }
93
94
  }
95
+ async url(port) {
96
+ const tunnel = (await this.sb.tunnels())[port];
97
+ if (!tunnel)
98
+ throw new ProviderError("modal", `port ${port} was not requested when this sandbox was created`, 400);
99
+ return tunnel.url;
100
+ }
94
101
  async writeFile(path, content) {
95
102
  await this.sb.filesystem.writeBytes(toBytes(content), path);
96
103
  }
@@ -109,8 +109,9 @@ class MorphBox {
109
109
  // and would leave the process running, so it is set past ours as a fallback.
110
110
  const script = guardTimeout(`[ -r ${ENV_FILE} ] && . ${ENV_FILE}; ${wrapCommand(cmd, { cwd: opts.cwd, env: opts.env })}`, seconds);
111
111
  try {
112
- // With callbacks the SDK switches to its SSE endpoint and streams; otherwise one request.
113
- const r = await this.inst.exec(["sh", "-c", script], {
112
+ // Morph joins command array entries into shell text. Pass the complete script so the
113
+ // timeout guard keeps its quoting on both buffered and streaming requests.
114
+ const r = await this.inst.exec(script, {
114
115
  timeout: seconds + 15,
115
116
  onStdout: opts.onStdout,
116
117
  onStderr: opts.onStderr,
@@ -7,6 +7,7 @@ const DEFAULT_IMAGE = "ubuntu:22.04";
7
7
  const MIN_EXPIRY_SECONDS = 300;
8
8
  const MAX_EXPIRY_SECONDS = 604_800;
9
9
  const READY_TIMEOUT_MS = 5 * 60_000;
10
+ const DELETE_TIMEOUT_MS = 60_000;
10
11
  /**
11
12
  * Northflank sandboxes via `@northflank/js-client`. Auth: NORTHFLANK_API_TOKEN plus
12
13
  * NORTHFLANK_PROJECT_ID (the project every sandbox is created in; its region is fixed at
@@ -155,7 +156,23 @@ class NorthflankBox {
155
156
  return new Uint8Array(Buffer.from(r.stdout, "base64"));
156
157
  }
157
158
  async kill() {
158
- await call(() => this.nf.delete.service({ parameters: this.params }));
159
+ try {
160
+ await call(() => this.nf.delete.service({ parameters: this.params }));
161
+ // The delete request acknowledges scheduling. The service can still execute commands
162
+ // until teardown completes, so keep polling until Northflank reports it gone.
163
+ const deadline = Date.now() + DELETE_TIMEOUT_MS;
164
+ for (;;) {
165
+ await this.info();
166
+ if (Date.now() >= deadline)
167
+ throw new ProviderError("northflank", `service ${this.nativeId} did not disappear after deletion`, 504);
168
+ await sleep(1000);
169
+ }
170
+ }
171
+ catch (err) {
172
+ if (err instanceof ProviderError && err.status === 404)
173
+ return;
174
+ throw err;
175
+ }
159
176
  }
160
177
  /** One exec session: optional stdin, streamed stdout/stderr, exit code. `expired` is thrown when limitMs passes. */
161
178
  async run(command, limitMs, opts = {}, stdin, expired = () => timeoutError("northflank", Math.round(limitMs / 1000))) {
@@ -190,7 +207,6 @@ class NorthflankBox {
190
207
  let timer;
191
208
  const timedOut = new Promise((resolve) => {
192
209
  timer = setTimeout(() => resolve("timeout"), limitMs);
193
- timer.unref();
194
210
  });
195
211
  try {
196
212
  const res = await Promise.race([session.waitForCommandResult(), failed, timedOut]);
@@ -255,5 +271,6 @@ function plan(vcpu, memoryGb) {
255
271
  return (fits[0] ?? PLANS[PLANS.length - 1])[0];
256
272
  }
257
273
  function sleep(ms) {
258
- return new Promise((r) => setTimeout(r, ms).unref());
274
+ // Keep standalone callers running until the next readiness poll.
275
+ return new Promise((r) => setTimeout(r, ms));
259
276
  }
@@ -1,10 +1,10 @@
1
1
  import { ProviderError } from "../types.js";
2
2
  import { optionalImport } from "../util.js";
3
- import { E2BBox } from "./e2b.js";
3
+ import { E2BNativeBox } from "./e2b.js";
4
4
  /**
5
5
  * Novita AI Agent Sandbox via the official `novita-sandbox` SDK (2.x), a fork of E2B's SDK with
6
- * the same surface (Sandbox.create/connect, commands.run with onStdout/onStderr, files.read/write,
7
- * pause, kill), so the E2B box wrapper is reused as-is.
6
+ * the same surface for creating, running and pausing sandboxes, including getHost and background
7
+ * command handles, so the E2B box wrapper is reused.
8
8
  *
9
9
  * Why not the `e2b` SDK with Novita's domain: that was Novita's documented route for its v1
10
10
  * cluster (sandbox.novita.ai), but since the 2026-06-08 SDK 2.0 release the E2B-compatible page
@@ -56,7 +56,7 @@ export class NovitaProvider {
56
56
  const template = spec.image?.novita;
57
57
  try {
58
58
  const sbx = template ? await Sandbox.create(template, opts) : await Sandbox.create(opts);
59
- return new E2BBox(sbx, ID);
59
+ return new E2BNativeBox(sbx, ID);
60
60
  }
61
61
  catch (err) {
62
62
  throw wrap(err);
@@ -66,7 +66,7 @@ export class NovitaProvider {
66
66
  async connect(nativeId) {
67
67
  const { Sandbox } = await optionalImport("novita-sandbox", "novita");
68
68
  try {
69
- return new E2BBox(await Sandbox.connect(nativeId, this.conn()), ID);
69
+ return new E2BNativeBox(await Sandbox.connect(nativeId, this.conn()), ID);
70
70
  }
71
71
  catch (err) {
72
72
  throw wrap(err);
@@ -176,7 +176,7 @@ class SailBox {
176
176
  get path() {
177
177
  return `/sailboxes/${encodeURIComponent(this.nativeId)}`;
178
178
  }
179
- url(sub) {
179
+ sandboxUrl(sub) {
180
180
  return `${this.p.sailboxApi}${this.path}${sub}`;
181
181
  }
182
182
  async resume() {
@@ -225,7 +225,7 @@ class SailBox {
225
225
  }
226
226
  };
227
227
  try {
228
- const res = await this.live(() => this.p.request("POST", this.url("/exec"), {
228
+ const res = await this.live(() => this.p.request("POST", this.sandboxUrl("/exec"), {
229
229
  signal: ctl.signal,
230
230
  json: {
231
231
  command: guardTimeout(wrapCommand(cmd, { cwd: opts.cwd }), secs),
@@ -297,12 +297,12 @@ class SailBox {
297
297
  }
298
298
  async writeFile(path, content) {
299
299
  const q = new URLSearchParams({ path, mode: "420" });
300
- const res = await this.live(() => this.p.request("PUT", this.url(`/files?${q}`), { body: toBytes(content) }));
300
+ const res = await this.live(() => this.p.request("PUT", this.sandboxUrl(`/files?${q}`), { body: toBytes(content) }));
301
301
  await res.arrayBuffer().catch(() => { });
302
302
  }
303
303
  async readFile(path) {
304
304
  const q = new URLSearchParams({ path });
305
- const res = await this.live(() => this.p.request("GET", this.url(`/files?${q}`)));
305
+ const res = await this.live(() => this.p.request("GET", this.sandboxUrl(`/files?${q}`)));
306
306
  return new Uint8Array(await res.arrayBuffer());
307
307
  }
308
308
  /** Pause in memory (no compute billed) and wait until it lands, so connect() can resume it. */
@@ -0,0 +1,12 @@
1
+ import { type ExecResult, type ProviderId } from "../types.js";
2
+ type ShellExec = (command: string) => Promise<ExecResult>;
3
+ /** Binary-safe files for shell APIs whose command arguments and output have bounded sizes. */
4
+ export declare class ShellFiles {
5
+ private provider;
6
+ private run;
7
+ constructor(provider: ProviderId, run: ShellExec);
8
+ private checked;
9
+ writeFile(path: string, content: Uint8Array | string): Promise<void>;
10
+ readFile(path: string): Promise<Uint8Array>;
11
+ }
12
+ export {};
@@ -0,0 +1,52 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ProviderError } from "../types.js";
3
+ import { shq, toBytes } from "../util.js";
4
+ /** Binary-safe files for shell APIs whose command arguments and output have bounded sizes. */
5
+ export class ShellFiles {
6
+ provider;
7
+ run;
8
+ constructor(provider, run) {
9
+ this.provider = provider;
10
+ this.run = run;
11
+ }
12
+ async checked(command) {
13
+ const result = await this.run(command);
14
+ if (result.exitCode !== 0)
15
+ throw new ProviderError(this.provider, result.stderr.trim() || "sandbox file command failed");
16
+ return result.stdout;
17
+ }
18
+ async writeFile(path, content) {
19
+ const destination = shq(path);
20
+ const temporary = shq(`${path}.sbr-${randomUUID()}`);
21
+ const bytes = Buffer.from(toBytes(content));
22
+ const chunkSize = 32 * 1024;
23
+ await this.checked(`mkdir -p -- "$(dirname -- ${destination})" && umask 077 && : > ${temporary}`);
24
+ try {
25
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
26
+ const chunk = bytes.subarray(offset, offset + chunkSize).toString("base64");
27
+ await this.checked(`printf '%s' '${chunk}' | base64 -d >> ${temporary}`);
28
+ }
29
+ await this.checked(`mv -f -- ${temporary} ${destination}`);
30
+ }
31
+ catch (err) {
32
+ await this.run(`rm -f -- ${temporary}`).catch(() => { });
33
+ throw err;
34
+ }
35
+ }
36
+ async readFile(path) {
37
+ const source = shq(path);
38
+ const length = Number((await this.checked(`test -f ${source} && wc -c < ${source}`)).trim());
39
+ if (!Number.isSafeInteger(length) || length < 0)
40
+ throw new ProviderError(this.provider, "invalid sandbox file length");
41
+ const chunks = [];
42
+ const chunkSize = 128 * 1024;
43
+ for (let offset = 0; offset < length; offset += chunkSize) {
44
+ const read = await this.checked(`bash -o pipefail -c ${shq(`dd if=${source} bs=${chunkSize} skip=${offset / chunkSize} count=1 2>/dev/null | base64`)}`);
45
+ const chunk = Buffer.from(read, "base64");
46
+ if (chunk.length !== Math.min(chunkSize, length - offset))
47
+ throw new ProviderError(this.provider, "sandbox file changed or the response was truncated");
48
+ chunks.push(chunk);
49
+ }
50
+ return Buffer.concat(chunks);
51
+ }
52
+ }
@@ -1,6 +1,6 @@
1
1
  import { vercelSandboxSize } from "../catalog.js";
2
2
  import { ProviderError } from "../types.js";
3
- import { DEFAULT_EXEC_TIMEOUT_S, killedByTimeout, optionalImport, timeoutError, toBytes, wrapCommand } from "../util.js";
3
+ import { DEFAULT_EXEC_TIMEOUT_S, errorStatus, killedByTimeout, optionalImport, timeoutError, toBytes, wrapCommand } from "../util.js";
4
4
  /**
5
5
  * Vercel Sandbox via `@vercel/sandbox`. Auth: VERCEL_OIDC_TOKEN (from `vercel env pull`), or
6
6
  * VERCEL_TOKEN + VERCEL_TEAM_ID + VERCEL_PROJECT_ID. Memory is fixed at 2 GB per vCPU.
@@ -27,6 +27,7 @@ export class VercelProvider {
27
27
  resources: { vcpus },
28
28
  env: spec.env,
29
29
  tags: spec.metadata,
30
+ ...(spec.ports?.length ? { ports: spec.ports } : {}),
30
31
  // v3 keeps sandboxes by default and restarts a stopped one on the next command; a router
31
32
  // sandbox is single-use, so nothing should outlive kill().
32
33
  persistent: false,
@@ -90,6 +91,43 @@ class VercelBox {
90
91
  throw new ProviderError("vercel", err?.message ?? String(err));
91
92
  }
92
93
  }
94
+ url(port) {
95
+ try {
96
+ return this.sbx.domain(port);
97
+ }
98
+ catch (err) {
99
+ if (err instanceof Error && err.message === `No route for port ${port}`) {
100
+ throw new ProviderError("vercel", `port ${port} was not requested when this sandbox was created`, 400);
101
+ }
102
+ throw err;
103
+ }
104
+ }
105
+ async start(cmd, opts = {}) {
106
+ try {
107
+ const command = await this.sbx.runCommand({
108
+ cmd: "sh",
109
+ args: ["-c", cmd],
110
+ cwd: opts.cwd,
111
+ env: opts.env,
112
+ detached: true,
113
+ });
114
+ return {
115
+ async kill() {
116
+ try {
117
+ await command.kill("SIGKILL");
118
+ }
119
+ catch (err) {
120
+ const status = errorStatus(err);
121
+ if (status !== 404)
122
+ throw new ProviderError("vercel", err instanceof Error ? err.message : String(err), status);
123
+ }
124
+ },
125
+ };
126
+ }
127
+ catch (err) {
128
+ throw new ProviderError("vercel", err instanceof Error ? err.message : String(err), errorStatus(err));
129
+ }
130
+ }
93
131
  async writeFile(path, content) {
94
132
  await this.sbx.writeFiles([{ path, content: Buffer.from(toBytes(content)) }]);
95
133
  }