@computesdk/cli 2.5.5 → 2.5.7

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
  });
@@ -1028,27 +1028,39 @@ function printDiscovery(d) {
1028
1028
  }
1029
1029
  console.log(pc2.dim(`discovery: ${d.workflowsFound ? "workflows found" : "no workflows yet"}${d.seeded ? ", cursors seeded" : ""}`));
1030
1030
  }
1031
+ function isPatchedWorkflowTarget(target) {
1032
+ return "workflowPath" in target;
1033
+ }
1034
+ function patchTouches(patch, path2) {
1035
+ const plain = `+++ b/${path2}`;
1036
+ const quoted = `+++ "b/${path2}"`;
1037
+ return patch.split("\n").some((line) => {
1038
+ const header = line.replace(/\t.*$/, "");
1039
+ return header === plain || header === quoted;
1040
+ });
1041
+ }
1031
1042
  function dispatchBody(workflow, opts) {
1032
- if (!workflow.dispatchable && !opts.manual) {
1043
+ const patched = isPatchedWorkflowTarget(workflow);
1044
+ if (!patched && !workflow.dispatchable && !opts.manual) {
1033
1045
  throw new ActionsCliError(
1034
1046
  "invalid_argument",
1035
1047
  `Workflow "${workflow.path}" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`
1036
1048
  );
1037
1049
  }
1038
- if (!workflow.dispatchable && opts.inputs !== void 0 && opts.inputs.length > 0) {
1050
+ if (!patched && !workflow.dispatchable && opts.inputs !== void 0 && opts.inputs.length > 0) {
1039
1051
  throw new ActionsCliError(
1040
1052
  "invalid_argument",
1041
1053
  `Workflow "${workflow.path}" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`
1042
1054
  );
1043
1055
  }
1044
- const ref = opts.ref ?? workflow.refs[0];
1056
+ const ref = opts.ref ?? (patched ? void 0 : workflow.refs[0]);
1045
1057
  if (!ref) throw new ActionsCliError("invalid_argument", "No --ref given and the workflow has no watched refs.");
1046
1058
  if (opts.providerRegion !== void 0 && opts.provider === void 0) {
1047
1059
  throw new ActionsCliError("invalid_argument", "--provider-region requires --provider.");
1048
1060
  }
1049
1061
  const maxPrice = maxPriceFields(opts.maxBid, opts.maxBidPer);
1050
1062
  return {
1051
- workflowId: workflow.id,
1063
+ ...patched ? { repoFullName: workflow.repoFullName, workflowPath: workflow.workflowPath } : { workflowId: workflow.id },
1052
1064
  ref,
1053
1065
  inputs: parseInputs(opts.inputs),
1054
1066
  ...opts.manual && { manual: true },
@@ -1138,13 +1150,13 @@ function parseVaultKind(kind) {
1138
1150
  if (kind === void 0 || kind === "secret" || kind === "variable") return kind ?? "secret";
1139
1151
  throw new ActionsCliError("invalid_argument", `--kind must be secret or variable, got "${kind}".`);
1140
1152
  }
1141
- function vaultPath(path, params) {
1153
+ function vaultPath(path2, params) {
1142
1154
  const search = new URLSearchParams();
1143
1155
  for (const [key, value] of Object.entries(params)) {
1144
1156
  if (value !== void 0) search.set(key, value);
1145
1157
  }
1146
1158
  const query = search.toString();
1147
- return query ? `${path}?${query}` : path;
1159
+ return query ? `${path2}?${query}` : path2;
1148
1160
  }
1149
1161
  function vaultSetBody(name, value, opts) {
1150
1162
  if (value === "") throw new ActionsCliError("invalid_argument", "The value is empty.");
@@ -1212,36 +1224,38 @@ function registerActionsCommands(program2) {
1212
1224
  ).action(async (repo, opts) => {
1213
1225
  try {
1214
1226
  const c = await client(opts);
1227
+ let ref = opts.ref;
1228
+ let local = null;
1229
+ if (opts.withChanges) {
1230
+ ref ?? (ref = currentBranch() ?? void 0);
1231
+ if (!ref) throw new ActionsCliError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
1232
+ local = localChangesPatch(ref, void 0, repo);
1233
+ } else if (!opts.json && hasLocalChanges()) {
1234
+ console.error(pc2.dim("You have uncommitted changes. Add --with-changes to run them."));
1235
+ }
1215
1236
  const { workflows } = await c.get(
1216
1237
  "/api/v1/actions/workflows",
1217
1238
  { repo }
1218
1239
  );
1219
- const workflow = matchWorkflow(workflows, opts.workflow);
1240
+ const workflow = matchWorkflow(workflows, opts.workflow) ?? (local && patchTouches(local.patch, opts.workflow) ? { repoFullName: repo, workflowPath: opts.workflow } : void 0);
1220
1241
  if (!workflow) {
1221
1242
  const choices = workflows.map((w) => `${w.path} (${w.name})`).join(", ") || "none";
1243
+ const hint = !opts.withChanges && hasLocalChanges() && /^\.github\/workflows\//.test(opts.workflow) ? " If it only exists in your working tree, add --with-changes." : "";
1222
1244
  throw new ActionsCliError(
1223
1245
  "workflow_not_found",
1224
- `No workflow "${opts.workflow}" in ${repo}. Available: ${choices}`
1246
+ `No workflow "${opts.workflow}" in ${repo}. Available: ${choices}${hint}`
1225
1247
  );
1226
1248
  }
1227
1249
  let patch;
1228
- let ref = opts.ref;
1229
- if (opts.withChanges) {
1230
- ref ?? (ref = currentBranch() ?? void 0);
1231
- if (!ref) throw new ActionsCliError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
1232
- const local = localChangesPatch(ref, void 0, repo);
1233
- if (local) {
1234
- const uploaded = await c.postText(
1235
- "/api/v1/actions/patches",
1236
- local.patch,
1237
- "text/x-patch; charset=utf-8"
1238
- );
1239
- patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };
1240
- } else if (!opts.json) {
1241
- console.error(pc2.dim(`no local changes beyond origin/${ref.replace(/^refs\/heads\//, "")}; running the ref as is`));
1242
- }
1243
- } else if (!opts.json && hasLocalChanges()) {
1244
- console.error(pc2.dim("You have uncommitted changes. Add --with-changes to run them."));
1250
+ if (local) {
1251
+ const uploaded = await c.postText(
1252
+ "/api/v1/actions/patches",
1253
+ local.patch,
1254
+ "text/x-patch; charset=utf-8"
1255
+ );
1256
+ patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };
1257
+ } else if (opts.withChanges && !opts.json && ref) {
1258
+ console.error(pc2.dim(`no local changes beyond origin/${ref.replace(/^refs\/heads\//, "")}; running the ref as is`));
1245
1259
  }
1246
1260
  const body = dispatchBody(workflow, { ...opts, ref, patchId: patch?.patchId });
1247
1261
  const result = await c.post(
@@ -1575,8 +1589,8 @@ function registerActionsCommands(program2) {
1575
1589
  vault.command("ls").description("List names and metadata (never values)")
1576
1590
  ).action(async (opts) => {
1577
1591
  try {
1578
- const path = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind) });
1579
- const data = await (await client(opts)).get(path);
1592
+ const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind) });
1593
+ const data = await (await client(opts)).get(path2);
1580
1594
  output(opts, data, (d) => {
1581
1595
  for (const item of d.items) console.log(formatVaultRow(item));
1582
1596
  });
@@ -1651,8 +1665,8 @@ function registerActionsCommands(program2) {
1651
1665
  vault.command("rm").description("Delete an item (with --repo, only the repo's override)").argument("<name>", "item name")
1652
1666
  ).action(async (name, opts) => {
1653
1667
  try {
1654
- const path = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
1655
- const result = await (await client(opts)).del(path);
1668
+ const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
1669
+ const result = await (await client(opts)).del(path2);
1656
1670
  output(opts, result, (r) => console.log(`deleted ${pc2.cyan(safeTerm(r.name))} ${pc2.dim(`(${r.kind})`)}`));
1657
1671
  } catch (e) {
1658
1672
  fail(e, opts);
@@ -2026,8 +2040,78 @@ function formatSettlementRow(s) {
2026
2040
  paid
2027
2041
  ].join(" ");
2028
2042
  }
2043
+ var MICRO_USD = 1e6;
2044
+ function bidBody(opts) {
2045
+ const rate = parseRate(opts.price, opts.per);
2046
+ const expiresInHours = parseExpiresIn(opts.expiresIn);
2047
+ return {
2048
+ size: opts.size,
2049
+ ...opts.region !== void 0 && { region: opts.region },
2050
+ maxUsd: rate.usd,
2051
+ per: rate.per,
2052
+ ...expiresInHours !== void 0 && { expiresInHours },
2053
+ useCase: parseMarketLane(opts.useCase)
2054
+ };
2055
+ }
2056
+ function parseTopupAmount(value) {
2057
+ const usd = Number(value.replace(/^\$/, ""));
2058
+ if (!USD_RE.test(value.replace(/^\$/, "")) || !Number.isFinite(usd) || usd <= 0) {
2059
+ throw new ActionsCliError(
2060
+ "invalid_argument",
2061
+ `Invalid amount "${value}". Expected a positive dollar amount (e.g. 50).`
2062
+ );
2063
+ }
2064
+ return usd;
2065
+ }
2066
+ 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)}`;
2068
+ }
2069
+ function formatBidRow(bid) {
2070
+ const status = bid.status === "open" ? pc3.green("open") : bid.status === "filled" ? pc3.cyan("filled") : pc3.gray("cancelled");
2071
+ return [
2072
+ bid.id,
2073
+ status,
2074
+ pc3.dim(bid.useCase === "sandbox" ? "sandbox" : "actions"),
2075
+ safeTerm(bid.size),
2076
+ safeTerm(bid.region ?? "any region"),
2077
+ `\u2264 ${formatRate(bid.maxUsd, bid.per)}`,
2078
+ pc3.dim(bid.expiresAt ? `expires ${bid.expiresAt}` : "standing")
2079
+ ].join(" ");
2080
+ }
2081
+ function formatCredits(b) {
2082
+ const lines = [`available ${formatMoney(b.balanceMicroUsd / MICRO_USD)}`];
2083
+ if (b.holds.length > 0) {
2084
+ lines.push(
2085
+ pc3.dim(`reserved ${formatMoney(b.heldMicroUsd / MICRO_USD)} across ${b.holds.length} running job${b.holds.length === 1 ? "" : "s"}`)
2086
+ );
2087
+ }
2088
+ return lines.join("\n");
2089
+ }
2090
+ function formatLedgerRow(e) {
2091
+ const usd = e.microUsd / MICRO_USD;
2092
+ const amount = usd < 0 ? `-${formatMoney(-usd)}` : `+${formatMoney(usd)}`;
2093
+ return [
2094
+ pc3.dim(e.createdAt.slice(0, 19).replace("T", " ")),
2095
+ (usd < 0 ? pc3.red : pc3.green)(amount.padStart(10)),
2096
+ safeTerm(e.label),
2097
+ pc3.dim(e.jobId ? `job ${e.jobId}` : "")
2098
+ ].join(" ").trimEnd();
2099
+ }
2100
+ function formatPurchaseRow(p2) {
2101
+ const cost = p2.costMicroUsd !== null ? formatMoney(p2.costMicroUsd / MICRO_USD) : p2.status === "live" ? pc3.yellow("running") : "-";
2102
+ return [
2103
+ pc3.dim(p2.startedAt.slice(0, 19).replace("T", " ")),
2104
+ cost.padStart(10),
2105
+ pc3.cyan(safeTerm(p2.sellerName)),
2106
+ pc3.dim(`${safeTerm(p2.provider)}/${safeTerm(p2.region ?? "any")}`),
2107
+ formatRate(p2.usd, p2.per),
2108
+ p2.secondsBilled !== null ? pc3.dim(`${p2.secondsBilled}s`) : "",
2109
+ p2.status === "replaced" ? pc3.yellow("replaced") : "",
2110
+ pc3.dim(p2.runId ? `run ${p2.runId}` : p2.sandboxId ? `sandbox ${p2.sandboxId}` : "")
2111
+ ].filter((part) => part !== "").join(" ");
2112
+ }
2029
2113
  function registerMarketCommands(program2) {
2030
- const market = program2.command("market").description("Sell compute capacity on the compute market").configureOutput({ outputError: usageErrorOutput });
2114
+ const market = program2.command("market").description("Buy and sell compute capacity on the compute market").configureOutput({ outputError: usageErrorOutput });
2031
2115
  const common = (cmd) => cmd.option("--api-key <key>", "API key (default: $COMPUTE_API_KEY)").option("--base-url <url>", "API base URL (default: https://platform.computesdk.com)").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)").option("--json", "print machine-readable JSON");
2032
2116
  common(
2033
2117
  market.command("listings").alias("list").description("Your listings \u2014 live, paused, expired, and withdrawn")
@@ -2200,6 +2284,154 @@ function registerMarketCommands(program2) {
2200
2284
  fail(e, opts);
2201
2285
  }
2202
2286
  });
2287
+ const cap = market.command("cap").description("The org market cap: the most a market-placed job pays without its own bid");
2288
+ common(cap.command("show", { isDefault: true }).description("Show the current cap")).action(
2289
+ async (opts) => {
2290
+ try {
2291
+ const { marketCap } = await (await client(opts)).get(
2292
+ "/api/v1/market/bids"
2293
+ );
2294
+ output(opts, marketCap, (c) => console.log(formatCap(c)));
2295
+ } catch (e) {
2296
+ fail(e, opts);
2297
+ }
2298
+ }
2299
+ );
2300
+ common(
2301
+ cap.command("set").description("Set the cap").requiredOption("--price <usd/unit>", "max price per unit of time (e.g. 0.40/hour)").option("--per <unit>", "unit for a bare --price usd (second, minute, or hour)")
2302
+ ).action(async (opts) => {
2303
+ try {
2304
+ const rate = parseRate(opts.price, opts.per);
2305
+ const { marketCap } = await (await client(opts)).post(
2306
+ "/api/v1/market/bids",
2307
+ { marketCap: rate }
2308
+ );
2309
+ output(opts, marketCap, (c) => console.log(formatCap(c)));
2310
+ } catch (e) {
2311
+ fail(e, opts);
2312
+ }
2313
+ });
2314
+ common(
2315
+ cap.command("clear").description("Remove the cap (refused while your placement order still names market)")
2316
+ ).action(async (opts) => {
2317
+ try {
2318
+ const { marketCap } = await (await client(opts)).post(
2319
+ "/api/v1/market/bids",
2320
+ { marketCap: null }
2321
+ );
2322
+ output(opts, marketCap, (c) => console.log(formatCap(c)));
2323
+ } catch (e) {
2324
+ fail(e, opts);
2325
+ }
2326
+ });
2327
+ common(
2328
+ market.command("bids").description("Your org's standing bids \u2014 open, filled, and cancelled")
2329
+ ).action(async (opts) => {
2330
+ try {
2331
+ const { bids } = await (await client(opts)).get(
2332
+ "/api/v1/market/bids"
2333
+ );
2334
+ output(opts, bids, (rows) => {
2335
+ if (rows.length === 0) {
2336
+ console.log("No bids yet \u2014 post one with `compute market bid`.");
2337
+ return;
2338
+ }
2339
+ for (const bid of rows) console.log(formatBidRow(bid));
2340
+ });
2341
+ } catch (e) {
2342
+ fail(e, opts);
2343
+ }
2344
+ });
2345
+ common(
2346
+ market.command("bid").description("Post a standing bid: the most you will pay for a size tier").requiredOption("--size <tier>", "size tier to buy (e.g. xlarge)").requiredOption("--price <usd/unit>", "max price per unit of time (e.g. 0.40/hour)").option("--per <unit>", "unit for a bare --price usd (second, minute, or hour)").option("--region <region>", "only fill in this region (default: any)").option("--use-case <lane>", "lane to buy on: actions or sandbox (default: actions)").option("--expires-in <hours>", "cancel after this many hours (default: standing)")
2347
+ ).action(async (opts) => {
2348
+ try {
2349
+ const result = await (await client(opts)).post(
2350
+ "/api/v1/market/bids",
2351
+ bidBody(opts)
2352
+ );
2353
+ output(opts, result, (r) => {
2354
+ console.log(`bid placed ${pc3.cyan(r.bid.id)}`);
2355
+ console.log(formatBidRow(r.bid));
2356
+ });
2357
+ } catch (e) {
2358
+ fail(e, opts);
2359
+ }
2360
+ });
2361
+ common(
2362
+ market.command("cancel-bid").description("Cancel an open standing bid").argument("<bid-id>", "bid ID")
2363
+ ).action(async (bidId, opts) => {
2364
+ try {
2365
+ const result = await (await client(opts)).del(
2366
+ `/api/v1/market/bids?id=${encodeURIComponent(bidId)}`
2367
+ );
2368
+ output(opts, result, (r) => console.log(`cancelled ${pc3.cyan(r.bid.id)}`));
2369
+ } catch (e) {
2370
+ fail(e, opts);
2371
+ }
2372
+ });
2373
+ common(
2374
+ market.command("purchases").description("What the market ran for you: seller, price, duration, and cost, newest first").option("--limit <n>", "purchases per page (max 200, default 50)").option("--cursor <cursor>", "continue from a previous page")
2375
+ ).action(async (opts) => {
2376
+ try {
2377
+ const page = await (await client(opts)).get("/api/v1/market/purchases", { limit: opts.limit, cursor: opts.cursor });
2378
+ output(opts, page, (p2) => {
2379
+ if (p2.purchases.length === 0) {
2380
+ console.log("No market purchases yet.");
2381
+ return;
2382
+ }
2383
+ for (const row of p2.purchases) console.log(formatPurchaseRow(row));
2384
+ if (p2.nextCursor) console.log(pc3.dim(`more: --cursor ${p2.nextCursor}`));
2385
+ });
2386
+ } catch (e) {
2387
+ fail(e, opts);
2388
+ }
2389
+ });
2390
+ common(
2391
+ market.command("credits").description("Prepaid market credits: available balance and reserved holds")
2392
+ ).action(async (opts) => {
2393
+ try {
2394
+ const balance = await (await client(opts)).get(
2395
+ "/api/v1/billing/balance"
2396
+ );
2397
+ output(opts, balance, (b) => console.log(formatCredits(b)));
2398
+ } catch (e) {
2399
+ fail(e, opts);
2400
+ }
2401
+ });
2402
+ common(
2403
+ market.command("ledger").description("Credit history, newest first: top-ups, charges, holds, refunds").option("--limit <n>", "entries per page (max 200, default 50)").option("--cursor <cursor>", "continue from a previous page")
2404
+ ).action(async (opts) => {
2405
+ try {
2406
+ const page = await (await client(opts)).get("/api/v1/billing/ledger", { limit: opts.limit, cursor: opts.cursor });
2407
+ output(opts, page, (p2) => {
2408
+ if (p2.entries.length === 0) {
2409
+ console.log("No credit activity yet \u2014 add credits with `compute market topup`.");
2410
+ return;
2411
+ }
2412
+ for (const entry of p2.entries) console.log(formatLedgerRow(entry));
2413
+ if (p2.nextCursor) console.log(pc3.dim(`more: --cursor ${p2.nextCursor}`));
2414
+ });
2415
+ } catch (e) {
2416
+ fail(e, opts);
2417
+ }
2418
+ });
2419
+ common(
2420
+ market.command("topup").description("Buy prepaid credits \u2014 prints a Stripe checkout link to pay in your browser").argument("<usd>", "amount in USD (e.g. 50)")
2421
+ ).action(async (amount, opts) => {
2422
+ try {
2423
+ const result = await (await client(opts)).post(
2424
+ "/api/v1/billing/topups",
2425
+ { amountUsd: parseTopupAmount(amount) }
2426
+ );
2427
+ output(opts, result, (r) => {
2428
+ console.log(`Pay ${formatMoney(r.amountMicroUsd / MICRO_USD)} at:`);
2429
+ console.log(r.url);
2430
+ });
2431
+ } catch (e) {
2432
+ fail(e, opts);
2433
+ }
2434
+ });
2203
2435
  const credential = market.command("credential").description("Connect the credential your listings fill under");
2204
2436
  common(
2205
2437
  credential.command("connect").description(
@@ -2263,25 +2495,151 @@ ${hints}`
2263
2495
  }
2264
2496
 
2265
2497
  // src/sandboxes.ts
2498
+ import * as fs from "fs";
2499
+ import * as os from "os";
2500
+ import * as path from "path";
2501
+ import * as readline from "readline";
2502
+ import { Readable } from "stream";
2266
2503
  import pc4 from "picocolors";
2504
+ import * as tar from "tar";
2505
+
2506
+ // src/current-instance.ts
2507
+ import { spawnSync as spawnSync2 } from "child_process";
2508
+ import { createHash } from "crypto";
2509
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
2510
+ import { homedir } from "os";
2511
+ import { join as join2 } from "path";
2512
+ function stateDir() {
2513
+ return process.env.BENCHSDK_STATE_DIR ?? join2(homedir(), ".benchsdk");
2514
+ }
2515
+ function statePath() {
2516
+ return join2(stateDir(), "current-instances.json");
2517
+ }
2518
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2519
+ function isUuid(value) {
2520
+ return value !== void 0 && UUID_RE.test(value);
2521
+ }
2522
+ function dirKey(cwd = process.cwd()) {
2523
+ const r = spawnSync2("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" });
2524
+ return r.status === 0 && r.stdout.trim() !== "" ? r.stdout.trim() : cwd;
2525
+ }
2526
+ function orgKey(opts) {
2527
+ const slug = opts.org || process.env.COMPUTE_ORG;
2528
+ if (slug) return `org:${slug}`;
2529
+ const key = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY;
2530
+ if (key) return `key:${createHash("sha256").update(key).digest("hex").slice(0, 12)}`;
2531
+ try {
2532
+ const raw = JSON.parse(readFileSync2(join2(stateDir(), "credentials.json"), "utf8"));
2533
+ const org2 = raw?.orgId ?? raw?.orgSlug;
2534
+ if (org2) return `org:${org2}`;
2535
+ } catch {
2536
+ }
2537
+ return "default";
2538
+ }
2539
+ function readStore() {
2540
+ try {
2541
+ const parsed = JSON.parse(readFileSync2(statePath(), "utf8"));
2542
+ if (typeof parsed !== "object" || parsed === null) return {};
2543
+ return parsed;
2544
+ } catch {
2545
+ return {};
2546
+ }
2547
+ }
2548
+ function writeStore(store) {
2549
+ mkdirSync2(stateDir(), { recursive: true });
2550
+ const tmp = `${statePath()}.${process.pid}.tmp`;
2551
+ writeFileSync2(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
2552
+ renameSync(tmp, statePath());
2553
+ }
2554
+ function withStoreLock(fn) {
2555
+ const lock = `${statePath()}.lock`;
2556
+ for (let attempt = 0; ; attempt++) {
2557
+ try {
2558
+ mkdirSync2(lock);
2559
+ break;
2560
+ } catch {
2561
+ if (attempt === 99) return fn();
2562
+ const until = Date.now() + 10;
2563
+ while (Date.now() < until) {
2564
+ }
2565
+ }
2566
+ }
2567
+ try {
2568
+ return fn();
2569
+ } finally {
2570
+ try {
2571
+ rmSync(lock, { recursive: true, force: true });
2572
+ } catch {
2573
+ }
2574
+ }
2575
+ }
2576
+ function setCurrentInstance(sandboxId, org2, dir = dirKey()) {
2577
+ withStoreLock(() => {
2578
+ const store = readStore();
2579
+ (store[dir] ?? (store[dir] = {}))[org2] = sandboxId;
2580
+ writeStore(store);
2581
+ });
2582
+ }
2583
+ function clearCurrentInstance(org2, dir = dirKey()) {
2584
+ return withStoreLock(() => {
2585
+ const store = readStore();
2586
+ const prev = store[dir]?.[org2];
2587
+ if (prev === void 0) return void 0;
2588
+ delete store[dir][org2];
2589
+ if (Object.keys(store[dir]).length === 0) delete store[dir];
2590
+ writeStore(store);
2591
+ return prev;
2592
+ });
2593
+ }
2594
+ function readFileCurrent(org2, dir = dirKey()) {
2595
+ return readStore()[dir]?.[org2];
2596
+ }
2597
+ function resolveInstanceId(arg, opts, dir = dirKey()) {
2598
+ if (isUuid(arg)) return { id: arg, source: "argument" };
2599
+ const env = process.env.COMPUTE_INSTANCE;
2600
+ if (env) return { id: env, source: "env" };
2601
+ const file = readFileCurrent(orgKey(opts), dir);
2602
+ if (file) return { id: file, source: "file", dir };
2603
+ return void 0;
2604
+ }
2605
+ function shortId(id) {
2606
+ return id.length > 8 ? `${id.slice(0, 4)}\u2026` : id;
2607
+ }
2608
+
2609
+ // src/sandboxes.ts
2267
2610
  function shellQuote(arg) {
2268
2611
  return `'${arg.replace(/'/g, `'\\''`)}'`;
2269
2612
  }
2270
- function printSandbox(s) {
2271
- const attach = "attach" in s ? s.attach : void 0;
2272
- console.log(`${pc4.cyan(s.id)} ${s.status} ${s.provider ?? "\u2014"} ${s.providerSandboxId ?? "\u2014"}`);
2273
- console.log(` label: ${s.label ?? "\u2014"} commands: ${s.commandCount} created: ${s.createdAt}`);
2613
+ function shortRate(rate) {
2614
+ return `${formatUsd(rateAllUnits(rate).perHour)}/h`;
2615
+ }
2616
+ function formatLocalTime(iso) {
2617
+ const d = new Date(iso);
2618
+ if (Number.isNaN(d.getTime())) return iso;
2619
+ const p2 = (n) => String(n).padStart(2, "0");
2620
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`;
2621
+ }
2622
+ function printSandbox(s, verbose = false) {
2623
+ const p2 = s.placement;
2624
+ console.log(
2625
+ `${pc4.cyan(s.id)} ${s.status} ${p2?.box?.provider ?? s.provider ?? "\u2014"} ${p2?.size ?? "\u2014"} ${p2 ? shortRate(p2.rate) : "\u2014"}`
2626
+ );
2627
+ if (s.label) {
2628
+ console.log(` label: ${s.label} created: ${formatLocalTime(s.createdAt)}`);
2629
+ }
2630
+ if (s.destroyError) console.log(` destroyError: ${pc4.red(s.destroyError)}`);
2631
+ if (!verbose) return;
2632
+ console.log(` providerSandboxId: ${s.providerSandboxId ?? "\u2014"} commands: ${s.commandCount}`);
2274
2633
  if (s.image !== void 0) {
2275
2634
  console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc4.dim(`(requested: ${s.requestedImage})`)}` : ""}`);
2276
2635
  }
2277
- if (s.destroyError) console.log(` destroyError: ${pc4.red(s.destroyError)}`);
2278
- if (s.placement) {
2279
- const p2 = s.placement;
2636
+ if (p2) {
2280
2637
  const box = p2.box ? ` / ${p2.box.sizeName ?? "custom"}${p2.box.resources ? ` (${p2.box.resources.cpus ?? "?"} vCPU / ${p2.box.resources.memoryMb ?? "?"} MB)` : ""}` : "";
2281
2638
  console.log(
2282
- ` 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)}` : ""}`
2639
+ ` placement: ${p2.source}${box} order: ${p2.orderType ?? "\u2014"} rate: ${formatUsdPer(p2.rate)}${p2.maxPrice ? ` max price: ${formatUsdPer(p2.maxPrice)}` : ""}`
2283
2640
  );
2284
2641
  }
2642
+ const attach = "attach" in s ? s.attach : void 0;
2285
2643
  if (attach !== void 0) {
2286
2644
  console.log(
2287
2645
  attach === null ? " attach: none (market fill or ambient provider \u2014 platform drive only)" : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ""}`
@@ -2338,10 +2696,16 @@ var EXEC_LEAD_OPTS = [
2338
2696
  ];
2339
2697
  var SPAWN_LEAD_OPTS = [
2340
2698
  ...AUTH_LEAD_OPTS,
2699
+ { aliases: ["-q", "--quiet"], key: "quiet", flag: "bool" },
2341
2700
  { aliases: ["--cwd"], key: "cwd", flag: "value" },
2342
2701
  { aliases: ["-e", "--env"], key: "env", flag: "repeat" },
2343
2702
  { aliases: ["--stdin"], key: "stdin", flag: "bool" }
2344
2703
  ];
2704
+ var SERVE_LEAD_OPTS = [
2705
+ ...SPAWN_LEAD_OPTS,
2706
+ { aliases: ["--port"], key: "port", flag: "value" },
2707
+ { aliases: ["--timeout-ms"], key: "timeoutMs", flag: "value" }
2708
+ ];
2345
2709
  function takeLeadingOptions(argv, specs) {
2346
2710
  var _a;
2347
2711
  const byAlias = /* @__PURE__ */ new Map();
@@ -2399,33 +2763,103 @@ function mergeLeadOpts(opts, inline) {
2399
2763
  }
2400
2764
  return merged;
2401
2765
  }
2766
+ function checkQuietJson(opts) {
2767
+ if (opts.quiet && opts.json) throw new Error("--quiet and --json cannot be combined");
2768
+ }
2769
+ function emitResult(opts, data, quietLine, render) {
2770
+ if (opts.quiet) {
2771
+ console.log(quietLine(data));
2772
+ return;
2773
+ }
2774
+ output(opts, data, render);
2775
+ }
2776
+ var NO_INSTANCE_HINT = "No instance given. Pass an ID, run `compute instances use <id>`, or set COMPUTE_INSTANCE.";
2777
+ function resolveSandbox(argId, opts) {
2778
+ const r = resolveInstanceId(argId, opts);
2779
+ if (!r) throw new Error(NO_INSTANCE_HINT);
2780
+ if (r.source !== "argument" && !opts.json && !opts.quiet) {
2781
+ console.error(
2782
+ pc4.dim(
2783
+ `instance ${shortId(r.id)} (${r.source === "env" ? "COMPUTE_INSTANCE" : `current for ${r.dir}`})`
2784
+ )
2785
+ );
2786
+ }
2787
+ const org2 = orgKey(opts);
2788
+ return {
2789
+ id: r.id,
2790
+ clearStale: (error) => {
2791
+ if (r.source === "file" && error instanceof ActionsApiError && error.status === 404 && readFileCurrent(org2) === r.id) {
2792
+ clearCurrentInstance(org2);
2793
+ console.error(pc4.dim(`cleared stale current instance ${shortId(r.id)}`));
2794
+ }
2795
+ }
2796
+ };
2797
+ }
2798
+ function requireUuidOrImplicit(argId, opts) {
2799
+ if (argId !== void 0 && !isUuid(argId)) {
2800
+ throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
2801
+ }
2802
+ return resolveSandbox(argId, opts);
2803
+ }
2804
+ function resolveTwoArgTarget(argId, resourceId, opts, label) {
2805
+ if (resourceId === void 0) {
2806
+ if (argId === void 0) throw new Error(`missing ${label}`);
2807
+ return { resolved: resolveSandbox(void 0, opts), resource: argId };
2808
+ }
2809
+ if (argId !== void 0 && !isUuid(argId)) {
2810
+ throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
2811
+ }
2812
+ return { resolved: resolveSandbox(argId, opts), resource: resourceId };
2813
+ }
2814
+ function addCreateFlags(c) {
2815
+ 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), []);
2816
+ }
2817
+ function buildCreateBody(opts) {
2818
+ const resources = {};
2819
+ if (opts.cpus) resources.cpus = Number(opts.cpus);
2820
+ if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);
2821
+ if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);
2822
+ const body = {};
2823
+ if (opts.order) body.providerOrder = opts.order.split(",").map((s) => s.trim());
2824
+ if (opts.size) body.size = opts.size;
2825
+ if (opts.label) body.label = opts.label;
2826
+ if (opts.image) body.image = opts.image;
2827
+ if (opts.snapshotId) body.snapshotId = opts.snapshotId;
2828
+ if (opts.timeoutMs) body.timeoutMs = Number(opts.timeoutMs);
2829
+ if (opts.secret && opts.secret.length > 0) body.secrets = opts.secret;
2830
+ if (Object.keys(resources).length > 0) body.resources = resources;
2831
+ const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);
2832
+ if (maxPrice) body.maxPrice = { usd: maxPrice.usd, per: maxPrice.per };
2833
+ if (opts.orderType && opts.market) {
2834
+ throw new Error("--market and --order-type are mutually exclusive.");
2835
+ }
2836
+ if (opts.orderType) body.orderType = opts.orderType;
2837
+ if (opts.market) body.orderType = "market";
2838
+ return body;
2839
+ }
2840
+ function fmtTimeout(ms) {
2841
+ if (ms % 36e5 === 0) return `${ms / 36e5}h`;
2842
+ if (ms % 6e4 === 0) return `${ms / 6e4}m`;
2843
+ if (ms % 1e3 === 0) return `${ms / 1e3}s`;
2844
+ return `${ms}ms`;
2845
+ }
2846
+ var PLATFORM_DEFAULT_TIMEOUT_MS = 30 * 6e4;
2402
2847
  function registerSandboxesCommands(program2) {
2403
2848
  const cmd = program2.command("instances").alias("sandboxes").alias("sbx").description("Create and drive compute instances through the platform").enablePositionalOptions().configureOutput({ outputError: usageErrorOutput });
2404
- 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) => {
2849
+ addCreateFlags(
2850
+ cmd.command("create").description('Place a sandbox (provider order walks 1,2,3; "market" bids first)')
2851
+ ).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) => {
2405
2852
  try {
2853
+ checkQuietJson(opts);
2406
2854
  const c = await client(opts);
2407
- const resources = {};
2408
- if (opts.cpus) resources.cpus = Number(opts.cpus);
2409
- if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);
2410
- if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);
2411
- const body = {};
2412
- if (opts.order) body.providerOrder = opts.order.split(",").map((s) => s.trim());
2413
- if (opts.size) body.size = opts.size;
2414
- if (opts.label) body.label = opts.label;
2415
- if (opts.image) body.image = opts.image;
2416
- if (opts.snapshotId) body.snapshotId = opts.snapshotId;
2417
- if (opts.timeoutMs) body.timeoutMs = Number(opts.timeoutMs);
2418
- if (opts.secret && opts.secret.length > 0) body.secrets = opts.secret;
2419
- if (Object.keys(resources).length > 0) body.resources = resources;
2420
- const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);
2421
- if (maxPrice) body.maxPrice = { usd: maxPrice.usd, per: maxPrice.per };
2422
- if (opts.orderType && opts.market) {
2423
- throw new Error("--market and --order-type are mutually exclusive.");
2855
+ const res = await c.post("/api/v1/sandboxes", buildCreateBody(opts));
2856
+ if (opts.use !== false) {
2857
+ setCurrentInstance(res.sandbox.id, orgKey(opts));
2858
+ if (!opts.json && !opts.quiet) {
2859
+ console.error(pc4.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));
2860
+ }
2424
2861
  }
2425
- if (opts.orderType) body.orderType = opts.orderType;
2426
- if (opts.market) body.orderType = "market";
2427
- const res = await c.post("/api/v1/sandboxes", body);
2428
- output(opts, res.sandbox, printSandbox);
2862
+ emitResult(opts, res.sandbox, (s) => s.id, (s) => printSandbox(s, opts.verbose));
2429
2863
  } catch (e) {
2430
2864
  fail(e, opts);
2431
2865
  }
@@ -2459,54 +2893,165 @@ function registerSandboxesCommands(program2) {
2459
2893
  fail(e, opts);
2460
2894
  }
2461
2895
  });
2462
- 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) => {
2896
+ 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) => {
2463
2897
  try {
2898
+ checkQuietJson(opts);
2464
2899
  const c = await client(opts);
2465
2900
  const res = await c.get(
2466
2901
  "/api/v1/sandboxes",
2467
2902
  { status: opts.status, limit: opts.limit, cursor: opts.cursor }
2468
2903
  );
2469
- output(opts, res, (page) => {
2470
- page.sandboxes.forEach(printSandbox);
2471
- if (page.nextCursor) console.log(pc4.dim(`nextCursor: ${page.nextCursor}`));
2472
- });
2904
+ emitResult(
2905
+ opts,
2906
+ res,
2907
+ (page) => page.sandboxes.map((s) => s.id).join("\n"),
2908
+ (page) => {
2909
+ page.sandboxes.forEach((s) => printSandbox(s, opts.verbose));
2910
+ if (page.nextCursor) console.log(pc4.dim(`nextCursor: ${page.nextCursor}`));
2911
+ }
2912
+ );
2473
2913
  } catch (e) {
2474
2914
  fail(e, opts);
2475
2915
  }
2476
2916
  });
2477
- 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) => {
2917
+ 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) => {
2478
2918
  try {
2919
+ checkQuietJson(opts);
2920
+ const resolved = requireUuidOrImplicit(argId, opts);
2479
2921
  const c = await client(opts);
2480
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}`);
2481
- output(opts, res.sandbox, printSandbox);
2922
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}`);
2923
+ output(opts, res.sandbox, (s) => printSandbox(s, opts.verbose));
2482
2924
  } catch (e) {
2483
2925
  fail(e, opts);
2484
2926
  }
2485
2927
  });
2486
- 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) => {
2928
+ 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) => {
2487
2929
  try {
2930
+ const org2 = orgKey(opts);
2931
+ if (opts.clear) {
2932
+ const prev = clearCurrentInstance(org2);
2933
+ output(
2934
+ opts,
2935
+ { cleared: prev ?? null },
2936
+ () => console.log(
2937
+ prev ? `forgot ${shortId(prev)} (was current for ${dirKey()})` : "nothing to forget"
2938
+ )
2939
+ );
2940
+ return;
2941
+ }
2942
+ if (argId === void 0) {
2943
+ const r = resolveInstanceId(void 0, opts);
2944
+ output(opts, { id: r?.id ?? null, source: r?.source ?? null }, () => {
2945
+ if (!r) console.log(NO_INSTANCE_HINT);
2946
+ else {
2947
+ const where = r.source === "env" ? "COMPUTE_INSTANCE" : `current for ${r.dir}`;
2948
+ console.log(`instance ${shortId(r.id)} (${where})`);
2949
+ }
2950
+ });
2951
+ return;
2952
+ }
2953
+ if (!isUuid(argId)) {
2954
+ throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
2955
+ }
2488
2956
  const c = await client(opts);
2489
- const res = await c.del(`/api/v1/sandboxes/${sandboxId}`);
2957
+ const res = await c.get(`/api/v1/sandboxes/${argId}`);
2958
+ if (res.sandbox.status === "destroyed") {
2959
+ throw new Error(`instance ${shortId(argId)} is destroyed \u2014 pick a running instance`);
2960
+ }
2961
+ setCurrentInstance(argId, org2);
2962
+ output(
2963
+ opts,
2964
+ { id: argId, dir: dirKey() },
2965
+ () => console.log(`instance ${shortId(argId)} (current for ${dirKey()})`)
2966
+ );
2967
+ } catch (e) {
2968
+ fail(e, opts);
2969
+ }
2970
+ });
2971
+ 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) => {
2972
+ try {
2973
+ const resolved = requireUuidOrImplicit(argId, opts);
2974
+ const c = await client(opts);
2975
+ const res = await c.del(`/api/v1/sandboxes/${resolved.id}`).catch((e) => {
2976
+ resolved.clearStale(e);
2977
+ throw e;
2978
+ });
2979
+ const org2 = orgKey(opts);
2980
+ if (readFileCurrent(org2) === resolved.id) {
2981
+ clearCurrentInstance(org2);
2982
+ if (!opts.json) {
2983
+ console.error(pc4.dim(`cleared current instance ${shortId(resolved.id)}`));
2984
+ }
2985
+ }
2490
2986
  output(opts, res.sandbox, printSandbox);
2491
2987
  } catch (e) {
2492
2988
  fail(e, opts);
2493
2989
  }
2494
2990
  });
2495
- 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) => {
2991
+ addCreateFlags(
2992
+ cmd.command("run [command...]").description(
2993
+ "Create an instance, run a command on it, and tear it down. `run -- <cmd>` waits and destroys; `--keep` waits and keeps; `-d` returns immediately."
2994
+ )
2995
+ ).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) => {
2496
2996
  let opts = rawOpts;
2497
2997
  try {
2998
+ checkQuietJson(opts);
2999
+ if (opts.keep && opts.detach) throw new Error("--keep and --detach are mutually exclusive.");
2498
3000
  const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
2499
3001
  opts = mergeLeadOpts(rawOpts, lead.inline);
2500
3002
  const command = lead.command;
2501
3003
  if (command.length === 0) throw new Error("missing command to run");
3004
+ await runInstanceCommand(command, opts);
3005
+ } catch (e) {
3006
+ fail(e, opts);
3007
+ }
3008
+ });
3009
+ 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) => {
3010
+ let opts = rawOpts;
3011
+ try {
3012
+ checkQuietJson(opts);
3013
+ if (argId !== void 0 && !isUuid(argId)) {
3014
+ rawCommand.unshift(argId);
3015
+ argId = void 0;
3016
+ }
3017
+ const lead = takeLeadingOptions(rawCommand, SERVE_LEAD_OPTS);
3018
+ opts = mergeLeadOpts(rawOpts, lead.inline);
3019
+ const command = lead.command;
3020
+ if (command.length === 0) throw new Error("missing command to serve");
3021
+ if (opts.port === void 0) throw new Error("--port is required");
3022
+ const port = Number(opts.port);
3023
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3024
+ throw new Error("--port must be an integer between 1 and 65535");
3025
+ }
3026
+ const resolved = resolveSandbox(argId, opts);
3027
+ await serveInstanceCommand(resolved.id, command, port, opts);
3028
+ } catch (e) {
3029
+ fail(e, opts);
3030
+ }
3031
+ });
3032
+ 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) => {
3033
+ let opts = rawOpts;
3034
+ try {
3035
+ if (argId !== void 0 && !isUuid(argId)) {
3036
+ rawCommand.unshift(argId);
3037
+ argId = void 0;
3038
+ }
3039
+ const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
3040
+ opts = mergeLeadOpts(rawOpts, lead.inline);
3041
+ const command = lead.command;
3042
+ if (command.length === 0) throw new Error("missing command to run");
3043
+ const resolved = resolveSandbox(argId, opts);
2502
3044
  const c = await client(opts);
2503
3045
  const res = await c.post(
2504
- `/api/v1/sandboxes/${sandboxId}/commands`,
3046
+ `/api/v1/sandboxes/${resolved.id}/commands`,
2505
3047
  {
2506
3048
  command: command.map(shellQuote).join(" "),
2507
3049
  ...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
2508
3050
  }
2509
- );
3051
+ ).catch((e) => {
3052
+ resolved.clearStale(e);
3053
+ throw e;
3054
+ });
2510
3055
  output(opts, res, (r) => {
2511
3056
  process.stdout.write(r.stdout);
2512
3057
  if (r.stderr) process.stderr.write(r.stderr);
@@ -2517,48 +3062,59 @@ function registerSandboxesCommands(program2) {
2517
3062
  fail(e, opts);
2518
3063
  }
2519
3064
  });
2520
- 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) => {
3065
+ 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) => {
2521
3066
  let opts = rawOpts;
2522
3067
  try {
3068
+ if (argId !== void 0 && !isUuid(argId)) {
3069
+ rawCommand.unshift(argId);
3070
+ argId = void 0;
3071
+ }
2523
3072
  const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);
2524
3073
  opts = mergeLeadOpts(rawOpts, lead.inline);
3074
+ checkQuietJson(opts);
2525
3075
  const command = lead.command;
2526
3076
  if (command.length === 0) throw new Error("missing command to spawn");
3077
+ const resolved = resolveSandbox(argId, opts);
2527
3078
  const c = await client(opts);
2528
3079
  const res = await c.post(
2529
- `/api/v1/sandboxes/${sandboxId}/processes`,
3080
+ `/api/v1/sandboxes/${resolved.id}/processes`,
2530
3081
  {
2531
3082
  command: command.map(shellQuote).join(" "),
2532
3083
  ...opts.cwd ? { cwd: opts.cwd } : {},
2533
3084
  ...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
2534
3085
  ...opts.stdin ? { stdin: true } : {}
2535
3086
  }
2536
- );
2537
- output(opts, res.process, printProcess);
3087
+ ).catch((e) => {
3088
+ resolved.clearStale(e);
3089
+ throw e;
3090
+ });
3091
+ emitResult(opts, res.process, (p2) => p2.jobId, printProcess);
2538
3092
  } catch (e) {
2539
3093
  fail(e, opts);
2540
3094
  }
2541
3095
  });
2542
- 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) => {
3096
+ 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) => {
2543
3097
  try {
3098
+ const resolved = requireUuidOrImplicit(argId, opts);
2544
3099
  const c = await client(opts);
2545
3100
  const res = await c.get(
2546
- `/api/v1/sandboxes/${sandboxId}/processes`
3101
+ `/api/v1/sandboxes/${resolved.id}/processes`
2547
3102
  );
2548
3103
  output(opts, res.processes, (list) => list.forEach(printProcess));
2549
3104
  } catch (e) {
2550
3105
  fail(e, opts);
2551
3106
  }
2552
3107
  });
2553
- 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) => {
3108
+ 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) => {
2554
3109
  try {
3110
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2555
3111
  const c = await client(opts);
2556
3112
  if (opts.follow) {
2557
- await followProcess(c, sandboxId, jobId);
3113
+ await followProcess(c, resolved.id, job);
2558
3114
  return;
2559
3115
  }
2560
3116
  const res = await c.get(
2561
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`
3117
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}`
2562
3118
  );
2563
3119
  output(opts, res.process, (p2) => {
2564
3120
  if (p2.stdout) process.stdout.write(p2.stdout);
@@ -2569,11 +3125,12 @@ function registerSandboxesCommands(program2) {
2569
3125
  fail(e, opts);
2570
3126
  }
2571
3127
  });
2572
- 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) => {
3128
+ 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) => {
2573
3129
  try {
3130
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2574
3131
  const c = await client(opts);
2575
3132
  const res = await c.post(
2576
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,
3133
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/wait`,
2577
3134
  opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
2578
3135
  );
2579
3136
  output(opts, res.process, printProcess);
@@ -2584,11 +3141,12 @@ function registerSandboxesCommands(program2) {
2584
3141
  fail(e, opts);
2585
3142
  }
2586
3143
  });
2587
- 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) => {
3144
+ 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) => {
2588
3145
  try {
3146
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2589
3147
  const c = await client(opts);
2590
3148
  const res = await c.post(
2591
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,
3149
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/kill`,
2592
3150
  opts.signal ? { signal: opts.signal } : {}
2593
3151
  );
2594
3152
  output(opts, res.process, printProcess);
@@ -2596,18 +3154,19 @@ function registerSandboxesCommands(program2) {
2596
3154
  fail(e, opts);
2597
3155
  }
2598
3156
  });
2599
- 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) => {
3157
+ 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) => {
2600
3158
  try {
3159
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2601
3160
  let data = opts.data;
2602
3161
  if (data === void 0 && opts.file) {
2603
3162
  const { readFile } = await import("fs/promises");
2604
3163
  data = opts.base64 ? (await readFile(opts.file)).toString("base64") : await readFile(opts.file, "utf8");
2605
3164
  }
2606
3165
  if (data === void 0 && !process.stdin.isTTY) {
2607
- const piped = await new Promise((resolve) => {
3166
+ const piped = await new Promise((resolve2) => {
2608
3167
  const chunks = [];
2609
3168
  process.stdin.on("data", (chunk) => chunks.push(chunk));
2610
- process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
3169
+ process.stdin.on("end", () => resolve2(Buffer.concat(chunks)));
2611
3170
  });
2612
3171
  data = opts.base64 ? piped.toString("base64") : piped.toString("utf8");
2613
3172
  }
@@ -2620,31 +3179,42 @@ function registerSandboxesCommands(program2) {
2620
3179
  }
2621
3180
  const c = await client(opts);
2622
3181
  const res = await c.post(
2623
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/stdin`,
3182
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/stdin`,
2624
3183
  { data, ...opts.base64 ? { encoding: "base64" } : {} }
2625
3184
  );
2626
- output(opts, res, () => console.log(`wrote ${data.length} chars to ${jobId}`));
3185
+ output(opts, res, () => console.log(`wrote ${data.length} chars to ${job}`));
2627
3186
  } catch (e) {
2628
3187
  fail(e, opts);
2629
3188
  }
2630
3189
  });
2631
- 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) => {
3190
+ 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) => {
2632
3191
  try {
3192
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2633
3193
  const c = await client(opts);
2634
3194
  const res = await c.post(
2635
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/close-stdin`,
3195
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/close-stdin`,
2636
3196
  {}
2637
3197
  );
2638
- output(opts, res, () => console.log(`closed stdin on ${jobId}`));
3198
+ output(opts, res, () => console.log(`closed stdin on ${job}`));
2639
3199
  } catch (e) {
2640
3200
  fail(e, opts);
2641
3201
  }
2642
3202
  });
2643
- 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) => {
3203
+ 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) => {
2644
3204
  try {
3205
+ let resolved;
3206
+ let p2;
3207
+ if (argId !== void 0 && !isUuid(argId)) {
3208
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3209
+ resolved = resolveSandbox(void 0, opts);
3210
+ p2 = argId;
3211
+ } else {
3212
+ resolved = resolveSandbox(argId, opts);
3213
+ p2 = path2 ?? "/";
3214
+ }
2645
3215
  const c = await client(opts);
2646
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/files`, {
2647
- path: path ?? "/"
3216
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, {
3217
+ path: p2
2648
3218
  });
2649
3219
  output(opts, res, (view) => {
2650
3220
  if (view.type === "directory") {
@@ -2659,10 +3229,21 @@ function registerSandboxesCommands(program2) {
2659
3229
  fail(e, opts);
2660
3230
  }
2661
3231
  });
2662
- 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) => {
3232
+ 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) => {
2663
3233
  try {
3234
+ let resolved;
3235
+ let p2;
3236
+ if (argId !== void 0 && !isUuid(argId)) {
3237
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3238
+ resolved = resolveSandbox(void 0, opts);
3239
+ p2 = argId;
3240
+ } else {
3241
+ resolved = resolveSandbox(argId, opts);
3242
+ if (path2 === void 0) throw new Error("missing path");
3243
+ p2 = path2;
3244
+ }
2664
3245
  const c = await client(opts);
2665
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/files`, { path });
3246
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, { path: p2 });
2666
3247
  output(opts, res, (view) => {
2667
3248
  if (view.type !== "file") {
2668
3249
  console.error(pc4.red(`${view.path} is a directory`));
@@ -2675,19 +3256,30 @@ function registerSandboxesCommands(program2) {
2675
3256
  fail(e, opts);
2676
3257
  }
2677
3258
  });
2678
- 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) => {
3259
+ 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) => {
2679
3260
  try {
3261
+ let resolved;
3262
+ let p2;
3263
+ if (argId !== void 0 && !isUuid(argId)) {
3264
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3265
+ resolved = resolveSandbox(void 0, opts);
3266
+ p2 = argId;
3267
+ } else {
3268
+ resolved = resolveSandbox(argId, opts);
3269
+ if (path2 === void 0) throw new Error("missing path");
3270
+ p2 = path2;
3271
+ }
2680
3272
  let content = opts.content;
2681
3273
  if (content === void 0 && opts.file) {
2682
3274
  const { readFile } = await import("fs/promises");
2683
3275
  content = await readFile(opts.file, "utf8");
2684
3276
  }
2685
3277
  if (content === void 0 && !process.stdin.isTTY) {
2686
- content = await new Promise((resolve) => {
3278
+ content = await new Promise((resolve2) => {
2687
3279
  let data = "";
2688
3280
  process.stdin.setEncoding("utf8");
2689
3281
  process.stdin.on("data", (chunk) => data += chunk);
2690
- process.stdin.on("end", () => resolve(data));
3282
+ process.stdin.on("end", () => resolve2(data));
2691
3283
  });
2692
3284
  }
2693
3285
  if (content === void 0) {
@@ -2696,19 +3288,30 @@ function registerSandboxesCommands(program2) {
2696
3288
  }
2697
3289
  const c = await client(opts);
2698
3290
  const res = await c.post(
2699
- `/api/v1/sandboxes/${sandboxId}/files`,
2700
- { path, content }
3291
+ `/api/v1/sandboxes/${resolved.id}/files`,
3292
+ { path: p2, content }
2701
3293
  );
2702
3294
  output(opts, res, (r) => console.log(`wrote ${r.path}`));
2703
3295
  } catch (e) {
2704
3296
  fail(e, opts);
2705
3297
  }
2706
3298
  });
2707
- 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) => {
3299
+ 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) => {
2708
3300
  try {
3301
+ let resolved;
3302
+ let p2;
3303
+ if (argId !== void 0 && !isUuid(argId)) {
3304
+ if (path2 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
3305
+ resolved = resolveSandbox(void 0, opts);
3306
+ p2 = argId;
3307
+ } else {
3308
+ resolved = resolveSandbox(argId, opts);
3309
+ if (path2 === void 0) throw new Error("missing path");
3310
+ p2 = path2;
3311
+ }
2709
3312
  const c = await client(opts);
2710
- const res = await c.post(`/api/v1/sandboxes/${sandboxId}/files`, {
2711
- path,
3313
+ const res = await c.post(`/api/v1/sandboxes/${resolved.id}/files`, {
3314
+ path: p2,
2712
3315
  mkdir: true
2713
3316
  });
2714
3317
  output(opts, res, (r) => console.log(`created ${r.path}`));
@@ -2716,45 +3319,68 @@ function registerSandboxesCommands(program2) {
2716
3319
  fail(e, opts);
2717
3320
  }
2718
3321
  });
2719
- 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) => {
3322
+ 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) => {
2720
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
+ }
2721
3335
  const c = await client(opts);
2722
3336
  const res = await c.del(
2723
- `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`
3337
+ `/api/v1/sandboxes/${resolved.id}/files?path=${encodeURIComponent(p2)}`
2724
3338
  );
2725
3339
  output(opts, res, (r) => console.log(`removed ${r.path}`));
2726
3340
  } catch (e) {
2727
3341
  fail(e, opts);
2728
3342
  }
2729
3343
  });
2730
- 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) => {
3344
+ 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) => {
2731
3345
  try {
3346
+ checkQuietJson(opts);
3347
+ await cpCommand(src, dst, opts);
3348
+ } catch (e) {
3349
+ fail(e, opts);
3350
+ }
3351
+ });
3352
+ 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) => {
3353
+ try {
3354
+ checkQuietJson(opts);
3355
+ const resolved = requireUuidOrImplicit(argId, opts);
2732
3356
  const c = await client(opts);
2733
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/urls`, {
3357
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/urls`, {
2734
3358
  port: opts.port,
2735
3359
  protocol: opts.protocol
2736
3360
  });
2737
- output(opts, res, (r) => console.log(safeTerm(r.url)));
3361
+ emitResult(opts, res, (r) => safeTerm(r.url), (r) => console.log(safeTerm(r.url)));
2738
3362
  } catch (e) {
2739
3363
  fail(e, opts);
2740
3364
  }
2741
3365
  });
2742
- 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) => {
3366
+ 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) => {
2743
3367
  try {
3368
+ const resolved = requireUuidOrImplicit(argId, opts);
2744
3369
  const c = await client(opts);
2745
3370
  const res = await c.get(
2746
- `/api/v1/sandboxes/${sandboxId}/snapshots`
3371
+ `/api/v1/sandboxes/${resolved.id}/snapshots`
2747
3372
  );
2748
3373
  output(opts, res.snapshots, (list) => list.forEach(printSnapshot));
2749
3374
  } catch (e) {
2750
3375
  fail(e, opts);
2751
3376
  }
2752
3377
  });
2753
- 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) => {
3378
+ 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) => {
2754
3379
  try {
3380
+ const resolved = requireUuidOrImplicit(argId, opts);
2755
3381
  const c = await client(opts);
2756
3382
  const res = await c.post(
2757
- `/api/v1/sandboxes/${sandboxId}/snapshots`,
3383
+ `/api/v1/sandboxes/${resolved.id}/snapshots`,
2758
3384
  opts.label ? { label: opts.label } : {}
2759
3385
  );
2760
3386
  output(opts, res.snapshot, printSnapshot);
@@ -2762,13 +3388,14 @@ function registerSandboxesCommands(program2) {
2762
3388
  fail(e, opts);
2763
3389
  }
2764
3390
  });
2765
- 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) => {
3391
+ 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) => {
2766
3392
  try {
3393
+ const { resolved, resource: snap } = resolveTwoArgTarget(argId, snapshotId, opts, "snapshotId");
2767
3394
  const c = await client(opts);
2768
3395
  const res = await c.del(
2769
- `/api/v1/sandboxes/${sandboxId}/snapshots/${snapshotId}`
3396
+ `/api/v1/sandboxes/${resolved.id}/snapshots/${snap}`
2770
3397
  );
2771
- output(opts, res, () => console.log(`deleted snapshot ${snapshotId}`));
3398
+ output(opts, res, () => console.log(`deleted snapshot ${snap}`));
2772
3399
  } catch (e) {
2773
3400
  fail(e, opts);
2774
3401
  }
@@ -2806,12 +3433,353 @@ async function followProcess(c, sandboxId, jobId) {
2806
3433
  if (exitCode !== 0) process.exitCode = exitCode;
2807
3434
  }
2808
3435
  }
3436
+ function printDetachSummary(sandboxId, jobId, timeoutText) {
3437
+ console.log(`instance ${sandboxId} job ${jobId} (running; ${timeoutText})`);
3438
+ console.log(` follow: compute instances logs ${sandboxId} ${jobId}`);
3439
+ console.log(` wait: compute instances wait ${sandboxId} ${jobId}`);
3440
+ console.log(` destroy: compute instances destroy ${sandboxId}`);
3441
+ }
3442
+ function runTimeoutText(opts) {
3443
+ return opts.timeoutMs ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}` : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;
3444
+ }
3445
+ async function runInstanceCommand(command, opts) {
3446
+ const c = await client(opts);
3447
+ const created = await c.post("/api/v1/sandboxes", buildCreateBody(opts));
3448
+ const sandbox = created.sandbox;
3449
+ const org2 = orgKey(opts);
3450
+ console.error(pc4.dim(`instance ${sandbox.id}`));
3451
+ const spawned = await c.post(
3452
+ `/api/v1/sandboxes/${sandbox.id}/processes`,
3453
+ { command: command.map(shellQuote).join(" ") }
3454
+ ).catch(async (e) => {
3455
+ try {
3456
+ await c.del(`/api/v1/sandboxes/${sandbox.id}`);
3457
+ } catch {
3458
+ }
3459
+ throw e;
3460
+ });
3461
+ const jobId = spawned.process.jobId;
3462
+ if (opts.detach) {
3463
+ setCurrentInstance(sandbox.id, org2);
3464
+ if (opts.quiet) console.log(sandbox.id);
3465
+ else printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
3466
+ return;
3467
+ }
3468
+ let exitCode = null;
3469
+ let destroyRequested = false;
3470
+ let detachRequested = false;
3471
+ let prompting = false;
3472
+ let printedOut = 0;
3473
+ let printedErr = 0;
3474
+ const flush = (p2) => {
3475
+ if (prompting) return;
3476
+ if (p2.stdout.length > printedOut) {
3477
+ process.stdout.write(p2.stdout.slice(printedOut));
3478
+ printedOut = p2.stdout.length;
3479
+ }
3480
+ if (p2.stderr.length > printedErr) {
3481
+ process.stderr.write(p2.stderr.slice(printedErr));
3482
+ printedErr = p2.stderr.length;
3483
+ }
3484
+ };
3485
+ const onSignal = () => {
3486
+ if (!process.stdin.isTTY || opts.yes || prompting) {
3487
+ if (prompting) return;
3488
+ destroyRequested = true;
3489
+ return;
3490
+ }
3491
+ prompting = true;
3492
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
3493
+ rl.question(`Destroy instance ${shortId(sandbox.id)}? [y/N/d] `, (answer) => {
3494
+ rl.close();
3495
+ prompting = false;
3496
+ const a = answer.trim().toLowerCase();
3497
+ if (a === "y") destroyRequested = true;
3498
+ else if (a === "d") detachRequested = true;
3499
+ });
3500
+ };
3501
+ process.on("SIGINT", onSignal);
3502
+ process.on("SIGTERM", onSignal);
3503
+ try {
3504
+ const deadline = opts.timeoutMs ? Date.now() + Number(opts.timeoutMs) : void 0;
3505
+ while (exitCode === null && !destroyRequested && !detachRequested) {
3506
+ const remaining = deadline === void 0 ? 55e3 : Math.max(1, deadline - Date.now());
3507
+ const res = await c.post(
3508
+ `/api/v1/sandboxes/${sandbox.id}/processes/${jobId}/wait`,
3509
+ { timeoutMs: Math.min(55e3, remaining) }
3510
+ );
3511
+ flush(res.process);
3512
+ if (res.process.status === "exited") {
3513
+ exitCode = res.process.exitCode ?? 128;
3514
+ } else if (deadline !== void 0 && Date.now() >= deadline) {
3515
+ destroyRequested = true;
3516
+ }
3517
+ }
3518
+ } finally {
3519
+ process.removeListener("SIGINT", onSignal);
3520
+ process.removeListener("SIGTERM", onSignal);
3521
+ if (detachRequested) {
3522
+ setCurrentInstance(sandbox.id, org2);
3523
+ printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
3524
+ } else if (opts.keep && exitCode !== null) {
3525
+ setCurrentInstance(sandbox.id, org2);
3526
+ if (opts.quiet) console.log(sandbox.id);
3527
+ else {
3528
+ console.error(pc4.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));
3529
+ console.log(sandbox.id);
3530
+ }
3531
+ } else {
3532
+ try {
3533
+ await c.del(`/api/v1/sandboxes/${sandbox.id}`);
3534
+ } catch (e) {
3535
+ console.error(
3536
+ pc4.red(`destroy failed for ${sandbox.id}: ${e instanceof Error ? e.message : String(e)}`)
3537
+ );
3538
+ if (exitCode === null || exitCode === 0) exitCode = 1;
3539
+ }
3540
+ const orgNow = orgKey(opts);
3541
+ if (readFileCurrent(orgNow) === sandbox.id) clearCurrentInstance(orgNow);
3542
+ }
3543
+ }
3544
+ process.exitCode = detachRequested ? 0 : exitCode ?? (destroyRequested ? 130 : 1);
3545
+ }
3546
+ var SERVE_POLL_MS = 3e4;
3547
+ var SERVE_DEFAULT_WAIT_MS = 12e4;
3548
+ async function serveInstanceCommand(id, command, port, opts) {
3549
+ const c = await client(opts);
3550
+ const spawned = await c.post(
3551
+ `/api/v1/sandboxes/${id}/processes`,
3552
+ {
3553
+ command: command.map(shellQuote).join(" "),
3554
+ ...opts.cwd ? { cwd: opts.cwd } : {},
3555
+ ...opts.env?.length ? { env: parseInputs(opts.env) } : {}
3556
+ }
3557
+ );
3558
+ const jobId = spawned.process.jobId;
3559
+ const jobStatus = () => c.get(`/api/v1/sandboxes/${id}/processes/${jobId}`);
3560
+ const reportExit = (proc) => {
3561
+ if (!opts.json) {
3562
+ const logs = `${proc.stdout}${proc.stderr}`.trimEnd().split("\n");
3563
+ if (logs.length > 0 && logs[0] !== "") {
3564
+ console.error(pc4.dim("--- last log lines ---"));
3565
+ for (const line of logs.slice(-50)) console.error(safeTerm(line));
3566
+ }
3567
+ }
3568
+ fail(new Error(`The server exited (code ${proc.exitCode ?? "?"}) before port ${port} listened.`), opts);
3569
+ };
3570
+ const waitMs = opts.timeoutMs ? Number(opts.timeoutMs) : SERVE_DEFAULT_WAIT_MS;
3571
+ const deadline = Date.now() + waitMs;
3572
+ let entry;
3573
+ let remaining = waitMs;
3574
+ while (!entry && remaining > 0) {
3575
+ const res = await c.get(
3576
+ `/api/v1/sandboxes/${id}/ports?wait=${port}&timeoutMs=${Math.min(SERVE_POLL_MS, remaining)}`
3577
+ );
3578
+ entry = res.ports.find((p2) => p2.port === port);
3579
+ if (entry) break;
3580
+ const proc = await jobStatus();
3581
+ if (proc.process.status === "exited") {
3582
+ reportExit(proc.process);
3583
+ return;
3584
+ }
3585
+ remaining = deadline - Date.now();
3586
+ }
3587
+ if (entry) {
3588
+ const proc = await jobStatus();
3589
+ if (proc.process.status === "exited") {
3590
+ reportExit(proc.process);
3591
+ return;
3592
+ }
3593
+ } else {
3594
+ if (!opts.json) printServeJobFooter(id, jobId);
3595
+ fail(new Error(`Port ${port} never listened within ${fmtTimeout(waitMs)}.`), opts);
3596
+ return;
3597
+ }
3598
+ if (!entry.public) {
3599
+ if (!opts.json) printServeJobFooter(id, jobId);
3600
+ fail(
3601
+ new Error(
3602
+ `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.`
3603
+ ),
3604
+ opts
3605
+ );
3606
+ return;
3607
+ }
3608
+ const { url } = await c.get(`/api/v1/sandboxes/${id}/urls?port=${port}`);
3609
+ if (opts.quiet) {
3610
+ console.log(safeTerm(url));
3611
+ return;
3612
+ }
3613
+ output(opts, { url }, () => {
3614
+ console.log(safeTerm(url));
3615
+ printServeJobFooter(id, jobId);
3616
+ });
3617
+ }
3618
+ function printServeJobFooter(sandboxId, jobId) {
3619
+ console.error(pc4.dim(` job ${jobId}`));
3620
+ console.error(pc4.dim(` logs: compute instances logs ${sandboxId} ${jobId}`));
3621
+ console.error(pc4.dim(` kill: compute instances kill ${sandboxId} ${jobId}`));
3622
+ }
3623
+ var CP_PROGRESS_MIN_BYTES = 10 * 1024 * 1024;
3624
+ function assertTransferUrl(raw) {
3625
+ let u;
3626
+ try {
3627
+ u = new URL(raw);
3628
+ } catch {
3629
+ throw new Error("platform returned a malformed transfer URL");
3630
+ }
3631
+ if (u.protocol === "https:") return;
3632
+ const loopback = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname);
3633
+ if (!(u.protocol === "http:" && loopback)) {
3634
+ throw new Error(`refusing insecure transfer URL: ${u.protocol}//${u.hostname} (expected https)`);
3635
+ }
3636
+ }
3637
+ function tarEntryIsSafe(p2, entry) {
3638
+ if (path.isAbsolute(p2) || p2.split("/").includes("..")) return false;
3639
+ const { type, linkpath } = entry;
3640
+ if ((type === "Link" || type === "SymbolicLink") && linkpath) {
3641
+ if (path.isAbsolute(linkpath) || linkpath.split("/").includes("..")) return false;
3642
+ }
3643
+ return true;
3644
+ }
3645
+ function parseCpEndpoint(arg) {
3646
+ 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);
3647
+ if (m) return { remoteId: m[1] || void 0, remotePath: m[2] };
3648
+ return { local: arg };
3649
+ }
3650
+ async function cpCommand(src, dst, opts) {
3651
+ const s = parseCpEndpoint(src);
3652
+ const d = parseCpEndpoint(dst);
3653
+ const sRemote = "remotePath" in s;
3654
+ const dRemote = "remotePath" in d;
3655
+ if (sRemote === dRemote) {
3656
+ throw new Error("cp needs exactly one remote side \u2014 write it as [id:]/abs/path (e.g. 3f2a\u2026:/app or :/app)");
3657
+ }
3658
+ const c = await client(opts);
3659
+ if (!sRemote && "remotePath" in d && "local" in s) {
3660
+ const resolved = resolveSandbox(d.remoteId, opts);
3661
+ const r = await cpUpload(c, resolved.id, s.local, d.remotePath, opts);
3662
+ output(opts, r, (done) => {
3663
+ if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) \u2192 ${shortId(resolved.id)}:${d.remotePath}`);
3664
+ });
3665
+ } else if ("remotePath" in s && "local" in d) {
3666
+ const resolved = resolveSandbox(s.remoteId, opts);
3667
+ const r = await cpDownload(c, resolved.id, s.remotePath, d.local, opts);
3668
+ output(opts, r, (done) => {
3669
+ if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) \u2192 ${d.local}`);
3670
+ });
3671
+ }
3672
+ }
3673
+ function cpProgress(total, opts) {
3674
+ const show = !opts.quiet && !opts.json && process.stderr.isTTY && total > CP_PROGRESS_MIN_BYTES;
3675
+ let sent = 0;
3676
+ return {
3677
+ bump(n) {
3678
+ if (!show) return;
3679
+ sent += n;
3680
+ process.stderr.write(`\r${formatBytes(sent)} / ${formatBytes(total)} (${Math.round(sent / total * 100)}%)`);
3681
+ },
3682
+ done() {
3683
+ if (show) process.stderr.write("\n");
3684
+ }
3685
+ };
3686
+ }
3687
+ async function cpUpload(c, sandboxId, localPath, remotePath, opts) {
3688
+ const abs = path.resolve(localPath);
3689
+ fs.statSync(abs);
3690
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "compute-cp-up-"));
3691
+ const tmp = path.join(tmpDir, "archive.tar.gz");
3692
+ try {
3693
+ await tar.create({ gzip: true, file: tmp, cwd: path.dirname(abs) }, [path.basename(abs)]);
3694
+ const size = fs.statSync(tmp).size;
3695
+ const created = await c.post(
3696
+ `/api/v1/sandboxes/${sandboxId}/transfers`,
3697
+ { direction: "upload", path: remotePath }
3698
+ );
3699
+ if (!created.uploadUrl) throw new Error("platform did not return an upload URL");
3700
+ assertTransferUrl(created.uploadUrl);
3701
+ const progress = cpProgress(size, opts);
3702
+ try {
3703
+ const stream = fs.createReadStream(tmp);
3704
+ stream.on("data", (chunk) => progress.bump(typeof chunk === "string" ? chunk.length : chunk.byteLength));
3705
+ const res = await fetch(created.uploadUrl, {
3706
+ method: "PUT",
3707
+ headers: { "content-length": String(size), "content-type": "application/gzip" },
3708
+ // @ts-expect-error Readable.toWeb body is supported at runtime; DOM types lag
3709
+ body: Readable.toWeb(stream),
3710
+ duplex: "half"
3711
+ });
3712
+ if (!res.ok) throw new Error(`upload failed: HTTP ${res.status}`);
3713
+ } finally {
3714
+ progress.done();
3715
+ }
3716
+ return await c.post(
3717
+ `/api/v1/sandboxes/${sandboxId}/transfers/${created.transferId}/complete`,
3718
+ {}
3719
+ );
3720
+ } finally {
3721
+ fs.rmSync(tmpDir, { recursive: true, force: true });
3722
+ }
3723
+ }
3724
+ async function cpDownload(c, sandboxId, remotePath, localDir, opts) {
3725
+ const created = await c.post(
3726
+ `/api/v1/sandboxes/${sandboxId}/transfers`,
3727
+ { direction: "download", path: remotePath }
3728
+ );
3729
+ if (!created.downloadUrl) throw new Error("platform did not return a download URL");
3730
+ assertTransferUrl(created.downloadUrl);
3731
+ const res = await fetch(created.downloadUrl);
3732
+ if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`);
3733
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "compute-cp-dl-"));
3734
+ const tmp = path.join(tmpDir, "archive.tar.gz");
3735
+ try {
3736
+ const progress = cpProgress(created.bytes ?? 0, opts);
3737
+ const ws = fs.createWriteStream(tmp);
3738
+ try {
3739
+ await new Promise((resolve2, reject) => {
3740
+ ws.once("error", reject);
3741
+ const reader = res.body.getReader();
3742
+ const pump = async () => {
3743
+ for (; ; ) {
3744
+ const { done, value } = await reader.read();
3745
+ if (done || value === void 0) break;
3746
+ progress.bump(value.byteLength);
3747
+ if (!ws.write(value)) await new Promise((r) => ws.once("drain", () => r()));
3748
+ }
3749
+ };
3750
+ pump().then(
3751
+ () => ws.end(() => resolve2()),
3752
+ reject
3753
+ );
3754
+ });
3755
+ } finally {
3756
+ ws.destroy();
3757
+ }
3758
+ progress.done();
3759
+ fs.mkdirSync(localDir, { recursive: true });
3760
+ await tar.extract({ file: tmp, cwd: localDir, filter: tarEntryIsSafe });
3761
+ return { path: localDir, bytes: created.bytes ?? fs.statSync(tmp).size, files: created.files ?? 0 };
3762
+ } finally {
3763
+ fs.rmSync(tmpDir, { recursive: true, force: true });
3764
+ }
3765
+ }
3766
+ function formatBytes(n) {
3767
+ if (n < 1024) return `${n} B`;
3768
+ const units = ["KB", "MB", "GB", "TB"];
3769
+ let v = n / 1024;
3770
+ let i = 0;
3771
+ while (v >= 1024 && i < units.length - 1) {
3772
+ v /= 1024;
3773
+ i += 1;
3774
+ }
3775
+ return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
3776
+ }
2809
3777
 
2810
3778
  // src/index.ts
2811
3779
  var __filename2 = fileURLToPath(import.meta.url);
2812
- var __dirname2 = dirname(__filename2);
3780
+ var __dirname2 = dirname2(__filename2);
2813
3781
  var packageJson = JSON.parse(
2814
- readFileSync2(join2(__dirname2, "..", "package.json"), "utf-8")
3782
+ readFileSync3(join4(__dirname2, "..", "package.json"), "utf-8")
2815
3783
  );
2816
3784
  var isDevBuild = import.meta.url.includes("worktrees") || import.meta.url.includes("/packages/cli/");
2817
3785
  var VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;