@sandboxrouter/sdk 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +4 -3
  2. package/dist/agent-bench.d.ts +39 -0
  3. package/dist/agent-bench.js +150 -0
  4. package/dist/bench-store.js +11 -2
  5. package/dist/bench.d.ts +22 -0
  6. package/dist/bench.js +59 -7
  7. package/dist/burst.d.ts +81 -0
  8. package/dist/burst.js +183 -0
  9. package/dist/catalog.d.ts +32 -0
  10. package/dist/catalog.js +58 -15
  11. package/dist/check.d.ts +2 -0
  12. package/dist/check.js +8 -0
  13. package/dist/cli.js +217 -5
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/leaderboard.d.ts +107 -2
  17. package/dist/leaderboard.js +175 -5
  18. package/dist/ledger.d.ts +2 -0
  19. package/dist/ledger.js +12 -1
  20. package/dist/price-index.d.ts +54 -0
  21. package/dist/price-index.js +50 -0
  22. package/dist/providers/beam.js +4 -0
  23. package/dist/providers/blaxel.js +4 -0
  24. package/dist/providers/boat.js +3 -1
  25. package/dist/providers/daytona.js +4 -0
  26. package/dist/providers/deno.js +4 -0
  27. package/dist/providers/e2b.d.ts +2 -0
  28. package/dist/providers/e2b.js +4 -0
  29. package/dist/providers/hopx.js +4 -0
  30. package/dist/providers/langsmith.js +4 -0
  31. package/dist/providers/modal.js +11 -2
  32. package/dist/providers/morph.js +4 -0
  33. package/dist/providers/runloop.js +4 -0
  34. package/dist/providers/sprites.js +4 -0
  35. package/dist/providers/tensorlake.js +4 -0
  36. package/dist/providers/vercel.js +4 -0
  37. package/dist/published.d.ts +2 -0
  38. package/dist/published.js +2087 -0
  39. package/dist/recommend.d.ts +117 -0
  40. package/dist/recommend.js +103 -0
  41. package/dist/results.js +81 -1
  42. package/dist/router.d.ts +50 -0
  43. package/dist/router.js +83 -10
  44. package/dist/submit.d.ts +6 -0
  45. package/dist/submit.js +70 -0
  46. package/dist/task.d.ts +80 -0
  47. package/dist/task.js +173 -0
  48. package/dist/types.d.ts +12 -0
  49. package/dist/util.d.ts +2 -0
  50. package/dist/util.js +2 -0
  51. package/dist/validate.d.ts +1 -1
  52. package/dist/validate.js +4 -1
  53. package/package.json +1 -1
@@ -0,0 +1,117 @@
1
+ /** A job the benchmarks measure. "start" is only starting a sandbox and running one command. */
2
+ export type RecJob = "start" | "short" | "long" | "python" | "download" | "agent" | "repo";
3
+ /** What to rank by: lowest cost, shortest time, or both together ("value"). */
4
+ export type RecPriority = "cost" | "speed" | "value";
5
+ export interface PublishedStart {
6
+ name: string;
7
+ medianCreateMs: number;
8
+ successRate: number;
9
+ runs: number;
10
+ hourlyUsd: number;
11
+ measuredAt: string;
12
+ }
13
+ export interface PublishedJob {
14
+ name: string;
15
+ /** Time to a usable sandbox when it ran this job. */
16
+ createMs: number;
17
+ /** The job itself, once the sandbox was up. */
18
+ taskMs: number;
19
+ /** One job in a new sandbox: start, minimum charge and per-sandbox fee included. */
20
+ taskUsd: number;
21
+ /** One job in a sandbox that's already running. */
22
+ reusedUsd: number;
23
+ successRate: number;
24
+ runs: number;
25
+ /** Bills at least this many seconds per sandbox. */
26
+ minimumSeconds?: number;
27
+ /** Fee per sandbox started. */
28
+ perSandboxUsd?: number;
29
+ measuredAt: string;
30
+ }
31
+ export interface PublishedLoadRow {
32
+ name: string;
33
+ /** How many were asked for at once, and how many started. */
34
+ n: number;
35
+ ok: number;
36
+ /** Of those that didn't start, how many the benchmarking account's own limit refused. */
37
+ limited: number;
38
+ p50Ms?: number;
39
+ p99Ms?: number;
40
+ wallMs: number;
41
+ /** Cost per 100 sandboxes, scaled from the ones that ran. */
42
+ usdPer100?: number;
43
+ measuredAt: string;
44
+ }
45
+ export interface PublishedLoad {
46
+ /** Sandboxes asked for at once. */
47
+ n: number;
48
+ /** "start": one command each; "rl": a short Python step each; "agents": the minute-long agent loop each. */
49
+ job: "start" | "rl" | "agents";
50
+ rows: Record<string, PublishedLoadRow>;
51
+ }
52
+ /** The published benchmark numbers, as the website and the SDK carry them. */
53
+ export interface PublishedData {
54
+ schema: 1;
55
+ /** Newest measurement in the data. */
56
+ dataThrough: string;
57
+ start: Record<string, PublishedStart>;
58
+ jobs: Partial<Record<Exclude<RecJob, "start">, Record<string, PublishedJob>>>;
59
+ load: PublishedLoad[];
60
+ }
61
+ export interface RecommendOptions {
62
+ /** The job to run. Default "short". */
63
+ job?: RecJob;
64
+ /** How many sandboxes at once. From 10 up, start times under that load are used where measured. Default 1. */
65
+ count?: number;
66
+ /** Default "value". */
67
+ priority?: RecPriority;
68
+ /** Jobs run in a sandbox that's already running (no start, minimum or per-sandbox fee). Default false. */
69
+ reuse?: boolean;
70
+ /** Only these providers (for example the ones you have keys for). */
71
+ providers?: readonly string[];
72
+ /** How many to return. Default all. */
73
+ limit?: number;
74
+ }
75
+ export interface Recommendation {
76
+ rank: number;
77
+ provider: string;
78
+ name: string;
79
+ /** Seconds for one job, start included unless reusing. */
80
+ secondsEach: number;
81
+ /** Cost of one job; for "start", undefined (see hourlyUsd). */
82
+ usdEach?: number;
83
+ /** Cost of all `count` jobs. */
84
+ usdTotal?: number;
85
+ /** List price per hour at the size it ran, for "start". */
86
+ hourlyUsd?: number;
87
+ /** Share of runs that worked (refusals for the benchmarking account's own limit left out). */
88
+ successRate: number;
89
+ /** Runs behind the numbers. */
90
+ runs: number;
91
+ /** Cost and time together, each against the median and divided by the success rate; 1.0 is the median, lower is better. */
92
+ valueScore: number;
93
+ /** The burst size the at-once numbers come from, when `count` is 10 or more and the provider started all of them. */
94
+ measuredAtOnce?: number;
95
+ /** Median time to ready when that many were asked for at once. */
96
+ readyAtOnceMs?: number;
97
+ notes: string[];
98
+ measuredAt: string;
99
+ }
100
+ export interface RecommendResult {
101
+ job: RecJob;
102
+ count: number;
103
+ priority: RecPriority;
104
+ reuse: boolean;
105
+ /** How the ranking was made, in a sentence. */
106
+ basis: string;
107
+ dataThrough: string;
108
+ results: Recommendation[];
109
+ }
110
+ /**
111
+ * Rank providers for a job from the published benchmarks. Costs and times are per successful job: each is
112
+ * divided by the provider's success rate, so one that fails often pays for it. For `count` of 10 or more, the
113
+ * start time is the one measured with that many asked for at once (the largest measured size not above
114
+ * `count`); providers not yet measured at that size are listed after the ones that were, since the limit that
115
+ * stopped them was the benchmarking account's, not theirs.
116
+ */
117
+ export declare function recommend(data: PublishedData, opts?: RecommendOptions): RecommendResult;
@@ -0,0 +1,103 @@
1
+ // Which provider for a job, from the published benchmarks. Pure and import-free on purpose: scripts/site-data.ts
2
+ // copies this file into the website (web/src/lib/recommend.ts) so the SDK, the CLI, /benchmarks.json and the MCP
3
+ // tool all answer the same way from the same numbers.
4
+ const LOAD_JOB = {
5
+ start: "start",
6
+ short: "start",
7
+ long: "start",
8
+ python: "rl",
9
+ download: "start",
10
+ agent: "agents",
11
+ repo: "start",
12
+ };
13
+ const mid = (xs) => {
14
+ const s = [...xs].sort((a, b) => a - b);
15
+ const m = Math.floor(s.length / 2);
16
+ return s.length === 0 ? 1 : s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
17
+ };
18
+ /**
19
+ * Rank providers for a job from the published benchmarks. Costs and times are per successful job: each is
20
+ * divided by the provider's success rate, so one that fails often pays for it. For `count` of 10 or more, the
21
+ * start time is the one measured with that many asked for at once (the largest measured size not above
22
+ * `count`); providers not yet measured at that size are listed after the ones that were, since the limit that
23
+ * stopped them was the benchmarking account's, not theirs.
24
+ */
25
+ export function recommend(data, opts = {}) {
26
+ const job = opts.job ?? "short";
27
+ const count = Math.max(1, Math.floor(opts.count ?? 1));
28
+ const priority = opts.priority ?? "value";
29
+ const reuse = job !== "start" && !!opts.reuse;
30
+ const only = opts.providers ? new Set(opts.providers) : undefined;
31
+ const loads = data.load.filter((l) => l.job === LOAD_JOB[job] && l.n <= count).sort((a, b) => b.n - a.n);
32
+ const load = count >= 10 && !reuse ? loads[0] : undefined;
33
+ const raw = [];
34
+ if (job === "start") {
35
+ for (const [id, s] of Object.entries(data.start)) {
36
+ if (only && !only.has(id))
37
+ continue;
38
+ raw.push({ provider: id, name: s.name, secondsEach: s.medianCreateMs / 1000, hourlyUsd: s.hourlyUsd, successRate: s.successRate, runs: s.runs, notes: [], measuredAt: s.measuredAt, usdKey: s.hourlyUsd });
39
+ }
40
+ }
41
+ else {
42
+ for (const [id, j] of Object.entries(data.jobs[job] ?? {})) {
43
+ if (only && !only.has(id))
44
+ continue;
45
+ const usd = reuse ? j.reusedUsd : j.taskUsd;
46
+ const notes = [];
47
+ if (!reuse && j.minimumSeconds && j.minimumSeconds > 1)
48
+ notes.push(`bills at least ${j.minimumSeconds} s per sandbox`);
49
+ if (!reuse && j.perSandboxUsd)
50
+ notes.push(`$${j.perSandboxUsd} per sandbox started`);
51
+ raw.push({
52
+ provider: id,
53
+ name: j.name,
54
+ secondsEach: (j.taskMs + (reuse ? 0 : j.createMs)) / 1000,
55
+ usdEach: usd,
56
+ usdTotal: usd * count,
57
+ successRate: j.successRate,
58
+ runs: j.runs,
59
+ notes,
60
+ measuredAt: j.measuredAt,
61
+ usdKey: usd,
62
+ });
63
+ }
64
+ }
65
+ const mostRuns = Math.max(1, ...raw.map((r) => r.runs));
66
+ for (const r of raw) {
67
+ if (r.runs < mostRuns / 2)
68
+ r.notes.push(`only ${r.runs} runs`);
69
+ if (r.successRate < 1)
70
+ r.notes.push(`${Math.round(r.successRate * 100)}% of runs worked`);
71
+ if (!load)
72
+ continue;
73
+ const l = load.rows[r.provider];
74
+ if (l && l.ok === l.n && l.p50Ms !== undefined) {
75
+ r.measuredAtOnce = l.n;
76
+ r.readyAtOnceMs = l.p50Ms;
77
+ // Swap the one-at-a-time start for the start under load.
78
+ const startS = job === "start" ? r.secondsEach : r.secondsEach - (data.jobs[job]?.[r.provider]?.createMs ?? 0) / 1000;
79
+ r.secondsEach = (job === "start" ? 0 : startS) + l.p50Ms / 1000;
80
+ }
81
+ else if (l && l.n - l.ok > l.limited) {
82
+ // Some failed for reasons other than the benchmarking account's limit: the provider's own.
83
+ r.notes.push(`${l.ok} of ${l.n} started at once`);
84
+ }
85
+ else {
86
+ r.notes.push(`not measured at ${load.n} at once yet${l ? " (the benchmarking account's limit)" : ""}`);
87
+ }
88
+ }
89
+ const ok = (r) => Math.max(r.successRate, 0.01);
90
+ const midCost = mid(raw.map((r) => r.usdKey / ok(r)));
91
+ const midTime = mid(raw.map((r) => r.secondsEach / ok(r)));
92
+ const scored = raw.map((r) => ({ ...r, valueScore: (r.usdKey / ok(r) / midCost) * (r.secondsEach / ok(r) / midTime) }));
93
+ const key = (r) => priority === "cost" ? r.usdKey / ok(r) : priority === "speed" ? r.secondsEach / ok(r) : r.valueScore;
94
+ const atScale = (r) => (load && r.measuredAtOnce === undefined ? 1 : 0);
95
+ scored.sort((a, b) => atScale(a) - atScale(b) || key(a) - key(b) || a.provider.localeCompare(b.provider));
96
+ const results = scored.slice(0, opts.limit ?? scored.length).map(({ usdKey: _, ...r }, i) => ({ ...r, rank: i + 1, valueScore: Math.round(r.valueScore * 100) / 100 }));
97
+ const what = job === "start" ? "starting a sandbox" : `the ${job} job${reuse ? " in a running sandbox" : " in a new sandbox"}`;
98
+ const by = priority === "cost" ? "lowest cost" : priority === "speed" ? "shortest time" : "best value (cost times time, each against the median)";
99
+ const basis = `Ranked by ${by} for ${what}, per successful run` +
100
+ (load ? `, with start times measured ${load.n} at once; providers not yet measured at that size come after` : "") +
101
+ ".";
102
+ return { job, count, priority, reuse, basis, dataThrough: data.dataThrough, results };
103
+ }
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 : []) {
@@ -111,12 +114,31 @@ export function validateResult(j, now = Date.now()) {
111
114
  out.push(`${r?.provider}: runs is not a positive number`);
112
115
  if (!isNum(r?.failures, 0, r?.runs ?? 0))
113
116
  out.push(`${r?.provider}: failures must be between 0 and runs`);
117
+ if (r?.limited !== undefined && !isNum(r.limited, 0, r?.failures ?? 0))
118
+ out.push(`${r?.provider}: limited must be between 0 and failures`);
114
119
  for (const k of ["medianCreateMs", "medianExecMs"]) {
115
120
  if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
116
121
  out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
117
122
  }
118
123
  if (r?.failures < r?.runs && r?.medianCreateMs === undefined)
119
124
  out.push(`${r?.provider}: successful runs but no medianCreateMs`);
125
+ if (r?.medianTaskMs !== undefined && !isNum(r.medianTaskMs, 1, MAX_MS))
126
+ out.push(`${r?.provider}: medianTaskMs must be between 1 ms and 15 min`);
127
+ if (r?.medianTaskCpuMs !== undefined && !isNum(r.medianTaskCpuMs, 0, 64 * MAX_MS))
128
+ out.push(`${r?.provider}: medianTaskCpuMs is out of range`);
129
+ if (r?.medianTaskMaxCoreMs !== undefined && !isNum(r.medianTaskMaxCoreMs, 0, MAX_MS))
130
+ out.push(`${r?.provider}: medianTaskMaxCoreMs is out of range`);
131
+ if (r?.taskPhasesMs !== undefined) {
132
+ const ph = r.taskPhasesMs;
133
+ const def = taskByVersion(j.task);
134
+ if (j.task === undefined)
135
+ out.push(`${r?.provider}: has task times but the report doesn't say which task (task)`);
136
+ else if (!def)
137
+ out.push(`${r?.provider}: unknown task "${String(j.task)}"`);
138
+ else if (!ph || typeof ph !== "object" || def.phases.some((p) => !isNum(ph[p.id], 1, MAX_MS))) {
139
+ out.push(`${r?.provider}: taskPhasesMs needs ${def.phases.map((p) => p.id).join(", ")}, each between 1 ms and 15 min`);
140
+ }
141
+ }
120
142
  if ("lastError" in (r ?? {}))
121
143
  out.push(`${r?.provider}: lastError must not be shared (it can hold account details)`);
122
144
  }
@@ -139,6 +161,64 @@ export function validateResult(j, now = Date.now()) {
139
161
  }
140
162
  }
141
163
  }
164
+ else if (j.tool === "sandboxrouter-agent") {
165
+ add(checkDate(j.date, now));
166
+ add(checkLabel(j.label));
167
+ add(checkBy(j.by));
168
+ if (typeof j.model !== "string" || !j.model || j.model.length > 80)
169
+ out.push("model must name the model used");
170
+ if (typeof j.task !== "string")
171
+ out.push("task must name the agent task version");
172
+ if (!isNum(j.runs, 3, 1000))
173
+ out.push("runs must be at least 3");
174
+ if (!Array.isArray(j.rows) || !j.rows.length)
175
+ out.push("rows is empty");
176
+ for (const r of Array.isArray(j.rows) ? j.rows : []) {
177
+ provider(r?.provider, "row provider");
178
+ if (noBench(r?.provider))
179
+ out.push(`${r.provider}: ${NO_BENCH}`);
180
+ if (!isNum(r?.ok, 0, r?.runs ?? 0))
181
+ out.push(`${r?.provider}: ok must be between 0 and runs`);
182
+ if (r?.limited !== undefined && !isNum(r.limited, 0, 1000))
183
+ out.push(`${r?.provider}: limited is out of range`);
184
+ for (const k of ["medianWallMs", "medianModelMs", "medianCpuMs"]) {
185
+ if (r?.[k] !== undefined && !isNum(r[k], 0, 4 * MAX_MS))
186
+ out.push(`${r?.provider}: ${k} is out of range`);
187
+ }
188
+ if (r?.medianUsd !== undefined && !isNum(r.medianUsd, 0, 1000))
189
+ out.push(`${r?.provider}: medianUsd is out of range`);
190
+ }
191
+ }
192
+ else if (j.tool === "sandboxrouter-burst") {
193
+ add(checkDate(j.date, now));
194
+ add(checkLabel(j.label));
195
+ add(checkBy(j.by));
196
+ if (!isNum(j.n, 2, 1000))
197
+ out.push("n must be between 2 and 1000");
198
+ if (j.task !== undefined && !taskByVersion(j.task))
199
+ out.push(`unknown task "${String(j.task)}"`);
200
+ if (!Array.isArray(j.rows) || !j.rows.length)
201
+ out.push("rows is empty");
202
+ for (const r of Array.isArray(j.rows) ? j.rows : []) {
203
+ provider(r?.provider, "row provider");
204
+ if (noBench(r?.provider))
205
+ out.push(`${r.provider}: ${NO_BENCH}`);
206
+ if (r?.n !== j.n)
207
+ out.push(`${r?.provider}: n must match the report's n`);
208
+ if (!isNum(r?.ok, 0, j.n) || !isNum(r?.limited, 0, j.n) || r.ok + r.limited > j.n)
209
+ out.push(`${r?.provider}: ok and limited must add up to at most n`);
210
+ for (const k of ["p50Ms", "p95Ms", "p99Ms", "jobP50Ms"]) {
211
+ if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
212
+ out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
213
+ }
214
+ if (!isNum(r?.wallMs, 1, 4 * MAX_MS))
215
+ out.push(`${r?.provider}: wallMs is out of range`);
216
+ if (r?.usd !== undefined && !isNum(r.usd, 0, 1000))
217
+ out.push(`${r?.provider}: usd is out of range`);
218
+ if (r?.ok > 0 && r?.p50Ms === undefined)
219
+ out.push(`${r?.provider}: sandboxes started but no p50Ms`);
220
+ }
221
+ }
142
222
  else if (j.tool === "sandboxrouter-cost") {
143
223
  add(checkDate(j.date, now));
144
224
  add(checkBy(j.by));
@@ -162,7 +242,7 @@ export function validateResult(j, now = Date.now()) {
162
242
  }
163
243
  }
164
244
  else {
165
- out.push(`unknown tool "${String(j.tool)}": expected a bench report, a saved check or a cost run`);
245
+ out.push(`unknown tool "${String(j.tool)}": expected a bench report, a burst report, an agent report, a saved check or a cost run`);
166
246
  }
167
247
  return out;
168
248
  }
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
  /**
@@ -36,6 +41,8 @@ export interface Candidate {
36
41
  perSandboxUsd?: number;
37
42
  /** Why this provider won't be tried, if it won't. */
38
43
  skip?: string;
44
+ /** Set while the provider is at the back of the line after a limit or repeated failures (see `cooldown`). */
45
+ cooling?: string;
39
46
  }
40
47
  /** What `router.quote()` answers: the provider a create would start on first, and what the run would cost there. */
41
48
  export interface Quote {
@@ -71,6 +78,11 @@ export interface RouterOptions {
71
78
  providers?: Provider[];
72
79
  /** Path of the bench results file: start times for the speed tie-break and strategy "fastest". */
73
80
  benchFile?: string;
81
+ /**
82
+ * When neither this router nor your bench file has timed a provider, use the published start times
83
+ * (sandboxrouter.ai/benchmarks, carried in the package). Default true; false to rank on your own data only.
84
+ */
85
+ published?: boolean;
74
86
  /** Desktop-only computer providers (sandbox providers that also sell computers are found automatically). */
75
87
  computers?: ComputerProvider[];
76
88
  /**
@@ -107,6 +119,19 @@ export interface RouterOptions {
107
119
  factor?: number;
108
120
  minSeconds?: number;
109
121
  };
122
+ /**
123
+ * Remember trouble between creates, so one provider's outage or limit doesn't slow every request: a provider
124
+ * that refuses for a limit (429, quota, concurrency cap) goes to the back of the line for `limitSeconds`
125
+ * (default 30), and one that fails `failures` times (default 3) within `windowSeconds` (default 60) goes to
126
+ * the back for `downSeconds` (default 60). It's still tried when nothing else can take the sandbox, and one
127
+ * success clears it. `false` turns this off.
128
+ */
129
+ cooldown?: false | {
130
+ limitSeconds?: number;
131
+ failures?: number;
132
+ windowSeconds?: number;
133
+ downSeconds?: number;
134
+ };
110
135
  /**
111
136
  * What a provider's 401 or 403 (or a missing provider package) does to a create. "stop" (default):
112
137
  * the create fails, because with your own keys that is a key or setup you need to fix, and moving the
@@ -123,6 +148,7 @@ export declare function defaultProviders(): Provider[];
123
148
  export declare class Router {
124
149
  private providers;
125
150
  private benchFile?;
151
+ private readonly published;
126
152
  private readonly verified;
127
153
  private readonly failing;
128
154
  private readonly requireVerified;
@@ -131,6 +157,11 @@ export declare class Router {
131
157
  private readonly live;
132
158
  private computerOnly;
133
159
  private readonly quick;
160
+ private readonly cool;
161
+ /** Providers sent to the back of the line, until when and why. */
162
+ private readonly cooling;
163
+ /** Recent failed creates per provider (not limits), for the failure count. */
164
+ private readonly failures;
134
165
  private readonly accountErrors;
135
166
  /** The local record of sandboxes this router created, or undefined when turned off. */
136
167
  readonly ledger?: Ledger;
@@ -142,6 +173,18 @@ export declare class Router {
142
173
  provider(id: ProviderId): Provider;
143
174
  /** The ordered list of providers a create would try, with the reason any are skipped. */
144
175
  plan(spec?: SandboxSpec, route?: RouteOptions): Candidate[];
176
+ /**
177
+ * Providers currently at the back of the line and why (see `cooldown`). For dashboards and logs.
178
+ */
179
+ troubled(): {
180
+ provider: ProviderId;
181
+ reason: string;
182
+ untilMs: number;
183
+ }[];
184
+ /** After a failed create: a limit cools the provider at once; other failures count toward a cooldown. */
185
+ private noteFailure;
186
+ /** A provider that just worked is back to normal. */
187
+ private noteSuccess;
145
188
  /**
146
189
  * Why a create has nowhere to go, leading with what the caller can fix: no keys at all, or why the
147
190
  * providers they do have keys for were skipped.
@@ -202,6 +245,13 @@ export declare class RoutedSandbox {
202
245
  /** Every create attempt, including failed fallbacks. */
203
246
  attempts: Attempt[], price?: SandboxPrice, ledger?: Ledger | undefined);
204
247
  get nativeId(): string;
248
+ /**
249
+ * The provider SDK's own sandbox object, for what the router doesn't cover: ports, background processes,
250
+ * snapshots, anything else the provider has. Narrow it with the provider's own type, e.g.
251
+ * `if (sbx.provider === "e2b") (sbx.native as import("e2b").Sandbox).getHost(3000)`. Undefined for providers
252
+ * driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
253
+ */
254
+ get native(): unknown;
205
255
  /**
206
256
  * Run a command. If it outlives `opts.timeoutSeconds` the adapter stops it and this rejects with
207
257
  * `ProviderError("<provider>: command timed out after Ns")`. Should an adapter fail to notice its
package/dist/router.js CHANGED
@@ -1,8 +1,9 @@
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
+ import { PUBLISHED } from "./published.js";
4
5
  import { Ledger, defaultLedgerFile } from "./ledger.js";
5
- import { DEFAULT_EXEC_TIMEOUT_S, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
6
+ import { DEFAULT_EXEC_TIMEOUT_S, LIMIT_ERROR, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
6
7
  import { BILLED_VS_LIST } from "./billing.js";
7
8
  import { FAILING, VERIFIED } from "./verified.js";
8
9
  import { validate } from "./validate.js";
@@ -100,6 +101,7 @@ export function defaultProviders() {
100
101
  export class Router {
101
102
  providers;
102
103
  benchFile;
104
+ published;
103
105
  verified;
104
106
  failing;
105
107
  requireVerified;
@@ -108,6 +110,11 @@ export class Router {
108
110
  live = new Map();
109
111
  computerOnly;
110
112
  quick;
113
+ cool;
114
+ /** Providers sent to the back of the line, until when and why. */
115
+ cooling = new Map();
116
+ /** Recent failed creates per provider (not limits), for the failure count. */
117
+ failures = new Map();
111
118
  accountErrors;
112
119
  /** The local record of sandboxes this router created, or undefined when turned off. */
113
120
  ledger;
@@ -117,6 +124,7 @@ export class Router {
117
124
  this.ledger = new Ledger(file);
118
125
  this.providers = new Map((opts.providers ?? defaultProviders()).map((p) => [p.id, p]));
119
126
  this.benchFile = opts.benchFile;
127
+ this.published = opts.published ?? true;
120
128
  this.verified = new Set(opts.verified ?? Object.keys(VERIFIED));
121
129
  this.failing = new Set(opts.failing ?? Object.keys(FAILING));
122
130
  this.requireVerified = opts.requireVerified ?? false;
@@ -124,6 +132,7 @@ export class Router {
124
132
  opts.billedVsList ?? Object.fromEntries(Object.entries(BILLED_VS_LIST).map(([id, b]) => [id, b.ratio]));
125
133
  this.computerOnly = opts.computers ?? (opts.providers ? [] : defaultComputerProviders());
126
134
  this.quick = opts.quickFallback === false ? false : { factor: 5, minSeconds: 10, ...opts.quickFallback };
135
+ this.cool = opts.cooldown === false ? false : { limitSeconds: 30, failures: 3, windowSeconds: 60, downSeconds: 60, ...opts.cooldown };
127
136
  this.accountErrors = opts.accountErrors ?? "stop";
128
137
  }
129
138
  /** Registered and has credentials. False for providers this router doesn't know. */
@@ -163,9 +172,14 @@ export class Router {
163
172
  provider: id,
164
173
  estimatedHourlyUsd: round(list * (ratio ?? 1)),
165
174
  listHourlyUsd: list,
175
+ ...(cpuHourlyAtFull(id, spec) > 0 ? { cpuHourlyUsd: round(cpuHourlyAtFull(id, spec) * billedCpuShare(id, spec) * (ratio ?? 1)) } : {}),
166
176
  ...(ratio !== undefined ? { billedVsList: ratio } : {}),
167
177
  size: sizeOf(id, spec),
168
- medianCreateMs: speed ? (live && live.length >= LIVE_MIN_SAMPLES ? median(live) : median(bench[id]?.createMs)) : undefined,
178
+ medianCreateMs: speed
179
+ ? live && live.length >= LIVE_MIN_SAMPLES
180
+ ? median(live)
181
+ : (median(bench[id]?.createMs) ?? (this.published ? PUBLISHED.start[id]?.medianCreateMs : undefined))
182
+ : undefined,
169
183
  verified: this.verified.has(id),
170
184
  failing: this.failing.has(id),
171
185
  };
@@ -191,6 +205,7 @@ export class Router {
191
205
  // Neutral by construction: the same rule for every provider, ties alphabetical by id. Nothing here
192
206
  // depends on who the provider is, only on its price, what it really billed, how fast it started for
193
207
  // this router and whether its last real-account check failed. An explicit list keeps the caller's order.
208
+ let ordered = list;
194
209
  if (!explicit) {
195
210
  const hours = runHours(spec);
196
211
  const byCost = (a, b) => rankUsd(a, hours) - rankUsd(b, hours) || a.provider.localeCompare(b.provider);
@@ -204,10 +219,50 @@ export class Router {
204
219
  list.sort((a, b) => Number(b.verified) - Number(a.verified) || byCost(a, b));
205
220
  }
206
221
  else {
207
- return balanced(list, hours);
222
+ ordered = balanced(list, hours);
208
223
  }
209
224
  }
210
- return list;
225
+ // Providers in a cooldown go to the back, in the same order among themselves: still there if nothing else can.
226
+ const now = Date.now();
227
+ for (const c of ordered) {
228
+ const t = this.cooling.get(c.provider);
229
+ if (t && t.until > now)
230
+ c.cooling = `${t.reason}; back in line in ${Math.ceil((t.until - now) / 1000)}s`;
231
+ }
232
+ return [...ordered.filter((c) => !c.cooling), ...ordered.filter((c) => c.cooling)];
233
+ }
234
+ /**
235
+ * Providers currently at the back of the line and why (see `cooldown`). For dashboards and logs.
236
+ */
237
+ troubled() {
238
+ const now = Date.now();
239
+ return [...this.cooling]
240
+ .filter(([, t]) => t.until > now)
241
+ .map(([provider, t]) => ({ provider, reason: t.reason, untilMs: t.until }));
242
+ }
243
+ /** After a failed create: a limit cools the provider at once; other failures count toward a cooldown. */
244
+ noteFailure(id, err, status) {
245
+ const cool = this.cool;
246
+ if (!cool)
247
+ return;
248
+ const now = Date.now();
249
+ const msg = err?.message ?? String(err);
250
+ if (status === 429 || LIMIT_ERROR.test(msg)) {
251
+ this.cooling.set(id, { until: now + cool.limitSeconds * 1000, reason: "hit a limit" });
252
+ return;
253
+ }
254
+ const recent = (this.failures.get(id) ?? []).filter((t) => now - t < cool.windowSeconds * 1000);
255
+ recent.push(now);
256
+ this.failures.set(id, recent);
257
+ if (recent.length >= cool.failures) {
258
+ this.cooling.set(id, { until: now + cool.downSeconds * 1000, reason: `${recent.length} failed creates in ${cool.windowSeconds}s` });
259
+ this.failures.delete(id);
260
+ }
261
+ }
262
+ /** A provider that just worked is back to normal. */
263
+ noteSuccess(id) {
264
+ this.cooling.delete(id);
265
+ this.failures.delete(id);
211
266
  }
212
267
  /**
213
268
  * Why a create has nowhere to go, leading with what the caller can fix: no keys at all, or why the
@@ -283,15 +338,18 @@ export class Router {
283
338
  const attempts = [];
284
339
  const tries = route.fallback === false ? usable.slice(0, 1) : usable;
285
340
  const deadline = Date.now() + (route.deadlineSeconds ?? DEFAULT_CREATE_DEADLINE_S) * 1000;
341
+ 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");
286
342
  for (const [i, c] of tries.entries()) {
287
343
  const left = deadline - Date.now();
288
- if (left <= 0) {
289
- 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");
290
- }
344
+ if (left <= 0)
345
+ throw outOfTime();
291
346
  const t0 = Date.now();
292
347
  const pending = this.provider(c.provider).create(spec);
293
348
  const { limitS, typicalMs } = this.waitFor(c.provider, route, i === tries.length - 1);
294
349
  const waitS = Math.min(limitS, left / 1000);
350
+ // This try's wait is what's left of the deadline: if it times out, the deadline is spent. Decided here,
351
+ // not by reading the clock again, since a timer can fire a millisecond early and let one more try start.
352
+ const lastChance = left / 1000 <= limitS;
295
353
  const price = { estimatedHourlyUsd: c.estimatedHourlyUsd, listHourlyUsd: c.listHourlyUsd, size: c.size };
296
354
  let timedOut = false;
297
355
  try {
@@ -302,6 +360,7 @@ export class Router {
302
360
  });
303
361
  attempts.push({ provider: c.provider, ok: true, ms: Date.now() - t0 });
304
362
  this.observe(c.provider, Date.now() - t0);
363
+ this.noteSuccess(c.provider);
305
364
  const sbx = new RoutedSandbox(c.provider, box, attempts, price, this.ledger);
306
365
  this.record(sbx, price, spec.timeoutMinutes);
307
366
  return sbx;
@@ -313,6 +372,9 @@ export class Router {
313
372
  pending.then((late) => this.discard(c.provider, late, price, spec.timeoutMinutes), () => { });
314
373
  const status = errorStatus(err);
315
374
  attempts.push({ provider: c.provider, ok: false, ms: Date.now() - t0, error: err.message, ...(status ? { status } : {}) });
375
+ this.noteFailure(c.provider, err, status);
376
+ if (timedOut && lastChance)
377
+ throw outOfTime();
316
378
  const setup = err instanceof SetupError || (status !== undefined && SETUP_ERRORS.has(status));
317
379
  // On the router's own accounts, a key, permission or install problem is ours: move on.
318
380
  const account = err instanceof SetupError || status === 401 || status === 403;
@@ -432,6 +494,15 @@ export class RoutedSandbox {
432
494
  get nativeId() {
433
495
  return this.box.nativeId;
434
496
  }
497
+ /**
498
+ * The provider SDK's own sandbox object, for what the router doesn't cover: ports, background processes,
499
+ * snapshots, anything else the provider has. Narrow it with the provider's own type, e.g.
500
+ * `if (sbx.provider === "e2b") (sbx.native as import("e2b").Sandbox).getHost(3000)`. Undefined for providers
501
+ * driven over plain HTTP (use `nativeId` with their API). Calls made through it aren't routed or tracked.
502
+ */
503
+ get native() {
504
+ return this.box.native;
505
+ }
435
506
  /**
436
507
  * Run a command. If it outlives `opts.timeoutSeconds` the adapter stops it and this rejects with
437
508
  * `ProviderError("<provider>: command timed out after Ns")`. Should an adapter fail to notice its
@@ -516,10 +587,12 @@ export function runHours(spec) {
516
587
  * per-sandbox charge is added, so short runs favor providers that bill by the second without a fee.
517
588
  */
518
589
  export function rankUsd(c, hours) {
519
- const { minSeconds, incrementSeconds } = billingRules(c.provider);
590
+ const { minSeconds, incrementSeconds, minimumCovers } = billingRules(c.provider);
520
591
  const seconds = hours * 3600;
521
592
  const billed = Math.max(minSeconds, Math.ceil(seconds / incrementSeconds - 1e-9) * incrementSeconds);
522
- return (c.estimatedHourlyUsd * billed) / Math.max(seconds, 1) + (c.perSandboxUsd ?? 0) / Math.max(hours, 1 / 3600);
593
+ // Where the minimum covers memory only (Vercel), CPU is billed for the time actually used.
594
+ const cpu = minimumCovers === "memory" ? (c.cpuHourlyUsd ?? 0) : 0;
595
+ return ((c.estimatedHourlyUsd - cpu) * billed + cpu * seconds) / Math.max(seconds, 1) + (c.perSandboxUsd ?? 0) / Math.max(hours, 1 / 3600);
523
596
  }
524
597
  /** Seconds to wait for one provider's create before trying the next (RouteOptions.createTimeoutSeconds). */
525
598
  export const DEFAULT_CREATE_TIMEOUT_S = 120;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Sends a saved bench report to the public results as a pull request, with the GitHub CLI (`gh`): forks the
3
+ * repo if needed, puts the file in results/ on a new branch, and opens the PR. Returns the PR's URL.
4
+ * Nothing but the report file is sent; the report holds no keys (makeReport strips errors, and CI checks).
5
+ */
6
+ export declare function submitReport(file: string, summary: string): string;