@computesdk/cli 2.5.6 → 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
  });
@@ -1031,9 +1031,9 @@ function printDiscovery(d) {
1031
1031
  function isPatchedWorkflowTarget(target) {
1032
1032
  return "workflowPath" in target;
1033
1033
  }
1034
- function patchTouches(patch, path) {
1035
- const plain = `+++ b/${path}`;
1036
- const quoted = `+++ "b/${path}"`;
1034
+ function patchTouches(patch, path2) {
1035
+ const plain = `+++ b/${path2}`;
1036
+ const quoted = `+++ "b/${path2}"`;
1037
1037
  return patch.split("\n").some((line) => {
1038
1038
  const header = line.replace(/\t.*$/, "");
1039
1039
  return header === plain || header === quoted;
@@ -1150,13 +1150,13 @@ function parseVaultKind(kind) {
1150
1150
  if (kind === void 0 || kind === "secret" || kind === "variable") return kind ?? "secret";
1151
1151
  throw new ActionsCliError("invalid_argument", `--kind must be secret or variable, got "${kind}".`);
1152
1152
  }
1153
- function vaultPath(path, params) {
1153
+ function vaultPath(path2, params) {
1154
1154
  const search = new URLSearchParams();
1155
1155
  for (const [key, value] of Object.entries(params)) {
1156
1156
  if (value !== void 0) search.set(key, value);
1157
1157
  }
1158
1158
  const query = search.toString();
1159
- return query ? `${path}?${query}` : path;
1159
+ return query ? `${path2}?${query}` : path2;
1160
1160
  }
1161
1161
  function vaultSetBody(name, value, opts) {
1162
1162
  if (value === "") throw new ActionsCliError("invalid_argument", "The value is empty.");
@@ -1589,8 +1589,8 @@ function registerActionsCommands(program2) {
1589
1589
  vault.command("ls").description("List names and metadata (never values)")
1590
1590
  ).action(async (opts) => {
1591
1591
  try {
1592
- const path = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind) });
1593
- 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);
1594
1594
  output(opts, data, (d) => {
1595
1595
  for (const item of d.items) console.log(formatVaultRow(item));
1596
1596
  });
@@ -1665,8 +1665,8 @@ function registerActionsCommands(program2) {
1665
1665
  vault.command("rm").description("Delete an item (with --repo, only the repo's override)").argument("<name>", "item name")
1666
1666
  ).action(async (name, opts) => {
1667
1667
  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);
1668
+ const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
1669
+ const result = await (await client(opts)).del(path2);
1670
1670
  output(opts, result, (r) => console.log(`deleted ${pc2.cyan(safeTerm(r.name))} ${pc2.dim(`(${r.kind})`)}`));
1671
1671
  } catch (e) {
1672
1672
  fail(e, opts);
@@ -2495,25 +2495,151 @@ ${hints}`
2495
2495
  }
2496
2496
 
2497
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";
2498
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
2499
2610
  function shellQuote(arg) {
2500
2611
  return `'${arg.replace(/'/g, `'\\''`)}'`;
2501
2612
  }
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}`);
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}`);
2506
2633
  if (s.image !== void 0) {
2507
2634
  console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc4.dim(`(requested: ${s.requestedImage})`)}` : ""}`);
2508
2635
  }
2509
- if (s.destroyError) console.log(` destroyError: ${pc4.red(s.destroyError)}`);
2510
- if (s.placement) {
2511
- const p2 = s.placement;
2636
+ if (p2) {
2512
2637
  const box = p2.box ? ` / ${p2.box.sizeName ?? "custom"}${p2.box.resources ? ` (${p2.box.resources.cpus ?? "?"} vCPU / ${p2.box.resources.memoryMb ?? "?"} MB)` : ""}` : "";
2513
2638
  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)}` : ""}`
2639
+ ` placement: ${p2.source}${box} order: ${p2.orderType ?? "\u2014"} rate: ${formatUsdPer(p2.rate)}${p2.maxPrice ? ` max price: ${formatUsdPer(p2.maxPrice)}` : ""}`
2515
2640
  );
2516
2641
  }
2642
+ const attach = "attach" in s ? s.attach : void 0;
2517
2643
  if (attach !== void 0) {
2518
2644
  console.log(
2519
2645
  attach === null ? " attach: none (market fill or ambient provider \u2014 platform drive only)" : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ""}`
@@ -2570,10 +2696,16 @@ var EXEC_LEAD_OPTS = [
2570
2696
  ];
2571
2697
  var SPAWN_LEAD_OPTS = [
2572
2698
  ...AUTH_LEAD_OPTS,
2699
+ { aliases: ["-q", "--quiet"], key: "quiet", flag: "bool" },
2573
2700
  { aliases: ["--cwd"], key: "cwd", flag: "value" },
2574
2701
  { aliases: ["-e", "--env"], key: "env", flag: "repeat" },
2575
2702
  { aliases: ["--stdin"], key: "stdin", flag: "bool" }
2576
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
+ ];
2577
2709
  function takeLeadingOptions(argv, specs) {
2578
2710
  var _a;
2579
2711
  const byAlias = /* @__PURE__ */ new Map();
@@ -2631,33 +2763,103 @@ function mergeLeadOpts(opts, inline) {
2631
2763
  }
2632
2764
  return merged;
2633
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;
2634
2847
  function registerSandboxesCommands(program2) {
2635
2848
  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) => {
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) => {
2637
2852
  try {
2853
+ checkQuietJson(opts);
2638
2854
  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.");
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
+ }
2656
2861
  }
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);
2862
+ emitResult(opts, res.sandbox, (s) => s.id, (s) => printSandbox(s, opts.verbose));
2661
2863
  } catch (e) {
2662
2864
  fail(e, opts);
2663
2865
  }
@@ -2691,54 +2893,165 @@ function registerSandboxesCommands(program2) {
2691
2893
  fail(e, opts);
2692
2894
  }
2693
2895
  });
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) => {
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) => {
2695
2897
  try {
2898
+ checkQuietJson(opts);
2696
2899
  const c = await client(opts);
2697
2900
  const res = await c.get(
2698
2901
  "/api/v1/sandboxes",
2699
2902
  { status: opts.status, limit: opts.limit, cursor: opts.cursor }
2700
2903
  );
2701
- output(opts, res, (page) => {
2702
- page.sandboxes.forEach(printSandbox);
2703
- if (page.nextCursor) console.log(pc4.dim(`nextCursor: ${page.nextCursor}`));
2704
- });
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
+ );
2705
2913
  } catch (e) {
2706
2914
  fail(e, opts);
2707
2915
  }
2708
2916
  });
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) => {
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) => {
2710
2918
  try {
2919
+ checkQuietJson(opts);
2920
+ const resolved = requireUuidOrImplicit(argId, opts);
2711
2921
  const c = await client(opts);
2712
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}`);
2713
- 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));
2714
2924
  } catch (e) {
2715
2925
  fail(e, opts);
2716
2926
  }
2717
2927
  });
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) => {
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) => {
2719
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
+ }
2720
2956
  const c = await client(opts);
2721
- 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
+ }
2722
2986
  output(opts, res.sandbox, printSandbox);
2723
2987
  } catch (e) {
2724
2988
  fail(e, opts);
2725
2989
  }
2726
2990
  });
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) => {
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) => {
2996
+ let opts = rawOpts;
2997
+ try {
2998
+ checkQuietJson(opts);
2999
+ if (opts.keep && opts.detach) throw new Error("--keep and --detach are mutually exclusive.");
3000
+ const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
3001
+ opts = mergeLeadOpts(rawOpts, lead.inline);
3002
+ const command = lead.command;
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) => {
2728
3033
  let opts = rawOpts;
2729
3034
  try {
3035
+ if (argId !== void 0 && !isUuid(argId)) {
3036
+ rawCommand.unshift(argId);
3037
+ argId = void 0;
3038
+ }
2730
3039
  const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
2731
3040
  opts = mergeLeadOpts(rawOpts, lead.inline);
2732
3041
  const command = lead.command;
2733
3042
  if (command.length === 0) throw new Error("missing command to run");
3043
+ const resolved = resolveSandbox(argId, opts);
2734
3044
  const c = await client(opts);
2735
3045
  const res = await c.post(
2736
- `/api/v1/sandboxes/${sandboxId}/commands`,
3046
+ `/api/v1/sandboxes/${resolved.id}/commands`,
2737
3047
  {
2738
3048
  command: command.map(shellQuote).join(" "),
2739
3049
  ...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
2740
3050
  }
2741
- );
3051
+ ).catch((e) => {
3052
+ resolved.clearStale(e);
3053
+ throw e;
3054
+ });
2742
3055
  output(opts, res, (r) => {
2743
3056
  process.stdout.write(r.stdout);
2744
3057
  if (r.stderr) process.stderr.write(r.stderr);
@@ -2749,48 +3062,59 @@ function registerSandboxesCommands(program2) {
2749
3062
  fail(e, opts);
2750
3063
  }
2751
3064
  });
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) => {
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) => {
2753
3066
  let opts = rawOpts;
2754
3067
  try {
3068
+ if (argId !== void 0 && !isUuid(argId)) {
3069
+ rawCommand.unshift(argId);
3070
+ argId = void 0;
3071
+ }
2755
3072
  const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);
2756
3073
  opts = mergeLeadOpts(rawOpts, lead.inline);
3074
+ checkQuietJson(opts);
2757
3075
  const command = lead.command;
2758
3076
  if (command.length === 0) throw new Error("missing command to spawn");
3077
+ const resolved = resolveSandbox(argId, opts);
2759
3078
  const c = await client(opts);
2760
3079
  const res = await c.post(
2761
- `/api/v1/sandboxes/${sandboxId}/processes`,
3080
+ `/api/v1/sandboxes/${resolved.id}/processes`,
2762
3081
  {
2763
3082
  command: command.map(shellQuote).join(" "),
2764
3083
  ...opts.cwd ? { cwd: opts.cwd } : {},
2765
3084
  ...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
2766
3085
  ...opts.stdin ? { stdin: true } : {}
2767
3086
  }
2768
- );
2769
- 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);
2770
3092
  } catch (e) {
2771
3093
  fail(e, opts);
2772
3094
  }
2773
3095
  });
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) => {
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) => {
2775
3097
  try {
3098
+ const resolved = requireUuidOrImplicit(argId, opts);
2776
3099
  const c = await client(opts);
2777
3100
  const res = await c.get(
2778
- `/api/v1/sandboxes/${sandboxId}/processes`
3101
+ `/api/v1/sandboxes/${resolved.id}/processes`
2779
3102
  );
2780
3103
  output(opts, res.processes, (list) => list.forEach(printProcess));
2781
3104
  } catch (e) {
2782
3105
  fail(e, opts);
2783
3106
  }
2784
3107
  });
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) => {
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) => {
2786
3109
  try {
3110
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2787
3111
  const c = await client(opts);
2788
3112
  if (opts.follow) {
2789
- await followProcess(c, sandboxId, jobId);
3113
+ await followProcess(c, resolved.id, job);
2790
3114
  return;
2791
3115
  }
2792
3116
  const res = await c.get(
2793
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`
3117
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}`
2794
3118
  );
2795
3119
  output(opts, res.process, (p2) => {
2796
3120
  if (p2.stdout) process.stdout.write(p2.stdout);
@@ -2801,11 +3125,12 @@ function registerSandboxesCommands(program2) {
2801
3125
  fail(e, opts);
2802
3126
  }
2803
3127
  });
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) => {
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) => {
2805
3129
  try {
3130
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2806
3131
  const c = await client(opts);
2807
3132
  const res = await c.post(
2808
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,
3133
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/wait`,
2809
3134
  opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
2810
3135
  );
2811
3136
  output(opts, res.process, printProcess);
@@ -2816,11 +3141,12 @@ function registerSandboxesCommands(program2) {
2816
3141
  fail(e, opts);
2817
3142
  }
2818
3143
  });
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) => {
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) => {
2820
3145
  try {
3146
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2821
3147
  const c = await client(opts);
2822
3148
  const res = await c.post(
2823
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,
3149
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/kill`,
2824
3150
  opts.signal ? { signal: opts.signal } : {}
2825
3151
  );
2826
3152
  output(opts, res.process, printProcess);
@@ -2828,18 +3154,19 @@ function registerSandboxesCommands(program2) {
2828
3154
  fail(e, opts);
2829
3155
  }
2830
3156
  });
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) => {
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) => {
2832
3158
  try {
3159
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2833
3160
  let data = opts.data;
2834
3161
  if (data === void 0 && opts.file) {
2835
3162
  const { readFile } = await import("fs/promises");
2836
3163
  data = opts.base64 ? (await readFile(opts.file)).toString("base64") : await readFile(opts.file, "utf8");
2837
3164
  }
2838
3165
  if (data === void 0 && !process.stdin.isTTY) {
2839
- const piped = await new Promise((resolve) => {
3166
+ const piped = await new Promise((resolve2) => {
2840
3167
  const chunks = [];
2841
3168
  process.stdin.on("data", (chunk) => chunks.push(chunk));
2842
- process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
3169
+ process.stdin.on("end", () => resolve2(Buffer.concat(chunks)));
2843
3170
  });
2844
3171
  data = opts.base64 ? piped.toString("base64") : piped.toString("utf8");
2845
3172
  }
@@ -2852,31 +3179,42 @@ function registerSandboxesCommands(program2) {
2852
3179
  }
2853
3180
  const c = await client(opts);
2854
3181
  const res = await c.post(
2855
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/stdin`,
3182
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/stdin`,
2856
3183
  { data, ...opts.base64 ? { encoding: "base64" } : {} }
2857
3184
  );
2858
- output(opts, res, () => console.log(`wrote ${data.length} chars to ${jobId}`));
3185
+ output(opts, res, () => console.log(`wrote ${data.length} chars to ${job}`));
2859
3186
  } catch (e) {
2860
3187
  fail(e, opts);
2861
3188
  }
2862
3189
  });
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) => {
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) => {
2864
3191
  try {
3192
+ const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, "jobId");
2865
3193
  const c = await client(opts);
2866
3194
  const res = await c.post(
2867
- `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/close-stdin`,
3195
+ `/api/v1/sandboxes/${resolved.id}/processes/${job}/close-stdin`,
2868
3196
  {}
2869
3197
  );
2870
- output(opts, res, () => console.log(`closed stdin on ${jobId}`));
3198
+ output(opts, res, () => console.log(`closed stdin on ${job}`));
2871
3199
  } catch (e) {
2872
3200
  fail(e, opts);
2873
3201
  }
2874
3202
  });
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) => {
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) => {
2876
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
+ }
2877
3215
  const c = await client(opts);
2878
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/files`, {
2879
- path: path ?? "/"
3216
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, {
3217
+ path: p2
2880
3218
  });
2881
3219
  output(opts, res, (view) => {
2882
3220
  if (view.type === "directory") {
@@ -2891,10 +3229,21 @@ function registerSandboxesCommands(program2) {
2891
3229
  fail(e, opts);
2892
3230
  }
2893
3231
  });
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) => {
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) => {
2895
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
+ }
2896
3245
  const c = await client(opts);
2897
- 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 });
2898
3247
  output(opts, res, (view) => {
2899
3248
  if (view.type !== "file") {
2900
3249
  console.error(pc4.red(`${view.path} is a directory`));
@@ -2907,19 +3256,30 @@ function registerSandboxesCommands(program2) {
2907
3256
  fail(e, opts);
2908
3257
  }
2909
3258
  });
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) => {
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) => {
2911
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
+ }
2912
3272
  let content = opts.content;
2913
3273
  if (content === void 0 && opts.file) {
2914
3274
  const { readFile } = await import("fs/promises");
2915
3275
  content = await readFile(opts.file, "utf8");
2916
3276
  }
2917
3277
  if (content === void 0 && !process.stdin.isTTY) {
2918
- content = await new Promise((resolve) => {
3278
+ content = await new Promise((resolve2) => {
2919
3279
  let data = "";
2920
3280
  process.stdin.setEncoding("utf8");
2921
3281
  process.stdin.on("data", (chunk) => data += chunk);
2922
- process.stdin.on("end", () => resolve(data));
3282
+ process.stdin.on("end", () => resolve2(data));
2923
3283
  });
2924
3284
  }
2925
3285
  if (content === void 0) {
@@ -2928,19 +3288,30 @@ function registerSandboxesCommands(program2) {
2928
3288
  }
2929
3289
  const c = await client(opts);
2930
3290
  const res = await c.post(
2931
- `/api/v1/sandboxes/${sandboxId}/files`,
2932
- { path, content }
3291
+ `/api/v1/sandboxes/${resolved.id}/files`,
3292
+ { path: p2, content }
2933
3293
  );
2934
3294
  output(opts, res, (r) => console.log(`wrote ${r.path}`));
2935
3295
  } catch (e) {
2936
3296
  fail(e, opts);
2937
3297
  }
2938
3298
  });
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) => {
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) => {
2940
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
+ }
2941
3312
  const c = await client(opts);
2942
- const res = await c.post(`/api/v1/sandboxes/${sandboxId}/files`, {
2943
- path,
3313
+ const res = await c.post(`/api/v1/sandboxes/${resolved.id}/files`, {
3314
+ path: p2,
2944
3315
  mkdir: true
2945
3316
  });
2946
3317
  output(opts, res, (r) => console.log(`created ${r.path}`));
@@ -2948,45 +3319,68 @@ function registerSandboxesCommands(program2) {
2948
3319
  fail(e, opts);
2949
3320
  }
2950
3321
  });
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) => {
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) => {
2952
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
+ }
2953
3335
  const c = await client(opts);
2954
3336
  const res = await c.del(
2955
- `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`
3337
+ `/api/v1/sandboxes/${resolved.id}/files?path=${encodeURIComponent(p2)}`
2956
3338
  );
2957
3339
  output(opts, res, (r) => console.log(`removed ${r.path}`));
2958
3340
  } catch (e) {
2959
3341
  fail(e, opts);
2960
3342
  }
2961
3343
  });
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) => {
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) => {
2963
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);
2964
3356
  const c = await client(opts);
2965
- const res = await c.get(`/api/v1/sandboxes/${sandboxId}/urls`, {
3357
+ const res = await c.get(`/api/v1/sandboxes/${resolved.id}/urls`, {
2966
3358
  port: opts.port,
2967
3359
  protocol: opts.protocol
2968
3360
  });
2969
- output(opts, res, (r) => console.log(safeTerm(r.url)));
3361
+ emitResult(opts, res, (r) => safeTerm(r.url), (r) => console.log(safeTerm(r.url)));
2970
3362
  } catch (e) {
2971
3363
  fail(e, opts);
2972
3364
  }
2973
3365
  });
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) => {
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) => {
2975
3367
  try {
3368
+ const resolved = requireUuidOrImplicit(argId, opts);
2976
3369
  const c = await client(opts);
2977
3370
  const res = await c.get(
2978
- `/api/v1/sandboxes/${sandboxId}/snapshots`
3371
+ `/api/v1/sandboxes/${resolved.id}/snapshots`
2979
3372
  );
2980
3373
  output(opts, res.snapshots, (list) => list.forEach(printSnapshot));
2981
3374
  } catch (e) {
2982
3375
  fail(e, opts);
2983
3376
  }
2984
3377
  });
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) => {
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) => {
2986
3379
  try {
3380
+ const resolved = requireUuidOrImplicit(argId, opts);
2987
3381
  const c = await client(opts);
2988
3382
  const res = await c.post(
2989
- `/api/v1/sandboxes/${sandboxId}/snapshots`,
3383
+ `/api/v1/sandboxes/${resolved.id}/snapshots`,
2990
3384
  opts.label ? { label: opts.label } : {}
2991
3385
  );
2992
3386
  output(opts, res.snapshot, printSnapshot);
@@ -2994,13 +3388,14 @@ function registerSandboxesCommands(program2) {
2994
3388
  fail(e, opts);
2995
3389
  }
2996
3390
  });
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) => {
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) => {
2998
3392
  try {
3393
+ const { resolved, resource: snap } = resolveTwoArgTarget(argId, snapshotId, opts, "snapshotId");
2999
3394
  const c = await client(opts);
3000
3395
  const res = await c.del(
3001
- `/api/v1/sandboxes/${sandboxId}/snapshots/${snapshotId}`
3396
+ `/api/v1/sandboxes/${resolved.id}/snapshots/${snap}`
3002
3397
  );
3003
- output(opts, res, () => console.log(`deleted snapshot ${snapshotId}`));
3398
+ output(opts, res, () => console.log(`deleted snapshot ${snap}`));
3004
3399
  } catch (e) {
3005
3400
  fail(e, opts);
3006
3401
  }
@@ -3038,12 +3433,353 @@ async function followProcess(c, sandboxId, jobId) {
3038
3433
  if (exitCode !== 0) process.exitCode = exitCode;
3039
3434
  }
3040
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
+ }
3041
3777
 
3042
3778
  // src/index.ts
3043
3779
  var __filename2 = fileURLToPath(import.meta.url);
3044
- var __dirname2 = dirname(__filename2);
3780
+ var __dirname2 = dirname2(__filename2);
3045
3781
  var packageJson = JSON.parse(
3046
- readFileSync2(join2(__dirname2, "..", "package.json"), "utf-8")
3782
+ readFileSync3(join4(__dirname2, "..", "package.json"), "utf-8")
3047
3783
  );
3048
3784
  var isDevBuild = import.meta.url.includes("worktrees") || import.meta.url.includes("/packages/cli/");
3049
3785
  var VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;