@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
package/dist/index.d.ts CHANGED
@@ -33,6 +33,8 @@ export { NorthflankProvider } from "./providers/northflank.js";
33
33
  export { BoatProvider } from "./providers/boat.js";
34
34
  export { ExeDevProvider } from "./providers/exedev.js";
35
35
  export { AgentCoreProvider } from "./providers/agentcore.js";
36
+ export { DigitalOceanProvider } from "./providers/digitalocean.js";
37
+ export { GoogleAgentPlatformProvider } from "./providers/google.js";
36
38
  export { AzureSessionsProvider } from "./providers/azure.js";
37
39
  export { LambdaMicrovmProvider, writeLambdaMicrovmBundle } from "./providers/lambda.js";
38
40
  export { AlibabaProvider } from "./providers/alibaba.js";
package/dist/index.js CHANGED
@@ -33,6 +33,8 @@ export { NorthflankProvider } from "./providers/northflank.js";
33
33
  export { BoatProvider } from "./providers/boat.js";
34
34
  export { ExeDevProvider } from "./providers/exedev.js";
35
35
  export { AgentCoreProvider } from "./providers/agentcore.js";
36
+ export { DigitalOceanProvider } from "./providers/digitalocean.js";
37
+ export { GoogleAgentPlatformProvider } from "./providers/google.js";
36
38
  export { AzureSessionsProvider } from "./providers/azure.js";
37
39
  export { LambdaMicrovmProvider, writeLambdaMicrovmBundle } from "./providers/lambda.js";
38
40
  export { AlibabaProvider } from "./providers/alibaba.js";
@@ -1,13 +1,13 @@
1
1
  import { DEFAULT_MEMORY_GB, DEFAULT_VCPU } from "../catalog.js";
2
2
  import { ProviderError } from "../types.js";
3
- import { DEFAULT_EXEC_TIMEOUT_S, dirname, optionalImport, shq, timeoutError, toBytes } from "../util.js";
3
+ import { DEFAULT_EXEC_TIMEOUT_S, dirname, optionalImport, timeoutError, toBytes } from "../util.js";
4
4
  /**
5
5
  * Beam (beam.cloud) sandboxes via the official `@beamcloud/beam-js` SDK (checked against 1.1.6).
6
6
  * Auth: BEAM_TOKEN and BEAM_WORKSPACE_ID (the TS SDK refuses requests without the workspace id).
7
7
  * new Sandbox({ name, cpu, memory: MiB, gpu?, image?, keepWarmSeconds, env }).create()
8
8
  * -> SandboxInstance (containerId is the sandbox id)
9
9
  * Sandbox.connect(id) reattach by id
10
- * instance.execShell(text, { cwd, env, wait }) start a process; .wait() -> exit code,
10
+ * instance.exec(argv, { cwd, env, wait }) start a process; .wait() -> exit code,
11
11
  * .stdout / .stderr are polled streams (async-iterable by line, or .read() for all so far)
12
12
  * instance.fs.writeBytes(path, buf) / fs.readBytes(path)
13
13
  * instance.terminate()
@@ -115,7 +115,8 @@ class BeamBox {
115
115
  try {
116
116
  // Never `wait: true`: that call returns only when the command exits, so the deadline below
117
117
  // could not start until it was already too late to enforce.
118
- proc = await this.sb.execShell(cmd, { cwd: opts.cwd, env, wait: false });
118
+ // Beam's gateway treats execShell input like argv on some accounts.
119
+ proc = await this.sb.exec(["sh", "-c", cmd], { cwd: opts.cwd, env, wait: false });
119
120
  }
120
121
  catch (err) {
121
122
  throw fail(err, "exec");
@@ -155,7 +156,7 @@ class BeamBox {
155
156
  catch {
156
157
  // Most likely a missing parent directory: create it and try once more.
157
158
  try {
158
- const p = await this.sb.execShell(`mkdir -p ${shq(dirname(path))}`, { wait: true });
159
+ const p = await this.sb.exec(["mkdir", "-p", "--", dirname(path)], { wait: true });
159
160
  await p.wait();
160
161
  await this.sb.fs.writeBytes(path, buf);
161
162
  }
@@ -6,6 +6,7 @@ import { type Provider, type ProviderSandbox, type SandboxSpec } from "../types.
6
6
  * wake on the next call. No pause(): archiving is a preview Blaxel enables per workspace (others
7
7
  * get 403 "Archiving a sandbox is in preview and is not enabled for this workspace", 2026-11-05).
8
8
  * kill() waits until the sandbox is gone, because Blaxel deletes asynchronously.
9
+ * Preview URLs create private previews on demand and carry a short-lived Blaxel preview token.
9
10
  */
10
11
  export declare class BlaxelProvider implements Provider {
11
12
  private apiKey;
@@ -1,10 +1,11 @@
1
- import { DEFAULT_MEMORY_GB, DEFAULT_VCPU } from "../catalog.js";
1
+ import { DEFAULT_MEMORY_GB, DEFAULT_VCPU, info } from "../catalog.js";
2
2
  import { ProviderError } from "../types.js";
3
3
  import { DEFAULT_EXEC_TIMEOUT_S, errorStatus, optionalImport, timeoutError, toBytes } from "../util.js";
4
4
  /** Blaxel's public base image (the SDK's own default). Set image.blaxel for another image or a `bl deploy` template. */
5
5
  const DEFAULT_IMAGE = "blaxel/base-image:latest";
6
6
  /** Blaxel rejects a max-age ttl under 5 minutes. */
7
7
  const MIN_TTL_MINUTES = 5;
8
+ const PREVIEW_TTL_MS = 30 * 60_000;
8
9
  /**
9
10
  * Blaxel sandboxes via `@blaxel/core`. Auth: BL_API_KEY + BL_WORKSPACE (or `bl login`).
10
11
  * Region: BL_REGION, else us-pdx-1. Blaxel sizes by memory only and gives 1 vCPU per 2 GB,
@@ -12,6 +13,7 @@ const MIN_TTL_MINUTES = 5;
12
13
  * wake on the next call. No pause(): archiving is a preview Blaxel enables per workspace (others
13
14
  * get 403 "Archiving a sandbox is in preview and is not enabled for this workspace", 2026-11-05).
14
15
  * kill() waits until the sandbox is gone, because Blaxel deletes asynchronously.
16
+ * Preview URLs create private previews on demand and carry a short-lived Blaxel preview token.
15
17
  */
16
18
  export class BlaxelProvider {
17
19
  apiKey;
@@ -118,6 +120,59 @@ class BlaxelBox {
118
120
  // A nonzero exit is a result (status "failed"), not an error.
119
121
  return { exitCode: r.exitCode, stdout: r.stdout ?? "", stderr: r.stderr ?? "", durationMs: Date.now() - t0 };
120
122
  }
123
+ async url(port) {
124
+ if (info("blaxel").limits.reservedPorts?.includes(port))
125
+ throw new ProviderError("blaxel", `port ${port} is reserved`, 400);
126
+ try {
127
+ const preview = await this.sbx.previews.createIfNotExists({
128
+ metadata: { name: `sandboxrouter-${port}` },
129
+ spec: { port, public: false },
130
+ });
131
+ // Never reuse a conflicting preview or turn even a previously created one public.
132
+ if (preview.spec.port !== port || preview.spec.public === true) {
133
+ throw new ProviderError("blaxel", `existing preview for port ${port} has different access or routing settings`, 409);
134
+ }
135
+ const url = new URL(preview.url);
136
+ if (url.protocol !== "https:")
137
+ throw new ProviderError("blaxel", "preview did not return an HTTPS URL");
138
+ const expiresAt = new Date(Date.now() + PREVIEW_TTL_MS);
139
+ const token = typeof preview.tokens.createIfExpired === "function"
140
+ ? await preview.tokens.createIfExpired(expiresAt, 60_000)
141
+ : await preview.tokens.create(expiresAt);
142
+ url.searchParams.set("bl_preview_token", token.value);
143
+ return url.toString();
144
+ }
145
+ catch (err) {
146
+ throw wrap(err);
147
+ }
148
+ }
149
+ async start(cmd, opts = {}) {
150
+ try {
151
+ const process = await this.sbx.process.exec({
152
+ command: cmd,
153
+ workingDir: opts.cwd,
154
+ env: opts.env,
155
+ waitForCompletion: false,
156
+ keepAlive: true,
157
+ timeout: 0,
158
+ });
159
+ return {
160
+ kill: async () => {
161
+ try {
162
+ await this.sbx.process.kill(process.pid);
163
+ }
164
+ catch (err) {
165
+ const error = wrap(err);
166
+ if (error.status !== 404)
167
+ throw error;
168
+ }
169
+ },
170
+ };
171
+ }
172
+ catch (err) {
173
+ throw wrap(err);
174
+ }
175
+ }
121
176
  async writeFile(path, content) {
122
177
  try {
123
178
  await this.sbx.fs.writeBinary(path, toBytes(content));
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { ProviderError } from "../types.js";
3
- import { DEFAULT_EXEC_TIMEOUT_S, optionalImport, timeoutError, toBytes, wrapCommand } from "../util.js";
3
+ import { DEFAULT_EXEC_TIMEOUT_S, errorStatus, optionalImport, timeoutError, toBytes, wrapCommand } from "../util.js";
4
4
  /**
5
5
  * Daytona via `@daytonaio/sdk`. Default snapshot; set image.daytona to start from an image.
6
6
  *
@@ -205,6 +205,38 @@ class DaytonaBox {
205
205
  await proc.deleteSession(session).catch(() => { });
206
206
  }
207
207
  }
208
+ async url(port) {
209
+ // A port-scoped signed URL works in a browser without revealing a sandbox-wide preview token.
210
+ return (await this.sbx.getSignedPreviewUrl(port, 3600)).url;
211
+ }
212
+ async start(cmd, opts = {}) {
213
+ const session = `sbr-${randomUUID()}`;
214
+ const process = this.sbx.process;
215
+ try {
216
+ await process.createSession(session);
217
+ await process.executeSessionCommand(session, {
218
+ command: wrapCommand(`(\n${cmd}\n)`, opts),
219
+ runAsync: true,
220
+ suppressInputEcho: true,
221
+ });
222
+ }
223
+ catch (err) {
224
+ await process.deleteSession(session).catch(() => { });
225
+ throw new ProviderError("daytona", err instanceof Error ? err.message : String(err), errorStatus(err));
226
+ }
227
+ return {
228
+ async kill() {
229
+ try {
230
+ await process.deleteSession(session);
231
+ }
232
+ catch (err) {
233
+ const status = errorStatus(err);
234
+ if (status !== 404)
235
+ throw new ProviderError("daytona", err instanceof Error ? err.message : String(err), status);
236
+ }
237
+ },
238
+ };
239
+ }
208
240
  async writeFile(path, content) {
209
241
  await this.sbx.fs.uploadFile(Buffer.from(toBytes(content)), path);
210
242
  }
@@ -14,6 +14,9 @@ interface DenoChild {
14
14
  interface DenoSdkSandbox {
15
15
  readonly id: string;
16
16
  spawn(command: string, options?: Record<string, unknown>): Promise<DenoChild>;
17
+ exposeHttp(target: {
18
+ port: number;
19
+ }): Promise<string>;
17
20
  fs: {
18
21
  writeFile(path: string, data: Uint8Array): Promise<void>;
19
22
  readFile(path: string): Promise<Uint8Array>;
@@ -13,6 +13,7 @@ import { dirname, optionalImport, toBytes } from "../util.js";
13
13
  * The default timeout ("session") would end the VM when this process disconnects, so the adapter
14
14
  * always passes a duration, which is what lets connect() reattach. exec streams stdout/stderr from
15
15
  * a spawned `/bin/sh -c`. No pause.
16
+ * url() explicitly opens a public HTTP preview; Deno serves it through the sandbox lifetime.
16
17
  * Docs: https://docs.deno.com/sandbox/, https://docs.deno.com/sandbox/create/,
17
18
  * https://docs.deno.com/sandbox/timeouts/, https://docs.deno.com/sandbox/security/,
18
19
  * https://deno.com/sandbox (pricing), https://jsr.io/@deno/sandbox
@@ -82,6 +83,7 @@ class DenoBox {
82
83
  return this.sbx;
83
84
  }
84
85
  nativeId;
86
+ previews = new Map();
85
87
  constructor(sbx) {
86
88
  this.sbx = sbx;
87
89
  this.nativeId = sbx.id;
@@ -125,6 +127,18 @@ class DenoBox {
125
127
  clearTimeout(giveUp);
126
128
  }
127
129
  }
130
+ url(port) {
131
+ // exposeHttp allocates a fresh public hostname on each call.
132
+ const existing = this.previews.get(port);
133
+ if (existing)
134
+ return existing;
135
+ const pending = sdk(() => this.sbx.exposeHttp({ port })).catch((err) => {
136
+ this.previews.delete(port);
137
+ throw err;
138
+ });
139
+ this.previews.set(port, pending);
140
+ return pending;
141
+ }
128
142
  async writeFile(path, content) {
129
143
  const dir = dirname(path);
130
144
  if (dir !== "/" && dir !== path)
@@ -0,0 +1,16 @@
1
+ import { type Provider, type ProviderSandbox, type SandboxSpec } from "../types.js";
2
+ export declare class DigitalOceanProvider implements Provider {
3
+ private token;
4
+ private baseUrl;
5
+ readonly id: "digitalocean";
6
+ constructor(token?: string | undefined, baseUrl?: string);
7
+ configured(): boolean;
8
+ /** @internal */
9
+ request<T>(method: string, path: string, body?: unknown, timeoutMs?: number): Promise<T>;
10
+ create(spec: SandboxSpec): Promise<ProviderSandbox>;
11
+ connect(nativeId: string): Promise<ProviderSandbox>;
12
+ /** @internal */
13
+ remove(path: string): Promise<void>;
14
+ private getSession;
15
+ private waitReady;
16
+ }
@@ -0,0 +1,174 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { digitalOceanSize, DEFAULT_MEMORY_GB, DEFAULT_VCPU } from "../catalog.js";
3
+ import { ProviderError } from "../types.js";
4
+ import { DEFAULT_EXEC_TIMEOUT_S, killedByTimeout, timeoutError, wrapCommand } from "../util.js";
5
+ import { ShellFiles } from "./shell-files.js";
6
+ /**
7
+ * DigitalOcean Harness Runtime. Start a harness-free microVM from an Environment Config,
8
+ * then use its session API to execute commands, pause, resume and delete. The temporary
9
+ * config is soft-deleted after the session is created. The service exposes an idle pause
10
+ * timeout rather than a wall-clock deletion deadline.
11
+ * https://docs.digitalocean.com/products/managed-agents/agent-harness-runtime/how-to/run-sandbox/
12
+ * https://docs.digitalocean.com/reference/api/reference/harness-runtime/
13
+ */
14
+ const ID = "digitalocean";
15
+ const API = "/v2/harness-runtime";
16
+ const BOOT_TIMEOUT_MS = 110_000;
17
+ const MAX_EXEC_SECONDS = 240;
18
+ function statusOf(session) {
19
+ return session.status?.replace(/^SESSION_STATUS_/, "");
20
+ }
21
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
22
+ export class DigitalOceanProvider {
23
+ token;
24
+ baseUrl;
25
+ id = ID;
26
+ constructor(token = process.env.DIGITALOCEAN_TOKEN || process.env.DIGITALOCEAN_ACCESS_TOKEN, baseUrl = process.env.DIGITALOCEAN_HARNESS_URL ?? "https://api.digitalocean.com") {
27
+ this.token = token;
28
+ this.baseUrl = baseUrl;
29
+ }
30
+ configured() {
31
+ return !!this.token;
32
+ }
33
+ /** @internal */
34
+ async request(method, path, body, timeoutMs = 30_000) {
35
+ if (!this.token)
36
+ throw new ProviderError(ID, "DIGITALOCEAN_TOKEN is not set");
37
+ const response = await fetch(`${this.baseUrl.replace(/\/$/, "")}${API}${path}`, {
38
+ method,
39
+ headers: {
40
+ Authorization: `Bearer ${this.token}`,
41
+ Accept: "application/json",
42
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
43
+ },
44
+ body: body === undefined ? undefined : JSON.stringify(body),
45
+ redirect: "error",
46
+ signal: AbortSignal.timeout(timeoutMs),
47
+ });
48
+ const text = await response.text();
49
+ if (!response.ok) {
50
+ let detail = text.slice(0, 280);
51
+ try {
52
+ detail = JSON.parse(text).message ?? detail;
53
+ }
54
+ catch { /* non-JSON error */ }
55
+ throw new ProviderError(ID, `${method} ${path}: HTTP ${response.status} ${detail}`, response.status);
56
+ }
57
+ return (text ? JSON.parse(text) : {});
58
+ }
59
+ async create(spec) {
60
+ const size = digitalOceanSize(spec.vcpu ?? DEFAULT_VCPU, spec.memoryGb ?? DEFAULT_MEMORY_GB);
61
+ if (!size)
62
+ throw new ProviderError(ID, "no Harness Runtime size can satisfy the requested vCPU and memory");
63
+ const name = `sbr-${randomBytes(8).toString("hex")}`;
64
+ // Keep the caller's env out of the durable config.
65
+ const idleSeconds = Math.max(60, Math.ceil((spec.timeoutMinutes ?? 30) * 60));
66
+ const manifest = [`name: ${name}`, "harness: none", `size: ${size.slug}`, `idle_timeout: ${idleSeconds}s`].join("\n");
67
+ const { config } = await this.request("POST", "/configs", {
68
+ name,
69
+ manifest_yaml: manifest,
70
+ });
71
+ if (!config?.id)
72
+ throw new ProviderError(ID, "create config returned no config id");
73
+ const configPath = `/configs/${encodeURIComponent(config.id)}`;
74
+ let session;
75
+ try {
76
+ const result = await this.request("POST", "/sessions", { name, config_id: config.id });
77
+ session = result.session;
78
+ if (!session?.session_id)
79
+ throw new ProviderError(ID, "create session returned no session id");
80
+ await this.waitReady(session);
81
+ await this.remove(configPath);
82
+ return new DigitalOceanBox(this, session.session_id, spec.env);
83
+ }
84
+ catch (err) {
85
+ if (session?.session_id)
86
+ await this.remove(sessionPath(session.session_id)).catch(() => { });
87
+ await this.remove(configPath).catch(() => { });
88
+ throw err;
89
+ }
90
+ }
91
+ async connect(nativeId) {
92
+ const path = sessionPath(nativeId);
93
+ const session = await this.getSession(path);
94
+ if (statusOf(session) === "PAUSED")
95
+ await this.request("POST", `${path}/resume`, undefined, BOOT_TIMEOUT_MS);
96
+ await this.waitReady(statusOf(session) === "PAUSED" ? await this.getSession(path) : session);
97
+ return new DigitalOceanBox(this, nativeId);
98
+ }
99
+ /** @internal */
100
+ async remove(path) {
101
+ try {
102
+ await this.request("DELETE", path);
103
+ }
104
+ catch (err) {
105
+ if (!(err instanceof ProviderError) || err.status !== 404)
106
+ throw err;
107
+ }
108
+ }
109
+ async getSession(path) {
110
+ const { session } = await this.request("GET", path);
111
+ if (!session?.session_id)
112
+ throw new ProviderError(ID, "session missing", 404);
113
+ return session;
114
+ }
115
+ async waitReady(session) {
116
+ const path = sessionPath(session.session_id);
117
+ const until = Date.now() + BOOT_TIMEOUT_MS;
118
+ while (Date.now() < until) {
119
+ const status = statusOf(session);
120
+ if (status === "READY")
121
+ return;
122
+ if (status === "FAILED" || status === "DESTROYED" || status === "PAUSED") {
123
+ throw new ProviderError(ID, `session is ${status.toLowerCase()}`, status === "DESTROYED" ? 404 : undefined);
124
+ }
125
+ await delay(500);
126
+ session = await this.getSession(path);
127
+ }
128
+ throw new ProviderError(ID, "session did not become ready", 504);
129
+ }
130
+ }
131
+ function sessionPath(id) {
132
+ return `/sessions/${encodeURIComponent(id)}`;
133
+ }
134
+ class DigitalOceanBox {
135
+ provider;
136
+ nativeId;
137
+ env;
138
+ files = new ShellFiles(ID, (command) => this.exec(command));
139
+ constructor(provider, nativeId, env) {
140
+ this.provider = provider;
141
+ this.nativeId = nativeId;
142
+ this.env = env;
143
+ }
144
+ async exec(command, opts = {}) {
145
+ const t0 = Date.now();
146
+ const seconds = Math.min(MAX_EXEC_SECONDS, Math.max(1, Math.ceil(opts.timeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_S)));
147
+ const path = `${sessionPath(this.nativeId)}/sandbox/exec`;
148
+ const cmd = wrapCommand(command, { env: { ...this.env, ...opts.env } });
149
+ const result = await this.provider.request("POST", path, {
150
+ argv: ["sh", "-c", cmd],
151
+ workdir: opts.cwd,
152
+ timeout_seconds: seconds,
153
+ }, (seconds + 15) * 1000);
154
+ const { exit_code, stdout = "", stderr = "" } = result;
155
+ if (typeof exit_code !== "number" || !Number.isInteger(exit_code))
156
+ throw new ProviderError(ID, "exec returned no exit code");
157
+ const durationMs = result.duration_ms ?? Date.now() - t0;
158
+ if (killedByTimeout(exit_code, durationMs, seconds))
159
+ throw timeoutError(ID, seconds);
160
+ if (stdout)
161
+ opts.onStdout?.(stdout);
162
+ if (stderr)
163
+ opts.onStderr?.(stderr);
164
+ return { stdout, stderr, exitCode: exit_code, durationMs };
165
+ }
166
+ readFile(path) { return this.files.readFile(path); }
167
+ writeFile(path, data) { return this.files.writeFile(path, data); }
168
+ async pause() {
169
+ await this.provider.request("POST", `${sessionPath(this.nativeId)}/pause`, undefined, BOOT_TIMEOUT_MS);
170
+ }
171
+ async kill() {
172
+ await this.provider.remove(sessionPath(this.nativeId));
173
+ }
174
+ }
@@ -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",
@@ -0,0 +1,23 @@
1
+ import { type Provider, type ProviderSandbox, type SandboxSpec } from "../types.js";
2
+ export declare class GoogleAgentPlatformProvider implements Provider {
3
+ private engine;
4
+ private template;
5
+ private token;
6
+ private baseUrl?;
7
+ readonly id: "google";
8
+ private auth?;
9
+ constructor(engine?: string | undefined, template?: string | undefined, token?: string | undefined, baseUrl?: string | undefined);
10
+ configured(): boolean;
11
+ private engineName;
12
+ private headers;
13
+ /** @internal */
14
+ request<T>(method: string, resource: string, body?: unknown, timeoutMs?: number): Promise<T>;
15
+ private sandboxName;
16
+ create(spec: SandboxSpec): Promise<ProviderSandbox>;
17
+ connect(nativeId: string): Promise<ProviderSandbox>;
18
+ /** @internal */
19
+ action(name: string, action: "pause" | "resume"): Promise<void>;
20
+ /** @internal */
21
+ remove(name: string): Promise<void>;
22
+ private wait;
23
+ }