@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.
@@ -3,6 +3,7 @@ import { type Provider, type ProviderSandbox, type SandboxSpec } from "../types.
3
3
  * Local sandboxes in Docker containers, through the `docker` CLI. Free and needs no account, so it
4
4
  * is good for development and tests. A container shares your machine's kernel: it is weaker
5
5
  * isolation than a cloud micro-VM, so don't point untrusted code at it with secrets mounted.
6
+ * Requested ports get a free loopback port on the Docker host, reachable only on that host.
6
7
  * Never chosen automatically; route to it with { provider: "docker" }.
7
8
  */
8
9
  export declare class DockerProvider implements Provider {
@@ -7,6 +7,7 @@ import { DEFAULT_EXEC_TIMEOUT_S, dirname, guardTimeout, killedByTimeout, shq, ti
7
7
  * Local sandboxes in Docker containers, through the `docker` CLI. Free and needs no account, so it
8
8
  * is good for development and tests. A container shares your machine's kernel: it is weaker
9
9
  * isolation than a cloud micro-VM, so don't point untrusted code at it with secrets mounted.
10
+ * Requested ports get a free loopback port on the Docker host, reachable only on that host.
10
11
  * Never chosen automatically; route to it with { provider: "docker" }.
11
12
  */
12
13
  export class DockerProvider {
@@ -40,6 +41,8 @@ export class DockerProvider {
40
41
  "--memory",
41
42
  `${Math.round((spec.memoryGb ?? DEFAULT_MEMORY_GB) * 1024)}m`,
42
43
  ];
44
+ for (const port of spec.ports ?? [])
45
+ args.push("--publish", `127.0.0.1::${port}`);
43
46
  for (const [k, v] of Object.entries(spec.env ?? {}))
44
47
  args.push("-e", `${k}=${v}`);
45
48
  for (const [k, v] of Object.entries(spec.metadata ?? {}))
@@ -87,6 +90,20 @@ class DockerBox {
87
90
  return { exitCode: r.code ?? -1, stdout: r.stdout, stderr: r.stderr, durationMs: r.ms };
88
91
  });
89
92
  }
93
+ async url(port) {
94
+ const r = await run(this.bin, ["port", this.nativeId, `${port}/tcp`]);
95
+ if (r.code !== 0 && containerAbsent(r.stderr))
96
+ throw new ProviderError("docker", `no container ${this.nativeId}`, 404);
97
+ if (r.code !== 0 && !/no public port/i.test(r.stderr)) {
98
+ throw new ProviderError("docker", `docker port failed: ${r.stderr.trim().slice(0, 300)}`);
99
+ }
100
+ const match = /^127\.0\.0\.1:(\d+)\s*$/m.exec(r.stdout);
101
+ const mapped = Number(match?.[1]);
102
+ if (!Number.isInteger(mapped) || mapped < 1 || mapped > 65535) {
103
+ throw new ProviderError("docker", `port ${port} has no loopback mapping; include it in the sandbox's ports at creation`, 400);
104
+ }
105
+ return `http://127.0.0.1:${mapped}`;
106
+ }
90
107
  async writeFile(path, content) {
91
108
  const r = await run(this.bin, ["exec", "-i", this.nativeId, "sh", "-c", `mkdir -p ${shq(dirname(path))} && cat > ${shq(path)}`], {
92
109
  stdin: toBytes(content),
@@ -1,4 +1,4 @@
1
- import { type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type SandboxSpec } from "../types.js";
1
+ import { type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderProcess, type ProviderSandbox, type SandboxSpec, type StartOptions } from "../types.js";
2
2
  import type { ComputerOs, ComputerProvider, ComputerSpec, ProviderComputer } from "../computers.js";
3
3
  /**
4
4
  * E2B via the official `e2b` SDK. vCPU and memory come from the template, not the create call.
@@ -77,3 +77,24 @@ export declare class E2BBox extends E2BCompatBox {
77
77
  /** Snapshot memory and disk. Sandbox.connect (router.get) resumes it. */
78
78
  pause(): Promise<void>;
79
79
  }
80
+ /** E2B-style SDK with browser hosts and detached, killable command handles. */
81
+ export interface E2BPreviewSandbox extends E2BLikeSandbox {
82
+ getHost(port: number): string;
83
+ getInfo?(): Promise<{
84
+ sandboxId?: string;
85
+ network?: {
86
+ allowPublicTraffic?: boolean | null;
87
+ } | null;
88
+ }>;
89
+ commands: {
90
+ run(cmd: string, opts: Parameters<E2BLikeSandbox["commands"]["run"]>[1]): Promise<E2BCommandHandle & {
91
+ disconnect(): Promise<void>;
92
+ }>;
93
+ };
94
+ }
95
+ export declare class E2BNativeBox extends E2BBox {
96
+ private sandbox;
97
+ constructor(sandbox: E2BPreviewSandbox, provider?: ProviderId);
98
+ url(port: number): Promise<string>;
99
+ start(cmd: string, opts?: StartOptions): Promise<ProviderProcess>;
100
+ }
@@ -1,5 +1,5 @@
1
1
  import { ProviderError } from "../types.js";
2
- import { DEFAULT_EXEC_TIMEOUT_S, optionalImport, timeoutError, toBytes } from "../util.js";
2
+ import { DEFAULT_EXEC_TIMEOUT_S, errorStatus, optionalImport, timeoutError, toBytes } from "../util.js";
3
3
  /** How long a desktop lives without activity. 1 hour is the Hobby tier's cap (Pro allows 24 h). */
4
4
  const DESKTOP_TIMEOUT_MS = 60 * 60_000;
5
5
  /**
@@ -26,11 +26,11 @@ export class E2BProvider {
26
26
  metadata: spec.metadata,
27
27
  };
28
28
  const sbx = spec.image?.e2b ? await Sandbox.create(spec.image.e2b, opts) : await Sandbox.create(opts);
29
- return new E2BBox(sbx);
29
+ return new E2BNativeBox(sbx);
30
30
  }
31
31
  async connect(nativeId) {
32
32
  const { Sandbox } = await optionalImport("e2b", "e2b");
33
- return new E2BBox(await Sandbox.connect(nativeId, { apiKey: this.apiKey }));
33
+ return new E2BNativeBox(await Sandbox.connect(nativeId, { apiKey: this.apiKey }));
34
34
  }
35
35
  /**
36
36
  * A fresh desktop every call. E2B has no get-or-create by user, so `externalUserId` (and `name`)
@@ -145,6 +145,53 @@ export class E2BBox extends E2BCompatBox {
145
145
  await this.sbx.pause();
146
146
  }
147
147
  }
148
+ export class E2BNativeBox extends E2BBox {
149
+ sandbox;
150
+ constructor(sandbox, provider = "e2b") {
151
+ super(sandbox, provider);
152
+ this.sandbox = sandbox;
153
+ }
154
+ async url(port) {
155
+ const info = await this.sandbox.getInfo?.();
156
+ if (info?.network?.allowPublicTraffic === false) {
157
+ throw new ProviderError(this.provider, "this sandbox requires authenticated preview traffic; use a provider or project with browser-accessible previews", 403);
158
+ }
159
+ return `https://${this.sandbox.getHost(port)}`;
160
+ }
161
+ async start(cmd, opts = {}) {
162
+ try {
163
+ const command = await this.sandbox.commands.run(cmd, {
164
+ cwd: opts.cwd,
165
+ envs: opts.env,
166
+ background: true,
167
+ timeoutMs: 0,
168
+ });
169
+ // Close the local stream while the command keeps running. The kill request is independent.
170
+ try {
171
+ await command.disconnect();
172
+ }
173
+ catch (err) {
174
+ await command.kill().catch(() => { });
175
+ throw err;
176
+ }
177
+ return {
178
+ kill: async () => {
179
+ try {
180
+ await command.kill();
181
+ }
182
+ catch (err) {
183
+ const status = errorStatus(err);
184
+ if (status !== 404)
185
+ throw new ProviderError(this.provider, err instanceof Error ? err.message : String(err), status);
186
+ }
187
+ },
188
+ };
189
+ }
190
+ catch (err) {
191
+ throw new ProviderError(this.provider, err instanceof Error ? err.message : String(err), errorStatus(err));
192
+ }
193
+ }
194
+ }
148
195
  /** Friendly names models send that xdotool doesn't know; anything else passes through verbatim. */
149
196
  const KEY_ALIASES = {
150
197
  enter: "Return",
@@ -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
  }
@@ -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. */
@@ -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
  }