@sandboxrouter/sdk 0.8.2 → 0.9.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.
package/README.md CHANGED
@@ -30,7 +30,7 @@ Site and docs: [sandboxrouter.ai](https://sandboxrouter.ai) · npm: [`@sandboxro
30
30
  AI agents need a disposable computer to run code a model wrote: install packages, run tests, do an RL rollout. Dozens of providers sell one, each with its own SDK and auth, and the same 2 vCPU / 4 GB sandbox costs from under a cent to over thirty cents an hour. sandboxRouter is one interface over all of them:
31
31
 
32
32
  - **Same code everywhere.** `create`, `exec` (streamed), `writeFile`, `readFile`, `pause`, `kill`. Switch providers by changing which keys are set.
33
- - **Cheapest real cost, then speed, with fallback.** Or `cheapest` for list price alone, `fastest` by start times, `verified` for tested providers first, or a list of providers you name. `requireVerified` limits a router to providers that passed the real-account check.
33
+ - **Cheapest real cost, then speed, with fallback.** A `maxHourlyUsd` price cap and `quote()` to see where a sandbox would land and what the run costs before starting it. Or `cheapest` for strictly lowest cost for the run, `fastest` by start times, `verified` for tested providers first, or a list of providers you name. `requireVerified` limits a router to providers that passed the real-account check.
34
34
  - **Errors you can act on.** Every failure has a `code` (`no_provider`, `setup`, `all_failed`, `timeout`, ...), an HTTP status, and the list of providers tried.
35
35
  - **Your keys.** Your accounts and your bills; nothing is proxied through anyone else.
36
36
  - **Cleanup.** A local ledger of every sandbox started, so `sandboxrouter gc` kills what a crashed script left behind.
package/dist/bench.d.ts CHANGED
@@ -11,7 +11,9 @@ export interface BenchRow {
11
11
  }
12
12
  /**
13
13
  * Cold start = time from create() call to a usable sandbox. Exec = round trip of `echo ok`.
14
- * Measured from wherever you run it, so network distance to each provider counts.
14
+ * Measured from wherever you run it, so network distance to each provider counts. Every provider is
15
+ * asked for the same size (2 vCPU / 4 GB unless `spec` says otherwise), except ones whose default
16
+ * image fixes the size, which run at that size.
15
17
  */
16
18
  export declare function bench(opts: {
17
19
  router?: Router;
package/dist/bench.js CHANGED
@@ -1,14 +1,18 @@
1
- import { CATALOG, fixedSize, hourlyCost } from "./catalog.js";
1
+ import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost } from "./catalog.js";
2
2
  import { loadBench, median, saveBench } from "./bench-store.js";
3
3
  import { Router } from "./router.js";
4
4
  /**
5
5
  * Cold start = time from create() call to a usable sandbox. Exec = round trip of `echo ok`.
6
- * Measured from wherever you run it, so network distance to each provider counts.
6
+ * Measured from wherever you run it, so network distance to each provider counts. Every provider is
7
+ * asked for the same size (2 vCPU / 4 GB unless `spec` says otherwise), except ones whose default
8
+ * image fixes the size, which run at that size.
7
9
  */
8
10
  export async function bench(opts) {
9
11
  const router = opts.router ?? new Router();
10
12
  const runs = opts.runs ?? 3;
11
- const spec = opts.spec ?? { timeoutMinutes: 5 };
13
+ // The CLI passes unset flags as undefined: drop them so they don't wipe the defaults.
14
+ const given = Object.fromEntries(Object.entries(opts.spec ?? {}).filter(([, v]) => v !== undefined));
15
+ const spec = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: 5, ...given };
12
16
  const ids = opts.providers ?? router.registered().filter((id) => router.isConfigured(id));
13
17
  const log = opts.onProgress ?? (() => { });
14
18
  const stored = loadBench(opts.benchFile);
@@ -23,7 +27,7 @@ export async function bench(opts) {
23
27
  let box;
24
28
  try {
25
29
  const t0 = performance.now();
26
- box = await router.create({ ...fixedSize(id), ...spec }, { provider: id, fallback: false });
30
+ box = await router.create(sized(id, spec), { provider: id, fallback: false });
27
31
  createMs.push(Math.round(performance.now() - t0));
28
32
  const t1 = performance.now();
29
33
  const r = await box.exec("echo ok");
@@ -46,13 +50,17 @@ export async function bench(opts) {
46
50
  failures,
47
51
  medianCreateMs: median(createMs),
48
52
  medianExecMs: median(execMs),
49
- hourlyUsd: hourlyCost(id, { ...fixedSize(id), ...spec }),
53
+ hourlyUsd: hourlyCost(id, sized(id, spec)),
50
54
  lastError,
51
55
  });
52
56
  }
53
57
  saveBench(stored, opts.benchFile);
54
58
  return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
55
59
  }
60
+ /** The spec a provider is benched at: the asked size, or its fixed default size if its image has one. */
61
+ function sized(id, spec) {
62
+ return { ...spec, ...fixedSize(id, spec) };
63
+ }
56
64
  export function benchMarkdown(rows) {
57
65
  const name = (id) => CATALOG.find((c) => c.id === id).name;
58
66
  const ms = (n) => (n === undefined ? "n/a" : `${n} ms`);
package/dist/cli.js CHANGED
@@ -17,6 +17,7 @@ const HELP = `sandboxrouter: one API for every sandbox provider
17
17
  Usage:
18
18
  sandboxrouter providers [--vcpu N] [--memory GB] price table + which keys are set
19
19
  sandboxrouter route [spec flags] [route flags] dry run: the order providers would be tried
20
+ sandboxrouter quote [spec/route flags] [--json] where a create would land and what the run would cost
20
21
  sandboxrouter run "<cmd>" [spec flags] [route flags] [--keep]
21
22
  sandboxrouter check --provider ID[,ID] | --all [--json] [--save [dir]] [--retry] [--out FILE] [--by GITHUB_USER]
22
23
  test providers for real: exec, env, UTF-8, streaming, files, timeout, pause,
@@ -42,6 +43,7 @@ Usage:
42
43
 
43
44
  Spec flags: --vcpu N --memory GB --gpu T4 --timeout MIN --expect SEC (how long you'll use it; ranks by the real bill)
44
45
  Route flags: --provider e2b[,modal,...] --strategy balanced|verified|cheapest|fastest (default balanced: cheapest real cost, speed breaks near-ties)
46
+ --max-price USD (per hour, for this run: skip providers that would cost more)
45
47
  --no-fallback --fallback-any (also on setup errors like a bad key)
46
48
  --create-timeout SEC (per provider, default 120) --require gpu,custom-image
47
49
 
@@ -57,6 +59,7 @@ const { values, positionals } = parseArgs({
57
59
  expect: { type: "string" },
58
60
  provider: { type: "string" },
59
61
  strategy: { type: "string" },
62
+ "max-price": { type: "string" },
60
63
  "no-fallback": { type: "boolean" },
61
64
  "fallback-any": { type: "boolean" },
62
65
  "create-timeout": { type: "string" },
@@ -115,6 +118,7 @@ const route = {
115
118
  fallback: values["no-fallback"] ? false : values["fallback-any"] ? "any" : undefined,
116
119
  createTimeoutSeconds: num(values["create-timeout"]),
117
120
  require: list(values.require),
121
+ maxHourlyUsd: num(values["max-price"]),
118
122
  };
119
123
  async function main() {
120
124
  const [cmd, ...rest] = positionals;
@@ -154,6 +158,23 @@ async function main() {
154
158
  ].join("\n"));
155
159
  return;
156
160
  }
161
+ if (cmd === "quote") {
162
+ const q = router.quote(spec, route);
163
+ if (values.json)
164
+ return console.log(JSON.stringify({ ...q, candidates: undefined }, null, 2));
165
+ const rules = [
166
+ q.minimumSeconds ? `at least ${q.minimumSeconds} s billed` : "",
167
+ q.billedInSecondsOf ? `billed in steps of ${q.billedInSecondsOf} s` : "",
168
+ q.perSandboxUsd ? `$${q.perSandboxUsd} per sandbox` : "",
169
+ ].filter(Boolean);
170
+ console.log(`${q.provider}, ${q.size.vcpu} vCPU / ${q.size.memoryGb} GB`);
171
+ console.log(`price $${q.hourlyUsd.toFixed(4)}/hr${rules.length ? ` (${rules.join(", ")})` : ""}`);
172
+ console.log(`this run ${q.runSeconds} s ≈ $${q.estimatedUsd.toFixed(6)} ($${q.runHourlyUsd.toFixed(4)}/hr)`);
173
+ const next = q.candidates.filter((c) => !c.skip && c.provider !== q.provider).slice(0, 3).map((c) => c.provider);
174
+ if (next.length)
175
+ console.log(`fallback ${next.join(" → ")}`);
176
+ return;
177
+ }
157
178
  if (cmd === "route") {
158
179
  const plan = router.plan(spec, route);
159
180
  if (values.json)
@@ -309,7 +330,7 @@ async function main() {
309
330
  console.error(`\n${r.provider} last error: ${r.lastError}`);
310
331
  if (values.share) {
311
332
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
312
- const report = makeReport(rows, { version, runs: rows[0].runs, spec, label: values.label, by });
333
+ const report = makeReport(rows, { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by });
313
334
  const left = rows.filter((r) => !benchmarksPublishable(r.provider)).map((r) => r.provider);
314
335
  if (left.length)
315
336
  console.log(`\nleft out of the shared report: ${left.join(", ")} (their terms don't allow publishing benchmarks)`);
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Candidate, Size } from "./router.js";
1
+ import type { Candidate, Quote, Size } from "./router.js";
2
2
  import type { Attempt, ExecOptions, ExecResult, RouteOptions, RouterErrorCode, SandboxSpec } from "./types.js";
3
3
  /**
4
4
  * Client for the sandboxrouter HTTP API: the hosted service (one key, prepaid credits) or your own
@@ -31,6 +31,8 @@ export declare class Client {
31
31
  }[]>;
32
32
  /** Dry run: which providers would be tried, in order, each with its price, size and any reason it's skipped. */
33
33
  route(spec?: SandboxSpec, route?: RouteOptions): Promise<Candidate[]>;
34
+ /** Where a create would land and what the run would cost, without starting anything (a hosted service includes its fee). */
35
+ quote(spec?: SandboxSpec, route?: RouteOptions): Promise<Quote>;
34
36
  /**
35
37
  * Start a sandbox on the first provider that works, as the server routes it. With `idempotencyKey`,
36
38
  * sending the same create again (say, after a timeout) returns the same sandbox instead of starting
package/dist/client.js CHANGED
@@ -51,6 +51,10 @@ export class Client {
51
51
  async route(spec = {}, route = {}) {
52
52
  return (await this.json("POST", "/v1/route", { ...spec, ...route })).candidates;
53
53
  }
54
+ /** Where a create would land and what the run would cost, without starting anything (a hosted service includes its fee). */
55
+ async quote(spec = {}, route = {}) {
56
+ return this.json("POST", "/v1/quote", { ...spec, ...route });
57
+ }
54
58
  /**
55
59
  * Start a sandbox on the first provider that works, as the server routes it. With `idempotencyKey`,
56
60
  * sending the same create again (say, after a timeout) returns the same sandbox instead of starting
package/dist/index.d.ts CHANGED
@@ -2,8 +2,9 @@ export { checkProvider, CHECK_STEPS, type CheckReport, type CheckResult, type Ch
2
2
  export { Ledger, defaultLedgerFile, type LedgerEntry } from "./ledger.js";
3
3
  export { conformanceTable, loadConformance, type ConformanceRow, type SavedCheck } from "./conformance.js";
4
4
  export { gc, listOpen, isGone, type GcResult, type OpenSandbox } from "./gc.js";
5
- export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, type Candidate, type RouterOptions, type SandboxPrice, type Size, } from "./router.js";
5
+ export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, rankUsd, runHours, usdPerHour, type Candidate, type Quote, type RouterOptions, type SandboxPrice, type Size, } from "./router.js";
6
6
  export { VERIFIED, FAILING } from "./verified.js";
7
+ export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
7
8
  export { BILLED_VS_LIST } from "./billing.js";
8
9
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
9
10
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd, type ProviderInfo } from "./catalog.js";
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@ export { checkProvider, CHECK_STEPS } from "./check.js";
2
2
  export { Ledger, defaultLedgerFile } from "./ledger.js";
3
3
  export { conformanceTable, loadConformance } from "./conformance.js";
4
4
  export { gc, listOpen, isGone } from "./gc.js";
5
- export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, } from "./router.js";
5
+ export { Router, RoutedSandbox, defaultProviders, defaultComputerProviders, parseId, balanced, sizeOf, PRICE_TIE, DEFAULT_CREATE_TIMEOUT_S, DEFAULT_CREATE_DEADLINE_S, rankUsd, runHours, usdPerHour, } from "./router.js";
6
6
  export { VERIFIED, FAILING } from "./verified.js";
7
+ export { KEYED_PROVIDERS, providerWithKey } from "./keyed.js";
7
8
  export { BILLED_VS_LIST } from "./billing.js";
8
9
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
9
10
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd } from "./catalog.js";
@@ -0,0 +1,5 @@
1
+ import type { Provider, ProviderId } from "./types.js";
2
+ /** Ids `providerWithKey` takes. */
3
+ export declare const KEYED_PROVIDERS: ProviderId[];
4
+ /** An adapter for `id` that uses `key` and no key from the environment. Throws for other providers or an empty key. */
5
+ export declare function providerWithKey(id: ProviderId, key: string): Provider;
package/dist/keyed.js ADDED
@@ -0,0 +1,44 @@
1
+ import { Agent37Provider } from "./providers/agent37.js";
2
+ import { BoatProvider } from "./providers/boat.js";
3
+ import { DaytonaProvider } from "./providers/daytona.js";
4
+ import { E2BProvider } from "./providers/e2b.js";
5
+ import { FreestyleProvider } from "./providers/freestyle.js";
6
+ import { MaritimeProvider } from "./providers/maritime.js";
7
+ import { NovitaProvider } from "./providers/novita.js";
8
+ import { OpenScaleProvider } from "./providers/openscale.js";
9
+ import { SailProvider } from "./providers/sail.js";
10
+ import { SpritesProvider } from "./providers/sprites.js";
11
+ import { SuperserveProvider } from "./providers/superserve.js";
12
+ import { TensorlakeProvider } from "./providers/tensorlake.js";
13
+ /**
14
+ * Providers whose adapter takes a single API key and sends only that key: given one here, nothing it
15
+ * does reads a key from this process's environment. A service running sandboxes on its own accounts can
16
+ * let a user bring their own key for these without ever charging the service's account for that user's
17
+ * sandboxes (test/keyed.test.ts checks every request carries the key given). Base URLs still come from
18
+ * the environment, as the operator set them; a user can't point the service at another host.
19
+ */
20
+ const KEYED = {
21
+ agent37: (k) => new Agent37Provider(k),
22
+ boat: (k) => new BoatProvider(k),
23
+ daytona: (k) => new DaytonaProvider(k),
24
+ e2b: (k) => new E2BProvider(k),
25
+ freestyle: (k) => new FreestyleProvider(k),
26
+ maritime: (k) => new MaritimeProvider(k),
27
+ novita: (k) => new NovitaProvider(k),
28
+ openscale: (k) => new OpenScaleProvider(k),
29
+ sail: (k) => new SailProvider(k),
30
+ sprites: (k) => new SpritesProvider(k),
31
+ superserve: (k) => new SuperserveProvider(k),
32
+ tensorlake: (k) => new TensorlakeProvider(k),
33
+ };
34
+ /** Ids `providerWithKey` takes. */
35
+ export const KEYED_PROVIDERS = Object.keys(KEYED);
36
+ /** An adapter for `id` that uses `key` and no key from the environment. Throws for other providers or an empty key. */
37
+ export function providerWithKey(id, key) {
38
+ const make = KEYED[id];
39
+ if (!make)
40
+ throw new Error(`${id} can't take a key this way; it takes: ${KEYED_PROVIDERS.join(", ")}`);
41
+ if (typeof key !== "string" || !key.trim())
42
+ throw new Error(`the ${id} key is empty`);
43
+ return make(key.trim());
44
+ }
@@ -41,8 +41,13 @@ export interface LeaderRow {
41
41
  vcpu: number;
42
42
  memoryGb: number;
43
43
  };
44
+ /** Date (ISO) of the newest run behind this row. */
45
+ measuredAt: string;
44
46
  }
45
- /** Median of each submission's medians, so one heavy submitter can't skew a provider. */
47
+ /**
48
+ * Each provider's latest run from each location (report label), then the median across locations, so
49
+ * an old run can't outvote a newer one and one heavy submitter can't skew a provider.
50
+ */
46
51
  export declare function aggregate(reports: BenchReport[]): LeaderRow[];
47
52
  /** One self-contained HTML page: a sorted table with an inline bar per measure, each on its own scale. */
48
53
  export declare function renderLeaderboard(reports: BenchReport[]): string;
@@ -40,14 +40,27 @@ export function loadReports(dir) {
40
40
  return out;
41
41
  }
42
42
  const KNOWN = new Set(CATALOG.map((c) => c.id));
43
- /** Median of each submission's medians, so one heavy submitter can't skew a provider. */
43
+ /**
44
+ * Each provider's latest run from each location (report label), then the median across locations, so
45
+ * an old run can't outvote a newer one and one heavy submitter can't skew a provider.
46
+ */
44
47
  export function aggregate(reports) {
48
+ const latest = new Map();
49
+ for (const rep of reports) {
50
+ for (const r of rep.rows) {
51
+ if (!KNOWN.has(r.provider))
52
+ continue;
53
+ const key = `${r.provider}\u0000${rep.label ?? ""}`;
54
+ const seen = latest.get(key);
55
+ if (!seen || rep.date > seen.date)
56
+ latest.set(key, { row: r, date: rep.date });
57
+ }
58
+ }
45
59
  const by = new Map();
46
- for (const rep of reports)
47
- for (const r of rep.rows)
48
- if (KNOWN.has(r.provider))
49
- by.set(r.provider, [...(by.get(r.provider) ?? []), r]);
50
- const rows = [...by.entries()].map(([id, rs]) => {
60
+ for (const x of latest.values())
61
+ by.set(x.row.provider, [...(by.get(x.row.provider) ?? []), x]);
62
+ const rows = [...by.entries()].map(([id, xs]) => {
63
+ const rs = xs.map((x) => x.row);
51
64
  const runs = rs.reduce((n, r) => n + r.runs, 0);
52
65
  const ok = rs.reduce((n, r) => n + (r.runs - r.failures), 0);
53
66
  return {
@@ -59,6 +72,7 @@ export function aggregate(reports) {
59
72
  successRate: runs ? ok / runs : 0,
60
73
  hourlyUsd: hourlyCost(id, fittingSpec(id)),
61
74
  size: fittingSpec(id),
75
+ measuredAt: xs.map((x) => x.date).sort().at(-1),
62
76
  };
63
77
  });
64
78
  return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
@@ -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/router.d.ts CHANGED
@@ -37,6 +37,33 @@ export interface Candidate {
37
37
  /** Why this provider won't be tried, if it won't. */
38
38
  skip?: string;
39
39
  }
40
+ /** What `router.quote()` answers: the provider a create would start on first, and what the run would cost there. */
41
+ export interface Quote {
42
+ provider: ProviderId;
43
+ size: {
44
+ vcpu: number;
45
+ memoryGb: number;
46
+ };
47
+ /** The provider's price per hour for this size: list price, corrected by what it really bills where measured. */
48
+ hourlyUsd: number;
49
+ listHourlyUsd: number;
50
+ /** The run the estimate is for: `expectedSeconds`, else `timeoutMinutes` (default 30). */
51
+ runSeconds: number;
52
+ /** What the run costs per hour once minimum charge, billing increment and per-sandbox charge are counted. */
53
+ runHourlyUsd: number;
54
+ /** What the run costs in all. */
55
+ estimatedUsd: number;
56
+ /** The provider bills at least this many seconds per sandbox. */
57
+ minimumSeconds?: number;
58
+ /** The provider bills in whole steps of this many seconds. */
59
+ billedInSecondsOf?: number;
60
+ /** A fixed charge per sandbox started, included in `estimatedUsd`. */
61
+ perSandboxUsd?: number;
62
+ /** The whole plan: every provider, in the order a create would try them, with why any are skipped. */
63
+ candidates: Candidate[];
64
+ }
65
+ /** "$0.0123/h": enough digits to tell cheap providers apart. */
66
+ export declare const usdPerHour: (n: number) => string;
40
67
  /** Providers within this share of the cheapest remaining price count as a tie, broken by speed. */
41
68
  export declare const PRICE_TIE = 0.1;
42
69
  export interface RouterOptions {
@@ -80,6 +107,15 @@ export interface RouterOptions {
80
107
  factor?: number;
81
108
  minSeconds?: number;
82
109
  };
110
+ /**
111
+ * What a provider's 401 or 403 (or a missing provider package) does to a create. "stop" (default):
112
+ * the create fails, because with your own keys that is a key or setup you need to fix, and moving the
113
+ * work elsewhere would hide it. "fallback": try the next provider. For services that run sandboxes on
114
+ * their own accounts, where a revoked key, a frozen workspace or a provider's creation cap is the
115
+ * service's problem, not the caller's. 400, 404 and 422 still stop: those are usually the request.
116
+ * Either way the failed try is in `attempts`.
117
+ */
118
+ accountErrors?: "stop" | "fallback";
83
119
  }
84
120
  /** Desktop-only providers. Filled in as adapters are added. */
85
121
  export declare function defaultComputerProviders(): ComputerProvider[];
@@ -95,6 +131,7 @@ export declare class Router {
95
131
  private readonly live;
96
132
  private computerOnly;
97
133
  private readonly quick;
134
+ private readonly accountErrors;
98
135
  /** The local record of sandboxes this router created, or undefined when turned off. */
99
136
  readonly ledger?: Ledger;
100
137
  constructor(opts?: RouterOptions);
@@ -110,6 +147,11 @@ export declare class Router {
110
147
  * providers they do have keys for were skipped.
111
148
  */
112
149
  private whyNone;
150
+ /**
151
+ * Where a create would land and what the run would cost there, without starting anything. Throws
152
+ * RouterError("no_provider") when nothing can take it, with the same reason create would give.
153
+ */
154
+ quote(spec?: SandboxSpec, route?: RouteOptions): Quote;
113
155
  /** Start a sandbox on the best available provider, falling back down the list on failure. */
114
156
  create(spec?: SandboxSpec, route?: RouteOptions): Promise<RoutedSandbox>;
115
157
  /**
package/dist/router.js CHANGED
@@ -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. */
@@ -104,6 +108,7 @@ export class Router {
104
108
  live = new Map();
105
109
  computerOnly;
106
110
  quick;
111
+ accountErrors;
107
112
  /** The local record of sandboxes this router created, or undefined when turned off. */
108
113
  ledger;
109
114
  constructor(opts = {}) {
@@ -119,6 +124,7 @@ export class Router {
119
124
  opts.billedVsList ?? Object.fromEntries(Object.entries(BILLED_VS_LIST).map(([id, b]) => [id, b.ratio]));
120
125
  this.computerOnly = opts.computers ?? (opts.providers ? [] : defaultComputerProviders());
121
126
  this.quick = opts.quickFallback === false ? false : { factor: 5, minSeconds: 10, ...opts.quickFallback };
127
+ this.accountErrors = opts.accountErrors ?? "stop";
122
128
  }
123
129
  /** Registered and has credentials. False for providers this router doesn't know. */
124
130
  isConfigured(id) {
@@ -175,6 +181,11 @@ export class Router {
175
181
  (p.configured() ? undefined : gated ? `not configured; ${gated}` : "not configured") ??
176
182
  (this.requireVerified && !c.verified ? "not tested (this router only uses providers that passed the real-account check)" : undefined);
177
183
  }
184
+ if (!c.skip && route.maxHourlyUsd !== undefined) {
185
+ const rate = rankUsd(c, runHours(spec));
186
+ if (rate > route.maxHourlyUsd)
187
+ c.skip = `${OVER_CAP}: ${usdPerHour(rate)} for this run, cap ${usdPerHour(route.maxHourlyUsd)}`;
188
+ }
178
189
  return c;
179
190
  });
180
191
  // Neutral by construction: the same rule for every provider, ties alphabetical by id. Nothing here
@@ -183,12 +194,11 @@ export class Router {
183
194
  if (!explicit) {
184
195
  const hours = runHours(spec);
185
196
  const byCost = (a, b) => rankUsd(a, hours) - rankUsd(b, hours) || a.provider.localeCompare(b.provider);
186
- const byList = (a, b) => a.listHourlyUsd - b.listHourlyUsd || a.provider.localeCompare(b.provider);
187
197
  if (strategy === "fastest") {
188
198
  list.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity) || byCost(a, b));
189
199
  }
190
200
  else if (strategy === "cheapest") {
191
- list.sort(byList);
201
+ list.sort(byCost);
192
202
  }
193
203
  else if (strategy === "verified") {
194
204
  list.sort((a, b) => Number(b.verified) - Number(a.verified) || byCost(a, b));
@@ -203,7 +213,7 @@ export class Router {
203
213
  * Why a create has nowhere to go, leading with what the caller can fix: no keys at all, or why the
204
214
  * providers they do have keys for were skipped.
205
215
  */
206
- whyNone(plan, explicit) {
216
+ whyNone(plan, explicit, spec = {}) {
207
217
  if (plan.length === 0)
208
218
  return "no provider can take this sandbox: none registered";
209
219
  // Providers the caller named: say what each one needs.
@@ -218,6 +228,13 @@ export class Router {
218
228
  if (keyed.length === 0)
219
229
  return ("no provider keys found: set the API key for at least one provider (the README's Env table lists each provider's variables); " +
220
230
  "`npx @sandboxrouter/sdk providers` shows which are set");
231
+ const over = keyed.filter((c) => c.skip?.startsWith(OVER_CAP));
232
+ if (over.length && over.length === keyed.length) {
233
+ const hours = runHours(spec);
234
+ const best = over.sort((a, b) => rankUsd(a, hours) - rankUsd(b, hours))[0];
235
+ // The skip's own words, so a service that prices the cap its own way (a fee) shows its price.
236
+ return `every provider you have keys for is over your price cap (maxHourlyUsd). Cheapest: ${best.provider}, ${best.skip.slice(OVER_CAP.length + 2)}`;
237
+ }
221
238
  const rest = plan.length - keyed.length;
222
239
  const small = keyed.filter((c) => c.skip?.startsWith("default image"));
223
240
  return (`none of the providers you have keys for can take this sandbox: ${keyed.map((c) => `${c.provider} (${c.skip})`).join(", ")}` +
@@ -227,12 +244,38 @@ export class Router {
227
244
  `or pass image: { ${small[0].provider}: "<template>" } with a template built at the size you need`
228
245
  : ""));
229
246
  }
247
+ /**
248
+ * Where a create would land and what the run would cost there, without starting anything. Throws
249
+ * RouterError("no_provider") when nothing can take it, with the same reason create would give.
250
+ */
251
+ quote(spec = {}, route = {}) {
252
+ const candidates = this.plan(spec, route);
253
+ const first = candidates.find((c) => !c.skip);
254
+ if (!first)
255
+ throw new RouterError(this.whyNone(candidates, !!route.provider, spec), [], "no_provider");
256
+ const hours = runHours(spec);
257
+ const rules = billingRules(first.provider);
258
+ const runHourlyUsd = rankUsd(first, hours);
259
+ return {
260
+ provider: first.provider,
261
+ size: first.size,
262
+ hourlyUsd: first.estimatedHourlyUsd,
263
+ listHourlyUsd: first.listHourlyUsd,
264
+ runSeconds: Math.round(hours * 3600),
265
+ runHourlyUsd,
266
+ estimatedUsd: runHourlyUsd * hours,
267
+ ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds } : {}),
268
+ ...(rules.incrementSeconds > 1 ? { billedInSecondsOf: rules.incrementSeconds } : {}),
269
+ ...(first.perSandboxUsd ? { perSandboxUsd: first.perSandboxUsd } : {}),
270
+ candidates,
271
+ };
272
+ }
230
273
  /** Start a sandbox on the best available provider, falling back down the list on failure. */
231
274
  async create(spec = {}, route = {}) {
232
275
  const plan = this.plan(spec, route);
233
276
  const usable = plan.filter((c) => !c.skip);
234
277
  if (usable.length === 0)
235
- throw new RouterError(this.whyNone(plan, !!route.provider), [], "no_provider");
278
+ throw new RouterError(this.whyNone(plan, !!route.provider, spec), [], "no_provider");
236
279
  // Pinned with no fallback: the first provider named, or nothing. Never a different one.
237
280
  if (route.provider && route.fallback === false && plan[0].skip) {
238
281
  throw new RouterError(`${plan[0].provider} can't take this sandbox: ${plan[0].skip}`, [], "no_provider");
@@ -271,7 +314,9 @@ export class Router {
271
314
  const status = errorStatus(err);
272
315
  attempts.push({ provider: c.provider, ok: false, ms: Date.now() - t0, error: err.message, ...(status ? { status } : {}) });
273
316
  const setup = err instanceof SetupError || (status !== undefined && SETUP_ERRORS.has(status));
274
- if (route.fallback !== "any" && setup) {
317
+ // On the router's own accounts, a key, permission or install problem is ours: move on.
318
+ const account = err instanceof SetupError || status === 401 || status === 403;
319
+ if (route.fallback !== "any" && setup && !(this.accountErrors === "fallback" && account)) {
275
320
  const msg = err.message.replace(/[.\s]+$/, "");
276
321
  throw new RouterError(`${msg.startsWith(c.provider) ? msg : `${c.provider}: ${msg}`}. This looks like a setup problem with ${c.provider} (key, image, request or a missing package), ` +
277
322
  `so the router stopped instead of moving the work to another provider; pass fallback: "any" to fall back on every error`, attempts, "setup");
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/types.d.ts CHANGED
@@ -41,7 +41,9 @@ export interface SandboxSpec {
41
41
  * whose last real-account check failed (`FAILING`) go last.
42
42
  * "verified": providers that passed the real-account check first (`VERIFIED`), then the rest; cheapest
43
43
  * list price first within each.
44
- * "cheapest": lowest list price for the spec, tested or not, ties alphabetical.
44
+ * "cheapest": lowest cost for the run (priced as in "balanced": minimum charge, billing increment and
45
+ * per-sandbox charge over `expectedSeconds`), strictly by price: no speed tie-break, and providers whose
46
+ * last check failed aren't moved last. Ties alphabetical.
45
47
  * "fastest": lowest median create time (this router's own, else your `bench` file), then cheapest.
46
48
  */
47
49
  export type Strategy = "default" | "balanced" | "verified" | "cheapest" | "fastest";
@@ -69,6 +71,13 @@ export interface RouteOptions {
69
71
  createTimeoutSeconds?: number;
70
72
  /** Capabilities every candidate must have. */
71
73
  require?: Capability[];
74
+ /**
75
+ * The most this sandbox may cost, in USD per hour. A provider is skipped when this run would cost more
76
+ * there, priced the way ranking prices it: hourly price, minimum charge and billing increment over
77
+ * `expectedSeconds` (else `timeoutMinutes`, default 30), plus any per-sandbox charge, divided by the
78
+ * run's hours. Omit for no cap.
79
+ */
80
+ maxHourlyUsd?: number;
72
81
  }
73
82
  export interface ExecOptions {
74
83
  cwd?: string;
@@ -136,7 +145,8 @@ export declare class ProviderError extends Error {
136
145
  }
137
146
  /**
138
147
  * A problem with local setup, such as a provider SDK that isn't installed or a missing setting:
139
- * something to fix here, not a provider being down. The router stops on it instead of falling back.
148
+ * something to fix here, not a provider being down. The router stops on it instead of falling back, unless it
149
+ * was made with `accountErrors: "fallback"`.
140
150
  */
141
151
  export declare class SetupError extends Error {
142
152
  constructor(message: string);
package/dist/types.js CHANGED
@@ -21,7 +21,8 @@ export class ProviderError extends Error {
21
21
  }
22
22
  /**
23
23
  * A problem with local setup, such as a provider SDK that isn't installed or a missing setting:
24
- * something to fix here, not a provider being down. The router stops on it instead of falling back.
24
+ * something to fix here, not a provider being down. The router stops on it instead of falling back, unless it
25
+ * was made with `accountErrors: "fallback"`.
25
26
  */
26
27
  export class SetupError extends Error {
27
28
  constructor(message) {
@@ -2,7 +2,7 @@ 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
3
  export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "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
package/dist/validate.js CHANGED
@@ -3,7 +3,7 @@ import { RouterError } from "./types.js";
3
3
  /** Every key a SandboxSpec can have. Anything else in a request is a mistake (e.g. "memory" for "memoryGb"). */
4
4
  export const SPEC_KEYS = ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "image", "metadata"];
5
5
  /** Every key RouteOptions can have. */
6
- export const ROUTE_KEYS = ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds"];
6
+ export const ROUTE_KEYS = ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"];
7
7
  export const STRATEGIES = ["default", "balanced", "verified", "cheapest", "fastest"];
8
8
  const bad = (msg) => new RouterError(msg, [], "bad_request");
9
9
  const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
@@ -32,7 +32,7 @@ export function validate(spec = {}, route = {}) {
32
32
  if (route.fallback !== undefined && route.fallback !== true && route.fallback !== false && route.fallback !== "any") {
33
33
  throw bad(`fallback must be true, false or "any", got ${JSON.stringify(route.fallback)}`);
34
34
  }
35
- for (const k of ["createTimeoutSeconds", "deadlineSeconds"]) {
35
+ for (const k of ["createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"]) {
36
36
  if (route[k] !== undefined && !positive(route[k]))
37
37
  throw bad(`${k} must be a positive number, got ${show(route[k])}`);
38
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "description": "One API for every sandbox provider: route AI agents' code by price, speed or capability, with automatic fallback. Free and open source.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",