@sandboxrouter/sdk 0.12.0 → 0.14.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 +13 -8
  2. package/dist/agent-bench.d.ts +12 -1
  3. package/dist/agent-bench.js +46 -7
  4. package/dist/bench.d.ts +13 -1
  5. package/dist/bench.js +39 -17
  6. package/dist/billing.js +0 -1
  7. package/dist/burst.d.ts +10 -0
  8. package/dist/burst.js +21 -10
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +34 -16
  11. package/dist/cli.js +47 -37
  12. package/dist/client.d.ts +6 -1
  13. package/dist/client.js +19 -0
  14. package/dist/computers.d.ts +2 -2
  15. package/dist/cost.d.ts +44 -5
  16. package/dist/cost.js +54 -24
  17. package/dist/leaderboard.d.ts +30 -8
  18. package/dist/leaderboard.js +89 -50
  19. package/dist/price-index.d.ts +3 -3
  20. package/dist/price-index.js +3 -3
  21. package/dist/providers/blaxel.d.ts +1 -0
  22. package/dist/providers/blaxel.js +56 -1
  23. package/dist/providers/daytona.js +33 -1
  24. package/dist/providers/deno.d.ts +3 -0
  25. package/dist/providers/deno.js +14 -0
  26. package/dist/providers/docker.d.ts +1 -0
  27. package/dist/providers/docker.js +30 -3
  28. package/dist/providers/e2b.d.ts +22 -1
  29. package/dist/providers/e2b.js +50 -3
  30. package/dist/providers/hopx.js +12 -0
  31. package/dist/providers/limrun.d.ts +1 -8
  32. package/dist/providers/limrun.js +0 -1
  33. package/dist/providers/mobilerun.d.ts +1 -5
  34. package/dist/providers/mobilerun.js +18 -26
  35. package/dist/providers/modal.js +7 -0
  36. package/dist/providers/novita.js +5 -5
  37. package/dist/providers/sail.js +4 -4
  38. package/dist/providers/vercel.js +41 -3
  39. package/dist/published.js +639 -1283
  40. package/dist/recommend.d.ts +17 -0
  41. package/dist/recommend.js +17 -11
  42. package/dist/results.d.ts +2 -2
  43. package/dist/results.js +104 -3
  44. package/dist/router.d.ts +22 -8
  45. package/dist/router.js +58 -11
  46. package/dist/server.d.ts +4 -1
  47. package/dist/server.js +101 -7
  48. package/dist/task.d.ts +2 -1
  49. package/dist/task.js +38 -19
  50. package/dist/types.d.ts +20 -4
  51. package/dist/validate.d.ts +4 -2
  52. package/dist/validate.js +18 -1
  53. package/package.json +18 -3
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { parseArgs } from "node:util";
3
3
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { platform, arch } from "node:os";
5
- import { ACCOUNT_ERROR, bench, benchMarkdown, NETWORK_ERROR } from "./bench.js";
5
+ import { bench, benchMarkdown, NETWORK_ERROR } from "./bench.js";
6
6
  import { TASKS } from "./task.js";
7
7
  import { submitReport } from "./submit.js";
8
8
  import { burst, spreadBurst } from "./burst.js";
@@ -70,7 +70,7 @@ Usage:
70
70
  sandboxrouter serve [--port 8787] [--host 127.0.0.1] [--cors https://site.example,http://localhost:3000]
71
71
 
72
72
  Spec flags: --vcpu N --memory GB --gpu T4 --timeout MIN --expect SEC (how long you'll use it; ranks by the real bill)
73
- --cpu 0.1 (how busy the CPU is, 0-1; lowers providers that bill active CPU)
73
+ --cpu 0.1 (how busy the CPU is, 0-1; lowers providers that bill active CPU) --ports 3000,8080
74
74
  Route flags: --provider e2b[,modal,...] --strategy balanced|verified|cheapest|fastest (default balanced: cheapest real cost, speed breaks near-ties)
75
75
  --max-price USD (per hour, for this run: skip providers that would cost more)
76
76
  --no-fallback --fallback-any (also on setup errors like a bad key)
@@ -83,6 +83,7 @@ const { values, positionals } = parseArgs({
83
83
  options: {
84
84
  vcpu: { type: "string" },
85
85
  memory: { type: "string" },
86
+ ports: { type: "string" },
86
87
  gpu: { type: "string" },
87
88
  timeout: { type: "string" },
88
89
  expect: { type: "string" },
@@ -142,6 +143,7 @@ const num = (s) => (s === undefined ? undefined : Number(s));
142
143
  const spec = {
143
144
  vcpu: num(values.vcpu),
144
145
  memoryGb: num(values.memory),
146
+ ports: list(values.ports)?.map(Number),
145
147
  gpu: values.gpu,
146
148
  timeoutMinutes: num(values.timeout),
147
149
  expectedSeconds: num(values.expect),
@@ -254,13 +256,18 @@ async function main() {
254
256
  if (values.json)
255
257
  return console.log(JSON.stringify({ ...q, candidates: undefined }, null, 2));
256
258
  const rules = [
257
- q.minimumSeconds ? `at least ${q.minimumSeconds} s billed` : "",
259
+ q.minimumSeconds ? `at least ${q.minimumSeconds} s billed${q.minimumCovers === "memory" ? " for memory" : ""}` : "",
258
260
  q.billedInSecondsOf ? `billed in steps of ${q.billedInSecondsOf} s` : "",
259
261
  q.perSandboxUsd ? `$${q.perSandboxUsd} per sandbox` : "",
260
262
  ].filter(Boolean);
261
263
  console.log(`${q.provider}, ${q.size.vcpu} vCPU / ${q.size.memoryGb} GB`);
262
264
  console.log(`price $${q.hourlyUsd.toFixed(4)}/hr${rules.length ? ` (${rules.join(", ")})` : ""}`);
263
265
  console.log(`this run ${q.runSeconds} s ≈ $${q.estimatedUsd.toFixed(6)} ($${q.runHourlyUsd.toFixed(4)}/hr)`);
266
+ const extra = q.conditionalStartFee;
267
+ if (extra)
268
+ console.log(`Excludes $${extra.minUsd}–$${extra.maxUsd} per start above your allowance. ${extra.source}`);
269
+ if (q.excludesGpuCost)
270
+ console.log("The estimate excludes GPU charges. Check your provider's GPU rates.");
264
271
  const next = q.candidates.filter((c) => !c.skip && c.provider !== q.provider).slice(0, 3).map((c) => c.provider);
265
272
  if (next.length)
266
273
  console.log(`fallback ${next.join(" → ")}`);
@@ -282,7 +289,10 @@ async function main() {
282
289
  // With --expect, what that run would be billed (minimum charge and fee included): what it's ranked by.
283
290
  const hours = runHours(spec);
284
291
  const run = spec.expectedSeconds ? ` ≈ $${(rankUsd(c, hours) * hours).toFixed(6)} for ${Math.round(hours * 3600)} s` : "";
285
- const cols = [`$${c.estimatedHourlyUsd.toFixed(4)}/hr${list}${fee}${run}`, size, speed, tested].filter(Boolean).join(" ");
292
+ const extra = c.conditionalStartFee;
293
+ const feeNote = extra ? `excludes $${extra.minUsd}–$${extra.maxUsd} per start above allowance` : "";
294
+ const gpuNote = c.excludesGpuCost ? "excludes GPU charges" : "";
295
+ const cols = [`$${c.estimatedHourlyUsd.toFixed(4)}/hr${list}${fee}${run}`, size, speed, tested, feeNote, gpuNote].filter(Boolean).join(" ");
286
296
  console.log(`${mark} ${c.provider.padEnd(11)} ${cols}${c.skip ? ` (skipped: ${c.skip})` : ""}`);
287
297
  }
288
298
  return;
@@ -301,7 +311,7 @@ async function main() {
301
311
  process.once("SIGINT", stop);
302
312
  for (const a of sbx.attempts.filter((a) => !a.ok))
303
313
  console.error(`! ${a.provider} failed, fell back: ${a.error}`);
304
- console.error(`> ${sbx.id} on ${sbx.provider} (~$${sbx.estimatedHourlyUsd}/hr, started in ${sbx.attempts.at(-1)?.ms} ms)`);
314
+ console.error(`> ${sbx.id} on ${sbx.provider} (~$${sbx.estimatedHourlyUsd}/hr${spec.gpu ? " excluding GPU charges" : ""}, started in ${sbx.attempts.at(-1)?.ms} ms)`);
305
315
  try {
306
316
  const r = await sbx.exec(command, {
307
317
  timeoutSeconds: 600,
@@ -321,9 +331,15 @@ async function main() {
321
331
  if (cmd === "check") {
322
332
  const ids = values.all ? router.registered().filter((id) => router.isConfigured(id)) : providers;
323
333
  if (!ids?.length) {
324
- if (values.all)
325
- return console.log("No providers configured: set at least one provider's keys (sandboxrouter providers lists them).");
326
- throw new RouterError("usage: sandboxrouter check --provider <id>[,<id>...] | --all");
334
+ if (!values.all)
335
+ throw new RouterError("usage: sandboxrouter check --provider <id>[,<id>...] | --all");
336
+ console.error("No providers configured: set at least one provider's keys (sandboxrouter providers lists them).");
337
+ if (values.out)
338
+ writeFileSync(values.out, "[]\n");
339
+ if (values.json)
340
+ console.log("[]");
341
+ process.exitCode = 1;
342
+ return;
327
343
  }
328
344
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
329
345
  const saveDir = values.save ? (rest[0] ?? "results/conformance") : undefined;
@@ -359,16 +375,16 @@ async function main() {
359
375
  writeFileSync(`${saveDir}/${p}.json`, JSON.stringify(saved, null, 2) + "\n");
360
376
  }
361
377
  }
378
+ const ran = reports.filter((r) => !r.inconclusive);
362
379
  if (values.out)
363
380
  writeFileSync(values.out, JSON.stringify(reports, null, 2) + "\n");
364
381
  if (values.json)
365
382
  console.log(JSON.stringify(reports, null, 2));
366
383
  else {
367
- const unpaid = reports.filter((r) => r.inconclusive).length;
368
- const ran = reports.length - unpaid;
369
- console.log(`\n${reports.filter((r) => r.ok).length}/${ran} passed${unpaid ? `; ${unpaid} not run (the account can't pay, or the provider's package isn't installed)` : ""}`);
384
+ const skipped = reports.length - ran.length;
385
+ console.log(`\n${ran.filter((r) => r.ok).length}/${ran.length} passed${skipped ? `; ${skipped} not run (the account can't pay, or the provider's package isn't installed)` : ""}`);
370
386
  }
371
- if (reports.some((r) => !r.ok && !r.inconclusive))
387
+ if (!ran.length || ran.some((r) => !r.ok))
372
388
  process.exitCode = 1;
373
389
  return;
374
390
  }
@@ -405,10 +421,22 @@ async function main() {
405
421
  }
406
422
  if (cmd === "agentbench") {
407
423
  const apiKey = process.env.GEMINI_API_KEY;
408
- if (!apiKey)
409
- return console.error("agentbench needs GEMINI_API_KEY (it stays on this machine; only shell commands reach the sandbox)");
424
+ if (!apiKey) {
425
+ console.error("agentbench needs GEMINI_API_KEY (it stays on this machine; only shell commands reach the sandbox)");
426
+ if (values.json)
427
+ console.log("[]");
428
+ process.exitCode = 1;
429
+ return;
430
+ }
410
431
  const model = values.model ?? "gemini-3.5-flash";
411
432
  const ids = providers ?? router.registered().filter((id) => router.isConfigured(id));
433
+ if (!ids.length) {
434
+ console.error("agentbench has no configured providers (sandboxrouter providers lists them).");
435
+ if (values.json)
436
+ console.log("[]");
437
+ process.exitCode = 1;
438
+ return;
439
+ }
412
440
  const rows = await agentBench({ router, providers: ids, runs: num(values.runs) ?? 5, apiKey, model, parallel: num(values.parallel), onProgress: (m) => console.error(m) });
413
441
  if (values.json)
414
442
  return console.log(JSON.stringify(rows, null, 2));
@@ -416,14 +444,8 @@ async function main() {
416
444
  console.log("| Provider | Done right | Wall | Waiting on model | Sandbox CPU | Turns | Sandbox cost |\n|---|---|---|---|---|---|---|");
417
445
  const s = (v) => (v === undefined ? "n/a" : `${(v / 1000).toFixed(1)} s`);
418
446
  for (const r of rows)
419
- console.log(`| ${r.provider} | ${r.ok}/${r.runs} | ${s(r.medianWallMs)} | ${s(r.medianModelMs)} | ${s(r.medianCpuMs)} | ${r.medianTurns ?? "n/a"} | ${r.medianUsd === undefined ? "n/a" : `$${r.medianUsd.toFixed(6)}`} |`);
447
+ console.log(`| ${r.provider} | ${r.ok}/${r.requested ?? r.runs}${r.limited ? ` (${r.limited} refused)` : ""} | ${s(r.medianWallMs)} | ${s(r.medianModelMs)} | ${s(r.medianCpuMs)} | ${r.medianTurns ?? "n/a"} | ${r.medianUsd === undefined ? "n/a" : `$${r.medianUsd.toFixed(6)}`} |`);
420
448
  if (values.share || values.submit) {
421
- const started = rows.filter((r) => r.medianWallMs !== undefined);
422
- if (rows.length - started.length >= 3) {
423
- console.error(`\nnot writing a report: ${rows.length - started.length} providers never started a session, which looks like this machine lost its connection. Run it again.`);
424
- process.exitCode = 1;
425
- return;
426
- }
427
449
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
428
450
  const report = {
429
451
  tool: "sandboxrouter-agent",
@@ -436,7 +458,7 @@ async function main() {
436
458
  runs: num(values.runs) ?? 5,
437
459
  node: process.version,
438
460
  platform: `${platform()}-${arch()}`,
439
- rows: started.filter((r) => benchmarksPublishable(r.provider)),
461
+ rows: rows.filter((r) => benchmarksPublishable(r.provider)),
440
462
  };
441
463
  const file = values.out ?? `sandboxrouter-agent-${report.date.slice(0, 10)}-${Math.random().toString(36).slice(2, 8)}.json`;
442
464
  writeFileSync(file, JSON.stringify(report, null, 2) + "\n");
@@ -480,14 +502,12 @@ async function main() {
480
502
  if (values.json)
481
503
  return console.log(JSON.stringify(rows, null, 2));
482
504
  console.log(`\nsandboxrouter burst: ${n} at once${job ? `, each running the ${job} job` : ""}\n`);
483
- console.log("| Provider | Started | p50 | p95 | p99 | All done | Burst cost |\n|---|---|---|---|---|---|---|");
505
+ console.log(`| Provider | ${job ? "Completed jobs" : "Ready"} | p50 ready | p95 ready | p99 ready | Last outcome | Est. cost of successes |\n|---|---|---|---|---|---|---|`);
484
506
  for (const r of rows) {
485
507
  const ms = (v) => (v === undefined ? "n/a" : `${v} ms`);
486
508
  console.log(`| ${r.provider} | ${r.ok}/${r.n}${r.limited ? ` (${r.limited} limited)` : ""} | ${ms(r.p50Ms)} | ${ms(r.p95Ms)} | ${ms(r.p99Ms)} | ${(r.wallMs / 1000).toFixed(1)} s | ${r.usd === undefined ? "n/a" : `$${r.usd.toFixed(4)}`} |`);
487
509
  }
488
510
  if (values.share || values.submit) {
489
- // As with bench: nothing from a run where this machine lost its connection, and no provider that never answered.
490
- const shared = rows.filter((r) => r.ok > 0 || r.limited > 0);
491
511
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
492
512
  const report = {
493
513
  tool: "sandboxrouter-burst",
@@ -499,13 +519,8 @@ async function main() {
499
519
  ...(job ? { task: TASKS[job].version } : {}),
500
520
  node: process.version,
501
521
  platform: `${platform()}-${arch()}`,
502
- rows: shared.filter((r) => benchmarksPublishable(r.provider)),
522
+ rows: rows.filter((r) => benchmarksPublishable(r.provider)),
503
523
  };
504
- if (rows.length - shared.length >= 3) {
505
- console.error(`\nnot writing a report: ${rows.length - shared.length} providers started nothing, which looks like this machine lost its connection. Run it again.`);
506
- process.exitCode = 1;
507
- return;
508
- }
509
524
  const file = values.out ?? `sandboxrouter-burst-${report.date.slice(0, 10)}-${Math.random().toString(36).slice(2, 8)}.json`;
510
525
  writeFileSync(file, JSON.stringify(report, null, 2) + "\n");
511
526
  if (values.submit) {
@@ -552,12 +567,7 @@ async function main() {
552
567
  }
553
568
  else if (values.share || values.submit) {
554
569
  const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
555
- // A provider whose every run failed on the submitter's own account (bad key, no credit, a limit hit) says
556
- // nothing about the provider: leave it out of what's shared, and say so.
557
- const account = rows.filter((r) => r.failures === r.runs && r.lastError && ACCOUNT_ERROR.test(r.lastError));
558
- if (account.length)
559
- console.error(`\nleft out of the shared report, every run failed on your account: ${account.map((r) => r.provider).join(", ")}`);
560
- const report = makeReport(rows.filter((r) => !account.includes(r)), { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by, task: values.task ? TASKS[job].version : undefined });
570
+ const report = makeReport(rows, { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by, task: values.task ? TASKS[job].version : undefined });
561
571
  const left = rows.filter((r) => !benchmarksPublishable(r.provider)).map((r) => r.provider);
562
572
  if (left.length)
563
573
  console.log(`\nleft out of the shared report: ${left.join(", ")} (their terms don't allow publishing benchmarks)`);
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Candidate, Quote, Size } from "./router.js";
2
- import type { Attempt, ExecOptions, ExecResult, RouteOptions, RouterErrorCode, SandboxSpec } from "./types.js";
2
+ import type { Attempt, Capability, ExecOptions, ExecResult, RouteOptions, RouterErrorCode, SandboxProcess, SandboxSpec, StartOptions } from "./types.js";
3
3
  /**
4
4
  * Client for the sandboxrouter HTTP API: the hosted service (one key, prepaid credits) or your own
5
5
  * `sandboxrouter serve`. Provider keys live on the server; this side only needs the one key.
@@ -28,6 +28,7 @@ export declare class Client {
28
28
  estimatedHourlyUsd: number;
29
29
  listHourlyUsd: number;
30
30
  size: Size;
31
+ capabilities?: Capability[];
31
32
  }[]>;
32
33
  /** Dry run: which providers would be tried, in order, each with its price, size and any reason it's skipped. */
33
34
  route(spec?: SandboxSpec, route?: RouteOptions): Promise<Candidate[]>;
@@ -78,6 +79,10 @@ export declare class RemoteSandbox {
78
79
  details?: Partial<CreateResponse>);
79
80
  private path;
80
81
  exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
82
+ /** Get the HTTP preview URL. Some providers need the port declared when creating the sandbox. */
83
+ url(port: number): Promise<string>;
84
+ /** Start a background command. The returned process can be killed without killing its sandbox. */
85
+ start(cmd: string, opts?: StartOptions): Promise<SandboxProcess>;
81
86
  writeFile(path: string, content: string | Uint8Array): Promise<void>;
82
87
  readFile(path: string): Promise<Uint8Array>;
83
88
  readText(path: string): Promise<string>;
package/dist/client.js CHANGED
@@ -143,6 +143,25 @@ export class RemoteSandbox {
143
143
  }
144
144
  throw new ClientError(502, "stream ended before the command finished");
145
145
  }
146
+ /** Get the HTTP preview URL. Some providers need the port declared when creating the sandbox. */
147
+ async url(port) {
148
+ const response = await this.client.request("GET", this.path(`/ports/${encodeURIComponent(String(port))}`));
149
+ return (await response.json()).url;
150
+ }
151
+ /** Start a background command. The returned process can be killed without killing its sandbox. */
152
+ async start(cmd, opts = {}) {
153
+ const response = await this.client.request("POST", this.path("/processes"), { ...opts, cmd });
154
+ const { id } = (await response.json());
155
+ const path = this.path(`/processes/${encodeURIComponent(id)}`);
156
+ let stopping;
157
+ return {
158
+ id,
159
+ kill: () => stopping ??= this.client.request("DELETE", path).then(() => { }).catch((err) => {
160
+ stopping = undefined;
161
+ throw err;
162
+ }),
163
+ };
164
+ }
146
165
  async writeFile(path, content) {
147
166
  const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
148
167
  await this.client.request("PUT", this.path(`/files?path=${encodeURIComponent(path)}`), data);
@@ -119,7 +119,7 @@ export declare class RoutedComputer {
119
119
  screenshot(opts?: {
120
120
  format?: "png" | "jpeg";
121
121
  quality?: number;
122
- }): Promise<Uint8Array<ArrayBufferLike>>;
122
+ }): Promise<Uint8Array>;
123
123
  /** Run a shell command (max 30 s). The second argument is `{ timeoutSeconds }`, or the number alone. */
124
124
  exec(command: string, opts?: number | {
125
125
  timeoutSeconds?: number;
@@ -128,7 +128,7 @@ export declare class RoutedComputer {
128
128
  stdout: string;
129
129
  stderr: string;
130
130
  }>;
131
- readFile(path: string): Promise<Uint8Array<ArrayBufferLike>>;
131
+ readFile(path: string): Promise<Uint8Array>;
132
132
  writeFile(path: string, content: string | Uint8Array): Promise<void>;
133
133
  /** What this computer's provider supports beyond the core actions. */
134
134
  get supports(): {
package/dist/cost.d.ts CHANGED
@@ -14,8 +14,11 @@ export interface Delivered {
14
14
  memoryMb: number;
15
15
  }
16
16
  export interface Bill {
17
- /** What the provider says it charged for this sandbox, USD. Undefined when it can't be read. */
17
+ /** Reported USD. The kind distinguishes metered usage from a provider's own estimate. */
18
18
  usd?: number;
19
+ kind?: "provider-usage" | "provider-estimate";
20
+ /** Monetary resolution of the underlying report, when it rounds to whole cents. */
21
+ resolutionUsd?: number;
19
22
  /** Seconds the provider billed, when it reports them. */
20
23
  seconds?: number;
21
24
  /** Where the number came from, or why there is none. */
@@ -42,6 +45,9 @@ export interface CostEntry {
42
45
  error?: string;
43
46
  bill?: Bill;
44
47
  }
48
+ /** Older records predate typed evidence. Sail's endpoint reports estimated usage at list rates. */
49
+ export declare function billKind(bill: Bill | undefined): Bill["kind"];
50
+ export declare function billResolutionUsd(bill: Bill | undefined): number | undefined;
45
51
  export interface CostRun {
46
52
  tool: "sandboxrouter-cost";
47
53
  version: string;
@@ -52,6 +58,40 @@ export interface CostRun {
52
58
  by?: string;
53
59
  entries: CostEntry[];
54
60
  }
61
+ export interface HostedLedgerEntry {
62
+ provider: ProviderId;
63
+ requested: {
64
+ vcpu: number;
65
+ memoryGb: number;
66
+ };
67
+ size: {
68
+ vcpu: number;
69
+ memoryGb: number;
70
+ };
71
+ expectedSeconds: number;
72
+ runtimeSeconds: number;
73
+ quoteUsd: number;
74
+ quoteAtRecordedRuntimeUsd?: number;
75
+ chargeUsd: number;
76
+ balanceDeltaUsd: number;
77
+ keySpendDeltaUsd?: number;
78
+ minimumSeconds?: number;
79
+ minimumCovers?: "all" | "memory";
80
+ incrementSeconds?: number;
81
+ feePct: number;
82
+ checkedAt?: string;
83
+ createMs?: number;
84
+ commandMs?: number;
85
+ belowQuotedCapRejected?: boolean;
86
+ commandVerified: true;
87
+ deleted: true;
88
+ }
89
+ export interface HostedLedgerRun {
90
+ tool: "sandboxrouter-hosted-ledger";
91
+ date: string;
92
+ keySpendDeltaUsd?: number;
93
+ entries: HostedLedgerEntry[];
94
+ }
55
95
  /**
56
96
  * The size the sandbox really has, as "<vcpus> <memoryMb>". nproc and MemTotal can show the whole host
57
97
  * (Daytona's containers report 64 CPUs and 755 GB while limited to 1 vCPU and 1 GB), so the cgroup limits
@@ -75,10 +115,9 @@ export declare const BILL_READERS: Partial<Record<ProviderId, Reader>>;
75
115
  export declare function settle(run: CostRun): Promise<CostRun>;
76
116
  export declare function costMarkdown(run: CostRun): string;
77
117
  /**
78
- * Billed / predicted per provider, from the saved cost runs in `dir` (default results/cost): the latest
79
- * entry whose bill is precise enough to compare. A bill rounded to whole cents only counts when the
80
- * prediction is at least $1, so rounding can't move the ratio by more than 1%. Providers whose terms
81
- * forbid publishing benchmarks are left out, like everywhere else results are published.
118
+ * Billed / predicted for the latest loaded run of at least ten minutes with metered provider usage.
119
+ * A bill rounded to whole cents only counts when the prediction is at least $1, so rounding can't
120
+ * move the ratio by more than 1%. Providers that forbid publishing benchmarks are left out.
82
121
  */
83
122
  export declare function billedVsList(dir?: string): {
84
123
  provider: ProviderId;
package/dist/cost.js CHANGED
@@ -2,6 +2,15 @@ import { readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { benchmarksPublishable, billingRules, fittingSpec, hourlyCost } from "./catalog.js";
4
4
  import { Router } from "./router.js";
5
+ /** Older records predate typed evidence. Sail's endpoint reports estimated usage at list rates. */
6
+ export function billKind(bill) {
7
+ if (bill?.usd === undefined)
8
+ return undefined;
9
+ return bill.kind ?? (/estimate at list rates/i.test(bill.source) ? "provider-estimate" : "provider-usage");
10
+ }
11
+ export function billResolutionUsd(bill) {
12
+ return bill?.resolutionUsd ?? (bill?.usd !== undefined && /integer cents/i.test(bill.source) ? 0.01 : undefined);
13
+ }
5
14
  /**
6
15
  * The size the sandbox really has, as "<vcpus> <memoryMb>". nproc and MemTotal can show the whole host
7
16
  * (Daytona's containers report 64 CPUs and 755 GB while limited to 1 vCPU and 1 GB), so the cgroup limits
@@ -34,13 +43,15 @@ export async function costRun(opts) {
34
43
  entry.startedAt = new Date(t0).toISOString();
35
44
  box = await router.create({ vcpu, memoryGb, timeoutMinutes: opts.minutes + 10 }, { provider, fallback: false });
36
45
  entry.sandboxId = box.nativeId;
37
- const [cpus, mem] = (await box.exec(PROBE)).stdout.trim().split(/\s+/).map(Number);
38
- if (cpus > 0 && mem > 0) {
39
- entry.delivered = { vcpu: cpus, memoryMb: mem };
40
- entry.deliveredUsdHour = round(hourlyCost(provider, { vcpu: cpus, memoryGb: mem / 1024 }));
46
+ const probe = await box.exec(PROBE);
47
+ const [cpus, mem, extra] = probe.stdout.trim().split(/\s+/).map(Number);
48
+ if (probe.exitCode !== 0 || !Number.isFinite(cpus) || !Number.isFinite(mem) || cpus <= 0 || mem <= 0 || extra !== undefined) {
49
+ throw new Error("size probe failed or returned invalid output");
41
50
  }
42
- if (load)
43
- await box.exec(LOAD);
51
+ entry.delivered = { vcpu: cpus, memoryMb: mem };
52
+ entry.deliveredUsdHour = round(hourlyCost(provider, { vcpu: cpus, memoryGb: mem / 1024 }));
53
+ if (load && (await box.exec(LOAD)).exitCode !== 0)
54
+ throw new Error("CPU load command failed");
44
55
  log(`${provider}: running ${box.nativeId} for ${opts.minutes} min`);
45
56
  await sleep(opts.minutes * 60_000 - (Date.now() - t0));
46
57
  }
@@ -65,7 +76,7 @@ export async function costRun(opts) {
65
76
  async function getJson(url, headers) {
66
77
  const r = await fetch(url, { headers, signal: AbortSignal.timeout(30_000) });
67
78
  if (!r.ok)
68
- throw new Error(`${r.status} ${(await r.text()).slice(0, 200)}`);
79
+ throw new Error(`billing HTTP ${r.status}`);
69
80
  return r.json();
70
81
  }
71
82
  const hourFloor = (iso) => new Date(Math.floor(Date.parse(iso) / 3_600_000) * 3_600_000).toISOString();
@@ -82,7 +93,10 @@ export const BILL_READERS = {
82
93
  if (!row)
83
94
  return { source: "daytona usage API: not posted yet (can take up to 48 h)" };
84
95
  const seconds = row.firstStart && row.lastEnd ? Math.round((Date.parse(row.lastEnd) - Date.parse(row.firstStart)) / 1000) : undefined;
85
- return { usd: round(row.totalPrice), seconds, source: "daytona analytics /usage/sandbox totalPrice" };
96
+ if (typeof row.totalPrice !== "number" || !Number.isFinite(row.totalPrice) || row.totalPrice < 0) {
97
+ return { source: "daytona analytics /usage/sandbox: no valid totalPrice yet" };
98
+ }
99
+ return { usd: round(row.totalPrice), kind: "provider-usage", seconds, source: "daytona analytics /usage/sandbox totalPrice" };
86
100
  },
87
101
  async blaxel(e) {
88
102
  const h = { Authorization: `Bearer ${process.env.BL_API_KEY}` };
@@ -94,7 +108,10 @@ export const BILL_READERS = {
94
108
  const row = (j.data ?? []).find((d) => d.resourceName === e.sandboxId);
95
109
  if (!row)
96
110
  return { source: "blaxel metrics API: not posted yet (lags a few minutes)" };
97
- return { usd: round(row.summary?.cost ?? 0), source: "blaxel /metrics cost (USD)" };
111
+ if (typeof row.summary?.cost !== "number" || !Number.isFinite(row.summary.cost) || row.summary.cost < 0) {
112
+ return { source: "blaxel /metrics: no valid cost yet" };
113
+ }
114
+ return { usd: round(row.summary.cost), kind: "provider-usage", source: "blaxel /metrics cost (USD)" };
98
115
  },
99
116
  async maritime(e) {
100
117
  const h = { Authorization: `Bearer ${process.env.MARITIME_API_KEY}` };
@@ -103,10 +120,13 @@ export const BILL_READERS = {
103
120
  const days = j.byMachineDay?.[`sandbox:${e.sandboxId}`] ?? [];
104
121
  if (!days.length)
105
122
  return { source: "maritime metered-usage: not posted yet" };
106
- const cents = days.reduce((n, d) => n + (d.cents ?? 0), 0);
123
+ if (!days.every((d) => Number.isInteger(d.cents) && d.cents >= 0)) {
124
+ return { source: "maritime metered-usage: no valid cents field yet" };
125
+ }
126
+ const cents = days.reduce((n, d) => n + d.cents, 0);
107
127
  const seconds = days.reduce((n, d) => n + (d.seconds ?? 0), 0);
108
128
  const model = j.plan ? `plan ${j.plan}` : "no usage plan on this account";
109
- return { usd: round(cents / 100), seconds: Math.round(seconds), source: `maritime metered-usage (integer cents; ${model})` };
129
+ return { usd: round(cents / 100), kind: "provider-usage", resolutionUsd: 0.01, seconds: Math.round(seconds), source: `maritime metered-usage (integer cents; ${model})` };
110
130
  },
111
131
  async sail(e) {
112
132
  const h = { Authorization: `Bearer ${process.env.SAIL_API_KEY}` };
@@ -116,9 +136,13 @@ export const BILL_READERS = {
116
136
  const row = (j.sailboxes ?? []).find((s) => s.sailbox_id === e.sandboxId);
117
137
  if (!row)
118
138
  return { source: "sail /sailboxes/spend: not posted yet (a few minutes)" };
139
+ if (!Number.isInteger(row.cost_usd_nanos) || row.cost_usd_nanos < 0) {
140
+ return { source: "sail /sailboxes/spend: no valid cost_usd_nanos yet" };
141
+ }
119
142
  const fees = j.creation_fees_waived ? "creation fee waived" : `${row.creation_count ?? 0} creation charge`;
120
143
  return {
121
- usd: round((row.cost_usd_nanos ?? 0) / 1e9),
144
+ usd: round(row.cost_usd_nanos / 1e9),
145
+ kind: "provider-estimate",
122
146
  seconds: Math.round(row.running_seconds ?? 0),
123
147
  source: `sail /sailboxes/spend cost_usd_nanos (estimate at list rates; ${fees}; ${Math.round(row.vcpu_seconds ?? 0)} vCPU-s, ${Math.round(row.memory_gib_seconds ?? 0)} GiB-s)`,
124
148
  };
@@ -132,8 +156,12 @@ export const BILL_READERS = {
132
156
  const row = (j.instances ?? []).find((i) => i.id === id);
133
157
  if (!row)
134
158
  return { source: "agent37 /v1/usage: not posted yet" };
159
+ if (!Number.isInteger(row.total_micros) || row.total_micros < 0) {
160
+ return { source: "agent37 /v1/usage: no valid total_micros yet" };
161
+ }
135
162
  return {
136
- usd: round((row.total_micros ?? 0) / 1e6),
163
+ usd: round(row.total_micros / 1e6),
164
+ kind: "provider-usage",
137
165
  seconds: (row.awake_minutes ?? 0) * 60,
138
166
  source: `agent37 /v1/usage total_micros (billed in whole minutes: ${row.awake_minutes ?? 0} awake)`,
139
167
  };
@@ -166,25 +194,25 @@ export async function settle(run) {
166
194
  }
167
195
  return run;
168
196
  }
169
- const usd = (n) => (n === undefined ? "n/a" : n < 0.01 ? `$${n.toFixed(5)}` : `$${n.toFixed(4)}`);
197
+ const usd = (n, resolution) => n === undefined ? "n/a" : `$${n.toFixed(resolution === 0.01 ? 2 : 6)}`;
170
198
  export function costMarkdown(run) {
171
199
  const lines = [
172
- "| Provider | Asked for | Got | Ran | Predicted (list × time) | Billed | Billed ÷ predicted | Source |",
200
+ "| Provider | Asked for | Got | Ran | Predicted (list × time) | Reported | Usage ÷ predicted | Source |",
173
201
  "|---|---|---|---|---|---|---|---|",
174
202
  ];
175
203
  for (const e of run.entries) {
176
204
  const got = e.delivered ? `${e.delivered.vcpu} vCPU / ${(e.delivered.memoryMb / 1024).toFixed(1)} GB` : "n/a";
177
- const ratio = e.bill?.usd !== undefined && e.predictedUsd ? `${((e.bill.usd / e.predictedUsd) * 100).toFixed(0)}%` : "n/a";
205
+ const ratio = billKind(e.bill) === "provider-usage" && e.bill?.usd !== undefined && e.predictedUsd && !billResolutionUsd(e.bill)
206
+ ? `${((e.bill.usd / e.predictedUsd) * 100).toFixed(0)}%` : "n/a";
178
207
  const ran = e.seconds !== undefined ? `${e.seconds} s${e.bill?.seconds !== undefined ? ` (billed ${e.bill.seconds} s)` : ""}` : "n/a";
179
- lines.push(`| ${e.provider} | ${e.requested.vcpu} vCPU / ${e.requested.memoryGb} GB | ${got} | ${ran} | ${usd(e.predictedUsd)} | ${usd(e.bill?.usd)} | ${ratio} | ${e.error ? `error: ${e.error}` : (e.bill?.source ?? "not settled")} |`);
208
+ lines.push(`| ${e.provider} | ${e.requested.vcpu} vCPU / ${e.requested.memoryGb} GB | ${got} | ${ran} | ${usd(e.predictedUsd)} | ${usd(e.bill?.usd, billResolutionUsd(e.bill))} | ${ratio} | ${e.error ? `error: ${e.error}` : (e.bill?.source ?? "not settled")} |`);
180
209
  }
181
210
  return lines.join("\n");
182
211
  }
183
212
  /**
184
- * Billed / predicted per provider, from the saved cost runs in `dir` (default results/cost): the latest
185
- * entry whose bill is precise enough to compare. A bill rounded to whole cents only counts when the
186
- * prediction is at least $1, so rounding can't move the ratio by more than 1%. Providers whose terms
187
- * forbid publishing benchmarks are left out, like everywhere else results are published.
213
+ * Billed / predicted for the latest loaded run of at least ten minutes with metered provider usage.
214
+ * A bill rounded to whole cents only counts when the prediction is at least $1, so rounding can't
215
+ * move the ratio by more than 1%. Providers that forbid publishing benchmarks are left out.
188
216
  */
189
217
  export function billedVsList(dir = "results/cost") {
190
218
  let files;
@@ -203,19 +231,21 @@ export function billedVsList(dir = "results/cost") {
203
231
  catch {
204
232
  continue;
205
233
  }
206
- if (run?.tool !== "sandboxrouter-cost" || !Array.isArray(run.entries))
234
+ if (run?.tool !== "sandboxrouter-cost" || !run.load || !Array.isArray(run.entries))
207
235
  continue;
208
236
  for (const e of run.entries) {
209
237
  const usd = e.bill?.usd;
210
238
  const predicted = e.predictedUsd;
211
- if (!usd || !predicted || usd <= 0 || predicted <= 0 || !benchmarksPublishable(e.provider))
239
+ if (e.error || (e.seconds ?? 0) < 600 || billKind(e.bill) !== "provider-usage" ||
240
+ !usd || !predicted || usd <= 0 || predicted <= 0 || !benchmarksPublishable(e.provider))
212
241
  continue;
213
242
  // A fixed per-sandbox charge (Sail's $0.01) isn't an hourly rate: take it out, or a 10-minute run
214
243
  // turns it into "bills 46% over list" for every hour after.
215
244
  const running = usd - billingRules(e.provider).perSandboxUsd;
216
245
  if (running <= 0)
217
246
  continue;
218
- if (/integer cents/i.test(e.bill.source) && predicted < 1)
247
+ const resolution = billResolutionUsd(e.bill);
248
+ if (resolution !== undefined && predicted < 100 * resolution)
219
249
  continue;
220
250
  const date = run.date.slice(0, 10);
221
251
  const prev = latest.get(e.provider);
@@ -1,5 +1,6 @@
1
1
  import { type PhaseMs } from "./task.js";
2
2
  import type { BenchRow } from "./bench.js";
3
+ import { type Size } from "./router.js";
3
4
  import type { ProviderId, SandboxSpec } from "./types.js";
4
5
  /**
5
6
  * A shareable bench result. People submit these as PRs to results/, and `sandboxrouter
@@ -37,6 +38,7 @@ export interface LeaderRow {
37
38
  submissions: number;
38
39
  medianCreateMs?: number;
39
40
  medianExecMs?: number;
41
+ medianReadyMs?: number;
40
42
  successRate: number;
41
43
  /** Runs behind the row that the provider was asked to do (refusals for an account limit left out). */
42
44
  runs: number;
@@ -56,7 +58,7 @@ export interface LeaderRow {
56
58
  * the one with the most runs wins (a 100-run start-time benchmark over a 3-run job that also timed starts);
57
59
  * ties go to the newest.
58
60
  */
59
- export declare function aggregate(reports: BenchReport[]): LeaderRow[];
61
+ export declare function aggregate(reports: BenchReport[], cohort?: Size): LeaderRow[];
60
62
  export interface TaskRow {
61
63
  provider: ProviderId;
62
64
  name: string;
@@ -74,8 +76,10 @@ export interface TaskRow {
74
76
  taskUsd: number;
75
77
  /** What one job costs in a sandbox that's already running (no start, minimum or per-sandbox fee). */
76
78
  reusedUsd: number;
77
- /** Runs behind the medians (refusals for an account limit left out). */
79
+ /** All requests in the comparison, including failed starts and limits. */
78
80
  runs: number;
81
+ ok: number;
82
+ limited: number;
79
83
  /** Share of those runs that finished the job. */
80
84
  successRate: number;
81
85
  /** CPU time the task used across all vCPUs (median), where the sandbox shows /proc/stat. */
@@ -86,12 +90,16 @@ export interface TaskRow {
86
90
  perSandboxUsd: number;
87
91
  measuredAt: string;
88
92
  }
89
- /**
90
- * Cost of the standard task (src/task.ts) per provider, from reports made with `bench --task` at
91
- * `version` (the short task's by default; TASKS.long.version for `--long`): each provider's latest run
92
- * from each location, then the median across locations (as `aggregate` does). Cheapest task first.
93
- */
94
- export declare function taskTable(reports: BenchReport[], version?: string): TaskRow[];
93
+ export declare function taskOutcomes(reports: BenchReport[], version: string, cohort?: Size): {
94
+ provider: ProviderId;
95
+ name: string;
96
+ requested: number;
97
+ completed: number;
98
+ limited: number;
99
+ failures: number;
100
+ taskFailures: number;
101
+ }[];
102
+ export declare function taskTable(reports: BenchReport[], version?: string, cohort?: Size): TaskRow[];
95
103
  /** One self-contained HTML page: a sorted table with an inline bar per measure, each on its own scale. */
96
104
  export declare function renderLeaderboard(reports: BenchReport[]): string;
97
105
  /** A saved `sandboxrouter burst` report (results/, tool "sandboxrouter-burst"). */
@@ -119,6 +127,14 @@ export declare function burstTable(reports: BurstReport[], task?: string, n?: nu
119
127
  n: number;
120
128
  ok: number;
121
129
  limited: number;
130
+ size?: {
131
+ vcpu: number;
132
+ memoryGb: number;
133
+ };
134
+ createFailures?: number;
135
+ commandFailures?: number;
136
+ taskFailures?: number;
137
+ cleanupFailures?: number;
122
138
  p50Ms?: number;
123
139
  p95Ms?: number;
124
140
  p99Ms?: number;
@@ -144,6 +160,12 @@ export declare function loadAgentReports(dir: string): AgentReport[];
144
160
  export declare function agentTable(reports: AgentReport[]): {
145
161
  provider: ProviderId;
146
162
  runs: number;
163
+ requested?: number;
164
+ started?: number;
165
+ size?: {
166
+ vcpu: number;
167
+ memoryGb: number;
168
+ };
147
169
  limited?: number;
148
170
  ok: number;
149
171
  medianWallMs?: number;