@sandboxrouter/sdk 0.8.3 → 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 +1 -1
- package/dist/cli.js +21 -0
- package/dist/client.d.ts +3 -1
- package/dist/client.js +4 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/keyed.d.ts +5 -0
- package/dist/keyed.js +44 -0
- package/dist/providers/openscale.d.ts +5 -1
- package/dist/providers/openscale.js +6 -2
- package/dist/router.d.ts +32 -0
- package/dist/router.js +45 -4
- package/dist/server.d.ts +7 -1
- package/dist/server.js +10 -3
- package/dist/types.d.ts +10 -1
- package/dist/validate.d.ts +1 -1
- package/dist/validate.js +2 -2
- package/package.json +1 -1
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
|
|
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/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)
|
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";
|
package/dist/keyed.d.ts
ADDED
|
@@ -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
|
+
}
|
|
@@ -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:
|
|
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 {
|
|
@@ -120,6 +147,11 @@ export declare class Router {
|
|
|
120
147
|
* providers they do have keys for were skipped.
|
|
121
148
|
*/
|
|
122
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;
|
|
123
155
|
/** Start a sandbox on the best available provider, falling back down the list on failure. */
|
|
124
156
|
create(spec?: SandboxSpec, route?: RouteOptions): Promise<RoutedSandbox>;
|
|
125
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. */
|
|
@@ -177,6 +181,11 @@ export class Router {
|
|
|
177
181
|
(p.configured() ? undefined : gated ? `not configured; ${gated}` : "not configured") ??
|
|
178
182
|
(this.requireVerified && !c.verified ? "not tested (this router only uses providers that passed the real-account check)" : undefined);
|
|
179
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
|
+
}
|
|
180
189
|
return c;
|
|
181
190
|
});
|
|
182
191
|
// Neutral by construction: the same rule for every provider, ties alphabetical by id. Nothing here
|
|
@@ -185,12 +194,11 @@ export class Router {
|
|
|
185
194
|
if (!explicit) {
|
|
186
195
|
const hours = runHours(spec);
|
|
187
196
|
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
197
|
if (strategy === "fastest") {
|
|
190
198
|
list.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity) || byCost(a, b));
|
|
191
199
|
}
|
|
192
200
|
else if (strategy === "cheapest") {
|
|
193
|
-
list.sort(
|
|
201
|
+
list.sort(byCost);
|
|
194
202
|
}
|
|
195
203
|
else if (strategy === "verified") {
|
|
196
204
|
list.sort((a, b) => Number(b.verified) - Number(a.verified) || byCost(a, b));
|
|
@@ -205,7 +213,7 @@ export class Router {
|
|
|
205
213
|
* Why a create has nowhere to go, leading with what the caller can fix: no keys at all, or why the
|
|
206
214
|
* providers they do have keys for were skipped.
|
|
207
215
|
*/
|
|
208
|
-
whyNone(plan, explicit) {
|
|
216
|
+
whyNone(plan, explicit, spec = {}) {
|
|
209
217
|
if (plan.length === 0)
|
|
210
218
|
return "no provider can take this sandbox: none registered";
|
|
211
219
|
// Providers the caller named: say what each one needs.
|
|
@@ -220,6 +228,13 @@ export class Router {
|
|
|
220
228
|
if (keyed.length === 0)
|
|
221
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); " +
|
|
222
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
|
+
}
|
|
223
238
|
const rest = plan.length - keyed.length;
|
|
224
239
|
const small = keyed.filter((c) => c.skip?.startsWith("default image"));
|
|
225
240
|
return (`none of the providers you have keys for can take this sandbox: ${keyed.map((c) => `${c.provider} (${c.skip})`).join(", ")}` +
|
|
@@ -229,12 +244,38 @@ export class Router {
|
|
|
229
244
|
`or pass image: { ${small[0].provider}: "<template>" } with a template built at the size you need`
|
|
230
245
|
: ""));
|
|
231
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
|
+
}
|
|
232
273
|
/** Start a sandbox on the best available provider, falling back down the list on failure. */
|
|
233
274
|
async create(spec = {}, route = {}) {
|
|
234
275
|
const plan = this.plan(spec, route);
|
|
235
276
|
const usable = plan.filter((c) => !c.skip);
|
|
236
277
|
if (usable.length === 0)
|
|
237
|
-
throw new RouterError(this.whyNone(plan, !!route.provider), [], "no_provider");
|
|
278
|
+
throw new RouterError(this.whyNone(plan, !!route.provider, spec), [], "no_provider");
|
|
238
279
|
// Pinned with no fallback: the first provider named, or nothing. Never a different one.
|
|
239
280
|
if (route.provider && route.fallback === false && plan[0].skip) {
|
|
240
281
|
throw new RouterError(`${plan[0].provider} can't take this sandbox: ${plan[0].skip}`, [], "no_provider");
|
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(
|
|
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(
|
|
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
|
|
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
|
|
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
|
|
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;
|
package/dist/validate.d.ts
CHANGED
|
@@ -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.
|
|
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",
|