@sandboxrouter/sdk 0.12.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.
Files changed (53) hide show
  1. package/README.md +13 -8
  2. package/dist/agent-bench.d.ts +12 -1
  3. package/dist/agent-bench.js +46 -7
  4. package/dist/bench.d.ts +13 -1
  5. package/dist/bench.js +39 -17
  6. package/dist/billing.js +0 -1
  7. package/dist/burst.d.ts +10 -0
  8. package/dist/burst.js +21 -10
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +34 -16
  11. package/dist/cli.js +47 -37
  12. package/dist/client.d.ts +6 -1
  13. package/dist/client.js +19 -0
  14. package/dist/computers.d.ts +2 -2
  15. package/dist/cost.d.ts +44 -5
  16. package/dist/cost.js +54 -24
  17. package/dist/leaderboard.d.ts +30 -8
  18. package/dist/leaderboard.js +89 -50
  19. package/dist/price-index.d.ts +3 -3
  20. package/dist/price-index.js +3 -3
  21. package/dist/providers/blaxel.d.ts +1 -0
  22. package/dist/providers/blaxel.js +56 -1
  23. package/dist/providers/daytona.js +33 -1
  24. package/dist/providers/deno.d.ts +3 -0
  25. package/dist/providers/deno.js +14 -0
  26. package/dist/providers/docker.d.ts +1 -0
  27. package/dist/providers/docker.js +30 -3
  28. package/dist/providers/e2b.d.ts +22 -1
  29. package/dist/providers/e2b.js +50 -3
  30. package/dist/providers/hopx.js +12 -0
  31. package/dist/providers/limrun.d.ts +1 -8
  32. package/dist/providers/limrun.js +0 -1
  33. package/dist/providers/mobilerun.d.ts +1 -5
  34. package/dist/providers/mobilerun.js +18 -26
  35. package/dist/providers/modal.js +7 -0
  36. package/dist/providers/novita.js +5 -5
  37. package/dist/providers/sail.js +4 -4
  38. package/dist/providers/vercel.js +41 -3
  39. package/dist/published.js +639 -1283
  40. package/dist/recommend.d.ts +17 -0
  41. package/dist/recommend.js +17 -11
  42. package/dist/results.d.ts +2 -2
  43. package/dist/results.js +104 -3
  44. package/dist/router.d.ts +22 -8
  45. package/dist/router.js +58 -11
  46. package/dist/server.d.ts +4 -1
  47. package/dist/server.js +101 -7
  48. package/dist/task.d.ts +2 -1
  49. package/dist/task.js +38 -19
  50. package/dist/types.d.ts +20 -4
  51. package/dist/validate.d.ts +4 -2
  52. package/dist/validate.js +18 -1
  53. package/package.json +18 -3
@@ -1,9 +1,17 @@
1
1
  import { readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { benchmarksPublishable, billingRules, CATALOG, cpuHourlyAtFull, fittingSpec, hourlyCost } from "./catalog.js";
3
+ import { benchmarksPublishable, billingRules, CATALOG, cpuHourlyAtFull, hourlyCost } from "./catalog.js";
4
4
  import { BILLED_VS_LIST } from "./billing.js";
5
- import { TASK_VERSION, taskByVersion, taskUsd } from "./task.js";
5
+ import { AGENT_TASK_VERSION } from "./agent-bench.js";
6
+ import { isCurrentTask, TASK_VERSION, taskByVersion, taskUsd } from "./task.js";
6
7
  import { median } from "./bench-store.js";
8
+ import { sizeOf } from "./router.js";
9
+ const sameSize = (a, b) => a.vcpu === b.vcpu && a.memoryGb === b.memoryGb;
10
+ const DEFAULT_SIZE = { vcpu: 2, memoryGb: 4 };
11
+ const requestedSize = (spec) => ({
12
+ vcpu: spec.vcpu ?? DEFAULT_SIZE.vcpu,
13
+ memoryGb: spec.memoryGb ?? DEFAULT_SIZE.memoryGb,
14
+ });
7
15
  export function makeReport(rows, opts) {
8
16
  return {
9
17
  tool: "sandboxrouter",
@@ -49,17 +57,18 @@ const KNOWN = new Set(CATALOG.map((c) => c.id));
49
57
  * the one with the most runs wins (a 100-run start-time benchmark over a 3-run job that also timed starts);
50
58
  * ties go to the newest.
51
59
  */
52
- export function aggregate(reports) {
60
+ export function aggregate(reports, cohort = DEFAULT_SIZE) {
61
+ const comparable = reports.filter((r) => sameSize(requestedSize(r.spec ?? {}), cohort));
53
62
  const latest = new Map();
54
63
  const newest = new Map();
55
- for (const rep of reports)
64
+ for (const rep of comparable)
56
65
  for (const r of rep.rows) {
57
66
  const key = `${r.provider}\u0000${rep.label ?? ""}`;
58
67
  if ((newest.get(key) ?? "") < rep.date)
59
68
  newest.set(key, rep.date);
60
69
  }
61
70
  const MONTH = 30 * 86_400_000;
62
- for (const rep of reports) {
71
+ for (const rep of comparable) {
63
72
  for (const r of rep.rows) {
64
73
  if (!KNOWN.has(r.provider))
65
74
  continue;
@@ -75,7 +84,10 @@ export function aggregate(reports) {
75
84
  for (const x of latest.values())
76
85
  by.set(x.row.provider, [...(by.get(x.row.provider) ?? []), x]);
77
86
  const rows = [...by.entries()].map(([id, xs]) => {
78
- const rs = xs.map((x) => x.row);
87
+ const latestRow = xs.reduce((a, b) => a.date >= b.date ? a : b).row;
88
+ const size = latestRow.size ?? sizeOf(id, cohort);
89
+ const matching = xs.filter(({ row }) => sameSize(row.size ?? sizeOf(id, cohort), size));
90
+ const rs = matching.map((x) => x.row);
79
91
  const runs = rs.reduce((n, r) => n + r.runs, 0);
80
92
  const ok = rs.reduce((n, r) => n + (r.runs - r.failures), 0);
81
93
  // Refusals for a limit on the benchmarking account aren't the provider failing: leave them out of the rate.
@@ -86,11 +98,12 @@ export function aggregate(reports) {
86
98
  submissions: rs.length,
87
99
  medianCreateMs: median(rs.map((r) => r.medianCreateMs).filter((n) => typeof n === "number")),
88
100
  medianExecMs: median(rs.map((r) => r.medianExecMs).filter((n) => typeof n === "number")),
101
+ medianReadyMs: rs.every((r) => r.medianReadyMs !== undefined) ? median(rs.map((r) => r.medianReadyMs)) : undefined,
89
102
  successRate: attempted ? ok / attempted : 0,
90
103
  runs: attempted,
91
- hourlyUsd: hourlyCost(id, fittingSpec(id)),
92
- size: fittingSpec(id),
93
- measuredAt: xs.map((x) => x.date).sort().at(-1),
104
+ hourlyUsd: hourlyCost(id, size),
105
+ size,
106
+ measuredAt: matching.map((x) => x.date).sort().at(-1),
94
107
  };
95
108
  });
96
109
  return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
@@ -100,16 +113,15 @@ export function aggregate(reports) {
100
113
  * `version` (the short task's by default; TASKS.long.version for `--long`): each provider's latest run
101
114
  * from each location, then the median across locations (as `aggregate` does). Cheapest task first.
102
115
  */
103
- export function taskTable(reports, version = TASK_VERSION) {
104
- const def = taskByVersion(version);
105
- if (!def)
106
- return [];
116
+ function currentTaskRows(reports, version, cohort) {
107
117
  const latest = new Map();
118
+ if (!isCurrentTask(version))
119
+ return new Map();
108
120
  for (const rep of reports) {
109
- if (rep.task !== version)
121
+ if (rep.task !== version || !sameSize(requestedSize(rep.spec ?? {}), cohort))
110
122
  continue;
111
123
  for (const r of rep.rows) {
112
- if (!KNOWN.has(r.provider) || !r.taskPhasesMs || r.medianTaskMs === undefined || r.medianCreateMs === undefined)
124
+ if (!KNOWN.has(r.provider) || r.size === undefined || r.taskOk === undefined)
113
125
  continue;
114
126
  const key = `${r.provider}\u0000${rep.label ?? ""}`;
115
127
  const seen = latest.get(key);
@@ -120,45 +132,71 @@ export function taskTable(reports, version = TASK_VERSION) {
120
132
  const by = new Map();
121
133
  for (const x of latest.values())
122
134
  by.set(x.row.provider, [...(by.get(x.row.provider) ?? []), x]);
123
- const rows = [...by.entries()].map(([id, xs]) => {
135
+ // Keep a provider's region samples comparable when its default shape changes between reports.
136
+ for (const [id, xs] of by) {
137
+ const newest = xs.reduce((a, b) => a.date >= b.date ? a : b);
138
+ by.set(id, xs.filter((x) => sameSize(x.row.size, newest.row.size)));
139
+ }
140
+ return by;
141
+ }
142
+ export function taskOutcomes(reports, version, cohort = DEFAULT_SIZE) {
143
+ return [...currentTaskRows(reports, version, cohort)].map(([provider, xs]) => ({
144
+ provider,
145
+ name: CATALOG.find((c) => c.id === provider).name,
146
+ requested: xs.reduce((n, x) => n + x.row.runs, 0),
147
+ completed: xs.reduce((n, x) => n + x.row.taskOk, 0),
148
+ limited: xs.reduce((n, x) => n + (x.row.limited ?? 0), 0),
149
+ failures: xs.reduce((n, x) => n + x.row.failures - (x.row.limited ?? 0), 0),
150
+ taskFailures: xs.reduce((n, x) => n + x.row.runs - x.row.failures - x.row.taskOk, 0),
151
+ }));
152
+ }
153
+ export function taskTable(reports, version = TASK_VERSION, cohort = DEFAULT_SIZE) {
154
+ const def = taskByVersion(version);
155
+ if (!def || !isCurrentTask(version))
156
+ return [];
157
+ const rows = [...currentTaskRows(reports, version, cohort)].flatMap(([id, xs]) => {
124
158
  const rs = xs.map((x) => x.row);
125
- const createMs = median(rs.map((r) => r.medianCreateMs));
126
- const taskMillis = median(rs.map((r) => r.medianTaskMs));
127
- const phasesMs = Object.fromEntries(def.phases.map((p) => [p.id, median(rs.map((r) => r.taskPhasesMs[p.id]))]));
159
+ const successful = rs.filter((r) => r.taskOk > 0 && r.taskPhasesMs && r.medianTaskMs !== undefined && r.medianTaskReadyMs !== undefined);
160
+ if (!successful.length)
161
+ return [];
162
+ const createMs = median(successful.map((r) => r.medianTaskReadyMs));
163
+ const taskMillis = median(successful.map((r) => r.medianTaskMs));
164
+ const phasesMs = Object.fromEntries(def.phases.map((p) => [p.id, median(successful.map((r) => r.taskPhasesMs[p.id]))]));
128
165
  // The job's own CPU hint (the agent loop's 10%) prices it the way its sandboxes were started.
129
- const size = { ...fittingSpec(id), ...(def.cpuUtilization ? { cpuUtilization: def.cpuUtilization } : {}) };
166
+ const size = { ...rs[0].size, ...(def.cpuUtilization ? { cpuUtilization: def.cpuUtilization } : {}) };
130
167
  const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
131
- const hourlyUsd = hourlyCost(id, fittingSpec(id)) * ratio;
168
+ const hourlyUsd = hourlyCost(id, size) * ratio;
132
169
  const rules = billingRules(id);
133
- const cpus = rs.map((r) => r.medianTaskCpuMs).filter((n) => typeof n === "number");
170
+ const cpus = successful.map((r) => r.medianTaskCpuMs).filter((n) => typeof n === "number");
134
171
  // A container can show the whole host's /proc/stat (Daytona does): a reading beyond what the sandbox's
135
172
  // own vCPUs could do in that time isn't the sandbox's, so it's dropped and the task is priced at full CPU.
136
- const read = cpus.length === rs.length ? median(cpus) : undefined;
173
+ const read = cpus.length === successful.length ? median(cpus) : undefined;
137
174
  const cpuMs = read !== undefined && read <= size.vcpu * taskMillis * 1.1 ? read : undefined;
138
- const cores = rs.map((r) => r.medianTaskMaxCoreMs).filter((n) => typeof n === "number");
139
- const coreRead = cores.length === rs.length ? median(cores) : undefined;
175
+ const cores = successful.map((r) => r.medianTaskMaxCoreMs).filter((n) => typeof n === "number");
176
+ const coreRead = cores.length === successful.length ? median(cores) : undefined;
140
177
  const maxCoreMs = cpuMs !== undefined && coreRead !== undefined && coreRead <= taskMillis * 1.1 ? coreRead : undefined;
141
- return {
142
- provider: id,
143
- name: CATALOG.find((c) => c.id === id).name,
144
- size,
145
- createMs,
146
- taskMs: taskMillis,
147
- phasesMs,
148
- hourlyUsd,
149
- taskUsd: taskUsd(id, size, createMs, taskMillis, cpuMs, ratio, false, maxCoreMs),
150
- reusedUsd: taskUsd(id, size, createMs, taskMillis, cpuMs, ratio, true, maxCoreMs),
151
- runs: rs.reduce((n, r) => n + r.runs - (r.limited ?? 0), 0),
152
- successRate: (() => {
153
- const tried = rs.reduce((n, r) => n + r.runs - (r.limited ?? 0), 0);
154
- return tried ? rs.reduce((n, r) => n + r.runs - r.failures, 0) / tried : 0;
155
- })(),
156
- ...(cpuMs !== undefined ? { cpuMs } : {}),
157
- activeCpu: cpuHourlyAtFull(id, size) > 0,
158
- minimumSeconds: rules.minSeconds,
159
- perSandboxUsd: rules.perSandboxUsd,
160
- measuredAt: xs.map((x) => x.date).sort().at(-1),
161
- };
178
+ const runs = rs.reduce((n, r) => n + r.runs, 0);
179
+ const ok = rs.reduce((n, r) => n + r.taskOk, 0);
180
+ return [{
181
+ provider: id,
182
+ name: CATALOG.find((c) => c.id === id).name,
183
+ size,
184
+ createMs,
185
+ taskMs: taskMillis,
186
+ phasesMs,
187
+ hourlyUsd,
188
+ taskUsd: taskUsd(id, size, createMs, taskMillis, cpuMs, ratio, false, maxCoreMs),
189
+ reusedUsd: taskUsd(id, size, createMs, taskMillis, cpuMs, ratio, true, maxCoreMs),
190
+ runs,
191
+ ok,
192
+ limited: rs.reduce((n, r) => n + (r.limited ?? 0), 0),
193
+ successRate: runs ? ok / runs : 0,
194
+ ...(cpuMs !== undefined ? { cpuMs } : {}),
195
+ activeCpu: cpuHourlyAtFull(id, size) > 0,
196
+ minimumSeconds: rules.minSeconds,
197
+ perSandboxUsd: rules.perSandboxUsd,
198
+ measuredAt: xs.map((x) => x.date).sort().at(-1),
199
+ }];
162
200
  });
163
201
  return rows.sort((a, b) => a.taskUsd - b.taskUsd || a.provider.localeCompare(b.provider));
164
202
  }
@@ -318,9 +356,6 @@ export function burstTable(reports, task, n) {
318
356
  if (n !== undefined && rep.n !== n)
319
357
  continue;
320
358
  for (const r of rep.rows) {
321
- // Nothing started (an account blocked outright): nothing measured.
322
- if (r.ok === 0)
323
- continue;
324
359
  if (!KNOWN.has(r.provider) || !benchmarksPublishable(r.provider))
325
360
  continue;
326
361
  const seen = latest.get(r.provider);
@@ -356,7 +391,11 @@ export function loadAgentReports(dir) {
356
391
  /** Each provider's latest real-agent result: done right first, then cheapest sandbox per session. */
357
392
  export function agentTable(reports) {
358
393
  const latest = new Map();
394
+ const current = reports.filter((r) => r.task === AGENT_TASK_VERSION);
395
+ const cohort = current.reduce((a, b) => !a || b.date > a.date ? b : a, undefined);
359
396
  for (const rep of reports) {
397
+ if (rep.task !== AGENT_TASK_VERSION || rep.model !== cohort?.model)
398
+ continue;
360
399
  for (const r of rep.rows) {
361
400
  if (!KNOWN.has(r.provider) || !benchmarksPublishable(r.provider))
362
401
  continue;
@@ -367,5 +406,5 @@ export function agentTable(reports) {
367
406
  }
368
407
  return [...latest.values()]
369
408
  .map(({ row, date, model }) => ({ ...row, name: CATALOG.find((c) => c.id === row.provider).name, measuredAt: date, model }))
370
- .sort((a, b) => b.ok / b.runs - a.ok / a.runs || (a.medianUsd ?? Infinity) - (b.medianUsd ?? Infinity));
409
+ .sort((a, b) => b.ok / Math.max(1, b.requested ?? b.runs) - a.ok / Math.max(1, a.requested ?? a.runs) || (a.medianUsd ?? Infinity) - (b.medianUsd ?? Infinity));
371
410
  }
@@ -1,9 +1,9 @@
1
1
  import type { ProviderId } from "./types.js";
2
2
  /**
3
3
  * The price index: what a few standard pieces of sandbox work cost today across the providers that passed
4
- * the real-account check. Each line is the median of what the router would charge on each of them (list
5
- * price, corrected by measured bills, with minimum charges and per-sandbox fees over the run), plus the
6
- * cheapest. It moves only when a provider's price in the catalog changes.
4
+ * the real-account check. Each line shows the median and lowest estimated direct-provider cost (list
5
+ * price, corrected by measured bills, with minimum charges and modeled per-sandbox fees over the run).
6
+ * Account-specific fees, such as Boat's allowance overages, are excluded.
7
7
  */
8
8
  export declare const INDEX_LINES: readonly [{
9
9
  readonly id: "2x4-hour";
@@ -4,9 +4,9 @@ import { Router, rankUsd, runHours } from "./router.js";
4
4
  import { VERIFIED } from "./verified.js";
5
5
  /**
6
6
  * The price index: what a few standard pieces of sandbox work cost today across the providers that passed
7
- * the real-account check. Each line is the median of what the router would charge on each of them (list
8
- * price, corrected by measured bills, with minimum charges and per-sandbox fees over the run), plus the
9
- * cheapest. It moves only when a provider's price in the catalog changes.
7
+ * the real-account check. Each line shows the median and lowest estimated direct-provider cost (list
8
+ * price, corrected by measured bills, with minimum charges and modeled per-sandbox fees over the run).
9
+ * Account-specific fees, such as Boat's allowance overages, are excluded.
10
10
  */
11
11
  export const INDEX_LINES = [
12
12
  { id: "2x4-hour", label: "2 vCPU / 4 GB, one hour", unit: "per hour", spec: { vcpu: 2, memoryGb: 4, timeoutMinutes: 60 }, scale: 1 },
@@ -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)
@@ -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 ?? {}))
@@ -53,8 +56,11 @@ export class DockerProvider {
53
56
  }
54
57
  async connect(nativeId) {
55
58
  const r = await run(this.bin, ["inspect", "-f", "{{.State.Status}}", nativeId]);
56
- if (r.code !== 0)
57
- throw new ProviderError("docker", `no container ${nativeId}`, 404);
59
+ if (r.code !== 0) {
60
+ if (containerAbsent(r.stderr))
61
+ throw new ProviderError("docker", `no container ${nativeId}`, 404);
62
+ throw new ProviderError("docker", `inspect failed: ${r.stderr.trim().slice(0, 300)}`);
63
+ }
58
64
  if (r.stdout.trim() === "paused")
59
65
  await run(this.bin, ["unpause", nativeId]);
60
66
  return new DockerBox(this.bin, nativeId);
@@ -84,6 +90,20 @@ class DockerBox {
84
90
  return { exitCode: r.code ?? -1, stdout: r.stdout, stderr: r.stderr, durationMs: r.ms };
85
91
  });
86
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
+ }
87
107
  async writeFile(path, content) {
88
108
  const r = await run(this.bin, ["exec", "-i", this.nativeId, "sh", "-c", `mkdir -p ${shq(dirname(path))} && cat > ${shq(path)}`], {
89
109
  stdin: toBytes(content),
@@ -103,9 +123,16 @@ class DockerBox {
103
123
  throw new ProviderError("docker", `pause failed: ${r.stderr.trim()}`);
104
124
  }
105
125
  async kill() {
106
- await run(this.bin, ["rm", "-f", this.nativeId]);
126
+ const r = await run(this.bin, ["rm", "-f", this.nativeId]);
127
+ if (r.code !== 0 && !containerAbsent(r.stderr)) {
128
+ throw new ProviderError("docker", `docker rm failed: ${r.stderr.trim().slice(0, 300)}`);
129
+ }
107
130
  }
108
131
  }
132
+ /** Only an explicit daemon response confirms that the container is gone. */
133
+ function containerAbsent(stderr) {
134
+ return /^(?:Error(?: response from daemon)?: )?No such (?:container|object): /im.test(stderr);
135
+ }
109
136
  function run(bin, args, opts = {}) {
110
137
  const t0 = Date.now();
111
138
  return new Promise((resolve, reject) => {
@@ -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);