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