@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.
@@ -0,0 +1,172 @@
1
+ import { type Router } from "./router.js";
2
+ import type { ProviderId } from "./types.js";
3
+ /**
4
+ * Assistant session benchmark: what a chat assistant with a code tool asks of a sandbox during one
5
+ * conversation, timed the way the person waiting sees it (from the test machine, network included).
6
+ *
7
+ * One session, in one sandbox:
8
+ * 1. first answer: start the sandbox and get the result of a first Python call;
9
+ * 2. upload: put the person's file (a 4 MB CSV) into the sandbox;
10
+ * 3. analyse: a Python script reads it, prints per-category totals and writes a 1 MB result file;
11
+ * 4. download: read the result file back;
12
+ * 5. tool calls: 20 short Python calls, each of which must see what the calls before it wrote;
13
+ * 6. after idle: nothing for a minute (the person is reading), then one more call.
14
+ *
15
+ * Every step is checked against values computed here, so a session only counts when the sandbox really kept
16
+ * the file, ran the analysis and returned the right bytes.
17
+ */
18
+ export declare const ASSISTANT_VERSION = "assistant-v1";
19
+ export declare const ASSISTANT_CALLS = 20;
20
+ export declare const ASSISTANT_IDLE_SECONDS = 60;
21
+ /** The uploaded file and what the analysis must produce from it. Always the same bytes. */
22
+ export declare function assistantFixture(rows?: number): {
23
+ csv: string;
24
+ /** What the analysis prints: one line per category, with its row count and total. */
25
+ summary: string;
26
+ resultBytes: number;
27
+ resultSha256: string;
28
+ };
29
+ export declare const ASSISTANT_FIRST = "python3 -c 'print(6 * 7)'";
30
+ export declare const ASSISTANT_ANALYSE = "python3 - <<'SRASSISTANT'\nimport collections, csv\nD = \"/tmp/sr-assistant\"\nrows = list(csv.reader(open(D + \"/data.csv\")))[1:]\ncount = collections.Counter()\ntotal = collections.Counter()\nfor i, c, a in rows:\n count[c] += 1\n total[c] += int(a)\ntop = sorted((r for r in rows if int(r[2]) >= 375000), key=lambda r: (-int(r[2]), int(r[0])))\nwith open(D + \"/top.csv\", \"w\", newline=\"\") as f:\n f.write(\"\".join(\",\".join(r) + \"\\n\" for r in top))\nfor c in sorted(count):\n print(\"%s,%d,%d\" % (c, count[c], total[c]))\nSRASSISTANT";
31
+ /** One short tool call: add a line to a notes file and print how many lines it has now. */
32
+ export declare const ASSISTANT_CALL = "python3 -c 'p = \"/tmp/sr-assistant/notes.txt\"; open(p, \"a\").write(\"x\\n\"); print(len(open(p).read().splitlines()))'";
33
+ /**
34
+ * Providers whose adapter has no file endpoint to use and sends files through shell commands, in chunks.
35
+ * Their upload and download times are for that route.
36
+ */
37
+ export declare const FILES_THROUGH_COMMANDS: ReadonlySet<string>;
38
+ /** One session's times, in ms as seen from the test machine. */
39
+ export interface AssistantSession {
40
+ createMs: number;
41
+ /** The first Python call, after the sandbox started. */
42
+ firstMs: number;
43
+ uploadMs: number;
44
+ analyseMs: number;
45
+ downloadMs: number;
46
+ /** Each of the short tool calls, in order. */
47
+ callMs: number[];
48
+ /** The one call after the idle minute. */
49
+ idleMs: number;
50
+ /** From the first call to the last, idle minute included, without time spent waiting for another provider's file transfer. */
51
+ sessionMs: number;
52
+ /** CPU time the session used inside the sandbox, where the sandbox shows it. */
53
+ cpuMs?: number;
54
+ maxCoreMs?: number;
55
+ }
56
+ export interface AssistantSummary {
57
+ /** Start plus the first call: how long until the assistant has its first result. Median. */
58
+ firstAnswerMs?: number;
59
+ uploadMs?: number;
60
+ analyseMs?: number;
61
+ downloadMs?: number;
62
+ /** Median and 95th percentile of every short call of every session. */
63
+ callMs?: number;
64
+ callP95Ms?: number;
65
+ idleMs?: number;
66
+ }
67
+ export interface AssistantRow extends AssistantSummary {
68
+ provider: string;
69
+ size: {
70
+ vcpu: number;
71
+ memoryGb: number;
72
+ };
73
+ /** Sessions where every step finished and checked out. */
74
+ sessions: AssistantSession[];
75
+ /** Sessions that did not start, stopped part-way, or returned something wrong. */
76
+ failures: number;
77
+ /** Published prices applied to one session's measured time and CPU use, median. */
78
+ sessionUsd?: number;
79
+ /** List price per hour at this size. */
80
+ hourlyUsd?: number;
81
+ }
82
+ /** A saved assistant session report (results/, tool "sandboxrouter-assistant"). */
83
+ export interface AssistantReport {
84
+ tool: "sandboxrouter-assistant";
85
+ version: string;
86
+ /** The session's version: a change to the steps makes older reports stop counting. */
87
+ task: string;
88
+ date: string;
89
+ label?: string;
90
+ by?: string;
91
+ spec: {
92
+ vcpu: number;
93
+ memoryGb: number;
94
+ };
95
+ /** Sessions asked of each provider. */
96
+ runs: number;
97
+ calls: number;
98
+ idleSeconds: number;
99
+ uploadBytes: number;
100
+ downloadBytes: number;
101
+ node: string;
102
+ platform: string;
103
+ rows: AssistantRow[];
104
+ }
105
+ export declare function assistantSummary(sessions: AssistantSession[]): AssistantSummary;
106
+ export interface AssistantOptions {
107
+ router: Router;
108
+ providers: ProviderId[];
109
+ runs?: number;
110
+ spec?: {
111
+ vcpu: number;
112
+ memoryGb: number;
113
+ };
114
+ onProgress?: (message: string) => void;
115
+ /** For tests. */
116
+ sleep?: (ms: number) => Promise<void>;
117
+ idleSeconds?: number;
118
+ }
119
+ /** Providers side by side, each running its sessions one after another. File transfers take turns, so they do not share the test machine's connection. */
120
+ export declare function assistant(opts: AssistantOptions): Promise<AssistantRow[]>;
121
+ export declare function loadAssistantReports(dir: string): AssistantReport[];
122
+ /**
123
+ * For the website: each provider's newest report of the current session. A provider is listed only when
124
+ * every session of that report finished and checked out. Fastest first answer first.
125
+ */
126
+ export declare function assistantTable(reports: AssistantReport[]): {
127
+ provider: string;
128
+ name: string;
129
+ size: {
130
+ vcpu: number;
131
+ memoryGb: number;
132
+ };
133
+ firstAnswerMs: number;
134
+ uploadMs: number;
135
+ analyseMs: number;
136
+ downloadMs: number;
137
+ callMs: number;
138
+ callP95Ms: number;
139
+ idleMs: number;
140
+ runs: number;
141
+ calls: number;
142
+ idleSeconds: number;
143
+ uploadBytes: number;
144
+ downloadBytes: number;
145
+ sessionUsd?: number | undefined;
146
+ hourlyUsd?: number | undefined;
147
+ filesThroughCommands?: boolean | undefined;
148
+ measuredAt: string;
149
+ }[];
150
+ /**
151
+ * For recommend(): each provider's newest report of the current session, as a job. The time is what a
152
+ * person waits for across the session (every step and call, not the idle minute); the cost is the whole
153
+ * session, idle minute included.
154
+ */
155
+ export declare function assistantJobs(reports: AssistantReport[]): Record<string, {
156
+ name: string;
157
+ size: {
158
+ vcpu: number;
159
+ memoryGb: number;
160
+ };
161
+ createMs: number;
162
+ taskMs: number;
163
+ taskUsd: number;
164
+ reusedUsd: number;
165
+ successRate: number;
166
+ runs: number;
167
+ ok: number;
168
+ minimumSeconds?: number;
169
+ perSandboxUsd?: number;
170
+ note?: string;
171
+ measuredAt: string;
172
+ }>;
@@ -0,0 +1,307 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { BILLED_VS_LIST } from "./billing.js";
5
+ import { benchmarksPublishable, billingRules, CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost } from "./catalog.js";
6
+ import { median } from "./bench-store.js";
7
+ import { percentile } from "./burst.js";
8
+ import { sizeOf } from "./router.js";
9
+ import { busyMs, maxCoreMs, taskUsd } from "./task.js";
10
+ /**
11
+ * Assistant session benchmark: what a chat assistant with a code tool asks of a sandbox during one
12
+ * conversation, timed the way the person waiting sees it (from the test machine, network included).
13
+ *
14
+ * One session, in one sandbox:
15
+ * 1. first answer: start the sandbox and get the result of a first Python call;
16
+ * 2. upload: put the person's file (a 4 MB CSV) into the sandbox;
17
+ * 3. analyse: a Python script reads it, prints per-category totals and writes a 1 MB result file;
18
+ * 4. download: read the result file back;
19
+ * 5. tool calls: 20 short Python calls, each of which must see what the calls before it wrote;
20
+ * 6. after idle: nothing for a minute (the person is reading), then one more call.
21
+ *
22
+ * Every step is checked against values computed here, so a session only counts when the sandbox really kept
23
+ * the file, ran the analysis and returned the right bytes.
24
+ */
25
+ export const ASSISTANT_VERSION = "assistant-v1";
26
+ export const ASSISTANT_CALLS = 20;
27
+ export const ASSISTANT_IDLE_SECONDS = 60;
28
+ const DIR = "/tmp/sr-assistant";
29
+ const ROWS = 200_000;
30
+ const TOP_FROM = 375_000;
31
+ /** The uploaded file and what the analysis must produce from it. Always the same bytes. */
32
+ export function assistantFixture(rows = ROWS) {
33
+ let s = 20261128;
34
+ const next = () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) >>> 8);
35
+ const lines = ["id,category,amount_cents"];
36
+ const count = new Map();
37
+ const total = new Map();
38
+ const top = [];
39
+ for (let id = 1; id <= rows; id++) {
40
+ const category = `cat-${String(next() % 12).padStart(2, "0")}`;
41
+ const amount = next() % 500_000;
42
+ lines.push(`${id},${category},${amount}`);
43
+ count.set(category, (count.get(category) ?? 0) + 1);
44
+ total.set(category, (total.get(category) ?? 0) + amount);
45
+ if (amount >= TOP_FROM)
46
+ top.push([id, category, amount]);
47
+ }
48
+ top.sort((a, b) => b[2] - a[2] || a[0] - b[0]);
49
+ const result = top.map((r) => `${r.join(",")}\n`).join("");
50
+ return {
51
+ csv: `${lines.join("\n")}\n`,
52
+ /** What the analysis prints: one line per category, with its row count and total. */
53
+ summary: [...count.keys()].sort().map((c) => `${c},${count.get(c)},${total.get(c)}`).join("\n"),
54
+ resultBytes: Buffer.byteLength(result),
55
+ resultSha256: createHash("sha256").update(result).digest("hex"),
56
+ };
57
+ }
58
+ export const ASSISTANT_FIRST = `python3 -c 'print(6 * 7)'`;
59
+ export const ASSISTANT_ANALYSE = `python3 - <<'SRASSISTANT'
60
+ import collections, csv
61
+ D = "${DIR}"
62
+ rows = list(csv.reader(open(D + "/data.csv")))[1:]
63
+ count = collections.Counter()
64
+ total = collections.Counter()
65
+ for i, c, a in rows:
66
+ count[c] += 1
67
+ total[c] += int(a)
68
+ top = sorted((r for r in rows if int(r[2]) >= ${TOP_FROM}), key=lambda r: (-int(r[2]), int(r[0])))
69
+ with open(D + "/top.csv", "w", newline="") as f:
70
+ f.write("".join(",".join(r) + "\\n" for r in top))
71
+ for c in sorted(count):
72
+ print("%s,%d,%d" % (c, count[c], total[c]))
73
+ SRASSISTANT`;
74
+ /** One short tool call: add a line to a notes file and print how many lines it has now. */
75
+ export const ASSISTANT_CALL = `python3 -c 'p = "${DIR}/notes.txt"; open(p, "a").write("x\\n"); print(len(open(p).read().splitlines()))'`;
76
+ /**
77
+ * Providers whose adapter has no file endpoint to use and sends files through shell commands, in chunks.
78
+ * Their upload and download times are for that route.
79
+ */
80
+ export const FILES_THROUGH_COMMANDS = new Set(["agentcore", "agent37", "boat"]);
81
+ const STAT = `grep '^cpu' /proc/stat 2> /dev/null | tr '\\n' ';'`;
82
+ export function assistantSummary(sessions) {
83
+ if (!sessions.length)
84
+ return {};
85
+ const calls = sessions.flatMap((s) => s.callMs).sort((a, b) => a - b);
86
+ return {
87
+ firstAnswerMs: median(sessions.map((s) => s.createMs + s.firstMs)),
88
+ uploadMs: median(sessions.map((s) => s.uploadMs)),
89
+ analyseMs: median(sessions.map((s) => s.analyseMs)),
90
+ downloadMs: median(sessions.map((s) => s.downloadMs)),
91
+ callMs: median(calls),
92
+ callP95Ms: percentile(calls, 0.95),
93
+ idleMs: median(sessions.map((s) => s.idleMs)),
94
+ };
95
+ }
96
+ /** Providers side by side, each running its sessions one after another. File transfers take turns, so they do not share the test machine's connection. */
97
+ export async function assistant(opts) {
98
+ const runs = opts.runs ?? 3;
99
+ const idle = (opts.idleSeconds ?? ASSISTANT_IDLE_SECONDS) * 1000;
100
+ const asked = opts.spec ?? { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB };
101
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
102
+ const fixture = assistantFixture();
103
+ const csv = new TextEncoder().encode(fixture.csv);
104
+ let line = Promise.resolve();
105
+ const alone = (work) => {
106
+ const mine = line.then(work, work);
107
+ line = mine.catch(() => { });
108
+ return mine;
109
+ };
110
+ const timed = async (work) => {
111
+ const t = performance.now();
112
+ await work();
113
+ return Math.max(1, Math.round(performance.now() - t));
114
+ };
115
+ const session = async (provider, spec) => {
116
+ const run = async (box, cmd, want, what) => {
117
+ const r = await box.exec(cmd, { timeoutSeconds: 120 });
118
+ if (r.exitCode !== 0)
119
+ throw new Error(`${what} exited ${r.exitCode}: ${r.stderr.slice(-160)}`);
120
+ if (r.stdout.replace(/\r/g, "").trim() !== want)
121
+ throw new Error(`${what} returned something else`);
122
+ };
123
+ let box;
124
+ try {
125
+ const t0 = performance.now();
126
+ box = await opts.router.create(spec, { provider, fallback: false, deadlineSeconds: 180 });
127
+ const live = box;
128
+ const createMs = Math.max(1, Math.round(performance.now() - t0));
129
+ const s0 = performance.now();
130
+ // Time spent waiting for another provider's transfer is not part of this session.
131
+ let waited = 0;
132
+ const transfer = async (work) => {
133
+ const t = performance.now();
134
+ const ms = await alone(() => timed(work));
135
+ waited += Math.max(0, performance.now() - t - ms);
136
+ return ms;
137
+ };
138
+ const firstMs = await timed(() => run(live, ASSISTANT_FIRST, "42", "the first call"));
139
+ const before = (await live.exec(`mkdir -p ${DIR}; ${STAT}`)).stdout;
140
+ const uploadMs = await transfer(() => live.writeFile(`${DIR}/data.csv`, csv));
141
+ const analyseMs = await timed(() => run(live, ASSISTANT_ANALYSE, fixture.summary, "the analysis"));
142
+ const downloadMs = await transfer(async () => {
143
+ const bytes = await live.readFile(`${DIR}/top.csv`);
144
+ if (createHash("sha256").update(bytes).digest("hex") !== fixture.resultSha256)
145
+ throw new Error("the downloaded file is not the one the analysis wrote");
146
+ });
147
+ const callMs = [];
148
+ for (let i = 1; i <= ASSISTANT_CALLS; i++)
149
+ callMs.push(await timed(() => run(live, ASSISTANT_CALL, String(i), `call ${i}`)));
150
+ await sleep(idle);
151
+ const idleMs = await timed(() => run(live, ASSISTANT_CALL, String(ASSISTANT_CALLS + 1), "the call after idle"));
152
+ const sessionMs = Math.max(1, Math.round(performance.now() - s0 - waited));
153
+ const after = (await live.exec(STAT)).stdout;
154
+ const cpu = busyMs(before, after);
155
+ const plausible = cpu !== undefined && cpu <= (spec.vcpu ?? DEFAULT_VCPU) * sessionMs * 1.1;
156
+ const core = plausible ? maxCoreMs(before, after) : undefined;
157
+ return { createMs, firstMs, uploadMs, analyseMs, downloadMs, callMs, idleMs, sessionMs, ...(plausible ? { cpuMs: cpu } : {}), ...(core !== undefined ? { maxCoreMs: core } : {}) };
158
+ }
159
+ finally {
160
+ await box?.kill().catch(() => { });
161
+ }
162
+ };
163
+ return Promise.all(opts.providers.map(async (provider) => {
164
+ // Mostly idle, like the agent job: providers that reserve CPU by expected use start with that hint.
165
+ const spec = { ...asked, ...fixedSize(provider, asked), timeoutMinutes: 15, cpuUtilization: 0.1 };
166
+ const size = sizeOf(provider, spec);
167
+ const done = [];
168
+ let failures = 0;
169
+ for (let i = 0; i < runs; i++) {
170
+ try {
171
+ const s = await session(provider, spec);
172
+ done.push(s);
173
+ opts.onProgress?.(`${provider} session ${i + 1}/${runs}: first answer ${s.createMs + s.firstMs} ms, upload ${s.uploadMs} ms, download ${s.downloadMs} ms, after idle ${s.idleMs} ms`);
174
+ }
175
+ catch (e) {
176
+ failures++;
177
+ opts.onProgress?.(`${provider} session ${i + 1}/${runs} failed: ${e.message.replace(/\s+/g, " ").slice(0, 200)}`);
178
+ }
179
+ }
180
+ let hourlyUsd;
181
+ let sessionUsd;
182
+ try {
183
+ hourlyUsd = hourlyCost(provider, { ...spec, cpuUtilization: 1 });
184
+ const ratio = BILLED_VS_LIST[provider]?.ratio ?? 1;
185
+ const usd = done.map((s) => Math.round(taskUsd(provider, { ...size, cpuUtilization: 0.1 }, s.createMs, s.sessionMs, s.cpuMs, ratio, false, s.maxCoreMs) * 1e9));
186
+ if (usd.length)
187
+ sessionUsd = median(usd) / 1e9;
188
+ }
189
+ catch {
190
+ /* no price: the row still stands */
191
+ }
192
+ return {
193
+ provider, size, sessions: done, ...assistantSummary(done), failures,
194
+ ...(sessionUsd !== undefined ? { sessionUsd } : {}),
195
+ ...(hourlyUsd !== undefined ? { hourlyUsd } : {}),
196
+ };
197
+ }));
198
+ }
199
+ export function loadAssistantReports(dir) {
200
+ let files;
201
+ try {
202
+ files = readdirSync(dir).filter((f) => f.endsWith(".json"));
203
+ }
204
+ catch {
205
+ return [];
206
+ }
207
+ const out = [];
208
+ for (const f of files.sort()) {
209
+ try {
210
+ const r = JSON.parse(readFileSync(join(dir, f), "utf8"));
211
+ if (r?.tool === "sandboxrouter-assistant" && Array.isArray(r.rows))
212
+ out.push(r);
213
+ }
214
+ catch {
215
+ /* skip unreadable files */
216
+ }
217
+ }
218
+ return out;
219
+ }
220
+ const KNOWN = new Set(CATALOG.map((c) => c.id));
221
+ /**
222
+ * For the website: each provider's newest report of the current session. A provider is listed only when
223
+ * every session of that report finished and checked out. Fastest first answer first.
224
+ */
225
+ export function assistantTable(reports) {
226
+ const latest = new Map();
227
+ for (const rep of reports) {
228
+ if (rep.task !== ASSISTANT_VERSION)
229
+ continue;
230
+ for (const row of rep.rows) {
231
+ if (!KNOWN.has(row.provider) || !benchmarksPublishable(row.provider))
232
+ continue;
233
+ const seen = latest.get(row.provider);
234
+ if (!seen || rep.date > seen.rep.date)
235
+ latest.set(row.provider, { row, rep });
236
+ }
237
+ }
238
+ return [...latest.values()]
239
+ .filter(({ row, rep }) => row.failures === 0 && row.sessions.length === rep.runs && row.firstAnswerMs !== undefined)
240
+ .map(({ row, rep }) => ({
241
+ provider: row.provider,
242
+ name: CATALOG.find((c) => c.id === row.provider).name,
243
+ size: row.size,
244
+ firstAnswerMs: row.firstAnswerMs,
245
+ uploadMs: row.uploadMs,
246
+ analyseMs: row.analyseMs,
247
+ downloadMs: row.downloadMs,
248
+ callMs: row.callMs,
249
+ callP95Ms: row.callP95Ms,
250
+ idleMs: row.idleMs,
251
+ runs: rep.runs,
252
+ calls: rep.calls,
253
+ idleSeconds: rep.idleSeconds,
254
+ uploadBytes: rep.uploadBytes,
255
+ downloadBytes: rep.downloadBytes,
256
+ ...(row.sessionUsd !== undefined ? { sessionUsd: row.sessionUsd } : {}),
257
+ ...(row.hourlyUsd !== undefined ? { hourlyUsd: row.hourlyUsd } : {}),
258
+ ...(FILES_THROUGH_COMMANDS.has(row.provider) ? { filesThroughCommands: true } : {}),
259
+ measuredAt: rep.date,
260
+ }))
261
+ .sort((a, b) => a.firstAnswerMs - b.firstAnswerMs);
262
+ }
263
+ /**
264
+ * For recommend(): each provider's newest report of the current session, as a job. The time is what a
265
+ * person waits for across the session (every step and call, not the idle minute); the cost is the whole
266
+ * session, idle minute included.
267
+ */
268
+ export function assistantJobs(reports) {
269
+ const latest = new Map();
270
+ for (const rep of reports) {
271
+ if (rep.task !== ASSISTANT_VERSION)
272
+ continue;
273
+ for (const row of rep.rows) {
274
+ if (!KNOWN.has(row.provider) || !benchmarksPublishable(row.provider))
275
+ continue;
276
+ const seen = latest.get(row.provider);
277
+ if (!seen || rep.date > seen.rep.date)
278
+ latest.set(row.provider, { row, rep });
279
+ }
280
+ }
281
+ const out = {};
282
+ for (const [provider, { row, rep }] of [...latest.entries()].sort(([a], [b]) => a.localeCompare(b))) {
283
+ if (!row.sessions.length || row.sessionUsd === undefined)
284
+ continue;
285
+ const id = provider;
286
+ const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
287
+ const waited = (s) => s.firstMs + s.uploadMs + s.analyseMs + s.downloadMs + s.callMs.reduce((a, b) => a + b, 0) + s.idleMs;
288
+ const reused = row.sessions.map((s) => Math.round(taskUsd(id, { ...row.size, cpuUtilization: 0.1 }, s.createMs, s.sessionMs, s.cpuMs, ratio, true, s.maxCoreMs) * 1e9));
289
+ const rules = billingRules(id);
290
+ out[provider] = {
291
+ name: CATALOG.find((c) => c.id === provider).name,
292
+ size: row.size,
293
+ createMs: median(row.sessions.map((s) => s.createMs)),
294
+ taskMs: median(row.sessions.map(waited)),
295
+ taskUsd: row.sessionUsd,
296
+ reusedUsd: median(reused) / 1e9,
297
+ successRate: row.sessions.length / rep.runs,
298
+ runs: rep.runs,
299
+ ok: row.sessions.length,
300
+ ...(rules.minSeconds > 1 ? { minimumSeconds: rules.minSeconds } : {}),
301
+ ...(rules.perSandboxUsd ? { perSandboxUsd: rules.perSandboxUsd } : {}),
302
+ ...(FILES_THROUGH_COMMANDS.has(provider) ? { note: "files go through shell commands on this provider" } : {}),
303
+ measuredAt: rep.date,
304
+ };
305
+ }
306
+ return out;
307
+ }
package/dist/bench.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import { Router, type Size } from "./router.js";
2
2
  import { type TaskKind } from "./task.js";
3
3
  import type { ProviderId, SandboxSpec } from "./types.js";
4
+ /**
5
+ * Providers whose delete request only schedules the deletion: the adapter then waits until the sandbox is
6
+ * gone, so their delete time covers the whole teardown. For the others it is the delete request alone.
7
+ */
8
+ export declare const KILL_WAITS_UNTIL_GONE: ReadonlySet<ProviderId>;
4
9
  export interface BenchRow {
5
10
  provider: ProviderId;
6
11
  runs: number;
@@ -12,6 +17,11 @@ export interface BenchRow {
12
17
  medianExecMs?: number;
13
18
  /** Paired time from request to first successful command. */
14
19
  medianReadyMs?: number;
20
+ /**
21
+ * Median time for the delete call to return, over the sandboxes that started. It is the wait the caller
22
+ * sees: a provider may finish freeing the machine after it answers.
23
+ */
24
+ medianKillMs?: number;
15
25
  hourlyUsd: number;
16
26
  /**
17
27
  * Of the failures, how many the provider refused for a limit or quota on the benchmarking account (a rate limit,
package/dist/bench.js CHANGED
@@ -2,6 +2,11 @@ import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fittingSpec, fixedSize, hourl
2
2
  import { loadBench, median, saveBench } from "./bench-store.js";
3
3
  import { Router, sizeOf } from "./router.js";
4
4
  import { runTask, taskMs, taskUsd, TASKS } from "./task.js";
5
+ /**
6
+ * Providers whose delete request only schedules the deletion: the adapter then waits until the sandbox is
7
+ * gone, so their delete time covers the whole teardown. For the others it is the delete request alone.
8
+ */
9
+ export const KILL_WAITS_UNTIL_GONE = new Set(["northflank", "blaxel"]);
5
10
  /**
6
11
  * Cold start = time from create() call to a usable sandbox. Exec = round trip of `echo ok`.
7
12
  * Measured from wherever you run it, so network distance to each provider counts. Every provider is
@@ -31,6 +36,7 @@ export async function bench(opts) {
31
36
  const createMs = [];
32
37
  const execMs = [];
33
38
  const readyMs = [];
39
+ const killMs = [];
34
40
  const tasks = [];
35
41
  const taskReadyMs = [];
36
42
  let createFailures = 0;
@@ -74,10 +80,13 @@ export async function bench(opts) {
74
80
  }
75
81
  }
76
82
  finally {
77
- await box?.kill().catch((err) => {
78
- cleanupFailures++;
79
- log(`${id} cleanup failed: ${err.message.slice(0, 180)}`);
80
- });
83
+ if (box) {
84
+ const k0 = performance.now();
85
+ await box.kill().then(() => killMs.push(Math.max(1, Math.round(performance.now() - k0))), (err) => {
86
+ cleanupFailures++;
87
+ log(`${id} cleanup failed: ${err.message.slice(0, 180)}`);
88
+ });
89
+ }
81
90
  }
82
91
  }
83
92
  const failures = createFailures + commandFailures;
@@ -93,6 +102,7 @@ export async function bench(opts) {
93
102
  medianCreateMs: median(createMs),
94
103
  medianExecMs: median(execMs),
95
104
  medianReadyMs: median(readyMs),
105
+ ...(killMs.length ? { medianKillMs: median(killMs) } : {}),
96
106
  hourlyUsd: hourlyCost(id, shape),
97
107
  ...(limited ? { limited } : {}),
98
108
  ...(kind ? { taskOk: tasks.length, medianTaskReadyMs: median(taskReadyMs) } : {}),
@@ -134,9 +144,9 @@ export function benchMarkdown(rows) {
134
144
  ? `$${taskUsd(r.provider, r.size ?? fittingSpec(r.provider), r.medianTaskReadyMs, r.medianTaskMs, r.medianTaskCpuMs, 1, false, r.medianTaskMaxCoreMs).toFixed(6)}`
135
145
  : "n/a";
136
146
  const lines = [
137
- `| # | Provider | Create (median) | Ready (median) | Exec round trip |${task ? " Task (median) | Est. task cost | Completed |" : ""} $/hr (list, size run) | Ready |`,
138
- `|---|---|---|---|---|${task ? "---|---|---|" : ""}---|---|`,
139
- ...rows.map((r, i) => `| ${i + 1} | ${name(r.provider)} | ${ms(r.medianCreateMs)} | ${ms(r.medianReadyMs)} | ${ms(r.medianExecMs)} |${task ? ` ${ms(r.medianTaskMs)} | ${cost(r)} | ${r.taskOk ?? 0}/${r.runs} |` : ""} $${r.hourlyUsd.toFixed(3)} | ${r.runs - r.failures}/${r.runs}${r.limited ? ` (${r.limited} refused)` : ""} |`),
147
+ `| # | Provider | Create (median) | Ready (median) | Exec round trip | Delete (median) |${task ? " Task (median) | Est. task cost | Completed |" : ""} $/hr (list, size run) | Ready |`,
148
+ `|---|---|---|---|---|---|${task ? "---|---|---|" : ""}---|---|`,
149
+ ...rows.map((r, i) => `| ${i + 1} | ${name(r.provider)} | ${ms(r.medianCreateMs)} | ${ms(r.medianReadyMs)} | ${ms(r.medianExecMs)} | ${ms(r.medianKillMs)} |${task ? ` ${ms(r.medianTaskMs)} | ${cost(r)} | ${r.taskOk ?? 0}/${r.runs} |` : ""} $${r.hourlyUsd.toFixed(3)} | ${r.runs - r.failures}/${r.runs}${r.limited ? ` (${r.limited} refused)` : ""} |`),
140
150
  ];
141
151
  return lines.join("\n");
142
152
  }
package/dist/catalog.js CHANGED
@@ -519,8 +519,10 @@ ENTRIES.push({
519
519
  name: "Run Cloud",
520
520
  pricing: {
521
521
  vcpuHour: 0.008856,
522
+ reservesCpu: true,
523
+ cpuFloor: 0.125,
522
524
  gbHour: 0.0029943,
523
- note: "per second ($0.00000492 per physical core = 2 vCPUs, $0.00000083175 per GiB); the reservation is the floor, CPU and memory used above it bill at the same rates; $5 to start without a card, then the first $15 a month free with one",
525
+ note: "per second ($0.00000492 per physical core = 2 vCPUs, $0.00000083175 per GiB); the reservation is the floor, CPU and memory used above it bill at the same rates (the adapter reserves cpuUtilization of the size and bursts to the full size); $5 to start without a card, then the first $15 a month free with one",
524
526
  source: "https://run.cloud/pricing",
525
527
  checked: "2026-11-27",
526
528
  },
package/dist/cli.js CHANGED
@@ -26,7 +26,7 @@ Usage:
26
26
  sandboxrouter providers [--vcpu N] [--memory GB] price table + which keys are set
27
27
  sandboxrouter route [spec flags] [route flags] dry run: the order providers would be tried
28
28
  sandboxrouter quote [spec/route flags] [--json] where a create would land and what the run would cost
29
- sandboxrouter recommend [--job short|long|python|download|agent|repo|start] [--count N] [--priority value|cost|speed]
29
+ sandboxrouter recommend [--job short|long|python|download|agent|repo|assistant|start] [--count N] [--priority value|cost|speed]
30
30
  [--reuse] [--provider a,b] [--json]
31
31
  which provider for a job, from the published benchmarks: per successful run, with start
32
32
  times under load for --count 10 and up; --provider limits it to the ones you name
@@ -236,7 +236,7 @@ async function main() {
236
236
  return;
237
237
  }
238
238
  if (cmd === "recommend") {
239
- const jobs = ["start", "short", "long", "python", "download", "agent", "repo"];
239
+ const jobs = ["start", "short", "long", "python", "download", "agent", "repo", "assistant"];
240
240
  const priorities = ["value", "cost", "speed"];
241
241
  const job = (values.job ?? "short");
242
242
  const priority = (values.priority ?? "value");