disk 1.13.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.
@@ -1,504 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { k as ArchilApiError, p as Archil } from "./src-CRvOOCjY.mjs";
3
- import { a as addGlobalOptions, c as resolveProgramCredentials, d as Command, i as validateSandboxName, l as renderTable, n as parseCreateSandboxOptions, o as addProfileCommands, r as parseRunOptions, s as isProfileCommand, u as spinner } from "./sandbox-options-D99F52j0.mjs";
2
+ import { p as Archil } from "./src-BFPiWUCL.mjs";
3
+ import { C as printError } from "./sandbox-options-AO9jKF4-.mjs";
4
+ import { n as createSandboxProgram } from "./sandbox-command-DJZqMVHm.mjs";
4
5
  import { createRequire } from "node:module";
5
- import { createInterface } from "node:readline/promises";
6
- //#region src/cli/sandbox-output.ts
7
- function parseOutputFormat(value) {
8
- if (value !== "table" && value !== "json") throw new Error("Output format must be 'table' or 'json'");
9
- return value;
10
- }
11
- function date(value) {
12
- return value?.toISOString() ?? "";
13
- }
14
- function sortSandboxes(sandboxes) {
15
- return [...sandboxes].sort((left, right) => {
16
- return right.lastActiveAt.getTime() - left.lastActiveAt.getTime() || left.name.localeCompare(right.name) || left.id.localeCompare(right.id);
17
- });
18
- }
19
- function formatSandboxList(sandboxes, format) {
20
- const ordered = sortSandboxes(sandboxes);
21
- if (format === "json") return JSON.stringify(ordered, null, 2);
22
- if (ordered.length === 0) return "No sandboxes found.";
23
- return renderTable(ordered.map((sandbox) => [
24
- sandbox.id,
25
- sandbox.name,
26
- sandbox.status,
27
- String(sandbox.vcpuCount),
28
- `${sandbox.memSizeMiB} MiB`,
29
- sandbox.baseImage,
30
- date(sandbox.lastActiveAt)
31
- ]), [
32
- "id",
33
- "name",
34
- "status",
35
- "cpu",
36
- "memory",
37
- "image",
38
- "last active"
39
- ]);
40
- }
41
- function formatSandbox(sandbox, format) {
42
- if (format === "json") return JSON.stringify(sandbox, null, 2);
43
- const rows = [
44
- ["id", sandbox.id],
45
- ["name", sandbox.name],
46
- ["status", sandbox.status],
47
- ["cpu", String(sandbox.vcpuCount)],
48
- ["memory", `${sandbox.memSizeMiB} MiB`],
49
- ["image", sandbox.baseImage],
50
- ["platform", sandbox.platform ?? ""],
51
- ["max TTL", `${sandbox.maxTtlSeconds} seconds`],
52
- ["idle TTL", sandbox.idleTtlSeconds === 0 ? "disabled" : `${sandbox.idleTtlSeconds} seconds`],
53
- ["on timeout", sandbox.onTimeout],
54
- ["max concurrent processes", String(sandbox.maxConcurrentExecs)],
55
- ["created", date(sandbox.createdAt)],
56
- ["running", date(sandbox.runningAt)],
57
- ["finished", date(sandbox.finishedAt)],
58
- ["last active", date(sandbox.lastActiveAt)],
59
- ["exit reason", sandbox.exitReason ?? ""]
60
- ];
61
- for (const endpoint of sandbox.endpoints ?? []) rows.push([`endpoint ${endpoint.port}`, endpoint.hostname]);
62
- return renderTable(rows.filter(([, value]) => value !== ""));
63
- }
64
- //#endregion
65
- //#region src/cli/write-output.ts
66
- /**
67
- * Writes `data`, then waits while the stream is full. A stream that closes or
68
- * fails never emits `drain`, so either ends the wait with an error instead.
69
- */
70
- async function writeOutput(stream, data) {
71
- if (stream.write(data) !== false || !stream.on || !stream.off) return;
72
- const { on, off } = {
73
- on: stream.on.bind(stream),
74
- off: stream.off.bind(stream)
75
- };
76
- await new Promise((resolve, reject) => {
77
- const drained = () => {
78
- remove();
79
- resolve();
80
- };
81
- const closed = () => {
82
- remove();
83
- reject(/* @__PURE__ */ new Error("Output stream closed"));
84
- };
85
- const failed = (error) => {
86
- remove();
87
- reject(error instanceof Error ? error : new Error(String(error)));
88
- };
89
- const remove = () => {
90
- off("drain", drained);
91
- off("close", closed);
92
- off("error", failed);
93
- };
94
- on("drain", drained);
95
- on("close", closed);
96
- on("error", failed);
97
- });
98
- }
99
- //#endregion
100
- //#region src/cli/sandbox-shell.ts
101
- async function runSandboxShell(options) {
102
- const stdin = options.stdin ?? process.stdin;
103
- const stdout = options.stdout ?? process.stdout;
104
- const stderr = options.stderr ?? process.stderr;
105
- const signals = options.signals ?? process;
106
- const forceExit = options.forceExit ?? (options.signals ? (() => {}) : (signal) => {
107
- process.kill(process.pid, signal);
108
- });
109
- if (!stdin.isTTY || !stdout.isTTY) throw new Error("sandbox shell requires TTY stdin and stdout");
110
- let remote;
111
- let result;
112
- let terminationRequested = false;
113
- let terminationStarted = false;
114
- let terminationReason = "terminated locally";
115
- let terminalConfigured = false;
116
- let failureSettled = false;
117
- let rejectFailure;
118
- const failure = new Promise((_resolve, reject) => {
119
- rejectFailure = reject;
120
- });
121
- const fail = (error) => {
122
- if (failureSettled) return;
123
- failureSettled = true;
124
- rejectFailure(error instanceof Error ? error : new Error(String(error)));
125
- };
126
- let resolveTermination;
127
- let rejectTermination;
128
- const termination = new Promise((resolve, reject) => {
129
- resolveTermination = resolve;
130
- rejectTermination = reject;
131
- });
132
- const startTermination = () => {
133
- if (!remote || terminationStarted) return;
134
- terminationStarted = true;
135
- remote.kill().then(() => resolveTermination({
136
- status: "cancelled",
137
- exitReason: terminationReason,
138
- stdout: "",
139
- stderr: ""
140
- }), (error) => rejectTermination(error instanceof Error ? error : new Error(String(error))));
141
- };
142
- const removeSignalListeners = () => {
143
- signals.off("SIGINT", onSigint);
144
- signals.off("SIGTERM", onSigterm);
145
- signals.off("SIGHUP", onSighup);
146
- };
147
- const requestTermination = (reason, signal) => {
148
- if (terminationRequested) {
149
- if (signal) {
150
- stdin.off("data", onInput);
151
- stdout.off("resize", onResize);
152
- removeSignalListeners();
153
- if (terminalConfigured) {
154
- stdin.setRawMode(priorRaw);
155
- terminalConfigured = false;
156
- }
157
- stdin.pause();
158
- forceExit(signal);
159
- }
160
- return;
161
- }
162
- terminationRequested = true;
163
- terminationReason = reason;
164
- startTermination();
165
- };
166
- const onInput = (chunk) => {
167
- const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : new Uint8Array(chunk);
168
- const emergency = bytes.indexOf(29);
169
- if (emergency >= 0) {
170
- if (emergency > 0) remote.sendInput(bytes.subarray(0, emergency)).catch(fail);
171
- requestTermination("terminated by Ctrl+]", "SIGTERM");
172
- } else remote.sendInput(bytes).catch(fail);
173
- };
174
- const onResize = () => {
175
- if (remote) remote.resize({
176
- cols: stdout.columns ?? 80,
177
- rows: stdout.rows ?? 24
178
- }).catch(fail);
179
- };
180
- const onSigint = () => requestTermination("terminated by local signal", "SIGINT");
181
- const onSigterm = () => requestTermination("terminated by local signal", "SIGTERM");
182
- const onSighup = () => requestTermination("terminated by local signal", "SIGHUP");
183
- const priorRaw = stdin.isRaw ?? false;
184
- try {
185
- remote = await options.sandbox.run("/bin/sh -l", {
186
- terminal: {
187
- cols: stdout.columns ?? 80,
188
- rows: stdout.rows ?? 24
189
- },
190
- collectOutput: false
191
- });
192
- stdin.setRawMode(true);
193
- terminalConfigured = true;
194
- stdout.on("resize", onResize);
195
- signals.on("SIGINT", onSigint);
196
- signals.on("SIGTERM", onSigterm);
197
- signals.on("SIGHUP", onSighup);
198
- stderr.write(`Archil shell process ${remote.id}; Ctrl+] exits\n`);
199
- stdin.on("data", onInput);
200
- stdin.resume();
201
- const streaming = (async () => {
202
- for await (const { data } of remote.output) await writeOutput(stdout, data);
203
- })();
204
- result = await Promise.race([
205
- streaming.then(() => remote.wait()),
206
- termination,
207
- failure
208
- ]);
209
- failureSettled = true;
210
- return result;
211
- } finally {
212
- stdin.off("data", onInput);
213
- stdout.off("resize", onResize);
214
- removeSignalListeners();
215
- if (terminalConfigured) stdin.setRawMode(priorRaw);
216
- stdin.pause();
217
- if (remote && !result && !terminationRequested) await remote.kill().catch(() => {});
218
- if (remote) await remote.disconnect().catch(() => {});
219
- await options.sandbox.processes.disconnect();
220
- }
221
- }
222
- //#endregion
223
- //#region src/cli/sandbox-command.ts
224
- const SANDBOX_ACTIONS = {
225
- running: [
226
- "pause",
227
- "stop",
228
- "fork"
229
- ],
230
- paused: [
231
- "resume",
232
- "start",
233
- "stop",
234
- "fork"
235
- ],
236
- stopped: [
237
- "start",
238
- "fork",
239
- "delete"
240
- ],
241
- exited: ["start", "delete"],
242
- failed: ["start", "delete"],
243
- pending: [],
244
- pausing: [],
245
- stopping: [],
246
- deleting: [],
247
- deleted: []
248
- };
249
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
250
- async function resolveSandbox(service, idOrName) {
251
- if (UUID.test(idOrName)) return service.get(idOrName);
252
- const byName = (await service.list()).filter(({ name }) => name === idOrName);
253
- if (byName.length === 0) throw new Error(`No sandbox found with id or name '${idOrName}'`);
254
- if (byName.length > 1) throw new Error(`Multiple sandboxes are named '${idOrName}'; pass an exact sandbox id`);
255
- return byName[0];
256
- }
257
- function resultExitCode(result) {
258
- return result.exitCode ?? (result.status === "completed" ? 0 : 1);
259
- }
260
- function createSandboxProgram(dependencies) {
261
- const stdout = dependencies.stdout ?? process.stdout;
262
- const stderr = dependencies.stderr ?? process.stderr;
263
- const stdin = dependencies.stdin ?? process.stdin;
264
- const signals = dependencies.signals ?? process;
265
- const setExitCode = dependencies.setExitCode ?? ((code) => {
266
- process.exitCode = code;
267
- });
268
- const forceExit = dependencies.forceExit ?? (dependencies.signals ? (() => {}) : (signal) => {
269
- process.kill(process.pid, signal);
270
- });
271
- const now = dependencies.now ?? Date.now;
272
- const sleep = dependencies.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
273
- let service;
274
- const program = new Command().name("sandbox").description("Manage Archil sandboxes from the command line").version(dependencies.version).hook("preAction", async (_thisCommand, actionCommand) => {
275
- if (isProfileCommand(actionCommand)) return;
276
- const credentials = await resolveProgramCredentials(program);
277
- service = dependencies.createClient(credentials).sandboxes;
278
- });
279
- addGlobalOptions(program);
280
- addProfileCommands(program, dependencies.validateCredential);
281
- const output = (value) => stdout.write(`${value}\n`);
282
- const withSpinner = async (label, enabled, operation) => {
283
- if (!enabled || !stderr.isTTY) return operation();
284
- const progress = spinner(stderr);
285
- progress.start(label);
286
- try {
287
- return await operation();
288
- } finally {
289
- progress.clear();
290
- }
291
- };
292
- const requireService = () => {
293
- if (!service) throw new Error("Sandbox client was not configured");
294
- return service;
295
- };
296
- const formatOption = (command) => command.option("-o, --output <format>", "Output format: table | json", parseOutputFormat, "table");
297
- const waitOption = (command) => command.option("--no-wait", "Return after the operation is accepted");
298
- const confirmDestructive = async (question, yes) => {
299
- if (yes) return true;
300
- if (!stdin.isTTY || !stderr.isTTY) throw new Error("This operation requires --yes when stdin/stderr is non-interactive");
301
- if (dependencies.confirm) return dependencies.confirm(question);
302
- const prompt = createInterface({
303
- input: stdin,
304
- output: stderr
305
- });
306
- try {
307
- return /^(y|yes)$/i.test((await prompt.question(`${question} [y/N] `)).trim());
308
- } finally {
309
- prompt.close();
310
- }
311
- };
312
- formatOption(program.command("list").description("List sandboxes")).action(async (options) => {
313
- output(formatSandboxList(await requireService().list(), options.output));
314
- });
315
- formatOption(program.command("get <id|name>").description("Show sandbox details")).action(async (target, options) => {
316
- output(formatSandbox(await resolveSandbox(requireService(), target), options.output));
317
- });
318
- 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("--base-image <image>", "Public OCI image", "ubuntu:26.04").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) => {
319
- const sandbox = await withSpinner("Creating sandbox", options.wait, () => requireService().create(parseCreateSandboxOptions(name, options), { wait: options.wait }));
320
- output(formatSandbox(sandbox, options.output));
321
- });
322
- const addLifecycleCommand = (action) => {
323
- const command = waitOption(formatOption(program.command(`${action} <id|name>`).description(`${action[0].toUpperCase()}${action.slice(1)} a sandbox`)));
324
- if (action === "start") command.option("-y, --yes", "Confirm cold-starting a paused sandbox");
325
- command.action(async (target, options) => {
326
- const sandbox = await resolveSandbox(requireService(), target);
327
- if (!SANDBOX_ACTIONS[sandbox.status].includes(action)) throw new Error(`Cannot ${action} sandbox '${sandbox.name}' while it is ${sandbox.status}`);
328
- if (action === "start" && sandbox.status === "paused" && !await confirmDestructive(`Cold-start '${sandbox.name}' and discard its memory snapshot?`, options.yes ?? false)) {
329
- if (options.output === "json") output(JSON.stringify({
330
- id: sandbox.id,
331
- name: sandbox.name,
332
- action,
333
- cancelled: true
334
- }, null, 2));
335
- else output(`Cancelled cold-start of '${sandbox.name}'.`);
336
- return;
337
- }
338
- await withSpinner({
339
- start: "Starting sandbox",
340
- pause: "Pausing sandbox",
341
- resume: "Resuming sandbox",
342
- stop: "Stopping sandbox"
343
- }[action], options.wait, () => sandbox[action]({ wait: options.wait }));
344
- output(formatSandbox(sandbox, options.output));
345
- });
346
- };
347
- addLifecycleCommand("start");
348
- addLifecycleCommand("pause");
349
- addLifecycleCommand("resume");
350
- addLifecycleCommand("stop");
351
- waitOption(formatOption(program.command("fork <id|name> [new-name]").description("Fork a sandbox"))).action(async (target, name, options) => {
352
- const sandbox = await resolveSandbox(requireService(), target);
353
- if (!SANDBOX_ACTIONS[sandbox.status].includes("fork")) throw new Error(`Cannot fork sandbox '${sandbox.name}' while it is ${sandbox.status}`);
354
- const fork = await withSpinner("Forking sandbox", options.wait, () => sandbox.fork({
355
- name: validateSandboxName(name),
356
- wait: options.wait
357
- }));
358
- output(formatSandbox(fork, options.output));
359
- });
360
- formatOption(program.command("delete <id|name>").description("Delete a sandbox permanently")).action(async (target, options) => {
361
- const sandbox = await resolveSandbox(requireService(), target);
362
- if (!SANDBOX_ACTIONS[sandbox.status].includes("delete")) throw new Error(`Cannot delete sandbox '${sandbox.name}' while it is ${sandbox.status}`);
363
- await withSpinner("Deleting sandbox", true, () => sandbox.delete());
364
- if (options.output === "json") output(JSON.stringify({
365
- id: sandbox.id,
366
- name: sandbox.name,
367
- deleted: true
368
- }, null, 2));
369
- else output(`Deleted '${sandbox.name}' (${sandbox.id}).`);
370
- });
371
- const stableStatuses = [
372
- "running",
373
- "paused",
374
- "stopped",
375
- "exited",
376
- "failed"
377
- ];
378
- 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) => {
379
- if (!stableStatuses.includes(value)) throw new Error(`Status must be one of: ${stableStatuses.join(", ")}`);
380
- return value;
381
- }).option("--timeout <seconds>", "Maximum time to wait in seconds", "300").action(async (target, options) => {
382
- const timeoutSeconds = Number(options.timeout);
383
- if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1) throw new Error("Wait timeout must be an integer of at least 1 second");
384
- const sandbox = await resolveSandbox(requireService(), target);
385
- const deadline = now() + timeoutSeconds * 1e3;
386
- await withSpinner(`Waiting for '${sandbox.name}'`, true, async () => {
387
- while (options.status ? sandbox.status !== options.status : !stableStatuses.includes(sandbox.status)) {
388
- const remaining = deadline - now();
389
- if (remaining <= 0) {
390
- const desired = options.status ? `status '${options.status}'` : "a stable state";
391
- throw new Error(`Timed out after ${timeoutSeconds} seconds waiting for sandbox '${sandbox.name}' to reach ${desired}; current status is '${sandbox.status}'`);
392
- }
393
- await sleep(Math.min(500, remaining));
394
- await sandbox.refresh();
395
- }
396
- });
397
- output(formatSandbox(sandbox, options.output));
398
- });
399
- formatOption(program.command("run <id|name> <command...>").description("Run a one-shot command in a running sandbox").addHelpText("after", `
400
- Examples:
401
- sandbox run my-sandbox -- echo hello
402
- sandbox run my-sandbox -- sh -c 'echo "$HOME"'
403
-
404
- Use -- before the command so its flags are not parsed as sandbox options.
405
- `)).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) => {
406
- const sandbox = await resolveSandbox(requireService(), target);
407
- if (sandbox.status !== "running") throw new Error(`Cannot run a command in sandbox '${sandbox.name}' while it is ${sandbox.status}`);
408
- const runOptions = parseRunOptions(options);
409
- let receivedStderr = false;
410
- let remote;
411
- let result;
412
- let terminationStarted = false;
413
- let resolveTermination;
414
- let rejectTermination;
415
- const termination = new Promise((resolve, reject) => {
416
- resolveTermination = resolve;
417
- rejectTermination = reject;
418
- });
419
- const removeSignalListeners = () => {
420
- signals.off("SIGINT", onSigint);
421
- signals.off("SIGTERM", onSigterm);
422
- signals.off("SIGHUP", onSighup);
423
- };
424
- const onSignal = (signal) => {
425
- if (!remote) return;
426
- if (terminationStarted) {
427
- removeSignalListeners();
428
- forceExit(signal);
429
- return;
430
- }
431
- terminationStarted = true;
432
- remote.kill().then(() => resolveTermination({
433
- status: "cancelled",
434
- exitReason: "terminated by local signal",
435
- stdout: remote?.stdout ?? "",
436
- stderr: remote?.stderr ?? ""
437
- }), (error) => rejectTermination(error instanceof Error ? error : new Error(String(error))));
438
- };
439
- const onSigint = () => onSignal("SIGINT");
440
- const onSigterm = () => onSignal("SIGTERM");
441
- const onSighup = () => onSignal("SIGHUP");
442
- try {
443
- const shellCommand = command.map((argument) => argument === "" ? "''" : `'${argument.replaceAll("'", `'"'"'`)}'`).join(" ");
444
- remote = await sandbox.run(shellCommand, {
445
- ...runOptions,
446
- collectOutput: options.output === "json"
447
- });
448
- try {
449
- await remote.closeStdin();
450
- } catch (error) {
451
- if (remote.status === "running") throw error;
452
- }
453
- signals.on("SIGINT", onSigint);
454
- signals.on("SIGTERM", onSigterm);
455
- signals.on("SIGHUP", onSighup);
456
- const streaming = options.output === "json" ? Promise.resolve() : (async () => {
457
- for await (const { stream, data } of remote.output) {
458
- if (stream === "stderr" && data.length) receivedStderr = true;
459
- await writeOutput(stream === "stdout" ? stdout : stderr, data);
460
- }
461
- })();
462
- result = await Promise.race([streaming.then(() => remote.wait()), termination]);
463
- if (options.output === "json") output(JSON.stringify(result, null, 2));
464
- else if (result.status !== "completed" && !receivedStderr) {
465
- let diagnostic;
466
- if (result.status === "timed_out") diagnostic = `Process timed out${runOptions.timeoutSeconds === void 0 ? "" : ` after ${runOptions.timeoutSeconds} second${runOptions.timeoutSeconds === 1 ? "" : "s"}`}`;
467
- else if (result.status === "failed") diagnostic = `Process failed${result.exitCode === void 0 ? "" : ` with exit code ${result.exitCode}`}`;
468
- else diagnostic = "Process cancelled";
469
- stderr.write(`${diagnostic}${result.exitReason ? `: ${result.exitReason}` : ""}\n`);
470
- }
471
- setExitCode(resultExitCode(result));
472
- } finally {
473
- removeSignalListeners();
474
- if (remote && !result && !terminationStarted) await remote.kill().catch(() => {});
475
- await remote?.disconnect().catch(() => {});
476
- await sandbox.processes.disconnect();
477
- }
478
- });
479
- formatOption(program.command("shell <id|name>").description("Open an interactive shell in a running sandbox")).action(async (target, options) => {
480
- const sandbox = await resolveSandbox(requireService(), target);
481
- if (sandbox.status !== "running") throw new Error(`Cannot open a shell in sandbox '${sandbox.name}' while it is ${sandbox.status}`);
482
- const shellOutput = options.output === "json" ? stderr : stdout;
483
- const result = await runSandboxShell({
484
- sandbox,
485
- stdin,
486
- stdout: shellOutput,
487
- stderr,
488
- signals,
489
- forceExit
490
- });
491
- if (options.output === "json") output(JSON.stringify(result, null, 2));
492
- setExitCode(resultExitCode(result));
493
- });
494
- return program;
495
- }
496
- //#endregion
497
6
  //#region bin/sandbox-cli.ts
498
7
  const pkg = createRequire(import.meta.url)("../package.json");
499
8
  function fail(error) {
500
- if (error instanceof ArchilApiError) console.error(`Error (${error.status}): ${error.message}`);
501
- else console.error(error instanceof Error ? error.message : String(error));
9
+ printError(error, process.stderr, "sandbox", { legacy: true });
502
10
  process.exit(1);
503
11
  }
504
12
  createSandboxProgram({