@sandboxrouter/sdk 0.19.0 → 0.20.1

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/results.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { steadySummary } from "./steady.js";
3
3
  import { assistantSummary } from "./assistant.js";
4
+ import { browserSummary } from "./browser.js";
4
5
  import { join, relative } from "node:path";
5
6
  import { benchmarksPublishable, CATALOG } from "./catalog.js";
6
7
  import { CHECK_STEPS } from "./check.js";
@@ -507,6 +508,53 @@ export function validateResult(j, now = Date.now()) {
507
508
  out.push(`${r.provider}: errors must not be shared (they can hold account details)`);
508
509
  }
509
510
  }
511
+ else if (j.tool === "sandboxrouter-browser") {
512
+ add(checkDate(j.date, now));
513
+ add(checkLabel(j.label));
514
+ add(checkBy(j.by));
515
+ if (typeof j.task !== "string" || !j.task)
516
+ out.push("task must be the browser task's version, e.g. \"browser-v1\"");
517
+ if (!isSize(j.spec))
518
+ out.push("spec must record the requested size");
519
+ if (!Number.isInteger(j.runs) || !isNum(j.runs, 3, 100))
520
+ out.push("runs must be at least 3 sessions");
521
+ if (!Number.isInteger(j.pages) || !isNum(j.pages, 1, 100) || !Number.isInteger(j.reloads) || !isNum(j.reloads, 1, 100))
522
+ out.push("pages and reloads must record how many pages were loaded");
523
+ if (!Array.isArray(j.rows) || !j.rows.length)
524
+ out.push("rows is empty");
525
+ for (const r of Array.isArray(j.rows) ? j.rows : []) {
526
+ provider(r?.provider, "row provider");
527
+ if (noBench(r?.provider))
528
+ out.push(`${r.provider}: ${NO_BENCH}`);
529
+ if (!isSize(r?.size))
530
+ out.push(`${r?.provider}: invalid sandbox size`);
531
+ const sessions = Array.isArray(r?.sessions) ? r.sessions : undefined;
532
+ const times = ["createMs", "setupMs", "launchMs", "workMs", "screenshotMs", "taskMs"];
533
+ const list = (v, n) => Array.isArray(v) && v.length === n && v.every((x) => isNum(x, 1, MAX_MS));
534
+ const whole = (s) => times.every((k) => isNum(s?.[k], 1, MAX_MS)) && list(s.pageMs, j.pages) && list(s.reloadMs, j.reloads) && isNum(s.screenshotBytes, 1, 1e9) &&
535
+ (s.cpuMs === undefined || isNum(s.cpuMs, 0, MAX_MS * 1024)) && (s.maxCoreMs === undefined || isNum(s.maxCoreMs, 0, MAX_MS));
536
+ if (!sessions || !sessions.every(whole)) {
537
+ out.push(`${r?.provider}: every session must list its times (1 ms to 15 min), one per page and one per reload`);
538
+ continue;
539
+ }
540
+ if (!isCount(r.failures, j.runs) || sessions.length + r.failures !== j.runs)
541
+ out.push(`${r.provider}: sessions plus failures must equal the sessions asked for`);
542
+ const stopped = r.failedAt === undefined ? 0 : ["create", "setup", "browse"].reduce((n, k) => n + (r.failedAt[k] ?? 0), 0);
543
+ if (r.failedAt !== undefined && (typeof r.failedAt !== "object" || Object.keys(r.failedAt).some((k) => !["create", "setup", "browse"].includes(k)) || stopped !== r.failures)) {
544
+ out.push(`${r.provider}: failedAt must count the failures by step (create, setup, browse)`);
545
+ }
546
+ const want = browserSummary(sessions);
547
+ for (const k of ["readyMs", "launchMs", "pageMs", "reloadMs", "workMs", "screenshotMs", "taskMs"]) {
548
+ if (r[k] !== want[k])
549
+ out.push(`${r.provider}: ${k} does not match the sessions`);
550
+ }
551
+ for (const k of ["sessionUsd", "taskUsd", "hourlyUsd"])
552
+ if (r[k] !== undefined && !isNum(r[k], 0, 1000))
553
+ out.push(`${r.provider}: ${k} is out of range`);
554
+ if ("error" in r || "lastError" in r)
555
+ out.push(`${r.provider}: errors must not be shared (they can hold account details)`);
556
+ }
557
+ }
510
558
  else {
511
559
  out.push(`unknown tool "${String(j.tool)}": expected a benchmark report, saved check, cost run or hosted ledger check`);
512
560
  }
package/dist/router.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type ProviderInfo } from "./catalog.js";
2
2
  import { type ComputerRoute, RoutedComputer, type ComputerOs, type ComputerProvider, type ComputerProviderId, type ComputerSpec } from "./computers.js";
3
3
  import { Ledger } from "./ledger.js";
4
4
  import { type CopyOptions, type CopyResult, type FileBox, type MoveOptions } from "./move.js";
5
+ import { type Keeper, type KeepOptions, type RecoverOptions, type RestoreOptions, type RestoreResult, type Saved, type SaveOptions, type SaveStore } from "./save.js";
5
6
  import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxProcess, type SandboxSpec, type StartOptions } from "./types.js";
6
7
  /** vCPUs and memory a sandbox gets. */
7
8
  export interface Size {
@@ -245,6 +246,27 @@ export declare class Router {
245
246
  move(from: FileBox, opts?: MoveOptions): Promise<RoutedSandbox & {
246
247
  moved: CopyResult;
247
248
  }>;
249
+ /**
250
+ * Save a sandbox's folder to your own storage (`folderStore(dir)`, or anything with put/get/delete),
251
+ * so the work outlives the sandbox. Files only. Saving under the same name replaces the last save.
252
+ *
253
+ * const store = folderStore("./saves");
254
+ * await router.save(sbx, store, { name: "job-42", exclude: ["node_modules"] });
255
+ */
256
+ save(box: FileBox, store: SaveStore, opts?: SaveOptions): Promise<Saved>;
257
+ /** Save a sandbox's folder every `everySeconds` (default 300) while it works. Call `stop()` when the job ends. */
258
+ keepSaved(box: FileBox, store: SaveStore, opts?: KeepOptions): Keeper;
259
+ /** Put a saved folder into a sandbox you already have. */
260
+ restore(box: FileBox, store: SaveStore, name: string, opts?: RestoreOptions): Promise<RestoreResult>;
261
+ /**
262
+ * Start a new sandbox with a saved folder in it, for when the sandbox doing the work is gone. Other
263
+ * providers are tried first and the one the save came from last, unless `provider` names where to go.
264
+ *
265
+ * sbx = await router.recover(store, "job-42");
266
+ */
267
+ recover(store: SaveStore, name: string, opts?: RecoverOptions): Promise<RoutedSandbox & {
268
+ restored: RestoreResult;
269
+ }>;
248
270
  /** Reattach to a sandbox by its routed id (`provider:nativeId`). */
249
271
  get(id: string): Promise<RoutedSandbox>;
250
272
  }
package/dist/router.js CHANGED
@@ -6,6 +6,7 @@ import { PUBLISHED } from "./published.js";
6
6
  import { Ledger, defaultLedgerFile } from "./ledger.js";
7
7
  import { DEFAULT_EXEC_TIMEOUT_S, LIMIT_ERROR, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
8
8
  import { copyFiles, moveSandbox } from "./move.js";
9
+ import { keepSaved, recoverSandbox, restoreFiles, saveFiles } from "./save.js";
9
10
  import { BILLED_VS_LIST } from "./billing.js";
10
11
  import { FAILING, VERIFIED } from "./verified.js";
11
12
  import { isPort, validate, validateStart } from "./validate.js";
@@ -493,6 +494,33 @@ export class Router {
493
494
  move(from, opts = {}) {
494
495
  return moveSandbox({ candidates: async (spec, route) => this.plan(spec, route), create: (spec, route) => this.create(spec, route) }, from, opts);
495
496
  }
497
+ /**
498
+ * Save a sandbox's folder to your own storage (`folderStore(dir)`, or anything with put/get/delete),
499
+ * so the work outlives the sandbox. Files only. Saving under the same name replaces the last save.
500
+ *
501
+ * const store = folderStore("./saves");
502
+ * await router.save(sbx, store, { name: "job-42", exclude: ["node_modules"] });
503
+ */
504
+ save(box, store, opts = {}) {
505
+ return saveFiles(box, store, opts);
506
+ }
507
+ /** Save a sandbox's folder every `everySeconds` (default 300) while it works. Call `stop()` when the job ends. */
508
+ keepSaved(box, store, opts = {}) {
509
+ return keepSaved(box, store, opts);
510
+ }
511
+ /** Put a saved folder into a sandbox you already have. */
512
+ restore(box, store, name, opts = {}) {
513
+ return restoreFiles(box, store, name, opts);
514
+ }
515
+ /**
516
+ * Start a new sandbox with a saved folder in it, for when the sandbox doing the work is gone. Other
517
+ * providers are tried first and the one the save came from last, unless `provider` names where to go.
518
+ *
519
+ * sbx = await router.recover(store, "job-42");
520
+ */
521
+ recover(store, name, opts = {}) {
522
+ return recoverSandbox({ candidates: async (spec, route) => this.plan(spec, route), create: (spec, route) => this.create(spec, route) }, store, name, opts);
523
+ }
496
524
  /** Reattach to a sandbox by its routed id (`provider:nativeId`). */
497
525
  async get(id) {
498
526
  const { provider, nativeId } = parseId(id);
package/dist/save.d.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { type FileBox, type Mover } from "./move.js";
2
+ import { type RouteOptions, type SandboxSpec } from "./types.js";
3
+ /**
4
+ * Where saved folders are kept: your own storage. Two keys are written per name, a small JSON record
5
+ * and the packed folder. `folderStore` keeps them on this machine's disk; anything with these three
6
+ * calls works (S3, R2, a database).
7
+ */
8
+ export interface SaveStore {
9
+ put(key: string, data: Uint8Array): Promise<void>;
10
+ /** Undefined when there is nothing under the key. */
11
+ get(key: string): Promise<Uint8Array | undefined>;
12
+ delete(key: string): Promise<void>;
13
+ }
14
+ /** A `SaveStore` that is a folder on this machine. */
15
+ export declare function folderStore(dir: string): SaveStore;
16
+ export interface SaveOptions {
17
+ /** What this save is called. Saving under the same name again replaces it. Default: the sandbox's id. */
18
+ name?: string;
19
+ /** Folder to save. Default: the folder the sandbox's commands run in. */
20
+ path?: string;
21
+ /** Names or patterns to leave out, as `tar --exclude` reads them, e.g. `["node_modules", ".venv"]`. */
22
+ exclude?: string[];
23
+ /** Refuse when the packed folder is bigger than this (default 200 MB). It passes through this process's memory. */
24
+ maxBytes?: number;
25
+ /** Seconds the pack command may take (default 600). */
26
+ timeoutSeconds?: number;
27
+ /** Bytes read per file transfer (default 4 MB). */
28
+ chunkBytes?: number;
29
+ }
30
+ /** The record of one save. */
31
+ export interface Saved {
32
+ name: string;
33
+ /** When it was taken (ISO). */
34
+ at: string;
35
+ /** The provider the sandbox was on. */
36
+ provider: string;
37
+ /** The sandbox's id. */
38
+ sandbox: string;
39
+ /** The folder that was saved. */
40
+ folder: string;
41
+ /** True when it was the sandbox's own working folder (no `path` given). */
42
+ whole: boolean;
43
+ /** Size of the packed (gzip) folder. */
44
+ bytes: number;
45
+ /** The sandbox's size, so a recovered one can match it. */
46
+ size?: {
47
+ vcpu: number;
48
+ memoryGb: number;
49
+ };
50
+ /** The store key holding the packed folder. */
51
+ blob: string;
52
+ }
53
+ export interface RestoreOptions {
54
+ /** Folder to unpack into. Default: the saved folder's path, or the sandbox's own working folder when that was what was saved. */
55
+ to?: string;
56
+ /** Seconds the unpack command may take (default 600). */
57
+ timeoutSeconds?: number;
58
+ /** Bytes sent per file transfer (default 4 MB). */
59
+ chunkBytes?: number;
60
+ }
61
+ export interface RestoreResult {
62
+ name: string;
63
+ /** When the save that was put back was taken (ISO). */
64
+ at: string;
65
+ /** The folder written. */
66
+ to: string;
67
+ bytes: number;
68
+ ms: number;
69
+ }
70
+ export interface RecoverOptions extends RestoreOptions, RouteOptions {
71
+ /** The new sandbox's spec. Its size defaults to the saved sandbox's. */
72
+ spec?: SandboxSpec;
73
+ }
74
+ export interface KeepOptions extends SaveOptions {
75
+ /** Seconds between saves, counted from the end of one to the start of the next (default 300, at least 30). */
76
+ everySeconds?: number;
77
+ onSave?: (saved: Saved) => void;
78
+ /** A save that failed. Saving carries on at the next interval. */
79
+ onError?: (error: unknown) => void;
80
+ }
81
+ /** A running `keepSaved`. */
82
+ export interface Keeper {
83
+ /** The newest save, if one has finished. */
84
+ readonly last: Saved | undefined;
85
+ /** Save now, outside the interval. */
86
+ saveNow(): Promise<Saved>;
87
+ /** Stop saving. Waits for a save in flight; pass `{ save: true }` to take one last save first. */
88
+ stop(opts?: {
89
+ save?: boolean;
90
+ }): Promise<void>;
91
+ }
92
+ export declare const DEFAULT_SAVE_MAX_BYTES: number;
93
+ export declare const DEFAULT_SAVE_EVERY_S = 300;
94
+ export declare const MIN_SAVE_EVERY_S = 30;
95
+ /** The record of the newest save under a name, or undefined. */
96
+ export declare function findSaved(store: SaveStore, name: string): Promise<Saved | undefined>;
97
+ /**
98
+ * Save a sandbox's folder to your own storage, so the work outlives the sandbox: packed with tar in
99
+ * the sandbox, read out in pieces, written to the store. Files, their modes and symlinks are saved;
100
+ * running processes, memory and env vars are not. A new save under the same name replaces the old
101
+ * one only once it is complete, so a save cut short (the sandbox died halfway) leaves the last good
102
+ * one in place. A file being written at that moment may be saved half-written.
103
+ */
104
+ export declare function saveFiles(box: FileBox, store: SaveStore, opts?: SaveOptions): Promise<Saved>;
105
+ /** Put a saved folder into a sandbox you already have, on any provider. */
106
+ export declare function restoreFiles(box: FileBox, store: SaveStore, name: string, opts?: RestoreOptions): Promise<RestoreResult>;
107
+ /**
108
+ * Start a new sandbox and put a saved folder into it: what to call when the sandbox that was doing
109
+ * the work is gone. Without a named provider it tries the other providers first and the one the
110
+ * save came from last. The new sandbox gets the saved one's size where a provider sells it.
111
+ */
112
+ export declare function recoverSandbox<B extends FileBox>(mover: Mover<B>, store: SaveStore, name: string, opts?: RecoverOptions): Promise<B & {
113
+ restored: RestoreResult;
114
+ }>;
115
+ /**
116
+ * Save a sandbox's folder again and again while it works, so a sandbox that dies costs the minutes
117
+ * since the last save and not the whole run. Saves never overlap. One that fails is reported to
118
+ * `onError` and the next is tried at the usual interval.
119
+ */
120
+ export declare function keepSaved(box: FileBox, store: SaveStore, opts?: KeepOptions): Keeper;
package/dist/save.js ADDED
@@ -0,0 +1,276 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { IMAGE_FILES, mb, workdir } from "./move.js";
5
+ import { RouterError } from "./types.js";
6
+ import { shq } from "./util.js";
7
+ /** A `SaveStore` that is a folder on this machine. */
8
+ export function folderStore(dir) {
9
+ const file = (key) => {
10
+ if (!KEY.test(key))
11
+ throw new RouterError(`bad save key "${key}"`, [], "bad_request");
12
+ return join(dir, key);
13
+ };
14
+ return {
15
+ async put(key, data) {
16
+ await mkdir(dir, { recursive: true });
17
+ // Written beside the file and renamed, so a reader never sees half of it.
18
+ const tmp = `${file(key)}.${randomUUID().slice(0, 8)}.tmp`;
19
+ await writeFile(tmp, data);
20
+ await rename(tmp, file(key));
21
+ },
22
+ async get(key) {
23
+ try {
24
+ return new Uint8Array(await readFile(file(key)));
25
+ }
26
+ catch (error) {
27
+ if (error.code === "ENOENT")
28
+ return undefined;
29
+ throw error;
30
+ }
31
+ },
32
+ async delete(key) {
33
+ await rm(file(key), { force: true });
34
+ },
35
+ };
36
+ }
37
+ export const DEFAULT_SAVE_MAX_BYTES = 200 * 1024 * 1024;
38
+ export const DEFAULT_SAVE_EVERY_S = 300;
39
+ export const MIN_SAVE_EVERY_S = 30;
40
+ const DEFAULT_CHUNK_BYTES = 4 * 1024 * 1024;
41
+ const DEFAULT_TIMEOUT_S = 600;
42
+ const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
43
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/;
44
+ /** A store-safe name: what was given, or the sandbox id with its separators replaced. */
45
+ function saveName(given, box) {
46
+ const name = given ?? box.id.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "");
47
+ if (!NAME.test(name))
48
+ throw new RouterError(`bad save name "${name}": use letters, digits, ".", "_" and "-" (120 at most)`, [], "bad_request");
49
+ return name;
50
+ }
51
+ const recordKey = (name) => `${name}.json`;
52
+ /** The record of the newest save under a name, or undefined. */
53
+ export async function findSaved(store, name) {
54
+ if (!NAME.test(name))
55
+ throw new RouterError(`bad save name "${name}"`, [], "bad_request");
56
+ const raw = await store.get(recordKey(name));
57
+ if (!raw)
58
+ return undefined;
59
+ try {
60
+ const saved = JSON.parse(new TextDecoder().decode(raw));
61
+ if (typeof saved.blob !== "string" || typeof saved.folder !== "string" || typeof saved.bytes !== "number")
62
+ throw new Error("missing fields");
63
+ return saved;
64
+ }
65
+ catch (error) {
66
+ throw new RouterError(`the record of save "${name}" can't be read: ${error.message}`, [], "all_failed");
67
+ }
68
+ }
69
+ const absolute = (p, what) => {
70
+ if (!p.startsWith("/"))
71
+ throw new RouterError(`${what} needs an absolute path, got "${p}"`, [], "bad_request");
72
+ if (p.replace(/\/+$/, "") === "")
73
+ throw new RouterError(`${what} won't take the whole filesystem (/): name a folder`, [], "bad_request");
74
+ };
75
+ async function run(box, what, cmd, timeoutSeconds) {
76
+ const r = await box.exec(cmd, { timeoutSeconds });
77
+ if (r.exitCode !== 0) {
78
+ const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ");
79
+ throw new RouterError(`${what} failed on ${box.provider} (exit ${r.exitCode})${detail ? `: ${detail}` : ""}`, [], "all_failed");
80
+ }
81
+ return r.stdout;
82
+ }
83
+ /**
84
+ * Save a sandbox's folder to your own storage, so the work outlives the sandbox: packed with tar in
85
+ * the sandbox, read out in pieces, written to the store. Files, their modes and symlinks are saved;
86
+ * running processes, memory and env vars are not. A new save under the same name replaces the old
87
+ * one only once it is complete, so a save cut short (the sandbox died halfway) leaves the last good
88
+ * one in place. A file being written at that moment may be saved half-written.
89
+ */
90
+ export async function saveFiles(box, store, opts = {}) {
91
+ const name = saveName(opts.name, box);
92
+ const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_TIMEOUT_S;
93
+ const chunk = Math.max(64 * 1024, Math.floor(opts.chunkBytes ?? DEFAULT_CHUNK_BYTES));
94
+ const maxBytes = opts.maxBytes ?? DEFAULT_SAVE_MAX_BYTES;
95
+ const folder = opts.path ?? (await workdir(box));
96
+ absolute(folder, "save");
97
+ const tmp = `/tmp/sr-save-${randomUUID().slice(0, 8)}`;
98
+ try {
99
+ const excludes = ["sr-save-*", "sr-move-*", ...(opts.exclude ?? [])].map((e) => `--exclude=${shq(e)}`).join(" ");
100
+ // tar exits 1 when a file changed while it was read. On a sandbox with work in progress that is
101
+ // expected and the archive is still whole, so only 2 and above count as failure.
102
+ const packed = await run(box, "packing the folder", [
103
+ `mkdir -p ${shq(tmp)}`,
104
+ `{ tar -czf ${shq(`${tmp}/a.tgz`)} ${excludes} -C ${shq(folder)} . ; rc=$?; [ "$rc" -le 1 ] || exit "$rc"; }`,
105
+ `echo "size=$(wc -c < ${shq(`${tmp}/a.tgz`)} | tr -d ' ')"`,
106
+ ].join(" && "), timeoutSeconds);
107
+ const bytes = Number(/size=(\d+)/.exec(packed)?.[1] ?? NaN);
108
+ if (!Number.isFinite(bytes))
109
+ throw new RouterError(`couldn't read the packed size on ${box.provider}`, [], "all_failed");
110
+ if (bytes > maxBytes) {
111
+ throw new RouterError(`the folder packs to ${mb(bytes)}, over the ${mb(maxBytes)} limit: pass path or exclude (e.g. node_modules), or a higher maxBytes`, [], "bad_request");
112
+ }
113
+ const listed = await run(box, "splitting the archive", `cd ${shq(tmp)} && split -b ${chunk} -a 4 a.tgz p. && rm a.tgz && ls p.*`, timeoutSeconds);
114
+ const parts = listed.split("\n").map((l) => l.trim()).filter((l) => /^p\.[a-z]{4}$/.test(l)).sort();
115
+ if (parts.length === 0)
116
+ throw new RouterError(`no archive pieces found on ${box.provider}`, [], "all_failed");
117
+ const data = new Uint8Array(bytes);
118
+ let at = 0;
119
+ for (const part of parts) {
120
+ const piece = await box.readFile(`${tmp}/${part}`);
121
+ if (at + piece.length > bytes)
122
+ throw new RouterError(`the archive read from ${box.provider} is longer than the ${bytes} bytes it packed`, [], "all_failed");
123
+ data.set(piece, at);
124
+ at += piece.length;
125
+ }
126
+ // Catches a piece a provider cut short before a broken archive replaces a good save.
127
+ if (at !== bytes)
128
+ throw new RouterError(`the archive read from ${box.provider} is ${at} bytes, expected ${bytes}`, [], "all_failed");
129
+ const before = await findSaved(store, name).catch(() => undefined);
130
+ const saved = {
131
+ name,
132
+ at: new Date().toISOString(),
133
+ provider: box.provider,
134
+ sandbox: box.id,
135
+ folder,
136
+ whole: opts.path === undefined,
137
+ bytes,
138
+ ...(box.size ? { size: { vcpu: box.size.vcpu, memoryGb: box.size.memoryGb } } : {}),
139
+ blob: `${name}.${Date.now().toString(36)}${randomUUID().slice(0, 4)}.tgz`,
140
+ };
141
+ // The packed folder first, the record last: the record only ever points at a complete archive.
142
+ await store.put(saved.blob, data);
143
+ await store.put(recordKey(name), new TextEncoder().encode(JSON.stringify(saved, null, 2) + "\n"));
144
+ if (before && before.blob !== saved.blob)
145
+ await store.delete(before.blob).catch(() => { });
146
+ return saved;
147
+ }
148
+ finally {
149
+ await box.exec(`rm -rf ${shq(tmp)}`, { timeoutSeconds: 60 }).catch(() => { });
150
+ }
151
+ }
152
+ /** Put a saved folder into a sandbox you already have, on any provider. */
153
+ export async function restoreFiles(box, store, name, opts = {}) {
154
+ const started = Date.now();
155
+ const saved = await findSaved(store, name);
156
+ if (!saved)
157
+ throw new RouterError(`nothing is saved as "${name}"`, [], "bad_request");
158
+ const data = await store.get(saved.blob);
159
+ if (!data)
160
+ throw new RouterError(`save "${name}" has a record but its archive (${saved.blob}) is missing from the store`, [], "all_failed");
161
+ if (data.length !== saved.bytes)
162
+ throw new RouterError(`save "${name}" is ${data.length} bytes in the store, its record says ${saved.bytes}`, [], "all_failed");
163
+ const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_TIMEOUT_S;
164
+ const chunk = Math.max(64 * 1024, Math.floor(opts.chunkBytes ?? DEFAULT_CHUNK_BYTES));
165
+ // A saved working folder goes into the new sandbox's own working folder, wherever its image puts that.
166
+ // Some images run commands in / (Modal's stock one): there the folder goes back at the path it was saved from.
167
+ const own = saved.whole && opts.to === undefined ? await workdir(box) : undefined;
168
+ const ownFolder = own !== undefined && own.replace(/\/+$/, "") !== "";
169
+ const to = opts.to ?? (ownFolder ? own : saved.folder);
170
+ absolute(to, "restore");
171
+ const tmp = `/tmp/sr-save-${randomUUID().slice(0, 8)}`;
172
+ try {
173
+ await run(box, "preparing the sandbox", `mkdir -p ${shq(tmp)} ${shq(to)}`, timeoutSeconds);
174
+ for (let i = 0, n = 0; i < data.length || n === 0; i += chunk, n++) {
175
+ await box.writeFile(`${tmp}/p.${String(n).padStart(6, "0")}`, data.subarray(i, i + chunk));
176
+ }
177
+ const got = await run(box, "checking the archive", `cat ${shq(tmp)}/p.* | wc -c | tr -d ' '`, timeoutSeconds);
178
+ if (Number(got.trim().split("\n").pop()) !== saved.bytes) {
179
+ throw new RouterError(`the archive arrived as ${got.trim()} bytes on ${box.provider}, expected ${saved.bytes}`, [], "all_failed");
180
+ }
181
+ // As in a move: the sandbox keeps its own image's shell startup files when a whole working folder is put back.
182
+ const keep = ownFolder ? IMAGE_FILES.map(shq).join(" ") : "";
183
+ const hold = keep ? `mkdir -p ${shq(`${tmp}/keep`)} && for f in ${keep}; do if [ -f ${shq(to)}/"$f" ]; then cp -p ${shq(to)}/"$f" ${shq(`${tmp}/keep`)}/; fi; done && ` : "";
184
+ const back = keep ? ` && for f in ${keep}; do if [ -f ${shq(`${tmp}/keep`)}/"$f" ]; then cp -p ${shq(`${tmp}/keep`)}/"$f" ${shq(to)}/; fi; done` : "";
185
+ await run(box, "unpacking the folder", `${hold}cat ${shq(tmp)}/p.* | tar -xzo -f - -C ${shq(to)}${back}`, timeoutSeconds);
186
+ return { name, at: saved.at, to, bytes: saved.bytes, ms: Date.now() - started };
187
+ }
188
+ finally {
189
+ await box.exec(`rm -rf ${shq(tmp)}`, { timeoutSeconds: 60 }).catch(() => { });
190
+ }
191
+ }
192
+ /**
193
+ * Start a new sandbox and put a saved folder into it: what to call when the sandbox that was doing
194
+ * the work is gone. Without a named provider it tries the other providers first and the one the
195
+ * save came from last. The new sandbox gets the saved one's size where a provider sells it.
196
+ */
197
+ export async function recoverSandbox(mover, store, name, opts = {}) {
198
+ const { spec: given = {}, to, timeoutSeconds, chunkBytes, ...route } = opts;
199
+ const saved = await findSaved(store, name);
200
+ if (!saved)
201
+ throw new RouterError(`nothing is saved as "${name}"`, [], "bad_request");
202
+ const usable = async (s) => (await mover.candidates(s, route)).filter((c) => !c.skip).map((c) => c.provider);
203
+ const sized = given.vcpu === undefined && given.memoryGb === undefined && saved.size ? { ...given, vcpu: saved.size.vcpu, memoryGb: saved.size.memoryGb } : undefined;
204
+ let spec = { ...given };
205
+ let list = sized ? await usable(sized) : [];
206
+ if (list.length > 0)
207
+ spec = sized;
208
+ else
209
+ list = await usable(spec);
210
+ if (list.length === 0)
211
+ throw new RouterError(`no provider can take save "${name}"`, [], "no_provider");
212
+ if (route.provider === undefined)
213
+ route.provider = [...list.filter((p) => p !== saved.provider), ...list.filter((p) => p === saved.provider)];
214
+ const next = await mover.create(spec, route);
215
+ try {
216
+ const restored = await restoreFiles(next, store, name, { to, timeoutSeconds, chunkBytes });
217
+ return Object.assign(next, { restored });
218
+ }
219
+ catch (error) {
220
+ await next.kill().catch(() => { });
221
+ throw error;
222
+ }
223
+ }
224
+ /**
225
+ * Save a sandbox's folder again and again while it works, so a sandbox that dies costs the minutes
226
+ * since the last save and not the whole run. Saves never overlap. One that fails is reported to
227
+ * `onError` and the next is tried at the usual interval.
228
+ */
229
+ export function keepSaved(box, store, opts = {}) {
230
+ const { everySeconds = DEFAULT_SAVE_EVERY_S, onSave, onError, ...save } = opts;
231
+ if (!Number.isFinite(everySeconds) || everySeconds < MIN_SAVE_EVERY_S) {
232
+ throw new RouterError(`everySeconds must be at least ${MIN_SAVE_EVERY_S}, got ${everySeconds}`, [], "bad_request");
233
+ }
234
+ // The name is fixed once, so every save replaces the one before it.
235
+ const name = saveName(save.name, box);
236
+ let last;
237
+ let stopped = false;
238
+ let timer;
239
+ let inFlight = Promise.resolve();
240
+ const saveNow = () => {
241
+ const next = inFlight.then(async () => {
242
+ const saved = await saveFiles(box, store, { ...save, name });
243
+ last = saved;
244
+ onSave?.(saved);
245
+ return saved;
246
+ });
247
+ inFlight = next.catch(() => { });
248
+ return next;
249
+ };
250
+ const arm = () => {
251
+ if (stopped)
252
+ return;
253
+ timer = setTimeout(() => {
254
+ saveNow()
255
+ .catch((error) => onError?.(error))
256
+ .finally(arm);
257
+ }, everySeconds * 1000);
258
+ // A pending save never keeps the process alive on its own.
259
+ timer.unref?.();
260
+ };
261
+ arm();
262
+ return {
263
+ get last() {
264
+ return last;
265
+ },
266
+ saveNow,
267
+ async stop(o = {}) {
268
+ stopped = true;
269
+ if (timer)
270
+ clearTimeout(timer);
271
+ if (o.save)
272
+ await saveNow();
273
+ await inFlight;
274
+ },
275
+ };
276
+ }
package/dist/types.d.ts CHANGED
@@ -38,6 +38,8 @@ export interface SandboxSpec {
38
38
  /**
39
39
  * Provider-specific image/template, keyed by provider, e.g.
40
40
  * { maritime: "python", e2b: "code-interpreter-v1", modal: "python:3.13-slim" }.
41
+ * Once any image is named, only the providers named are routed to: the sandbox never starts on a
42
+ * provider's default image by fallback. Routing picks among them as usual (cheapest, fastest).
41
43
  */
42
44
  image?: Partial<Record<ProviderId, string>>;
43
45
  /** Free-form tags stored on the sandbox where the provider supports it. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.19.0",
3
+ "version": "0.20.1",
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",
@@ -76,30 +76,30 @@
76
76
  "node": ">=20"
77
77
  },
78
78
  "peerDependencies": {
79
+ "@aws-crypto/sha256-js": ">=5",
80
+ "@aws-sdk/client-appstream": ">=3",
81
+ "@aws-sdk/credential-provider-node": ">=3",
82
+ "@beamcloud/beam-js": ">=1.1.6",
79
83
  "@blaxel/core": ">=0.3",
84
+ "@codesandbox/sdk": ">=2.4",
80
85
  "@daytonaio/sdk": ">=0.200",
86
+ "@deno/sandbox": ">=0.13.0 <0.14.0",
81
87
  "@e2b/desktop": ">=2.5",
82
88
  "@fly/sprites": ">=0.2",
83
89
  "@hopx-ai/sdk": ">=0.5",
90
+ "@limrun/api": ">=0.69",
91
+ "@mobilerun/sdk": ">=6",
84
92
  "@northflank/js-client": ">=0.12",
85
93
  "@runloop/api-client": ">=3",
94
+ "@smithy/signature-v4": ">=5",
86
95
  "@tensorlakeai/tensorlake": ">=0.5",
87
- "@vercel/sandbox": ">=3",
96
+ "@vercel/sandbox": ">=5",
88
97
  "e2b": ">=2",
98
+ "google-auth-library": "^10.0.0",
99
+ "langsmith": ">=0.11",
89
100
  "modal": ">=0.11",
90
101
  "morphcloud": ">=0.0.20",
91
- "google-auth-library": "^10.0.0",
92
- "@mobilerun/sdk": ">=6",
93
- "@limrun/api": ">=0.69",
94
- "@aws-sdk/client-appstream": ">=3",
95
- "@smithy/signature-v4": ">=5",
96
- "@aws-crypto/sha256-js": ">=5",
97
- "@aws-sdk/credential-provider-node": ">=3",
98
- "@beamcloud/beam-js": ">=1.1.6",
99
- "@codesandbox/sdk": ">=2.4",
100
- "@deno/sandbox": ">=0.13.0 <0.14.0",
101
- "novita-sandbox": ">=2",
102
- "langsmith": ">=0.11"
102
+ "novita-sandbox": ">=2"
103
103
  },
104
104
  "peerDependenciesMeta": {
105
105
  "e2b": {
@@ -180,21 +180,22 @@
180
180
  "@aws-sdk/client-appstream": "^3.1162.0",
181
181
  "@aws-sdk/credential-provider-node": "^3.972.93",
182
182
  "@blaxel/core": "^0.3.34",
183
- "@daytonaio/sdk": "^0.232.0",
183
+ "@daytonaio/sdk": "^0.234.0",
184
184
  "@e2b/desktop": "^2.5.0",
185
185
  "@fly/sprites": "^0.2.4",
186
186
  "@hopx-ai/sdk": "^0.5.1",
187
- "@limrun/api": "^0.74.0",
187
+ "@limrun/api": "^0.79.6",
188
188
  "@mobilerun/sdk": "^6.1.0",
189
189
  "@northflank/js-client": "^0.13.0",
190
190
  "@runloop/api-client": "^3.0.0",
191
191
  "@smithy/signature-v4": "^5.7.5",
192
192
  "@tensorlakeai/tensorlake": "^0.5.161",
193
193
  "@types/node": "^26.6.6",
194
- "@vercel/sandbox": "^4.0.0",
194
+ "@vercel/sandbox": "^5.0.0",
195
195
  "e2b": "^2.63.0",
196
196
  "modal": "^0.11.1",
197
197
  "morphcloud": "^0.0.20",
198
+ "novita-sandbox": "^2.1.6",
198
199
  "tsx": "^4.23.15",
199
200
  "typescript": "^7.0.2",
200
201
  "vitest": "^5.1.0"