@sandboxrouter/sdk 0.8.3 → 0.10.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.
@@ -2,8 +2,12 @@ import { type Provider, type ProviderSandbox, type SandboxSpec } from "../types.
2
2
  export declare const OPENSCALE_DOMAIN = "sandbox.openscale.so";
3
3
  export declare class OpenScaleProvider implements Provider {
4
4
  private apiKey;
5
+ /** The API's address; set OPENSCALE_API_URL only for a proxy or a test server. */
6
+ private apiUrl;
5
7
  readonly id: "openscale";
6
- constructor(apiKey?: string | undefined);
8
+ constructor(apiKey?: string | undefined,
9
+ /** The API's address; set OPENSCALE_API_URL only for a proxy or a test server. */
10
+ apiUrl?: string);
7
11
  configured(): boolean;
8
12
  /** @internal Connection options for the e2b SDK. */
9
13
  conn(): {
@@ -37,9 +37,13 @@ export const OPENSCALE_DOMAIN = "sandbox.openscale.so";
37
37
  const DEFAULT_TEMPLATE = "base";
38
38
  export class OpenScaleProvider {
39
39
  apiKey;
40
+ apiUrl;
40
41
  id = ID;
41
- constructor(apiKey = process.env.OPENSCALE_API_KEY) {
42
+ constructor(apiKey = process.env.OPENSCALE_API_KEY,
43
+ /** The API's address; set OPENSCALE_API_URL only for a proxy or a test server. */
44
+ apiUrl = process.env.OPENSCALE_API_URL || `https://api.${OPENSCALE_DOMAIN}`) {
42
45
  this.apiKey = apiKey;
46
+ this.apiUrl = apiUrl;
43
47
  }
44
48
  configured() {
45
49
  return !!this.apiKey;
@@ -48,7 +52,7 @@ export class OpenScaleProvider {
48
52
  conn() {
49
53
  if (!this.apiKey)
50
54
  throw new ProviderError(ID, "OPENSCALE_API_KEY is not set");
51
- return { apiKey: this.apiKey, domain: OPENSCALE_DOMAIN, apiUrl: `https://api.${OPENSCALE_DOMAIN}` };
55
+ return { apiKey: this.apiKey, domain: OPENSCALE_DOMAIN, apiUrl: this.apiUrl };
52
56
  }
53
57
  async create(spec) {
54
58
  const conn = this.conn();
package/dist/results.js CHANGED
@@ -2,6 +2,7 @@ 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
6
  /** A GitHub handle, without the "@": what `--by` accepts and what reports store. */
6
7
  export function contributor(by) {
7
8
  if (by === undefined)
@@ -101,6 +102,8 @@ export function validateResult(j, now = Date.now()) {
101
102
  add(checkBy(j.by));
102
103
  if (!isNum(j.runs, 3, 1000))
103
104
  out.push("runs must be at least 3");
105
+ if (j.task !== undefined && typeof j.task !== "string")
106
+ out.push("task must be the task version, e.g. \"v1\"");
104
107
  if (!Array.isArray(j.rows) || !j.rows.length)
105
108
  out.push("rows is empty");
106
109
  for (const r of Array.isArray(j.rows) ? j.rows : []) {
@@ -117,6 +120,21 @@ export function validateResult(j, now = Date.now()) {
117
120
  }
118
121
  if (r?.failures < r?.runs && r?.medianCreateMs === undefined)
119
122
  out.push(`${r?.provider}: successful runs but no medianCreateMs`);
123
+ if (r?.medianTaskMs !== undefined && !isNum(r.medianTaskMs, 1, MAX_MS))
124
+ out.push(`${r?.provider}: medianTaskMs must be between 1 ms and 15 min`);
125
+ if (r?.medianTaskCpuMs !== undefined && !isNum(r.medianTaskCpuMs, 0, 64 * MAX_MS))
126
+ out.push(`${r?.provider}: medianTaskCpuMs is out of range`);
127
+ if (r?.taskPhasesMs !== undefined) {
128
+ const ph = r.taskPhasesMs;
129
+ const def = taskByVersion(j.task);
130
+ if (j.task === undefined)
131
+ out.push(`${r?.provider}: has task times but the report doesn't say which task (task)`);
132
+ else if (!def)
133
+ out.push(`${r?.provider}: unknown task "${String(j.task)}"`);
134
+ else if (!ph || typeof ph !== "object" || def.phases.some((p) => !isNum(ph[p.id], 1, MAX_MS))) {
135
+ out.push(`${r?.provider}: taskPhasesMs needs ${def.phases.map((p) => p.id).join(", ")}, each between 1 ms and 15 min`);
136
+ }
137
+ }
120
138
  if ("lastError" in (r ?? {}))
121
139
  out.push(`${r?.provider}: lastError must not be shared (it can hold account details)`);
122
140
  }
package/dist/router.d.ts CHANGED
@@ -16,6 +16,11 @@ export interface Candidate {
16
16
  estimatedHourlyUsd: number;
17
17
  /** The provider's published list price for this size, USD/hour. */
18
18
  listHourlyUsd: number;
19
+ /**
20
+ * For providers that bill CPU only while busy: the CPU part of `estimatedHourlyUsd`, at the spec's
21
+ * `cpuUtilization`. Ranking needs it where a minimum charge covers memory only (Vercel).
22
+ */
23
+ cpuHourlyUsd?: number;
19
24
  /** Billed / list-price ratio behind `estimatedHourlyUsd`, when measured (`BILLED_VS_LIST`). */
20
25
  billedVsList?: number;
21
26
  /**
@@ -37,6 +42,33 @@ export interface Candidate {
37
42
  /** Why this provider won't be tried, if it won't. */
38
43
  skip?: string;
39
44
  }
45
+ /** What `router.quote()` answers: the provider a create would start on first, and what the run would cost there. */
46
+ export interface Quote {
47
+ provider: ProviderId;
48
+ size: {
49
+ vcpu: number;
50
+ memoryGb: number;
51
+ };
52
+ /** The provider's price per hour for this size: list price, corrected by what it really bills where measured. */
53
+ hourlyUsd: number;
54
+ listHourlyUsd: number;
55
+ /** The run the estimate is for: `expectedSeconds`, else `timeoutMinutes` (default 30). */
56
+ runSeconds: number;
57
+ /** What the run costs per hour once minimum charge, billing increment and per-sandbox charge are counted. */
58
+ runHourlyUsd: number;
59
+ /** What the run costs in all. */
60
+ estimatedUsd: number;
61
+ /** The provider bills at least this many seconds per sandbox. */
62
+ minimumSeconds?: number;
63
+ /** The provider bills in whole steps of this many seconds. */
64
+ billedInSecondsOf?: number;
65
+ /** A fixed charge per sandbox started, included in `estimatedUsd`. */
66
+ perSandboxUsd?: number;
67
+ /** The whole plan: every provider, in the order a create would try them, with why any are skipped. */
68
+ candidates: Candidate[];
69
+ }
70
+ /** "$0.0123/h": enough digits to tell cheap providers apart. */
71
+ export declare const usdPerHour: (n: number) => string;
40
72
  /** Providers within this share of the cheapest remaining price count as a tie, broken by speed. */
41
73
  export declare const PRICE_TIE = 0.1;
42
74
  export interface RouterOptions {
@@ -120,6 +152,11 @@ export declare class Router {
120
152
  * providers they do have keys for were skipped.
121
153
  */
122
154
  private whyNone;
155
+ /**
156
+ * Where a create would land and what the run would cost there, without starting anything. Throws
157
+ * RouterError("no_provider") when nothing can take it, with the same reason create would give.
158
+ */
159
+ quote(spec?: SandboxSpec, route?: RouteOptions): Quote;
123
160
  /** Start a sandbox on the best available provider, falling back down the list on failure. */
124
161
  create(spec?: SandboxSpec, route?: RouteOptions): Promise<RoutedSandbox>;
125
162
  /**
package/dist/router.js CHANGED
@@ -1,4 +1,4 @@
1
- import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, accessLabel, billingRules, fixedSize, hourlyCost, unfit } from "./catalog.js";
1
+ import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost, unfit } from "./catalog.js";
2
2
  import { RoutedComputer, createComputer, planComputer, } from "./computers.js";
3
3
  import { loadBench, median } from "./bench-store.js";
4
4
  import { Ledger, defaultLedgerFile } from "./ledger.js";
@@ -45,6 +45,10 @@ import { MobilerunProvider } from "./providers/mobilerun.js";
45
45
  import { LimrunProvider } from "./providers/limrun.js";
46
46
  import { WorkspacesAgentProvider } from "./providers/workspaces.js";
47
47
  import { ProviderError, SetupError, RouterError, } from "./types.js";
48
+ /** How a candidate over `maxHourlyUsd` is marked (its `skip` starts with this). */
49
+ const OVER_CAP = "over your price cap";
50
+ /** "$0.0123/h": enough digits to tell cheap providers apart. */
51
+ export const usdPerHour = (n) => `$${n >= 1 ? n.toFixed(2) : Number(n.toPrecision(3))}/h`;
48
52
  /** Providers within this share of the cheapest remaining price count as a tie, broken by speed. */
49
53
  export const PRICE_TIE = 0.1;
50
54
  /** Creates this router must have seen for a provider before its own timings replace the bench file's. */
@@ -159,6 +163,7 @@ export class Router {
159
163
  provider: id,
160
164
  estimatedHourlyUsd: round(list * (ratio ?? 1)),
161
165
  listHourlyUsd: list,
166
+ ...(cpuHourlyAtFull(id, spec) > 0 ? { cpuHourlyUsd: round(cpuHourlyAtFull(id, spec) * billedCpuShare(id, spec) * (ratio ?? 1)) } : {}),
162
167
  ...(ratio !== undefined ? { billedVsList: ratio } : {}),
163
168
  size: sizeOf(id, spec),
164
169
  medianCreateMs: speed ? (live && live.length >= LIVE_MIN_SAMPLES ? median(live) : median(bench[id]?.createMs)) : undefined,
@@ -177,6 +182,11 @@ export class Router {
177
182
  (p.configured() ? undefined : gated ? `not configured; ${gated}` : "not configured") ??
178
183
  (this.requireVerified && !c.verified ? "not tested (this router only uses providers that passed the real-account check)" : undefined);
179
184
  }
185
+ if (!c.skip && route.maxHourlyUsd !== undefined) {
186
+ const rate = rankUsd(c, runHours(spec));
187
+ if (rate > route.maxHourlyUsd)
188
+ c.skip = `${OVER_CAP}: ${usdPerHour(rate)} for this run, cap ${usdPerHour(route.maxHourlyUsd)}`;
189
+ }
180
190
  return c;
181
191
  });
182
192
  // Neutral by construction: the same rule for every provider, ties alphabetical by id. Nothing here
@@ -185,12 +195,11 @@ export class Router {
185
195
  if (!explicit) {
186
196
  const hours = runHours(spec);
187
197
  const byCost = (a, b) => rankUsd(a, hours) - rankUsd(b, hours) || a.provider.localeCompare(b.provider);
188
- const byList = (a, b) => a.listHourlyUsd - b.listHourlyUsd || a.provider.localeCompare(b.provider);
189
198
  if (strategy === "fastest") {
190
199
  list.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity) || byCost(a, b));
191
200
  }
192
201
  else if (strategy === "cheapest") {
193
- list.sort(byList);
202
+ list.sort(byCost);
194
203
  }
195
204
  else if (strategy === "verified") {
196
205
  list.sort((a, b) => Number(b.verified) - Number(a.verified) || byCost(a, b));
@@ -205,7 +214,7 @@ export class Router {
205
214
  * Why a create has nowhere to go, leading with what the caller can fix: no keys at all, or why the
206
215
  * providers they do have keys for were skipped.
207
216
  */
208
- whyNone(plan, explicit) {
217
+ whyNone(plan, explicit, spec = {}) {
209
218
  if (plan.length === 0)
210
219
  return "no provider can take this sandbox: none registered";
211
220
  // Providers the caller named: say what each one needs.
@@ -220,6 +229,13 @@ export class Router {
220
229
  if (keyed.length === 0)
221
230
  return ("no provider keys found: set the API key for at least one provider (the README's Env table lists each provider's variables); " +
222
231
  "`npx @sandboxrouter/sdk providers` shows which are set");
232
+ const over = keyed.filter((c) => c.skip?.startsWith(OVER_CAP));
233
+ if (over.length && over.length === keyed.length) {
234
+ const hours = runHours(spec);
235
+ const best = over.sort((a, b) => rankUsd(a, hours) - rankUsd(b, hours))[0];
236
+ // The skip's own words, so a service that prices the cap its own way (a fee) shows its price.
237
+ return `every provider you have keys for is over your price cap (maxHourlyUsd). Cheapest: ${best.provider}, ${best.skip.slice(OVER_CAP.length + 2)}`;
238
+ }
223
239
  const rest = plan.length - keyed.length;
224
240
  const small = keyed.filter((c) => c.skip?.startsWith("default image"));
225
241
  return (`none of the providers you have keys for can take this sandbox: ${keyed.map((c) => `${c.provider} (${c.skip})`).join(", ")}` +
@@ -229,12 +245,38 @@ export class Router {
229
245
  `or pass image: { ${small[0].provider}: "<template>" } with a template built at the size you need`
230
246
  : ""));
231
247
  }
248
+ /**
249
+ * Where a create would land and what the run would cost there, without starting anything. Throws
250
+ * RouterError("no_provider") when nothing can take it, with the same reason create would give.
251
+ */
252
+ quote(spec = {}, route = {}) {
253
+ const candidates = this.plan(spec, route);
254
+ const first = candidates.find((c) => !c.skip);
255
+ if (!first)
256
+ throw new RouterError(this.whyNone(candidates, !!route.provider, spec), [], "no_provider");
257
+ const hours = runHours(spec);
258
+ const rules = billingRules(first.provider);
259
+ const runHourlyUsd = rankUsd(first, hours);
260
+ return {
261
+ provider: first.provider,
262
+ size: first.size,
263
+ hourlyUsd: first.estimatedHourlyUsd,
264
+ listHourlyUsd: first.listHourlyUsd,
265
+ runSeconds: Math.round(hours * 3600),
266
+ runHourlyUsd,
267
+ estimatedUsd: runHourlyUsd * hours,
268
+ ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds } : {}),
269
+ ...(rules.incrementSeconds > 1 ? { billedInSecondsOf: rules.incrementSeconds } : {}),
270
+ ...(first.perSandboxUsd ? { perSandboxUsd: first.perSandboxUsd } : {}),
271
+ candidates,
272
+ };
273
+ }
232
274
  /** Start a sandbox on the best available provider, falling back down the list on failure. */
233
275
  async create(spec = {}, route = {}) {
234
276
  const plan = this.plan(spec, route);
235
277
  const usable = plan.filter((c) => !c.skip);
236
278
  if (usable.length === 0)
237
- throw new RouterError(this.whyNone(plan, !!route.provider), [], "no_provider");
279
+ throw new RouterError(this.whyNone(plan, !!route.provider, spec), [], "no_provider");
238
280
  // Pinned with no fallback: the first provider named, or nothing. Never a different one.
239
281
  if (route.provider && route.fallback === false && plan[0].skip) {
240
282
  throw new RouterError(`${plan[0].provider} can't take this sandbox: ${plan[0].skip}`, [], "no_provider");
@@ -242,15 +284,18 @@ export class Router {
242
284
  const attempts = [];
243
285
  const tries = route.fallback === false ? usable.slice(0, 1) : usable;
244
286
  const deadline = Date.now() + (route.deadlineSeconds ?? DEFAULT_CREATE_DEADLINE_S) * 1000;
287
+ const outOfTime = () => new RouterError(`create ran out of time (deadlineSeconds) after trying ${attempts.map((a) => a.provider).join(", ")}: ${attempts.map((a) => `${a.provider}: ${a.error}`).join(" | ")}`, attempts, "timeout");
245
288
  for (const [i, c] of tries.entries()) {
246
289
  const left = deadline - Date.now();
247
- if (left <= 0) {
248
- throw new RouterError(`create ran out of time (deadlineSeconds) after trying ${attempts.map((a) => a.provider).join(", ")}: ${attempts.map((a) => `${a.provider}: ${a.error}`).join(" | ")}`, attempts, "timeout");
249
- }
290
+ if (left <= 0)
291
+ throw outOfTime();
250
292
  const t0 = Date.now();
251
293
  const pending = this.provider(c.provider).create(spec);
252
294
  const { limitS, typicalMs } = this.waitFor(c.provider, route, i === tries.length - 1);
253
295
  const waitS = Math.min(limitS, left / 1000);
296
+ // This try's wait is what's left of the deadline: if it times out, the deadline is spent. Decided here,
297
+ // not by reading the clock again, since a timer can fire a millisecond early and let one more try start.
298
+ const lastChance = left / 1000 <= limitS;
254
299
  const price = { estimatedHourlyUsd: c.estimatedHourlyUsd, listHourlyUsd: c.listHourlyUsd, size: c.size };
255
300
  let timedOut = false;
256
301
  try {
@@ -272,6 +317,8 @@ export class Router {
272
317
  pending.then((late) => this.discard(c.provider, late, price, spec.timeoutMinutes), () => { });
273
318
  const status = errorStatus(err);
274
319
  attempts.push({ provider: c.provider, ok: false, ms: Date.now() - t0, error: err.message, ...(status ? { status } : {}) });
320
+ if (timedOut && lastChance)
321
+ throw outOfTime();
275
322
  const setup = err instanceof SetupError || (status !== undefined && SETUP_ERRORS.has(status));
276
323
  // On the router's own accounts, a key, permission or install problem is ours: move on.
277
324
  const account = err instanceof SetupError || status === 401 || status === 403;
@@ -475,10 +522,12 @@ export function runHours(spec) {
475
522
  * per-sandbox charge is added, so short runs favor providers that bill by the second without a fee.
476
523
  */
477
524
  export function rankUsd(c, hours) {
478
- const { minSeconds, incrementSeconds } = billingRules(c.provider);
525
+ const { minSeconds, incrementSeconds, minimumCovers } = billingRules(c.provider);
479
526
  const seconds = hours * 3600;
480
527
  const billed = Math.max(minSeconds, Math.ceil(seconds / incrementSeconds - 1e-9) * incrementSeconds);
481
- return (c.estimatedHourlyUsd * billed) / Math.max(seconds, 1) + (c.perSandboxUsd ?? 0) / Math.max(hours, 1 / 3600);
528
+ // Where the minimum covers memory only (Vercel), CPU is billed for the time actually used.
529
+ const cpu = minimumCovers === "memory" ? (c.cpuHourlyUsd ?? 0) : 0;
530
+ return ((c.estimatedHourlyUsd - cpu) * billed + cpu * seconds) / Math.max(seconds, 1) + (c.perSandboxUsd ?? 0) / Math.max(hours, 1 / 3600);
482
531
  }
483
532
  /** Seconds to wait for one provider's create before trying the next (RouteOptions.createTimeoutSeconds). */
484
533
  export const DEFAULT_CREATE_TIMEOUT_S = 120;
package/dist/server.d.ts CHANGED
@@ -48,6 +48,11 @@ export interface ServerHooks {
48
48
  orphanGraceMs?: number;
49
49
  /** false turns off pause. */
50
50
  pause?: boolean;
51
+ /**
52
+ * The router for this caller's requests (route, quote, create and every call on a sandbox), e.g. one
53
+ * with the caller's own provider keys. Default: the router passed to createApp.
54
+ */
55
+ routerFor?(caller: unknown): Router | Promise<Router>;
51
56
  }
52
57
  /**
53
58
  * OpenRouter-style HTTP API in front of every provider. One token for your clients; provider keys
@@ -55,6 +60,7 @@ export interface ServerHooks {
55
60
  *
56
61
  * GET /v1/providers
57
62
  * POST /v1/route dry run: which providers would be tried, in order
63
+ * POST /v1/quote where a create would land and what the run would cost
58
64
  * POST /v1/sandboxes { vcpu, memoryGb, ..., provider, strategy, fallback, require, createTimeoutSeconds }
59
65
  * POST /v1/sandboxes/:id/exec { cmd, cwd, env, timeoutSeconds, stream }
60
66
  * stream: true answers text/event-stream: `stdout`/`stderr` events (JSON string chunks),
@@ -75,7 +81,7 @@ export interface ServerHooks {
75
81
  * POST /v1/computers/:id/sleep
76
82
  * DELETE /v1/computers/:id
77
83
  */
78
- export declare function createApp(router?: Router, token?: string | undefined,
84
+ export declare function createApp(defaultRouter?: Router, token?: string | undefined,
79
85
  /** Browser origins allowed to call this server (e.g. the website's Playground). Off by default. */
80
86
  corsOrigins?: string[], hooks?: ServerHooks): import("node:http").Server<typeof IncomingMessage, typeof ServerResponse>;
81
87
  export declare class HttpError extends Error {
package/dist/server.js CHANGED
@@ -12,6 +12,7 @@ import { splitRequest } from "./validate.js";
12
12
  *
13
13
  * GET /v1/providers
14
14
  * POST /v1/route dry run: which providers would be tried, in order
15
+ * POST /v1/quote where a create would land and what the run would cost
15
16
  * POST /v1/sandboxes { vcpu, memoryGb, ..., provider, strategy, fallback, require, createTimeoutSeconds }
16
17
  * POST /v1/sandboxes/:id/exec { cmd, cwd, env, timeoutSeconds, stream }
17
18
  * stream: true answers text/event-stream: `stdout`/`stderr` events (JSON string chunks),
@@ -32,7 +33,7 @@ import { splitRequest } from "./validate.js";
32
33
  * POST /v1/computers/:id/sleep
33
34
  * DELETE /v1/computers/:id
34
35
  */
35
- export function createApp(router = new Router(), token = process.env.SANDBOXROUTER_TOKEN,
36
+ export function createApp(defaultRouter = new Router(), token = process.env.SANDBOXROUTER_TOKEN,
36
37
  /** Browser origins allowed to call this server (e.g. the website's Playground). Off by default. */
37
38
  corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.trim()).filter(Boolean), hooks = {}) {
38
39
  // With CORS on, any page open in a browser on this machine can call the server (Chrome even
@@ -144,6 +145,7 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
144
145
  return json(res, 401, { error: "unauthorized" });
145
146
  if (parts[0] !== "v1")
146
147
  return json(res, 404, { error: "not found" });
148
+ const router = hooks.routerFor ? await hooks.routerFor(caller) : defaultRouter;
147
149
  const box = async (id) => {
148
150
  if (hooks.owns && !(await hooks.owns(caller, id)))
149
151
  throw new HttpError(404, "no such sandbox");
@@ -163,6 +165,11 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
163
165
  const { spec, route } = splitRequest(await readJson(req));
164
166
  return json(res, 200, { candidates: router.plan(spec, route) });
165
167
  }
168
+ // POST /v1/quote
169
+ if (req.method === "POST" && parts[1] === "quote" && parts.length === 2) {
170
+ const { spec, route } = splitRequest(await readJson(req));
171
+ return json(res, 200, router.quote(spec, route));
172
+ }
166
173
  if (parts[1] === "computers") {
167
174
  if (!computersOn)
168
175
  return json(res, 404, { error: "computers aren't available on this server" });
@@ -297,7 +304,7 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
297
304
  const { spec, route } = splitComputerRequest(body);
298
305
  return once(req, res, body, async () => {
299
306
  await hooks.beforeCreateComputer?.(caller, spec);
300
- const c = await router.computer(spec, route);
307
+ const c = await defaultRouter.computer(spec, route);
301
308
  let extra;
302
309
  try {
303
310
  extra = await hooks.afterCreateComputer?.(caller, c);
@@ -317,7 +324,7 @@ corsOrigins = (process.env.SANDBOXROUTER_CORS ?? "").split(",").map((s) => s.tri
317
324
  return json(res, 404, { error: "not found" });
318
325
  if (hooks.owns && !(await hooks.owns(caller, id)))
319
326
  throw new HttpError(404, "no such computer");
320
- const c = await router.getComputer(id);
327
+ const c = await defaultRouter.getComputer(id);
321
328
  const sub = parts[3];
322
329
  if (req.method === "GET" && !sub)
323
330
  return json(res, 200, { ...(await c.info()), id, nativeId: c.nativeId });
package/dist/task.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import type { ProviderId, ProviderSandbox } from "./types.js";
2
+ /**
3
+ * The standard tasks for `bench --task`: the same fixed piece of work in every sandbox, so providers can be
4
+ * compared on what a job costs, not just on their hourly price. A slower CPU, disk or network makes the job
5
+ * take longer, and a longer job is billed more.
6
+ *
7
+ * Each phase is its own command, timed from here, minus the sandbox's own round trip for an empty command,
8
+ * so network distance to the provider mostly drops out.
9
+ *
10
+ * - "short": hash on one core, then two, then write to disk, once (seconds). Only POSIX shell and tools every
11
+ * Linux image has (coreutils or busybox), so no provider fails for lack of a package.
12
+ * - "long": the short job's phases 40 times in a row (minutes): sustained speed (CPUs that slow down after a
13
+ * burst) and prices once minimum charges stop mattering.
14
+ * - "python": a pure-Python script like a code-interpreter call. Needs python3 in the default image; a
15
+ * provider without it fails the task, which is itself worth knowing.
16
+ * - "download": fetch the 53 MB Node.js release from nodejs.org's CDN, with curl, else wget, else python3:
17
+ * what installing toolchains and packages depends on.
18
+ *
19
+ * Changing a phase changes what the numbers mean: bump that task's version, and older reports stop counting.
20
+ */
21
+ export type TaskKind = "short" | "long" | "python" | "download";
22
+ export interface TaskPhaseDef {
23
+ id: string;
24
+ label: string;
25
+ cmd: string;
26
+ }
27
+ export declare const TASKS: Record<TaskKind, {
28
+ version: string;
29
+ repeat: number;
30
+ phases: TaskPhaseDef[];
31
+ }>;
32
+ /** The short task's version and phases, which is what plain `bench --task` records. */
33
+ export declare const TASK_VERSION: string;
34
+ export declare const TASK_PHASES: TaskPhaseDef[];
35
+ /** Milliseconds per phase, by phase id. */
36
+ export type PhaseMs = Record<string, number>;
37
+ /** The task a report's `task` version names, if it's one this release knows. */
38
+ export declare function taskByVersion(version: unknown): (typeof TASKS)[TaskKind] | undefined;
39
+ /** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
40
+ export declare function phaseCommand(cmd: string, repeat: number): string;
41
+ /** What one run of a task measured: milliseconds per phase, and the CPU time it used across all vCPUs, if the sandbox shows it. */
42
+ export interface TaskRun {
43
+ ms: PhaseMs;
44
+ cpuMs?: number;
45
+ }
46
+ /** Busy CPU milliseconds between two /proc/stat "cpu" lines: user, nice, system, irq and softirq (not idle, iowait or steal), at 100 ticks a second. */
47
+ export declare function busyMs(before: string, after: string): number | undefined;
48
+ /** Runs a standard task in `box`: milliseconds per phase (network round trip taken out) and CPU time used. Throws if a phase fails. */
49
+ export declare function runTask(box: Pick<ProviderSandbox, "exec">, kind?: TaskKind): Promise<TaskRun>;
50
+ /** The whole task's time: the phases added up. */
51
+ export declare const taskMs: (phases: PhaseMs) => number;
52
+ /**
53
+ * What one task would be billed, USD, on a sandbox of `size`. It's billed from create until the task is
54
+ * done: the start time plus the task, rounded up to the provider's minimum charge and billing increment,
55
+ * plus its per-sandbox charge.
56
+ *
57
+ * Providers that bill CPU only while busy are charged for the CPU time the task really used (`cpuMillis`,
58
+ * at least their CPU floor) plus their memory for the whole time; their minimum charge covers memory only
59
+ * where that's how they bill (Vercel). Without `cpuMillis` they're charged as if every core was busy.
60
+ * `billedVsList` scales the price by what the provider was measured to really bill.
61
+ */
62
+ export declare function taskUsd(provider: ProviderId, size: {
63
+ vcpu: number;
64
+ memoryGb: number;
65
+ }, createMs: number, taskMillis: number, cpuMillis?: number, billedVsList?: number): number;
package/dist/task.js ADDED
@@ -0,0 +1,118 @@
1
+ import { billingRules, cpuHourlyAtFull, hourlyCost, info } from "./catalog.js";
2
+ const HASH_DISK = [
3
+ // One core: hash 512 MB of zeros.
4
+ { id: "cpu", label: "1 core", cmd: "head -c 536870912 /dev/zero | sha256sum > /dev/null" },
5
+ // Two cores at once (bench asks for 2 vCPU), 256 MB each: shows whether the second vCPU is real.
6
+ { id: "cores", label: "2 cores", cmd: "for i in 1 2; do (head -c 268435456 /dev/zero | sha256sum > /dev/null) & done; wait" },
7
+ // Write 256 MB and flush it to disk, then delete it.
8
+ { id: "disk", label: "disk", cmd: "dd if=/dev/zero of=/tmp/sr-task bs=1048576 count=256 conv=fsync 2> /dev/null; rm -f /tmp/sr-task" },
9
+ ];
10
+ // 200,000 small records through JSON, a regex and a sort: the kind of thing a code-interpreter call does.
11
+ const PYTHON = [
12
+ "import json, random, re",
13
+ "random.seed(1)",
14
+ "rows = [{'id': i, 'name': ''.join(random.choice('abcdefghij') for _ in range(16)), 'v': random.random()} for i in range(200000)]",
15
+ "back = json.loads(json.dumps(rows))",
16
+ "hits = sum(1 for r in back if re.search('abc', r['name']))",
17
+ "top = sorted(back, key=lambda r: (r['name'], r['v']))[:10]",
18
+ "print(hits, top[0]['id'])",
19
+ ].join("\n");
20
+ // The Node.js 22.11.0 Linux release (53 MB), from nodejs.org's CDN: a real download, like installing a toolchain.
21
+ const DOWNLOAD_URL = "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-x64.tar.gz";
22
+ const PY_FETCH = `import shutil, urllib.request; shutil.copyfileobj(urllib.request.urlopen('${DOWNLOAD_URL}'), open('/dev/null', 'wb'))`;
23
+ export const TASKS = {
24
+ short: { version: "v1", repeat: 1, phases: HASH_DISK },
25
+ long: { version: "v1-long", repeat: 40, phases: HASH_DISK },
26
+ python: { version: "python-v1", repeat: 1, phases: [{ id: "python", label: "Python", cmd: `python3 -c "${PYTHON}"` }] },
27
+ download: {
28
+ version: "download-v1",
29
+ repeat: 1,
30
+ phases: [
31
+ {
32
+ id: "download",
33
+ label: "53 MB download",
34
+ cmd: `if command -v curl > /dev/null; then curl -sSfL -o /dev/null '${DOWNLOAD_URL}'; ` +
35
+ `elif command -v wget > /dev/null; then wget -q -O /dev/null '${DOWNLOAD_URL}'; ` +
36
+ `else python3 -c "${PY_FETCH}"; fi`,
37
+ },
38
+ ],
39
+ },
40
+ };
41
+ /** The short task's version and phases, which is what plain `bench --task` records. */
42
+ export const TASK_VERSION = TASKS.short.version;
43
+ export const TASK_PHASES = TASKS.short.phases;
44
+ /** The task a report's `task` version names, if it's one this release knows. */
45
+ export function taskByVersion(version) {
46
+ return Object.values(TASKS).find((t) => t.version === version);
47
+ }
48
+ /** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
49
+ export function phaseCommand(cmd, repeat) {
50
+ return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do ${cmd}; n=$((n+1)); done`;
51
+ }
52
+ // Wraps a phase to read /proc/stat's total CPU line before and after it, so the run also reports the CPU
53
+ // time it really used: what providers that bill active CPU charge for.
54
+ const MARK = "SRCPU";
55
+ const withCpu = (cmd) => `a=$(head -n 1 /proc/stat 2> /dev/null); ${cmd}; rc=$?; b=$(head -n 1 /proc/stat 2> /dev/null); echo "${MARK}|$a|$b"; exit $rc`;
56
+ /** Busy CPU milliseconds between two /proc/stat "cpu" lines: user, nice, system, irq and softirq (not idle, iowait or steal), at 100 ticks a second. */
57
+ export function busyMs(before, after) {
58
+ const ticks = (line) => {
59
+ const f = line.trim().split(/\s+/);
60
+ if (f[0] !== "cpu" || f.length < 8)
61
+ return undefined;
62
+ const n = f.slice(1).map(Number);
63
+ return n[0] + n[1] + n[2] + n[5] + n[6];
64
+ };
65
+ const a = ticks(before);
66
+ const b = ticks(after);
67
+ return a === undefined || b === undefined || !(b >= a) ? undefined : (b - a) * 10;
68
+ }
69
+ /** Runs a standard task in `box`: milliseconds per phase (network round trip taken out) and CPU time used. Throws if a phase fails. */
70
+ export async function runTask(box, kind = "short") {
71
+ const { repeat, phases } = TASKS[kind];
72
+ const rtt = [];
73
+ for (let i = 0; i < 3; i++) {
74
+ const t = performance.now();
75
+ await box.exec("true");
76
+ rtt.push(performance.now() - t);
77
+ }
78
+ const overhead = rtt.sort((a, b) => a - b)[1];
79
+ const out = {};
80
+ let cpuMs = 0;
81
+ for (const p of phases) {
82
+ const t = performance.now();
83
+ const r = await box.exec(withCpu(phaseCommand(p.cmd, repeat)), { timeoutSeconds: repeat > 1 ? 900 : 300 });
84
+ if (r.exitCode !== 0)
85
+ throw new Error(`task phase ${p.id} exited ${r.exitCode}: ${(r.stderr || r.stdout).slice(0, 120)}`);
86
+ out[p.id] = Math.max(1, Math.round(performance.now() - t - overhead));
87
+ const line = r.stdout.split("\n").find((l) => l.startsWith(`${MARK}|`));
88
+ const used = line ? busyMs(line.split("|")[1] ?? "", line.split("|")[2] ?? "") : undefined;
89
+ cpuMs = cpuMs === undefined || used === undefined ? undefined : cpuMs + used;
90
+ }
91
+ return { ms: out, ...(cpuMs !== undefined ? { cpuMs } : {}) };
92
+ }
93
+ /** The whole task's time: the phases added up. */
94
+ export const taskMs = (phases) => Object.values(phases).reduce((s, ms) => s + ms, 0);
95
+ /**
96
+ * What one task would be billed, USD, on a sandbox of `size`. It's billed from create until the task is
97
+ * done: the start time plus the task, rounded up to the provider's minimum charge and billing increment,
98
+ * plus its per-sandbox charge.
99
+ *
100
+ * Providers that bill CPU only while busy are charged for the CPU time the task really used (`cpuMillis`,
101
+ * at least their CPU floor) plus their memory for the whole time; their minimum charge covers memory only
102
+ * where that's how they bill (Vercel). Without `cpuMillis` they're charged as if every core was busy.
103
+ * `billedVsList` scales the price by what the provider was measured to really bill.
104
+ */
105
+ export function taskUsd(provider, size, createMs, taskMillis, cpuMillis, billedVsList = 1) {
106
+ const { minSeconds, incrementSeconds, perSandboxUsd } = billingRules(provider);
107
+ const seconds = (createMs + taskMillis) / 1000;
108
+ const billed = Math.max(minSeconds, Math.ceil(seconds / incrementSeconds - 1e-9) * incrementSeconds);
109
+ const full = hourlyCost(provider, size);
110
+ const cpuFull = cpuHourlyAtFull(provider, size);
111
+ if (cpuFull === 0 || cpuMillis === undefined)
112
+ return (billedVsList * full * billed) / 3600 + perSandboxUsd;
113
+ const { vcpuHour, cpuFloor = 0 } = info(provider).pricing;
114
+ const vcpus = cpuFull / vcpuHour;
115
+ const cpuSeconds = Math.max(cpuMillis / 1000, cpuFloor * vcpus * seconds);
116
+ // Memory (and anything else that isn't CPU) is billed for the whole time, minimum included.
117
+ return (billedVsList * ((full - cpuFull) * billed + vcpuHour * cpuSeconds)) / 3600 + perSandboxUsd;
118
+ }
package/dist/types.d.ts CHANGED
@@ -26,6 +26,13 @@ export interface SandboxSpec {
26
26
  * cheaper per hour but charges a full minute.
27
27
  */
28
28
  expectedSeconds?: number;
29
+ /**
30
+ * How busy the CPU will be, 0 to 1 (default 1). Only a pricing hint: providers that bill CPU only
31
+ * while it's busy (Vercel, Cloudflare, Tensorlake, AgentCore, Sail, Sprites, Deno, Upstash) are priced
32
+ * at this share of their CPU plus their full memory, never below a provider's CPU floor. An agent that
33
+ * mostly waits on model calls uses about 0.1; a build or test run is close to 1.
34
+ */
35
+ cpuUtilization?: number;
29
36
  /**
30
37
  * Provider-specific image/template, keyed by provider, e.g.
31
38
  * { maritime: "python", e2b: "code-interpreter-v1", modal: "python:3.13-slim" }.
@@ -41,7 +48,9 @@ export interface SandboxSpec {
41
48
  * whose last real-account check failed (`FAILING`) go last.
42
49
  * "verified": providers that passed the real-account check first (`VERIFIED`), then the rest; cheapest
43
50
  * list price first within each.
44
- * "cheapest": lowest list price for the spec, tested or not, ties alphabetical.
51
+ * "cheapest": lowest cost for the run (priced as in "balanced": minimum charge, billing increment and
52
+ * per-sandbox charge over `expectedSeconds`), strictly by price: no speed tie-break, and providers whose
53
+ * last check failed aren't moved last. Ties alphabetical.
45
54
  * "fastest": lowest median create time (this router's own, else your `bench` file), then cheapest.
46
55
  */
47
56
  export type Strategy = "default" | "balanced" | "verified" | "cheapest" | "fastest";
@@ -69,6 +78,13 @@ export interface RouteOptions {
69
78
  createTimeoutSeconds?: number;
70
79
  /** Capabilities every candidate must have. */
71
80
  require?: Capability[];
81
+ /**
82
+ * The most this sandbox may cost, in USD per hour. A provider is skipped when this run would cost more
83
+ * there, priced the way ranking prices it: hourly price, minimum charge and billing increment over
84
+ * `expectedSeconds` (else `timeoutMinutes`, default 30), plus any per-sandbox charge, divided by the
85
+ * run's hours. Omit for no cap.
86
+ */
87
+ maxHourlyUsd?: number;
72
88
  }
73
89
  export interface ExecOptions {
74
90
  cwd?: string;
@@ -1,8 +1,8 @@
1
1
  import { type RouteOptions, type SandboxSpec, type Strategy } from "./types.js";
2
2
  /** Every key a SandboxSpec can have. Anything else in a request is a mistake (e.g. "memory" for "memoryGb"). */
3
- export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "image", "metadata"];
3
+ export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "cpuUtilization", "image", "metadata"];
4
4
  /** Every key RouteOptions can have. */
5
- export declare const ROUTE_KEYS: readonly ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds"];
5
+ export declare const ROUTE_KEYS: readonly ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"];
6
6
  export declare const STRATEGIES: readonly Strategy[];
7
7
  /**
8
8
  * Throws RouterError("bad_request") for a spec or route a provider couldn't make sense of: sizes and