disk 0.11.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 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:
@@ -89,8 +120,7 @@ const sandbox = await client.sandboxes.create({
89
120
  memSizeMiB: 8192,
90
121
  });
91
122
 
92
- const execution = await sandbox.processes.start("uname -a");
93
- const result = await execution.wait();
123
+ const result = await sandbox.exec("uname -a");
94
124
  console.log(result.stdout);
95
125
 
96
126
  const terminal = await sandbox.processes.start("codex", {
@@ -112,12 +142,8 @@ await resumed.kill();
112
142
  await sandbox.start();
113
143
  await sandbox.resume();
114
144
 
115
- // Existing exec API for durable control-plane exec records.
116
- const runningExec = await sandbox.exec("sleep 60", { wait: false });
117
-
118
145
  await sandbox.stop();
119
146
  const fork = await sandbox.fork({ name: "agent-task" });
120
- const connection = await fork.createConnection();
121
147
  await fork.stop();
122
148
  await fork.delete();
123
149
 
@@ -141,11 +167,14 @@ frames. Set `collectOutput: false` to stream through `onOutput` without
141
167
  retaining decoded output in the process handle or result. Resize and kill use
142
168
  separate one-shot process controls, so they do not wait behind stdin.
143
169
  `kill()` returns after the control is acknowledged; `wait()` observes exit.
144
- `maxConcurrentExecs` limits attached exec sessions; detached processes and
170
+ `maxConcurrentExecs` limits attached process sessions; detached processes and
145
171
  one-shot controls do not count. Pausing a sandbox disconnects attachments but
146
172
  preserves its processes for reattachment after resume. Processes end when
147
173
  their sandbox is stopped or expires.
148
- The existing `exec` API remains available for durable control-plane exec records.
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.
149
178
 
150
179
  Transfer files through the sandbox process connection without buffering the
151
180
  whole file in memory:
package/dist/cli.mjs CHANGED
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env node
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-Cpv1TIWC.mjs";
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, Option } from "commander";
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).addOption(new Option("-k, --api-key <key>", "Archil API key").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")).hook("preAction", () => {
9
- const opts = program.opts();
10
- try {
11
- configure({
12
- apiKey: opts.apiKey,
13
- region: opts.region,
14
- baseUrl: opts.baseUrl
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 };
package/dist/index.cjs CHANGED
@@ -145,7 +145,7 @@ function deriveS3BaseUrl(controlBaseUrl) {
145
145
  }
146
146
  //#endregion
147
147
  //#region src/version.ts
148
- const VERSION = "0.11.0";
148
+ const VERSION = "1.0.0";
149
149
  const USER_AGENT = `archil-js/${VERSION}`;
150
150
  //#endregion
151
151
  //#region src/client.ts
@@ -1684,72 +1684,6 @@ const POLL_INTERVAL_MS = 500;
1684
1684
  function sleep() {
1685
1685
  return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
1686
1686
  }
1687
- var SandboxExec = class {
1688
- sandboxId;
1689
- id;
1690
- command;
1691
- status;
1692
- exitCode;
1693
- stdout;
1694
- stderr;
1695
- exitReason;
1696
- executeTimeMs;
1697
- startedAt;
1698
- finishedAt;
1699
- /** @internal */
1700
- _client;
1701
- /** @internal */
1702
- constructor(data, client) {
1703
- this._client = client;
1704
- this._apply(data);
1705
- }
1706
- /** @internal Overwrite this exec's fields in place from a fresh wire snapshot. */
1707
- _apply(data) {
1708
- this.sandboxId = data.sandbox_id;
1709
- this.id = data.exec_id;
1710
- this.command = data.command;
1711
- this.status = data.status;
1712
- this.exitCode = data.exit_code;
1713
- this.stdout = data.stdout;
1714
- this.stderr = data.stderr;
1715
- this.exitReason = data.exit_reason;
1716
- this.executeTimeMs = data.execute_time_ms;
1717
- this.startedAt = new Date(data.started_at);
1718
- this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
1719
- return this;
1720
- }
1721
- toJSON() {
1722
- return {
1723
- sandboxId: this.sandboxId,
1724
- id: this.id,
1725
- command: this.command,
1726
- status: this.status,
1727
- exitCode: this.exitCode,
1728
- stdout: this.stdout,
1729
- stderr: this.stderr,
1730
- exitReason: this.exitReason,
1731
- executeTimeMs: this.executeTimeMs,
1732
- startedAt: this.startedAt,
1733
- finishedAt: this.finishedAt
1734
- };
1735
- }
1736
- /** Re-fetch this exec and update it in place, returning the same object. */
1737
- async refresh() {
1738
- const data = await unwrap(this._client.GET("/api/sandboxes/{sid}/execs/{eid}", { params: { path: {
1739
- sid: this.sandboxId,
1740
- eid: this.id
1741
- } } }));
1742
- return this._apply(data);
1743
- }
1744
- /** Cancel this exec and update it in place, returning the same object. */
1745
- async cancel() {
1746
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/execs/{eid}/cancel", { params: { path: {
1747
- sid: this.sandboxId,
1748
- eid: this.id
1749
- } } }));
1750
- return this._apply(data);
1751
- }
1752
- };
1753
1687
  var Sandbox = class Sandbox {
1754
1688
  id;
1755
1689
  name;
@@ -1818,6 +1752,10 @@ var Sandbox = class Sandbox {
1818
1752
  exitReason: this.exitReason
1819
1753
  };
1820
1754
  }
1755
+ /** Run a process and wait for it to exit. */
1756
+ async exec(command, options = {}) {
1757
+ return (await this.processes.start(command, options)).wait();
1758
+ }
1821
1759
  /** Re-fetch this sandbox. */
1822
1760
  async refresh() {
1823
1761
  const data = await unwrap(this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
@@ -1865,53 +1803,10 @@ var Sandbox = class Sandbox {
1865
1803
  const fork = new Sandbox(data, this._client);
1866
1804
  return options.wait === false ? fork : waitForSandboxStart(fork);
1867
1805
  }
1868
- /** Create a short-lived signed WebSocket URL for a sandbox process connection. */
1869
- async createConnection() {
1870
- const data = await unwrap(this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }));
1871
- return {
1872
- url: data.url,
1873
- expiresAt: new Date(data.expires_at)
1874
- };
1875
- }
1876
1806
  /** Delete this sandbox and its backing disk. */
1877
1807
  async delete() {
1878
1808
  await unwrapEmpty(this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }));
1879
1809
  }
1880
- async exec(command, options = {}) {
1881
- const exec = new SandboxExec(await unwrap(this._client.POST("/api/sandboxes/{sid}/execs", {
1882
- params: {
1883
- path: { sid: this.id },
1884
- query: { wait: options.wait ?? true }
1885
- },
1886
- body: {
1887
- command,
1888
- command_tty: options.commandTty,
1889
- env: options.env,
1890
- timeout_seconds: options.timeoutSeconds
1891
- }
1892
- })), this._client);
1893
- if (options.wait === false) return exec;
1894
- while (exec.status === "running") {
1895
- await sleep();
1896
- await exec.refresh();
1897
- }
1898
- return exec;
1899
- }
1900
- async listExecs() {
1901
- return ((await unwrap(this._client.GET("/api/sandboxes/{sid}/execs", { params: { path: { sid: this.id } } })))?.execs ?? []).map((exec) => new SandboxExec(exec, this._client));
1902
- }
1903
- async getExec(execId) {
1904
- return new SandboxExec(await unwrap(this._client.GET("/api/sandboxes/{sid}/execs/{eid}", { params: { path: {
1905
- sid: this.id,
1906
- eid: execId
1907
- } } })), this._client);
1908
- }
1909
- async cancelExec(execId) {
1910
- return new SandboxExec(await unwrap(this._client.POST("/api/sandboxes/{sid}/execs/{eid}/cancel", { params: { path: {
1911
- sid: this.id,
1912
- eid: execId
1913
- } } })), this._client);
1914
- }
1915
1810
  };
1916
1811
  /** @internal Continue waiting if the server returned before startup completed. */
1917
1812
  async function waitForSandboxStart(sandbox) {
@@ -2358,7 +2253,6 @@ exports.Disk = Disk;
2358
2253
  exports.DiskMultipart = DiskMultipart;
2359
2254
  exports.Disks = Disks;
2360
2255
  exports.Sandbox = Sandbox;
2361
- exports.SandboxExec = SandboxExec;
2362
2256
  exports.SandboxFileTransferError = SandboxFileTransferError;
2363
2257
  exports.SandboxFiles = SandboxFiles;
2364
2258
  exports.SandboxProcess = SandboxProcess;