disk 1.14.0 → 1.15.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,1073 @@
1
+ import { c as desktopViewerPath, i as DESKTOP_PORT } from "./sandbox-desktop-CrvuoiGi.mjs";
2
+ import { forwardPort, openPortTunnel } from "./tunnel.mjs";
3
+ import { S as formatDuration, T as styles, a as addGlobalOptions, b as colorEnabled, c as resolveProgramCredentials, f as renderTable, h as readProfileCredential, i as validateSandboxName, n as parseCreateSandboxOptions, o as addProfileCommands, r as parseRunOptions, s as isProfileCommand, t as optionalInteger, u as loadProfiles, v as diskConfigDir, w as statusStyle, x as createUi, y as Command } from "./sandbox-options-AO9jKF4-.mjs";
4
+ import { mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { dirname, join } from "node:path";
6
+ import { homedir } from "node:os";
7
+ import { execFile, spawn } from "node:child_process";
8
+ import { createInterface } from "node:readline/promises";
9
+ import { promisify } from "node:util";
10
+ //#region src/cli/sandbox-output.ts
11
+ const plain = styles(false);
12
+ function parseOutputFormat(value) {
13
+ if (value !== "table" && value !== "json") throw new Error("Output format must be 'table' or 'json'");
14
+ return value;
15
+ }
16
+ function date(value) {
17
+ return value?.toISOString() ?? "";
18
+ }
19
+ function sortSandboxes(sandboxes) {
20
+ return [...sandboxes].sort((left, right) => {
21
+ return right.lastActiveAt.getTime() - left.lastActiveAt.getTime() || left.name.localeCompare(right.name) || left.id.localeCompare(right.id);
22
+ });
23
+ }
24
+ function formatSandboxList(sandboxes, format, style = plain) {
25
+ const ordered = sortSandboxes(sandboxes);
26
+ if (format === "json") return JSON.stringify(ordered, null, 2);
27
+ if (ordered.length === 0) return "No sandboxes found.";
28
+ return renderTable(ordered.map((sandbox) => [
29
+ sandbox.id,
30
+ style.bold(sandbox.name),
31
+ statusStyle(style, sandbox.status),
32
+ String(sandbox.vcpuCount),
33
+ `${sandbox.memSizeMiB} MiB`,
34
+ sandbox.baseImage,
35
+ date(sandbox.lastActiveAt)
36
+ ]), [
37
+ "id",
38
+ "name",
39
+ "status",
40
+ "cpu",
41
+ "memory",
42
+ "image",
43
+ "last active"
44
+ ]);
45
+ }
46
+ function formatSandbox(sandbox, format, style = plain) {
47
+ if (format === "json") return JSON.stringify(sandbox, null, 2);
48
+ const rows = [
49
+ ["id", sandbox.id],
50
+ ["name", sandbox.name],
51
+ ["status", statusStyle(style, sandbox.status)],
52
+ ["cpu", String(sandbox.vcpuCount)],
53
+ ["memory", `${sandbox.memSizeMiB} MiB`],
54
+ ["image", sandbox.baseImage],
55
+ ["platform", sandbox.platform ?? ""],
56
+ ["max TTL", `${sandbox.maxTtlSeconds} seconds`],
57
+ ["idle TTL", sandbox.idleTtlSeconds === 0 ? "disabled" : `${sandbox.idleTtlSeconds} seconds`],
58
+ ["on timeout", sandbox.onTimeout],
59
+ ["max concurrent processes", String(sandbox.maxConcurrentExecs)],
60
+ ["created", date(sandbox.createdAt)],
61
+ ["running", date(sandbox.runningAt)],
62
+ ["finished", date(sandbox.finishedAt)],
63
+ ["last active", date(sandbox.lastActiveAt)],
64
+ ["exit reason", sandbox.exitReason ?? ""]
65
+ ];
66
+ for (const endpoint of sandbox.endpoints ?? []) rows.push([`endpoint ${endpoint.port}`, endpoint.hostname]);
67
+ return renderTable(rows.filter(([, value]) => value !== "").map(([label, value]) => [style.dim(label), value]));
68
+ }
69
+ //#endregion
70
+ //#region src/cli/write-output.ts
71
+ /**
72
+ * Writes `data`, then waits while the stream is full. A stream that closes or
73
+ * fails never emits `drain`, so either ends the wait with an error instead.
74
+ */
75
+ async function writeOutput(stream, data) {
76
+ if (stream.write(data) !== false || !stream.on || !stream.off) return;
77
+ const { on, off } = {
78
+ on: stream.on.bind(stream),
79
+ off: stream.off.bind(stream)
80
+ };
81
+ await new Promise((resolve, reject) => {
82
+ const drained = () => {
83
+ remove();
84
+ resolve();
85
+ };
86
+ const closed = () => {
87
+ remove();
88
+ reject(/* @__PURE__ */ new Error("Output stream closed"));
89
+ };
90
+ const failed = (error) => {
91
+ remove();
92
+ reject(error instanceof Error ? error : new Error(String(error)));
93
+ };
94
+ const remove = () => {
95
+ off("drain", drained);
96
+ off("close", closed);
97
+ off("error", failed);
98
+ };
99
+ on("drain", drained);
100
+ on("close", closed);
101
+ on("error", failed);
102
+ });
103
+ }
104
+ //#endregion
105
+ //#region src/cli/sandbox-ssh.ts
106
+ const SSH_HOST_SUFFIX = ".archil";
107
+ function sshKeyPath(home = homedir()) {
108
+ return join(home, ".ssh", "archil_ed25519");
109
+ }
110
+ function sshKnownHostsPath(env = process.env) {
111
+ return join(diskConfigDir(env), "known_hosts");
112
+ }
113
+ /** `my-desk.archil` and `my-desk` both name the sandbox `my-desk`. */
114
+ function sshTarget(host) {
115
+ return host.endsWith(".archil") ? host.slice(0, -7) : host;
116
+ }
117
+ /** Creates the CLI's SSH key on first use; returns its public key. */
118
+ async function ensureSshKey(keyPath = sshKeyPath()) {
119
+ try {
120
+ return (await readFile(`${keyPath}.pub`, "utf8")).trim();
121
+ } catch (error) {
122
+ if (error.code !== "ENOENT") throw error;
123
+ }
124
+ await mkdir(dirname(keyPath), {
125
+ recursive: true,
126
+ mode: 448
127
+ });
128
+ try {
129
+ await promisify(execFile)("ssh-keygen", [
130
+ "-q",
131
+ "-t",
132
+ "ed25519",
133
+ "-N",
134
+ "",
135
+ "-C",
136
+ "archil-cli",
137
+ "-f",
138
+ keyPath
139
+ ]);
140
+ } catch (error) {
141
+ throw new Error(`Couldn't create an SSH key with ssh-keygen: ${error instanceof Error ? error.message : String(error)}`);
142
+ }
143
+ return (await readFile(`${keyPath}.pub`, "utf8")).trim();
144
+ }
145
+ /** Records `hostKey` for `host` in the CLI's known_hosts file, replacing any older entry. */
146
+ async function rememberHostKey(knownHostsPath, host, hostKey) {
147
+ await mkdir(dirname(knownHostsPath), { recursive: true });
148
+ await withFileLock(`${knownHostsPath}.lock`, async () => {
149
+ let lines = [];
150
+ try {
151
+ lines = (await readFile(knownHostsPath, "utf8")).split("\n").filter(Boolean);
152
+ } catch (error) {
153
+ if (error.code !== "ENOENT") throw error;
154
+ }
155
+ const entry = `${host} ${hostKey.trim().split(/\s+/).slice(0, 2).join(" ")}`;
156
+ const kept = lines.filter((line) => line.split(" ")[0] !== host);
157
+ const temporary = `${knownHostsPath}.${process.pid}.tmp`;
158
+ await writeFile(temporary, `${[...kept, entry].join("\n")}\n`, { mode: 384 });
159
+ await rename(temporary, knownHostsPath);
160
+ });
161
+ }
162
+ const LOCK_WAIT_MS = 1e4;
163
+ const LOCK_STALE_MS = 1e4;
164
+ /** Runs `operation` while holding an exclusive lock file; a lock older than LOCK_STALE_MS is taken over. */
165
+ async function withFileLock(path, operation) {
166
+ const deadline = Date.now() + LOCK_WAIT_MS;
167
+ for (;;) try {
168
+ await (await open(path, "wx")).close();
169
+ break;
170
+ } catch (error) {
171
+ if (error.code !== "EEXIST") throw error;
172
+ if (await stat(path).then((info) => Date.now() - info.mtimeMs, () => 0) > LOCK_STALE_MS) {
173
+ await unlink(path).catch(() => {});
174
+ continue;
175
+ }
176
+ if (Date.now() > deadline) throw new Error(`Timed out waiting for ${path}`);
177
+ await new Promise((resolve) => setTimeout(resolve, 25));
178
+ }
179
+ try {
180
+ return await operation();
181
+ } finally {
182
+ await unlink(path).catch(() => {});
183
+ }
184
+ }
185
+ const SETUP_LOCK = `
186
+ lock=/tmp/.archil-ssh-setup.lock
187
+ i=0
188
+ until mkdir "$lock" 2>/dev/null; do
189
+ i=$((i + 1))
190
+ [ "$i" -ge 600 ] && break
191
+ sleep 0.5
192
+ done
193
+ trap 'rmdir "$lock" 2>/dev/null' EXIT`;
194
+ const FIND_SSHD = "command -v sshd || { [ -x /usr/sbin/sshd ] && echo /usr/sbin/sshd; }";
195
+ const INSTALL_SSHD = `${SETUP_LOCK}
196
+ # Another connection may have installed it while this one waited.
197
+ if command -v sshd >/dev/null || [ -x /usr/sbin/sshd ]; then
198
+ exit 0
199
+ elif command -v apt-get >/dev/null; then
200
+ export DEBIAN_FRONTEND=noninteractive
201
+ apt-get update -qq && apt-get install -y -qq --no-install-recommends openssh-server
202
+ elif command -v apk >/dev/null; then
203
+ apk add --no-cache openssh-server
204
+ elif command -v dnf >/dev/null; then
205
+ dnf install -y -q openssh-server
206
+ else
207
+ echo "no supported package manager to install openssh-server" >&2
208
+ exit 1
209
+ fi`;
210
+ const PREPARE_SSHD = `${SETUP_LOCK}
211
+ set -e
212
+ sshd=$(${FIND_SSHD})
213
+ mkdir -p /run/sshd /root/.ssh
214
+ chmod 700 /root/.ssh
215
+ ssh-keygen -A >/dev/null
216
+ touch /root/.ssh/authorized_keys
217
+ grep -qxF "$ARCHIL_SSH_KEY" /root/.ssh/authorized_keys || printf '%s\\n' "$ARCHIL_SSH_KEY" >> /root/.ssh/authorized_keys
218
+ chmod 600 /root/.ssh/authorized_keys
219
+ echo "$sshd"
220
+ cat /etc/ssh/ssh_host_ed25519_key.pub`;
221
+ /**
222
+ * Makes sure the sandbox can serve SSH for `publicKey`, installing
223
+ * openssh-server the first time if needed. Returns the sshd path and the
224
+ * sandbox's host key.
225
+ */
226
+ async function prepareSandboxSsh(sandbox, publicKey, notify) {
227
+ if (!(await sandbox.exec(FIND_SSHD)).stdout.trim()) {
228
+ notify(`Installing openssh-server in '${sandbox.name}' (first SSH connection only)...`);
229
+ const installed = await sandbox.exec(INSTALL_SSHD, { timeoutSeconds: 300 });
230
+ if (installed.exitCode !== 0) throw new Error(`Couldn't install openssh-server in '${sandbox.name}': ${(installed.stderr || installed.stdout).trim().split("\n").slice(-3).join("\n")}`);
231
+ }
232
+ const prepared = await sandbox.exec(PREPARE_SSHD, { env: { ARCHIL_SSH_KEY: publicKey } });
233
+ const [sshd, hostKey] = prepared.stdout.trim().split("\n");
234
+ if (prepared.exitCode !== 0 || !sshd || !hostKey) throw new Error(`Couldn't set up SSH in '${sandbox.name}': ${(prepared.stderr || prepared.stdout).trim()}`);
235
+ return {
236
+ sshd,
237
+ hostKey
238
+ };
239
+ }
240
+ /** Relays an sshd running in inetd mode inside the sandbox over `input`/`output`. Resolves to its exit code. */
241
+ async function relaySshd(sandbox, sshd, input, output, errors) {
242
+ const remote = await sandbox.run(`exec ${sshd} -i`, { collectOutput: false });
243
+ (async () => {
244
+ for await (const chunk of input) await remote.sendInput(chunk);
245
+ await remote.closeStdin();
246
+ })().catch(() => remote.kill().catch(() => {}));
247
+ try {
248
+ for await (const { stream, data } of remote.output) await writeOutput(stream === "stdout" ? output : errors, data);
249
+ const result = await remote.wait();
250
+ return result.exitCode ?? (result.status === "completed" ? 0 : 1);
251
+ } finally {
252
+ await remote.disconnect().catch(() => {});
253
+ await sandbox.processes.disconnect().catch(() => {});
254
+ }
255
+ }
256
+ /** The ProxyCommand that runs this CLI's `ssh-proxy` command for `%n`, the host as typed. */
257
+ function proxyCommand(cliArgs) {
258
+ return [
259
+ ...cliArgs,
260
+ "ssh-proxy",
261
+ "%n"
262
+ ].map(quoteForSsh).join(" ");
263
+ }
264
+ /** An ssh_config block that sends every `<sandbox>.archil` host through the CLI. */
265
+ function sshConfigBlock(cliArgs, keyPath = sshKeyPath(), knownHostsPath = sshKnownHostsPath()) {
266
+ return [
267
+ "# Archil sandboxes: ssh <sandbox-name>.archil",
268
+ `Host *${SSH_HOST_SUFFIX}`,
269
+ " User root",
270
+ ` IdentityFile ${quoteForSsh(keyPath)}`,
271
+ " IdentitiesOnly yes",
272
+ ` UserKnownHostsFile ${quoteForSsh(knownHostsPath)}`,
273
+ " StrictHostKeyChecking yes",
274
+ ` ProxyCommand ${proxyCommand(cliArgs)}`,
275
+ ""
276
+ ].join("\n");
277
+ }
278
+ /** ssh options equivalent to `sshConfigBlock`, for running ssh without editing ~/.ssh/config. */
279
+ function sshOptions(cliArgs, keyPath = sshKeyPath(), knownHostsPath = sshKnownHostsPath()) {
280
+ return [
281
+ "-o",
282
+ "User=root",
283
+ "-o",
284
+ `IdentityFile=${quoteForSsh(keyPath)}`,
285
+ "-o",
286
+ "IdentitiesOnly=yes",
287
+ "-o",
288
+ `UserKnownHostsFile=${quoteForSsh(knownHostsPath)}`,
289
+ "-o",
290
+ "StrictHostKeyChecking=yes",
291
+ "-o",
292
+ `ProxyCommand=${proxyCommand(cliArgs)}`
293
+ ];
294
+ }
295
+ function quoteForSsh(value) {
296
+ return /^[\w./%@:+-]+$/.test(value) ? value : `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
297
+ }
298
+ //#endregion
299
+ //#region src/cli/sandbox-access.ts
300
+ const SSH_INCLUDE_FILE = "archil_config";
301
+ const SSH_INCLUDE_LINE = `Include ~/.ssh/${SSH_INCLUDE_FILE}`;
302
+ /** The block an earlier version of `ssh-config --install` appended. */
303
+ const LEGACY_BLOCK = /# >>> archil sandboxes >>>[\s\S]*?# <<< archil sandboxes <<<\n?/;
304
+ /** `config` with the archil Include as its first line, exactly once, and no legacy appended block. */
305
+ function withArchilInclude(config) {
306
+ const rest = config.replace(LEGACY_BLOCK, "").split("\n").filter((line) => line.trim() !== SSH_INCLUDE_LINE).join("\n").replace(/^\n+/, "").replace(/\n{2,}$/, "\n");
307
+ return `${SSH_INCLUDE_LINE}\n${rest ? `\n${rest}` : ""}`;
308
+ }
309
+ /** Resumes a paused sandbox or cold-starts a stopped one, showing progress. */
310
+ async function wakeSandbox(ui, sandbox) {
311
+ if (sandbox.status === "paused") await ui.step(`Resuming ${sandbox.name}`, () => sandbox.resume(), `Resumed ${sandbox.name}`);
312
+ else if (sandbox.status === "stopped" || sandbox.status === "exited" || sandbox.status === "failed") await ui.step(`Starting ${sandbox.name}`, () => sandbox.start(), `Started ${sandbox.name}`);
313
+ if (sandbox.status !== "running") throw new Error(`Sandbox '${sandbox.name}' is ${sandbox.status}; wait for it to settle and try again`);
314
+ }
315
+ function addAccessCommands(context) {
316
+ addDesktopCommand(context);
317
+ addForwardCommand(context);
318
+ addSshCommands(context);
319
+ }
320
+ /** Waits for Ctrl-C (or SIGTERM/SIGHUP). */
321
+ function untilInterrupted(signals) {
322
+ return new Promise((resolve) => {
323
+ const names = [
324
+ "SIGINT",
325
+ "SIGTERM",
326
+ "SIGHUP"
327
+ ];
328
+ const done = () => {
329
+ for (const name of names) signals.off(name, done);
330
+ resolve();
331
+ };
332
+ for (const name of names) signals.on(name, done);
333
+ });
334
+ }
335
+ /**
336
+ * Forwards `port` privately, prints `describe`'s summary, shows a live status
337
+ * line until Ctrl-C, then closes the forward (which revokes its token).
338
+ */
339
+ async function serveTunnel(context, sandbox, port, requestedLocalPort, describe, status, open, outputFormat) {
340
+ const { ui, signals, now } = context;
341
+ const { style } = ui;
342
+ let activity = {
343
+ connections: 0,
344
+ websockets: 0
345
+ };
346
+ let live;
347
+ const started = now();
348
+ const statusLine = () => `${style.green("●")} ${style.bold("Live")} ${status(activity)} ${style.dim("·")} up ${formatDuration(now() - started)} ${style.dim("· Ctrl-C to stop")}`;
349
+ const forwarded = await ui.step("Opening private tunnel", () => forwardPort(sandbox, port, {
350
+ localPort: requestedLocalPort,
351
+ openTunnel: context.openTunnel,
352
+ onActivity: (next) => {
353
+ activity = next;
354
+ live?.update(statusLine());
355
+ },
356
+ onWarning: (message) => ui.warn(message)
357
+ }), "Private tunnel open");
358
+ const { url, rows, json } = describe(forwarded.localPort);
359
+ if (outputFormat === "json") context.output(JSON.stringify(json, null, 2));
360
+ else if (!context.stdout.isTTY || !ui.interactive) context.output(url);
361
+ if (ui.interactive) {
362
+ ui.blank();
363
+ ui.details(rows);
364
+ ui.blank();
365
+ }
366
+ if (open) openUrlQuietly(context, url);
367
+ live = ui.live(statusLine());
368
+ const ticker = setInterval(() => live?.update(statusLine()), 1e3);
369
+ try {
370
+ await untilInterrupted(signals);
371
+ } finally {
372
+ clearInterval(ticker);
373
+ live.stop();
374
+ }
375
+ const uptime = formatDuration(now() - started);
376
+ await forwarded.close();
377
+ await sandbox.processes.disconnect().catch(() => {});
378
+ ui.success(`Closed tunnel after ${uptime} and revoked its access token`);
379
+ }
380
+ function openUrlQuietly(context, url) {
381
+ try {
382
+ context.openUrl(url);
383
+ } catch {}
384
+ }
385
+ function link(ui, url) {
386
+ return ui.style.cyan(ui.style.underline(url));
387
+ }
388
+ function plural(count, noun) {
389
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
390
+ }
391
+ function addDesktopCommand(context) {
392
+ const { program, ui, output } = context;
393
+ context.formatOption(program.command("desktop <id|name>").description("Open a sandbox's desktop in your browser").addHelpText("after", `
394
+ By default the desktop stays private: a short-lived Archil port token and a
395
+ tunnel on localhost carry the connection, and the command runs until Ctrl-C.
396
+ --share instead publishes a public link that anyone can use to see and control
397
+ the desktop until you run --unshare.
398
+ `)).option("--share", "Print a public viewer link instead of opening a private tunnel").option("--unshare", "Remove the public link, invalidate old links, and disconnect viewers").option("--port <port>", "Local tunnel port (default: 6080, or any free port if it is taken)").option("--no-open", "Print the URL without opening a browser").action(async (target, options) => {
399
+ if (options.share && options.unshare) throw new Error("Pass either --share or --unshare, not both");
400
+ const localPort = optionalInteger(options.port, "Port", 1, 65535);
401
+ const sandbox = await context.resolve(target);
402
+ await wakeSandbox(ui, sandbox);
403
+ try {
404
+ await openDesktop(context, sandbox, options, localPort);
405
+ } finally {
406
+ await sandbox.processes.disconnect().catch(() => {});
407
+ }
408
+ });
409
+ }
410
+ async function openDesktop(context, sandbox, options, localPort) {
411
+ const { ui, output } = context;
412
+ const { style } = ui;
413
+ if (options.unshare) {
414
+ await ui.step(`Unpublishing ${sandbox.name}`, () => sandbox.desktop.unshare(), `Unpublished ${sandbox.name}; old links stop working and viewers are disconnected`);
415
+ if (options.output === "json") output(JSON.stringify({
416
+ id: sandbox.id,
417
+ name: sandbox.name,
418
+ url: null,
419
+ shared: false
420
+ }, null, 2));
421
+ else if (!ui.interactive) output(`Unshared '${sandbox.name}'; old links no longer work.`);
422
+ return;
423
+ }
424
+ const { token } = await ui.step("Starting desktop", () => sandbox.desktop.start(), "Desktop running");
425
+ const deskName = style.bold(sandbox.name);
426
+ if (options.share) {
427
+ const url = await ui.step("Publishing desktop", () => sandbox.desktop.share(), "Published");
428
+ if (options.output === "json") output(JSON.stringify({
429
+ id: sandbox.id,
430
+ name: sandbox.name,
431
+ url,
432
+ shared: true
433
+ }, null, 2));
434
+ else if (!context.stdout.isTTY || !ui.interactive) output(url);
435
+ if (ui.interactive) {
436
+ ui.blank();
437
+ ui.details([["Desktop", link(ui, url)], ["Sandbox", deskName]]);
438
+ ui.blank();
439
+ ui.warn(`Anyone with this link can see and control the desktop. Revoke it with ${style.bold(`${context.commandName} desktop ${sandbox.name} --unshare`)}`);
440
+ }
441
+ return;
442
+ }
443
+ await serveTunnel(context, sandbox, DESKTOP_PORT, localPort, (port) => {
444
+ const url = `http://127.0.0.1:${port}${desktopViewerPath(token)}`;
445
+ return {
446
+ url,
447
+ rows: [
448
+ ["Desktop", link(ui, url)],
449
+ ["Sandbox", `${deskName} ${style.dim(`· ${sandbox.vcpuCount} vCPU · ${Math.round(sandbox.memSizeMiB / 1024)} GiB`)}`],
450
+ ["Access", `private to this machine ${style.dim("· the sandbox stays awake while this runs")}`],
451
+ ...options.open ? [["Browser", "opened in your default browser"]] : []
452
+ ],
453
+ json: {
454
+ id: sandbox.id,
455
+ name: sandbox.name,
456
+ url,
457
+ shared: false
458
+ }
459
+ };
460
+ }, (activity) => plural(activity.websockets, "viewer"), options.open, options.output);
461
+ }
462
+ function addForwardCommand(context) {
463
+ const { program, ui } = context;
464
+ context.formatOption(program.command("forward <id|name> <port>").description("Forward a sandbox's HTTP port to localhost, privately").addHelpText("after", `
465
+ The port stays private: a short-lived Archil port token and a tunnel on
466
+ localhost carry the traffic until Ctrl-C. HTTP and WebSocket services work;
467
+ other protocols (databases, raw TCP) don't, because Archil authenticates the
468
+ first HTTP request on each connection.
469
+
470
+ Examples:
471
+ archil sandbox forward dev 3000
472
+ archil sandbox forward dev 8888 --local-port 9999
473
+ `)).option("--local-port <port>", "Local port (default: the same port, or any free port if it is taken)").option("--open", "Open the forwarded URL in your browser").action(async (target, remotePort, options) => {
474
+ const port = optionalInteger(remotePort, "Port", 1, 65535);
475
+ const localPort = optionalInteger(options.localPort, "Local port", 1, 65535);
476
+ const sandbox = await context.resolve(target);
477
+ await wakeSandbox(ui, sandbox);
478
+ const { style } = ui;
479
+ await serveTunnel(context, sandbox, port, localPort, (actual) => {
480
+ const url = `http://127.0.0.1:${actual}`;
481
+ return {
482
+ url,
483
+ rows: [["Forwarding", `${link(ui, url)} ${style.dim("→")} ${style.bold(sandbox.name)}:${port}`], ["Access", `private to this machine ${style.dim("· HTTP and WebSocket only · the sandbox stays awake while this runs")}`]],
484
+ json: {
485
+ id: sandbox.id,
486
+ name: sandbox.name,
487
+ port,
488
+ url
489
+ }
490
+ };
491
+ }, (activity) => plural(activity.connections, "connection"), options.open ?? false, options.output);
492
+ });
493
+ }
494
+ function addSshCommands(context) {
495
+ const { program, ui } = context;
496
+ /**
497
+ * The CLI arguments a persisted ProxyCommand needs to reach the same
498
+ * account later, from an editor that has none of this shell's environment.
499
+ * A key saved in a profile is referenced by --profile. A key that only exists
500
+ * in ARCHIL_API_KEY or --api-key is never written to disk; `persistsKey` says
501
+ * whether the config works without it. Region and base URL aren't secret, so
502
+ * they're written whenever the profile doesn't already supply them.
503
+ */
504
+ const persistentProxyArgs = async () => {
505
+ const credentials = context.credentials();
506
+ const config = await loadProfiles();
507
+ const profile = credentials.profile ? config.profiles[credentials.profile] : void 0;
508
+ const savedKey = profile ? await readProfileCredential(credentials.profile).catch(() => void 0) : void 0;
509
+ const persistsKey = savedKey !== void 0 && savedKey === credentials.apiKey;
510
+ const args = [...context.selfCommand];
511
+ if (persistsKey) args.push("--profile", credentials.profile);
512
+ if (!persistsKey || credentials.region !== profile?.region) args.push("--region", credentials.region);
513
+ if (credentials.baseUrl && (!persistsKey || credentials.baseUrl !== profile?.baseUrl)) args.push("--base-url", credentials.baseUrl);
514
+ return {
515
+ args,
516
+ persistsKey
517
+ };
518
+ };
519
+ program.command("ssh <id|name> [command...]").description("Open an SSH session (or run a command) in a sandbox").addHelpText("after", `
520
+ Uses real SSH, so ssh options, port forwarding (-L), and agent forwarding work.
521
+ The connection runs over the Archil API; no port is opened. The first
522
+ connection installs openssh-server if the image doesn't have it.
523
+
524
+ Arguments after the sandbox go to ssh; put -- before any that start with a dash:
525
+ archil sandbox ssh dev
526
+ archil sandbox ssh dev -- uname -a
527
+ archil sandbox ssh dev -- -L 5432:localhost:5432
528
+ For scp, rsync, VS Code, and Cursor, run 'ssh-config --install' once and use
529
+ the host <sandbox-name>${SSH_HOST_SUFFIX}.
530
+ `).action(async (target, command) => {
531
+ const credentials = context.credentials();
532
+ await ensureKeyWithProgress(ui);
533
+ const code = await context.runSsh([
534
+ ...sshOptions(context.selfCommand),
535
+ `${sshTarget(target)}${SSH_HOST_SUFFIX}`,
536
+ ...command
537
+ ], {
538
+ ...process.env,
539
+ ARCHIL_API_KEY: credentials.apiKey,
540
+ ARCHIL_REGION: credentials.region,
541
+ ...credentials.baseUrl ? { ARCHIL_BASE_URL: credentials.baseUrl } : {}
542
+ });
543
+ context.setExitCode(code);
544
+ });
545
+ program.command("ssh-proxy <host>").description("Connect ssh's stdin/stdout to a sandbox (used as an ssh ProxyCommand)").action(async (host) => {
546
+ const publicKey = await ensureSshKey();
547
+ const sandbox = await context.resolve(sshTarget(host));
548
+ await wakeSandbox(ui, sandbox);
549
+ const notify = (message) => ui.info(message);
550
+ const { sshd, hostKey } = await prepareSandboxSsh(sandbox, publicKey, notify);
551
+ await rememberHostKey(sshKnownHostsPath(), host, hostKey);
552
+ context.setExitCode(await relaySshd(sandbox, sshd, context.stdin, context.stdout, context.stderr));
553
+ });
554
+ program.command("ssh-config").description("Print (or --install) the ssh config that makes <sandbox>.archil hosts work").option("--install", "Write ~/.ssh/archil_config and include it from the top of ~/.ssh/config").action(async (options) => {
555
+ await ensureKeyWithProgress(ui);
556
+ const { args, persistsKey } = await persistentProxyArgs();
557
+ const block = sshConfigBlock(args);
558
+ if (!persistsKey) ui.warn("Your API key comes from ARCHIL_API_KEY or --api-key, which this config can't store. ssh needs that variable set wherever it runs, and editors usually don't have it. Run 'archil login' to save a profile instead.");
559
+ if (context.selfCommand.some((part) => part.includes(`/_npx/`))) ui.warn("This config points at a temporary npx copy of the CLI. Install it first so the path stays valid: npm install -g archil");
560
+ if (!options.install) {
561
+ context.output(block.trimEnd());
562
+ return;
563
+ }
564
+ const sshDir = join(homedir(), ".ssh");
565
+ await mkdir(sshDir, {
566
+ recursive: true,
567
+ mode: 448
568
+ });
569
+ await writeFile(join(sshDir, SSH_INCLUDE_FILE), block, { mode: 384 });
570
+ const path = join(sshDir, "config");
571
+ let existing = "";
572
+ try {
573
+ existing = await readFile(path, "utf8");
574
+ } catch (error) {
575
+ if (error.code !== "ENOENT") throw error;
576
+ }
577
+ await writeFile(path, withArchilInclude(existing), { mode: 384 });
578
+ ui.success(`Added ${ui.style.bold(`*${SSH_HOST_SUFFIX}`)} hosts (${join("~/.ssh", SSH_INCLUDE_FILE)}, included at the top of ~/.ssh/config)`);
579
+ ui.blank();
580
+ ui.details([
581
+ ["Shell", `ssh my-sandbox${SSH_HOST_SUFFIX}`],
582
+ ["Copy", `scp ./file my-sandbox${SSH_HOST_SUFFIX}:/root/`],
583
+ ["Editors", `Remote-SSH: Connect to Host... → my-sandbox${SSH_HOST_SUFFIX}`]
584
+ ]);
585
+ });
586
+ }
587
+ async function ensureKeyWithProgress(ui) {
588
+ try {
589
+ return (await readFile(`${sshKeyPath()}.pub`, "utf8")).trim();
590
+ } catch {
591
+ return ui.step("Creating an SSH key for Archil", () => ensureSshKey(), `Created SSH key ${sshKeyPath()}`);
592
+ }
593
+ }
594
+ function runSshProcess(args, env) {
595
+ return new Promise((resolve, reject) => {
596
+ const child = spawn("ssh", args, {
597
+ stdio: "inherit",
598
+ env
599
+ });
600
+ child.on("error", (error) => reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error("ssh isn't installed on this machine; install OpenSSH and try again") : error));
601
+ child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
602
+ });
603
+ }
604
+ //#endregion
605
+ //#region src/cli/sandbox-shell.ts
606
+ async function runSandboxShell(options) {
607
+ const stdin = options.stdin ?? process.stdin;
608
+ const stdout = options.stdout ?? process.stdout;
609
+ const stderr = options.stderr ?? process.stderr;
610
+ const signals = options.signals ?? process;
611
+ const forceExit = options.forceExit ?? (options.signals ? (() => {}) : (signal) => {
612
+ process.kill(process.pid, signal);
613
+ });
614
+ if (!stdin.isTTY || !stdout.isTTY) throw new Error("sandbox shell requires TTY stdin and stdout");
615
+ let remote;
616
+ let result;
617
+ let terminationRequested = false;
618
+ let terminationStarted = false;
619
+ let terminationReason = "terminated locally";
620
+ let terminalConfigured = false;
621
+ let failureSettled = false;
622
+ let rejectFailure;
623
+ const failure = new Promise((_resolve, reject) => {
624
+ rejectFailure = reject;
625
+ });
626
+ const fail = (error) => {
627
+ if (failureSettled) return;
628
+ failureSettled = true;
629
+ rejectFailure(error instanceof Error ? error : new Error(String(error)));
630
+ };
631
+ let resolveTermination;
632
+ let rejectTermination;
633
+ const termination = new Promise((resolve, reject) => {
634
+ resolveTermination = resolve;
635
+ rejectTermination = reject;
636
+ });
637
+ const startTermination = () => {
638
+ if (!remote || terminationStarted) return;
639
+ terminationStarted = true;
640
+ remote.kill().then(() => resolveTermination({
641
+ status: "cancelled",
642
+ exitReason: terminationReason,
643
+ stdout: "",
644
+ stderr: ""
645
+ }), (error) => rejectTermination(error instanceof Error ? error : new Error(String(error))));
646
+ };
647
+ const removeSignalListeners = () => {
648
+ signals.off("SIGINT", onSigint);
649
+ signals.off("SIGTERM", onSigterm);
650
+ signals.off("SIGHUP", onSighup);
651
+ };
652
+ const requestTermination = (reason, signal) => {
653
+ if (terminationRequested) {
654
+ if (signal) {
655
+ stdin.off("data", onInput);
656
+ stdout.off("resize", onResize);
657
+ removeSignalListeners();
658
+ if (terminalConfigured) {
659
+ stdin.setRawMode(priorRaw);
660
+ terminalConfigured = false;
661
+ }
662
+ stdin.pause();
663
+ forceExit(signal);
664
+ }
665
+ return;
666
+ }
667
+ terminationRequested = true;
668
+ terminationReason = reason;
669
+ startTermination();
670
+ };
671
+ const onInput = (chunk) => {
672
+ const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : new Uint8Array(chunk);
673
+ const emergency = bytes.indexOf(29);
674
+ if (emergency >= 0) {
675
+ if (emergency > 0) remote.sendInput(bytes.subarray(0, emergency)).catch(fail);
676
+ requestTermination("terminated by Ctrl+]", "SIGTERM");
677
+ } else remote.sendInput(bytes).catch(fail);
678
+ };
679
+ const onResize = () => {
680
+ if (remote) remote.resize({
681
+ cols: stdout.columns ?? 80,
682
+ rows: stdout.rows ?? 24
683
+ }).catch(fail);
684
+ };
685
+ const onSigint = () => requestTermination("terminated by local signal", "SIGINT");
686
+ const onSigterm = () => requestTermination("terminated by local signal", "SIGTERM");
687
+ const onSighup = () => requestTermination("terminated by local signal", "SIGHUP");
688
+ const priorRaw = stdin.isRaw ?? false;
689
+ try {
690
+ remote = await options.sandbox.run("/bin/sh -l", {
691
+ terminal: {
692
+ cols: stdout.columns ?? 80,
693
+ rows: stdout.rows ?? 24
694
+ },
695
+ collectOutput: false
696
+ });
697
+ stdin.setRawMode(true);
698
+ terminalConfigured = true;
699
+ stdout.on("resize", onResize);
700
+ signals.on("SIGINT", onSigint);
701
+ signals.on("SIGTERM", onSigterm);
702
+ signals.on("SIGHUP", onSighup);
703
+ stderr.write(`Archil shell process ${remote.id}; Ctrl+] exits\n`);
704
+ stdin.on("data", onInput);
705
+ stdin.resume();
706
+ const streaming = (async () => {
707
+ for await (const { data } of remote.output) await writeOutput(stdout, data);
708
+ })();
709
+ result = await Promise.race([
710
+ streaming.then(() => remote.wait()),
711
+ termination,
712
+ failure
713
+ ]);
714
+ failureSettled = true;
715
+ return result;
716
+ } finally {
717
+ stdin.off("data", onInput);
718
+ stdout.off("resize", onResize);
719
+ removeSignalListeners();
720
+ if (terminalConfigured) stdin.setRawMode(priorRaw);
721
+ stdin.pause();
722
+ if (remote && !result && !terminationRequested) await remote.kill().catch(() => {});
723
+ if (remote) await remote.disconnect().catch(() => {});
724
+ await options.sandbox.processes.disconnect();
725
+ }
726
+ }
727
+ //#endregion
728
+ //#region src/cli/sandbox-command.ts
729
+ const SANDBOX_ACTIONS = {
730
+ running: [
731
+ "pause",
732
+ "stop",
733
+ "fork"
734
+ ],
735
+ paused: [
736
+ "resume",
737
+ "start",
738
+ "stop",
739
+ "fork"
740
+ ],
741
+ stopped: [
742
+ "start",
743
+ "fork",
744
+ "delete"
745
+ ],
746
+ exited: ["start", "delete"],
747
+ failed: ["start", "delete"],
748
+ pending: [],
749
+ pausing: [],
750
+ stopping: [],
751
+ deleting: [],
752
+ deleted: []
753
+ };
754
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
755
+ async function resolveSandbox(service, idOrName) {
756
+ if (UUID.test(idOrName)) return service.get(idOrName);
757
+ const byName = (await service.list()).filter(({ name }) => name === idOrName);
758
+ if (byName.length === 0) throw new Error(`No sandbox found with id or name '${idOrName}'`);
759
+ if (byName.length > 1) throw new Error(`Multiple sandboxes are named '${idOrName}'; pass an exact sandbox id`);
760
+ return byName[0];
761
+ }
762
+ function openInBrowser(url) {
763
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
764
+ spawn(command, args, {
765
+ stdio: "ignore",
766
+ detached: true
767
+ }).on("error", () => {}).unref();
768
+ }
769
+ function commandNames(command) {
770
+ const names = [];
771
+ for (let current = command; current; current = current.parent) names.unshift(current.name());
772
+ return names;
773
+ }
774
+ function resultExitCode(result) {
775
+ return result.exitCode ?? (result.status === "completed" ? 0 : 1);
776
+ }
777
+ function createSandboxProgram(dependencies) {
778
+ const program = new Command().name("sandbox").description("Manage Archil sandboxes from the command line").version(dependencies.version);
779
+ addGlobalOptions(program);
780
+ addProfileCommands(program, dependencies.validateCredential);
781
+ addSandboxCommands(program, program, {
782
+ jsonWhenPiped: false,
783
+ ...dependencies
784
+ });
785
+ return program;
786
+ }
787
+ /**
788
+ * Adds the sandbox commands to `program`. Credentials come from the global
789
+ * options on `credentialsFrom`, which is `program` itself for the standalone
790
+ * `sandbox` CLI and the root program when nested as `archil sandbox`.
791
+ */
792
+ function addSandboxCommands(program, credentialsFrom, dependencies) {
793
+ const stdout = dependencies.stdout ?? process.stdout;
794
+ const stderr = dependencies.stderr ?? process.stderr;
795
+ const stdin = dependencies.stdin ?? process.stdin;
796
+ const signals = dependencies.signals ?? process;
797
+ const setExitCode = dependencies.setExitCode ?? ((code) => {
798
+ process.exitCode = code;
799
+ });
800
+ const forceExit = dependencies.forceExit ?? (dependencies.signals ? (() => {}) : (signal) => {
801
+ process.kill(process.pid, signal);
802
+ });
803
+ const now = dependencies.now ?? Date.now;
804
+ const sleep = dependencies.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
805
+ let service;
806
+ let credentials;
807
+ program.hook("preAction", async (_thisCommand, actionCommand) => {
808
+ if (isProfileCommand(actionCommand)) return;
809
+ credentials = await resolveProgramCredentials(credentialsFrom);
810
+ service = dependencies.createClient(credentials).sandboxes;
811
+ });
812
+ const ui = createUi(stderr, { now });
813
+ const tableStyle = styles(dependencies.jsonWhenPiped !== false && colorEnabled(stdout));
814
+ const output = (value) => stdout.write(`${value}\n`);
815
+ const withSpinner = async (label, enabled, operation, done) => enabled ? ui.step(label, operation, done) : operation();
816
+ const requireService = () => {
817
+ if (!service) throw new Error("Sandbox client was not configured");
818
+ return service;
819
+ };
820
+ const formatOption = (command, { jsonWhenPiped = true } = {}) => command.option("-o, --output <format>", jsonWhenPiped && dependencies.jsonWhenPiped !== false ? "Output format: table | json (default: table in a terminal, json when piped)" : "Output format: table | json", parseOutputFormat, stdout.isTTY || !jsonWhenPiped || dependencies.jsonWhenPiped === false ? "table" : "json");
821
+ const waitOption = (command) => command.option("--no-wait", "Return after the operation is accepted");
822
+ const confirmDestructive = async (question, yes) => {
823
+ if (yes) return true;
824
+ if (!stdin.isTTY || !stderr.isTTY) throw new Error("This operation requires --yes when stdin/stderr is non-interactive");
825
+ if (dependencies.confirm) return dependencies.confirm(question);
826
+ const prompt = createInterface({
827
+ input: stdin,
828
+ output: stderr
829
+ });
830
+ try {
831
+ return /^(y|yes)$/i.test((await prompt.question(`${question} [y/N] `)).trim());
832
+ } finally {
833
+ prompt.close();
834
+ }
835
+ };
836
+ formatOption(program.command("list").description("List sandboxes")).action(async (options) => {
837
+ output(formatSandboxList(await requireService().list(), options.output, tableStyle));
838
+ });
839
+ formatOption(program.command("get <id|name>").description("Show sandbox details")).action(async (target, options) => {
840
+ output(formatSandbox(await resolveSandbox(requireService(), target), options.output, tableStyle));
841
+ });
842
+ waitOption(formatOption(program.command("create [name]").description("Create a sandbox"))).option("--vcpu-count <count>", "Virtual CPU count (1-32)").option("--mem-size-mib <mib>", "Memory in MiB (256-65536)").option("--desktop", "Start a VNC desktop you can open with the desktop command").option("--base-image <image>", "Public OCI image (default: ubuntu:26.04, or the desktop image with --desktop)").option("--max-ttl-seconds <seconds>", "Maximum sandbox lifetime").option("--idle-ttl-seconds <seconds>", "Seconds without a process connection before pausing (0 disables)").option("--on-timeout <pause|delete>", "Pause (default) or delete the sandbox when a TTL runs out").option("--max-concurrent-processes <count>", "Maximum attached processes").option("--env <name=value>", "Set an environment variable (repeatable)", (value, previous) => [...previous, value], []).action(async (name, options) => {
843
+ if (options.desktop && !options.wait) throw new Error("--desktop waits for the sandbox to start; remove --no-wait");
844
+ const request = parseCreateSandboxOptions(name, options);
845
+ const label = request.name ? `Creating ${request.name}` : "Creating sandbox";
846
+ const sandbox = await withSpinner(label, options.wait, () => requireService().create(request, { wait: options.wait }), (created) => `Created ${ui.style.bold(created.name)}`);
847
+ if (options.desktop) try {
848
+ await ui.step("Starting desktop", () => sandbox.desktop.start(), "Desktop running");
849
+ } catch (error) {
850
+ output(formatSandbox(sandbox, options.output, tableStyle));
851
+ const name = commandNames(program).join(" ");
852
+ ui.warn(`'${sandbox.name}' was created but its desktop didn't start. Retry with ${ui.style.bold(`${name} desktop ${sandbox.name}`)}, or remove it with ${ui.style.bold(`${name} stop ${sandbox.name} && ${name} delete ${sandbox.name}`)}.`);
853
+ throw error;
854
+ } finally {
855
+ await sandbox.processes.disconnect().catch(() => {});
856
+ }
857
+ output(formatSandbox(sandbox, options.output, tableStyle));
858
+ if (ui.interactive) {
859
+ const name = commandNames(program).join(" ");
860
+ ui.blank();
861
+ ui.info(options.desktop ? `Open the desktop: ${ui.style.bold(`${name} desktop ${sandbox.name}`)}` : `Open a shell: ${ui.style.bold(`${name} shell ${sandbox.name}`)}`);
862
+ }
863
+ });
864
+ addAccessCommands({
865
+ program,
866
+ ui,
867
+ stdout,
868
+ stderr,
869
+ stdin,
870
+ signals,
871
+ now,
872
+ output,
873
+ formatOption: (command) => formatOption(command, { jsonWhenPiped: false }),
874
+ resolve: (target) => resolveSandbox(requireService(), target),
875
+ credentials: () => {
876
+ if (!credentials) throw new Error("Sandbox client was not configured");
877
+ return credentials;
878
+ },
879
+ openUrl: dependencies.openUrl ?? openInBrowser,
880
+ openTunnel: dependencies.openTunnel ?? openPortTunnel,
881
+ get selfCommand() {
882
+ return dependencies.selfCommand ?? [
883
+ process.execPath,
884
+ process.argv[1],
885
+ ...commandNames(program).slice(1)
886
+ ];
887
+ },
888
+ get commandName() {
889
+ return commandNames(program).join(" ");
890
+ },
891
+ setExitCode,
892
+ runSsh: dependencies.runSsh ?? runSshProcess
893
+ });
894
+ const addLifecycleCommand = (action) => {
895
+ const command = waitOption(formatOption(program.command(`${action} <id|name>`).description(`${action[0].toUpperCase()}${action.slice(1)} a sandbox`)));
896
+ if (action === "start") command.option("-y, --yes", "Confirm cold-starting a paused sandbox");
897
+ command.action(async (target, options) => {
898
+ const sandbox = await resolveSandbox(requireService(), target);
899
+ if (!SANDBOX_ACTIONS[sandbox.status].includes(action)) throw new Error(`Cannot ${action} sandbox '${sandbox.name}' while it is ${sandbox.status}`);
900
+ if (action === "start" && sandbox.status === "paused" && !await confirmDestructive(`Cold-start '${sandbox.name}' and discard its memory snapshot?`, options.yes ?? false)) {
901
+ if (options.output === "json") output(JSON.stringify({
902
+ id: sandbox.id,
903
+ name: sandbox.name,
904
+ action,
905
+ cancelled: true
906
+ }, null, 2));
907
+ else output(`Cancelled cold-start of '${sandbox.name}'.`);
908
+ return;
909
+ }
910
+ await withSpinner(`${{
911
+ start: "Starting sandbox",
912
+ pause: "Pausing sandbox",
913
+ resume: "Resuming sandbox",
914
+ stop: "Stopping sandbox"
915
+ }[action]} ${sandbox.name}`, options.wait, () => sandbox[action]({ wait: options.wait }), `${{
916
+ start: "Started",
917
+ pause: "Paused",
918
+ resume: "Resumed",
919
+ stop: "Stopped"
920
+ }[action]} ${ui.style.bold(sandbox.name)}`);
921
+ output(formatSandbox(sandbox, options.output, tableStyle));
922
+ });
923
+ };
924
+ addLifecycleCommand("start");
925
+ addLifecycleCommand("pause");
926
+ addLifecycleCommand("resume");
927
+ addLifecycleCommand("stop");
928
+ waitOption(formatOption(program.command("fork <id|name> [new-name]").description("Fork a sandbox"))).action(async (target, name, options) => {
929
+ const sandbox = await resolveSandbox(requireService(), target);
930
+ if (!SANDBOX_ACTIONS[sandbox.status].includes("fork")) throw new Error(`Cannot fork sandbox '${sandbox.name}' while it is ${sandbox.status}`);
931
+ const fork = await withSpinner(`Forking ${sandbox.name}`, options.wait, () => sandbox.fork({
932
+ name: validateSandboxName(name),
933
+ wait: options.wait
934
+ }), (forked) => `Forked ${ui.style.bold(sandbox.name)} into ${ui.style.bold(forked.name)}`);
935
+ output(formatSandbox(fork, options.output, tableStyle));
936
+ });
937
+ formatOption(program.command("delete <id|name>").description("Delete a sandbox permanently")).action(async (target, options) => {
938
+ const sandbox = await resolveSandbox(requireService(), target);
939
+ if (!SANDBOX_ACTIONS[sandbox.status].includes("delete")) throw new Error(`Cannot delete sandbox '${sandbox.name}' while it is ${sandbox.status}`);
940
+ await withSpinner(`Deleting ${sandbox.name}`, true, () => sandbox.delete(), `Deleted ${ui.style.bold(sandbox.name)}`);
941
+ if (options.output === "json") output(JSON.stringify({
942
+ id: sandbox.id,
943
+ name: sandbox.name,
944
+ deleted: true
945
+ }, null, 2));
946
+ else output(`Deleted '${sandbox.name}' (${sandbox.id}).`);
947
+ });
948
+ const stableStatuses = [
949
+ "running",
950
+ "paused",
951
+ "stopped",
952
+ "exited",
953
+ "failed"
954
+ ];
955
+ formatOption(program.command("wait <id|name>").description("Wait for a sandbox to reach a stable state")).option("--status <status>", "Stable status: running | paused | stopped | exited | failed", (value) => {
956
+ if (!stableStatuses.includes(value)) throw new Error(`Status must be one of: ${stableStatuses.join(", ")}`);
957
+ return value;
958
+ }).option("--timeout <seconds>", "Maximum time to wait in seconds", "300").action(async (target, options) => {
959
+ const timeoutSeconds = Number(options.timeout);
960
+ if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1) throw new Error("Wait timeout must be an integer of at least 1 second");
961
+ const sandbox = await resolveSandbox(requireService(), target);
962
+ const deadline = now() + timeoutSeconds * 1e3;
963
+ await withSpinner(`Waiting for '${sandbox.name}'`, true, async () => {
964
+ while (options.status ? sandbox.status !== options.status : !stableStatuses.includes(sandbox.status)) {
965
+ const remaining = deadline - now();
966
+ if (remaining <= 0) {
967
+ const desired = options.status ? `status '${options.status}'` : "a stable state";
968
+ throw new Error(`Timed out after ${timeoutSeconds} seconds waiting for sandbox '${sandbox.name}' to reach ${desired}; current status is '${sandbox.status}'`);
969
+ }
970
+ await sleep(Math.min(500, remaining));
971
+ await sandbox.refresh();
972
+ }
973
+ });
974
+ output(formatSandbox(sandbox, options.output, tableStyle));
975
+ });
976
+ formatOption(program.command("run <id|name> <command...>").description("Run a one-shot command in a running sandbox").addHelpText("after", `
977
+ Examples:
978
+ sandbox run my-sandbox -- echo hello
979
+ sandbox run my-sandbox -- sh -c 'echo "$HOME"'
980
+
981
+ Use -- before the command so its flags are not parsed as sandbox options.
982
+ `), { jsonWhenPiped: false }).option("--env <name=value>", "Set an environment variable (repeatable)", (value, previous) => [...previous, value], []).option("--timeout <seconds>", "Command timeout in seconds").action(async (target, command, options) => {
983
+ const sandbox = await resolveSandbox(requireService(), target);
984
+ if (sandbox.status !== "running") throw new Error(`Cannot run a command in sandbox '${sandbox.name}' while it is ${sandbox.status}`);
985
+ const runOptions = parseRunOptions(options);
986
+ let receivedStderr = false;
987
+ let remote;
988
+ let result;
989
+ let terminationStarted = false;
990
+ let resolveTermination;
991
+ let rejectTermination;
992
+ const termination = new Promise((resolve, reject) => {
993
+ resolveTermination = resolve;
994
+ rejectTermination = reject;
995
+ });
996
+ const removeSignalListeners = () => {
997
+ signals.off("SIGINT", onSigint);
998
+ signals.off("SIGTERM", onSigterm);
999
+ signals.off("SIGHUP", onSighup);
1000
+ };
1001
+ const onSignal = (signal) => {
1002
+ if (!remote) return;
1003
+ if (terminationStarted) {
1004
+ removeSignalListeners();
1005
+ forceExit(signal);
1006
+ return;
1007
+ }
1008
+ terminationStarted = true;
1009
+ remote.kill().then(() => resolveTermination({
1010
+ status: "cancelled",
1011
+ exitReason: "terminated by local signal",
1012
+ stdout: remote?.stdout ?? "",
1013
+ stderr: remote?.stderr ?? ""
1014
+ }), (error) => rejectTermination(error instanceof Error ? error : new Error(String(error))));
1015
+ };
1016
+ const onSigint = () => onSignal("SIGINT");
1017
+ const onSigterm = () => onSignal("SIGTERM");
1018
+ const onSighup = () => onSignal("SIGHUP");
1019
+ try {
1020
+ const shellCommand = command.map((argument) => argument === "" ? "''" : `'${argument.replaceAll("'", `'"'"'`)}'`).join(" ");
1021
+ remote = await sandbox.run(shellCommand, {
1022
+ ...runOptions,
1023
+ collectOutput: options.output === "json"
1024
+ });
1025
+ try {
1026
+ await remote.closeStdin();
1027
+ } catch (error) {
1028
+ if (remote.status === "running") throw error;
1029
+ }
1030
+ signals.on("SIGINT", onSigint);
1031
+ signals.on("SIGTERM", onSigterm);
1032
+ signals.on("SIGHUP", onSighup);
1033
+ const streaming = options.output === "json" ? Promise.resolve() : (async () => {
1034
+ for await (const { stream, data } of remote.output) {
1035
+ if (stream === "stderr" && data.length) receivedStderr = true;
1036
+ await writeOutput(stream === "stdout" ? stdout : stderr, data);
1037
+ }
1038
+ })();
1039
+ result = await Promise.race([streaming.then(() => remote.wait()), termination]);
1040
+ if (options.output === "json") output(JSON.stringify(result, null, 2));
1041
+ else if (result.status !== "completed" && !receivedStderr) {
1042
+ let diagnostic;
1043
+ if (result.status === "timed_out") diagnostic = `Process timed out${runOptions.timeoutSeconds === void 0 ? "" : ` after ${runOptions.timeoutSeconds} second${runOptions.timeoutSeconds === 1 ? "" : "s"}`}`;
1044
+ else if (result.status === "failed") diagnostic = `Process failed${result.exitCode === void 0 ? "" : ` with exit code ${result.exitCode}`}`;
1045
+ else diagnostic = "Process cancelled";
1046
+ stderr.write(`${diagnostic}${result.exitReason ? `: ${result.exitReason}` : ""}\n`);
1047
+ }
1048
+ setExitCode(resultExitCode(result));
1049
+ } finally {
1050
+ removeSignalListeners();
1051
+ if (remote && !result && !terminationStarted) await remote.kill().catch(() => {});
1052
+ await remote?.disconnect().catch(() => {});
1053
+ await sandbox.processes.disconnect();
1054
+ }
1055
+ });
1056
+ formatOption(program.command("shell <id|name>").description("Open an interactive shell in a running sandbox"), { jsonWhenPiped: false }).action(async (target, options) => {
1057
+ const sandbox = await resolveSandbox(requireService(), target);
1058
+ if (sandbox.status !== "running") throw new Error(`Cannot open a shell in sandbox '${sandbox.name}' while it is ${sandbox.status}`);
1059
+ const shellOutput = options.output === "json" ? stderr : stdout;
1060
+ const result = await runSandboxShell({
1061
+ sandbox,
1062
+ stdin,
1063
+ stdout: shellOutput,
1064
+ stderr,
1065
+ signals,
1066
+ forceExit
1067
+ });
1068
+ if (options.output === "json") output(JSON.stringify(result, null, 2));
1069
+ setExitCode(resultExitCode(result));
1070
+ });
1071
+ }
1072
+ //#endregion
1073
+ export { createSandboxProgram as n, openInBrowser as r, addSandboxCommands as t };