@sandboxrouter/sdk 0.11.0 → 0.13.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.
@@ -5,6 +5,7 @@ export type RecPriority = "cost" | "speed" | "value";
5
5
  export interface PublishedStart {
6
6
  name: string;
7
7
  medianCreateMs: number;
8
+ medianReadyMs?: number;
8
9
  successRate: number;
9
10
  runs: number;
10
11
  hourlyUsd: number;
@@ -22,6 +23,8 @@ export interface PublishedJob {
22
23
  reusedUsd: number;
23
24
  successRate: number;
24
25
  runs: number;
26
+ ok?: number;
27
+ limited?: number;
25
28
  /** Bills at least this many seconds per sandbox. */
26
29
  minimumSeconds?: number;
27
30
  /** Fee per sandbox started. */
@@ -35,6 +38,14 @@ export interface PublishedLoadRow {
35
38
  ok: number;
36
39
  /** Of those that didn't start, how many the benchmarking account's own limit refused. */
37
40
  limited: number;
41
+ size?: {
42
+ vcpu: number;
43
+ memoryGb: number;
44
+ };
45
+ createFailures?: number;
46
+ commandFailures?: number;
47
+ taskFailures?: number;
48
+ cleanupFailures?: number;
38
49
  p50Ms?: number;
39
50
  p99Ms?: number;
40
51
  wallMs: number;
@@ -57,6 +68,12 @@ export interface PublishedData {
57
68
  start: Record<string, PublishedStart>;
58
69
  jobs: Partial<Record<Exclude<RecJob, "start">, Record<string, PublishedJob>>>;
59
70
  load: PublishedLoad[];
71
+ /** Start fees above included allowances. The benchmark estimates exclude these charges. */
72
+ conditionalStartFees?: Record<string, {
73
+ minUsd: number;
74
+ maxUsd: number;
75
+ source: string;
76
+ }>;
60
77
  }
61
78
  export interface RecommendOptions {
62
79
  /** The job to run. Default "short". */
package/dist/recommend.js CHANGED
@@ -31,11 +31,12 @@ export function recommend(data, opts = {}) {
31
31
  const loads = data.load.filter((l) => l.job === LOAD_JOB[job] && l.n <= count).sort((a, b) => b.n - a.n);
32
32
  const load = count >= 10 && !reuse ? loads[0] : undefined;
33
33
  const raw = [];
34
+ const startRows = Object.entries(data.start).filter(([id]) => !only || only.has(id));
35
+ // Use one timing definition across the cohort. Legacy reports did not store paired readiness.
36
+ const paired = startRows.length > 0 && startRows.every(([, s]) => s.medianReadyMs !== undefined);
34
37
  if (job === "start") {
35
- for (const [id, s] of Object.entries(data.start)) {
36
- if (only && !only.has(id))
37
- continue;
38
- raw.push({ provider: id, name: s.name, secondsEach: s.medianCreateMs / 1000, hourlyUsd: s.hourlyUsd, successRate: s.successRate, runs: s.runs, notes: [], measuredAt: s.measuredAt, usdKey: s.hourlyUsd });
38
+ for (const [id, s] of startRows) {
39
+ raw.push({ provider: id, name: s.name, secondsEach: (paired ? s.medianReadyMs : s.medianCreateMs) / 1000, hourlyUsd: s.hourlyUsd, successRate: s.successRate, runs: s.runs, notes: [], measuredAt: s.measuredAt, usdKey: s.hourlyUsd });
39
40
  }
40
41
  }
41
42
  else {
@@ -48,6 +49,8 @@ export function recommend(data, opts = {}) {
48
49
  notes.push(`bills at least ${j.minimumSeconds} s per sandbox`);
49
50
  if (!reuse && j.perSandboxUsd)
50
51
  notes.push(`$${j.perSandboxUsd} per sandbox started`);
52
+ if (j.limited)
53
+ notes.push(`${j.limited} reported limit refusals`);
51
54
  raw.push({
52
55
  provider: id,
53
56
  name: j.name,
@@ -64,6 +67,9 @@ export function recommend(data, opts = {}) {
64
67
  }
65
68
  const mostRuns = Math.max(1, ...raw.map((r) => r.runs));
66
69
  for (const r of raw) {
70
+ const fee = data.conditionalStartFees?.[r.provider];
71
+ if (!reuse && fee)
72
+ r.notes.push(`excludes $${fee.minUsd}–$${fee.maxUsd} per start above allowance`);
67
73
  if (r.runs < mostRuns / 2)
68
74
  r.notes.push(`only ${r.runs} runs`);
69
75
  if (r.successRate < 1)
@@ -78,12 +84,11 @@ export function recommend(data, opts = {}) {
78
84
  const startS = job === "start" ? r.secondsEach : r.secondsEach - (data.jobs[job]?.[r.provider]?.createMs ?? 0) / 1000;
79
85
  r.secondsEach = (job === "start" ? 0 : startS) + l.p50Ms / 1000;
80
86
  }
81
- else if (l && l.n - l.ok > l.limited) {
82
- // Some failed for reasons other than the benchmarking account's limit: the provider's own.
83
- r.notes.push(`${l.ok} of ${l.n} started at once`);
87
+ else if (l) {
88
+ r.notes.push(`${l.ok} of ${l.n} completed${l.limited ? ` (${l.limited} reported limit refusals)` : ""}`);
84
89
  }
85
90
  else {
86
- r.notes.push(`not measured at ${load.n} at once yet${l ? " (the benchmarking account's limit)" : ""}`);
91
+ r.notes.push(`not measured at ${load.n} at once yet`);
87
92
  }
88
93
  }
89
94
  const ok = (r) => Math.max(r.successRate, 0.01);
@@ -96,8 +101,9 @@ export function recommend(data, opts = {}) {
96
101
  const results = scored.slice(0, opts.limit ?? scored.length).map(({ usdKey: _, ...r }, i) => ({ ...r, rank: i + 1, valueScore: Math.round(r.valueScore * 100) / 100 }));
97
102
  const what = job === "start" ? "starting a sandbox" : `the ${job} job${reuse ? " in a running sandbox" : " in a new sandbox"}`;
98
103
  const by = priority === "cost" ? "lowest cost" : priority === "speed" ? "shortest time" : "best value (cost times time, each against the median)";
99
- const basis = `Ranked by ${by} for ${what}, per successful run` +
100
- (load ? `, with start times measured ${load.n} at once; providers not yet measured at that size come after` : "") +
101
- ".";
104
+ const basis = !results.length ? `No current verified results for ${what}.` :
105
+ `Ranked by ${by} for ${what} with a success-rate adjustment` +
106
+ (load ? `, with readiness measured on batches of ${load.n}; providers that did not finish the batch are listed after` : "") +
107
+ (job === "start" && !paired ? ". Single-request timings use the create response; the first command is measured separately" : "") + ".";
102
108
  return { job, count, priority, reuse, basis, dataThrough: data.dataThrough, results };
103
109
  }
package/dist/results.js CHANGED
@@ -2,7 +2,8 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
3
  import { benchmarksPublishable, CATALOG } from "./catalog.js";
4
4
  import { CHECK_STEPS } from "./check.js";
5
- import { taskByVersion } from "./task.js";
5
+ import { isCurrentTask, taskByVersion } from "./task.js";
6
+ import { AGENT_TASK_VERSION } from "./agent-bench.js";
6
7
  /** A GitHub handle, without the "@": what `--by` accepts and what reports store. */
7
8
  export function contributor(by) {
8
9
  if (by === undefined)
@@ -53,6 +54,8 @@ const IPV4 = /\b(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3
53
54
  /** "12 Main Street", "Calle Mayor 5", "Apt 4B": a street or a flat, which a label never needs. */
54
55
  const ADDRESS = /\b\d+[A-Za-z]?\s+(?:[A-Za-zÀ-ÿ'.-]+\s+){0,3}(?:street|st|road|rd|avenue|ave|lane|ln|drive|dr|way|court|ct|place|pl|boulevard|blvd|terrace|close)\b\.?|\b(?:calle|carrer|rue|via|avenida|straße|strasse|str)\.?\s+[A-Za-zÀ-ÿ'.-]+(?:\s+[A-Za-zÀ-ÿ'.-]+){0,3}\s+\d+|\b(?:apt|apartment|flat|suite|unit|piso|puerta)\.?\s*#?\d+/i;
55
56
  const isNum = (n, min = 0, max = Infinity) => typeof n === "number" && Number.isFinite(n) && n >= min && n <= max;
57
+ const isCount = (n, max) => Number.isInteger(n) && isNum(n, 0, max);
58
+ const isSize = (size) => isNum(size?.vcpu, 0.1, 1024) && isNum(size?.memoryGb, 0.0625, 4096);
56
59
  function checkDate(iso, now) {
57
60
  if (typeof iso !== "string" || Number.isNaN(Date.parse(iso)))
58
61
  return "date is missing or not an ISO date";
@@ -116,12 +119,34 @@ export function validateResult(j, now = Date.now()) {
116
119
  out.push(`${r?.provider}: failures must be between 0 and runs`);
117
120
  if (r?.limited !== undefined && !isNum(r.limited, 0, r?.failures ?? 0))
118
121
  out.push(`${r?.provider}: limited must be between 0 and failures`);
119
- for (const k of ["medianCreateMs", "medianExecMs"]) {
122
+ for (const k of ["medianCreateMs", "medianExecMs", "medianReadyMs", "medianTaskReadyMs"]) {
120
123
  if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
121
124
  out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
122
125
  }
123
126
  if (r?.failures < r?.runs && r?.medianCreateMs === undefined)
124
127
  out.push(`${r?.provider}: successful runs but no medianCreateMs`);
128
+ if (r?.size !== undefined && !isSize(r.size))
129
+ out.push(`${r?.provider}: invalid sandbox size`);
130
+ if (isCurrentTask(j.task)) {
131
+ if (!isSize(j.spec) || !isSize(r?.size))
132
+ out.push(`${r?.provider}: current tasks must record requested and nominal sizes`);
133
+ if (!isCount(r?.taskOk, (r?.runs ?? 0) - (r?.failures ?? 0)))
134
+ out.push(`${r?.provider}: invalid completed task count`);
135
+ if (r?.taskOk > 0 && (r.medianTaskMs === undefined || r.medianTaskReadyMs === undefined || !r.taskPhasesMs)) {
136
+ out.push(`${r.provider}: completed tasks require task and readiness timings`);
137
+ }
138
+ if (r?.taskOk === 0 && (r.medianTaskMs !== undefined || r.medianTaskReadyMs !== undefined || r.taskPhasesMs)) {
139
+ out.push(`${r.provider}: task timings require a completed task`);
140
+ }
141
+ }
142
+ if (r?.createFailures !== undefined || r?.commandFailures !== undefined) {
143
+ if (!isCount(r.createFailures, r.runs) || !isCount(r.commandFailures, r.runs) ||
144
+ r.createFailures + r.commandFailures !== r.failures || (r.limited ?? 0) > r.createFailures) {
145
+ out.push(`${r.provider}: create and command failure counts must reconcile with failures and limits`);
146
+ }
147
+ }
148
+ if (r?.cleanupFailures !== undefined && !isCount(r.cleanupFailures, r.runs))
149
+ out.push(`${r.provider}: invalid cleanup failure count`);
125
150
  if (r?.medianTaskMs !== undefined && !isNum(r.medianTaskMs, 1, MAX_MS))
126
151
  out.push(`${r?.provider}: medianTaskMs must be between 1 ms and 15 min`);
127
152
  if (r?.medianTaskCpuMs !== undefined && !isNum(r.medianTaskCpuMs, 0, 64 * MAX_MS))
@@ -179,6 +204,11 @@ export function validateResult(j, now = Date.now()) {
179
204
  out.push(`${r.provider}: ${NO_BENCH}`);
180
205
  if (!isNum(r?.ok, 0, r?.runs ?? 0))
181
206
  out.push(`${r?.provider}: ok must be between 0 and runs`);
207
+ if (j.task === AGENT_TASK_VERSION &&
208
+ (r?.requested !== j.runs || r.runs + (r.limited ?? 0) !== r.requested ||
209
+ !isCount(r.started, r.runs) || r.ok > r.started || !isSize(r.size))) {
210
+ out.push(`${r?.provider}: agent request, start, success counts and shape must reconcile`);
211
+ }
182
212
  if (r?.limited !== undefined && !isNum(r.limited, 0, 1000))
183
213
  out.push(`${r?.provider}: limited is out of range`);
184
214
  for (const k of ["medianWallMs", "medianModelMs", "medianCpuMs"]) {
@@ -207,6 +237,16 @@ export function validateResult(j, now = Date.now()) {
207
237
  out.push(`${r?.provider}: n must match the report's n`);
208
238
  if (!isNum(r?.ok, 0, j.n) || !isNum(r?.limited, 0, j.n) || r.ok + r.limited > j.n)
209
239
  out.push(`${r?.provider}: ok and limited must add up to at most n`);
240
+ if (r?.size !== undefined && !isSize(r.size))
241
+ out.push(`${r.provider}: invalid sandbox size`);
242
+ if (r?.createFailures !== undefined || r?.commandFailures !== undefined || r?.taskFailures !== undefined) {
243
+ if (![r.createFailures, r.commandFailures, r.taskFailures].every((n) => isCount(n, j.n)) ||
244
+ r.ok + r.createFailures + r.commandFailures + r.taskFailures !== j.n || r.limited > r.createFailures) {
245
+ out.push(`${r.provider}: burst failures, limits and completed requests do not reconcile`);
246
+ }
247
+ }
248
+ if (r?.cleanupFailures !== undefined && !isCount(r.cleanupFailures, j.n))
249
+ out.push(`${r.provider}: invalid cleanup failure count`);
210
250
  for (const k of ["p50Ms", "p95Ms", "p99Ms", "jobP50Ms"]) {
211
251
  if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
212
252
  out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
@@ -219,6 +259,36 @@ export function validateResult(j, now = Date.now()) {
219
259
  out.push(`${r?.provider}: sandboxes started but no p50Ms`);
220
260
  }
221
261
  }
262
+ else if (j.tool === "sandboxrouter-spread") {
263
+ add(checkDate(j.date, now));
264
+ add(checkLabel(j.label));
265
+ add(checkBy(j.by));
266
+ if (!isNum(j.n, 2, 10_000))
267
+ out.push("n must be between 2 and 10000");
268
+ if (!isNum(j.ok, 0, j.n) || !isNum(j.failed, 0, j.n) || j.ok + j.failed !== j.n)
269
+ out.push("ok and failed must add up to n");
270
+ for (const k of ["p50Ms", "p95Ms", "p99Ms"]) {
271
+ if (j[k] !== undefined && !isNum(j[k], 1, 4 * MAX_MS))
272
+ out.push(`${k} is out of range`);
273
+ }
274
+ if (!isNum(j.wallMs, 1, 4 * MAX_MS))
275
+ out.push("wallMs is out of range");
276
+ if (!isNum(j.usd, 0, 10_000))
277
+ out.push("usd is out of range");
278
+ if (!Array.isArray(j.byProvider) || j.byProvider.length < 2)
279
+ out.push("byProvider must list at least two providers");
280
+ let started = 0;
281
+ for (const b of Array.isArray(j.byProvider) ? j.byProvider : []) {
282
+ provider(b?.provider, "byProvider provider");
283
+ if (noBench(b?.provider))
284
+ out.push(`${b.provider}: ${NO_BENCH}`);
285
+ if (!isNum(b?.ok, 0, j.n) || !isNum(b?.spilledIn, 0, j.n) || !isNum(b?.refused, 0, 100 * j.n))
286
+ out.push(`${b?.provider}: counts out of range`);
287
+ started += b?.ok ?? 0;
288
+ }
289
+ if (started !== j.ok)
290
+ out.push("byProvider ok counts must add up to ok");
291
+ }
222
292
  else if (j.tool === "sandboxrouter-cost") {
223
293
  add(checkDate(j.date, now));
224
294
  add(checkBy(j.by));
@@ -242,7 +312,7 @@ export function validateResult(j, now = Date.now()) {
242
312
  }
243
313
  }
244
314
  else {
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`);
315
+ out.push(`unknown tool "${String(j.tool)}": expected a bench report, a burst report, a spread report, an agent report, a saved check or a cost run`);
246
316
  }
247
317
  return out;
248
318
  }
package/dist/router.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type ProviderInfo } from "./catalog.js";
1
2
  import { type ComputerRoute, RoutedComputer, type ComputerOs, type ComputerProvider, type ComputerProviderId, type ComputerSpec } from "./computers.js";
2
3
  import { Ledger } from "./ledger.js";
3
4
  import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxSpec } from "./types.js";
@@ -28,7 +29,7 @@ export interface Candidate {
28
29
  * asked for (2 vCPU / 4 GB when nothing was). Some providers round up to their next size.
29
30
  */
30
31
  size: Size;
31
- /** Median create time: this router's own recent creates when it has a few, else your `bench` file. */
32
+ /** Median create time from this router, your `bench` file or the published benchmarks, in that order. */
32
33
  medianCreateMs?: number;
33
34
  /** Passed the real-account check (as of this release, or `RouterOptions.verified`). */
34
35
  verified: boolean;
@@ -39,6 +40,10 @@ export interface Candidate {
39
40
  * spreads it over the run (`expectedSeconds`, else `timeoutMinutes`, default 30), so it weighs more on short ones.
40
41
  */
41
42
  perSandboxUsd?: number;
43
+ /** Account-specific start fees that the estimate and price cap exclude. */
44
+ conditionalStartFee?: ProviderInfo["pricing"]["conditionalStartFee"];
45
+ /** The compute estimate omits GPU charges when the request includes a GPU. */
46
+ excludesGpuCost?: true;
42
47
  /** Why this provider won't be tried, if it won't. */
43
48
  skip?: string;
44
49
  /** Set while the provider is at the back of the line after a limit or repeated failures (see `cooldown`). */
@@ -58,14 +63,20 @@ export interface Quote {
58
63
  runSeconds: number;
59
64
  /** What the run costs per hour once minimum charge, billing increment and per-sandbox charge are counted. */
60
65
  runHourlyUsd: number;
61
- /** What the run costs in all. */
66
+ /** Estimated charge for this run, excluding account-specific fees. */
62
67
  estimatedUsd: number;
63
68
  /** The provider bills at least this many seconds per sandbox. */
64
69
  minimumSeconds?: number;
70
+ /** Which components are subject to the minimum. */
71
+ minimumCovers?: "all" | "memory";
65
72
  /** The provider bills in whole steps of this many seconds. */
66
73
  billedInSecondsOf?: number;
67
74
  /** A fixed charge per sandbox started, included in `estimatedUsd`. */
68
75
  perSandboxUsd?: number;
76
+ /** Account-specific start fees that the estimate excludes. */
77
+ conditionalStartFee?: Candidate["conditionalStartFee"];
78
+ /** The compute estimate omits GPU charges when the request includes a GPU. */
79
+ excludesGpuCost?: true;
69
80
  /** The whole plan: every provider, in the order a create would try them, with why any are skipped. */
70
81
  candidates: Candidate[];
71
82
  }
@@ -294,5 +305,5 @@ export declare const DEFAULT_CREATE_TIMEOUT_S = 120;
294
305
  export declare const DEFAULT_CREATE_DEADLINE_S = 240;
295
306
  /** Seconds past a command's timeout before the router stops waiting for the adapter. */
296
307
  export declare const EXEC_GRACE_S = 30;
297
- /** The size a provider gives for a spec: its fixed default image size, else what was asked for. */
308
+ /** The size a provider gives for a spec, including fixed images and Vercel allocations. */
298
309
  export declare function sizeOf(id: ProviderId, spec?: SandboxSpec): Size;
package/dist/router.js CHANGED
@@ -1,4 +1,4 @@
1
- import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost, unfit } from "./catalog.js";
1
+ import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost, info, unfit, vercelSandboxSize } from "./catalog.js";
2
2
  import { RoutedComputer, createComputer, planComputer, } from "./computers.js";
3
3
  import { loadBench, median } from "./bench-store.js";
4
4
  import { PUBLISHED } from "./published.js";
@@ -186,6 +186,11 @@ export class Router {
186
186
  const fee = billingRules(id).perSandboxUsd;
187
187
  if (fee)
188
188
  c.perSandboxUsd = fee;
189
+ const conditionalStartFee = info(id).pricing.conditionalStartFee;
190
+ if (conditionalStartFee)
191
+ c.conditionalStartFee = { ...conditionalStartFee };
192
+ if (spec.gpu)
193
+ c.excludesGpuCost = true;
189
194
  if (!p)
190
195
  c.skip = "no adapter registered";
191
196
  else {
@@ -196,9 +201,13 @@ export class Router {
196
201
  (this.requireVerified && !c.verified ? "not tested (this router only uses providers that passed the real-account check)" : undefined);
197
202
  }
198
203
  if (!c.skip && route.maxHourlyUsd !== undefined) {
199
- const rate = rankUsd(c, runHours(spec));
200
- if (rate > route.maxHourlyUsd)
201
- c.skip = `${OVER_CAP}: ${usdPerHour(rate)} for this run, cap ${usdPerHour(route.maxHourlyUsd)}`;
204
+ if (c.excludesGpuCost)
205
+ c.skip = "cannot verify maxHourlyUsd because GPU charges are not modelled";
206
+ else {
207
+ const rate = rankUsd(c, runHours(spec));
208
+ if (rate > route.maxHourlyUsd)
209
+ c.skip = `${OVER_CAP}: ${usdPerHour(rate)} for this run, cap ${usdPerHour(route.maxHourlyUsd)}`;
210
+ }
202
211
  }
203
212
  return c;
204
213
  });
@@ -319,9 +328,11 @@ export class Router {
319
328
  runSeconds: Math.round(hours * 3600),
320
329
  runHourlyUsd,
321
330
  estimatedUsd: runHourlyUsd * hours,
322
- ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds } : {}),
331
+ ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds, minimumCovers: rules.minimumCovers } : {}),
323
332
  ...(rules.incrementSeconds > 1 ? { billedInSecondsOf: rules.incrementSeconds } : {}),
324
333
  ...(first.perSandboxUsd ? { perSandboxUsd: first.perSandboxUsd } : {}),
334
+ ...(first.conditionalStartFee ? { conditionalStartFee: first.conditionalStartFee } : {}),
335
+ ...(first.excludesGpuCost ? { excludesGpuCost: true } : {}),
325
336
  candidates,
326
337
  };
327
338
  }
@@ -600,7 +611,9 @@ export const DEFAULT_CREATE_TIMEOUT_S = 120;
600
611
  export const DEFAULT_CREATE_DEADLINE_S = 240;
601
612
  /** Seconds past a command's timeout before the router stops waiting for the adapter. */
602
613
  export const EXEC_GRACE_S = 30;
603
- /** The size a provider gives for a spec: its fixed default image size, else what was asked for. */
614
+ /** The size a provider gives for a spec, including fixed images and Vercel allocations. */
604
615
  export function sizeOf(id, spec = {}) {
616
+ if (id === "vercel")
617
+ return vercelSandboxSize(spec);
605
618
  return fixedSize(id, spec) ?? { vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB };
606
619
  }
package/dist/task.d.ts CHANGED
@@ -44,7 +44,8 @@ export declare const TASK_VERSION: string;
44
44
  export declare const TASK_PHASES: TaskPhaseDef[];
45
45
  /** Milliseconds per phase, by phase id. */
46
46
  export type PhaseMs = Record<string, number>;
47
- /** The task a report's `task` version names, if it's one this release knows. */
47
+ export declare const isCurrentTask: (version: unknown) => boolean;
48
+ /** Legacy reports keep their original phase schema for validation and archival. */
48
49
  export declare function taskByVersion(version: unknown): (typeof TASKS)[TaskKind] | undefined;
49
50
  /** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
50
51
  export declare function phaseCommand(cmd: string, repeat: number): string;
package/dist/task.js CHANGED
@@ -1,11 +1,22 @@
1
1
  import { billingRules, cpuHourlyAtFull, hourlyCost, info } from "./catalog.js";
2
+ const ZERO_256_SHA256 = "a6d72ac7690f53be6ae46ba88506bd97302a093f7108472bd9efc3cefda06484";
3
+ const ZERO_512_SHA256 = "9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767";
4
+ const hashZeros = (count, hash) => `hash=$(head -c ${count} /dev/zero | sha256sum) && [ "${'${hash%% *}'}" = "${hash}" ]`;
2
5
  const HASH_DISK = [
3
6
  // One core: hash 512 MB of zeros.
4
- { id: "cpu", label: "1 core", cmd: "head -c 536870912 /dev/zero | sha256sum > /dev/null" },
7
+ { id: "cpu", label: "1 core", cmd: hashZeros(536870912, ZERO_512_SHA256) },
5
8
  // Two cores at once (bench asks for 2 vCPU), 256 MB each: shows whether the second vCPU is real.
6
- { id: "cores", label: "2 cores", cmd: "for i in 1 2; do (head -c 268435456 /dev/zero | sha256sum > /dev/null) & done; wait" },
9
+ {
10
+ id: "cores",
11
+ label: "2 cores",
12
+ cmd: `(${hashZeros(268435456, ZERO_256_SHA256)}) & left=$!; (${hashZeros(268435456, ZERO_256_SHA256)}) & right=$!; wait "$left"; l=$?; wait "$right"; r=$?; [ "$l" = 0 ] && [ "$r" = 0 ]`,
13
+ },
7
14
  // Write 256 MB and flush it to disk, then delete it.
8
- { id: "disk", label: "disk", cmd: "dd if=/dev/zero of=/tmp/sr-task bs=1048576 count=256 conv=fsync 2> /dev/null; rm -f /tmp/sr-task" },
15
+ {
16
+ id: "disk",
17
+ label: "disk",
18
+ cmd: 'f=$(mktemp /tmp/sr-task.XXXXXX) || exit $?; dd if=/dev/zero of="$f" bs=1048576 count=256 conv=fsync 2> /dev/null && [ "$(wc -c < "$f")" -eq 268435456 ]; rc=$?; rm -f "$f" || exit $?; exit "$rc"',
19
+ },
9
20
  ];
10
21
  // 200,000 small records through JSON, a regex and a sort: the kind of thing a code-interpreter call does.
11
22
  const PYTHON = [
@@ -15,7 +26,7 @@ const PYTHON = [
15
26
  "back = json.loads(json.dumps(rows))",
16
27
  "hits = sum(1 for r in back if re.search('abc', r['name']))",
17
28
  "top = sorted(back, key=lambda r: (r['name'], r['v']))[:10]",
18
- "print(hits, top[0]['id'])",
29
+ "if (hits, top[0]['id']) != (2837, 68550): raise SystemExit('Python output check failed')",
19
30
  ].join("\n");
20
31
  // The Node.js 22.11.0 Linux release (53 MB), from nodejs.org's CDN: a real download, like installing a toolchain.
21
32
  const DOWNLOAD_URL = "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-x64.tar.gz";
@@ -28,20 +39,22 @@ const FETCH = [
28
39
  'case "$(uname -m)" in aarch64|arm64) A=arm64 ;; *) A=x64 ;; esac',
29
40
  `get() { if command -v curl > /dev/null; then curl -sSfL -o "$2" "$1"; elif command -v wget > /dev/null; then wget -q -O "$2" "$1"; else python3 -c "import shutil, sys, urllib.request; shutil.copyfileobj(urllib.request.urlopen(sys.argv[1]), open(sys.argv[2], 'wb'))" "$1" "$2"; fi; }`,
30
41
  "rm -rf /tmp/sr-node /tmp/sr-repo && mkdir -p /tmp/sr-node /tmp/sr-repo",
31
- `get "${NODE_BASE}-$A.tar.gz" /tmp/sr-node.tgz && tar xzf /tmp/sr-node.tgz -C /tmp/sr-node --strip-components=1`,
32
- `get "${REPO_TARBALL}" /tmp/sr-repo.tgz && tar xzf /tmp/sr-repo.tgz -C /tmp/sr-repo --strip-components=1`,
33
- "set +e",
42
+ `get "${NODE_BASE}-$A.tar.gz" /tmp/sr-node.tgz || exit $?`,
43
+ "tar xzf /tmp/sr-node.tgz -C /tmp/sr-node --strip-components=1",
44
+ `get "${REPO_TARBALL}" /tmp/sr-repo.tgz || exit $?`,
45
+ "tar xzf /tmp/sr-repo.tgz -C /tmp/sr-repo --strip-components=1",
46
+ "test -x /tmp/sr-node/bin/node && test -f /tmp/sr-repo/package-lock.json",
34
47
  ].join("\n");
35
48
  const IN_REPO = "cd /tmp/sr-repo && PATH=/tmp/sr-node/bin:$PATH";
36
49
  // One tool call in the agent loop: a little real work, like reading files and running a check.
37
50
  const TOOL = "import json, hashlib; d = [{'i': i, 'h': hashlib.sha256(str(i).encode()).hexdigest()} for i in range(40000)]; print(len(json.dumps(d)))";
38
51
  /** `cpuUtilization`: the hint the job's sandboxes start with (the agent loop is mostly idle), which Modal reserves and pricing uses. */
39
52
  export const TASKS = {
40
- short: { version: "v1", repeat: 1, phases: HASH_DISK },
41
- long: { version: "v1-long", repeat: 40, phases: HASH_DISK },
42
- python: { version: "python-v1", repeat: 1, phases: [{ id: "python", label: "Python", cmd: `python3 -c "${PYTHON}"` }] },
53
+ short: { version: "v2", repeat: 1, phases: HASH_DISK },
54
+ long: { version: "v2-long", repeat: 40, phases: HASH_DISK },
55
+ python: { version: "python-v2", repeat: 1, phases: [{ id: "python", label: "Python", cmd: `python3 -c "${PYTHON}"` }] },
43
56
  repo: {
44
- version: "repo-v1",
57
+ version: "repo-v2",
45
58
  repeat: 1,
46
59
  phases: [
47
60
  { id: "fetch", label: "fetch Node and the repo", cmd: FETCH, timeoutSeconds: 600 },
@@ -50,13 +63,13 @@ export const TASKS = {
50
63
  ],
51
64
  },
52
65
  agent: {
53
- version: "agent-v1",
66
+ version: "agent-v2",
54
67
  repeat: 1,
55
68
  cpuUtilization: 0.1,
56
- phases: [{ id: "agent", label: "10 turns", cmd: `n=0; while [ $n -lt 10 ]; do sleep 6; python3 -c "${TOOL}" > /dev/null; n=$((n+1)); done` }],
69
+ phases: [{ id: "agent", label: "10 turns", cmd: `n=0; while [ $n -lt 10 ]; do sleep 6 && python3 -c "${TOOL}" > /dev/null || exit $?; n=$((n+1)); done` }],
57
70
  },
58
71
  download: {
59
- version: "download-v1",
72
+ version: "download-v2",
60
73
  repeat: 1,
61
74
  phases: [
62
75
  {
@@ -72,20 +85,25 @@ export const TASKS = {
72
85
  /** The short task's version and phases, which is what plain `bench --task` records. */
73
86
  export const TASK_VERSION = TASKS.short.version;
74
87
  export const TASK_PHASES = TASKS.short.phases;
75
- /** The task a report's `task` version names, if it's one this release knows. */
88
+ const LEGACY_TASKS = {
89
+ v1: "short", "v1-long": "long", "python-v1": "python", "repo-v1": "repo", "agent-v1": "agent", "download-v1": "download",
90
+ };
91
+ export const isCurrentTask = (version) => Object.values(TASKS).some((t) => t.version === version);
92
+ /** Legacy reports keep their original phase schema for validation and archival. */
76
93
  export function taskByVersion(version) {
77
- return Object.values(TASKS).find((t) => t.version === version);
94
+ return Object.values(TASKS).find((t) => t.version === version) ??
95
+ (typeof version === "string" && Object.hasOwn(LEGACY_TASKS, version) ? TASKS[LEGACY_TASKS[version]] : undefined);
78
96
  }
79
97
  /** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
80
98
  export function phaseCommand(cmd, repeat) {
81
- return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do ${cmd}; n=$((n+1)); done`;
99
+ return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do (${cmd}) || exit $?; n=$((n+1)); done`;
82
100
  }
83
101
  // Wraps a phase to read /proc/stat's total CPU line before and after it, so the run also reports the CPU
84
102
  // time it really used: what providers that bill active CPU charge for.
85
103
  const MARK = "SRCPU";
86
104
  // Every "cpu" line (the total, then one per core), joined with ";" so the reading stays on one output line.
87
105
  const STAT = `grep '^cpu' /proc/stat 2> /dev/null | tr '\\n' ';'`;
88
- const withCpu = (cmd) => `a=$(${STAT}); ${cmd}; rc=$?; b=$(${STAT}); echo "${MARK}|$a|$b"; exit $rc`;
106
+ const withCpu = (cmd) => `a=$(${STAT}); (${cmd}); rc=$?; b=$(${STAT}); echo "${MARK}|$a|$b"; exit $rc`;
89
107
  /** Busy ticks on one /proc/stat cpu line: user, nice, system, irq and softirq (not idle, iowait or steal). */
90
108
  const lineTicks = (line) => {
91
109
  const f = line.trim().split(/\s+/);
@@ -118,7 +136,8 @@ export async function runTask(box, kind = "short") {
118
136
  const rtt = [];
119
137
  for (let i = 0; i < 3; i++) {
120
138
  const t = performance.now();
121
- await box.exec("true");
139
+ if ((await box.exec("true")).exitCode !== 0)
140
+ throw new Error("task round-trip probe failed");
122
141
  rtt.push(performance.now() - t);
123
142
  }
124
143
  const overhead = rtt.sort((a, b) => a - b)[1];
package/dist/types.d.ts CHANGED
@@ -79,10 +79,11 @@ export interface RouteOptions {
79
79
  /** Capabilities every candidate must have. */
80
80
  require?: Capability[];
81
81
  /**
82
- * The most this sandbox may cost, in USD per hour. A provider is skipped when this run would cost more
83
- * there, priced the way ranking prices it: hourly price, minimum charge and billing increment over
82
+ * An estimated effective hourly price limit for routing, in USD. A provider is skipped when this run
83
+ * is estimated to cost more there: hourly price, minimum charge and billing increment over
84
84
  * `expectedSeconds` (else `timeoutMinutes`, default 30), plus any per-sandbox charge, divided by the
85
- * run's hours. Omit for no cap.
85
+ * run's hours. This does not stop the sandbox or enforce a budget. Requests with unpriced GPU
86
+ * charges cannot use this limit. Omit for no cap.
86
87
  */
87
88
  maxHourlyUsd?: number;
88
89
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.11.0",
3
+ "version": "0.13.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",
@@ -24,7 +24,8 @@
24
24
  "test": "vitest run",
25
25
  "typecheck": "tsc --noEmit",
26
26
  "dev": "tsx src/cli.ts",
27
- "prepublishOnly": "npm run build && npm test",
27
+ "prepublishOnly": "npm run test:package && npm test",
28
+ "test:package": "npm run build && node scripts/check-package.mjs",
28
29
  "test:py": "python3 -m unittest discover -s python/tests -v",
29
30
  "site:data": "node --import tsx scripts/site-data.ts",
30
31
  "price:check": "node --import tsx scripts/price-watch.ts",
@@ -201,5 +202,19 @@
201
202
  "type": "git",
202
203
  "url": "git+https://github.com/gigialc/sandboxrouter.git"
203
204
  },
204
- "homepage": "https://sandboxrouter.ai"
205
+ "homepage": "https://sandboxrouter.ai",
206
+ "overrides": {
207
+ "@hey-api/json-schema-ref-parser": {
208
+ "js-yaml": "^4.3.2"
209
+ },
210
+ "@hopx-ai/sdk": {
211
+ "glob": "^14.0.2"
212
+ },
213
+ "@vercel/cli-config": {
214
+ "zod": "^4.6.6"
215
+ },
216
+ "archiver-utils": {
217
+ "glob": "^14.0.2"
218
+ }
219
+ }
205
220
  }