@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
@@ -5,6 +5,7 @@ export type RecPriority = "cost" | "speed" | "value";
5
5
  export interface PublishedStart {
6
6
  name: string;
7
7
  medianCreateMs: number;
8
+ medianReadyMs?: number;
8
9
  successRate: number;
9
10
  runs: number;
10
11
  hourlyUsd: number;
@@ -22,6 +23,8 @@ export interface PublishedJob {
22
23
  reusedUsd: number;
23
24
  successRate: number;
24
25
  runs: number;
26
+ ok?: number;
27
+ limited?: number;
25
28
  /** Bills at least this many seconds per sandbox. */
26
29
  minimumSeconds?: number;
27
30
  /** Fee per sandbox started. */
@@ -35,6 +38,14 @@ export interface PublishedLoadRow {
35
38
  ok: number;
36
39
  /** Of those that didn't start, how many the benchmarking account's own limit refused. */
37
40
  limited: number;
41
+ size?: {
42
+ vcpu: number;
43
+ memoryGb: number;
44
+ };
45
+ createFailures?: number;
46
+ commandFailures?: number;
47
+ taskFailures?: number;
48
+ cleanupFailures?: number;
38
49
  p50Ms?: number;
39
50
  p99Ms?: number;
40
51
  wallMs: number;
@@ -57,6 +68,12 @@ export interface PublishedData {
57
68
  start: Record<string, PublishedStart>;
58
69
  jobs: Partial<Record<Exclude<RecJob, "start">, Record<string, PublishedJob>>>;
59
70
  load: PublishedLoad[];
71
+ /** Start fees above included allowances. The benchmark estimates exclude these charges. */
72
+ conditionalStartFees?: Record<string, {
73
+ minUsd: number;
74
+ maxUsd: number;
75
+ source: string;
76
+ }>;
60
77
  }
61
78
  export interface RecommendOptions {
62
79
  /** The job to run. Default "short". */
package/dist/recommend.js CHANGED
@@ -31,11 +31,12 @@ export function recommend(data, opts = {}) {
31
31
  const loads = data.load.filter((l) => l.job === LOAD_JOB[job] && l.n <= count).sort((a, b) => b.n - a.n);
32
32
  const load = count >= 10 && !reuse ? loads[0] : undefined;
33
33
  const raw = [];
34
+ const startRows = Object.entries(data.start).filter(([id]) => !only || only.has(id));
35
+ // Use one timing definition across the cohort. Legacy reports did not store paired readiness.
36
+ const paired = startRows.length > 0 && startRows.every(([, s]) => s.medianReadyMs !== undefined);
34
37
  if (job === "start") {
35
- for (const [id, s] of Object.entries(data.start)) {
36
- if (only && !only.has(id))
37
- continue;
38
- raw.push({ provider: id, name: s.name, secondsEach: s.medianCreateMs / 1000, hourlyUsd: s.hourlyUsd, successRate: s.successRate, runs: s.runs, notes: [], measuredAt: s.measuredAt, usdKey: s.hourlyUsd });
38
+ for (const [id, s] of startRows) {
39
+ raw.push({ provider: id, name: s.name, secondsEach: (paired ? s.medianReadyMs : s.medianCreateMs) / 1000, hourlyUsd: s.hourlyUsd, successRate: s.successRate, runs: s.runs, notes: [], measuredAt: s.measuredAt, usdKey: s.hourlyUsd });
39
40
  }
40
41
  }
41
42
  else {
@@ -48,6 +49,8 @@ export function recommend(data, opts = {}) {
48
49
  notes.push(`bills at least ${j.minimumSeconds} s per sandbox`);
49
50
  if (!reuse && j.perSandboxUsd)
50
51
  notes.push(`$${j.perSandboxUsd} per sandbox started`);
52
+ if (j.limited)
53
+ notes.push(`${j.limited} reported limit refusals`);
51
54
  raw.push({
52
55
  provider: id,
53
56
  name: j.name,
@@ -64,6 +67,9 @@ export function recommend(data, opts = {}) {
64
67
  }
65
68
  const mostRuns = Math.max(1, ...raw.map((r) => r.runs));
66
69
  for (const r of raw) {
70
+ const fee = data.conditionalStartFees?.[r.provider];
71
+ if (!reuse && fee)
72
+ r.notes.push(`excludes $${fee.minUsd}–$${fee.maxUsd} per start above allowance`);
67
73
  if (r.runs < mostRuns / 2)
68
74
  r.notes.push(`only ${r.runs} runs`);
69
75
  if (r.successRate < 1)
@@ -78,12 +84,11 @@ export function recommend(data, opts = {}) {
78
84
  const startS = job === "start" ? r.secondsEach : r.secondsEach - (data.jobs[job]?.[r.provider]?.createMs ?? 0) / 1000;
79
85
  r.secondsEach = (job === "start" ? 0 : startS) + l.p50Ms / 1000;
80
86
  }
81
- else if (l && l.n - l.ok > l.limited) {
82
- // Some failed for reasons other than the benchmarking account's limit: the provider's own.
83
- r.notes.push(`${l.ok} of ${l.n} started at once`);
87
+ else if (l) {
88
+ r.notes.push(`${l.ok} of ${l.n} completed${l.limited ? ` (${l.limited} reported limit refusals)` : ""}`);
84
89
  }
85
90
  else {
86
- r.notes.push(`not measured at ${load.n} at once yet${l ? " (the benchmarking account's limit)" : ""}`);
91
+ r.notes.push(`not measured at ${load.n} at once yet`);
87
92
  }
88
93
  }
89
94
  const ok = (r) => Math.max(r.successRate, 0.01);
@@ -96,8 +101,9 @@ export function recommend(data, opts = {}) {
96
101
  const results = scored.slice(0, opts.limit ?? scored.length).map(({ usdKey: _, ...r }, i) => ({ ...r, rank: i + 1, valueScore: Math.round(r.valueScore * 100) / 100 }));
97
102
  const what = job === "start" ? "starting a sandbox" : `the ${job} job${reuse ? " in a running sandbox" : " in a new sandbox"}`;
98
103
  const by = priority === "cost" ? "lowest cost" : priority === "speed" ? "shortest time" : "best value (cost times time, each against the median)";
99
- const basis = `Ranked by ${by} for ${what}, per successful run` +
100
- (load ? `, with start times measured ${load.n} at once; providers not yet measured at that size come after` : "") +
101
- ".";
104
+ const basis = !results.length ? `No current verified results for ${what}.` :
105
+ `Ranked by ${by} for ${what} with a success-rate adjustment` +
106
+ (load ? `, with readiness measured on batches of ${load.n}; providers that did not finish the batch are listed after` : "") +
107
+ (job === "start" && !paired ? ". Single-request timings use the create response; the first command is measured separately" : "") + ".";
102
108
  return { job, count, priority, reuse, basis, dataThrough: data.dataThrough, results };
103
109
  }
package/dist/results.d.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  * Checks for the files people submit to results/: bench reports, saved `check` runs and `cost` runs.
3
3
  *
4
4
  * Submissions are self-reported, so nothing here can prove a number is real. What it can do is keep
5
- * the obvious problems out before a maintainer reviews the PR: files that aren't one of the three
6
- * formats, unknown providers, impossible numbers, anything that looks like a key, and labels that
5
+ * the obvious problems out before a maintainer reviews the PR: unsupported formats, unknown
6
+ * providers, impossible numbers, anything that looks like a key, and labels that
7
7
  * look like a home address or an email. CI runs it on every push and pull request
8
8
  * (`npm run results:check`), and on a pull request it also refuses edits to someone else's bench
9
9
  * report: a new run is a new file.
package/dist/results.js CHANGED
@@ -2,7 +2,8 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
3
  import { benchmarksPublishable, CATALOG } from "./catalog.js";
4
4
  import { CHECK_STEPS } from "./check.js";
5
- import { taskByVersion } from "./task.js";
5
+ import { isCurrentTask, taskByVersion } from "./task.js";
6
+ import { AGENT_TASK_VERSION } from "./agent-bench.js";
6
7
  /** A GitHub handle, without the "@": what `--by` accepts and what reports store. */
7
8
  export function contributor(by) {
8
9
  if (by === undefined)
@@ -53,6 +54,8 @@ const IPV4 = /\b(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3
53
54
  /** "12 Main Street", "Calle Mayor 5", "Apt 4B": a street or a flat, which a label never needs. */
54
55
  const ADDRESS = /\b\d+[A-Za-z]?\s+(?:[A-Za-zÀ-ÿ'.-]+\s+){0,3}(?:street|st|road|rd|avenue|ave|lane|ln|drive|dr|way|court|ct|place|pl|boulevard|blvd|terrace|close)\b\.?|\b(?:calle|carrer|rue|via|avenida|straße|strasse|str)\.?\s+[A-Za-zÀ-ÿ'.-]+(?:\s+[A-Za-zÀ-ÿ'.-]+){0,3}\s+\d+|\b(?:apt|apartment|flat|suite|unit|piso|puerta)\.?\s*#?\d+/i;
55
56
  const isNum = (n, min = 0, max = Infinity) => typeof n === "number" && Number.isFinite(n) && n >= min && n <= max;
57
+ const isCount = (n, max) => Number.isInteger(n) && isNum(n, 0, max);
58
+ const isSize = (size) => isNum(size?.vcpu, 0.1, 1024) && isNum(size?.memoryGb, 0.0625, 4096);
56
59
  function checkDate(iso, now) {
57
60
  if (typeof iso !== "string" || Number.isNaN(Date.parse(iso)))
58
61
  return "date is missing or not an ISO date";
@@ -116,12 +119,34 @@ export function validateResult(j, now = Date.now()) {
116
119
  out.push(`${r?.provider}: failures must be between 0 and runs`);
117
120
  if (r?.limited !== undefined && !isNum(r.limited, 0, r?.failures ?? 0))
118
121
  out.push(`${r?.provider}: limited must be between 0 and failures`);
119
- for (const k of ["medianCreateMs", "medianExecMs"]) {
122
+ for (const k of ["medianCreateMs", "medianExecMs", "medianReadyMs", "medianTaskReadyMs"]) {
120
123
  if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
121
124
  out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
122
125
  }
123
126
  if (r?.failures < r?.runs && r?.medianCreateMs === undefined)
124
127
  out.push(`${r?.provider}: successful runs but no medianCreateMs`);
128
+ if (r?.size !== undefined && !isSize(r.size))
129
+ out.push(`${r?.provider}: invalid sandbox size`);
130
+ if (isCurrentTask(j.task)) {
131
+ if (!isSize(j.spec) || !isSize(r?.size))
132
+ out.push(`${r?.provider}: current tasks must record requested and nominal sizes`);
133
+ if (!isCount(r?.taskOk, (r?.runs ?? 0) - (r?.failures ?? 0)))
134
+ out.push(`${r?.provider}: invalid completed task count`);
135
+ if (r?.taskOk > 0 && (r.medianTaskMs === undefined || r.medianTaskReadyMs === undefined || !r.taskPhasesMs)) {
136
+ out.push(`${r.provider}: completed tasks require task and readiness timings`);
137
+ }
138
+ if (r?.taskOk === 0 && (r.medianTaskMs !== undefined || r.medianTaskReadyMs !== undefined || r.taskPhasesMs)) {
139
+ out.push(`${r.provider}: task timings require a completed task`);
140
+ }
141
+ }
142
+ if (r?.createFailures !== undefined || r?.commandFailures !== undefined) {
143
+ if (!isCount(r.createFailures, r.runs) || !isCount(r.commandFailures, r.runs) ||
144
+ r.createFailures + r.commandFailures !== r.failures || (r.limited ?? 0) > r.createFailures) {
145
+ out.push(`${r.provider}: create and command failure counts must reconcile with failures and limits`);
146
+ }
147
+ }
148
+ if (r?.cleanupFailures !== undefined && !isCount(r.cleanupFailures, r.runs))
149
+ out.push(`${r.provider}: invalid cleanup failure count`);
125
150
  if (r?.medianTaskMs !== undefined && !isNum(r.medianTaskMs, 1, MAX_MS))
126
151
  out.push(`${r?.provider}: medianTaskMs must be between 1 ms and 15 min`);
127
152
  if (r?.medianTaskCpuMs !== undefined && !isNum(r.medianTaskCpuMs, 0, 64 * MAX_MS))
@@ -179,6 +204,11 @@ export function validateResult(j, now = Date.now()) {
179
204
  out.push(`${r.provider}: ${NO_BENCH}`);
180
205
  if (!isNum(r?.ok, 0, r?.runs ?? 0))
181
206
  out.push(`${r?.provider}: ok must be between 0 and runs`);
207
+ if (j.task === AGENT_TASK_VERSION &&
208
+ (r?.requested !== j.runs || r.runs + (r.limited ?? 0) !== r.requested ||
209
+ !isCount(r.started, r.runs) || r.ok > r.started || !isSize(r.size))) {
210
+ out.push(`${r?.provider}: agent request, start, success counts and shape must reconcile`);
211
+ }
182
212
  if (r?.limited !== undefined && !isNum(r.limited, 0, 1000))
183
213
  out.push(`${r?.provider}: limited is out of range`);
184
214
  for (const k of ["medianWallMs", "medianModelMs", "medianCpuMs"]) {
@@ -207,6 +237,16 @@ export function validateResult(j, now = Date.now()) {
207
237
  out.push(`${r?.provider}: n must match the report's n`);
208
238
  if (!isNum(r?.ok, 0, j.n) || !isNum(r?.limited, 0, j.n) || r.ok + r.limited > j.n)
209
239
  out.push(`${r?.provider}: ok and limited must add up to at most n`);
240
+ if (r?.size !== undefined && !isSize(r.size))
241
+ out.push(`${r.provider}: invalid sandbox size`);
242
+ if (r?.createFailures !== undefined || r?.commandFailures !== undefined || r?.taskFailures !== undefined) {
243
+ if (![r.createFailures, r.commandFailures, r.taskFailures].every((n) => isCount(n, j.n)) ||
244
+ r.ok + r.createFailures + r.commandFailures + r.taskFailures !== j.n || r.limited > r.createFailures) {
245
+ out.push(`${r.provider}: burst failures, limits and completed requests do not reconcile`);
246
+ }
247
+ }
248
+ if (r?.cleanupFailures !== undefined && !isCount(r.cleanupFailures, j.n))
249
+ out.push(`${r.provider}: invalid cleanup failure count`);
210
250
  for (const k of ["p50Ms", "p95Ms", "p99Ms", "jobP50Ms"]) {
211
251
  if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
212
252
  out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
@@ -266,13 +306,74 @@ export function validateResult(j, now = Date.now()) {
266
306
  out.push(`${e?.provider}: predictedUsd is out of range`);
267
307
  if (e?.bill?.usd !== undefined && !isNum(e.bill.usd, 0, 1000))
268
308
  out.push(`${e?.provider}: bill.usd is out of range`);
309
+ if (e?.bill?.kind !== undefined && !["provider-usage", "provider-estimate"].includes(e.bill.kind)) {
310
+ out.push(`${e?.provider}: invalid billing evidence kind`);
311
+ }
312
+ if (e?.bill?.resolutionUsd !== undefined && !isNum(e.bill.resolutionUsd, 0.000001, 1)) {
313
+ out.push(`${e?.provider}: billing resolution is out of range`);
314
+ }
269
315
  if (e?.delivered && !(isNum(e.delivered.vcpu, 0.1, 1024) && isNum(e.delivered.memoryMb, 64, 4_194_304))) {
270
316
  out.push(`${e?.provider}: delivered size is out of range`);
271
317
  }
272
318
  }
273
319
  }
320
+ else if (j.tool === "sandboxrouter-hosted-ledger") {
321
+ add(checkDate(j.date, now));
322
+ const runFields = new Set(["tool", "date", "entries", "keySpendDeltaUsd"]);
323
+ if (Object.keys(j).some((key) => !runFields.has(key)))
324
+ out.push("hosted ledger reports must contain only public billing fields");
325
+ if (j.keySpendDeltaUsd !== undefined && !isNum(j.keySpendDeltaUsd, 0, 1000))
326
+ out.push("invalid total key spend delta");
327
+ if (!Array.isArray(j.entries) || !j.entries.length)
328
+ out.push("entries is empty");
329
+ const fields = new Set([
330
+ "provider", "requested", "size", "expectedSeconds", "runtimeSeconds", "quoteUsd", "chargeUsd", "quoteAtRecordedRuntimeUsd",
331
+ "balanceDeltaUsd", "keySpendDeltaUsd", "minimumSeconds", "minimumCovers", "incrementSeconds",
332
+ "feePct", "checkedAt", "createMs", "commandMs", "belowQuotedCapRejected", "commandVerified", "deleted",
333
+ ]);
334
+ for (const e of Array.isArray(j.entries) ? j.entries : []) {
335
+ provider(e?.provider, "entry provider");
336
+ if (noBench(e?.provider))
337
+ out.push(`${e.provider}: ${NO_BENCH}`);
338
+ if (Object.keys(e ?? {}).some((key) => !fields.has(key)))
339
+ out.push("hosted ledger entries must contain only public billing fields");
340
+ if (![e?.requested, e?.size].every((size) => isSize(size) && Object.keys(size).length === 2)) {
341
+ out.push(`${e?.provider}: sandbox sizes must contain only vcpu and memoryGb`);
342
+ }
343
+ for (const key of ["expectedSeconds", "runtimeSeconds"]) {
344
+ if (!isNum(e?.[key], 0, 24 * 3600))
345
+ out.push(`${e?.provider}: invalid ${key}`);
346
+ }
347
+ for (const key of ["quoteUsd", "chargeUsd", "balanceDeltaUsd"]) {
348
+ if (!isNum(e?.[key], 0, 1000))
349
+ out.push(`${e?.provider}: invalid ${key}`);
350
+ }
351
+ if (e?.keySpendDeltaUsd !== undefined && !isNum(e.keySpendDeltaUsd, 0, 1000))
352
+ out.push(`${e.provider}: invalid keySpendDeltaUsd`);
353
+ if (e?.quoteAtRecordedRuntimeUsd !== undefined && !isNum(e.quoteAtRecordedRuntimeUsd, 0, 1000))
354
+ out.push(`${e.provider}: invalid runtime quote`);
355
+ if (e?.minimumSeconds !== undefined && !isNum(e.minimumSeconds, 0, 24 * 3600))
356
+ out.push(`${e.provider}: invalid minimumSeconds`);
357
+ if (e?.minimumCovers !== undefined && !["all", "memory"].includes(e.minimumCovers))
358
+ out.push(`${e.provider}: invalid minimumCovers`);
359
+ if (e?.incrementSeconds !== undefined && !isNum(e.incrementSeconds, 1, 24 * 3600))
360
+ out.push(`${e.provider}: invalid incrementSeconds`);
361
+ if (!isNum(e?.feePct, 0, 100))
362
+ out.push(`${e?.provider}: invalid feePct`);
363
+ if (e?.checkedAt !== undefined)
364
+ add(checkDate(e.checkedAt, now));
365
+ for (const key of ["createMs", "commandMs"]) {
366
+ if (e?.[key] !== undefined && !isNum(e[key], 0, MAX_MS))
367
+ out.push(`${e.provider}: invalid ${key}`);
368
+ }
369
+ if (e?.belowQuotedCapRejected !== undefined && typeof e.belowQuotedCapRejected !== "boolean")
370
+ out.push(`${e.provider}: invalid cap check`);
371
+ if (e?.commandVerified !== true || e?.deleted !== true)
372
+ out.push(`${e?.provider}: command output and deletion must be verified`);
373
+ }
374
+ }
274
375
  else {
275
- out.push(`unknown tool "${String(j.tool)}": expected a bench report, a burst report, a spread report, an agent report, a saved check or a cost run`);
376
+ out.push(`unknown tool "${String(j.tool)}": expected a benchmark report, saved check, cost run or hosted ledger check`);
276
377
  }
277
378
  return out;
278
379
  }
package/dist/router.d.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import { type ProviderInfo } from "./catalog.js";
1
2
  import { type ComputerRoute, RoutedComputer, type ComputerOs, type ComputerProvider, type ComputerProviderId, type ComputerSpec } from "./computers.js";
2
3
  import { Ledger } from "./ledger.js";
3
- import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxSpec } from "./types.js";
4
+ import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxProcess, type SandboxSpec, type StartOptions } from "./types.js";
4
5
  /** vCPUs and memory a sandbox gets. */
5
6
  export interface Size {
6
7
  vcpu: number;
@@ -28,7 +29,7 @@ export interface Candidate {
28
29
  * asked for (2 vCPU / 4 GB when nothing was). Some providers round up to their next size.
29
30
  */
30
31
  size: Size;
31
- /** Median create time: this router's own recent creates when it has a few, else your `bench` file. */
32
+ /** Median create time from this router, your `bench` file or the published benchmarks, in that order. */
32
33
  medianCreateMs?: number;
33
34
  /** Passed the real-account check (as of this release, or `RouterOptions.verified`). */
34
35
  verified: boolean;
@@ -39,6 +40,10 @@ export interface Candidate {
39
40
  * spreads it over the run (`expectedSeconds`, else `timeoutMinutes`, default 30), so it weighs more on short ones.
40
41
  */
41
42
  perSandboxUsd?: number;
43
+ /** Account-specific start fees that the estimate and price cap exclude. */
44
+ conditionalStartFee?: ProviderInfo["pricing"]["conditionalStartFee"];
45
+ /** The compute estimate omits GPU charges when the request includes a GPU. */
46
+ excludesGpuCost?: true;
42
47
  /** Why this provider won't be tried, if it won't. */
43
48
  skip?: string;
44
49
  /** Set while the provider is at the back of the line after a limit or repeated failures (see `cooldown`). */
@@ -58,14 +63,20 @@ export interface Quote {
58
63
  runSeconds: number;
59
64
  /** What the run costs per hour once minimum charge, billing increment and per-sandbox charge are counted. */
60
65
  runHourlyUsd: number;
61
- /** What the run costs in all. */
66
+ /** Estimated charge for this run, excluding account-specific fees. */
62
67
  estimatedUsd: number;
63
68
  /** The provider bills at least this many seconds per sandbox. */
64
69
  minimumSeconds?: number;
70
+ /** Which components are subject to the minimum. */
71
+ minimumCovers?: "all" | "memory";
65
72
  /** The provider bills in whole steps of this many seconds. */
66
73
  billedInSecondsOf?: number;
67
74
  /** A fixed charge per sandbox started, included in `estimatedUsd`. */
68
75
  perSandboxUsd?: number;
76
+ /** Account-specific start fees that the estimate excludes. */
77
+ conditionalStartFee?: Candidate["conditionalStartFee"];
78
+ /** The compute estimate omits GPU charges when the request includes a GPU. */
79
+ excludesGpuCost?: true;
69
80
  /** The whole plan: every provider, in the order a create would try them, with why any are skipped. */
70
81
  candidates: Candidate[];
71
82
  }
@@ -246,10 +257,9 @@ export declare class RoutedSandbox {
246
257
  attempts: Attempt[], price?: SandboxPrice, ledger?: Ledger | undefined);
247
258
  get nativeId(): string;
248
259
  /**
249
- * The provider SDK's own sandbox object, for what the router doesn't cover: ports, background processes,
250
- * snapshots, anything else the provider has. Narrow it with the provider's own type, e.g.
251
- * `if (sbx.provider === "e2b") (sbx.native as import("e2b").Sandbox).getHost(3000)`. Undefined for providers
252
- * driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
260
+ * The provider SDK's own sandbox object for provider-specific features such as snapshots. Narrow it
261
+ * with the provider's own type. Undefined for providers driven over plain HTTP (use `nativeId` with
262
+ * their API). Calls made through it aren't routed or tracked.
253
263
  */
254
264
  get native(): unknown;
255
265
  /**
@@ -259,6 +269,10 @@ export declare class RoutedSandbox {
259
269
  * always rely on the timeout being bounded and the message being the same on every provider.
260
270
  */
261
271
  exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
272
+ /** Get the provider's HTTP preview URL for a service listening on this port. */
273
+ url(port: number): Promise<string>;
274
+ /** Start a command and return a handle that stops it without stopping the sandbox. */
275
+ start(cmd: string, opts?: StartOptions): Promise<SandboxProcess>;
262
276
  writeFile(path: string, content: string | Uint8Array): Promise<void>;
263
277
  readFile(path: string): Promise<Uint8Array>;
264
278
  readText(path: string): Promise<string>;
@@ -294,5 +308,5 @@ export declare const DEFAULT_CREATE_TIMEOUT_S = 120;
294
308
  export declare const DEFAULT_CREATE_DEADLINE_S = 240;
295
309
  /** Seconds past a command's timeout before the router stops waiting for the adapter. */
296
310
  export declare const EXEC_GRACE_S = 30;
297
- /** The size a provider gives for a spec: its fixed default image size, else what was asked for. */
311
+ /** The size a provider gives for a spec, including fixed images and Vercel allocations. */
298
312
  export declare function sizeOf(id: ProviderId, spec?: SandboxSpec): Size;
package/dist/router.js CHANGED
@@ -1,4 +1,5 @@
1
- import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost, unfit } from "./catalog.js";
1
+ import { randomUUID } from "node:crypto";
2
+ import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost, info, unfit, vercelSandboxSize } from "./catalog.js";
2
3
  import { RoutedComputer, createComputer, planComputer, } from "./computers.js";
3
4
  import { loadBench, median } from "./bench-store.js";
4
5
  import { PUBLISHED } from "./published.js";
@@ -6,7 +7,7 @@ import { Ledger, defaultLedgerFile } from "./ledger.js";
6
7
  import { DEFAULT_EXEC_TIMEOUT_S, LIMIT_ERROR, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
7
8
  import { BILLED_VS_LIST } from "./billing.js";
8
9
  import { FAILING, VERIFIED } from "./verified.js";
9
- import { validate } from "./validate.js";
10
+ import { isPort, validate, validateStart } from "./validate.js";
10
11
  import { DaytonaProvider } from "./providers/daytona.js";
11
12
  import { E2BProvider } from "./providers/e2b.js";
12
13
  import { MaritimeProvider } from "./providers/maritime.js";
@@ -186,6 +187,11 @@ export class Router {
186
187
  const fee = billingRules(id).perSandboxUsd;
187
188
  if (fee)
188
189
  c.perSandboxUsd = fee;
190
+ const conditionalStartFee = info(id).pricing.conditionalStartFee;
191
+ if (conditionalStartFee)
192
+ c.conditionalStartFee = { ...conditionalStartFee };
193
+ if (spec.gpu)
194
+ c.excludesGpuCost = true;
189
195
  if (!p)
190
196
  c.skip = "no adapter registered";
191
197
  else {
@@ -196,9 +202,13 @@ export class Router {
196
202
  (this.requireVerified && !c.verified ? "not tested (this router only uses providers that passed the real-account check)" : undefined);
197
203
  }
198
204
  if (!c.skip && route.maxHourlyUsd !== undefined) {
199
- const rate = rankUsd(c, runHours(spec));
200
- if (rate > route.maxHourlyUsd)
201
- c.skip = `${OVER_CAP}: ${usdPerHour(rate)} for this run, cap ${usdPerHour(route.maxHourlyUsd)}`;
205
+ if (c.excludesGpuCost)
206
+ c.skip = "cannot verify maxHourlyUsd because GPU charges are not modelled";
207
+ else {
208
+ const rate = rankUsd(c, runHours(spec));
209
+ if (rate > route.maxHourlyUsd)
210
+ c.skip = `${OVER_CAP}: ${usdPerHour(rate)} for this run, cap ${usdPerHour(route.maxHourlyUsd)}`;
211
+ }
202
212
  }
203
213
  return c;
204
214
  });
@@ -319,9 +329,11 @@ export class Router {
319
329
  runSeconds: Math.round(hours * 3600),
320
330
  runHourlyUsd,
321
331
  estimatedUsd: runHourlyUsd * hours,
322
- ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds } : {}),
332
+ ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds, minimumCovers: rules.minimumCovers } : {}),
323
333
  ...(rules.incrementSeconds > 1 ? { billedInSecondsOf: rules.incrementSeconds } : {}),
324
334
  ...(first.perSandboxUsd ? { perSandboxUsd: first.perSandboxUsd } : {}),
335
+ ...(first.conditionalStartFee ? { conditionalStartFee: first.conditionalStartFee } : {}),
336
+ ...(first.excludesGpuCost ? { excludesGpuCost: true } : {}),
325
337
  candidates,
326
338
  };
327
339
  }
@@ -495,10 +507,9 @@ export class RoutedSandbox {
495
507
  return this.box.nativeId;
496
508
  }
497
509
  /**
498
- * The provider SDK's own sandbox object, for what the router doesn't cover: ports, background processes,
499
- * snapshots, anything else the provider has. Narrow it with the provider's own type, e.g.
500
- * `if (sbx.provider === "e2b") (sbx.native as import("e2b").Sandbox).getHost(3000)`. Undefined for providers
501
- * driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
510
+ * The provider SDK's own sandbox object for provider-specific features such as snapshots. Narrow it
511
+ * with the provider's own type. Undefined for providers driven over plain HTTP (use `nativeId` with
512
+ * their API). Calls made through it aren't routed or tracked.
502
513
  */
503
514
  get native() {
504
515
  return this.box.native;
@@ -513,6 +524,40 @@ export class RoutedSandbox {
513
524
  const seconds = opts.timeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_S;
514
525
  return withDeadline(this.box.exec(cmd, opts), (seconds + EXEC_GRACE_S) * 1000, () => timeoutError(this.provider, seconds));
515
526
  }
527
+ /** Get the provider's HTTP preview URL for a service listening on this port. */
528
+ async url(port) {
529
+ if (!isPort(port))
530
+ throw new RouterError("port must be an integer from 1 to 65535", [], "bad_request");
531
+ if (!this.box.url)
532
+ throw new RouterError(`${this.provider} does not support port URLs; create with require: ["ports"]`, [], "unsupported");
533
+ const preview = await this.box.url(port);
534
+ if (!/^https?:\/\//i.test(preview) || !URL.canParse(preview)) {
535
+ throw new ProviderError(this.provider, "invalid HTTP preview URL", 502);
536
+ }
537
+ return preview;
538
+ }
539
+ /** Start a command and return a handle that stops it without stopping the sandbox. */
540
+ async start(cmd, opts = {}) {
541
+ validateStart(cmd, opts);
542
+ if (!this.box.start)
543
+ throw new RouterError(`${this.provider} does not support background commands; create with require: ["background"]`, [], "unsupported");
544
+ const pending = this.box.start(cmd, opts);
545
+ const handle = await withDeadline(pending, (DEFAULT_EXEC_TIMEOUT_S + EXEC_GRACE_S) * 1000, () => {
546
+ // The caller has no handle if the provider answers after the start deadline.
547
+ void pending.then((late) => late.kill()).catch(() => { });
548
+ return new ProviderError(this.provider, "background command start timed out", 504);
549
+ });
550
+ let stopping;
551
+ return {
552
+ id: randomUUID(),
553
+ kill: () => stopping ??= Promise.resolve().then(() => handle.kill()).catch((error) => {
554
+ if (errorStatus(error) === 404)
555
+ return;
556
+ stopping = undefined;
557
+ throw error;
558
+ }),
559
+ };
560
+ }
516
561
  writeFile(path, content) {
517
562
  return this.box.writeFile(path, content);
518
563
  }
@@ -600,7 +645,9 @@ export const DEFAULT_CREATE_TIMEOUT_S = 120;
600
645
  export const DEFAULT_CREATE_DEADLINE_S = 240;
601
646
  /** Seconds past a command's timeout before the router stops waiting for the adapter. */
602
647
  export const EXEC_GRACE_S = 30;
603
- /** The size a provider gives for a spec: its fixed default image size, else what was asked for. */
648
+ /** The size a provider gives for a spec, including fixed images and Vercel allocations. */
604
649
  export function sizeOf(id, spec = {}) {
650
+ if (id === "vercel")
651
+ return vercelSandboxSize(spec);
605
652
  return fixedSize(id, spec) ?? { vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB };
606
653
  }
package/dist/server.d.ts CHANGED
@@ -61,11 +61,14 @@ export interface ServerHooks {
61
61
  * GET /v1/providers
62
62
  * POST /v1/route dry run: which providers would be tried, in order
63
63
  * POST /v1/quote where a create would land and what the run would cost
64
- * POST /v1/sandboxes { vcpu, memoryGb, ..., provider, strategy, fallback, require, createTimeoutSeconds }
64
+ * POST /v1/sandboxes { vcpu, memoryGb, ports, ..., provider, strategy, fallback, require, createTimeoutSeconds }
65
65
  * POST /v1/sandboxes/:id/exec { cmd, cwd, env, timeoutSeconds, stream }
66
66
  * stream: true answers text/event-stream: `stdout`/`stderr` events (JSON string chunks),
67
67
  * then one `result` event (the ExecResult), or an `error` event
68
68
  * POST /v1/sandboxes/:id/pause keeps the disk; the next call resumes it
69
+ * GET /v1/sandboxes/:id/ports/:port { url }
70
+ * POST /v1/sandboxes/:id/processes { cmd, cwd, env } -> { id }
71
+ * DELETE /v1/sandboxes/:id/processes/:processId
69
72
  * PUT /v1/sandboxes/:id/files?path= raw body
70
73
  * GET /v1/sandboxes/:id/files?path= raw body
71
74
  * DELETE /v1/sandboxes/:id