@sandboxrouter/sdk 0.15.2 → 0.17.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/cli.js CHANGED
@@ -214,6 +214,11 @@ async function main() {
214
214
  if (!command)
215
215
  throw new RouterError('usage: sandboxrouter compare "<cmd>" [--setup "<cmd>"] [--runs 3] [--provider a,b]');
216
216
  const ids = providers ?? router.registered().filter((id) => router.isConfigured(id));
217
+ // With no keys there is nothing to compare: say so instead of printing an empty table.
218
+ if (!ids.length) {
219
+ throw new RouterError("no provider keys found: set the API key for at least one provider (the README's Env table lists each provider's variables); " +
220
+ "`npx @sandboxrouter/sdk providers` shows which are set");
221
+ }
217
222
  const rows = await compare({ router, providers: ids, command, setup: values.setup, runs: num(values.runs), timeoutSeconds: num(values.seconds), parallel: num(values.parallel), onProgress: (m) => console.error(m) });
218
223
  if (values.json)
219
224
  return console.log(JSON.stringify(rows, null, 2));
package/dist/client.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Candidate, Quote, Size } from "./router.js";
2
+ import { type CopyOptions, type CopyResult, type FileBox, type MoveOptions } from "./move.js";
2
3
  import type { Attempt, Capability, ExecOptions, ExecResult, RouteOptions, RouterErrorCode, SandboxProcess, SandboxSpec, StartOptions } from "./types.js";
3
4
  /**
4
5
  * Client for the sandboxrouter HTTP API: the hosted service (one key, prepaid credits) or your own
@@ -42,6 +43,15 @@ export declare class Client {
42
43
  create(spec?: SandboxSpec, route?: RouteOptions, opts?: {
43
44
  idempotencyKey?: string;
44
45
  }): Promise<RemoteSandbox>;
46
+ /** Copy a folder from one sandbox to another, on any two providers. The files pass through this machine. */
47
+ copy(from: FileBox, to: FileBox, opts?: CopyOptions): Promise<CopyResult>;
48
+ /**
49
+ * Move a sandbox's folder to a new sandbox and kill the old one: on another provider by default,
50
+ * or on the ones `provider` names. If the new one can't start or the copy fails, the old sandbox is left running.
51
+ */
52
+ move(from: FileBox, opts?: MoveOptions): Promise<RemoteSandbox & {
53
+ moved: CopyResult;
54
+ }>;
45
55
  /** A handle on a sandbox you created earlier. */
46
56
  sandbox(id: string): RemoteSandbox;
47
57
  }
package/dist/client.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { copyFiles, moveSandbox } from "./move.js";
1
2
  /**
2
3
  * Client for the sandboxrouter HTTP API: the hosted service (one key, prepaid credits) or your own
3
4
  * `sandboxrouter serve`. Provider keys live on the server; this side only needs the one key.
@@ -66,6 +67,17 @@ export class Client {
66
67
  const r = (await res.json());
67
68
  return new RemoteSandbox(this, r.id, r.provider, { ...r, replayed: res.headers.get("idempotent-replayed") === "true" });
68
69
  }
70
+ /** Copy a folder from one sandbox to another, on any two providers. The files pass through this machine. */
71
+ copy(from, to, opts = {}) {
72
+ return copyFiles(from, to, opts);
73
+ }
74
+ /**
75
+ * Move a sandbox's folder to a new sandbox and kill the old one: on another provider by default,
76
+ * or on the ones `provider` names. If the new one can't start or the copy fails, the old sandbox is left running.
77
+ */
78
+ move(from, opts = {}) {
79
+ return moveSandbox({ candidates: (spec, route) => this.route(spec, route), create: (spec, route) => this.create(spec, route) }, from, opts);
80
+ }
69
81
  /** A handle on a sandbox you created earlier. */
70
82
  sandbox(id) {
71
83
  return new RemoteSandbox(this, id, id.split(":")[0]);
package/dist/index.d.ts CHANGED
@@ -13,6 +13,7 @@ export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./val
13
13
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd, type ProviderInfo } from "./catalog.js";
14
14
  export { createApp, HttpError, ERROR_STATUS, ORPHAN_GRACE_MS, type ServerHooks } from "./server.js";
15
15
  export { Client, ClientError, RemoteSandbox, type CreateResponse } from "./client.js";
16
+ export { copyFiles, moveSandbox, DEFAULT_COPY_MAX_BYTES, type CopyOptions, type CopyResult, type FileBox, type MoveOptions, type Mover } from "./move.js";
16
17
  export { RoutedComputer, createComputer, splitComputerRequest, DEFAULT_COMPUTER_TIMEOUT_S, DEFAULT_COMPUTER_DEADLINE_S, type ComputerRoute, planComputer, computerCatalog, computerHourly, COMPUTER_ENTRIES, type ComputerCatalogEntry, type ComputerCandidate, type ComputerProviderId, type ActionResult, type ComputerAction, type ComputerActionName, type ComputerInfo, type ComputerOs, type ComputerProvider, type ComputerSpec, type ProviderComputer, } from "./computers.js";
17
18
  export { bench, benchMarkdown, type BenchRow } from "./bench.js";
18
19
  export { aggregate, loadReports, makeReport, renderLeaderboard, type BenchReport, type LeaderRow } from "./leaderboard.js";
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./val
13
13
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd } from "./catalog.js";
14
14
  export { createApp, HttpError, ERROR_STATUS, ORPHAN_GRACE_MS } from "./server.js";
15
15
  export { Client, ClientError, RemoteSandbox } from "./client.js";
16
+ export { copyFiles, moveSandbox, DEFAULT_COPY_MAX_BYTES } from "./move.js";
16
17
  export { RoutedComputer, createComputer, splitComputerRequest, DEFAULT_COMPUTER_TIMEOUT_S, DEFAULT_COMPUTER_DEADLINE_S, planComputer, computerCatalog, computerHourly, COMPUTER_ENTRIES, } from "./computers.js";
17
18
  export { bench, benchMarkdown } from "./bench.js";
18
19
  export { aggregate, loadReports, makeReport, renderLeaderboard } from "./leaderboard.js";
package/dist/move.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type ExecOptions, type ExecResult, type ProviderId, type RouteOptions, type SandboxSpec } from "./types.js";
2
+ /** What copy and move need from a sandbox: a `RoutedSandbox` and a `RemoteSandbox` both fit. */
3
+ export interface FileBox {
4
+ readonly id: string;
5
+ readonly provider: string;
6
+ readonly size?: {
7
+ vcpu: number;
8
+ memoryGb: number;
9
+ };
10
+ exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
11
+ readFile(path: string): Promise<Uint8Array>;
12
+ writeFile(path: string, content: string | Uint8Array): Promise<void>;
13
+ kill(): Promise<void>;
14
+ }
15
+ export interface CopyOptions {
16
+ /**
17
+ * Folder to copy from the source. Default: the folder its commands run in. Copied whole like that,
18
+ * the destination keeps its own shell startup files (`.bashrc`, `.profile`, ...), since those belong to its image.
19
+ */
20
+ path?: string;
21
+ /** Folder to copy into. Default: the same path, or the destination's own working folder when `path` isn't given. */
22
+ to?: string;
23
+ /** Names or patterns to leave behind, as `tar --exclude` reads them, e.g. `["node_modules", ".venv", "*.log"]`. */
24
+ exclude?: string[];
25
+ /** Refuse when the packed folder is bigger than this (default 1 GB), before anything is sent. */
26
+ maxBytes?: number;
27
+ /** Seconds each pack and unpack command may take (default 600). */
28
+ timeoutSeconds?: number;
29
+ /** Bytes sent per file transfer (default 4 MB). Providers cap how much one file call carries. */
30
+ chunkBytes?: number;
31
+ /**
32
+ * Encrypt the folder between the two sandboxes, so everything in between (this process, and the
33
+ * sandboxRouter server when you use the hosted API) only relays bytes it can't read. The destination
34
+ * makes a key pair and keeps the private key; the source encrypts the archive (AES-256) with a
35
+ * one-time key sealed to the destination's public key; the destination checks the archive's SHA-256
36
+ * before unpacking. Both sandboxes need `openssl`. It doesn't hide the files from the two providers
37
+ * that run the sandboxes, or from whoever can run commands in them.
38
+ */
39
+ encrypt?: boolean;
40
+ }
41
+ export interface CopyResult {
42
+ /** The folder read on the source. */
43
+ from: string;
44
+ /** The folder written on the destination. */
45
+ to: string;
46
+ /** Size of the packed (gzip) folder that was sent. */
47
+ bytes: number;
48
+ /** True when the folder crossed encrypted (`encrypt`). */
49
+ encrypted: boolean;
50
+ ms: number;
51
+ }
52
+ export interface MoveOptions extends CopyOptions, RouteOptions {
53
+ /** The new sandbox's spec. Its size defaults to the old sandbox's. */
54
+ spec?: SandboxSpec;
55
+ /** Leave the old sandbox running (default: kill it once the files are across). */
56
+ keep?: boolean;
57
+ }
58
+ export declare const DEFAULT_COPY_MAX_BYTES: number;
59
+ /**
60
+ * Copy a folder from one sandbox to another, on any two providers: packed with tar on the source,
61
+ * carried through this process in pieces, unpacked on the destination. Files, their modes and
62
+ * symlinks come across; running processes, memory and env vars don't. The source isn't changed.
63
+ * Both sandboxes need `tar` and `split` (every stock image has them). With `encrypt`, what crosses
64
+ * is ciphertext only the destination sandbox can open.
65
+ */
66
+ export declare function copyFiles(from: FileBox, to: FileBox, opts?: CopyOptions): Promise<CopyResult>;
67
+ /** What a move needs from a router: a `Router` and a hosted `Client` both fit. */
68
+ export interface Mover<B extends FileBox> {
69
+ candidates(spec: SandboxSpec, route: RouteOptions): Promise<{
70
+ provider: ProviderId;
71
+ skip?: string;
72
+ }[]>;
73
+ create(spec: SandboxSpec, route: RouteOptions): Promise<B>;
74
+ }
75
+ /**
76
+ * Start a sandbox on another provider, copy the folder across, then kill the old one. If anything
77
+ * fails the new sandbox is killed and the old one is left as it was.
78
+ */
79
+ export declare function moveSandbox<B extends FileBox>(mover: Mover<B>, from: FileBox, opts?: MoveOptions): Promise<B & {
80
+ moved: CopyResult;
81
+ }>;
package/dist/move.js ADDED
@@ -0,0 +1,172 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { RouterError } from "./types.js";
3
+ import { shq } from "./util.js";
4
+ export const DEFAULT_COPY_MAX_BYTES = 1024 ** 3;
5
+ /** Shell startup files the destination keeps as its image made them when a working folder is copied whole (no `path`). */
6
+ const IMAGE_FILES = [".bashrc", ".bash_profile", ".bash_logout", ".profile", ".zshrc"];
7
+ const DEFAULT_CHUNK_BYTES = 4 * 1024 * 1024;
8
+ const DEFAULT_COPY_TIMEOUT_S = 600;
9
+ /**
10
+ * Copy a folder from one sandbox to another, on any two providers: packed with tar on the source,
11
+ * carried through this process in pieces, unpacked on the destination. Files, their modes and
12
+ * symlinks come across; running processes, memory and env vars don't. The source isn't changed.
13
+ * Both sandboxes need `tar` and `split` (every stock image has them). With `encrypt`, what crosses
14
+ * is ciphertext only the destination sandbox can open.
15
+ */
16
+ export async function copyFiles(from, to, opts = {}) {
17
+ const started = Date.now();
18
+ const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_COPY_TIMEOUT_S;
19
+ const chunk = Math.max(64 * 1024, Math.floor(opts.chunkBytes ?? DEFAULT_CHUNK_BYTES));
20
+ const maxBytes = opts.maxBytes ?? DEFAULT_COPY_MAX_BYTES;
21
+ const src = opts.path ?? (await workdir(from));
22
+ const dst = opts.to ?? opts.path ?? (await workdir(to));
23
+ for (const p of [src, dst]) {
24
+ if (!p.startsWith("/"))
25
+ throw new RouterError(`copy needs an absolute path, got "${p}"`, [], "bad_request");
26
+ if (p.replace(/\/+$/, "") === "")
27
+ throw new RouterError("copy won't take the whole filesystem (/): name a folder", [], "bad_request");
28
+ }
29
+ const encrypt = opts.encrypt === true;
30
+ const tmp = `/tmp/sr-move-${randomUUID().slice(0, 8)}`;
31
+ const run = async (box, what, cmd) => {
32
+ const r = await box.exec(cmd, { timeoutSeconds });
33
+ if (r.exitCode !== 0) {
34
+ const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ");
35
+ throw new RouterError(`${what} failed on ${box.provider} (exit ${r.exitCode})${detail ? `: ${detail}` : ""}`, [], "all_failed");
36
+ }
37
+ return r.stdout;
38
+ };
39
+ const clean = (box) => box.exec(`rm -rf ${shq(tmp)}`, { timeoutSeconds: 60 }).catch(() => { });
40
+ try {
41
+ // The archive is written outside the folder where it can be, and excluded by name in case /tmp is inside it.
42
+ const excludes = ["sr-move-*", ...(opts.exclude ?? [])].map((e) => `--exclude=${shq(e)}`).join(" ");
43
+ const packed = await run(from, "packing the folder", [
44
+ `mkdir -p ${shq(tmp)}`,
45
+ `tar -czf ${shq(`${tmp}/a.tgz`)} ${excludes} -C ${shq(src)} .`,
46
+ `echo "size=$(wc -c < ${shq(`${tmp}/a.tgz`)} | tr -d ' ')"`,
47
+ ].join(" && "));
48
+ const bytes = Number(/size=(\d+)/.exec(packed)?.[1] ?? NaN);
49
+ if (!Number.isFinite(bytes))
50
+ throw new RouterError(`couldn't read the packed size on ${from.provider}`, [], "all_failed");
51
+ if (bytes > maxBytes) {
52
+ throw new RouterError(`the folder packs to ${mb(bytes)}, over the ${mb(maxBytes)} limit: pass exclude (e.g. node_modules) or a higher maxBytes`, [], "bad_request");
53
+ }
54
+ await run(to, "preparing the destination", `mkdir -p ${shq(tmp)} ${shq(dst)}`);
55
+ // What is sent: the archive, or its ciphertext (a few bytes longer).
56
+ let sent = bytes;
57
+ if (encrypt) {
58
+ for (const box of [from, to]) {
59
+ const has = await box.exec("command -v openssl >/dev/null 2>&1", { timeoutSeconds: 60 });
60
+ if (has.exitCode !== 0)
61
+ throw new RouterError(`encrypt needs openssl in both sandboxes, and ${box.provider}'s image has none`, [], "unsupported");
62
+ }
63
+ // The private key is made on the destination and never leaves it; only the public key travels.
64
+ const pem = await run(to, "making the destination's key", `cd ${shq(tmp)} && umask 077 && openssl genrsa -out k.pem 2048 2>/dev/null && openssl rsa -in k.pem -pubout 2>/dev/null`);
65
+ const pub = /-----BEGIN PUBLIC KEY-----[\s\S]+?-----END PUBLIC KEY-----/.exec(pem)?.[0];
66
+ if (!pub)
67
+ throw new RouterError(`couldn't read the public key made on ${to.provider}`, [], "all_failed");
68
+ await from.writeFile(`${tmp}/pub.pem`, `${pub}\n`);
69
+ // A one-time AES key encrypts the archive; that key and the archive's hash are sealed to the public key.
70
+ const sealed = await run(from, "encrypting the archive", [
71
+ `cd ${shq(tmp)}`,
72
+ "umask 077",
73
+ "openssl rand -hex 32 > k",
74
+ `h=$(openssl dgst -sha256 -r a.tgz | cut -d' ' -f1)`,
75
+ "openssl enc -aes-256-cbc -pbkdf2 -pass file:k -in a.tgz -out a.enc",
76
+ `printf '%s %s' "$(cat k)" "$h" | openssl pkeyutl -encrypt -pubin -inkey pub.pem -out k.enc`,
77
+ "rm -f k a.tgz pub.pem",
78
+ "mv a.enc a.tgz",
79
+ `echo "size=$(wc -c < a.tgz | tr -d ' ')"`,
80
+ ].join(" && "));
81
+ sent = Number(/size=(\d+)/.exec(sealed)?.[1] ?? NaN);
82
+ if (!Number.isFinite(sent))
83
+ throw new RouterError(`couldn't read the encrypted size on ${from.provider}`, [], "all_failed");
84
+ await to.writeFile(`${tmp}/k.enc`, await from.readFile(`${tmp}/k.enc`));
85
+ }
86
+ const listed = await run(from, "splitting the archive", `cd ${shq(tmp)} && split -b ${chunk} -a 4 a.tgz p. && rm a.tgz && ls p.*`);
87
+ const parts = listed.split("\n").map((l) => l.trim()).filter((l) => /^p\.[a-z]{4}$/.test(l)).sort();
88
+ if (parts.length === 0)
89
+ throw new RouterError(`no archive pieces found on ${from.provider}`, [], "all_failed");
90
+ for (const part of parts)
91
+ await to.writeFile(`${tmp}/${part}`, await from.readFile(`${tmp}/${part}`));
92
+ // The size check catches a piece a provider cut short before tar unpacks half a folder.
93
+ const got = await run(to, "checking the archive", `cat ${shq(tmp)}/p.* | wc -c | tr -d ' '`);
94
+ if (Number(got.trim().split("\n").pop()) !== sent) {
95
+ throw new RouterError(`the archive arrived as ${got.trim()} bytes on ${to.provider}, expected ${sent}`, [], "all_failed");
96
+ }
97
+ // -o: the files belong to whoever runs the destination sandbox, not the source's user id.
98
+ // Copying a whole working folder would replace the destination image's shell startup files with
99
+ // the source image's (a different PATH, a different user): the destination's are put back after.
100
+ const keep = opts.path === undefined ? IMAGE_FILES.map(shq).join(" ") : "";
101
+ const save = keep ? `mkdir -p ${shq(`${tmp}/keep`)} && for f in ${keep}; do if [ -f ${shq(dst)}/"$f" ]; then cp -p ${shq(dst)}/"$f" ${shq(`${tmp}/keep`)}/; fi; done && ` : "";
102
+ const restore = keep ? ` && for f in ${keep}; do if [ -f ${shq(`${tmp}/keep`)}/"$f" ]; then cp -p ${shq(`${tmp}/keep`)}/"$f" ${shq(dst)}/; fi; done` : "";
103
+ // Encrypted: open the one-time key with the private key, decrypt, and unpack only if the hash matches.
104
+ const open = encrypt
105
+ ? [
106
+ `cd ${shq(tmp)}`,
107
+ // The keys and the plain archive are written private (umask 077), in a subshell so that
108
+ // tar below still unpacks with the sandbox's own umask and the files keep their modes.
109
+ `( ${[
110
+ "umask 077",
111
+ "openssl pkeyutl -decrypt -inkey k.pem -in k.enc -out kh",
112
+ "cut -d' ' -f1 kh > k",
113
+ "cat p.* | openssl enc -d -aes-256-cbc -pbkdf2 -pass file:k -out a.tgz",
114
+ `[ "$(openssl dgst -sha256 -r a.tgz | cut -d' ' -f1)" = "$(cut -d' ' -f2 kh)" ]`,
115
+ ].join(" && ")} )`,
116
+ `tar -xzo -f a.tgz -C ${shq(dst)}`,
117
+ ].join(" && ")
118
+ : `cat ${shq(tmp)}/p.* | tar -xzo -f - -C ${shq(dst)}`;
119
+ await run(to, encrypt ? "decrypting and unpacking the folder" : "unpacking the folder", `${save}${open}${restore}`);
120
+ return { from: src, to: dst, bytes, encrypted: encrypt, ms: Date.now() - started };
121
+ }
122
+ finally {
123
+ await Promise.all([clean(from), clean(to)]);
124
+ }
125
+ }
126
+ /**
127
+ * Start a sandbox on another provider, copy the folder across, then kill the old one. If anything
128
+ * fails the new sandbox is killed and the old one is left as it was.
129
+ */
130
+ export async function moveSandbox(mover, from, opts = {}) {
131
+ const { spec: given = {}, keep, path, to, exclude, maxBytes, timeoutSeconds, chunkBytes, encrypt, ...route } = opts;
132
+ let spec = { ...given };
133
+ const elsewhere = async (s) => (await mover.candidates(s, route)).filter((c) => !c.skip && c.provider !== from.provider).map((c) => c.provider);
134
+ // The new sandbox keeps the old one's size. A provider's fixed default size (E2B's 2 vCPU / 0.5 GB)
135
+ // may be one nobody else sells, so when nothing else takes it the move goes ahead at the default size.
136
+ const sized = given.vcpu === undefined && given.memoryGb === undefined && from.size ? { ...given, vcpu: from.size.vcpu, memoryGb: from.size.memoryGb } : undefined;
137
+ if (route.provider !== undefined) {
138
+ if (sized && (await mover.candidates(sized, route)).some((c) => !c.skip))
139
+ spec = sized;
140
+ }
141
+ else {
142
+ // Without a named provider, "move" means somewhere else: the usual order, minus where it is now.
143
+ let list = sized ? await elsewhere(sized) : [];
144
+ if (list.length > 0)
145
+ spec = sized;
146
+ else
147
+ list = await elsewhere(spec);
148
+ if (list.length === 0)
149
+ throw new RouterError(`no other provider can take this sandbox (it is on ${from.provider})`, [], "no_provider");
150
+ route.provider = list;
151
+ }
152
+ const next = await mover.create(spec, route);
153
+ let moved;
154
+ try {
155
+ moved = await copyFiles(from, next, { path, to, exclude, maxBytes, timeoutSeconds, chunkBytes, encrypt });
156
+ }
157
+ catch (error) {
158
+ await next.kill().catch(() => { });
159
+ throw error;
160
+ }
161
+ if (!keep)
162
+ await from.kill();
163
+ return Object.assign(next, { moved });
164
+ }
165
+ async function workdir(box) {
166
+ const r = await box.exec("pwd", { timeoutSeconds: 60 });
167
+ const dir = r.stdout.trim().split("\n").pop()?.trim() ?? "";
168
+ if (r.exitCode !== 0 || !dir.startsWith("/"))
169
+ throw new RouterError(`couldn't find the working folder on ${box.provider}: pass path`, [], "all_failed");
170
+ return dir;
171
+ }
172
+ const mb = (n) => `${(n / 1024 / 1024).toFixed(n < 10 * 1024 * 1024 ? 1 : 0)} MB`;
@@ -123,6 +123,8 @@ class BoatError extends ProviderError {
123
123
  }
124
124
  const READY = new Set(["ready", "idle", "running"]);
125
125
  const STOPPED = new Set(["archived", "stopped"]);
126
+ /** 409 codes a data call gets while the sandbox is stopped or still booting: resume or wait, then retry. */
127
+ const STOPPED_CODES = new Set(["sandbox_not_ready", "machine_not_running", "boat_starting"]);
126
128
  /** Boat has four fixed sizes (catalog.ts). Pick the smallest that covers the request. */
127
129
  function machineType(vcpu, memoryGb) {
128
130
  const fit = BOAT_SIZES.find((s) => s.vcpu >= vcpu && s.memoryGb >= memoryGb);
@@ -145,13 +147,16 @@ class BoatSandbox {
145
147
  this.nativeId = nativeId;
146
148
  this.base = `/sandboxes/${encodeURIComponent(nativeId)}`;
147
149
  }
148
- /** Data call; when the sandbox is stopped (409 sandbox_not_ready) or still starting, wait/resume once and retry. */
150
+ /**
151
+ * Data call; when the sandbox is stopped or still starting, wait/resume once and retry. Boat has answered a
152
+ * stopped sandbox with 409 sandbox_not_ready and, since Nov 2026, 409 machine_not_running.
153
+ */
149
154
  async call(method, path, json) {
150
155
  try {
151
156
  return await this.p.request(method, `${this.base}${path}`, { json });
152
157
  }
153
158
  catch (err) {
154
- if (!(err instanceof BoatError && err.status === 409 && (err.code === "sandbox_not_ready" || err.code === "boat_starting")))
159
+ if (!(err instanceof BoatError && err.status === 409 && STOPPED_CODES.has(err.code ?? "")))
155
160
  throw err;
156
161
  await this.p.ready(this.nativeId);
157
162
  return this.p.request(method, `${this.base}${path}`, { json });
package/dist/router.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  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
+ import { type CopyOptions, type CopyResult, type FileBox, type MoveOptions } from "./move.js";
4
5
  import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxProcess, type SandboxSpec, type StartOptions } from "./types.js";
5
6
  /** vCPUs and memory a sandbox gets. */
6
7
  export interface Size {
@@ -227,6 +228,23 @@ export declare class Router {
227
228
  /** Start a desktop or phone, routed like a sandbox (see createComputer). */
228
229
  computer(spec?: ComputerSpec, route?: ComputerRoute): Promise<RoutedComputer>;
229
230
  getComputer(id: string): Promise<RoutedComputer>;
231
+ /**
232
+ * Copy a folder from one sandbox to another, on any two providers. Files only: running processes,
233
+ * memory and env vars stay behind. See `CopyOptions`.
234
+ */
235
+ copy(from: FileBox, to: FileBox, opts?: CopyOptions): Promise<CopyResult>;
236
+ /**
237
+ * Move a sandbox's folder to a new sandbox and kill the old one: on another provider by default,
238
+ * or on the ones `provider` names. The new sandbox keeps the old one's size where another provider
239
+ * sells it, else the default size. If the new one can't
240
+ * start or the copy fails, the old sandbox is left running and untouched.
241
+ *
242
+ * sbx = await router.move(sbx); // next-best provider
243
+ * sbx = await router.move(sbx, { provider: "e2b", path: "/workspace", exclude: ["node_modules"] });
244
+ */
245
+ move(from: FileBox, opts?: MoveOptions): Promise<RoutedSandbox & {
246
+ moved: CopyResult;
247
+ }>;
230
248
  /** Reattach to a sandbox by its routed id (`provider:nativeId`). */
231
249
  get(id: string): Promise<RoutedSandbox>;
232
250
  }
package/dist/router.js CHANGED
@@ -5,6 +5,7 @@ import { loadBench, median } from "./bench-store.js";
5
5
  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
+ import { copyFiles, moveSandbox } from "./move.js";
8
9
  import { BILLED_VS_LIST } from "./billing.js";
9
10
  import { FAILING, VERIFIED } from "./verified.js";
10
11
  import { isPort, validate, validateStart } from "./validate.js";
@@ -471,6 +472,25 @@ export class Router {
471
472
  const e = this.ledger?.list().find((x) => x.id === id);
472
473
  return new RoutedComputer(provider, await p.connectComputer(id.slice(i + 1)), [], e?.usdHour, this.ledger);
473
474
  }
475
+ /**
476
+ * Copy a folder from one sandbox to another, on any two providers. Files only: running processes,
477
+ * memory and env vars stay behind. See `CopyOptions`.
478
+ */
479
+ copy(from, to, opts = {}) {
480
+ return copyFiles(from, to, opts);
481
+ }
482
+ /**
483
+ * Move a sandbox's folder to a new sandbox and kill the old one: on another provider by default,
484
+ * or on the ones `provider` names. The new sandbox keeps the old one's size where another provider
485
+ * sells it, else the default size. If the new one can't
486
+ * start or the copy fails, the old sandbox is left running and untouched.
487
+ *
488
+ * sbx = await router.move(sbx); // next-best provider
489
+ * sbx = await router.move(sbx, { provider: "e2b", path: "/workspace", exclude: ["node_modules"] });
490
+ */
491
+ move(from, opts = {}) {
492
+ return moveSandbox({ candidates: async (spec, route) => this.plan(spec, route), create: (spec, route) => this.create(spec, route) }, from, opts);
493
+ }
474
494
  /** Reattach to a sandbox by its routed id (`provider:nativeId`). */
475
495
  async get(id) {
476
496
  const { provider, nativeId } = parseId(id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandboxrouter/sdk",
3
- "version": "0.15.2",
3
+ "version": "0.17.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",
@@ -184,14 +184,14 @@
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.69.1",
187
+ "@limrun/api": "^0.73.2",
188
188
  "@mobilerun/sdk": "^6.1.0",
189
189
  "@northflank/js-client": "^0.12.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": "^3.9.1",
194
+ "@vercel/sandbox": "^4.0.0",
195
195
  "e2b": "^2.63.0",
196
196
  "modal": "^0.11.1",
197
197
  "morphcloud": "^0.0.20",