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
package/README.md
CHANGED
|
@@ -39,6 +39,37 @@ npx disk api-keys delete key-abc123
|
|
|
39
39
|
|
|
40
40
|
`list` and `get` pretty-print tables by default; pass `-o json` to pipe into `jq`. Credentials come from `ARCHIL_API_KEY` / `ARCHIL_REGION`, or `--api-key` / `--region` / `--base-url` flags.
|
|
41
41
|
|
|
42
|
+
### Profiles
|
|
43
|
+
|
|
44
|
+
`disk` and `sandbox` share named profiles:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx disk profile create --profile test-yellow --region aws-us-east-1
|
|
48
|
+
npx sandbox profile use test-yellow
|
|
49
|
+
npx sandbox list
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`profile create` securely prompts for the API key. Flags override environment variables, which override the selected profile. The library API does not read profiles.
|
|
53
|
+
|
|
54
|
+
### Sandbox CLI
|
|
55
|
+
|
|
56
|
+
The `sandbox` executable manages persistent sandboxes:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npx sandbox list
|
|
60
|
+
npx sandbox create dev --vcpu-count 4 --mem-size-mib 8192 --env NODE_ENV=development
|
|
61
|
+
npx sandbox pause dev
|
|
62
|
+
npx sandbox resume dev --no-wait
|
|
63
|
+
npx sandbox wait dev --status running --timeout 60
|
|
64
|
+
npx sandbox fork dev agent-task
|
|
65
|
+
npx sandbox run dev -- sh -c 'echo "$NODE_ENV"'
|
|
66
|
+
npx sandbox shell dev
|
|
67
|
+
npx sandbox stop dev
|
|
68
|
+
npx sandbox delete dev
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Commands accept an exact ID or unique name. Lifecycle commands wait by default; use `--no-wait` to return once accepted. Use `-o json` for structured output. Starting a paused sandbox discards its memory snapshot and prompts unless `--yes` is passed. In a shell, `Ctrl+]` is the emergency escape.
|
|
72
|
+
|
|
42
73
|
## Library
|
|
43
74
|
|
|
44
75
|
Setup:
|
|
@@ -92,15 +123,27 @@ const sandbox = await client.sandboxes.create({
|
|
|
92
123
|
const result = await sandbox.exec("uname -a");
|
|
93
124
|
console.log(result.stdout);
|
|
94
125
|
|
|
126
|
+
const terminal = await sandbox.processes.start("codex", {
|
|
127
|
+
terminal: { cols: 120, rows: 40 },
|
|
128
|
+
onOutput: ({ data }) => process.stdout.write(data),
|
|
129
|
+
});
|
|
130
|
+
const processId = terminal.id;
|
|
131
|
+
await terminal.sendInput("Review this repository\n");
|
|
132
|
+
await terminal.resize({ cols: 160, rows: 50 });
|
|
133
|
+
const cursor = terminal.cursor;
|
|
134
|
+
await terminal.disconnect();
|
|
135
|
+
|
|
136
|
+
const resumed = await sandbox.processes.connect(processId, {
|
|
137
|
+
offset: cursor,
|
|
138
|
+
onOutput: ({ data }) => process.stdout.write(data),
|
|
139
|
+
});
|
|
140
|
+
await resumed.kill();
|
|
141
|
+
|
|
95
142
|
await sandbox.start();
|
|
96
143
|
await sandbox.resume();
|
|
97
144
|
|
|
98
|
-
// Return the initial state immediately instead of waiting for completion.
|
|
99
|
-
const runningExec = await sandbox.exec("sleep 60", { wait: false });
|
|
100
|
-
|
|
101
145
|
await sandbox.stop();
|
|
102
146
|
const fork = await sandbox.fork({ name: "agent-task" });
|
|
103
|
-
const connection = await fork.createConnection();
|
|
104
147
|
await fork.stop();
|
|
105
148
|
await fork.delete();
|
|
106
149
|
|
|
@@ -111,10 +154,48 @@ const usingDisk = await client.sandboxes.list({ disk: "dsk-abc123" });
|
|
|
111
154
|
Sandboxes support 1–32 vCPUs and 256–65,536 MiB of memory. When omitted,
|
|
112
155
|
`vcpuCount` defaults to 1 and `memSizeMiB` defaults to 2,048 MiB.
|
|
113
156
|
|
|
114
|
-
`
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
157
|
+
`sandbox.processes.start()` always returns a runtime-owned process immediately.
|
|
158
|
+
Pass `terminal: true` when the command needs terminal behavior, or provide
|
|
159
|
+
`{ cols, rows }` for an initial size. Terminal processes merge stdout and stderr
|
|
160
|
+
into `stdout`; non-terminal processes keep the streams separate. Disconnecting
|
|
161
|
+
leaves the process running. Reconnect with `sandbox.processes.connect(id)` to
|
|
162
|
+
replay buffered output from the beginning, or pass `{ offset: process.cursor }`
|
|
163
|
+
to continue where the previous connection stopped. `onOutput` receives raw
|
|
164
|
+
bytes with their stream and absolute offset. Call `closeStdin()` to deliver EOF
|
|
165
|
+
to a non-terminal process. `sendInput()` streams large input as 1 MiB WebSocket
|
|
166
|
+
frames. Set `collectOutput: false` to stream through `onOutput` without
|
|
167
|
+
retaining decoded output in the process handle or result. Resize and kill use
|
|
168
|
+
separate one-shot process controls, so they do not wait behind stdin.
|
|
169
|
+
`kill()` returns after the control is acknowledged; `wait()` observes exit.
|
|
170
|
+
`maxConcurrentExecs` limits attached process sessions; detached processes and
|
|
171
|
+
one-shot controls do not count. Pausing a sandbox disconnects attachments but
|
|
172
|
+
preserves its processes for reattachment after resume. Processes end when
|
|
173
|
+
their sandbox is stopped or expires.
|
|
174
|
+
`sandbox.exec()` is the one-call start-and-wait convenience for ordinary
|
|
175
|
+
commands. It uses `sandbox.processes` internally and does not create a durable
|
|
176
|
+
control-plane exec record; use `sandbox.processes.start()` when you need the
|
|
177
|
+
process handle.
|
|
178
|
+
|
|
179
|
+
Transfer files through the sandbox process connection without buffering the
|
|
180
|
+
whole file in memory:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
await sandbox.files.uploadFile(file.stream(), "/workspace/input.tar.gz");
|
|
184
|
+
|
|
185
|
+
const writable = await fileHandle.createWritable();
|
|
186
|
+
await sandbox.files.downloadFile("/workspace/result.json", (chunk) =>
|
|
187
|
+
writable.write(chunk),
|
|
188
|
+
);
|
|
189
|
+
await writable.close();
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Downloads request one bounded chunk at a time. A short or empty chunk marks
|
|
193
|
+
end-of-file, so the source does not need to be sized before transfer.
|
|
194
|
+
|
|
195
|
+
`uploadFile()` accepts a `Uint8Array`, `ArrayBuffer`, `Blob`, async iterable, or
|
|
196
|
+
`ReadableStream`. `downloadFile()` passes each chunk to the provided writer and
|
|
197
|
+
waits for it before requesting more data. Uploads replace the remote target only
|
|
198
|
+
after the transfer succeeds.
|
|
118
199
|
|
|
119
200
|
API keys live at the account level, so those helpers are top-level:
|
|
120
201
|
|
package/dist/cli.mjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { O as ArchilApiError, a as deleteApiKey, l as listApiKeys, n as createApiKey, r as createDisk, s as getDisk, t as configure, u as listDisks } 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";
|
|
3
4
|
import { createRequire } from "node:module";
|
|
4
|
-
import { Command
|
|
5
|
+
import { Command } from "commander";
|
|
5
6
|
//#region bin/cli.ts
|
|
6
7
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
7
8
|
const program = new Command();
|
|
8
|
-
program.name("disk").description("Manage Archil disks from the command line").version(pkg.version).
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
} catch (err) {
|
|
17
|
-
fail(err);
|
|
18
|
-
}
|
|
9
|
+
program.name("disk").description("Manage Archil disks from the command line").version(pkg.version).hook("preAction", async (_thisCommand, actionCommand) => {
|
|
10
|
+
if (isProfileCommand(actionCommand)) return;
|
|
11
|
+
const resolved = await resolveProgramCredentials(program);
|
|
12
|
+
configure({
|
|
13
|
+
apiKey: resolved.apiKey,
|
|
14
|
+
region: resolved.region,
|
|
15
|
+
baseUrl: resolved.baseUrl
|
|
16
|
+
});
|
|
19
17
|
});
|
|
18
|
+
addGlobalOptions(program);
|
|
19
|
+
addProfileCommands(program);
|
|
20
20
|
function fail(err) {
|
|
21
21
|
if (err instanceof ArchilApiError) console.error(`Error (${err.status}): ${err.message}`);
|
|
22
22
|
else console.error(err instanceof Error ? err.message : String(err));
|
|
@@ -50,23 +50,6 @@ function formatBytes(n) {
|
|
|
50
50
|
}
|
|
51
51
|
return `${v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : 2)} ${units[i]}`;
|
|
52
52
|
}
|
|
53
|
-
function renderTable(rows, headers) {
|
|
54
|
-
const all = headers ? [headers, ...rows] : rows;
|
|
55
|
-
if (all.length === 0) return "";
|
|
56
|
-
const cols = Math.max(...all.map((r) => r.length));
|
|
57
|
-
const widths = [];
|
|
58
|
-
for (let i = 0; i < cols; i++) widths[i] = Math.max(...all.map((r) => (r[i] ?? "").length));
|
|
59
|
-
const bar = (l, m, r) => l + widths.map((w) => "─".repeat(w + 2)).join(m) + r;
|
|
60
|
-
const line = (r) => "│ " + widths.map((w, i) => (r[i] ?? "").padEnd(w)).join(" │ ") + " │";
|
|
61
|
-
const out = [bar("╭", "┬", "╮")];
|
|
62
|
-
if (headers) {
|
|
63
|
-
out.push(line(headers));
|
|
64
|
-
out.push(bar("├", "┼", "┤"));
|
|
65
|
-
}
|
|
66
|
-
for (const r of rows) out.push(line(r));
|
|
67
|
-
out.push(bar("╰", "┴", "╯"));
|
|
68
|
-
return out.join("\n");
|
|
69
|
-
}
|
|
70
53
|
function section(title, body) {
|
|
71
54
|
console.log("");
|
|
72
55
|
console.log(title);
|
|
@@ -260,6 +243,8 @@ function rewriteSugar(argv) {
|
|
|
260
243
|
"exec",
|
|
261
244
|
"grep",
|
|
262
245
|
"api-keys",
|
|
246
|
+
"profile",
|
|
247
|
+
"sandboxes",
|
|
263
248
|
"help",
|
|
264
249
|
"--help",
|
|
265
250
|
"-h",
|
|
@@ -276,6 +261,6 @@ function rewriteSugar(argv) {
|
|
|
276
261
|
];
|
|
277
262
|
return argv;
|
|
278
263
|
}
|
|
279
|
-
program.parseAsync(rewriteSugar(process.argv));
|
|
264
|
+
program.parseAsync(rewriteSugar(process.argv)).catch(fail);
|
|
280
265
|
//#endregion
|
|
281
266
|
export {};
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { D as REGION_URLS, p as Archil } from "./src-Cw7ldF_H.mjs";
|
|
2
|
+
import { Option } from "commander";
|
|
3
|
+
import { isCancel, password, spinner } from "@clack/prompts";
|
|
4
|
+
import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
//#region src/cli/config-paths.ts
|
|
8
|
+
function diskConfigDir(env = process.env, platform = process.platform, home = homedir()) {
|
|
9
|
+
if (env.ARCHIL_DISK_CONFIG_DIR) return env.ARCHIL_DISK_CONFIG_DIR;
|
|
10
|
+
if (platform === "win32") return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Archil", "disk");
|
|
11
|
+
if (platform === "darwin") return join(home, "Library", "Application Support", "Archil", "disk");
|
|
12
|
+
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "archil", "disk");
|
|
13
|
+
}
|
|
14
|
+
function profileConfigPath(env = process.env) {
|
|
15
|
+
return join(diskConfigDir(env), "config.json");
|
|
16
|
+
}
|
|
17
|
+
function credentialFilePath(profile, env = process.env) {
|
|
18
|
+
return join(diskConfigDir(env), "credentials", `${encodeURIComponent(profile)}.key`);
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/cli/credentials.ts
|
|
22
|
+
function validateApiKey(value) {
|
|
23
|
+
const key = value.trim();
|
|
24
|
+
if (!key) throw new Error("API key is empty");
|
|
25
|
+
if (/\s/.test(key)) throw new Error("API key must not contain whitespace");
|
|
26
|
+
return key;
|
|
27
|
+
}
|
|
28
|
+
async function readProfileCredential(profile, env = process.env) {
|
|
29
|
+
const path = credentialFilePath(profile, env);
|
|
30
|
+
try {
|
|
31
|
+
if (process.platform !== "win32") {
|
|
32
|
+
if (((await stat(path)).mode & 63) !== 0) throw new Error(`Refusing to read credential file ${path}: permissions must be 0600`);
|
|
33
|
+
}
|
|
34
|
+
return validateApiKey(await readFile(path, "utf8"));
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error.code === "ENOENT") throw new Error(`Missing API key for profile '${profile}': delete and recreate it with 'profile create --profile ${profile}'`);
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function writeProfileCredential(profile, secret, env = process.env) {
|
|
41
|
+
const path = credentialFilePath(profile, env);
|
|
42
|
+
await mkdir(dirname(path), {
|
|
43
|
+
recursive: true,
|
|
44
|
+
mode: 448
|
|
45
|
+
});
|
|
46
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
47
|
+
const handle = await open(temporary, "wx", 384);
|
|
48
|
+
try {
|
|
49
|
+
await handle.writeFile(`${validateApiKey(secret)}\n`);
|
|
50
|
+
await handle.sync();
|
|
51
|
+
} finally {
|
|
52
|
+
await handle.close();
|
|
53
|
+
}
|
|
54
|
+
await rename(temporary, path);
|
|
55
|
+
}
|
|
56
|
+
async function deleteProfileCredential(profile, env = process.env) {
|
|
57
|
+
await rm(credentialFilePath(profile, env), { force: true });
|
|
58
|
+
}
|
|
59
|
+
async function resolveCliCredentials(options, profiles, env = process.env, readCredential = readProfileCredential) {
|
|
60
|
+
const selected = options.profile ?? env.ARCHIL_PROFILE ?? profiles.currentProfile;
|
|
61
|
+
const profile = selected ? profiles.profiles[selected] : void 0;
|
|
62
|
+
if (selected && !profile) throw new Error(`Profile '${selected}' does not exist`);
|
|
63
|
+
const apiKey = options.apiKey ?? env.ARCHIL_API_KEY ?? (profile && selected ? await readCredential(selected, env) : void 0);
|
|
64
|
+
const region = options.region ?? env.ARCHIL_REGION ?? profile?.region;
|
|
65
|
+
const baseUrl = options.baseUrl ?? env.ARCHIL_BASE_URL ?? profile?.baseUrl;
|
|
66
|
+
if (!apiKey) throw new Error("Missing API key: pass --api-key, set ARCHIL_API_KEY, or run 'profile create'");
|
|
67
|
+
if (!region) throw new Error("Missing region: pass --region, set ARCHIL_REGION, or select a profile");
|
|
68
|
+
return {
|
|
69
|
+
apiKey: validateApiKey(apiKey),
|
|
70
|
+
region,
|
|
71
|
+
baseUrl,
|
|
72
|
+
profile: selected
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
async function promptSecret(prompt = "API key: ", input = process.stdin, output = process.stderr) {
|
|
76
|
+
if (!input.isTTY) {
|
|
77
|
+
const chunks = [];
|
|
78
|
+
for await (const chunk of input) chunks.push(Buffer.from(chunk));
|
|
79
|
+
return validateApiKey(Buffer.concat(chunks).toString("utf8"));
|
|
80
|
+
}
|
|
81
|
+
const result = await password({
|
|
82
|
+
message: prompt,
|
|
83
|
+
input,
|
|
84
|
+
output,
|
|
85
|
+
withGuide: false,
|
|
86
|
+
validate(value) {
|
|
87
|
+
try {
|
|
88
|
+
validateApiKey(value ?? "");
|
|
89
|
+
} catch (error) {
|
|
90
|
+
return error instanceof Error ? error.message : String(error);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
if (isCancel(result)) throw new Error("Profile creation cancelled");
|
|
95
|
+
return validateApiKey(result);
|
|
96
|
+
}
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/cli/credential-validation.ts
|
|
99
|
+
async function validateCredentialAndResolveRegion(options, probe = async ({ apiKey, region, baseUrl }) => {
|
|
100
|
+
await new Archil({
|
|
101
|
+
apiKey,
|
|
102
|
+
region,
|
|
103
|
+
baseUrl
|
|
104
|
+
}).disks.list({ limit: 1 });
|
|
105
|
+
}) {
|
|
106
|
+
const apiKey = validateApiKey(options.apiKey);
|
|
107
|
+
if (options.region) {
|
|
108
|
+
await probe({
|
|
109
|
+
...options,
|
|
110
|
+
apiKey,
|
|
111
|
+
region: options.region
|
|
112
|
+
});
|
|
113
|
+
return options.region;
|
|
114
|
+
}
|
|
115
|
+
if (options.baseUrl) throw new Error("Profile creation with --base-url also requires --region because custom environments cannot be auto-detected");
|
|
116
|
+
const failures = [];
|
|
117
|
+
for (const region of Object.keys(REGION_URLS)) try {
|
|
118
|
+
await probe({
|
|
119
|
+
apiKey,
|
|
120
|
+
region
|
|
121
|
+
});
|
|
122
|
+
return region;
|
|
123
|
+
} catch (error) {
|
|
124
|
+
failures.push(error);
|
|
125
|
+
}
|
|
126
|
+
throw new AggregateError(failures, "API key was not accepted in any known production region; pass --region for a custom environment");
|
|
127
|
+
}
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/cli/output.ts
|
|
130
|
+
function renderTable(rows, headers) {
|
|
131
|
+
const all = headers ? [headers, ...rows] : rows;
|
|
132
|
+
if (all.length === 0) return "";
|
|
133
|
+
const columnCount = Math.max(...all.map((row) => row.length));
|
|
134
|
+
const widths = Array.from({ length: columnCount }, (_, index) => Math.max(...all.map((row) => (row[index] ?? "").length)));
|
|
135
|
+
const border = (left, middle, right) => left + widths.map((width) => "─".repeat(width + 2)).join(middle) + right;
|
|
136
|
+
const line = (row) => "│ " + widths.map((width, index) => (row[index] ?? "").padEnd(width)).join(" │ ") + " │";
|
|
137
|
+
const output = [border("╭", "┬", "╮")];
|
|
138
|
+
if (headers) output.push(line(headers), border("├", "┼", "┤"));
|
|
139
|
+
output.push(...rows.map(line), border("╰", "┴", "╯"));
|
|
140
|
+
return output.join("\n");
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/cli/profiles.ts
|
|
144
|
+
const EMPTY_PROFILE_CONFIG = {
|
|
145
|
+
version: 1,
|
|
146
|
+
profiles: {}
|
|
147
|
+
};
|
|
148
|
+
function parseConfig(value) {
|
|
149
|
+
if (!value || typeof value !== "object") throw new Error("Profile configuration must be a JSON object");
|
|
150
|
+
const raw = value;
|
|
151
|
+
if (raw.version !== 1) throw new Error(`Unsupported profile configuration version: ${String(raw.version)}`);
|
|
152
|
+
if (!raw.profiles || typeof raw.profiles !== "object" || Array.isArray(raw.profiles)) throw new Error("Profile configuration has an invalid profiles field");
|
|
153
|
+
for (const [name, profile] of Object.entries(raw.profiles)) {
|
|
154
|
+
if (!profile || typeof profile !== "object") throw new Error(`Profile '${name}' is invalid`);
|
|
155
|
+
const p = profile;
|
|
156
|
+
if (typeof p.region !== "string" || !p.region) throw new Error(`Profile '${name}' has no region`);
|
|
157
|
+
}
|
|
158
|
+
if (raw.currentProfile !== void 0 && typeof raw.currentProfile !== "string") throw new Error("Profile configuration has an invalid currentProfile field");
|
|
159
|
+
return value;
|
|
160
|
+
}
|
|
161
|
+
async function loadProfiles(env = process.env) {
|
|
162
|
+
const path = profileConfigPath(env);
|
|
163
|
+
try {
|
|
164
|
+
return parseConfig(JSON.parse(await readFile(path, "utf8")));
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error.code === "ENOENT") return {
|
|
167
|
+
...EMPTY_PROFILE_CONFIG,
|
|
168
|
+
profiles: {}
|
|
169
|
+
};
|
|
170
|
+
if (error instanceof SyntaxError) throw new Error(`Malformed profile configuration at ${path}`);
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
async function saveProfiles(config, env = process.env) {
|
|
175
|
+
const path = profileConfigPath(env);
|
|
176
|
+
await mkdir(dirname(path), {
|
|
177
|
+
recursive: true,
|
|
178
|
+
mode: 448
|
|
179
|
+
});
|
|
180
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
181
|
+
const handle = await open(temporary, "wx", 384);
|
|
182
|
+
try {
|
|
183
|
+
await handle.writeFile(`${JSON.stringify(config, null, 2)}\n`);
|
|
184
|
+
await handle.sync();
|
|
185
|
+
} finally {
|
|
186
|
+
await handle.close();
|
|
187
|
+
}
|
|
188
|
+
await rename(temporary, path);
|
|
189
|
+
if (process.platform !== "win32") {
|
|
190
|
+
if (((await stat(path)).mode & 511) !== 384) await chmod(path, 384);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function deleteProfile(name, env = process.env) {
|
|
194
|
+
const config = await loadProfiles(env);
|
|
195
|
+
const profile = config.profiles[name];
|
|
196
|
+
if (!profile) return void 0;
|
|
197
|
+
delete config.profiles[name];
|
|
198
|
+
if (config.currentProfile === name) config.currentProfile = void 0;
|
|
199
|
+
await saveProfiles(config, env);
|
|
200
|
+
return profile;
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/cli/common.ts
|
|
204
|
+
function addGlobalOptions(program) {
|
|
205
|
+
program.configureHelp({ showGlobalOptions: true }).addOption(new Option("-k, --api-key <key>", "Archil API key (prefer profiles, environment variables, or stdin)").env("ARCHIL_API_KEY")).addOption(new Option("-r, --region <region>", "Archil region").env("ARCHIL_REGION")).addOption(new Option("--base-url <url>", "Override control-plane base URL").env("ARCHIL_BASE_URL")).addOption(new Option("--profile <name>", "Named Archil profile").env("ARCHIL_PROFILE"));
|
|
206
|
+
}
|
|
207
|
+
function isProfileCommand(command) {
|
|
208
|
+
return command.parent?.name() === "profile";
|
|
209
|
+
}
|
|
210
|
+
async function resolveProgramCredentials(program) {
|
|
211
|
+
return resolveCliCredentials(program.opts(), await loadProfiles());
|
|
212
|
+
}
|
|
213
|
+
function addProfileCommands(program, validateCredential = validateCredentialAndResolveRegion) {
|
|
214
|
+
const outputOption = (command) => command.option("-o, --output <format>", "Output format: table | text | json", (value) => {
|
|
215
|
+
if (value !== "table" && value !== "text" && value !== "json") throw new Error("Output format must be 'table', 'text', or 'json'");
|
|
216
|
+
return value;
|
|
217
|
+
}, "table");
|
|
218
|
+
const profiles = program.command("profile").description("Manage named Archil profiles and credentials");
|
|
219
|
+
outputOption(profiles.command("create").description("Create a named profile")).action(async (options) => {
|
|
220
|
+
const global = program.opts();
|
|
221
|
+
const config = await loadProfiles();
|
|
222
|
+
if (global.profile && config.profiles[global.profile]) throw new Error(`Profile '${global.profile}' already exists`);
|
|
223
|
+
const apiKey = validateApiKey(global.apiKey ?? await promptSecret());
|
|
224
|
+
const progress = !global.region && !global.baseUrl && process.stderr.isTTY ? spinner({
|
|
225
|
+
output: process.stderr,
|
|
226
|
+
withGuide: false
|
|
227
|
+
}) : void 0;
|
|
228
|
+
progress?.start("Finding the API key's region");
|
|
229
|
+
let region;
|
|
230
|
+
try {
|
|
231
|
+
region = await validateCredential({
|
|
232
|
+
apiKey,
|
|
233
|
+
region: global.region,
|
|
234
|
+
baseUrl: global.baseUrl
|
|
235
|
+
});
|
|
236
|
+
progress?.stop("Found valid region");
|
|
237
|
+
} catch (error) {
|
|
238
|
+
progress?.error("No valid region found");
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
let name = global.profile ?? region;
|
|
242
|
+
if (!global.profile) {
|
|
243
|
+
let suffix = 2;
|
|
244
|
+
while (config.profiles[name]) name = `${region}-${suffix++}`;
|
|
245
|
+
}
|
|
246
|
+
await writeProfileCredential(name, apiKey);
|
|
247
|
+
config.profiles[name] = {
|
|
248
|
+
region,
|
|
249
|
+
baseUrl: global.baseUrl
|
|
250
|
+
};
|
|
251
|
+
config.currentProfile = name;
|
|
252
|
+
await saveProfiles(config);
|
|
253
|
+
if (options.output === "json") console.log(JSON.stringify({
|
|
254
|
+
name,
|
|
255
|
+
region,
|
|
256
|
+
baseUrl: global.baseUrl,
|
|
257
|
+
current: true
|
|
258
|
+
}, null, 2));
|
|
259
|
+
else console.log(`Created profile '${name}' (${region})`);
|
|
260
|
+
});
|
|
261
|
+
outputOption(profiles.command("list").description("List profiles without revealing credentials")).action(async (options) => {
|
|
262
|
+
const config = await loadProfiles();
|
|
263
|
+
const items = Object.entries(config.profiles).sort(([a], [b]) => a.localeCompare(b)).map(([name, profile]) => ({
|
|
264
|
+
name,
|
|
265
|
+
region: profile.region,
|
|
266
|
+
baseUrl: profile.baseUrl,
|
|
267
|
+
current: config.currentProfile === name
|
|
268
|
+
}));
|
|
269
|
+
if (options.output === "json") console.log(JSON.stringify(items, null, 2));
|
|
270
|
+
else if (options.output === "text") for (const item of items) console.log(`${item.current ? "*" : " "} ${item.name}\t${item.region}\t${item.baseUrl ?? "default"}`);
|
|
271
|
+
else console.log(renderTable(items.map((item) => [
|
|
272
|
+
item.current ? "*" : "",
|
|
273
|
+
item.name,
|
|
274
|
+
item.region,
|
|
275
|
+
item.baseUrl ?? "default"
|
|
276
|
+
]), [
|
|
277
|
+
"current",
|
|
278
|
+
"name",
|
|
279
|
+
"region",
|
|
280
|
+
"base URL"
|
|
281
|
+
]));
|
|
282
|
+
});
|
|
283
|
+
outputOption(profiles.command("use <name>").description("Select the default profile")).action(async (name, options) => {
|
|
284
|
+
const config = await loadProfiles();
|
|
285
|
+
if (!config.profiles[name]) throw new Error(`Profile '${name}' does not exist`);
|
|
286
|
+
config.currentProfile = name;
|
|
287
|
+
await saveProfiles(config);
|
|
288
|
+
if (options.output === "json") console.log(JSON.stringify({
|
|
289
|
+
name,
|
|
290
|
+
current: true
|
|
291
|
+
}, null, 2));
|
|
292
|
+
else console.log(`Using profile '${name}'`);
|
|
293
|
+
});
|
|
294
|
+
outputOption(profiles.command("delete <name>").description("Delete a profile and its stored credential")).action(async (name, options) => {
|
|
295
|
+
if (!(await loadProfiles()).profiles[name]) throw new Error(`Profile '${name}' does not exist`);
|
|
296
|
+
await deleteProfileCredential(name);
|
|
297
|
+
await deleteProfile(name);
|
|
298
|
+
if (options.output === "json") console.log(JSON.stringify({
|
|
299
|
+
name,
|
|
300
|
+
deleted: true
|
|
301
|
+
}, null, 2));
|
|
302
|
+
else console.log(`Deleted profile '${name}'`);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
export { renderTable as a, resolveProgramCredentials as i, addProfileCommands as n, isProfileCommand as r, addGlobalOptions as t };
|