@computesdk/cli 2.5.6 → 2.5.8

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/dist/index.js CHANGED
@@ -5,9 +5,9 @@ import "dotenv/config";
5
5
  import { Command } from "commander";
6
6
  import * as p from "@clack/prompts";
7
7
  import pc5 from "picocolors";
8
- import { readFileSync as readFileSync2 } from "fs";
8
+ import { readFileSync as readFileSync3 } from "fs";
9
9
  import { fileURLToPath } from "url";
10
- import { dirname, join as join2 } from "path";
10
+ import { dirname as dirname2, join as join4 } from "path";
11
11
 
12
12
  // src/providers.ts
13
13
  var PROVIDER_ENV = {
@@ -167,8 +167,8 @@ var ActionsClient = class {
167
167
  this.orgPromise ?? (this.orgPromise = this.get("/api/v1/actions/org"));
168
168
  return this.orgPromise;
169
169
  }
170
- async get(path, params) {
171
- const url = new URL(`${this.auth.baseUrl}${path}`);
170
+ async get(path2, params) {
171
+ const url = new URL(`${this.auth.baseUrl}${path2}`);
172
172
  for (const [key, value] of Object.entries(params ?? {})) {
173
173
  if (value === void 0) continue;
174
174
  for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);
@@ -176,8 +176,8 @@ var ActionsClient = class {
176
176
  const res = await this.fetchImpl(url, { headers: this.headers() });
177
177
  return this.parse(res);
178
178
  }
179
- async post(path, body = {}) {
180
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
179
+ async post(path2, body = {}) {
180
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
181
181
  method: "POST",
182
182
  headers: { ...this.headers(), "content-type": "application/json" },
183
183
  body: JSON.stringify(body)
@@ -185,32 +185,32 @@ var ActionsClient = class {
185
185
  return this.parse(res);
186
186
  }
187
187
  /** POST a raw text body (e.g. a unified diff to `/api/v1/actions/patches`). */
188
- async postText(path, body, contentType) {
189
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
188
+ async postText(path2, body, contentType) {
189
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
190
190
  method: "POST",
191
191
  headers: { ...this.headers(), "content-type": contentType },
192
192
  body
193
193
  });
194
194
  return this.parse(res);
195
195
  }
196
- async put(path, body = {}) {
197
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
196
+ async put(path2, body = {}) {
197
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
198
198
  method: "PUT",
199
199
  headers: { ...this.headers(), "content-type": "application/json" },
200
200
  body: JSON.stringify(body)
201
201
  });
202
202
  return this.parse(res);
203
203
  }
204
- async patch(path, body = {}) {
205
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
204
+ async patch(path2, body = {}) {
205
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
206
206
  method: "PATCH",
207
207
  headers: { ...this.headers(), "content-type": "application/json" },
208
208
  body: JSON.stringify(body)
209
209
  });
210
210
  return this.parse(res);
211
211
  }
212
- async del(path) {
213
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
212
+ async del(path2) {
213
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
214
214
  method: "DELETE",
215
215
  headers: this.headers()
216
216
  });
@@ -220,8 +220,8 @@ var ActionsClient = class {
220
220
  * One `data:` JSON payload per SSE event. `next()` resolves to the payload,
221
221
  * or null when the stream ends. Call `close()` to abort.
222
222
  */
223
- async *sse(path, params) {
224
- const url = new URL(`${this.auth.baseUrl}${path}`);
223
+ async *sse(path2, params) {
224
+ const url = new URL(`${this.auth.baseUrl}${path2}`);
225
225
  for (const [key, value] of Object.entries(params ?? {})) {
226
226
  if (value === void 0) continue;
227
227
  for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);
@@ -240,8 +240,8 @@ var ActionsClient = class {
240
240
  * events are distinguished by name rather than payload shape (process
241
241
  * follow: stdout/stderr share a `{chunk}` payload).
242
242
  */
243
- async *sseNamed(path, params) {
244
- const url = new URL(`${this.auth.baseUrl}${path}`);
243
+ async *sseNamed(path2, params) {
244
+ const url = new URL(`${this.auth.baseUrl}${path2}`);
245
245
  for (const [key, value] of Object.entries(params ?? {})) {
246
246
  if (value === void 0) continue;
247
247
  for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);
@@ -256,8 +256,8 @@ var ActionsClient = class {
256
256
  yield* readSseNamedEvents(res.body);
257
257
  }
258
258
  /** Download bytes following redirects (artifact URLs 302 to storage). */
259
- async download(path) {
260
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
259
+ async download(path2) {
260
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
261
261
  headers: this.headers(),
262
262
  redirect: "follow"
263
263
  });
@@ -768,6 +768,7 @@ function formatRunDetail(run, runUrl) {
768
768
  if (run.providerOverride) lines.push(`dispatched to: ${run.providerOverride}`);
769
769
  if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);
770
770
  if (runUrl) lines.push(`url: ${runUrl}`);
771
+ if (run.benchmarks && run.benchmarks.length > 0) lines.push(`benchmarks: ${resultsSummary(run.benchmarks)}`);
771
772
  if (run.jobs.length > 0) {
772
773
  lines.push("");
773
774
  lines.push(pc2.bold("jobs"));
@@ -785,6 +786,57 @@ function formatRunDetail(run, runUrl) {
785
786
  }
786
787
  return lines.join("\n");
787
788
  }
789
+ function resultsSummary(results) {
790
+ return results.map((r) => {
791
+ const rows = overallRows(r);
792
+ if (rows.length === 0) return `${safeTerm(r.benchmarkSlug)} (${safeTerm(r.status)}, no results yet)`;
793
+ const failed = rows.filter((p2) => !p2.skipped && p2.successRate !== null && p2.successRate < 1).length;
794
+ return `${safeTerm(r.benchmarkSlug)} \xB7 ${rows.length} providers${failed > 0 ? ` \xB7 ${failed} failed` : ""}`;
795
+ }).join("; ");
796
+ }
797
+ function overallRows(result) {
798
+ const byProvider = /* @__PURE__ */ new Map();
799
+ for (const p2 of result.providers) {
800
+ const cur = byProvider.get(p2.provider);
801
+ const isOverall = Object.keys(p2.dimensions).length === 0;
802
+ const curIsOverall = cur ? Object.keys(cur.dimensions).length === 0 : false;
803
+ if (!cur || isOverall && !curIsOverall || !curIsOverall && (p2.compositeScore ?? -1) > (cur.compositeScore ?? -1)) {
804
+ byProvider.set(p2.provider, p2);
805
+ }
806
+ }
807
+ return Array.from(byProvider.values());
808
+ }
809
+ function formatScore(n) {
810
+ return n === null ? "-" : n.toFixed(2);
811
+ }
812
+ function formatMetric(n) {
813
+ return Number.isInteger(n) ? String(n) : n.toFixed(Math.abs(n) >= 100 ? 1 : 2);
814
+ }
815
+ function formatRate(n) {
816
+ return n === null ? "-" : `${Math.round(n * 100)}%`;
817
+ }
818
+ function formatRunResults(results) {
819
+ if (results.length === 0) return pc2.dim("no benchmark results on this run");
820
+ const lines = [];
821
+ for (const [i, result] of results.entries()) {
822
+ if (i > 0) lines.push("");
823
+ lines.push(`${pc2.bold(safeTerm(result.benchmarkName))} ${safeTerm(result.status)}`);
824
+ lines.push(pc2.dim(`${safeTerm(result.benchmarkRunId)} ${safeTerm(result.dashboardUrl)}`));
825
+ const rows = [...overallRows(result)].sort((a, b) => (b.compositeScore ?? -1) - (a.compositeScore ?? -1));
826
+ if (rows.length === 0) {
827
+ lines.push(pc2.dim(result.status === "failed" ? " failed before reporting results" : " no results yet"));
828
+ continue;
829
+ }
830
+ const width = Math.max(8, ...rows.map((p2) => p2.provider.length));
831
+ lines.push(pc2.dim(` ${"provider".padEnd(width)} ${"score".padStart(7)} ${"success".padStart(7)} metrics`));
832
+ for (const p2 of rows) {
833
+ const metrics = Object.entries(p2.metrics).map(([name, m]) => `${safeTerm(name)} ${formatMetric(m.median)}${m.unit ? safeTerm(m.unit) : ""}`).join(" ");
834
+ const status = p2.skipped ? pc2.dim(`skipped${p2.skipReason ? `: ${safeTerm(p2.skipReason)}` : ""}`) : metrics;
835
+ lines.push(` ${safeTerm(p2.provider).padEnd(width)} ${formatScore(p2.compositeScore).padStart(7)} ${formatRate(p2.successRate).padStart(7)} ${status}`);
836
+ }
837
+ }
838
+ return lines.join("\n");
839
+ }
788
840
  function formatRunInspection(run) {
789
841
  const lines = [];
790
842
  lines.push(`${pc2.bold("run")} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? "" : ` #${run.runNumber}`}`);
@@ -1031,9 +1083,9 @@ function printDiscovery(d) {
1031
1083
  function isPatchedWorkflowTarget(target) {
1032
1084
  return "workflowPath" in target;
1033
1085
  }
1034
- function patchTouches(patch, path) {
1035
- const plain = `+++ b/${path}`;
1036
- const quoted = `+++ "b/${path}"`;
1086
+ function patchTouches(patch, path2) {
1087
+ const plain = `+++ b/${path2}`;
1088
+ const quoted = `+++ "b/${path2}"`;
1037
1089
  return patch.split("\n").some((line) => {
1038
1090
  const header = line.replace(/\t.*$/, "");
1039
1091
  return header === plain || header === quoted;
@@ -1150,13 +1202,13 @@ function parseVaultKind(kind) {
1150
1202
  if (kind === void 0 || kind === "secret" || kind === "variable") return kind ?? "secret";
1151
1203
  throw new ActionsCliError("invalid_argument", `--kind must be secret or variable, got "${kind}".`);
1152
1204
  }
1153
- function vaultPath(path, params) {
1205
+ function vaultPath(path2, params) {
1154
1206
  const search = new URLSearchParams();
1155
1207
  for (const [key, value] of Object.entries(params)) {
1156
1208
  if (value !== void 0) search.set(key, value);
1157
1209
  }
1158
1210
  const query = search.toString();
1159
- return query ? `${path}?${query}` : path;
1211
+ return query ? `${path2}?${query}` : path2;
1160
1212
  }
1161
1213
  function vaultSetBody(name, value, opts) {
1162
1214
  if (value === "") throw new ActionsCliError("invalid_argument", "The value is empty.");
@@ -1345,6 +1397,17 @@ function registerActionsCommands(program2) {
1345
1397
  fail(e, opts);
1346
1398
  }
1347
1399
  });
1400
+ common(
1401
+ actions.command("benchmarks").description("Show the benchmark runs this run produced: per-provider score and success rate").argument("<run-id>", "run ID")
1402
+ ).action(async (runId, opts) => {
1403
+ try {
1404
+ const run = await (await client(opts)).get(`/api/v1/actions/runs/${runId}`);
1405
+ const benchmarks = run.benchmarks ?? [];
1406
+ output(opts, { runId: run.id, conclusion: run.conclusion, benchmarks }, () => console.log(formatRunResults(benchmarks)));
1407
+ } catch (e) {
1408
+ fail(e, opts);
1409
+ }
1410
+ });
1348
1411
  common(
1349
1412
  actions.command("inspect").description("Inspect a run: resolved runner image, caches, secret names, concurrency, placement context").argument("<run-id>", "run ID")
1350
1413
  ).action(async (runId, opts) => {
@@ -1589,8 +1652,8 @@ function registerActionsCommands(program2) {
1589
1652
  vault.command("ls").description("List names and metadata (never values)")
1590
1653
  ).action(async (opts) => {
1591
1654
  try {
1592
- const path = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind) });
1593
- const data = await (await client(opts)).get(path);
1655
+ const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind) });
1656
+ const data = await (await client(opts)).get(path2);
1594
1657
  output(opts, data, (d) => {
1595
1658
  for (const item of d.items) console.log(formatVaultRow(item));
1596
1659
  });
@@ -1665,8 +1728,8 @@ function registerActionsCommands(program2) {
1665
1728
  vault.command("rm").description("Delete an item (with --repo, only the repo's override)").argument("<name>", "item name")
1666
1729
  ).action(async (name, opts) => {
1667
1730
  try {
1668
- const path = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
1669
- const result = await (await client(opts)).del(path);
1731
+ const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
1732
+ const result = await (await client(opts)).del(path2);
1670
1733
  output(opts, result, (r) => console.log(`deleted ${pc2.cyan(safeTerm(r.name))} ${pc2.dim(`(${r.kind})`)}`));
1671
1734
  } catch (e) {
1672
1735
  fail(e, opts);
@@ -1923,7 +1986,7 @@ function credentialBody(fields, values) {
1923
1986
  }
1924
1987
  return { fields: values };
1925
1988
  }
1926
- function formatRate(usd, per) {
1989
+ function formatRate2(usd, per) {
1927
1990
  return formatUsdPer({ usd, per });
1928
1991
  }
1929
1992
  function formatListingStatus(ask) {
@@ -1933,7 +1996,7 @@ function formatListingStatus(ask) {
1933
1996
  else if (!ask.live) label = pc3.gray("expired");
1934
1997
  else label = pc3.green("live");
1935
1998
  if (ask.pendingUsd !== null && ask.pendingPer !== null) {
1936
- label += pc3.dim(` \u2192 ${formatRate(ask.pendingUsd, ask.pendingPer)} next window`);
1999
+ label += pc3.dim(` \u2192 ${formatRate2(ask.pendingUsd, ask.pendingPer)} next window`);
1937
2000
  }
1938
2001
  return label;
1939
2002
  }
@@ -1945,7 +2008,7 @@ function formatListingRow(ask) {
1945
2008
  pc3.dim(ask.useCase === "sandbox" ? "sandbox" : "actions"),
1946
2009
  safeTerm(ask.size),
1947
2010
  safeTerm(ask.region ?? "-"),
1948
- formatRate(ask.usd, ask.per),
2011
+ formatRate2(ask.usd, ask.per),
1949
2012
  pc3.dim(`\xD7${ask.maxConcurrent}`),
1950
2013
  pc3.dim(expiry)
1951
2014
  ].join(" ");
@@ -1982,7 +2045,7 @@ function formatBook(book) {
1982
2045
  const where = ask.region ? safeTerm(ask.region) : "any region";
1983
2046
  const expiry = ask.expiresAt ? pc3.dim(ask.rollover ? ` renews ${ask.expiresAt}` : ` until ${ask.expiresAt}`) : "";
1984
2047
  lines.push(
1985
- ` ${lane(ask.useCase)} ${formatRate(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`
2048
+ ` ${lane(ask.useCase)} ${formatRate2(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`
1986
2049
  );
1987
2050
  }
1988
2051
  lines.push("");
@@ -1992,7 +2055,7 @@ function formatBook(book) {
1992
2055
  const where = bid.region ? safeTerm(bid.region) : "anywhere";
1993
2056
  const yours = bid.mine ? pc3.cyan(" (yours)") : "";
1994
2057
  lines.push(
1995
- ` ${lane(bid.useCase)} pays up to ${formatRate(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc3.dim(`posted ${bid.createdAt}`)}${yours}`
2058
+ ` ${lane(bid.useCase)} pays up to ${formatRate2(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc3.dim(`posted ${bid.createdAt}`)}${yours}`
1996
2059
  );
1997
2060
  }
1998
2061
  lines.push("");
@@ -2001,7 +2064,7 @@ function formatBook(book) {
2001
2064
  for (const fill of book.fills) {
2002
2065
  const statusNote = fill.status === "replaced" ? pc3.yellow(" replaced") : fill.status === "closed" ? pc3.gray(" closed") : "";
2003
2066
  lines.push(
2004
- ` ${pc3.dim(fill.id)} ${lane(fill.useCase)} ${formatRate(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? "-")} ${pc3.dim(fill.createdAt)}${statusNote}`
2067
+ ` ${pc3.dim(fill.id)} ${lane(fill.useCase)} ${formatRate2(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? "-")} ${pc3.dim(fill.createdAt)}${statusNote}`
2005
2068
  );
2006
2069
  }
2007
2070
  return lines.join("\n");
@@ -2064,7 +2127,7 @@ function parseTopupAmount(value) {
2064
2127
  return usd;
2065
2128
  }
2066
2129
  function formatCap(cap) {
2067
- return cap === null ? "No market cap \u2014 market-placed jobs need their own bid to fill." : `market cap ${formatRate(cap.usd, cap.per)}`;
2130
+ return cap === null ? "No market cap \u2014 market-placed jobs need their own bid to fill." : `market cap ${formatRate2(cap.usd, cap.per)}`;
2068
2131
  }
2069
2132
  function formatBidRow(bid) {
2070
2133
  const status = bid.status === "open" ? pc3.green("open") : bid.status === "filled" ? pc3.cyan("filled") : pc3.gray("cancelled");
@@ -2074,7 +2137,7 @@ function formatBidRow(bid) {
2074
2137
  pc3.dim(bid.useCase === "sandbox" ? "sandbox" : "actions"),
2075
2138
  safeTerm(bid.size),
2076
2139
  safeTerm(bid.region ?? "any region"),
2077
- `\u2264 ${formatRate(bid.maxUsd, bid.per)}`,
2140
+ `\u2264 ${formatRate2(bid.maxUsd, bid.per)}`,
2078
2141
  pc3.dim(bid.expiresAt ? `expires ${bid.expiresAt}` : "standing")
2079
2142
  ].join(" ");
2080
2143
  }
@@ -2104,7 +2167,7 @@ function formatPurchaseRow(p2) {
2104
2167
  cost.padStart(10),
2105
2168
  pc3.cyan(safeTerm(p2.sellerName)),
2106
2169
  pc3.dim(`${safeTerm(p2.provider)}/${safeTerm(p2.region ?? "any")}`),
2107
- formatRate(p2.usd, p2.per),
2170
+ formatRate2(p2.usd, p2.per),
2108
2171
  p2.secondsBilled !== null ? pc3.dim(`${p2.secondsBilled}s`) : "",
2109
2172
  p2.status === "replaced" ? pc3.yellow("replaced") : "",
2110
2173
  pc3.dim(p2.runId ? `run ${p2.runId}` : p2.sandboxId ? `sandbox ${p2.sandboxId}` : "")
@@ -2173,7 +2236,7 @@ function registerMarketCommands(program2) {
2173
2236
  listingPatchBody(listingId, { price: opts.price, per: opts.per })
2174
2237
  );
2175
2238
  output(opts, result, (r) => {
2176
- const rate = r.ask.pendingUsd !== null && r.ask.pendingPer !== null ? `${formatRate(r.ask.pendingUsd, r.ask.pendingPer)} ${pc3.dim("(applies next window)")}` : formatRate(r.ask.usd, r.ask.per);
2239
+ const rate = r.ask.pendingUsd !== null && r.ask.pendingPer !== null ? `${formatRate2(r.ask.pendingUsd, r.ask.pendingPer)} ${pc3.dim("(applies next window)")}` : formatRate2(r.ask.usd, r.ask.per);
2177
2240
  console.log(`repriced ${pc3.cyan(r.ask.id)} ${rate}`);
2178
2241
  });
2179
2242
  } catch (e) {
@@ -2495,25 +2558,151 @@ ${hints}`
2495
2558
  }
2496
2559
 
2497
2560
  // src/sandboxes.ts
2561
+ import * as fs from "fs";
2562
+ import * as os from "os";
2563
+ import * as path from "path";
2564
+ import * as readline from "readline";
2565
+ import { Readable } from "stream";
2498
2566
  import pc4 from "picocolors";
2567
+ import * as tar from "tar";
2568
+
2569
+ // src/current-instance.ts
2570
+ import { spawnSync as spawnSync2 } from "child_process";
2571
+ import { createHash } from "crypto";
2572
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
2573
+ import { homedir } from "os";
2574
+ import { join as join2 } from "path";
2575
+ function stateDir() {
2576
+ return process.env.BENCHSDK_STATE_DIR ?? join2(homedir(), ".benchsdk");
2577
+ }
2578
+ function statePath() {
2579
+ return join2(stateDir(), "current-instances.json");
2580
+ }
2581
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2582
+ function isUuid(value) {
2583
+ return value !== void 0 && UUID_RE.test(value);
2584
+ }
2585
+ function dirKey(cwd = process.cwd()) {
2586
+ const r = spawnSync2("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" });
2587
+ return r.status === 0 && r.stdout.trim() !== "" ? r.stdout.trim() : cwd;
2588
+ }
2589
+ function orgKey(opts) {
2590
+ const slug = opts.org || process.env.COMPUTE_ORG;
2591
+ if (slug) return `org:${slug}`;
2592
+ const key = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY;
2593
+ if (key) return `key:${createHash("sha256").update(key).digest("hex").slice(0, 12)}`;
2594
+ try {
2595
+ const raw = JSON.parse(readFileSync2(join2(stateDir(), "credentials.json"), "utf8"));
2596
+ const org2 = raw?.orgId ?? raw?.orgSlug;
2597
+ if (org2) return `org:${org2}`;
2598
+ } catch {
2599
+ }
2600
+ return "default";
2601
+ }
2602
+ function readStore() {
2603
+ try {
2604
+ const parsed = JSON.parse(readFileSync2(statePath(), "utf8"));
2605
+ if (typeof parsed !== "object" || parsed === null) return {};
2606
+ return parsed;
2607
+ } catch {
2608
+ return {};
2609
+ }
2610
+ }
2611
+ function writeStore(store) {
2612
+ mkdirSync2(stateDir(), { recursive: true });
2613
+ const tmp = `${statePath()}.${process.pid}.tmp`;
2614
+ writeFileSync2(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
2615
+ renameSync(tmp, statePath());
2616
+ }
2617
+ function withStoreLock(fn) {
2618
+ const lock = `${statePath()}.lock`;
2619
+ for (let attempt = 0; ; attempt++) {
2620
+ try {
2621
+ mkdirSync2(lock);
2622
+ break;
2623
+ } catch {
2624
+ if (attempt === 99) return fn();
2625
+ const until = Date.now() + 10;
2626
+ while (Date.now() < until) {
2627
+ }
2628
+ }
2629
+ }
2630
+ try {
2631
+ return fn();
2632
+ } finally {
2633
+ try {
2634
+ rmSync(lock, { recursive: true, force: true });
2635
+ } catch {
2636
+ }
2637
+ }
2638
+ }
2639
+ function setCurrentInstance(sandboxId, org2, dir = dirKey()) {
2640
+ withStoreLock(() => {
2641
+ const store = readStore();
2642
+ (store[dir] ?? (store[dir] = {}))[org2] = sandboxId;
2643
+ writeStore(store);
2644
+ });
2645
+ }
2646
+ function clearCurrentInstance(org2, dir = dirKey()) {
2647
+ return withStoreLock(() => {
2648
+ const store = readStore();
2649
+ const prev = store[dir]?.[org2];
2650
+ if (prev === void 0) return void 0;
2651
+ delete store[dir][org2];
2652
+ if (Object.keys(store[dir]).length === 0) delete store[dir];
2653
+ writeStore(store);
2654
+ return prev;
2655
+ });
2656
+ }
2657
+ function readFileCurrent(org2, dir = dirKey()) {
2658
+ return readStore()[dir]?.[org2];
2659
+ }
2660
+ function resolveInstanceId(arg, opts, dir = dirKey()) {
2661
+ if (isUuid(arg)) return { id: arg, source: "argument" };
2662
+ const env = process.env.COMPUTE_INSTANCE;
2663
+ if (env) return { id: env, source: "env" };
2664
+ const file = readFileCurrent(orgKey(opts), dir);
2665
+ if (file) return { id: file, source: "file", dir };
2666
+ return void 0;
2667
+ }
2668
+ function shortId(id) {
2669
+ return id.length > 8 ? `${id.slice(0, 4)}\u2026` : id;
2670
+ }
2671
+
2672
+ // src/sandboxes.ts
2499
2673
  function shellQuote(arg) {
2500
2674
  return `'${arg.replace(/'/g, `'\\''`)}'`;
2501
2675
  }
2502
- function printSandbox(s) {
2503
- const attach = "attach" in s ? s.attach : void 0;
2504
- console.log(`${pc4.cyan(s.id)} ${s.status} ${s.provider ?? "\u2014"} ${s.providerSandboxId ?? "\u2014"}`);
2505
- console.log(` label: ${s.label ?? "\u2014"} commands: ${s.commandCount} created: ${s.createdAt}`);
2676
+ function shortRate(rate) {
2677
+ return `${formatUsd(rateAllUnits(rate).perHour)}/h`;
2678
+ }
2679
+ function formatLocalTime(iso) {
2680
+ const d = new Date(iso);
2681
+ if (Number.isNaN(d.getTime())) return iso;
2682
+ const p2 = (n) => String(n).padStart(2, "0");
2683
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`;
2684
+ }
2685
+ function printSandbox(s, verbose = false) {
2686
+ const p2 = s.placement;
2687
+ console.log(
2688
+ `${pc4.cyan(s.id)} ${s.status} ${p2?.box?.provider ?? s.provider ?? "\u2014"} ${p2?.size ?? "\u2014"} ${p2 ? shortRate(p2.rate) : "\u2014"}`
2689
+ );
2690
+ if (s.label) {
2691
+ console.log(` label: ${s.label} created: ${formatLocalTime(s.createdAt)}`);
2692
+ }
2693
+ if (s.destroyError) console.log(` destroyError: ${pc4.red(s.destroyError)}`);
2694
+ if (!verbose) return;
2695
+ console.log(` providerSandboxId: ${s.providerSandboxId ?? "\u2014"} commands: ${s.commandCount}`);
2506
2696
  if (s.image !== void 0) {
2507
2697
  console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc4.dim(`(requested: ${s.requestedImage})`)}` : ""}`);
2508
2698
  }
2509
- if (s.destroyError) console.log(` destroyError: ${pc4.red(s.destroyError)}`);
2510
- if (s.placement) {
2511
- const p2 = s.placement;
2699
+ if (p2) {
2512
2700
  const box = p2.box ? ` / ${p2.box.sizeName ?? "custom"}${p2.box.resources ? ` (${p2.box.resources.cpus ?? "?"} vCPU / ${p2.box.resources.memoryMb ?? "?"} MB)` : ""}` : "";
2513
2701
  console.log(
2514
- ` provider: ${p2.box?.provider ?? s.provider ?? "\u2014"}${box} size: ${p2.size ?? "\u2014"} order: ${p2.orderType ?? "\u2014"} rate: ${formatUsdPer(p2.rate)}${p2.maxPrice ? ` max price: ${formatUsdPer(p2.maxPrice)}` : ""}`
2702
+ ` placement: ${p2.source}${box} order: ${p2.orderType ?? "\u2014"} rate: ${formatUsdPer(p2.rate)}${p2.maxPrice ? ` max price: ${formatUsdPer(p2.maxPrice)}` : ""}`
2515
2703
  );
2516
2704
  }
2705
+ const attach = "attach" in s ? s.attach : void 0;
2517
2706
  if (attach !== void 0) {
2518
2707
  console.log(
2519
2708
  attach === null ? " attach: none (market fill or ambient provider \u2014 platform drive only)" : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ""}`
@@ -2570,10 +2759,16 @@ var EXEC_LEAD_OPTS = [
2570
2759
  ];
2571
2760
  var SPAWN_LEAD_OPTS = [
2572
2761
  ...AUTH_LEAD_OPTS,
2762
+ { aliases: ["-q", "--quiet"], key: "quiet", flag: "bool" },
2573
2763
  { aliases: ["--cwd"], key: "cwd", flag: "value" },
2574
2764
  { aliases: ["-e", "--env"], key: "env", flag: "repeat" },
2575
2765
  { aliases: ["--stdin"], key: "stdin", flag: "bool" }
2576
2766
  ];
2767
+ var SERVE_LEAD_OPTS = [
2768
+ ...SPAWN_LEAD_OPTS,
2769
+ { aliases: ["--port"], key: "port", flag: "value" },
2770
+ { aliases: ["--timeout-ms"], key: "timeoutMs", flag: "value" }
2771
+ ];
2577
2772
  function takeLeadingOptions(argv, specs) {
2578
2773
  var _a;
2579
2774
  const byAlias = /* @__PURE__ */ new Map();
@@ -2631,33 +2826,103 @@ function mergeLeadOpts(opts, inline) {
2631
2826
  }
2632
2827
  return merged;
2633
2828
  }
2829
+ function checkQuietJson(opts) {
2830
+ if (opts.quiet && opts.json) throw new Error("--quiet and --json cannot be combined");
2831
+ }
2832
+ function emitResult(opts, data, quietLine, render) {
2833
+ if (opts.quiet) {
2834
+ console.log(quietLine(data));
2835
+ return;
2836
+ }
2837
+ output(opts, data, render);
2838
+ }
2839
+ var NO_INSTANCE_HINT = "No instance given. Pass an ID, run `compute instances use <id>`, or set COMPUTE_INSTANCE.";
2840
+ function resolveSandbox(argId, opts) {
2841
+ const r = resolveInstanceId(argId, opts);
2842
+ if (!r) throw new Error(NO_INSTANCE_HINT);
2843
+ if (r.source !== "argument" && !opts.json && !opts.quiet) {
2844
+ console.error(
2845
+ pc4.dim(
2846
+ `instance ${shortId(r.id)} (${r.source === "env" ? "COMPUTE_INSTANCE" : `current for ${r.dir}`})`
2847
+ )
2848
+ );
2849
+ }
2850
+ const org2 = orgKey(opts);
2851
+ return {
2852
+ id: r.id,
2853
+ clearStale: (error) => {
2854
+ if (r.source === "file" && error instanceof ActionsApiError && error.status === 404 && readFileCurrent(org2) === r.id) {
2855
+ clearCurrentInstance(org2);
2856
+ console.error(pc4.dim(`cleared stale current instance ${shortId(r.id)}`));
2857
+ }
2858
+ }
2859
+ };
2860
+ }
2861
+ function requireUuidOrImplicit(argId, opts) {
2862
+ if (argId !== void 0 && !isUuid(argId)) {
2863
+ throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
2864
+ }
2865
+ return resolveSandbox(argId, opts);
2866
+ }
2867
+ function resolveTwoArgTarget(argId, resourceId, opts, label) {
2868
+ if (resourceId === void 0) {
2869
+ if (argId === void 0) throw new Error(`missing ${label}`);
2870
+ return { resolved: resolveSandbox(void 0, opts), resource: argId };
2871
+ }
2872
+ if (argId !== void 0 && !isUuid(argId)) {
2873
+ throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
2874
+ }
2875
+ return { resolved: resolveSandbox(argId, opts), resource: resourceId };
2876
+ }
2877
+ function addCreateFlags(c) {
2878
+ return c.option("--order <providers>", 'provider order, comma-separated (e.g. "market,blaxel,vercel")').option("--size <size>", "platform size: small (1 vCPU/2 GB), medium, large, xlarge (8/16 GB); default medium").option("--label <label>", "label for the sandbox").option("--image <image>", "container image to boot").option("--snapshot-id <id>", "provider snapshot to resume").option("--cpus <n>", "CPU cores (raw resources \u2014 mutually exclusive with --size)").option("--memory-mb <n>", "memory in MB (raw resources)").option("--disk-mb <n>", "ephemeral disk in MB (raw resources)").option("--max-price <usd/unit>", "max price for a market fill (e.g. 0.12/hour); makes the create a limit order").option("--max-price-per <unit>", "unit for a bare --max-price usd (second, minute, or hour)").option("--market", 'place the create on the compute market (order type "market")').option("--order-type <type>", "explicit market order type: market or limit").option("--timeout-ms <ms>", "sandbox timeout in ms (provider minimums apply, e.g. blaxel \u22655m)").option("--secret <name>", "vault secret name to inject (repeatable)", (v, a) => a.concat(v), []);
2879
+ }
2880
+ function buildCreateBody(opts) {
2881
+ const resources = {};
2882
+ if (opts.cpus) resources.cpus = Number(opts.cpus);
2883
+ if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);
2884
+ if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);
2885
+ const body = {};
2886
+ if (opts.order) body.providerOrder = opts.order.split(",").map((s) => s.trim());
2887
+ if (opts.size) body.size = opts.size;
2888
+ if (opts.label) body.label = opts.label;
2889
+ if (opts.image) body.image = opts.image;
2890
+ if (opts.snapshotId) body.snapshotId = opts.snapshotId;
2891
+ if (opts.timeoutMs) body.timeoutMs = Number(opts.timeoutMs);
2892
+ if (opts.secret && opts.secret.length > 0) body.secrets = opts.secret;
2893
+ if (Object.keys(resources).length > 0) body.resources = resources;
2894
+ const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);
2895
+ if (maxPrice) body.maxPrice = { usd: maxPrice.usd, per: maxPrice.per };
2896
+ if (opts.orderType && opts.market) {
2897
+ throw new Error("--market and --order-type are mutually exclusive.");
2898
+ }
2899
+ if (opts.orderType) body.orderType = opts.orderType;
2900
+ if (opts.market) body.orderType = "market";
2901
+ return body;
2902
+ }
2903
+ function fmtTimeout(ms) {
2904
+ if (ms % 36e5 === 0) return `${ms / 36e5}h`;
2905
+ if (ms % 6e4 === 0) return `${ms / 6e4}m`;
2906
+ if (ms % 1e3 === 0) return `${ms / 1e3}s`;
2907
+ return `${ms}ms`;
2908
+ }
2909
+ var PLATFORM_DEFAULT_TIMEOUT_MS = 30 * 6e4;
2634
2910
  function registerSandboxesCommands(program2) {
2635
2911
  const cmd = program2.command("instances").alias("sandboxes").alias("sbx").description("Create and drive compute instances through the platform").enablePositionalOptions().configureOutput({ outputError: usageErrorOutput });
2636
- cmd.command("create").description('Place a sandbox (provider order walks 1,2,3; "market" bids first)').option("--order <providers>", 'provider order, comma-separated (e.g. "market,blaxel,vercel")').option("--size <size>", "platform size: small (1 vCPU/2 GB), medium, large, xlarge (8/16 GB); default medium").option("--label <label>", "label for the sandbox").option("--image <image>", "container image to boot").option("--snapshot-id <id>", "provider snapshot to resume").option("--cpus <n>", "CPU cores (raw resources \u2014 mutually exclusive with --size)").option("--memory-mb <n>", "memory in MB (raw resources)").option("--disk-mb <n>", "ephemeral disk in MB (raw resources)").option("--max-price <usd/unit>", "max price for a market fill (e.g. 0.12/hour); makes the create a limit order").option("--max-price-per <unit>", "unit for a bare --max-price usd (second, minute, or hour)").option("--market", 'place the create on the compute market (order type "market")').option("--order-type <type>", "explicit market order type: market or limit").option("--timeout-ms <ms>", "sandbox timeout in ms (provider minimums apply, e.g. blaxel \u22655m)").option("--secret <name>", "vault secret name to inject (repeatable)", (v, a) => a.concat(v), []).option("--api-key <key>", "platform API key (or COMPUTE_API_KEY)").option("--base-url <url>", "platform base URL").option("--allow-untrusted-host", "allow non-computesdk.com base URLs").option("--json", "print the raw response").action(async (opts) => {
2912
+ addCreateFlags(
2913
+ cmd.command("create").description('Place a sandbox (provider order walks 1,2,3; "market" bids first)')
2914
+ ).option("--no-use", "do not mark the new instance as this directory's current instance").option("-q, --quiet", "print only the new instance ID").option("--verbose", "print the full instance details").option("--api-key <key>", "platform API key (or COMPUTE_API_KEY)").option("--base-url <url>", "platform base URL").option("--allow-untrusted-host", "allow non-computesdk.com base URLs").option("--json", "print the raw response").action(async (opts) => {
2637
2915
  try {
2916
+ checkQuietJson(opts);
2638
2917
  const c = await client(opts);
2639
- const resources = {};
2640
- if (opts.cpus) resources.cpus = Number(opts.cpus);
2641
- if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);
2642
- if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);
2643
- const body = {};
2644
- if (opts.order) body.providerOrder = opts.order.split(",").map((s) => s.trim());
2645
- if (opts.size) body.size = opts.size;
2646
- if (opts.label) body.label = opts.label;
2647
- if (opts.image) body.image = opts.image;
2648
- if (opts.snapshotId) body.snapshotId = opts.snapshotId;
2649
- if (opts.timeoutMs) body.timeoutMs = Number(opts.timeoutMs);
2650
- if (opts.secret && opts.secret.length > 0) body.secrets = opts.secret;
2651
- if (Object.keys(resources).length > 0) body.resources = resources;
2652
- const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);
2653
- if (maxPrice) body.maxPrice = { usd: maxPrice.usd, per: maxPrice.per };
2654
- if (opts.orderType && opts.market) {
2655
- throw new Error("--market and --order-type are mutually exclusive.");
2918
+ const res = await c.post("/api/v1/sandboxes", buildCreateBody(opts));
2919
+ if (opts.use !== false) {
2920
+ setCurrentInstance(res.sandbox.id, orgKey(opts));
2921
+ if (!opts.json && !opts.quiet) {
2922
+ console.error(pc4.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));
2923
+ }
2656
2924
  }
2657
- if (opts.orderType) body.orderType = opts.orderType;
2658
- if (opts.market) body.orderType = "market";
2659
- const res = await c.post("/api/v1/sandboxes", body);
2660
- output(opts, res.sandbox, printSandbox);
2925
+ emitResult(opts, res.sandbox, (s) => s.id, (s) => printSandbox(s, opts.verbose));
2661
2926
  } catch (e) {
2662
2927
  fail(e, opts);
2663
2928
  }
@@ -2691,54 +2956,165 @@ function registerSandboxesCommands(program2) {
2691
2956
  fail(e, opts);
2692
2957
  }
2693
2958
  });
2694
- cmd.command("list").description("List sandboxes").option("--status <status>", "creating | running | destroyed").option("--limit <n>", "page size").option("--cursor <cursor>", "page cursor from a previous response").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (opts) => {
2959
+ cmd.command("list").description("List sandboxes").option("--status <status>", "creating | running | destroyed").option("--limit <n>", "page size").option("--cursor <cursor>", "page cursor from a previous response").option("-q, --quiet", "print only instance IDs, one per line").option("--verbose", "print the full instance details").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (opts) => {
2695
2960
  try {
2961
+ checkQuietJson(opts);
2696
2962
  const c = await client(opts);
2697
2963
  const res = await c.get(
2698
2964
  "/api/v1/sandboxes",
2699
2965
  { status: opts.status, limit: opts.limit, cursor: opts.cursor }
2700
2966
  );
2701
- output(opts, res, (page) => {
2702
- page.sandboxes.forEach(printSandbox);
2703
- if (page.nextCursor) console.log(pc4.dim(`nextCursor: ${page.nextCursor}`));
2704
- });
2967
+ emitResult(
2968
+ opts,
2969
+ res,
2970
+ (page) => page.sandboxes.map((s) => s.id).join("\n"),
2971
+ (page) => {
2972
+ page.sandboxes.forEach((s) => printSandbox(s, opts.verbose));
2973
+ if (page.nextCursor) console.log(pc4.dim(`nextCursor: ${page.nextCursor}`));
2974
+ }
2975
+ );
2705
2976
  } catch (e) {
2706
2977
  fail(e, opts);
2707
2978
  }
2708
2979
  });
2709
- cmd.command("get <sandboxId>").description("Show one sandbox (includes the BYOK attach descriptor)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, opts) => {
2980
+ cmd.command("get [sandboxId]").description("Show one sandbox (includes the BYOK attach descriptor)").option("--verbose", "print the full instance details").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2710
2981
  try {
2982
+ checkQuietJson(opts);
2983
+ const resolved = requireUuidOrImplicit(argId, opts);
2711
2984
  const c = await client(opts);
2712
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}`);
2713
- output(opts, res.sandbox, printSandbox);
2985
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}`);
2986
+ output(opts, res.sandbox, (s) => printSandbox(s, opts.verbose));
2987
+ } catch (e) {
2988
+ fail(e, opts);
2989
+ }
2990
+ });
2991
+ cmd.command("use [sandboxId]").description("Show or set this directory's current instance (COMPUTE_INSTANCE always wins)").option("--clear", "forget this directory's current instance").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2992
+ try {
2993
+ const org2 = orgKey(opts);
2994
+ if (opts.clear) {
2995
+ const prev = clearCurrentInstance(org2);
2996
+ output(
2997
+ opts,
2998
+ { cleared: prev ?? null },
2999
+ () => console.log(
3000
+ prev ? `forgot ${shortId(prev)} (was current for ${dirKey()})` : "nothing to forget"
3001
+ )
3002
+ );
3003
+ return;
3004
+ }
3005
+ if (argId === void 0) {
3006
+ const r = resolveInstanceId(void 0, opts);
3007
+ output(opts, { id: r?.id ?? null, source: r?.source ?? null }, () => {
3008
+ if (!r) console.log(NO_INSTANCE_HINT);
3009
+ else {
3010
+ const where = r.source === "env" ? "COMPUTE_INSTANCE" : `current for ${r.dir}`;
3011
+ console.log(`instance ${shortId(r.id)} (${where})`);
3012
+ }
3013
+ });
3014
+ return;
3015
+ }
3016
+ if (!isUuid(argId)) {
3017
+ throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3018
+ }
3019
+ const c = await client(opts);
3020
+ const res = await c.get(`/api/v1/sandboxes/${argId}`);
3021
+ if (res.sandbox.status === "destroyed") {
3022
+ throw new Error(`instance ${shortId(argId)} is destroyed \u2014 pick a running instance`);
3023
+ }
3024
+ setCurrentInstance(argId, org2);
3025
+ output(
3026
+ opts,
3027
+ { id: argId, dir: dirKey() },
3028
+ () => console.log(`instance ${shortId(argId)} (current for ${dirKey()})`)
3029
+ );
2714
3030
  } catch (e) {
2715
3031
  fail(e, opts);
2716
3032
  }
2717
3033
  });
2718
- cmd.command("destroy <sandboxId>").description("Destroy a sandbox (verified teardown + cost settle)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, opts) => {
3034
+ cmd.command("destroy [sandboxId]").description("Destroy a sandbox (verified teardown + cost settle)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2719
3035
  try {
3036
+ const resolved = requireUuidOrImplicit(argId, opts);
2720
3037
  const c = await client(opts);
2721
- const res = await c.del(`/api/v1/sandboxes/${sandboxId}`);
3038
+ const res = await c.del(`/api/v1/sandboxes/${resolved.id}`).catch((e) => {
3039
+ resolved.clearStale(e);
3040
+ throw e;
3041
+ });
3042
+ const org2 = orgKey(opts);
3043
+ if (readFileCurrent(org2) === resolved.id) {
3044
+ clearCurrentInstance(org2);
3045
+ if (!opts.json) {
3046
+ console.error(pc4.dim(`cleared current instance ${shortId(resolved.id)}`));
3047
+ }
3048
+ }
2722
3049
  output(opts, res.sandbox, printSandbox);
2723
3050
  } catch (e) {
2724
3051
  fail(e, opts);
2725
3052
  }
2726
3053
  });
2727
- cmd.command("exec <sandboxId> <command...>").description("Run a one-shot command and print its result (options before the command; -- also works)").option("--timeout-ms <ms>", "command timeout in ms").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (sandboxId, rawCommand, rawOpts) => {
3054
+ addCreateFlags(
3055
+ cmd.command("run [command...]").description(
3056
+ "Create an instance, run a command on it, and tear it down. `run -- <cmd>` waits and destroys; `--keep` waits and keeps; `-d` returns immediately."
3057
+ )
3058
+ ).option("--keep", "keep the instance after the command exits (it becomes this directory's current instance)").option("-d, --detach", "start the command and return immediately (instance becomes current)").option("--yes", "non-interactive: Ctrl-C destroys without asking").option("-q, --quiet", "with --detach, print only the instance ID").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (rawCommand, rawOpts) => {
2728
3059
  let opts = rawOpts;
2729
3060
  try {
3061
+ checkQuietJson(opts);
3062
+ if (opts.keep && opts.detach) throw new Error("--keep and --detach are mutually exclusive.");
2730
3063
  const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
2731
3064
  opts = mergeLeadOpts(rawOpts, lead.inline);
2732
3065
  const command = lead.command;
2733
3066
  if (command.length === 0) throw new Error("missing command to run");
3067
+ await runInstanceCommand(command, opts);
3068
+ } catch (e) {
3069
+ fail(e, opts);
3070
+ }
3071
+ });
3072
+ cmd.command("serve [sandboxId] [command...]").description("Start a server, wait for its port to listen publicly, and print the URL").option("--port <n>", "the TCP port the server listens on (required)").option("--cwd <dir>", "working directory").option("-e, --env <key=value>", "environment variable (repeatable)", (v, a) => a.concat(v), []).option("--timeout-ms <ms>", "give up waiting for the port after this (default 120000)").option("-q, --quiet", "print only the URL").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (argId, rawCommand, rawOpts) => {
3073
+ let opts = rawOpts;
3074
+ try {
3075
+ checkQuietJson(opts);
3076
+ if (argId !== void 0 && !isUuid(argId)) {
3077
+ rawCommand.unshift(argId);
3078
+ argId = void 0;
3079
+ }
3080
+ const lead = takeLeadingOptions(rawCommand, SERVE_LEAD_OPTS);
3081
+ opts = mergeLeadOpts(rawOpts, lead.inline);
3082
+ const command = lead.command;
3083
+ if (command.length === 0) throw new Error("missing command to serve");
3084
+ if (opts.port === void 0) throw new Error("--port is required");
3085
+ const port = Number(opts.port);
3086
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3087
+ throw new Error("--port must be an integer between 1 and 65535");
3088
+ }
3089
+ const resolved = resolveSandbox(argId, opts);
3090
+ await serveInstanceCommand(resolved.id, command, port, opts);
3091
+ } catch (e) {
3092
+ fail(e, opts);
3093
+ }
3094
+ });
3095
+ cmd.command("exec [sandboxId] [command...]").description("Run a one-shot command and print its result (options before the command; -- also works)").option("--timeout-ms <ms>", "command timeout in ms").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (argId, rawCommand, rawOpts) => {
3096
+ let opts = rawOpts;
3097
+ try {
3098
+ if (argId !== void 0 && !isUuid(argId)) {
3099
+ rawCommand.unshift(argId);
3100
+ argId = void 0;
3101
+ }
3102
+ const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
3103
+ opts = mergeLeadOpts(rawOpts, lead.inline);
3104
+ const command = lead.command;
3105
+ if (command.length === 0) throw new Error("missing command to run");
3106
+ const resolved = resolveSandbox(argId, opts);
2734
3107
  const c = await client(opts);
2735
3108
  const res = await c.post(
2736
- `/api/v1/sandboxes/${sandboxId}/commands`,
3109
+ `/api/v1/sandboxes/${resolved.id}/commands`,
2737
3110
  {
2738
3111
  command: command.map(shellQuote).join(" "),
2739
3112
  ...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
2740
3113
  }
2741
- );
3114
+ ).catch((e) => {
3115
+ resolved.clearStale(e);
3116
+ throw e;
3117
+ });
2742
3118
  output(opts, res, (r) => {
2743
3119
  process.stdout.write(r.stdout);
2744
3120
  if (r.stderr) process.stderr.write(r.stderr);
@@ -2749,48 +3125,59 @@ function registerSandboxesCommands(program2) {
2749
3125
  fail(e, opts);
2750
3126
  }
2751
3127
  });
2752
- cmd.command("spawn <sandboxId> <command...>").description("Start a detached process that outlives this request (options before the command; -- also works)").option("--cwd <dir>", "working directory").option("-e, --env <key=value>", "environment variable (repeatable)", (v, a) => a.concat(v), []).option("--stdin", "keep the process's stdin pipe open for `stdin`/`close-stdin`").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (sandboxId, rawCommand, rawOpts) => {
3128
+ cmd.command("spawn [sandboxId] [command...]").description("Start a detached process that outlives this request (options before the command; -- also works)").option("--cwd <dir>", "working directory").option("-e, --env <key=value>", "environment variable (repeatable)", (v, a) => a.concat(v), []).option("--stdin", "keep the process's stdin pipe open for `stdin`/`close-stdin`").option("-q, --quiet", "print only the job ID").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (argId, rawCommand, rawOpts) => {
2753
3129
  let opts = rawOpts;
2754
3130
  try {
3131
+ if (argId !== void 0 && !isUuid(argId)) {
3132
+ rawCommand.unshift(argId);
3133
+ argId = void 0;
3134
+ }
2755
3135
  const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);
2756
3136
  opts = mergeLeadOpts(rawOpts, lead.inline);
3137
+ checkQuietJson(opts);
2757
3138
  const command = lead.command;
2758
3139
  if (command.length === 0) throw new Error("missing command to spawn");
3140
+ const resolved = resolveSandbox(argId, opts);
2759
3141
  const c = await client(opts);
2760
3142
  const res = await c.post(
2761
- `/api/v1/sandboxes/${sandboxId}/processes`,
3143
+ `/api/v1/sandboxes/${resolved.id}/processes`,
2762
3144
  {
2763
3145
  command: command.map(shellQuote).join(" "),
2764
3146
  ...opts.cwd ? { cwd: opts.cwd } : {},
2765
3147
  ...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
2766
3148
  ...opts.stdin ? { stdin: true } : {}
2767
3149
  }
2768
- );
2769
- output(opts, res.process, printProcess);
3150
+ ).catch((e) => {
3151
+ resolved.clearStale(e);
3152
+ throw e;
3153
+ });
3154
+ emitResult(opts, res.process, (p2) => p2.jobId, printProcess);
2770
3155
  } catch (e) {
2771
3156
  fail(e, opts);
2772
3157
  }
2773
3158
  });
2774
- cmd.command("ps <sandboxId>").description("List the sandbox's tracked processes").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, opts) => {
3159
+ cmd.command("ps [sandboxId]").description("List the sandbox's tracked processes").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2775
3160
  try {
3161
+ const resolved = requireUuidOrImplicit(argId, opts);
2776
3162
  const c = await client(opts);
2777
3163
  const res = await c.get(
2778
- `/api/v1/sandboxes/${sandboxId}/processes`
3164
+ `/api/v1/sandboxes/${resolved.id}/processes`
2779
3165
  );
2780
3166
  output(opts, res.processes, (list) => list.forEach(printProcess));
2781
3167
  } catch (e) {
2782
3168
  fail(e, opts);
2783
3169
  }
2784
3170
  });
2785
- cmd.command("logs <sandboxId> <jobId>").description("Show a process's buffered output (--follow streams until exit)").option("-f, --follow", "stream output until the process exits").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, jobId, opts) => {
3171
+ cmd.command("logs [jobOrSandboxId] [jobId]").description("Show a process's buffered output (--follow streams until exit)").option("-f, --follow", "stream output until the process exits").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, jobId, opts) => {
2786
3172
  try {
3173
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2787
3174
  const c = await client(opts);
2788
3175
  if (opts.follow) {
2789
- await followProcess(c, sandboxId, jobId);
3176
+ await followProcess(c, resolved.id, job);
2790
3177
  return;
2791
3178
  }
2792
3179
  const res = await c.get(
2793
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`
3180
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}`
2794
3181
  );
2795
3182
  output(opts, res.process, (p2) => {
2796
3183
  if (p2.stdout) process.stdout.write(p2.stdout);
@@ -2801,11 +3188,12 @@ function registerSandboxesCommands(program2) {
2801
3188
  fail(e, opts);
2802
3189
  }
2803
3190
  });
2804
- cmd.command("wait <sandboxId> <jobId>").description("Block until a process exits").option("--timeout-ms <ms>", "bound the wait (job keeps running on timeout)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, jobId, opts) => {
3191
+ cmd.command("wait [jobOrSandboxId] [jobId]").description("Block until a process exits").option("--timeout-ms <ms>", "bound the wait (job keeps running on timeout)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, jobId, opts) => {
2805
3192
  try {
3193
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2806
3194
  const c = await client(opts);
2807
3195
  const res = await c.post(
2808
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,
3196
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/wait`,
2809
3197
  opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
2810
3198
  );
2811
3199
  output(opts, res.process, printProcess);
@@ -2816,11 +3204,12 @@ function registerSandboxesCommands(program2) {
2816
3204
  fail(e, opts);
2817
3205
  }
2818
3206
  });
2819
- cmd.command("kill <sandboxId> <jobId>").description("Signal a process (default SIGTERM)").option("--signal <signal>", "signal name or number, e.g. SIGKILL or 9").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, jobId, opts) => {
3207
+ cmd.command("kill [jobOrSandboxId] [jobId]").description("Signal a process (default SIGTERM)").option("--signal <signal>", "signal name or number, e.g. SIGKILL or 9").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, jobId, opts) => {
2820
3208
  try {
3209
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2821
3210
  const c = await client(opts);
2822
3211
  const res = await c.post(
2823
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,
3212
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/kill`,
2824
3213
  opts.signal ? { signal: opts.signal } : {}
2825
3214
  );
2826
3215
  output(opts, res.process, printProcess);
@@ -2828,18 +3217,19 @@ function registerSandboxesCommands(program2) {
2828
3217
  fail(e, opts);
2829
3218
  }
2830
3219
  });
2831
- cmd.command("stdin <sandboxId> <jobId>").description("Write to a process's stdin pipe (spawn with --stdin; --data, --file, or piped)").option("--data <text>", "data to write").option("--file <local>", "read data from a local file").option("--base64", "base64-encode the input before sending (binary-safe)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, jobId, opts) => {
3220
+ cmd.command("stdin [jobOrSandboxId] [jobId]").description("Write to a process's stdin pipe (spawn with --stdin; --data, --file, or piped)").option("--data <text>", "data to write").option("--file <local>", "read data from a local file").option("--base64", "base64-encode the input before sending (binary-safe)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, jobId, opts) => {
2832
3221
  try {
3222
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2833
3223
  let data = opts.data;
2834
3224
  if (data === void 0 && opts.file) {
2835
3225
  const { readFile } = await import("fs/promises");
2836
3226
  data = opts.base64 ? (await readFile(opts.file)).toString("base64") : await readFile(opts.file, "utf8");
2837
3227
  }
2838
3228
  if (data === void 0 && !process.stdin.isTTY) {
2839
- const piped = await new Promise((resolve) => {
3229
+ const piped = await new Promise((resolve2) => {
2840
3230
  const chunks = [];
2841
3231
  process.stdin.on("data", (chunk) => chunks.push(chunk));
2842
- process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
3232
+ process.stdin.on("end", () => resolve2(Buffer.concat(chunks)));
2843
3233
  });
2844
3234
  data = opts.base64 ? piped.toString("base64") : piped.toString("utf8");
2845
3235
  }
@@ -2852,31 +3242,42 @@ function registerSandboxesCommands(program2) {
2852
3242
  }
2853
3243
  const c = await client(opts);
2854
3244
  const res = await c.post(
2855
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/stdin`,
3245
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/stdin`,
2856
3246
  { data, ...opts.base64 ? { encoding: "base64" } : {} }
2857
3247
  );
2858
- output(opts, res, () => console.log(`wrote ${data.length} chars to ${jobId}`));
3248
+ output(opts, res, () => console.log(`wrote ${data.length} chars to ${job}`));
2859
3249
  } catch (e) {
2860
3250
  fail(e, opts);
2861
3251
  }
2862
3252
  });
2863
- cmd.command("close-stdin <sandboxId> <jobId>").description("Close a process's stdin pipe").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, jobId, opts) => {
3253
+ cmd.command("close-stdin [jobOrSandboxId] [jobId]").description("Close a process's stdin pipe").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, jobId, opts) => {
2864
3254
  try {
3255
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2865
3256
  const c = await client(opts);
2866
3257
  const res = await c.post(
2867
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/close-stdin`,
3258
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/close-stdin`,
2868
3259
  {}
2869
3260
  );
2870
- output(opts, res, () => console.log(`closed stdin on ${jobId}`));
3261
+ output(opts, res, () => console.log(`closed stdin on ${job}`));
2871
3262
  } catch (e) {
2872
3263
  fail(e, opts);
2873
3264
  }
2874
3265
  });
2875
- cmd.command("ls <sandboxId> [path]").description("List a directory (or stat a path) inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, path, opts) => {
3266
+ cmd.command("ls [pathOrSandboxId] [path]").description("List a directory (or stat a path) inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path2, opts) => {
2876
3267
  try {
3268
+ let resolved;
3269
+ let p2;
3270
+ if (argId !== void 0 && !isUuid(argId)) {
3271
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3272
+ resolved = resolveSandbox(void 0, opts);
3273
+ p2 = argId;
3274
+ } else {
3275
+ resolved = resolveSandbox(argId, opts);
3276
+ p2 = path2 ?? "/";
3277
+ }
2877
3278
  const c = await client(opts);
2878
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/files`, {
2879
- path: path ?? "/"
3279
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, {
3280
+ path: p2
2880
3281
  });
2881
3282
  output(opts, res, (view) => {
2882
3283
  if (view.type === "directory") {
@@ -2891,10 +3292,21 @@ function registerSandboxesCommands(program2) {
2891
3292
  fail(e, opts);
2892
3293
  }
2893
3294
  });
2894
- cmd.command("cat <sandboxId> <path>").description("Print a file's contents").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, path, opts) => {
3295
+ cmd.command("cat [pathOrSandboxId] [path]").description("Print a file's contents").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path2, opts) => {
2895
3296
  try {
3297
+ let resolved;
3298
+ let p2;
3299
+ if (argId !== void 0 && !isUuid(argId)) {
3300
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3301
+ resolved = resolveSandbox(void 0, opts);
3302
+ p2 = argId;
3303
+ } else {
3304
+ resolved = resolveSandbox(argId, opts);
3305
+ if (path2 === void 0) throw new Error("missing path");
3306
+ p2 = path2;
3307
+ }
2896
3308
  const c = await client(opts);
2897
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/files`, { path });
3309
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, { path: p2 });
2898
3310
  output(opts, res, (view) => {
2899
3311
  if (view.type !== "file") {
2900
3312
  console.error(pc4.red(`${view.path} is a directory`));
@@ -2907,19 +3319,30 @@ function registerSandboxesCommands(program2) {
2907
3319
  fail(e, opts);
2908
3320
  }
2909
3321
  });
2910
- cmd.command("write <sandboxId> <path>").description("Write a file inside the sandbox (--content or --file <local>, else stdin)").option("--content <text>", "file contents").option("--file <local>", "read contents from a local file").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, path, opts) => {
3322
+ cmd.command("write [pathOrSandboxId] [path]").description("Write a file inside the sandbox (--content or --file <local>, else stdin)").option("--content <text>", "file contents").option("--file <local>", "read contents from a local file").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path2, opts) => {
2911
3323
  try {
3324
+ let resolved;
3325
+ let p2;
3326
+ if (argId !== void 0 && !isUuid(argId)) {
3327
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3328
+ resolved = resolveSandbox(void 0, opts);
3329
+ p2 = argId;
3330
+ } else {
3331
+ resolved = resolveSandbox(argId, opts);
3332
+ if (path2 === void 0) throw new Error("missing path");
3333
+ p2 = path2;
3334
+ }
2912
3335
  let content = opts.content;
2913
3336
  if (content === void 0 && opts.file) {
2914
3337
  const { readFile } = await import("fs/promises");
2915
3338
  content = await readFile(opts.file, "utf8");
2916
3339
  }
2917
3340
  if (content === void 0 && !process.stdin.isTTY) {
2918
- content = await new Promise((resolve) => {
3341
+ content = await new Promise((resolve2) => {
2919
3342
  let data = "";
2920
3343
  process.stdin.setEncoding("utf8");
2921
3344
  process.stdin.on("data", (chunk) => data += chunk);
2922
- process.stdin.on("end", () => resolve(data));
3345
+ process.stdin.on("end", () => resolve2(data));
2923
3346
  });
2924
3347
  }
2925
3348
  if (content === void 0) {
@@ -2928,19 +3351,30 @@ function registerSandboxesCommands(program2) {
2928
3351
  }
2929
3352
  const c = await client(opts);
2930
3353
  const res = await c.post(
2931
- `/api/v1/sandboxes/${sandboxId}/files`,
2932
- { path, content }
3354
+ `/api/v1/sandboxes/${resolved.id}/files`,
3355
+ { path: p2, content }
2933
3356
  );
2934
3357
  output(opts, res, (r) => console.log(`wrote ${r.path}`));
2935
3358
  } catch (e) {
2936
3359
  fail(e, opts);
2937
3360
  }
2938
3361
  });
2939
- cmd.command("mkdir <sandboxId> <path>").description("Create a directory (parents included)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, path, opts) => {
3362
+ cmd.command("mkdir [pathOrSandboxId] [path]").description("Create a directory (parents included)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path2, opts) => {
2940
3363
  try {
3364
+ let resolved;
3365
+ let p2;
3366
+ if (argId !== void 0 && !isUuid(argId)) {
3367
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3368
+ resolved = resolveSandbox(void 0, opts);
3369
+ p2 = argId;
3370
+ } else {
3371
+ resolved = resolveSandbox(argId, opts);
3372
+ if (path2 === void 0) throw new Error("missing path");
3373
+ p2 = path2;
3374
+ }
2941
3375
  const c = await client(opts);
2942
- const res = await c.post(`/api/v1/sandboxes/${sandboxId}/files`, {
2943
- path,
3376
+ const res = await c.post(`/api/v1/sandboxes/${resolved.id}/files`, {
3377
+ path: p2,
2944
3378
  mkdir: true
2945
3379
  });
2946
3380
  output(opts, res, (r) => console.log(`created ${r.path}`));
@@ -2948,45 +3382,68 @@ function registerSandboxesCommands(program2) {
2948
3382
  fail(e, opts);
2949
3383
  }
2950
3384
  });
2951
- cmd.command("rm <sandboxId> <path>").description("Remove a file or directory inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, path, opts) => {
3385
+ cmd.command("rm [pathOrSandboxId] [path]").description("Remove a file or directory inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path2, opts) => {
2952
3386
  try {
3387
+ let resolved;
3388
+ let p2;
3389
+ if (argId !== void 0 && !isUuid(argId)) {
3390
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3391
+ resolved = resolveSandbox(void 0, opts);
3392
+ p2 = argId;
3393
+ } else {
3394
+ resolved = resolveSandbox(argId, opts);
3395
+ if (path2 === void 0) throw new Error("missing path");
3396
+ p2 = path2;
3397
+ }
2953
3398
  const c = await client(opts);
2954
3399
  const res = await c.del(
2955
- `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`
3400
+ `/api/v1/sandboxes/${resolved.id}/files?path=${encodeURIComponent(p2)}`
2956
3401
  );
2957
3402
  output(opts, res, (r) => console.log(`removed ${r.path}`));
2958
3403
  } catch (e) {
2959
3404
  fail(e, opts);
2960
3405
  }
2961
3406
  });
2962
- cmd.command("url <sandboxId>").description("Resolve the provider's public URL for a port").requiredOption("--port <n>", "port the service listens on").option("--protocol <protocol>", "protocol (default provider-chosen)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, opts) => {
3407
+ cmd.command("cp <src> <dst>").description("Copy files/dirs between here and an instance \u2014 remote side is [id:]/abs/path").option("-q, --quiet", "print nothing on success").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--org <slug>").option("--json", "print the raw response").action(async (src, dst, opts) => {
3408
+ try {
3409
+ checkQuietJson(opts);
3410
+ await cpCommand(src, dst, opts);
3411
+ } catch (e) {
3412
+ fail(e, opts);
3413
+ }
3414
+ });
3415
+ cmd.command("url [sandboxId]").description("Resolve the provider's public URL for a port").requiredOption("--port <n>", "port the service listens on").option("--protocol <protocol>", "protocol (default provider-chosen)").option("-q, --quiet", "print only the URL (the default)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2963
3416
  try {
3417
+ checkQuietJson(opts);
3418
+ const resolved = requireUuidOrImplicit(argId, opts);
2964
3419
  const c = await client(opts);
2965
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/urls`, {
3420
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/urls`, {
2966
3421
  port: opts.port,
2967
3422
  protocol: opts.protocol
2968
3423
  });
2969
- output(opts, res, (r) => console.log(safeTerm(r.url)));
3424
+ emitResult(opts, res, (r) => safeTerm(r.url), (r) => console.log(safeTerm(r.url)));
2970
3425
  } catch (e) {
2971
3426
  fail(e, opts);
2972
3427
  }
2973
3428
  });
2974
- cmd.command("snapshots <sandboxId>").description("List the sandbox's snapshots").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, opts) => {
3429
+ cmd.command("snapshots [sandboxId]").description("List the sandbox's snapshots").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2975
3430
  try {
3431
+ const resolved = requireUuidOrImplicit(argId, opts);
2976
3432
  const c = await client(opts);
2977
3433
  const res = await c.get(
2978
- `/api/v1/sandboxes/${sandboxId}/snapshots`
3434
+ `/api/v1/sandboxes/${resolved.id}/snapshots`
2979
3435
  );
2980
3436
  output(opts, res.snapshots, (list) => list.forEach(printSnapshot));
2981
3437
  } catch (e) {
2982
3438
  fail(e, opts);
2983
3439
  }
2984
3440
  });
2985
- cmd.command("snapshot <sandboxId>").description("Snapshot a running sandbox through its provider").option("--label <label>", "label for the snapshot").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, opts) => {
3441
+ cmd.command("snapshot [sandboxId]").description("Snapshot a running sandbox through its provider").option("--label <label>", "label for the snapshot").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, opts) => {
2986
3442
  try {
3443
+ const resolved = requireUuidOrImplicit(argId, opts);
2987
3444
  const c = await client(opts);
2988
3445
  const res = await c.post(
2989
- `/api/v1/sandboxes/${sandboxId}/snapshots`,
3446
+ `/api/v1/sandboxes/${resolved.id}/snapshots`,
2990
3447
  opts.label ? { label: opts.label } : {}
2991
3448
  );
2992
3449
  output(opts, res.snapshot, printSnapshot);
@@ -2994,13 +3451,14 @@ function registerSandboxesCommands(program2) {
2994
3451
  fail(e, opts);
2995
3452
  }
2996
3453
  });
2997
- cmd.command("snapshot-delete <sandboxId> <snapshotId>").description("Delete a snapshot's provider artifact").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (sandboxId, snapshotId, opts) => {
3454
+ cmd.command("snapshot-delete [snapOrSandboxId] [snapshotId]").description("Delete a snapshot's provider artifact").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, snapshotId, opts) => {
2998
3455
  try {
3456
+ const { resolved, resource: snap } = resolveTwoArgTarget(argId, snapshotId, opts, "snapshotId");
2999
3457
  const c = await client(opts);
3000
3458
  const res = await c.del(
3001
- `/api/v1/sandboxes/${sandboxId}/snapshots/${snapshotId}`
3459
+ `/api/v1/sandboxes/${resolved.id}/snapshots/${snap}`
3002
3460
  );
3003
- output(opts, res, () => console.log(`deleted snapshot ${snapshotId}`));
3461
+ output(opts, res, () => console.log(`deleted snapshot ${snap}`));
3004
3462
  } catch (e) {
3005
3463
  fail(e, opts);
3006
3464
  }
@@ -3038,12 +3496,353 @@ async function followProcess(c, sandboxId, jobId) {
3038
3496
  if (exitCode !== 0) process.exitCode = exitCode;
3039
3497
  }
3040
3498
  }
3499
+ function printDetachSummary(sandboxId, jobId, timeoutText) {
3500
+ console.log(`instance ${sandboxId} job ${jobId} (running; ${timeoutText})`);
3501
+ console.log(` follow: compute instances logs ${sandboxId} ${jobId}`);
3502
+ console.log(` wait: compute instances wait ${sandboxId} ${jobId}`);
3503
+ console.log(` destroy: compute instances destroy ${sandboxId}`);
3504
+ }
3505
+ function runTimeoutText(opts) {
3506
+ return opts.timeoutMs ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}` : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;
3507
+ }
3508
+ async function runInstanceCommand(command, opts) {
3509
+ const c = await client(opts);
3510
+ const created = await c.post("/api/v1/sandboxes", buildCreateBody(opts));
3511
+ const sandbox = created.sandbox;
3512
+ const org2 = orgKey(opts);
3513
+ console.error(pc4.dim(`instance ${sandbox.id}`));
3514
+ const spawned = await c.post(
3515
+ `/api/v1/sandboxes/${sandbox.id}/processes`,
3516
+ { command: command.map(shellQuote).join(" ") }
3517
+ ).catch(async (e) => {
3518
+ try {
3519
+ await c.del(`/api/v1/sandboxes/${sandbox.id}`);
3520
+ } catch {
3521
+ }
3522
+ throw e;
3523
+ });
3524
+ const jobId = spawned.process.jobId;
3525
+ if (opts.detach) {
3526
+ setCurrentInstance(sandbox.id, org2);
3527
+ if (opts.quiet) console.log(sandbox.id);
3528
+ else printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
3529
+ return;
3530
+ }
3531
+ let exitCode = null;
3532
+ let destroyRequested = false;
3533
+ let detachRequested = false;
3534
+ let prompting = false;
3535
+ let printedOut = 0;
3536
+ let printedErr = 0;
3537
+ const flush = (p2) => {
3538
+ if (prompting) return;
3539
+ if (p2.stdout.length > printedOut) {
3540
+ process.stdout.write(p2.stdout.slice(printedOut));
3541
+ printedOut = p2.stdout.length;
3542
+ }
3543
+ if (p2.stderr.length > printedErr) {
3544
+ process.stderr.write(p2.stderr.slice(printedErr));
3545
+ printedErr = p2.stderr.length;
3546
+ }
3547
+ };
3548
+ const onSignal = () => {
3549
+ if (!process.stdin.isTTY || opts.yes || prompting) {
3550
+ if (prompting) return;
3551
+ destroyRequested = true;
3552
+ return;
3553
+ }
3554
+ prompting = true;
3555
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
3556
+ rl.question(`Destroy instance ${shortId(sandbox.id)}? [y/N/d] `, (answer) => {
3557
+ rl.close();
3558
+ prompting = false;
3559
+ const a = answer.trim().toLowerCase();
3560
+ if (a === "y") destroyRequested = true;
3561
+ else if (a === "d") detachRequested = true;
3562
+ });
3563
+ };
3564
+ process.on("SIGINT", onSignal);
3565
+ process.on("SIGTERM", onSignal);
3566
+ try {
3567
+ const deadline = opts.timeoutMs ? Date.now() + Number(opts.timeoutMs) : void 0;
3568
+ while (exitCode === null && !destroyRequested && !detachRequested) {
3569
+ const remaining = deadline === void 0 ? 55e3 : Math.max(1, deadline - Date.now());
3570
+ const res = await c.post(
3571
+ `/api/v1/sandboxes/${sandbox.id}/processes/${jobId}/wait`,
3572
+ { timeoutMs: Math.min(55e3, remaining) }
3573
+ );
3574
+ flush(res.process);
3575
+ if (res.process.status === "exited") {
3576
+ exitCode = res.process.exitCode ?? 128;
3577
+ } else if (deadline !== void 0 && Date.now() >= deadline) {
3578
+ destroyRequested = true;
3579
+ }
3580
+ }
3581
+ } finally {
3582
+ process.removeListener("SIGINT", onSignal);
3583
+ process.removeListener("SIGTERM", onSignal);
3584
+ if (detachRequested) {
3585
+ setCurrentInstance(sandbox.id, org2);
3586
+ printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
3587
+ } else if (opts.keep && exitCode !== null) {
3588
+ setCurrentInstance(sandbox.id, org2);
3589
+ if (opts.quiet) console.log(sandbox.id);
3590
+ else {
3591
+ console.error(pc4.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));
3592
+ console.log(sandbox.id);
3593
+ }
3594
+ } else {
3595
+ try {
3596
+ await c.del(`/api/v1/sandboxes/${sandbox.id}`);
3597
+ } catch (e) {
3598
+ console.error(
3599
+ pc4.red(`destroy failed for ${sandbox.id}: ${e instanceof Error ? e.message : String(e)}`)
3600
+ );
3601
+ if (exitCode === null || exitCode === 0) exitCode = 1;
3602
+ }
3603
+ const orgNow = orgKey(opts);
3604
+ if (readFileCurrent(orgNow) === sandbox.id) clearCurrentInstance(orgNow);
3605
+ }
3606
+ }
3607
+ process.exitCode = detachRequested ? 0 : exitCode ?? (destroyRequested ? 130 : 1);
3608
+ }
3609
+ var SERVE_POLL_MS = 3e4;
3610
+ var SERVE_DEFAULT_WAIT_MS = 12e4;
3611
+ async function serveInstanceCommand(id, command, port, opts) {
3612
+ const c = await client(opts);
3613
+ const spawned = await c.post(
3614
+ `/api/v1/sandboxes/${id}/processes`,
3615
+ {
3616
+ command: command.map(shellQuote).join(" "),
3617
+ ...opts.cwd ? { cwd: opts.cwd } : {},
3618
+ ...opts.env?.length ? { env: parseInputs(opts.env) } : {}
3619
+ }
3620
+ );
3621
+ const jobId = spawned.process.jobId;
3622
+ const jobStatus = () => c.get(`/api/v1/sandboxes/${id}/processes/${jobId}`);
3623
+ const reportExit = (proc) => {
3624
+ if (!opts.json) {
3625
+ const logs = `${proc.stdout}${proc.stderr}`.trimEnd().split("\n");
3626
+ if (logs.length > 0 && logs[0] !== "") {
3627
+ console.error(pc4.dim("--- last log lines ---"));
3628
+ for (const line of logs.slice(-50)) console.error(safeTerm(line));
3629
+ }
3630
+ }
3631
+ fail(new Error(`The server exited (code ${proc.exitCode ?? "?"}) before port ${port} listened.`), opts);
3632
+ };
3633
+ const waitMs = opts.timeoutMs ? Number(opts.timeoutMs) : SERVE_DEFAULT_WAIT_MS;
3634
+ const deadline = Date.now() + waitMs;
3635
+ let entry;
3636
+ let remaining = waitMs;
3637
+ while (!entry && remaining > 0) {
3638
+ const res = await c.get(
3639
+ `/api/v1/sandboxes/${id}/ports?wait=${port}&timeoutMs=${Math.min(SERVE_POLL_MS, remaining)}`
3640
+ );
3641
+ entry = res.ports.find((p2) => p2.port === port);
3642
+ if (entry) break;
3643
+ const proc = await jobStatus();
3644
+ if (proc.process.status === "exited") {
3645
+ reportExit(proc.process);
3646
+ return;
3647
+ }
3648
+ remaining = deadline - Date.now();
3649
+ }
3650
+ if (entry) {
3651
+ const proc = await jobStatus();
3652
+ if (proc.process.status === "exited") {
3653
+ reportExit(proc.process);
3654
+ return;
3655
+ }
3656
+ } else {
3657
+ if (!opts.json) printServeJobFooter(id, jobId);
3658
+ fail(new Error(`Port ${port} never listened within ${fmtTimeout(waitMs)}.`), opts);
3659
+ return;
3660
+ }
3661
+ if (!entry.public) {
3662
+ if (!opts.json) printServeJobFooter(id, jobId);
3663
+ fail(
3664
+ new Error(
3665
+ `Port ${port} is listening on ${safeTerm(entry.address)} only. Bind to 0.0.0.0 (e.g. --host 0.0.0.0) so it can be reached.`
3666
+ ),
3667
+ opts
3668
+ );
3669
+ return;
3670
+ }
3671
+ const { url } = await c.get(`/api/v1/sandboxes/${id}/urls?port=${port}`);
3672
+ if (opts.quiet) {
3673
+ console.log(safeTerm(url));
3674
+ return;
3675
+ }
3676
+ output(opts, { url }, () => {
3677
+ console.log(safeTerm(url));
3678
+ printServeJobFooter(id, jobId);
3679
+ });
3680
+ }
3681
+ function printServeJobFooter(sandboxId, jobId) {
3682
+ console.error(pc4.dim(` job ${jobId}`));
3683
+ console.error(pc4.dim(` logs: compute instances logs ${sandboxId} ${jobId}`));
3684
+ console.error(pc4.dim(` kill: compute instances kill ${sandboxId} ${jobId}`));
3685
+ }
3686
+ var CP_PROGRESS_MIN_BYTES = 10 * 1024 * 1024;
3687
+ function assertTransferUrl(raw) {
3688
+ let u;
3689
+ try {
3690
+ u = new URL(raw);
3691
+ } catch {
3692
+ throw new Error("platform returned a malformed transfer URL");
3693
+ }
3694
+ if (u.protocol === "https:") return;
3695
+ const loopback = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname);
3696
+ if (!(u.protocol === "http:" && loopback)) {
3697
+ throw new Error(`refusing insecure transfer URL: ${u.protocol}//${u.hostname} (expected https)`);
3698
+ }
3699
+ }
3700
+ function tarEntryIsSafe(p2, entry) {
3701
+ if (path.isAbsolute(p2) || p2.split("/").includes("..")) return false;
3702
+ const { type, linkpath } = entry;
3703
+ if ((type === "Link" || type === "SymbolicLink") && linkpath) {
3704
+ if (path.isAbsolute(linkpath) || linkpath.split("/").includes("..")) return false;
3705
+ }
3706
+ return true;
3707
+ }
3708
+ function parseCpEndpoint(arg) {
3709
+ const m = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})?:(\/.*)$/.exec(arg);
3710
+ if (m) return { remoteId: m[1] || void 0, remotePath: m[2] };
3711
+ return { local: arg };
3712
+ }
3713
+ async function cpCommand(src, dst, opts) {
3714
+ const s = parseCpEndpoint(src);
3715
+ const d = parseCpEndpoint(dst);
3716
+ const sRemote = "remotePath" in s;
3717
+ const dRemote = "remotePath" in d;
3718
+ if (sRemote === dRemote) {
3719
+ throw new Error("cp needs exactly one remote side \u2014 write it as [id:]/abs/path (e.g. 3f2a\u2026:/app or :/app)");
3720
+ }
3721
+ const c = await client(opts);
3722
+ if (!sRemote && "remotePath" in d && "local" in s) {
3723
+ const resolved = resolveSandbox(d.remoteId, opts);
3724
+ const r = await cpUpload(c, resolved.id, s.local, d.remotePath, opts);
3725
+ output(opts, r, (done) => {
3726
+ if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) \u2192 ${shortId(resolved.id)}:${d.remotePath}`);
3727
+ });
3728
+ } else if ("remotePath" in s && "local" in d) {
3729
+ const resolved = resolveSandbox(s.remoteId, opts);
3730
+ const r = await cpDownload(c, resolved.id, s.remotePath, d.local, opts);
3731
+ output(opts, r, (done) => {
3732
+ if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) \u2192 ${d.local}`);
3733
+ });
3734
+ }
3735
+ }
3736
+ function cpProgress(total, opts) {
3737
+ const show = !opts.quiet && !opts.json && process.stderr.isTTY && total > CP_PROGRESS_MIN_BYTES;
3738
+ let sent = 0;
3739
+ return {
3740
+ bump(n) {
3741
+ if (!show) return;
3742
+ sent += n;
3743
+ process.stderr.write(`\r${formatBytes(sent)} / ${formatBytes(total)} (${Math.round(sent / total * 100)}%)`);
3744
+ },
3745
+ done() {
3746
+ if (show) process.stderr.write("\n");
3747
+ }
3748
+ };
3749
+ }
3750
+ async function cpUpload(c, sandboxId, localPath, remotePath, opts) {
3751
+ const abs = path.resolve(localPath);
3752
+ fs.statSync(abs);
3753
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "compute-cp-up-"));
3754
+ const tmp = path.join(tmpDir, "archive.tar.gz");
3755
+ try {
3756
+ await tar.create({ gzip: true, file: tmp, cwd: path.dirname(abs) }, [path.basename(abs)]);
3757
+ const size = fs.statSync(tmp).size;
3758
+ const created = await c.post(
3759
+ `/api/v1/sandboxes/${sandboxId}/transfers`,
3760
+ { direction: "upload", path: remotePath }
3761
+ );
3762
+ if (!created.uploadUrl) throw new Error("platform did not return an upload URL");
3763
+ assertTransferUrl(created.uploadUrl);
3764
+ const progress = cpProgress(size, opts);
3765
+ try {
3766
+ const stream = fs.createReadStream(tmp);
3767
+ stream.on("data", (chunk) => progress.bump(typeof chunk === "string" ? chunk.length : chunk.byteLength));
3768
+ const res = await fetch(created.uploadUrl, {
3769
+ method: "PUT",
3770
+ headers: { "content-length": String(size), "content-type": "application/gzip" },
3771
+ // @ts-expect-error Readable.toWeb body is supported at runtime; DOM types lag
3772
+ body: Readable.toWeb(stream),
3773
+ duplex: "half"
3774
+ });
3775
+ if (!res.ok) throw new Error(`upload failed: HTTP ${res.status}`);
3776
+ } finally {
3777
+ progress.done();
3778
+ }
3779
+ return await c.post(
3780
+ `/api/v1/sandboxes/${sandboxId}/transfers/${created.transferId}/complete`,
3781
+ {}
3782
+ );
3783
+ } finally {
3784
+ fs.rmSync(tmpDir, { recursive: true, force: true });
3785
+ }
3786
+ }
3787
+ async function cpDownload(c, sandboxId, remotePath, localDir, opts) {
3788
+ const created = await c.post(
3789
+ `/api/v1/sandboxes/${sandboxId}/transfers`,
3790
+ { direction: "download", path: remotePath }
3791
+ );
3792
+ if (!created.downloadUrl) throw new Error("platform did not return a download URL");
3793
+ assertTransferUrl(created.downloadUrl);
3794
+ const res = await fetch(created.downloadUrl);
3795
+ if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`);
3796
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "compute-cp-dl-"));
3797
+ const tmp = path.join(tmpDir, "archive.tar.gz");
3798
+ try {
3799
+ const progress = cpProgress(created.bytes ?? 0, opts);
3800
+ const ws = fs.createWriteStream(tmp);
3801
+ try {
3802
+ await new Promise((resolve2, reject) => {
3803
+ ws.once("error", reject);
3804
+ const reader = res.body.getReader();
3805
+ const pump = async () => {
3806
+ for (; ; ) {
3807
+ const { done, value } = await reader.read();
3808
+ if (done || value === void 0) break;
3809
+ progress.bump(value.byteLength);
3810
+ if (!ws.write(value)) await new Promise((r) => ws.once("drain", () => r()));
3811
+ }
3812
+ };
3813
+ pump().then(
3814
+ () => ws.end(() => resolve2()),
3815
+ reject
3816
+ );
3817
+ });
3818
+ } finally {
3819
+ ws.destroy();
3820
+ }
3821
+ progress.done();
3822
+ fs.mkdirSync(localDir, { recursive: true });
3823
+ await tar.extract({ file: tmp, cwd: localDir, filter: tarEntryIsSafe });
3824
+ return { path: localDir, bytes: created.bytes ?? fs.statSync(tmp).size, files: created.files ?? 0 };
3825
+ } finally {
3826
+ fs.rmSync(tmpDir, { recursive: true, force: true });
3827
+ }
3828
+ }
3829
+ function formatBytes(n) {
3830
+ if (n < 1024) return `${n} B`;
3831
+ const units = ["KB", "MB", "GB", "TB"];
3832
+ let v = n / 1024;
3833
+ let i = 0;
3834
+ while (v >= 1024 && i < units.length - 1) {
3835
+ v /= 1024;
3836
+ i += 1;
3837
+ }
3838
+ return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
3839
+ }
3041
3840
 
3042
3841
  // src/index.ts
3043
3842
  var __filename2 = fileURLToPath(import.meta.url);
3044
- var __dirname2 = dirname(__filename2);
3843
+ var __dirname2 = dirname2(__filename2);
3045
3844
  var packageJson = JSON.parse(
3046
- readFileSync2(join2(__dirname2, "..", "package.json"), "utf-8")
3845
+ readFileSync3(join4(__dirname2, "..", "package.json"), "utf-8")
3047
3846
  );
3048
3847
  var isDevBuild = import.meta.url.includes("worktrees") || import.meta.url.includes("/packages/cli/");
3049
3848
  var VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;