@computesdk/cli 2.5.8 → 2.6.1

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
@@ -73,344 +73,39 @@ import { spawnSync } from "child_process";
73
73
  import pc from "picocolors";
74
74
 
75
75
  // src/actions-client.ts
76
- var DEFAULT_BASE_URL = "https://platform.computesdk.com";
77
- var ActionsApiError = class extends Error {
78
- constructor(status, message, body) {
79
- super(message);
80
- this.status = status;
81
- this.body = body;
82
- this.name = "ActionsApiError";
83
- }
84
- };
85
- var ActionsCliError = class extends Error {
86
- constructor(code, message) {
87
- super(message);
88
- this.code = code;
89
- this.name = "ActionsCliError";
90
- }
91
- };
92
- function codeForStatus(status) {
93
- switch (status) {
94
- case 400:
95
- return "bad_request";
96
- case 401:
97
- return "unauthenticated";
98
- case 403:
99
- return "forbidden";
100
- case 404:
101
- return "not_found";
102
- case 409:
103
- return "conflict";
104
- case 413:
105
- return "payload_too_large";
106
- case 429:
107
- return "rate_limited";
108
- default:
109
- return status >= 500 ? "server_error" : "http_error";
110
- }
76
+ import {
77
+ DEFAULT_BASE_URL,
78
+ PlatformApiError,
79
+ PlatformClient,
80
+ PlatformClientError,
81
+ codeForStatus,
82
+ errorDetails,
83
+ isSecurePlatformTransport,
84
+ isTrustedPlatformHost,
85
+ readSseEvents,
86
+ readSseNamedEvents,
87
+ resolvePlatformAuth,
88
+ toErrorEnvelope
89
+ } from "@computesdk/platform";
90
+ var CLI_CREDENTIALS_HINT = "Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.";
91
+ function resolveActionsAuth(opts, resolveStored) {
92
+ return resolvePlatformAuth(opts, resolveStored, CLI_CREDENTIALS_HINT);
111
93
  }
112
- function errorDetails(body) {
113
- if (body && typeof body === "object" && "details" in body) {
114
- const details = body.details;
115
- if (details && typeof details === "object" && !Array.isArray(details)) {
116
- return details;
117
- }
118
- }
119
- return void 0;
120
- }
121
- function toErrorEnvelope(error) {
122
- if (error instanceof ActionsApiError) {
123
- const details = errorDetails(error.body);
124
- const insufficientScope = error.message.includes("insufficient_scope") || typeof error.body === "string" && error.body.includes("insufficient_scope") || typeof error.body === "object" && error.body !== null && JSON.stringify(error.body).includes("insufficient_scope");
125
- return {
126
- ok: false,
127
- error: {
128
- code: codeForStatus(error.status),
129
- message: insufficientScope ? `${error.message} \u2014 run \`compute login\` to sign in again.` : error.message,
130
- httpStatus: error.status,
131
- retryable: error.status === 429 || error.status === 502 || error.status === 503 || error.status === 504,
132
- ...details !== void 0 && { details }
133
- }
134
- };
135
- }
136
- if (error instanceof ActionsCliError) {
137
- return { ok: false, error: { code: error.code, message: error.message, retryable: false } };
138
- }
139
- if (error instanceof TypeError && /fetch failed/i.test(error.message)) {
140
- const cause = error.cause;
141
- const detail = cause instanceof Error ? `: ${cause.message}` : "";
142
- return {
143
- ok: false,
144
- error: { code: "network", message: `${error.message}${detail}`, retryable: true }
145
- };
146
- }
147
- return {
148
- ok: false,
149
- error: {
150
- code: "unknown",
151
- message: error instanceof Error ? error.message : String(error),
152
- retryable: false
153
- }
154
- };
94
+ function encodeWatchCursor(id, jobId, step, offset) {
95
+ const stepPart = step === null ? "-" : step === "runner" ? "runner" : String(step);
96
+ return `${id}:${jobId}:${stepPart}:${offset}`;
155
97
  }
156
- var ActionsClient = class {
157
- constructor(auth, fetchImpl = fetch) {
158
- this.auth = auth;
159
- this.fetchImpl = fetchImpl;
98
+ var ActionsClient = class extends PlatformClient {
99
+ constructor() {
100
+ super(...arguments);
160
101
  this.orgPromise = null;
161
102
  }
162
- get baseUrl() {
163
- return this.auth.baseUrl;
164
- }
165
103
  /** The credential's org — fetched once, needed for dashboard URLs. */
166
104
  org() {
167
105
  this.orgPromise ?? (this.orgPromise = this.get("/api/v1/actions/org"));
168
106
  return this.orgPromise;
169
107
  }
170
- async get(path2, params) {
171
- const url = new URL(`${this.auth.baseUrl}${path2}`);
172
- for (const [key, value] of Object.entries(params ?? {})) {
173
- if (value === void 0) continue;
174
- for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);
175
- }
176
- const res = await this.fetchImpl(url, { headers: this.headers() });
177
- return this.parse(res);
178
- }
179
- async post(path2, body = {}) {
180
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
181
- method: "POST",
182
- headers: { ...this.headers(), "content-type": "application/json" },
183
- body: JSON.stringify(body)
184
- });
185
- return this.parse(res);
186
- }
187
- /** POST a raw text body (e.g. a unified diff to `/api/v1/actions/patches`). */
188
- async postText(path2, body, contentType) {
189
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
190
- method: "POST",
191
- headers: { ...this.headers(), "content-type": contentType },
192
- body
193
- });
194
- return this.parse(res);
195
- }
196
- async put(path2, body = {}) {
197
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
198
- method: "PUT",
199
- headers: { ...this.headers(), "content-type": "application/json" },
200
- body: JSON.stringify(body)
201
- });
202
- return this.parse(res);
203
- }
204
- async patch(path2, body = {}) {
205
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
206
- method: "PATCH",
207
- headers: { ...this.headers(), "content-type": "application/json" },
208
- body: JSON.stringify(body)
209
- });
210
- return this.parse(res);
211
- }
212
- async del(path2) {
213
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
214
- method: "DELETE",
215
- headers: this.headers()
216
- });
217
- return this.parse(res);
218
- }
219
- /**
220
- * One `data:` JSON payload per SSE event. `next()` resolves to the payload,
221
- * or null when the stream ends. Call `close()` to abort.
222
- */
223
- async *sse(path2, params) {
224
- const url = new URL(`${this.auth.baseUrl}${path2}`);
225
- for (const [key, value] of Object.entries(params ?? {})) {
226
- if (value === void 0) continue;
227
- for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);
228
- }
229
- const res = await this.fetchImpl(url, {
230
- headers: { ...this.headers(), accept: "text/event-stream" }
231
- });
232
- if (!res.ok) {
233
- await this.parse(res);
234
- }
235
- if (!res.body) throw new Error("SSE response has no body");
236
- yield* readSseEvents(res.body);
237
- }
238
- /**
239
- * `sse()` with the frame's `event:` name preserved — for streams whose
240
- * events are distinguished by name rather than payload shape (process
241
- * follow: stdout/stderr share a `{chunk}` payload).
242
- */
243
- async *sseNamed(path2, params) {
244
- const url = new URL(`${this.auth.baseUrl}${path2}`);
245
- for (const [key, value] of Object.entries(params ?? {})) {
246
- if (value === void 0) continue;
247
- for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);
248
- }
249
- const res = await this.fetchImpl(url, {
250
- headers: { ...this.headers(), accept: "text/event-stream" }
251
- });
252
- if (!res.ok) {
253
- await this.parse(res);
254
- }
255
- if (!res.body) throw new Error("SSE response has no body");
256
- yield* readSseNamedEvents(res.body);
257
- }
258
- /** Download bytes following redirects (artifact URLs 302 to storage). */
259
- async download(path2) {
260
- const res = await this.fetchImpl(`${this.auth.baseUrl}${path2}`, {
261
- headers: this.headers(),
262
- redirect: "follow"
263
- });
264
- if (!res.ok) {
265
- const body = await res.json().catch(() => void 0);
266
- throw new ActionsApiError(res.status, errorMessage(body, res.status), body);
267
- }
268
- return new Uint8Array(await res.arrayBuffer());
269
- }
270
- headers() {
271
- const headers = {
272
- authorization: `Bearer ${this.auth.apiKey}`,
273
- accept: "application/json"
274
- };
275
- if (this.auth.orgSlug) headers["X-Org-Slug"] = this.auth.orgSlug;
276
- return headers;
277
- }
278
- async parse(res) {
279
- const body = await res.json().catch(() => void 0);
280
- if (!res.ok) throw new ActionsApiError(res.status, errorMessage(body, res.status), body);
281
- return body;
282
- }
283
108
  };
284
- function errorMessage(body, status) {
285
- if (body && typeof body === "object" && "error" in body && typeof body.error === "string") {
286
- return body.error;
287
- }
288
- return `Request failed with status ${status}`;
289
- }
290
- async function* readSseEvents(body) {
291
- const reader = body.getReader();
292
- const decoder = new TextDecoder();
293
- let buffer = "";
294
- try {
295
- for (; ; ) {
296
- const { done, value } = await reader.read();
297
- if (done) break;
298
- buffer += decoder.decode(value, { stream: true });
299
- let idx;
300
- while ((idx = buffer.indexOf("\n\n")) !== -1) {
301
- const event = buffer.slice(0, idx);
302
- buffer = buffer.slice(idx + 2);
303
- for (const line of event.split("\n")) {
304
- if (line.startsWith("data: ")) {
305
- yield JSON.parse(line.slice(6));
306
- }
307
- }
308
- }
309
- }
310
- } finally {
311
- reader.releaseLock();
312
- }
313
- }
314
- async function* readSseNamedEvents(body) {
315
- const reader = body.getReader();
316
- const decoder = new TextDecoder();
317
- let buffer = "";
318
- try {
319
- for (; ; ) {
320
- const { done, value } = await reader.read();
321
- if (done) break;
322
- buffer += decoder.decode(value, { stream: true });
323
- let idx;
324
- while ((idx = buffer.indexOf("\n\n")) !== -1) {
325
- const frame = buffer.slice(0, idx);
326
- buffer = buffer.slice(idx + 2);
327
- let event = "message";
328
- const dataLines = [];
329
- for (const line of frame.split("\n")) {
330
- if (line.startsWith("event: ")) event = line.slice(7);
331
- else if (line.startsWith("data: ")) dataLines.push(line.slice(6));
332
- }
333
- if (dataLines.length > 0) {
334
- yield { event, data: JSON.parse(dataLines.join("\n")) };
335
- }
336
- }
337
- }
338
- } finally {
339
- reader.releaseLock();
340
- }
341
- }
342
- function encodeWatchCursor(id, jobId, step, offset) {
343
- const stepPart = step === null ? "-" : step === "runner" ? "runner" : String(step);
344
- return `${id}:${jobId}:${stepPart}:${offset}`;
345
- }
346
- var NO_CREDENTIALS_HINT = "Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.";
347
- async function resolveActionsAuth(opts, resolveStored = resolveStoredPlatformAuth) {
348
- const baseUrl = (opts.baseUrl || process.env.COMPUTE_PLATFORM_URL || process.env.BENCHMARKS_PLATFORM_URL || // legacy name
349
- DEFAULT_BASE_URL).replace(/\/+$/, "");
350
- let orgSlug = opts.org || process.env.COMPUTE_ORG || void 0;
351
- if (!opts.allowUntrustedHost && !isTrustedActionsHost(baseUrl)) {
352
- throw new ActionsCliError(
353
- "untrusted_host",
354
- `Refusing to send the API key to ${baseUrl} \u2014 it is not a computesdk.com or localhost host. If this is a self-hosted/dev deployment you trust, pass --allow-untrusted-host.`
355
- );
356
- }
357
- if (!isSecureActionsTransport(baseUrl)) {
358
- throw new ActionsCliError(
359
- "insecure_transport",
360
- `Refusing to send the API key over plaintext HTTP to ${baseUrl}. Use an https:// base URL; http:// is only allowed for localhost/loopback.`
361
- );
362
- }
363
- let apiKey = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY || // legacy name
364
- void 0;
365
- if (!apiKey) {
366
- if (!isTrustedActionsHost(baseUrl)) {
367
- throw new ActionsCliError(
368
- "untrusted_host_stored_auth",
369
- `Refusing to use stored platform credentials with untrusted host ${baseUrl}. Pass --api-key or set COMPUTE_API_KEY to use an explicit key with --allow-untrusted-host.`
370
- );
371
- }
372
- let stored;
373
- try {
374
- stored = await resolveStored({ baseUrl });
375
- } catch (error) {
376
- const reason = error instanceof Error ? error.message : String(error);
377
- const detail = reason.startsWith("No credentials found") ? "No API key." : reason;
378
- throw new ActionsCliError("no_credentials", `${detail} ${NO_CREDENTIALS_HINT}`);
379
- }
380
- apiKey = stored.apiKey || stored.token || void 0;
381
- }
382
- if (!apiKey) {
383
- throw new ActionsCliError("no_credentials", `No API key. ${NO_CREDENTIALS_HINT}`);
384
- }
385
- return { apiKey, baseUrl, ...orgSlug && { orgSlug } };
386
- }
387
- async function resolveStoredPlatformAuth(opts) {
388
- const { resolveAuth } = await import("@benchsdk/cli");
389
- const auth = await resolveAuth({ baseUrl: opts.baseUrl });
390
- return { apiKey: auth.apiKey, token: auth.token, orgSlug: auth.orgSlug, orgId: auth.orgId };
391
- }
392
- function isLoopbackHost(host) {
393
- return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
394
- }
395
- function isSecureActionsTransport(baseUrl) {
396
- let url;
397
- try {
398
- url = new URL(baseUrl);
399
- } catch {
400
- return false;
401
- }
402
- if (url.protocol === "https:") return true;
403
- return url.protocol === "http:" && isLoopbackHost(url.hostname);
404
- }
405
- function isTrustedActionsHost(baseUrl) {
406
- let host;
407
- try {
408
- host = new URL(baseUrl).hostname;
409
- } catch {
410
- return false;
411
- }
412
- return host === "computesdk.com" || host.endsWith(".computesdk.com") || isLoopbackHost(host);
413
- }
414
109
 
415
110
  // src/rate-display.ts
416
111
  var SECONDS_PER_MINUTE = 60;
@@ -536,9 +231,9 @@ function printLaneSettings(s, lane) {
536
231
  }
537
232
  }
538
233
  function settingsFail(e, opts, lane, verb, deps) {
539
- if (e instanceof ActionsApiError && e.status === 403) {
234
+ if (e instanceof PlatformApiError && e.status === 403) {
540
235
  return deps.fail(
541
- new ActionsApiError(
236
+ new PlatformApiError(
542
237
  403,
543
238
  `Only org owners/admins can ${verb} ${lane} settings`,
544
239
  e.body
@@ -639,8 +334,8 @@ async function client(opts) {
639
334
  return new ActionsClient(await resolveActionsAuth(opts));
640
335
  }
641
336
  function assertSecretValueHost(auth, what) {
642
- if (!isTrustedActionsHost(auth.baseUrl)) {
643
- throw new ActionsCliError(
337
+ if (!isTrustedPlatformHost(auth.baseUrl)) {
338
+ throw new PlatformClientError(
644
339
  "untrusted_host",
645
340
  `Refusing to send or read ${what} at ${auth.baseUrl} \u2014 only computesdk.com and localhost hosts are allowed, even with --allow-untrusted-host.`
646
341
  );
@@ -666,7 +361,7 @@ async function listRunJobs(c, runId) {
666
361
  const run = await c.get(`/api/v1/actions/runs/${runId}`);
667
362
  return run.jobs;
668
363
  } catch (e) {
669
- if (!(e instanceof ActionsApiError) || e.status !== 404) throw e;
364
+ if (!(e instanceof PlatformApiError) || e.status !== 404) throw e;
670
365
  }
671
366
  const state = await c.get(`/api/v1/actions/runs/${runId}/state`);
672
367
  return state.jobs.map((j) => ({
@@ -689,7 +384,7 @@ async function fetchRunSummary(c, runId) {
689
384
  try {
690
385
  return await c.get(`/api/v1/actions/runs/${runId}/summary`);
691
386
  } catch (e) {
692
- if (!(e instanceof ActionsApiError && e.status === 404)) {
387
+ if (!(e instanceof PlatformApiError && e.status === 404)) {
693
388
  console.error(
694
389
  pc2.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`)
695
390
  );
@@ -700,7 +395,7 @@ async function fetchRunSummary(c, runId) {
700
395
  function fail(error, opts = {}) {
701
396
  if (opts.json) {
702
397
  process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + "\n");
703
- } else if (error instanceof ActionsApiError) {
398
+ } else if (error instanceof PlatformApiError) {
704
399
  console.error(pc2.red(`Error (${error.status}): ${error.message}`));
705
400
  } else {
706
401
  console.error(pc2.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
@@ -710,7 +405,7 @@ function fail(error, opts = {}) {
710
405
  function usageErrorOutput(str, write, argv = process.argv) {
711
406
  if (argv.includes("--json")) {
712
407
  const message = str.replace(/^error:\s*/i, "").trim();
713
- write(JSON.stringify(toErrorEnvelope(new ActionsCliError("invalid_argument", message))) + "\n");
408
+ write(JSON.stringify(toErrorEnvelope(new PlatformClientError("invalid_argument", message))) + "\n");
714
409
  } else {
715
410
  write(str);
716
411
  }
@@ -932,7 +627,7 @@ function parseInputs(pairs) {
932
627
  for (const pair of pairs ?? []) {
933
628
  const eq = pair.indexOf("=");
934
629
  if (eq === -1) {
935
- throw new ActionsCliError("invalid_argument", `Invalid --inputs entry "${pair}". Expected key=value.`);
630
+ throw new PlatformClientError("invalid_argument", `Invalid --inputs entry "${pair}". Expected key=value.`);
936
631
  }
937
632
  inputs[pair.slice(0, eq)] = pair.slice(eq + 1);
938
633
  }
@@ -982,7 +677,7 @@ function parseStep(step) {
982
677
  if (step === "runner") return "runner";
983
678
  const n = Number(step);
984
679
  if (!Number.isInteger(n) || n < 0) {
985
- throw new ActionsCliError("invalid_argument", `Invalid --step "${step}". Expected a step ordinal or "runner".`);
680
+ throw new PlatformClientError("invalid_argument", `Invalid --step "${step}". Expected a step ordinal or "runner".`);
986
681
  }
987
682
  return n;
988
683
  }
@@ -1094,21 +789,21 @@ function patchTouches(patch, path2) {
1094
789
  function dispatchBody(workflow, opts) {
1095
790
  const patched = isPatchedWorkflowTarget(workflow);
1096
791
  if (!patched && !workflow.dispatchable && !opts.manual) {
1097
- throw new ActionsCliError(
792
+ throw new PlatformClientError(
1098
793
  "invalid_argument",
1099
794
  `Workflow "${workflow.path}" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`
1100
795
  );
1101
796
  }
1102
797
  if (!patched && !workflow.dispatchable && opts.inputs !== void 0 && opts.inputs.length > 0) {
1103
- throw new ActionsCliError(
798
+ throw new PlatformClientError(
1104
799
  "invalid_argument",
1105
800
  `Workflow "${workflow.path}" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`
1106
801
  );
1107
802
  }
1108
803
  const ref = opts.ref ?? (patched ? void 0 : workflow.refs[0]);
1109
- if (!ref) throw new ActionsCliError("invalid_argument", "No --ref given and the workflow has no watched refs.");
804
+ if (!ref) throw new PlatformClientError("invalid_argument", "No --ref given and the workflow has no watched refs.");
1110
805
  if (opts.providerRegion !== void 0 && opts.provider === void 0) {
1111
- throw new ActionsCliError("invalid_argument", "--provider-region requires --provider.");
806
+ throw new PlatformClientError("invalid_argument", "--provider-region requires --provider.");
1112
807
  }
1113
808
  const maxPrice = maxPriceFields(opts.maxBid, opts.maxBidPer);
1114
809
  return {
@@ -1148,7 +843,7 @@ function localChangesPatch(ref, git = runGit, repo) {
1148
843
  if (repo !== void 0) {
1149
844
  const remote = git(["remote", "get-url", "origin"]).stdout.trim();
1150
845
  if (!remoteNamesRepo(remote, repo)) {
1151
- throw new ActionsCliError(
846
+ throw new PlatformClientError(
1152
847
  "invalid_argument",
1153
848
  `--with-changes sends this checkout's changes, but its origin (${remote || "none"}) is not ${repo}. Run it from a checkout of ${repo}.`
1154
849
  );
@@ -1156,17 +851,17 @@ function localChangesPatch(ref, git = runGit, repo) {
1156
851
  }
1157
852
  const fetched = git(["fetch", "--quiet", "origin", branch]);
1158
853
  if (fetched.status !== 0) {
1159
- throw new ActionsCliError("invalid_argument", `git fetch origin ${branch} failed: ${fetched.stderr.trim() || "is the branch pushed?"}`);
854
+ throw new PlatformClientError("invalid_argument", `git fetch origin ${branch} failed: ${fetched.stderr.trim() || "is the branch pushed?"}`);
1160
855
  }
1161
856
  if (git(["rev-parse", "--verify", "--quiet", `${base}^{commit}`]).status !== 0) {
1162
- throw new ActionsCliError(
857
+ throw new PlatformClientError(
1163
858
  "invalid_argument",
1164
859
  `--with-changes diffs against ${base}, which does not exist locally. Push the branch (or run \`git fetch origin ${branch}\`), or pass --ref <branch that exists on origin>.`
1165
860
  );
1166
861
  }
1167
862
  const tracked = git(["diff", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--"]);
1168
863
  if (tracked.status !== 0) {
1169
- throw new ActionsCliError("invalid_argument", `git diff against ${base} failed: ${tracked.stderr.trim()}`);
864
+ throw new PlatformClientError("invalid_argument", `git diff against ${base} failed: ${tracked.stderr.trim()}`);
1170
865
  }
1171
866
  const parts = [tracked.stdout];
1172
867
  const topLevel = git(["rev-parse", "--show-toplevel"]).stdout.replace(/\r?\n$/, "");
@@ -1178,29 +873,29 @@ function localChangesPatch(ref, git = runGit, repo) {
1178
873
  const patch = parts.filter((p2) => p2 !== "").join("");
1179
874
  if (patch.trim() === "") return null;
1180
875
  if (patch.includes("\0") || /^Binary files .* differ$/m.test(patch)) {
1181
- throw new ActionsCliError("invalid_argument", "Local changes include a binary file; --with-changes sends text diffs only.");
876
+ throw new PlatformClientError("invalid_argument", "Local changes include a binary file; --with-changes sends text diffs only.");
1182
877
  }
1183
878
  const files = patch.match(/^\+\+\+ /gm)?.length ?? 0;
1184
879
  return { patch, files, base };
1185
880
  }
1186
881
  function maxPriceFields(maxBid, maxBidPer) {
1187
882
  if (maxBidPer !== void 0 && maxBid === void 0) {
1188
- throw new ActionsCliError("invalid_argument", "--max-bid-per requires --max-bid.");
883
+ throw new PlatformClientError("invalid_argument", "--max-bid-per requires --max-bid.");
1189
884
  }
1190
885
  if (maxBid === void 0) return void 0;
1191
886
  const usd = Number(maxBid);
1192
887
  if (!/^\d+(\.\d+)?([eE][+-]?\d+)?$/.test(maxBid) || !Number.isFinite(usd) || usd <= 0) {
1193
- throw new ActionsCliError("invalid_argument", `Invalid --max-bid "${maxBid}". Expected a positive dollar amount (e.g. 0.12).`);
888
+ throw new PlatformClientError("invalid_argument", `Invalid --max-bid "${maxBid}". Expected a positive dollar amount (e.g. 0.12).`);
1194
889
  }
1195
890
  const per = maxBidPer ?? "second";
1196
891
  if (per !== "second" && per !== "minute" && per !== "hour") {
1197
- throw new ActionsCliError("invalid_argument", `--max-bid-per must be second, minute, or hour, got "${maxBidPer}".`);
892
+ throw new PlatformClientError("invalid_argument", `--max-bid-per must be second, minute, or hour, got "${maxBidPer}".`);
1198
893
  }
1199
894
  return { maxPriceUsd: usd, maxPricePer: per };
1200
895
  }
1201
896
  function parseVaultKind(kind) {
1202
897
  if (kind === void 0 || kind === "secret" || kind === "variable") return kind ?? "secret";
1203
- throw new ActionsCliError("invalid_argument", `--kind must be secret or variable, got "${kind}".`);
898
+ throw new PlatformClientError("invalid_argument", `--kind must be secret or variable, got "${kind}".`);
1204
899
  }
1205
900
  function vaultPath(path2, params) {
1206
901
  const search = new URLSearchParams();
@@ -1211,9 +906,9 @@ function vaultPath(path2, params) {
1211
906
  return query ? `${path2}?${query}` : path2;
1212
907
  }
1213
908
  function vaultSetBody(name, value, opts) {
1214
- if (value === "") throw new ActionsCliError("invalid_argument", "The value is empty.");
909
+ if (value === "") throw new PlatformClientError("invalid_argument", "The value is empty.");
1215
910
  if (opts.revealable && opts.kind === "variable") {
1216
- throw new ActionsCliError("invalid_argument", "--revealable applies to secrets; variables are always readable.");
911
+ throw new PlatformClientError("invalid_argument", "--revealable applies to secrets; variables are always readable.");
1217
912
  }
1218
913
  return {
1219
914
  name,
@@ -1226,12 +921,12 @@ function vaultSetBody(name, value, opts) {
1226
921
  }
1227
922
  function vaultDeliveryLabels(opts) {
1228
923
  if (opts.proxy && opts.inject) {
1229
- throw new ActionsCliError("invalid_argument", "--proxy and --inject are mutually exclusive.");
924
+ throw new PlatformClientError("invalid_argument", "--proxy and --inject are mutually exclusive.");
1230
925
  }
1231
926
  const hosts = (opts.hosts ?? []).flatMap((host) => host.split(/[\s,]+/)).map((host) => host.trim().toLowerCase()).filter((host) => host !== "");
1232
927
  if (opts.inject) {
1233
928
  if (hosts.length > 0) {
1234
- throw new ActionsCliError(
929
+ throw new PlatformClientError(
1235
930
  "invalid_argument",
1236
931
  "--inject takes no --hosts \u2014 host rules only apply to --proxy."
1237
932
  );
@@ -1239,10 +934,10 @@ function vaultDeliveryLabels(opts) {
1239
934
  return ["materialize"];
1240
935
  }
1241
936
  if (!opts.proxy) {
1242
- throw new ActionsCliError("invalid_argument", "Pick a delivery: --proxy (with --hosts) or --inject.");
937
+ throw new PlatformClientError("invalid_argument", "Pick a delivery: --proxy (with --hosts) or --inject.");
1243
938
  }
1244
939
  if (hosts.length === 0) {
1245
- throw new ActionsCliError(
940
+ throw new PlatformClientError(
1246
941
  "invalid_argument",
1247
942
  "--proxy needs --hosts \u2014 the hosts the real value may be attached to."
1248
943
  );
@@ -1252,7 +947,7 @@ function vaultDeliveryLabels(opts) {
1252
947
  function vaultSetLabels(opts) {
1253
948
  const flagged = opts.proxy === true || opts.inject === true || (opts.hosts?.length ?? 0) > 0;
1254
949
  if (flagged && (opts.labels?.length ?? 0) > 0) {
1255
- throw new ActionsCliError("invalid_argument", "Use --labels or --proxy/--inject --hosts, not both.");
950
+ throw new PlatformClientError("invalid_argument", "Use --labels or --proxy/--inject --hosts, not both.");
1256
951
  }
1257
952
  if (!flagged) return opts.labels;
1258
953
  return vaultDeliveryLabels(opts);
@@ -1280,7 +975,7 @@ function registerActionsCommands(program2) {
1280
975
  let local = null;
1281
976
  if (opts.withChanges) {
1282
977
  ref ?? (ref = currentBranch() ?? void 0);
1283
- if (!ref) throw new ActionsCliError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
978
+ if (!ref) throw new PlatformClientError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
1284
979
  local = localChangesPatch(ref, void 0, repo);
1285
980
  } else if (!opts.json && hasLocalChanges()) {
1286
981
  console.error(pc2.dim("You have uncommitted changes. Add --with-changes to run them."));
@@ -1293,7 +988,7 @@ function registerActionsCommands(program2) {
1293
988
  if (!workflow) {
1294
989
  const choices = workflows.map((w) => `${w.path} (${w.name})`).join(", ") || "none";
1295
990
  const hint = !opts.withChanges && hasLocalChanges() && /^\.github\/workflows\//.test(opts.workflow) ? " If it only exists in your working tree, add --with-changes." : "";
1296
- throw new ActionsCliError(
991
+ throw new PlatformClientError(
1297
992
  "workflow_not_found",
1298
993
  `No workflow "${opts.workflow}" in ${repo}. Available: ${choices}${hint}`
1299
994
  );
@@ -1666,7 +1361,7 @@ function registerActionsCommands(program2) {
1666
1361
  ).action(async (name, opts) => {
1667
1362
  try {
1668
1363
  if (opts.fromFile === void 0 && process.stdin.isTTY) {
1669
- throw new ActionsCliError(
1364
+ throw new PlatformClientError(
1670
1365
  "invalid_argument",
1671
1366
  'Pipe the value on stdin (e.g. printf %s "$VALUE" | compute actions vault set NAME) or pass --from-file.'
1672
1367
  );
@@ -1839,7 +1534,7 @@ var MARKET_LANES = ["actions", "sandbox"];
1839
1534
  function parseMarketLane(value) {
1840
1535
  if (value === void 0) return "actions";
1841
1536
  if (!MARKET_LANES.includes(value)) {
1842
- throw new ActionsCliError(
1537
+ throw new PlatformClientError(
1843
1538
  "invalid_argument",
1844
1539
  `--use-case must be ${MARKET_LANES.join(" or ")}, got "${value}".`
1845
1540
  );
@@ -1848,7 +1543,7 @@ function parseMarketLane(value) {
1848
1543
  }
1849
1544
  function parseRate(price, per) {
1850
1545
  if (price === void 0) {
1851
- throw new ActionsCliError("invalid_argument", "A price is required \u2014 pass --price <usd>/<unit>.");
1546
+ throw new PlatformClientError("invalid_argument", "A price is required \u2014 pass --price <usd>/<unit>.");
1852
1547
  }
1853
1548
  let usdText = price;
1854
1549
  let unit = per;
@@ -1857,7 +1552,7 @@ function parseRate(price, per) {
1857
1552
  usdText = price.slice(0, slash);
1858
1553
  const inline = price.slice(slash + 1);
1859
1554
  if (per !== void 0 && per !== inline) {
1860
- throw new ActionsCliError(
1555
+ throw new PlatformClientError(
1861
1556
  "invalid_argument",
1862
1557
  `--price "${price}" conflicts with --per "${per}".`
1863
1558
  );
@@ -1866,19 +1561,19 @@ function parseRate(price, per) {
1866
1561
  }
1867
1562
  const usd = Number(usdText);
1868
1563
  if (!USD_RE.test(usdText) || !Number.isFinite(usd) || usd <= 0) {
1869
- throw new ActionsCliError(
1564
+ throw new PlatformClientError(
1870
1565
  "invalid_argument",
1871
1566
  `Invalid --price "${price}". Expected a positive dollar amount (e.g. 0.12/hour).`
1872
1567
  );
1873
1568
  }
1874
1569
  if (unit === void 0) {
1875
- throw new ActionsCliError(
1570
+ throw new PlatformClientError(
1876
1571
  "invalid_argument",
1877
1572
  "--price needs a unit \u2014 write it as <usd>/<unit> (e.g. --price 0.12/hour) or pass --per hour."
1878
1573
  );
1879
1574
  }
1880
1575
  if (!RATE_UNITS.includes(unit)) {
1881
- throw new ActionsCliError(
1576
+ throw new PlatformClientError(
1882
1577
  "invalid_argument",
1883
1578
  `The unit must be second, minute, or hour, got "${unit}".`
1884
1579
  );
@@ -1889,7 +1584,7 @@ function parseCapacity(value) {
1889
1584
  if (value === void 0) return void 0;
1890
1585
  const n = Number(value);
1891
1586
  if (!Number.isInteger(n) || n <= 0) {
1892
- throw new ActionsCliError(
1587
+ throw new PlatformClientError(
1893
1588
  "invalid_argument",
1894
1589
  `Invalid --capacity "${value}". Expected a positive integer.`
1895
1590
  );
@@ -1900,7 +1595,7 @@ function parseExpiresIn(value) {
1900
1595
  if (value === void 0) return void 0;
1901
1596
  const hours = Number(value);
1902
1597
  if (!Number.isFinite(hours) || hours <= 0) {
1903
- throw new ActionsCliError(
1598
+ throw new PlatformClientError(
1904
1599
  "invalid_argument",
1905
1600
  `Invalid --expires-in "${value}". Expected a positive number of hours.`
1906
1601
  );
@@ -1912,7 +1607,7 @@ function sellBody(opts) {
1912
1607
  const maxConcurrent = parseCapacity(opts.capacity);
1913
1608
  const expiresInHours = parseExpiresIn(opts.expiresIn);
1914
1609
  if (opts.renew && expiresInHours === void 0) {
1915
- throw new ActionsCliError(
1610
+ throw new PlatformClientError(
1916
1611
  "invalid_argument",
1917
1612
  "--renew requires --expires-in \u2014 a standing listing never expires."
1918
1613
  );
@@ -1939,7 +1634,7 @@ function listingPatchBody(listingId, change) {
1939
1634
  if (maxConcurrent !== void 0) body.maxConcurrent = maxConcurrent;
1940
1635
  if (change.status !== void 0) body.status = change.status;
1941
1636
  if (body.usd === void 0 && body.maxConcurrent === void 0 && body.status === void 0) {
1942
- throw new ActionsCliError(
1637
+ throw new PlatformClientError(
1943
1638
  "invalid_argument",
1944
1639
  "Nothing to change \u2014 pass --price, --capacity, or a status command."
1945
1640
  );
@@ -1954,7 +1649,7 @@ function credentialValues(providerId, fields, overrides, env = process.env) {
1954
1649
  const declared = new Set(fields.map((f) => f.name));
1955
1650
  const unknown = Object.keys(overrides).filter((name) => !declared.has(name));
1956
1651
  if (unknown.length > 0) {
1957
- throw new ActionsCliError(
1652
+ throw new PlatformClientError(
1958
1653
  "invalid_argument",
1959
1654
  `${providerId} takes no credential field "${unknown.join('", "')}" \u2014 expected one of ${fields.map((f) => f.name).join(", ")}.`
1960
1655
  );
@@ -2082,7 +1777,7 @@ function replaceTarget(listingId, fillId) {
2082
1777
  };
2083
1778
  }
2084
1779
  if (listingId === void 0) {
2085
- throw new ActionsCliError(
1780
+ throw new PlatformClientError(
2086
1781
  "invalid_argument",
2087
1782
  "Nothing to replace \u2014 pass a listing ID or --fill <fill-id>."
2088
1783
  );
@@ -2119,7 +1814,7 @@ function bidBody(opts) {
2119
1814
  function parseTopupAmount(value) {
2120
1815
  const usd = Number(value.replace(/^\$/, ""));
2121
1816
  if (!USD_RE.test(value.replace(/^\$/, "")) || !Number.isFinite(usd) || usd <= 0) {
2122
- throw new ActionsCliError(
1817
+ throw new PlatformClientError(
2123
1818
  "invalid_argument",
2124
1819
  `Invalid amount "${value}". Expected a positive dollar amount (e.g. 50).`
2125
1820
  );
@@ -2207,7 +1902,7 @@ function registerMarketCommands(program2) {
2207
1902
  );
2208
1903
  const preset = provider.sizes.find((s) => s.name === "medium") ?? provider.sizes[0];
2209
1904
  if (!preset) {
2210
- throw new ActionsCliError(
1905
+ throw new PlatformClientError(
2211
1906
  "invalid_argument",
2212
1907
  `--size is required \u2014 ${provider.provider} advertises no size tiers.`
2213
1908
  );
@@ -2507,7 +2202,7 @@ function registerMarketCommands(program2) {
2507
2202
  "/api/v1/market/provider"
2508
2203
  );
2509
2204
  if (provider.credentialFields.length === 0) {
2510
- throw new ActionsCliError(
2205
+ throw new PlatformClientError(
2511
2206
  "invalid_argument",
2512
2207
  `${provider.provider} authenticates with the deployment's own identity \u2014 there is no credential to connect.`
2513
2208
  );
@@ -2519,7 +2214,7 @@ function registerMarketCommands(program2) {
2519
2214
  );
2520
2215
  if (resolved.missing.length > 0) {
2521
2216
  const hints = resolved.missing.map((f) => ` export ${resolved.envNames[f.name]}=\u2026 # ${f.label}`).join("\n");
2522
- throw new ActionsCliError(
2217
+ throw new PlatformClientError(
2523
2218
  "invalid_argument",
2524
2219
  `Missing credential field${resolved.missing.length === 1 ? "" : "s"}. Set:
2525
2220
  ${hints}`
@@ -2755,6 +2450,8 @@ var AUTH_LEAD_OPTS = [
2755
2450
  ];
2756
2451
  var EXEC_LEAD_OPTS = [
2757
2452
  ...AUTH_LEAD_OPTS,
2453
+ { aliases: ["--cwd"], key: "cwd", flag: "value" },
2454
+ { aliases: ["-e", "--env"], key: "env", flag: "repeat" },
2758
2455
  { aliases: ["--timeout-ms"], key: "timeoutMs", flag: "value" }
2759
2456
  ];
2760
2457
  var SPAWN_LEAD_OPTS = [
@@ -2851,7 +2548,7 @@ function resolveSandbox(argId, opts) {
2851
2548
  return {
2852
2549
  id: r.id,
2853
2550
  clearStale: (error) => {
2854
- if (r.source === "file" && error instanceof ActionsApiError && error.status === 404 && readFileCurrent(org2) === r.id) {
2551
+ if (r.source === "file" && error instanceof PlatformApiError && error.status === 404 && readFileCurrent(org2) === r.id) {
2855
2552
  clearCurrentInstance(org2);
2856
2553
  console.error(pc4.dim(`cleared stale current instance ${shortId(r.id)}`));
2857
2554
  }
@@ -3092,7 +2789,7 @@ function registerSandboxesCommands(program2) {
3092
2789
  fail(e, opts);
3093
2790
  }
3094
2791
  });
3095
- cmd.command("exec [sandboxId] [command...]").description("Run a one-shot command and print its result (options before the command; -- also works)").option("--timeout-ms <ms>", "command timeout in ms").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (argId, rawCommand, rawOpts) => {
2792
+ cmd.command("exec [sandboxId] [command...]").description("Run a one-shot command and print its result (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("--timeout-ms <ms>", "command timeout in ms").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (argId, rawCommand, rawOpts) => {
3096
2793
  let opts = rawOpts;
3097
2794
  try {
3098
2795
  if (argId !== void 0 && !isUuid(argId)) {
@@ -3109,6 +2806,8 @@ function registerSandboxesCommands(program2) {
3109
2806
  `/api/v1/sandboxes/${resolved.id}/commands`,
3110
2807
  {
3111
2808
  command: command.map(shellQuote).join(" "),
2809
+ ...opts.cwd ? { cwd: opts.cwd } : {},
2810
+ ...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
3112
2811
  ...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
3113
2812
  }
3114
2813
  ).catch((e) => {