@sandboxrouter/sdk 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/steady.js ADDED
@@ -0,0 +1,164 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { benchmarksPublishable, CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost } from "./catalog.js";
4
+ import { median } from "./bench-store.js";
5
+ import { percentile } from "./burst.js";
6
+ import { sizeOf } from "./router.js";
7
+ import { hashZeros, phaseCommand, ZERO_256_SHA256 } from "./task.js";
8
+ /**
9
+ * Steadiness benchmark: one sandbox kept for several minutes, running the same small piece of work at a fixed
10
+ * interval, the way an agent session does a tool call now and then. Start time and a single job say how fast
11
+ * a provider is; this says whether it stays that fast, which depends on what else shares the machine.
12
+ *
13
+ * Each sample hashes 1 GB on one core (256 MB, four times) and is timed by the sandbox's own clock, so the
14
+ * network between the test machine and the provider is not in the number.
15
+ */
16
+ export const STEADY_VERSION = "steady-v1";
17
+ const MARK = "SRSTEADY";
18
+ // The sandbox's own clock: nanoseconds from GNU date where the image has it, else /proc/uptime (seconds, to
19
+ // a hundredth), which busybox images and every Linux kernel have.
20
+ const CLOCK = `t=$(date +%s%N 2> /dev/null); case "$t" in ""|*[!0-9]*) cut -d' ' -f1 /proc/uptime ;; *) echo "$t" ;; esac`;
21
+ export const STEADY_SAMPLE = `a=$(${CLOCK}); (${phaseCommand(hashZeros(268435456, ZERO_256_SHA256), 4)}); rc=$?; b=$(${CLOCK}); echo "${MARK}|$a|$b"; exit $rc`;
22
+ /** Milliseconds between the two clock readings a sample printed, or undefined if they are not there. */
23
+ export function sampleMs(stdout) {
24
+ const line = stdout.split("\n").find((l) => l.startsWith(`${MARK}|`));
25
+ const [, a, b] = line?.trim().split("|") ?? [];
26
+ let ms;
27
+ // Nanoseconds since 1970 are 19 digits; uptime is seconds with two decimals.
28
+ if (/^\d{16,}$/.test(a ?? "") && /^\d{16,}$/.test(b ?? ""))
29
+ ms = Number((BigInt(b) - BigInt(a)) / 1000000n);
30
+ else if (/^\d+\.\d+$/.test(a ?? "") && /^\d+\.\d+$/.test(b ?? ""))
31
+ ms = Math.round((Number(b) - Number(a)) * 1000);
32
+ else
33
+ return undefined;
34
+ return ms >= 1 ? ms : undefined;
35
+ }
36
+ /** The numbers a row reports, from its samples. */
37
+ export function steadySummary(ms) {
38
+ if (!ms.length)
39
+ return {};
40
+ const sorted = [...ms].sort((a, b) => a - b);
41
+ return { medianMs: median(sorted), p95Ms: percentile(sorted, 0.95), maxMs: sorted.at(-1) };
42
+ }
43
+ /** One sandbox per provider, all providers at once: each only runs one core's worth of work every interval. */
44
+ export async function steady(opts) {
45
+ const samples = opts.samples ?? 60;
46
+ const interval = (opts.intervalSeconds ?? 10) * 1000;
47
+ const asked = opts.spec ?? { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB };
48
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
49
+ const minutes = Math.ceil((samples * interval) / 60_000) + 5;
50
+ return Promise.all(opts.providers.map(async (provider) => {
51
+ const spec = { ...asked, ...fixedSize(provider, asked), timeoutMinutes: minutes };
52
+ const ms = [];
53
+ let failures = 0;
54
+ let box;
55
+ try {
56
+ box = await opts.router.create(spec, { provider, fallback: false });
57
+ const t0 = Date.now();
58
+ for (let i = 0; i < samples; i++) {
59
+ const wait = t0 + i * interval - Date.now();
60
+ if (wait > 0)
61
+ await sleep(wait);
62
+ try {
63
+ const r = await box.exec(STEADY_SAMPLE, { timeoutSeconds: 120 });
64
+ const took = r.exitCode === 0 ? sampleMs(r.stdout) : undefined;
65
+ if (took === undefined)
66
+ failures++;
67
+ else
68
+ ms.push(took);
69
+ }
70
+ catch {
71
+ failures++;
72
+ }
73
+ if ((i + 1) % 10 === 0)
74
+ opts.onProgress?.(`${provider}: ${i + 1}/${samples} samples, ${failures} failed`);
75
+ }
76
+ }
77
+ catch (e) {
78
+ // No sandbox: every sample is missing.
79
+ failures = samples - ms.length;
80
+ opts.onProgress?.(`${provider}: ${e.message.replace(/\s+/g, " ").slice(0, 200)}`);
81
+ }
82
+ finally {
83
+ await box?.kill().catch(() => { });
84
+ }
85
+ let hourlyUsd;
86
+ try {
87
+ hourlyUsd = hourlyCost(provider, spec);
88
+ }
89
+ catch {
90
+ /* no price: the row still stands */
91
+ }
92
+ return { provider, size: sizeOf(provider, spec), sampleMs: ms, ...steadySummary(ms), failures, ...(hourlyUsd !== undefined ? { hourlyUsd } : {}) };
93
+ }));
94
+ }
95
+ export function loadSteadyReports(dir) {
96
+ let files;
97
+ try {
98
+ files = readdirSync(dir).filter((f) => f.endsWith(".json"));
99
+ }
100
+ catch {
101
+ return [];
102
+ }
103
+ const out = [];
104
+ for (const f of files.sort()) {
105
+ try {
106
+ const r = JSON.parse(readFileSync(join(dir, f), "utf8"));
107
+ if (r?.tool === "sandboxrouter-steady" && Array.isArray(r.rows))
108
+ out.push(r);
109
+ }
110
+ catch {
111
+ /* skip unreadable files */
112
+ }
113
+ }
114
+ return out;
115
+ }
116
+ const KNOWN = new Set(CATALOG.map((c) => c.id));
117
+ /**
118
+ * For the website: per provider, every complete run of the current sample from the 30 days before its newest
119
+ * one. One sandbox is one machine at one time, so the row is the median across runs, and the slowest sample
120
+ * of any of them. Steadiest first: the smallest gap between the 95th percentile and the median.
121
+ */
122
+ export function steadyTable(reports) {
123
+ const MONTH = 30 * 86_400_000;
124
+ const by = new Map();
125
+ for (const rep of reports) {
126
+ if (rep.task !== STEADY_VERSION)
127
+ continue;
128
+ for (const row of rep.rows) {
129
+ if (!KNOWN.has(row.provider) || !benchmarksPublishable(row.provider))
130
+ continue;
131
+ by.set(row.provider, [...(by.get(row.provider) ?? []), { row, rep }]);
132
+ }
133
+ }
134
+ return [...by.entries()]
135
+ .flatMap(([provider, all]) => {
136
+ const newest = all.reduce((a, b) => (a.rep.date >= b.rep.date ? a : b));
137
+ // Same size and schedule as the newest run, so the runs behind a row are the same test.
138
+ const runs = all.filter(({ row, rep }) => Date.parse(newest.rep.date) - Date.parse(rep.date) <= MONTH &&
139
+ rep.samples === newest.rep.samples && rep.intervalSeconds === newest.rep.intervalSeconds &&
140
+ row.size.vcpu === newest.row.size.vcpu && row.size.memoryGb === newest.row.size.memoryGb);
141
+ // A run with a failed sample keeps the provider off the table: it did not hold for the whole test.
142
+ if (runs.some(({ row, rep }) => row.failures !== 0 || row.sampleMs.length !== rep.samples || row.medianMs === undefined || row.p95Ms === undefined))
143
+ return [];
144
+ const spreads = runs.map(({ row }) => row.p95Ms / row.medianMs - 1).sort((a, b) => a - b);
145
+ const mid = Math.floor(spreads.length / 2);
146
+ return [{
147
+ provider,
148
+ name: CATALOG.find((c) => c.id === provider).name,
149
+ size: newest.row.size,
150
+ medianMs: median(runs.map(({ row }) => row.medianMs)),
151
+ maxMs: Math.max(...runs.map(({ row }) => row.maxMs)),
152
+ /** How much slower the 95th percentile sample was than the median one, as a fraction (0.04 = 4%): the median across runs. */
153
+ spread: spreads.length % 2 ? spreads[mid] : (spreads[mid - 1] + spreads[mid]) / 2,
154
+ /** Each run's own figure, lowest first. */
155
+ spreads,
156
+ runs: runs.length,
157
+ samples: newest.rep.samples,
158
+ intervalSeconds: newest.rep.intervalSeconds,
159
+ ...(newest.row.hourlyUsd !== undefined ? { hourlyUsd: newest.row.hourlyUsd } : {}),
160
+ measuredAt: newest.rep.date,
161
+ }];
162
+ })
163
+ .sort((a, b) => a.spread - b.spread || a.medianMs - b.medianMs);
164
+ }
package/dist/task.d.ts CHANGED
@@ -32,6 +32,8 @@ export interface TaskPhaseDef {
32
32
  /** Seconds the phase may take (default 300, or 900 for a repeated phase). */
33
33
  timeoutSeconds?: number;
34
34
  }
35
+ export declare const ZERO_256_SHA256 = "a6d72ac7690f53be6ae46ba88506bd97302a093f7108472bd9efc3cefda06484";
36
+ export declare const hashZeros: (count: number, hash: string) => string;
35
37
  /** `cpuUtilization`: the hint the job's sandboxes start with (the agent loop is mostly idle), which Modal reserves and pricing uses. */
36
38
  export declare const TASKS: Record<TaskKind, {
37
39
  version: string;
package/dist/task.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { billingRules, cpuHourlyAtFull, hourlyCost, info } from "./catalog.js";
2
- const ZERO_256_SHA256 = "a6d72ac7690f53be6ae46ba88506bd97302a093f7108472bd9efc3cefda06484";
2
+ export const ZERO_256_SHA256 = "a6d72ac7690f53be6ae46ba88506bd97302a093f7108472bd9efc3cefda06484";
3
3
  const ZERO_512_SHA256 = "9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767";
4
- const hashZeros = (count, hash) => `hash=$(head -c ${count} /dev/zero | sha256sum) && [ "${'${hash%% *}'}" = "${hash}" ]`;
4
+ export const hashZeros = (count, hash) => `hash=$(head -c ${count} /dev/zero | sha256sum) && [ "${'${hash%% *}'}" = "${hash}" ]`;
5
5
  const HASH_DISK = [
6
6
  // One core: hash 512 MB of zeros.
7
7
  { id: "cpu", label: "1 core", cmd: hashZeros(536870912, ZERO_512_SHA256) },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.18.0",
3
+ "version": "0.19.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",