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,591 @@
1
+ #!/usr/bin/env node
2
+ import { p as Archil } from "./src-BFPiWUCL.mjs";
3
+ import { C as printError, _ as writeProfileCredential, a as addGlobalOptions, d as saveProfiles, g as resolveCliCredentials, l as deleteProfile, m as deleteProfileCredential, o as addProfileCommands, p as validateCredentialAndResolveRegion, u as loadProfiles, v as diskConfigDir, x as createUi, y as Command } from "./sandbox-options-AO9jKF4-.mjs";
4
+ import { n as rewriteDiskExecSugar, t as addDiskCommands } from "./disk-command-CvRVHqnG.mjs";
5
+ import { r as openInBrowser, t as addSandboxCommands } from "./sandbox-command-DJZqMVHm.mjs";
6
+ import { createRequire } from "node:module";
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import { delimiter, join } from "node:path";
9
+ import { hostname } from "node:os";
10
+ import { spawn } from "node:child_process";
11
+ import { fileURLToPath } from "node:url";
12
+ import { accessSync, closeSync, constants, openSync, readSync, realpathSync } from "node:fs";
13
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
14
+ import { createServer } from "node:http";
15
+ const MAX_CALLBACK_BYTES = 16 * 1024;
16
+ const LOGIN_TIMEOUT_MS = 600 * 1e3;
17
+ var LoginDeniedError = class extends Error {};
18
+ function consoleUrl(env = process.env) {
19
+ return (env.ARCHIL_CONSOLE_URL ?? "https://console.archil.com").replace(/\/+$/, "");
20
+ }
21
+ /** Starts the loopback listener and returns the URL the user should open. */
22
+ async function startLoginSession(options = {}) {
23
+ const base = options.console ?? consoleUrl();
24
+ const state = randomBytes(32).toString("hex");
25
+ let settle;
26
+ const grant = new Promise((resolve, reject) => {
27
+ settle = {
28
+ resolve,
29
+ reject
30
+ };
31
+ });
32
+ grant.catch(() => {});
33
+ let finished = false;
34
+ const finish = (outcome) => {
35
+ if (finished) return;
36
+ finished = true;
37
+ clearTimeout(timer);
38
+ setTimeout(() => server.close(), 100).unref();
39
+ if (outcome.grant) settle.resolve(outcome.grant);
40
+ else settle.reject(outcome.error);
41
+ };
42
+ const server = createServer((request, response) => {
43
+ handleCallback(request, response, state, base).then((outcome) => {
44
+ if (outcome) finish(outcome);
45
+ }, () => respond(response, 400, page("Something went wrong", "The CLI couldn't read the sign-in response. Run archil login again.")));
46
+ });
47
+ await new Promise((resolve, reject) => {
48
+ server.once("error", reject);
49
+ server.listen(0, "127.0.0.1", () => resolve());
50
+ });
51
+ const timer = setTimeout(() => finish({ error: /* @__PURE__ */ new Error("Timed out waiting for the browser; run archil login again") }), options.timeoutMs ?? LOGIN_TIMEOUT_MS);
52
+ timer.unref();
53
+ const port = server.address().port;
54
+ return {
55
+ url: `${base}/cli/login?${new URLSearchParams({
56
+ port: String(port),
57
+ state,
58
+ hostname: options.machine ?? hostname()
59
+ })}`,
60
+ grant,
61
+ close: () => finish({ error: /* @__PURE__ */ new Error("Login cancelled") })
62
+ };
63
+ }
64
+ async function handleCallback(request, response, state, consoleBase) {
65
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
66
+ if (request.method !== "POST" || url.pathname !== "/callback") {
67
+ respond(response, 404, page("Not found", "This address only receives Archil CLI sign-ins."));
68
+ return;
69
+ }
70
+ const origin = request.headers.origin;
71
+ if (origin && origin !== new URL(consoleBase).origin) {
72
+ respond(response, 403, page("Not allowed", "This sign-in didn't come from the Archil console."));
73
+ return;
74
+ }
75
+ const fields = new URLSearchParams(await readBody(request));
76
+ if (!sameSecret(fields.get("state") ?? "", state)) {
77
+ respond(response, 400, page("Sign-in link expired", "This page doesn't match the sign-in your terminal started. Run archil login again."));
78
+ return;
79
+ }
80
+ if (fields.get("error")) {
81
+ respond(response, 200, page("Sign-in cancelled", "No key was created. You can close this tab."));
82
+ return { error: new LoginDeniedError("Sign-in was cancelled in the browser") };
83
+ }
84
+ const apiKey = fields.get("apiKey");
85
+ const region = fields.get("region");
86
+ if (!apiKey || !region) {
87
+ respond(response, 400, page("Something went wrong", "The console didn't send a key. Run archil login again."));
88
+ return { error: /* @__PURE__ */ new Error("The console didn't send an API key") };
89
+ }
90
+ const account = fields.get("account");
91
+ respond(response, 200, page("You're signed in", `${account ? `The CLI is now signed in to ${account}. ` : ""}Return to your terminal; you can close this tab.`, true));
92
+ return { grant: {
93
+ apiKey,
94
+ region,
95
+ baseUrl: fields.get("baseUrl") || void 0,
96
+ keyId: fields.get("keyId") || void 0,
97
+ account: fields.get("account") || void 0
98
+ } };
99
+ }
100
+ function sameSecret(given, expected) {
101
+ const a = Buffer.from(given);
102
+ const b = Buffer.from(expected);
103
+ return a.length === b.length && timingSafeEqual(a, b);
104
+ }
105
+ function readBody(request) {
106
+ return new Promise((resolve, reject) => {
107
+ let size = 0;
108
+ const chunks = [];
109
+ request.on("data", (chunk) => {
110
+ size += chunk.length;
111
+ if (size > MAX_CALLBACK_BYTES) {
112
+ reject(/* @__PURE__ */ new Error("callback too large"));
113
+ request.destroy();
114
+ return;
115
+ }
116
+ chunks.push(chunk);
117
+ });
118
+ request.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
119
+ request.on("error", reject);
120
+ });
121
+ }
122
+ function respond(response, status, html) {
123
+ response.writeHead(status, {
124
+ "Content-Type": "text/html; charset=utf-8",
125
+ "Cache-Control": "no-store",
126
+ "Referrer-Policy": "no-referrer"
127
+ });
128
+ response.end(html);
129
+ }
130
+ function escapeHtml(text) {
131
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
132
+ }
133
+ const LOGO = `<svg viewBox="0 0 64 64" width="28" height="28" fill="none" aria-hidden="true"><rect x="1.82" y="1.82" width="60.36" height="60.36" stroke="currentColor" stroke-width="2"/><path transform="translate(-115.998 -166.784)" d="M172.376 222.438L169.116 222.447V207.734C169.116 206.191 167.865 204.939 166.321 204.938H156.427C155.042 204.939 153.762 205.677 153.067 206.876L144.003 222.525L123.625 222.59L150.84 175.562L172.376 175.41V222.438ZM168.961 184.194C168.961 182.71 167.017 182.155 166.233 183.415L156.512 199.038C155.836 200.124 156.617 201.53 157.896 201.53H166.088C167.675 201.53 168.961 200.244 168.961 198.657V184.194Z" fill="currentColor"/></svg>`;
134
+ function page(title, message, success = false) {
135
+ return `<!doctype html>
136
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
137
+ <title>${escapeHtml(title)} · Archil CLI</title>
138
+ <style>
139
+ :root { color-scheme: light dark; --bg: #fafafa; --fg: #111; --muted: #666; --card: #fff; --border: #e5e5e5; --ok: #16a34a; }
140
+ @media (prefers-color-scheme: dark) { :root { --bg: #0a0a0a; --fg: #ededed; --muted: #a1a1a1; --card: #141414; --border: #262626; --ok: #22c55e; } }
141
+ * { box-sizing: border-box; }
142
+ body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: var(--bg); color: var(--fg); font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased; }
143
+ header { padding: 32px 32px 16px; display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500; letter-spacing: -0.01em; }
144
+ main { flex: 1; display: flex; justify-content: center; padding: 48px 20px 96px; }
145
+ section { width: min(560px, 100%); }
146
+ .mark { width: 40px; height: 40px; border-radius: 999px; display: grid; place-items: center; margin-bottom: 24px; background: ${success ? "color-mix(in srgb, var(--ok) 14%, transparent)" : "color-mix(in srgb, var(--muted) 14%, transparent)"}; color: ${success ? "var(--ok)" : "var(--muted)"}; font-size: 20px; }
147
+ h1 { margin: 0 0 6px; font-size: 24px; font-weight: 600; letter-spacing: -0.02em; line-height: 1.15; }
148
+ p { margin: 0; color: var(--muted); font-size: 13px; }
149
+ </style></head>
150
+ <body><header>${LOGO}<span>ARCHIL</span></header>
151
+ <main><section><div class="mark">${success ? "✓" : "!"}</div><h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p></section></main></body></html>`;
152
+ }
153
+ //#endregion
154
+ //#region src/cli/completion.ts
155
+ /** Mount commands the native client handles; suggested at the top level. */
156
+ const NATIVE_COMMANDS = [
157
+ "mount",
158
+ "unmount",
159
+ "status"
160
+ ];
161
+ const SANDBOX_NAME_CACHE_MS = 15e3;
162
+ function findOption(chain, word) {
163
+ const long = word.startsWith("--") ? word.slice(2).split("=")[0] : void 0;
164
+ for (const command of [...chain].reverse()) {
165
+ const option = command.optionList().find((candidate) => long !== void 0 ? candidate.long === long : candidate.short === word.slice(1));
166
+ if (option) return option;
167
+ }
168
+ }
169
+ /**
170
+ * Candidates for the last word in `words` (everything after the program name;
171
+ * the last entry is the partial word being completed, possibly empty).
172
+ */
173
+ async function completeWords(root, words, lookup) {
174
+ const chain = [root];
175
+ const operands = [];
176
+ const done = words.slice(0, -1);
177
+ const current = words.at(-1) ?? "";
178
+ let pendingOption;
179
+ let afterSeparator = false;
180
+ for (const word of done) {
181
+ if (pendingOption) {
182
+ pendingOption = void 0;
183
+ continue;
184
+ }
185
+ if (afterSeparator) {
186
+ operands.push(word);
187
+ continue;
188
+ }
189
+ if (word === "--") {
190
+ afterSeparator = true;
191
+ continue;
192
+ }
193
+ if (word.startsWith("-") && word.length > 1) {
194
+ const option = findOption(chain, word);
195
+ if (option?.takesValue && !word.includes("=")) pendingOption = option;
196
+ continue;
197
+ }
198
+ const command = chain.at(-1);
199
+ const subcommand = operands.length === 0 ? command.commands.find((candidate) => candidate.name() === word) : void 0;
200
+ if (subcommand) chain.push(subcommand);
201
+ else operands.push(word);
202
+ }
203
+ const command = chain.at(-1);
204
+ const matching = (candidates) => candidates.filter((candidate) => candidate.startsWith(current)).sort();
205
+ if (pendingOption) {
206
+ if (pendingOption.long === "output") return matching(["table", "json"]);
207
+ if (pendingOption.long === "profile") return matching(await lookup("profiles"));
208
+ return [];
209
+ }
210
+ if (!afterSeparator && current.startsWith("-")) {
211
+ const options = chain.flatMap((owner) => owner.optionList()).map((option) => `--${option.long}`);
212
+ return matching([.../* @__PURE__ */ new Set([...options, "--help"])]);
213
+ }
214
+ if (!afterSeparator && command.commands.length > 0 && operands.length === 0) return matching([...command.commands.map((candidate) => candidate.name()).filter((name) => !name.startsWith("__") && name !== "ssh-proxy"), ...command === root ? NATIVE_COMMANDS : []]);
215
+ const argument = command.argumentList()[operands.length] ?? command.argumentList().at(-1);
216
+ const insideSandbox = chain.some((owner) => owner.name() === "sandbox");
217
+ if (argument?.name === "id|name" && insideSandbox && operands.length === 0) return matching(await lookup("sandboxes"));
218
+ return [];
219
+ }
220
+ const GLOBAL_OPTION_NAMES = {
221
+ "-k": "apiKey",
222
+ "--api-key": "apiKey",
223
+ "-r": "region",
224
+ "--region": "region",
225
+ "--base-url": "baseUrl",
226
+ "--profile": "profile"
227
+ };
228
+ /** Global credential options typed on the command line being completed, so lookups use the same account. */
229
+ function credentialOptions(words) {
230
+ const options = {};
231
+ for (let index = 0; index < words.length; index++) {
232
+ const word = words[index];
233
+ if (word === "--") break;
234
+ const [flag, inline] = word.includes("=") ? [word.slice(0, word.indexOf("=")), word.slice(word.indexOf("=") + 1)] : [word, void 0];
235
+ const key = GLOBAL_OPTION_NAMES[flag];
236
+ if (!key) continue;
237
+ const value = inline ?? words[index + 1];
238
+ if (inline === void 0) index++;
239
+ if (value) options[key] = value;
240
+ }
241
+ return options;
242
+ }
243
+ /**
244
+ * Sandbox names for completion, cached briefly so repeated tabs don't hit the
245
+ * API. The cache is keyed by account (`cacheKey`) so switching profiles never
246
+ * suggests another account's sandboxes.
247
+ */
248
+ async function cachedSandboxNames(cacheKey, list, now = Date.now()) {
249
+ const path = join(diskConfigDir(), "completion-cache.json");
250
+ try {
251
+ const cached = JSON.parse(await readFile(path, "utf8"));
252
+ if (cached.key === cacheKey && now - cached.at < SANDBOX_NAME_CACHE_MS) return cached.sandboxes;
253
+ } catch {}
254
+ const sandboxes = [...new Set(await list())];
255
+ await mkdir(diskConfigDir(), { recursive: true }).catch(() => {});
256
+ await writeFile(path, JSON.stringify({
257
+ key: cacheKey,
258
+ at: now,
259
+ sandboxes
260
+ }), { mode: 384 }).catch(() => {});
261
+ return sandboxes;
262
+ }
263
+ function completionScript(shell, name = "archil") {
264
+ switch (shell) {
265
+ case "bash": return `# ${name} completion for bash. Add to ~/.bashrc: source <(${name} completion bash)
266
+ _${name}_complete() {
267
+ local IFS=$'\\n'
268
+ COMPREPLY=($(${name} __complete "\${COMP_WORDS[@]:1:$COMP_CWORD}" 2>/dev/null))
269
+ }
270
+ complete -o default -F _${name}_complete ${name}
271
+ `;
272
+ case "zsh": return `#compdef ${name}
273
+ # ${name} completion for zsh. Add to ~/.zshrc: source <(${name} completion zsh)
274
+ _${name}() {
275
+ local -a candidates
276
+ candidates=("\${(@f)$(${name} __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)}")
277
+ compadd -- \${candidates:#}
278
+ }
279
+ if [ "$funcstack[1]" = "_${name}" ]; then _${name} "$@"; else compdef _${name} ${name}; fi
280
+ `;
281
+ case "fish": return `# ${name} completion for fish. Save to ~/.config/fish/completions/${name}.fish
282
+ complete -c ${name} -f -a '(${name} __complete (commandline -opc)[2..-1] (commandline -ct))'
283
+ `;
284
+ default: throw new Error(`Unsupported shell '${shell}'; use bash, zsh, or fish`);
285
+ }
286
+ }
287
+ //#endregion
288
+ //#region src/cli/archil-command.ts
289
+ const OWN_COMMANDS = /* @__PURE__ */ new Set([
290
+ "disk",
291
+ "sandbox",
292
+ "profile",
293
+ "login",
294
+ "logout",
295
+ "whoami",
296
+ "completion",
297
+ "help",
298
+ "__complete"
299
+ ]);
300
+ const GLOBAL_OPTIONS_WITH_VALUES = /* @__PURE__ */ new Set([
301
+ "-k",
302
+ "--api-key",
303
+ "-r",
304
+ "--region",
305
+ "--base-url",
306
+ "--profile"
307
+ ]);
308
+ const SKIP_ENV = "ARCHIL_CLI_FORWARD_SKIP";
309
+ const NATIVE_CLIENT_INSTALL = "curl https://archil.com/install | sh";
310
+ function createArchilProgram(dependencies) {
311
+ const program = new Command().name("archil").description("Manage Archil disks and sandboxes").version(dependencies.version).addHelpText("after", `
312
+ Mount commands (mount, unmount, status, checkout, ...) belong to the Archil
313
+ client and are passed through to it. Install it with:
314
+ ${NATIVE_CLIENT_INSTALL}
315
+ `);
316
+ addGlobalOptions(program);
317
+ addAccountCommands(program, dependencies);
318
+ addProfileCommands(program, dependencies.validateCredential);
319
+ addDiskCommands(program.command("disk").description("Create, inspect, and run commands against disks"), program);
320
+ addSandboxCommands(program.command("sandbox").description("Create and manage persistent sandboxes"), program, dependencies);
321
+ program.command("completion <shell>").description("Print a shell completion script: bash, zsh, or fish").addHelpText("after", `
322
+ source <(archil completion zsh) # add to ~/.zshrc
323
+ source <(archil completion bash) # add to ~/.bashrc
324
+ archil completion fish > ~/.config/fish/completions/archil.fish
325
+ `).action((shell) => {
326
+ (dependencies.stdout ?? process.stdout).write(completionScript(shell));
327
+ });
328
+ return program;
329
+ }
330
+ /** Index in `args` (argv without node and script) of the first command word, skipping global options and their values. */
331
+ function firstCommandIndex(args) {
332
+ for (let index = 0; index < args.length; index++) {
333
+ const token = args[index];
334
+ if (token === "--") return index + 1 < args.length ? index + 1 : -1;
335
+ if (GLOBAL_OPTIONS_WITH_VALUES.has(token)) {
336
+ index++;
337
+ continue;
338
+ }
339
+ if (!token.startsWith("-")) return index;
340
+ }
341
+ return -1;
342
+ }
343
+ function firstCommand(args) {
344
+ const index = firstCommandIndex(args);
345
+ return index === -1 ? void 0 : args[index];
346
+ }
347
+ /** Whether `args` should go to the native client instead of this CLI. */
348
+ function isNativeCommand(args) {
349
+ const command = firstCommand(args);
350
+ return command !== void 0 && !OWN_COMMANDS.has(command);
351
+ }
352
+ /**
353
+ * Finds the native `archil` on PATH. It skips this CLI, other npm copies of it
354
+ * (node scripts or symlinks to them), and every binary an earlier hop already
355
+ * tried. Package managers also install this CLI behind wrappers that don't look
356
+ * like node (pnpm's sh shims, Volta and asdf binaries); if one of those is
357
+ * picked, it lands back here, skips itself via SKIP_ENV, and moves on.
358
+ */
359
+ function findNativeClient(env, selfPath) {
360
+ const skip = /* @__PURE__ */ new Set([safeRealpath(selfPath), ...skippedPaths(env)]);
361
+ const names = process.platform === "win32" ? ["archil.exe"] : ["archil"];
362
+ for (const directory of (env.PATH ?? "").split(delimiter)) {
363
+ if (!directory) continue;
364
+ for (const name of names) {
365
+ const candidate = join(directory, name);
366
+ try {
367
+ accessSync(candidate, constants.X_OK);
368
+ } catch {
369
+ continue;
370
+ }
371
+ const resolved = safeRealpath(candidate);
372
+ if (skip.has(resolved) || isNodeScript(resolved)) continue;
373
+ return candidate;
374
+ }
375
+ }
376
+ }
377
+ function skippedPaths(env) {
378
+ return (env[SKIP_ENV] ?? "").split(delimiter).filter(Boolean).map(safeRealpath);
379
+ }
380
+ /** Runs the native client with `args` and resolves to the exit code to use. */
381
+ async function forwardToNativeClient(args, env, selfPath) {
382
+ const command = firstCommand(args);
383
+ const native = findNativeClient(env, selfPath);
384
+ if (!native) throw new Error(`'archil ${command}' is a command of the Archil client, which isn't installed. Install it with:\n ${NATIVE_CLIENT_INSTALL}`);
385
+ const skip = [
386
+ ...skippedPaths(env),
387
+ safeRealpath(selfPath),
388
+ safeRealpath(native)
389
+ ].join(delimiter);
390
+ const ignore = () => {};
391
+ const signals = [
392
+ "SIGINT",
393
+ "SIGTERM",
394
+ "SIGHUP"
395
+ ];
396
+ for (const signal of signals) process.on(signal, ignore);
397
+ try {
398
+ return await new Promise((resolve, reject) => {
399
+ const child = spawn(native, args, {
400
+ stdio: "inherit",
401
+ env: {
402
+ ...env,
403
+ [SKIP_ENV]: skip
404
+ }
405
+ });
406
+ child.on("error", reject);
407
+ child.on("exit", (code, signal) => resolve(code ?? (signal ? 128 + (signalNumber(signal) ?? 1) : 1)));
408
+ });
409
+ } finally {
410
+ for (const signal of signals) process.off(signal, ignore);
411
+ }
412
+ }
413
+ function signalNumber(signal) {
414
+ return {
415
+ SIGHUP: 1,
416
+ SIGINT: 2,
417
+ SIGKILL: 9,
418
+ SIGTERM: 15
419
+ }[signal];
420
+ }
421
+ function safeRealpath(path) {
422
+ try {
423
+ return realpathSync(path);
424
+ } catch {
425
+ return path;
426
+ }
427
+ }
428
+ function isNodeScript(path) {
429
+ let fd;
430
+ try {
431
+ fd = openSync(path, "r");
432
+ const head = Buffer.alloc(128);
433
+ const length = readSync(fd, head, 0, head.length, 0);
434
+ const firstLine = head.subarray(0, length).toString().split("\n")[0];
435
+ return firstLine.startsWith("#!") && firstLine.includes("node");
436
+ } catch {
437
+ return false;
438
+ } finally {
439
+ if (fd !== void 0) closeSync(fd);
440
+ }
441
+ }
442
+ /**
443
+ * Where `archil login` saves a key when no --profile is given: replace the
444
+ * profile an earlier login made for this endpoint, otherwise use the region's
445
+ * name, and never overwrite a profile someone created by hand.
446
+ */
447
+ function loginProfileName(profiles, region, baseUrl, account, requested) {
448
+ if (requested !== void 0) {
449
+ const existing = profiles[requested];
450
+ if (existing && existing.apiKeyId === void 0) throw new Error(`Profile '${requested}' already exists and wasn't created by 'archil login'; pick another name with --profile, or delete it with 'archil profile delete ${requested}'`);
451
+ return requested;
452
+ }
453
+ const previousLogin = Object.entries(profiles).find(([, profile]) => profile.apiKeyId !== void 0 && profile.region === region && profile.baseUrl === baseUrl && profile.account === account);
454
+ if (previousLogin) return previousLogin[0];
455
+ let name = region;
456
+ for (let suffix = 2; profiles[name]; suffix++) name = `${region}-${suffix}`;
457
+ return name;
458
+ }
459
+ function addAccountCommands(program, dependencies) {
460
+ const stderr = dependencies.stderr ?? process.stderr;
461
+ const signals = dependencies.signals ?? process;
462
+ const ui = createUi(stderr);
463
+ const { style } = ui;
464
+ const validate = dependencies.validateCredential ?? validateCredentialAndResolveRegion;
465
+ program.command("login").description("Sign in through your browser and save the key as a profile").option("--no-browser", "Print the sign-in link instead of opening a browser").addHelpText("after", `
466
+ Opens the Archil console, where you approve access for this machine. The
467
+ console creates an API key named "CLI on <hostname>" and hands it back to this
468
+ command, which saves it as a profile (named after its region unless you pass
469
+ --profile) and makes that profile the default.
470
+
471
+ Without a browser on this machine (CI, a remote shell), create a key in the
472
+ console and run 'archil profile create', or set ARCHIL_API_KEY and ARCHIL_REGION.
473
+ `).action(async (options) => {
474
+ const global = program.opts();
475
+ const session = await startLoginSession();
476
+ const cancel = () => session.close();
477
+ signals.once("SIGINT", cancel);
478
+ try {
479
+ if (options.browser) {
480
+ (dependencies.openUrl ?? openInBrowser)(session.url);
481
+ ui.info("Opened the Archil console in your browser to approve this sign-in.");
482
+ ui.details([["Link", style.dim(session.url)]]);
483
+ } else {
484
+ ui.info("Open this link in a browser on this machine to approve the sign-in:");
485
+ stderr.write(`\n ${style.cyan(style.underline(session.url))}\n\n`);
486
+ }
487
+ const grant = await ui.step("Waiting for approval in the browser", () => session.grant, "Approved in the browser").catch((error) => {
488
+ if (error instanceof LoginDeniedError) throw new Error("Sign-in was cancelled in the browser; nothing was saved");
489
+ throw error;
490
+ });
491
+ const region = await ui.step("Checking the new key", () => validate({
492
+ apiKey: grant.apiKey,
493
+ region: grant.region,
494
+ baseUrl: grant.baseUrl
495
+ }), "Key works");
496
+ const config = await loadProfiles();
497
+ const name = loginProfileName(config.profiles, region, grant.baseUrl, grant.account, global.profile);
498
+ await writeProfileCredential(name, grant.apiKey);
499
+ config.profiles[name] = {
500
+ region,
501
+ baseUrl: grant.baseUrl,
502
+ apiKeyId: grant.keyId,
503
+ account: grant.account
504
+ };
505
+ config.currentProfile = name;
506
+ await saveProfiles(config);
507
+ const where = name === region ? "" : `, ${region}`;
508
+ ui.success(`Signed in${grant.account ? ` to ${style.bold(grant.account)}` : ""} as profile ${style.bold(name)} ${style.dim(`(now the default${where})`)}`);
509
+ ui.blank();
510
+ ui.details([["Try", "archil sandbox create my-desk --desktop"], ["", "archil sandbox list"]]);
511
+ } finally {
512
+ signals.off("SIGINT", cancel);
513
+ session.close();
514
+ }
515
+ });
516
+ program.command("logout").description("Delete the current profile and its saved key from this machine").action(async () => {
517
+ const global = program.opts();
518
+ const config = await loadProfiles();
519
+ const name = global.profile ?? process.env.ARCHIL_PROFILE ?? config.currentProfile;
520
+ const profile = name ? config.profiles[name] : void 0;
521
+ if (!name || !profile) ui.info("No profile is signed in.");
522
+ else {
523
+ await deleteProfileCredential(name);
524
+ await deleteProfile(name);
525
+ ui.success(`Signed out of ${style.bold(name)}; its key is no longer saved on this machine`);
526
+ if (profile.apiKeyId) ui.info(`The key still works until you revoke it: ${style.cyan(style.underline(`${consoleUrl()}/api-keys`))}`);
527
+ }
528
+ if (process.env.ARCHIL_API_KEY) ui.warn("ARCHIL_API_KEY is still set in your environment, so commands keep using it.");
529
+ });
530
+ program.command("whoami").description("Show which account and profile commands use, and check the credentials").action(async () => {
531
+ const global = program.opts();
532
+ const config = await loadProfiles();
533
+ const credentials = await resolveCliCredentials(global, config);
534
+ const profile = credentials.profile ? config.profiles[credentials.profile] : void 0;
535
+ const fromEnvironment = Boolean(global.apiKey ?? process.env.ARCHIL_API_KEY);
536
+ await ui.step("Checking credentials", () => validate(credentials), "Credentials work");
537
+ ui.blank();
538
+ ui.details([
539
+ ...profile?.account ? [["Account", style.bold(profile.account)]] : [],
540
+ ["Profile", fromEnvironment ? style.dim("none (ARCHIL_API_KEY)") : credentials.profile ?? style.dim("none")],
541
+ ["Region", credentials.region],
542
+ ...credentials.baseUrl ? [["Endpoint", credentials.baseUrl]] : [],
543
+ ["Key", `…${credentials.apiKey.slice(-4)}`]
544
+ ]);
545
+ });
546
+ }
547
+ //#endregion
548
+ //#region bin/archil-cli.ts
549
+ const pkg = createRequire(import.meta.url)("../package.json");
550
+ function fail(error) {
551
+ printError(error, process.stderr, "archil");
552
+ process.exit(1);
553
+ }
554
+ async function main(argv) {
555
+ const args = argv.slice(2);
556
+ if (isNativeCommand(args)) {
557
+ process.exitCode = await forwardToNativeClient(args, process.env, process.argv[1] ?? fileURLToPath(import.meta.url));
558
+ return;
559
+ }
560
+ const program = createArchilProgram({
561
+ version: pkg.version,
562
+ createClient: (options) => new Archil(options)
563
+ });
564
+ if (args[0] === "__complete") {
565
+ const words = args.slice(1);
566
+ const credentials = credentialOptions(words);
567
+ const candidates = await completeWords(program, words, (source) => completionLookup(source, credentials)).catch(() => []);
568
+ process.stdout.write(candidates.length > 0 ? `${candidates.join("\n")}\n` : "", () => process.exit(0));
569
+ return;
570
+ }
571
+ const commandIndex = firstCommandIndex(args);
572
+ const isDisk = commandIndex !== -1 && args[commandIndex] === "disk";
573
+ await program.parseAsync(isDisk ? rewriteDiskExecSugar(argv, commandIndex + 3) : argv);
574
+ }
575
+ async function completionLookup(source, options) {
576
+ const profiles = await loadProfiles();
577
+ if (source === "profiles") return Object.keys(profiles.profiles);
578
+ const credentials = await resolveCliCredentials(options, profiles);
579
+ return cachedSandboxNames(createHash("sha256").update([
580
+ credentials.apiKey,
581
+ credentials.region,
582
+ credentials.baseUrl ?? ""
583
+ ].join("\n")).digest("hex"), async () => {
584
+ const listing = new Archil(credentials).sandboxes.list();
585
+ const timeout = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("timed out")), 3e3).unref());
586
+ return (await Promise.race([listing, timeout])).map((sandbox) => sandbox.name);
587
+ });
588
+ }
589
+ main(process.argv).catch(fail);
590
+ //#endregion
591
+ export {};