@computesdk/cli 2.6.4 → 2.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +348 -4
- package/cli-manifest.json +3425 -0
- package/dist/index.js +2057 -494
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
package/dist/index.js
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
import "dotenv/config";
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
import * as p from "@clack/prompts";
|
|
7
|
-
import
|
|
8
|
-
import { readFileSync as
|
|
7
|
+
import pc13 from "picocolors";
|
|
8
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
9
9
|
import { fileURLToPath } from "url";
|
|
10
|
-
import { dirname as
|
|
10
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
11
11
|
|
|
12
12
|
// src/providers.ts
|
|
13
13
|
var PROVIDER_ENV = {
|
|
@@ -65,12 +65,12 @@ function getProviderStatus() {
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
// src/actions.ts
|
|
68
|
-
import
|
|
69
|
-
import { mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
68
|
+
import pc7 from "picocolors";
|
|
69
|
+
import { mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
70
70
|
import { spawnSync } from "child_process";
|
|
71
71
|
|
|
72
72
|
// src/settings.ts
|
|
73
|
-
import
|
|
73
|
+
import pc2 from "picocolors";
|
|
74
74
|
|
|
75
75
|
// src/actions-client.ts
|
|
76
76
|
import {
|
|
@@ -146,6 +146,32 @@ function formatUsdPer(rate) {
|
|
|
146
146
|
return formatRateAllUnits(rateAllUnits(rate));
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
+
// src/term.ts
|
|
150
|
+
import pc from "picocolors";
|
|
151
|
+
function safeTerm(s) {
|
|
152
|
+
return s.replace(/[\u0000-\u001F\u007F-\u009F]/g, "\uFFFD");
|
|
153
|
+
}
|
|
154
|
+
function safeTermText(s) {
|
|
155
|
+
return s.replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g, "\uFFFD");
|
|
156
|
+
}
|
|
157
|
+
function conclusionLabel(conclusion) {
|
|
158
|
+
switch (conclusion) {
|
|
159
|
+
case "passed":
|
|
160
|
+
return pc.green("passed");
|
|
161
|
+
case "failed":
|
|
162
|
+
return pc.red("failed");
|
|
163
|
+
case "running":
|
|
164
|
+
return pc.yellow("running");
|
|
165
|
+
case "cancelled":
|
|
166
|
+
return pc.gray("cancelled");
|
|
167
|
+
case "none":
|
|
168
|
+
return pc.yellow("queued");
|
|
169
|
+
// Anything else is the server's string verbatim.
|
|
170
|
+
default:
|
|
171
|
+
return safeTerm(conclusion);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
149
175
|
// src/settings.ts
|
|
150
176
|
var PLATFORM_SIZES = ["small", "medium", "large", "xlarge"];
|
|
151
177
|
function parseMaxPrice(value, per) {
|
|
@@ -193,14 +219,62 @@ function parseSizeCap(entry) {
|
|
|
193
219
|
}
|
|
194
220
|
return { size, cap };
|
|
195
221
|
}
|
|
222
|
+
var MAX_WARM_POOL_SIZE = 16;
|
|
223
|
+
var MAX_SNAPSHOT_POOL_SIZE = 32;
|
|
224
|
+
function parseResourcesFlag(entry) {
|
|
225
|
+
const eq = entry.indexOf("=");
|
|
226
|
+
const provider = eq === -1 ? "" : entry.slice(0, eq).trim();
|
|
227
|
+
const preset = eq === -1 ? "" : entry.slice(eq + 1).trim();
|
|
228
|
+
if (provider === "" || preset === "") {
|
|
229
|
+
throw new PlatformClientError(
|
|
230
|
+
"invalid_argument",
|
|
231
|
+
`Invalid --resources "${entry}" \u2014 expected <provider>=<preset> (e.g. blaxel=large) or <provider>=none.`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
return { provider, preset: preset === "none" ? null : preset };
|
|
235
|
+
}
|
|
236
|
+
function parsePoolFlag(flag, entry, max) {
|
|
237
|
+
const eq = entry.indexOf("=");
|
|
238
|
+
const key = eq === -1 ? "" : entry.slice(0, eq).trim();
|
|
239
|
+
const value = eq === -1 ? "" : entry.slice(eq + 1).trim();
|
|
240
|
+
const size = Number(value);
|
|
241
|
+
if (key === "" || !/^\d+$/.test(value) || size > max) {
|
|
242
|
+
throw new PlatformClientError(
|
|
243
|
+
"invalid_argument",
|
|
244
|
+
`Invalid ${flag} "${entry}" \u2014 expected <provider>[:<region>]=<n> with n in 0..${max} (0 clears it).`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
return { key, size };
|
|
248
|
+
}
|
|
249
|
+
function parseWarmPoolFlag(entry) {
|
|
250
|
+
return parsePoolFlag("--warm-pool", entry, MAX_WARM_POOL_SIZE);
|
|
251
|
+
}
|
|
252
|
+
function parseSnapshotPoolFlag(entry) {
|
|
253
|
+
return parsePoolFlag("--snapshot-pool", entry, MAX_SNAPSHOT_POOL_SIZE);
|
|
254
|
+
}
|
|
255
|
+
function poolPatch(entries, parse) {
|
|
256
|
+
const pool = {};
|
|
257
|
+
for (const entry of entries) {
|
|
258
|
+
const { key, size } = parse(entry);
|
|
259
|
+
pool[key] = size;
|
|
260
|
+
}
|
|
261
|
+
return pool;
|
|
262
|
+
}
|
|
263
|
+
function formatResources(r) {
|
|
264
|
+
const parts = [];
|
|
265
|
+
if (r.cpus !== void 0) parts.push(`${r.cpus} vCPU`);
|
|
266
|
+
if (r.memoryMb !== void 0) parts.push(`${r.memoryMb} MB`);
|
|
267
|
+
if (r.ephemeralDiskMb) parts.push(`${r.ephemeralDiskMb} MB disk`);
|
|
268
|
+
return parts.join(" / ") || "\u2014";
|
|
269
|
+
}
|
|
196
270
|
var fmtRate = (cap) => cap ? formatUsdPer(cap) : "\u2014";
|
|
197
|
-
var fmtRef = (ref) => ref ? ` ${
|
|
271
|
+
var fmtRef = (ref) => ref ? ` ${pc2.dim(`reference ${formatUsdPer(ref)}`)}` : "";
|
|
198
272
|
function printLaneSettings(s, lane) {
|
|
199
273
|
const sandbox = lane === "sandboxes";
|
|
200
274
|
const orderType = s.marketOrderType ?? (sandbox ? "inherit" : "\u2014");
|
|
201
|
-
const orderSuffix = sandbox && s.marketOrderType == null ?
|
|
275
|
+
const orderSuffix = sandbox && s.marketOrderType == null ? pc2.dim(` (Actions: ${s.actionsMarketOrderType ?? "\u2014"})`) : "";
|
|
202
276
|
console.log(`order type: ${orderType}${orderSuffix}`);
|
|
203
|
-
const capSuffix = sandbox && s.marketCap == null ?
|
|
277
|
+
const capSuffix = sandbox && s.marketCap == null ? pc2.dim(` (inherits Actions: ${fmtRate(s.actionsMarketCap)})`) : "";
|
|
204
278
|
console.log(`general cap: ${fmtRate(s.marketCap)}${capSuffix}`);
|
|
205
279
|
console.log("per-size caps:");
|
|
206
280
|
for (const size of PLATFORM_SIZES) {
|
|
@@ -209,15 +283,14 @@ function printLaneSettings(s, lane) {
|
|
|
209
283
|
` ${size.padEnd(7)} ${fmtRate(cap)}${cap ? "" : fmtRef(s.referencePrices?.[size])}`
|
|
210
284
|
);
|
|
211
285
|
}
|
|
212
|
-
const
|
|
213
|
-
console.log(`provider order: ${
|
|
286
|
+
const orderText2 = s.providerOrder.length > 0 ? s.providerOrder.join(", ") : sandbox ? pc2.dim(`inherit (Actions: ${(s.actionsProviderOrder ?? []).join(", ") || "\u2014"})`) : s.defaultProviderOrder && s.defaultProviderOrder.length > 0 ? pc2.dim(`default (${s.defaultProviderOrder.join(", ")})`) : "\u2014";
|
|
287
|
+
console.log(`provider order: ${orderText2}`);
|
|
214
288
|
const resources = Object.entries(s.providerResources ?? {});
|
|
215
|
-
console.log("
|
|
289
|
+
console.log("resources:");
|
|
216
290
|
if (resources.length === 0) console.log(" \u2014");
|
|
217
291
|
for (const [provider, r] of resources) {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
);
|
|
292
|
+
const preset = s.providerResourcePresets?.[provider];
|
|
293
|
+
console.log(preset ? ` ${provider} ${preset} (${formatResources(r)})` : ` ${provider} ${formatResources(r)}`);
|
|
221
294
|
}
|
|
222
295
|
const pool = Object.entries(s.warmPool ?? {});
|
|
223
296
|
console.log("warm pool:");
|
|
@@ -227,7 +300,22 @@ function printLaneSettings(s, lane) {
|
|
|
227
300
|
const snap = Object.entries(s.snapshotPool);
|
|
228
301
|
console.log("snapshot pool:");
|
|
229
302
|
if (snap.length === 0) console.log(" \u2014");
|
|
230
|
-
for (const [entry, cap] of snap) console.log(` ${entry} ${cap}`);
|
|
303
|
+
for (const [entry, cap] of snap) console.log(` ${safeTerm(entry)} ${cap}`);
|
|
304
|
+
}
|
|
305
|
+
if (s.snapshotSummary !== void 0) printSnapshotSummary(s.snapshotSummary);
|
|
306
|
+
}
|
|
307
|
+
function printSnapshotSummary(summary) {
|
|
308
|
+
const capped = summary.workflows.filter((w) => w.snapshotCap !== null);
|
|
309
|
+
console.log("workflow snapshot caps:");
|
|
310
|
+
if (capped.length === 0) console.log(` ${pc2.dim("\u2014 (every workflow uses the dynamic pool)")}`);
|
|
311
|
+
for (const w of capped) {
|
|
312
|
+
const cap = w.snapshotCap === 0 ? "off" : String(w.snapshotCap);
|
|
313
|
+
console.log(` ${safeTerm(w.repoFullName)} ${safeTerm(w.path)} ${cap}`);
|
|
314
|
+
}
|
|
315
|
+
console.log("live snapshots:");
|
|
316
|
+
if (summary.live.length === 0) console.log(" \u2014");
|
|
317
|
+
for (const row of summary.live) {
|
|
318
|
+
console.log(` ${safeTerm(row.repoFullName)} ${row.workflowPath === null ? pc2.dim("(no workflow)") : safeTerm(row.workflowPath)} ${row.count}`);
|
|
231
319
|
}
|
|
232
320
|
}
|
|
233
321
|
function settingsFail(e, opts, lane, verb, deps) {
|
|
@@ -243,8 +331,8 @@ function settingsFail(e, opts, lane, verb, deps) {
|
|
|
243
331
|
}
|
|
244
332
|
return deps.fail(e, opts);
|
|
245
333
|
}
|
|
246
|
-
function registerSettingsCommands(group, lane,
|
|
247
|
-
const settings =
|
|
334
|
+
function registerSettingsCommands(group, lane, common2, deps) {
|
|
335
|
+
const settings = common2(
|
|
248
336
|
group.command("settings").description(`Show the org's ${lane} routing policy (order, caps, sizes, pools)`).configureOutput({
|
|
249
337
|
outputError: (str, write) => deps.usageErrorOutput(str, write)
|
|
250
338
|
})
|
|
@@ -257,7 +345,7 @@ function registerSettingsCommands(group, lane, common, deps) {
|
|
|
257
345
|
settingsFail(e, opts, lane, "view", deps);
|
|
258
346
|
}
|
|
259
347
|
});
|
|
260
|
-
|
|
348
|
+
const set = common2(
|
|
261
349
|
settings.command("set").description(`Update the org's ${lane} routing policy`).option(
|
|
262
350
|
"--cap <size=rate>",
|
|
263
351
|
"per-size cap: <size>=<usd>/<unit> or <size>=none to clear (repeatable)",
|
|
@@ -270,55 +358,838 @@ function registerSettingsCommands(group, lane, common, deps) {
|
|
|
270
358
|
"--order <providers>",
|
|
271
359
|
lane === "sandboxes" ? 'provider order, comma-separated (e.g. "market,blaxel,vercel"); "inherit" restores the Actions order' : 'provider order, comma-separated (e.g. "market,blaxel,vercel"); "default" restores the platform default'
|
|
272
360
|
)
|
|
361
|
+
);
|
|
362
|
+
set.option(
|
|
363
|
+
"--resources <provider=preset>",
|
|
364
|
+
"per-provider size preset (e.g. blaxel=large); <provider>=none clears it (repeatable)",
|
|
365
|
+
(v, a) => a.concat(v),
|
|
366
|
+
[]
|
|
367
|
+
).option(
|
|
368
|
+
"--warm-pool <provider[:region]=n>",
|
|
369
|
+
`warm pool size per placement entry, 0..${MAX_WARM_POOL_SIZE}; 0 clears it (repeatable)`,
|
|
370
|
+
(v, a) => a.concat(v),
|
|
371
|
+
[]
|
|
372
|
+
);
|
|
373
|
+
if (lane === "actions") {
|
|
374
|
+
set.option(
|
|
375
|
+
"--snapshot-pool <provider[:region]=n>",
|
|
376
|
+
`snapshot cap per placement entry, 0..${MAX_SNAPSHOT_POOL_SIZE}; 0 clears it (repeatable)`,
|
|
377
|
+
(v, a) => a.concat(v),
|
|
378
|
+
[]
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
set.action(async (opts) => {
|
|
382
|
+
try {
|
|
383
|
+
const body = {};
|
|
384
|
+
if (opts.cap.length > 0) {
|
|
385
|
+
const caps = {};
|
|
386
|
+
for (const entry of opts.cap) {
|
|
387
|
+
const { size, cap } = parseSizeCap(entry);
|
|
388
|
+
caps[size] = cap;
|
|
389
|
+
}
|
|
390
|
+
body.marketCaps = caps;
|
|
391
|
+
}
|
|
392
|
+
if (opts.generalCap !== void 0) {
|
|
393
|
+
body.marketCap = opts.generalCap === "none" ? null : parseMaxPrice(opts.generalCap, void 0);
|
|
394
|
+
}
|
|
395
|
+
if (opts.orderType !== void 0) {
|
|
396
|
+
if (lane === "sandboxes" && opts.orderType === "inherit") {
|
|
397
|
+
body.marketOrderType = null;
|
|
398
|
+
} else if (opts.orderType === "limit" || opts.orderType === "market") {
|
|
399
|
+
body.marketOrderType = opts.orderType;
|
|
400
|
+
} else {
|
|
401
|
+
throw new Error(
|
|
402
|
+
lane === "sandboxes" ? "--order-type must be limit, market, or inherit." : "--order-type must be limit or market."
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (opts.order !== void 0) {
|
|
407
|
+
if (opts.order === "inherit" && lane === "sandboxes") {
|
|
408
|
+
body.providerOrder = [];
|
|
409
|
+
} else if (opts.order === "default" && lane === "actions") {
|
|
410
|
+
body.providerOrder = [];
|
|
411
|
+
} else {
|
|
412
|
+
body.providerOrder = opts.order.split(",").map((s) => s.trim()).filter(Boolean);
|
|
413
|
+
if (body.providerOrder.length === 0) {
|
|
414
|
+
throw new Error(
|
|
415
|
+
lane === "sandboxes" ? `--order "${opts.order}" names no providers \u2014 pass a comma-separated list or "inherit".` : `--order "${opts.order}" names no providers \u2014 pass a comma-separated list or "default".`
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (opts.resources && opts.resources.length > 0) {
|
|
421
|
+
const resources = {};
|
|
422
|
+
for (const entry of opts.resources) {
|
|
423
|
+
const { provider, preset } = parseResourcesFlag(entry);
|
|
424
|
+
resources[provider] = preset;
|
|
425
|
+
}
|
|
426
|
+
body.providerResources = resources;
|
|
427
|
+
}
|
|
428
|
+
if (opts.warmPool && opts.warmPool.length > 0) {
|
|
429
|
+
body.warmPool = poolPatch(opts.warmPool, parseWarmPoolFlag);
|
|
430
|
+
}
|
|
431
|
+
if (opts.snapshotPool && opts.snapshotPool.length > 0) {
|
|
432
|
+
body.snapshotPool = poolPatch(opts.snapshotPool, parseSnapshotPoolFlag);
|
|
433
|
+
}
|
|
434
|
+
if (Object.keys(body).length === 0) {
|
|
435
|
+
throw new Error(
|
|
436
|
+
lane === "sandboxes" ? "Nothing to change \u2014 pass --cap, --general-cap, --order-type, --order, --resources, or --warm-pool." : "Nothing to change \u2014 pass --cap, --general-cap, --order-type, --order, --resources, --warm-pool, or --snapshot-pool."
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
const c = await deps.client(opts);
|
|
440
|
+
const res = await c.patch(`/api/v1/${lane}/settings`, body);
|
|
441
|
+
deps.output(opts, res, (s) => printLaneSettings(s, lane));
|
|
442
|
+
} catch (e) {
|
|
443
|
+
settingsFail(e, opts, lane, "change", deps);
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// src/actions-repos.ts
|
|
449
|
+
import pc5 from "picocolors";
|
|
450
|
+
import { readFileSync } from "fs";
|
|
451
|
+
|
|
452
|
+
// src/actions-workflows.ts
|
|
453
|
+
import pc4 from "picocolors";
|
|
454
|
+
|
|
455
|
+
// src/actions-runs.ts
|
|
456
|
+
import pc3 from "picocolors";
|
|
457
|
+
|
|
458
|
+
// src/confirm.ts
|
|
459
|
+
import { createInterface } from "readline/promises";
|
|
460
|
+
async function confirmWrite(question, opts) {
|
|
461
|
+
if (opts.yes) return;
|
|
462
|
+
if (!process.stdin.isTTY) {
|
|
463
|
+
throw new PlatformClientError("confirmation_required", `${question} Pass -y to confirm.`);
|
|
464
|
+
}
|
|
465
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
466
|
+
let answer;
|
|
467
|
+
try {
|
|
468
|
+
answer = await rl.question(`${question} [y/N] `);
|
|
469
|
+
} finally {
|
|
470
|
+
rl.close();
|
|
471
|
+
}
|
|
472
|
+
if (!/^y(es)?$/i.test(answer.trim())) {
|
|
473
|
+
throw new PlatformClientError("cancelled", "Cancelled; nothing was changed.");
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// src/actions-runs.ts
|
|
478
|
+
var WORKFLOW_PATH_PREFIX = ".github/";
|
|
479
|
+
function plural(n, noun) {
|
|
480
|
+
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
481
|
+
}
|
|
482
|
+
function resolveWorkflowPaths(workflows, selectors) {
|
|
483
|
+
const paths = [];
|
|
484
|
+
for (const selector of selectors) {
|
|
485
|
+
const matchers = [
|
|
486
|
+
(w) => w.path === selector,
|
|
487
|
+
(w) => w.name === selector,
|
|
488
|
+
(w) => w.path.split("/").pop() === selector,
|
|
489
|
+
(w) => w.id === selector
|
|
490
|
+
];
|
|
491
|
+
let found = [];
|
|
492
|
+
for (const matches of matchers) {
|
|
493
|
+
found = workflows.filter(matches);
|
|
494
|
+
if (found.length > 0) break;
|
|
495
|
+
}
|
|
496
|
+
if (found.length === 0) {
|
|
497
|
+
const choices = [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(", ") || "none";
|
|
498
|
+
throw new PlatformClientError("workflow_not_found", `No workflow "${selector}". Available: ${choices}`);
|
|
499
|
+
}
|
|
500
|
+
for (const w of found) if (!paths.includes(w.path)) paths.push(w.path);
|
|
501
|
+
}
|
|
502
|
+
return paths;
|
|
503
|
+
}
|
|
504
|
+
async function runFilterQuery(c, repo, opts) {
|
|
505
|
+
let workflow;
|
|
506
|
+
if (opts.workflow && opts.workflow.length > 0) {
|
|
507
|
+
const lookups = opts.workflow.filter((s) => !s.startsWith(WORKFLOW_PATH_PREFIX));
|
|
508
|
+
const catalog = lookups.length === 0 ? [] : (await c.get("/api/v1/actions/workflows", { repo, include: "all" })).workflows;
|
|
509
|
+
workflow = [];
|
|
510
|
+
for (const selector of opts.workflow) {
|
|
511
|
+
const paths = selector.startsWith(WORKFLOW_PATH_PREFIX) ? [selector] : resolveWorkflowPaths(catalog, [selector]);
|
|
512
|
+
for (const path2 of paths) if (!workflow.includes(path2)) workflow.push(path2);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
repo,
|
|
517
|
+
status: opts.status,
|
|
518
|
+
branch: opts.branch,
|
|
519
|
+
event: opts.event,
|
|
520
|
+
workflow,
|
|
521
|
+
q: opts.search,
|
|
522
|
+
archived: opts.archived ? "only" : void 0,
|
|
523
|
+
reliability: opts.reliability ? "1" : void 0
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function parseDayCursor(value) {
|
|
527
|
+
const comma = value.lastIndexOf(",");
|
|
528
|
+
if (comma <= 0 || comma === value.length - 1) {
|
|
529
|
+
throw new PlatformClientError(
|
|
530
|
+
"invalid_argument",
|
|
531
|
+
`Invalid --cursor "${value}". Expected <startedAt>,<id>, as printed after a page.`
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
return { startedAt: value.slice(0, comma), id: value.slice(comma + 1) };
|
|
535
|
+
}
|
|
536
|
+
async function listDayRuns(c, day, query, { all, cursor }) {
|
|
537
|
+
const runs = [];
|
|
538
|
+
const seen = /* @__PURE__ */ new Set();
|
|
539
|
+
let next = cursor ?? null;
|
|
540
|
+
for (; ; ) {
|
|
541
|
+
const page = await c.get(`/api/v1/actions/runs/day/${encodeURIComponent(day)}`, {
|
|
542
|
+
...query,
|
|
543
|
+
cursorStartedAt: next?.startedAt,
|
|
544
|
+
cursorId: next?.id
|
|
545
|
+
});
|
|
546
|
+
runs.push(...page.runs);
|
|
547
|
+
next = page.nextCursor ?? null;
|
|
548
|
+
if (!all || next === null) return { runs, nextCursor: next };
|
|
549
|
+
const key = `${next.startedAt},${next.id}`;
|
|
550
|
+
if (seen.has(key)) throw new PlatformClientError("invalid_argument", `The platform repeated cursor ${key}; stopping.`);
|
|
551
|
+
seen.add(key);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function formatRunDays(days) {
|
|
555
|
+
if (days.length === 0) return "No runs found.";
|
|
556
|
+
return days.map((d) => `${safeTerm(d.day)} ${plural(d.count, "run")}`).join("\n");
|
|
557
|
+
}
|
|
558
|
+
function formatDayCursor(cursor) {
|
|
559
|
+
return `more: --cursor ${safeTerm(cursor.startedAt)},${safeTerm(cursor.id)}`;
|
|
560
|
+
}
|
|
561
|
+
function archiveQuestion(count, archived) {
|
|
562
|
+
return archived ? `Archive ${plural(count, "run")}? Archived runs leave the run lists and counts; \`compute actions runs unarchive\` restores them.` : `Unarchive ${plural(count, "run")}? They return to the run lists and counts.`;
|
|
563
|
+
}
|
|
564
|
+
function notFoundIds(error) {
|
|
565
|
+
if (!(error instanceof PlatformApiError)) return [];
|
|
566
|
+
const ids = error.details?.notFound;
|
|
567
|
+
return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
|
|
568
|
+
}
|
|
569
|
+
function registerRunsCommands(actions, common2, deps) {
|
|
570
|
+
const withFilters = (cmd) => cmd.option("--status <status...>", "filter by conclusion: passed, failed, running, cancelled, none").option("--branch <branch...>", "filter by branch/ref").option("--event <event...>", "filter by trigger: push, pull_request, schedule, workflow_dispatch").option("--workflow <path|name...>", "filter by workflow path, name or file name (e.g. ci.yml)").option("--search <text>", "search title, ref, SHA prefix, workflow, #run or #PR number").option("--archived", "archived runs only (hidden by default)").option("--reliability", "reliability runs only (hidden by default)");
|
|
571
|
+
const printRuns = (runs2) => {
|
|
572
|
+
if (runs2.length === 0) {
|
|
573
|
+
console.log("No runs found.");
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
for (const run of runs2) console.log(deps.formatRunRow(run));
|
|
577
|
+
};
|
|
578
|
+
const runs = actions.command("runs").description("List recent runs (every repo, or one), or one day's runs with --day");
|
|
579
|
+
common2(
|
|
580
|
+
withFilters(runs.argument("[repo]", "repository in owner/repo format (default: every repo)")).option("--day <YYYY-MM-DD>", "list one day's runs, page by page, instead of the newest 100").option("--time-zone <iana>", "with --day: the time zone the day is read in (default: UTC)").option("--cursor <startedAt,id>", "with --day: continue after this cursor (printed after a page)").option("--all", "with --day: follow every page")
|
|
581
|
+
).action(async (repo, opts) => {
|
|
582
|
+
try {
|
|
583
|
+
if (opts.day === void 0 && (opts.all || opts.timeZone !== void 0 || opts.cursor !== void 0)) {
|
|
584
|
+
throw new PlatformClientError("invalid_argument", "--all, --time-zone and --cursor page one day's runs: pass --day <YYYY-MM-DD>.");
|
|
585
|
+
}
|
|
586
|
+
const cursor = opts.cursor === void 0 ? void 0 : parseDayCursor(opts.cursor);
|
|
587
|
+
const c = await deps.client(opts);
|
|
588
|
+
const query = await runFilterQuery(c, repo, opts);
|
|
589
|
+
if (opts.day !== void 0) {
|
|
590
|
+
const page = await listDayRuns(c, opts.day, { ...query, timeZone: opts.timeZone }, { all: opts.all === true, cursor });
|
|
591
|
+
deps.output(opts, page, (p2) => {
|
|
592
|
+
printRuns(p2.runs);
|
|
593
|
+
if (p2.nextCursor) console.log(pc3.dim(formatDayCursor(p2.nextCursor)));
|
|
594
|
+
});
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const { runs: list } = await c.get("/api/v1/actions/runs", query);
|
|
598
|
+
deps.output(opts, list, printRuns);
|
|
599
|
+
} catch (e) {
|
|
600
|
+
deps.fail(e, opts);
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
common2(
|
|
604
|
+
withFilters(
|
|
605
|
+
runs.command("days").description("How many runs each day holds, newest first (same filters as runs)").argument("[repo]", "repository in owner/repo format (default: every repo)")
|
|
606
|
+
).option("--time-zone <iana>", "the time zone days are read in (default: UTC)")
|
|
607
|
+
).action(async (repo, opts) => {
|
|
608
|
+
try {
|
|
609
|
+
const c = await deps.client(opts);
|
|
610
|
+
const query = await runFilterQuery(c, repo, opts);
|
|
611
|
+
const data = await c.get("/api/v1/actions/run-days", { ...query, timeZone: opts.timeZone });
|
|
612
|
+
deps.output(opts, data, (d) => console.log(formatRunDays(d.days)));
|
|
613
|
+
} catch (e) {
|
|
614
|
+
deps.fail(e, opts);
|
|
615
|
+
}
|
|
616
|
+
});
|
|
617
|
+
for (const archived of [true, false]) {
|
|
618
|
+
const verb = archived ? "archive" : "unarchive";
|
|
619
|
+
common2(
|
|
620
|
+
runs.command(verb).description(
|
|
621
|
+
archived ? "Archive runs: hide them from run lists and counts, still reachable by id (owner/admin)" : "Restore archived runs to the run lists (owner/admin)"
|
|
622
|
+
).argument("<run-id...>", "run IDs").option("-y, --yes", "skip the confirmation")
|
|
623
|
+
).action(async (runIds, opts) => {
|
|
624
|
+
try {
|
|
625
|
+
await confirmWrite(archiveQuestion(runIds.length, archived), opts);
|
|
626
|
+
const result = await (await deps.client(opts)).post("/api/v1/actions/runs/archive", {
|
|
627
|
+
runIds,
|
|
628
|
+
archived
|
|
629
|
+
});
|
|
630
|
+
deps.output(opts, result, (r) => console.log(`${verb}d ${plural(r.archived, "run")}`));
|
|
631
|
+
} catch (e) {
|
|
632
|
+
const missing = notFoundIds(e);
|
|
633
|
+
if (!opts.json && missing.length > 0 && e instanceof PlatformApiError) {
|
|
634
|
+
deps.fail(new PlatformApiError(e.status, `${e.message} \u2014 not found: ${missing.join(", ")}`, e.body), opts);
|
|
635
|
+
}
|
|
636
|
+
deps.fail(e, opts);
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// src/actions-workflows.ts
|
|
643
|
+
function formatAgo(iso, now = Date.now()) {
|
|
644
|
+
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1e3));
|
|
645
|
+
if (s < 60) return `${s}s ago`;
|
|
646
|
+
const m = Math.floor(s / 60);
|
|
647
|
+
if (m < 60) return `${m}m ago`;
|
|
648
|
+
const h = Math.floor(m / 60);
|
|
649
|
+
if (h < 48) return `${h}h ago`;
|
|
650
|
+
return `${Math.floor(h / 24)}d ago`;
|
|
651
|
+
}
|
|
652
|
+
function orderText(order) {
|
|
653
|
+
return order && order.length > 0 ? order.map(safeTerm).join(",") : "inherits";
|
|
654
|
+
}
|
|
655
|
+
function snapshotText(cap) {
|
|
656
|
+
if (cap === null || cap === void 0) return "dynamic";
|
|
657
|
+
return cap === 0 ? "off" : String(cap);
|
|
658
|
+
}
|
|
659
|
+
function formatWorkflowInputs(inputs) {
|
|
660
|
+
return inputs.map((i) => {
|
|
661
|
+
const name = safeTerm(i.name);
|
|
662
|
+
if (i.required) return `${name}* (required)`;
|
|
663
|
+
return i.default !== "" ? `${name} default=${safeTerm(i.default)}` : name;
|
|
664
|
+
}).join(", ");
|
|
665
|
+
}
|
|
666
|
+
function stateLabel(w) {
|
|
667
|
+
if (w.repoEnabled === false) return pc4.gray("\u25CB repo disabled");
|
|
668
|
+
if (w.enabled === false || w.userDisabledAt) return pc4.gray("\u25CB disabled (user)");
|
|
669
|
+
return pc4.green("\u25CF enabled");
|
|
670
|
+
}
|
|
671
|
+
function formatWorkflowRow(w, now = Date.now()) {
|
|
672
|
+
const last = w.lastRun ? `${conclusionLabel(w.lastRun.conclusion)} ${formatAgo(w.lastRun.queuedAt, now)}` : "never";
|
|
673
|
+
const inputs = formatWorkflowInputs(w.inputs ?? []);
|
|
674
|
+
return [
|
|
675
|
+
stateLabel(w),
|
|
676
|
+
pc4.dim(safeTerm(w.repoFullName)),
|
|
677
|
+
`${safeTerm(w.path)} (${safeTerm(w.name)})`,
|
|
678
|
+
`order: ${orderText(w.providerOrder)}`,
|
|
679
|
+
`snapshots: ${snapshotText(w.snapshotCap)}`,
|
|
680
|
+
`last: ${last}`,
|
|
681
|
+
...inputs ? [pc4.dim(`inputs: ${inputs}`)] : []
|
|
682
|
+
].join(" ");
|
|
683
|
+
}
|
|
684
|
+
function formatRefOnlyRow(w) {
|
|
685
|
+
const inputs = formatWorkflowInputs(w.inputs);
|
|
686
|
+
return [
|
|
687
|
+
pc4.cyan("\u25C7 ref-only"),
|
|
688
|
+
`${safeTerm(w.path)} (${safeTerm(w.name)})`,
|
|
689
|
+
w.dispatchable ? inputs ? `inputs: ${inputs}` : pc4.dim("no inputs") : pc4.dim("push-only: dispatch with --manual")
|
|
690
|
+
].join(" ");
|
|
691
|
+
}
|
|
692
|
+
function matchRefOnly(refOnly, selector) {
|
|
693
|
+
const byPath = refOnly.find((w) => w.path === selector);
|
|
694
|
+
if (byPath) return byPath;
|
|
695
|
+
const byName = refOnly.filter((w) => w.name === selector);
|
|
696
|
+
if (byName.length > 1) {
|
|
697
|
+
throw new PlatformClientError(
|
|
698
|
+
"invalid_argument",
|
|
699
|
+
`"${selector}" matches ${byName.length} workflows only on this ref: ${byName.map((w) => safeTerm(w.path)).join(", ")}. Pass the path.`
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
return byName[0];
|
|
703
|
+
}
|
|
704
|
+
function workflowChoices(workflows) {
|
|
705
|
+
return [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(", ") || "none";
|
|
706
|
+
}
|
|
707
|
+
function resolveControlTarget(catalog, repo, selector) {
|
|
708
|
+
const inRepo = catalog.filter((w) => w.repoFullName === repo);
|
|
709
|
+
let paths;
|
|
710
|
+
try {
|
|
711
|
+
paths = resolveWorkflowPaths(inRepo, [selector]);
|
|
712
|
+
} catch (e) {
|
|
713
|
+
if (e instanceof PlatformClientError && e.code === "workflow_not_found") {
|
|
714
|
+
throw new PlatformClientError("workflow_not_found", `No workflow "${selector}" in ${repo}. Available: ${workflowChoices(inRepo)}`);
|
|
715
|
+
}
|
|
716
|
+
throw e;
|
|
717
|
+
}
|
|
718
|
+
if (paths.length > 1) {
|
|
719
|
+
throw new PlatformClientError(
|
|
720
|
+
"invalid_argument",
|
|
721
|
+
`"${selector}" matches ${paths.length} workflows in ${repo}: ${paths.join(", ")}. Pass the path.`
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
return paths[0];
|
|
725
|
+
}
|
|
726
|
+
function setControls(opts) {
|
|
727
|
+
const controls = {};
|
|
728
|
+
if (opts.order !== void 0 && opts.inheritOrder) {
|
|
729
|
+
throw new PlatformClientError("invalid_argument", "Pass --order or --inherit-order, not both.");
|
|
730
|
+
}
|
|
731
|
+
if (opts.snapshotCap !== void 0 && opts.dynamicSnapshots) {
|
|
732
|
+
throw new PlatformClientError("invalid_argument", "Pass --snapshot-cap or --dynamic-snapshots, not both.");
|
|
733
|
+
}
|
|
734
|
+
if (opts.inheritOrder) controls.providerOrder = null;
|
|
735
|
+
if (opts.order !== void 0) {
|
|
736
|
+
const order = opts.order.split(",").map((s) => s.trim()).filter(Boolean);
|
|
737
|
+
if (order.length === 0) {
|
|
738
|
+
throw new PlatformClientError(
|
|
739
|
+
"invalid_argument",
|
|
740
|
+
`--order "${opts.order}" names no providers \u2014 pass a comma-separated list, or --inherit-order.`
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
controls.providerOrder = order;
|
|
744
|
+
}
|
|
745
|
+
if (opts.dynamicSnapshots) controls.snapshotCap = null;
|
|
746
|
+
if (opts.snapshotCap !== void 0) {
|
|
747
|
+
if (!/^\d+$/.test(opts.snapshotCap.trim())) {
|
|
748
|
+
throw new PlatformClientError(
|
|
749
|
+
"invalid_argument",
|
|
750
|
+
`Invalid --snapshot-cap "${opts.snapshotCap}". Expected a whole number (0 turns snapshots off), or --dynamic-snapshots.`
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
controls.snapshotCap = Number(opts.snapshotCap.trim());
|
|
754
|
+
}
|
|
755
|
+
if (Object.keys(controls).length === 0) {
|
|
756
|
+
throw new PlatformClientError(
|
|
757
|
+
"invalid_argument",
|
|
758
|
+
"Nothing to change \u2014 pass --order, --inherit-order, --snapshot-cap or --dynamic-snapshots."
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
return controls;
|
|
762
|
+
}
|
|
763
|
+
function describeControls(c) {
|
|
764
|
+
const parts = [];
|
|
765
|
+
if (c.providerOrder !== void 0) parts.push(`order: ${orderText(c.providerOrder)}`);
|
|
766
|
+
if (c.snapshotCap !== void 0) parts.push(`snapshots: ${snapshotText(c.snapshotCap)}`);
|
|
767
|
+
return parts.join(", ");
|
|
768
|
+
}
|
|
769
|
+
function formatControlsResult(verb, r) {
|
|
770
|
+
const detail = verb === "set" ? ` order: ${orderText(r.providerOrder)} snapshots: ${snapshotText(r.snapshotCap)}` : "";
|
|
771
|
+
return `${verb} ${pc4.cyan(safeTerm(r.repoFullName))} ${safeTerm(r.path)}${detail}`;
|
|
772
|
+
}
|
|
773
|
+
function registerWorkflowsCommands(actions, common2, deps) {
|
|
774
|
+
const workflows = actions.command("workflows").description("List workflows with their controls (every repo, or one); --all adds disabled ones, --ref the files only a branch has");
|
|
775
|
+
common2(
|
|
776
|
+
workflows.argument("[repo]", "repository in owner/repo format (default: every repo)").option("--all", "include user-disabled workflows and workflows on disabled repos").option("--ref <ref>", "with a repo: also list the workflow files only this branch or tag has (dispatchable by path)")
|
|
777
|
+
).action(async (repo, opts) => {
|
|
778
|
+
try {
|
|
779
|
+
if (opts.ref !== void 0 && repo === void 0) {
|
|
780
|
+
throw new PlatformClientError("invalid_argument", "--ref needs a repo: compute actions workflows <owner/repo> --ref <ref>.");
|
|
781
|
+
}
|
|
782
|
+
const c = await deps.client(opts);
|
|
783
|
+
const data = await c.get("/api/v1/actions/workflows", {
|
|
784
|
+
repo,
|
|
785
|
+
include: opts.all ? "all" : void 0,
|
|
786
|
+
ref: opts.ref
|
|
787
|
+
});
|
|
788
|
+
deps.output(opts, data, (d) => {
|
|
789
|
+
if (d.workflows.length === 0 && (d.refOnly ?? []).length === 0) {
|
|
790
|
+
console.log("No workflows found.");
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
for (const w of d.workflows) console.log(formatWorkflowRow(w));
|
|
794
|
+
if (opts.ref !== void 0) {
|
|
795
|
+
const refOnly = d.refOnly ?? [];
|
|
796
|
+
console.log(pc4.dim(refOnly.length === 0 ? `only on ${safeTerm(opts.ref)}: none` : `only on ${safeTerm(opts.ref)}:`));
|
|
797
|
+
for (const w of refOnly) console.log(formatRefOnlyRow(w));
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
} catch (e) {
|
|
801
|
+
deps.fail(e, opts);
|
|
802
|
+
}
|
|
803
|
+
});
|
|
804
|
+
async function writeControls(repo, selector, controls, question, verb, opts) {
|
|
805
|
+
await confirmWrite(question, opts);
|
|
806
|
+
const c = await deps.client(opts);
|
|
807
|
+
const { workflows: catalog } = await c.get("/api/v1/actions/workflows", {
|
|
808
|
+
repo,
|
|
809
|
+
include: "all"
|
|
810
|
+
});
|
|
811
|
+
const path2 = resolveControlTarget(catalog, repo, selector);
|
|
812
|
+
const result = await c.patch("/api/v1/actions/workflows", {
|
|
813
|
+
repoFullName: repo,
|
|
814
|
+
path: path2,
|
|
815
|
+
...controls
|
|
816
|
+
});
|
|
817
|
+
deps.output(opts, result, (r) => console.log(formatControlsResult(verb, r)));
|
|
818
|
+
}
|
|
819
|
+
for (const enabled of [true, false]) {
|
|
820
|
+
const verb = enabled ? "enable" : "disable";
|
|
821
|
+
common2(
|
|
822
|
+
workflows.command(verb).description(
|
|
823
|
+
enabled ? "Turn a workflow back on (owner/admin)" : "Turn a workflow off: no pushes, schedules or dispatches run it until enabled (owner/admin)"
|
|
824
|
+
).argument("<repo>", "repository in owner/repo format").argument("<workflow>", "workflow path, name, file name (ci.yml) or id").option("-y, --yes", "skip the confirmation")
|
|
825
|
+
).action(async (repo, selector, opts) => {
|
|
826
|
+
try {
|
|
827
|
+
const question = enabled ? `Enable workflow "${selector}" in ${repo}? It runs again on its triggers.` : `Disable workflow "${selector}" in ${repo}? Pushes, schedules and dispatches stop running it until it is enabled.`;
|
|
828
|
+
await writeControls(repo, selector, { enabled }, question, `${verb}d`, opts);
|
|
829
|
+
} catch (e) {
|
|
830
|
+
deps.fail(e, opts);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
common2(
|
|
835
|
+
workflows.command("set").description("Set a workflow's provider order and snapshot cap (owner/admin)").argument("<repo>", "repository in owner/repo format").argument("<workflow>", "workflow path, name, file name (ci.yml) or id").option("--order <providers>", 'provider order for this workflow, comma-separated (e.g. "market,blaxel,vercel")').option("--inherit-order", "drop the workflow's order: it follows the org order").option("--snapshot-cap <n>", "most snapshots this workflow keeps (0 turns them off)").option("--dynamic-snapshots", "drop the cap: the workflow uses the dynamic snapshot pool").option("-y, --yes", "skip the confirmation")
|
|
836
|
+
).action(async (repo, selector, opts) => {
|
|
837
|
+
try {
|
|
838
|
+
const controls = setControls(opts);
|
|
839
|
+
await writeControls(
|
|
840
|
+
repo,
|
|
841
|
+
selector,
|
|
842
|
+
controls,
|
|
843
|
+
`Change workflow "${selector}" in ${repo} (${describeControls(controls)})?`,
|
|
844
|
+
"set",
|
|
845
|
+
opts
|
|
846
|
+
);
|
|
847
|
+
} catch (e) {
|
|
848
|
+
deps.fail(e, opts);
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/actions-repos.ts
|
|
854
|
+
var FORK_PRS = { allow: true, refuse: false };
|
|
855
|
+
function plural2(n, noun) {
|
|
856
|
+
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
857
|
+
}
|
|
858
|
+
function formatIn(iso, now = Date.now()) {
|
|
859
|
+
const s = Math.max(0, Math.round((Date.parse(iso) - now) / 1e3));
|
|
860
|
+
if (s < 60) return `in ${s}s`;
|
|
861
|
+
const m = Math.round(s / 60);
|
|
862
|
+
if (m < 60) return `in ${m}m`;
|
|
863
|
+
const h = Math.round(m / 60);
|
|
864
|
+
if (h < 48) return `in ${h}h`;
|
|
865
|
+
return `in ${Math.round(h / 24)}d`;
|
|
866
|
+
}
|
|
867
|
+
function pollText(r, now) {
|
|
868
|
+
if (!r.enabled) return null;
|
|
869
|
+
if (r.pollSchedule === "never") return "not polled yet";
|
|
870
|
+
if (!r.nextPollDueAt) return null;
|
|
871
|
+
return Date.parse(r.nextPollDueAt) <= now ? "poll due" : `next poll ${formatIn(r.nextPollDueAt, now)}`;
|
|
872
|
+
}
|
|
873
|
+
function formatRepoRow(r, now = Date.now()) {
|
|
874
|
+
const head = r.enabled ? pc5.green("enabled") : pc5.dim("disabled");
|
|
875
|
+
const via = r.authType === "github_app" ? "github-app" : r.authType;
|
|
876
|
+
const parts = [
|
|
877
|
+
safeTerm(via),
|
|
878
|
+
safeTerm(r.defaultBranch),
|
|
879
|
+
r.workflowPaths.length > 0 ? plural2(r.workflowPaths.length, "workflow") : "no workflows yet"
|
|
880
|
+
];
|
|
881
|
+
if (r.runs) {
|
|
882
|
+
parts.push(plural2(r.runs.total, "run"));
|
|
883
|
+
if (r.runs.lastRunState && r.runs.lastRunQueuedAt) {
|
|
884
|
+
parts.push(`last ${conclusionLabel(r.runs.lastRunState)} ${formatAgo(r.runs.lastRunQueuedAt, now)}`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
const poll = pollText(r, now);
|
|
888
|
+
if (poll) parts.push(poll);
|
|
889
|
+
if (r.forkPullRequests) parts.push("fork PRs on");
|
|
890
|
+
const error = r.lastPollError ? pc5.red(` poll error: ${safeTerm(r.lastPollError)}`) : "";
|
|
891
|
+
return `${head} ${safeTerm(r.fullName)} ${pc5.dim(parts.join(" \xB7 "))}${error}`;
|
|
892
|
+
}
|
|
893
|
+
function formatBranchRow(b, now = Date.now(), defaultBranch) {
|
|
894
|
+
const isDefault = defaultBranch !== void 0 && b.ref === `refs/heads/${defaultBranch}`;
|
|
895
|
+
const at = Number.isNaN(Date.parse(b.lastRunAt)) ? null : formatAgo(b.lastRunAt, now);
|
|
896
|
+
return [
|
|
897
|
+
safeTerm(b.ref) + (isDefault ? pc5.dim(" (default)") : ""),
|
|
898
|
+
...b.prNumber !== null ? [`PR #${b.prNumber}`] : [],
|
|
899
|
+
b.watched ? pc5.green("watched") : pc5.dim("history only"),
|
|
900
|
+
plural2(b.runCount, "run"),
|
|
901
|
+
...at ? [b.runCount > 0 ? `last ${at}` : pc5.dim(`moved ${at}`)] : [],
|
|
902
|
+
...b.latestRunId ? [pc5.dim(safeTerm(b.latestRunId))] : []
|
|
903
|
+
].join(" ");
|
|
904
|
+
}
|
|
905
|
+
function printDiscovery(d) {
|
|
906
|
+
if (d.error) {
|
|
907
|
+
console.log(pc5.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
console.log(pc5.dim(`discovery: ${d.workflowsFound ? "workflows found" : "no workflows yet"}${d.seeded ? ", cursors seeded" : ""}`));
|
|
911
|
+
}
|
|
912
|
+
function withRetryAfter(error) {
|
|
913
|
+
if (!(error instanceof PlatformApiError) || error.status !== 429) return error;
|
|
914
|
+
const next = error.details?.nextAllowedAt;
|
|
915
|
+
if (typeof next !== "string") return error;
|
|
916
|
+
const rewritten = new PlatformApiError(error.status, `${error.message}; retry after ${next} (${formatIn(next)})`, error.body);
|
|
917
|
+
rewritten.retryAfterMs = error.retryAfterMs;
|
|
918
|
+
return rewritten;
|
|
919
|
+
}
|
|
920
|
+
function parseForkPrs(value) {
|
|
921
|
+
if (!Object.prototype.hasOwnProperty.call(FORK_PRS, value)) {
|
|
922
|
+
throw new PlatformClientError("invalid_argument", `Invalid --fork-prs "${value}". Expected allow or refuse.`);
|
|
923
|
+
}
|
|
924
|
+
return FORK_PRS[value];
|
|
925
|
+
}
|
|
926
|
+
var repoIdBody = (opts) => opts.repoId !== void 0 ? { repoId: opts.repoId } : {};
|
|
927
|
+
var REPO_ID_HELP = "scope to one row when two installations grant the same name";
|
|
928
|
+
function registerReposCommands(actions, common2, deps) {
|
|
929
|
+
const { client: client2, output: output2, fail: fail3 } = deps;
|
|
930
|
+
const repos = actions.command("repos").description("List the org's connected repositories: run counts, last run and next poll");
|
|
931
|
+
common2(repos).action(async (opts) => {
|
|
932
|
+
try {
|
|
933
|
+
const data = await (await client2(opts)).get("/api/v1/actions/repos");
|
|
934
|
+
output2(opts, data, (d) => {
|
|
935
|
+
if (d.repos.length === 0) {
|
|
936
|
+
console.log("No repositories connected.");
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
for (const r of d.repos) console.log(formatRepoRow(r));
|
|
940
|
+
});
|
|
941
|
+
} catch (e) {
|
|
942
|
+
fail3(e, opts);
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
common2(
|
|
946
|
+
repos.command("connect").description("Connect a git remote (validated by a real ls-remote; lands enabled)").argument("<cloneUrl>", "http(s) or ssh git remote URL").option("--name <owner/repo>", "repo name override (default: derived from cloneUrl)").option("--branch <branch>", "default branch (default: main, else the remote's first)").option("--token <token>", "credential for private http(s) remotes").option("--username <user>", 'username \u2014 with --token, makes auth "basic" instead of "token"').option("--ssh-key-file <path>", "OpenSSH/PEM private key file for ssh remotes").option("--known-hosts-file <path>", "known_hosts pin for ssh remotes")
|
|
947
|
+
).action(async (cloneUrl, opts) => {
|
|
948
|
+
try {
|
|
949
|
+
let body;
|
|
950
|
+
if (opts.sshKeyFile !== void 0) {
|
|
951
|
+
if (opts.token !== void 0 || opts.username !== void 0) {
|
|
952
|
+
throw new Error("Pass either --ssh-key-file or --token/--username, not both.");
|
|
953
|
+
}
|
|
954
|
+
body = {
|
|
955
|
+
authType: "ssh",
|
|
956
|
+
credential: readFileSync(opts.sshKeyFile, "utf8"),
|
|
957
|
+
...opts.knownHostsFile !== void 0 && {
|
|
958
|
+
knownHosts: readFileSync(opts.knownHostsFile, "utf8")
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
} else if (opts.username !== void 0) {
|
|
962
|
+
if (opts.token === void 0) throw new Error("--username requires --token.");
|
|
963
|
+
body = { authType: "basic", username: opts.username, credential: opts.token };
|
|
964
|
+
} else if (opts.token !== void 0) {
|
|
965
|
+
body = { authType: "token", credential: opts.token };
|
|
966
|
+
} else {
|
|
967
|
+
body = { authType: "none" };
|
|
968
|
+
}
|
|
969
|
+
if (opts.knownHostsFile !== void 0 && opts.sshKeyFile === void 0) {
|
|
970
|
+
throw new Error("--known-hosts-file requires --ssh-key-file.");
|
|
971
|
+
}
|
|
972
|
+
const result = await (await client2(opts)).post("/api/v1/actions/repos", {
|
|
973
|
+
cloneUrl,
|
|
974
|
+
...body,
|
|
975
|
+
...opts.name !== void 0 && { name: opts.name },
|
|
976
|
+
...opts.branch !== void 0 && { defaultBranch: opts.branch }
|
|
977
|
+
});
|
|
978
|
+
output2(opts, result, (r) => {
|
|
979
|
+
console.log(`connected ${pc5.cyan(safeTerm(r.fullName))} ${pc5.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);
|
|
980
|
+
printDiscovery(r.discovery);
|
|
981
|
+
});
|
|
982
|
+
} catch (e) {
|
|
983
|
+
fail3(e, opts);
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
common2(
|
|
987
|
+
repos.command("sync").description("Re-read the GitHub App installation so repos granted after install show up (owner/admin key)")
|
|
988
|
+
).action(async (opts) => {
|
|
989
|
+
try {
|
|
990
|
+
const result = await (await client2(opts)).post("/api/v1/actions/repos/sync", {});
|
|
991
|
+
output2(opts, result, (r) => {
|
|
992
|
+
for (const a of r.accounts) {
|
|
993
|
+
console.log(a.error === null ? `synced ${pc5.cyan(safeTerm(a.account))}` : `failed ${pc5.cyan(safeTerm(a.account))} ${pc5.red(safeTerm(a.error))}`);
|
|
994
|
+
}
|
|
995
|
+
console.log(pc5.dim(`${r.repos.length} repos visible`));
|
|
996
|
+
});
|
|
997
|
+
if (result.accounts.some((a) => a.error !== null)) process.exitCode = 1;
|
|
998
|
+
} catch (e) {
|
|
999
|
+
fail3(e, opts);
|
|
1000
|
+
}
|
|
1001
|
+
});
|
|
1002
|
+
common2(
|
|
1003
|
+
repos.command("enable").description("Enable a repo the org can already see (granted by a GitHub App install, or a connected remote)").argument("<repo>", "repository in owner/repo format").option("--repo-id <id>", REPO_ID_HELP)
|
|
1004
|
+
).action(async (repo, opts) => {
|
|
1005
|
+
try {
|
|
1006
|
+
const result = await (await client2(opts)).patch("/api/v1/actions/repos", {
|
|
1007
|
+
fullName: repo,
|
|
1008
|
+
enabled: true,
|
|
1009
|
+
...repoIdBody(opts)
|
|
1010
|
+
});
|
|
1011
|
+
output2(opts, result, (r) => {
|
|
1012
|
+
console.log(`enabled ${pc5.cyan(safeTerm(r.fullName))}`);
|
|
1013
|
+
if (r.discovery) printDiscovery(r.discovery);
|
|
1014
|
+
});
|
|
1015
|
+
} catch (e) {
|
|
1016
|
+
fail3(e, opts);
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
common2(
|
|
1020
|
+
repos.command("disable").description("Disable a repo \u2014 it stays connected but no runs are scheduled").argument("<repo>", "repository in owner/repo format").option("--repo-id <id>", REPO_ID_HELP)
|
|
1021
|
+
).action(async (repo, opts) => {
|
|
1022
|
+
try {
|
|
1023
|
+
const result = await (await client2(opts)).patch("/api/v1/actions/repos", {
|
|
1024
|
+
fullName: repo,
|
|
1025
|
+
enabled: false,
|
|
1026
|
+
...repoIdBody(opts)
|
|
1027
|
+
});
|
|
1028
|
+
output2(opts, result, (r) => console.log(`disabled ${pc5.cyan(safeTerm(r.fullName))}`));
|
|
1029
|
+
} catch (e) {
|
|
1030
|
+
fail3(e, opts);
|
|
1031
|
+
}
|
|
1032
|
+
});
|
|
1033
|
+
common2(
|
|
1034
|
+
repos.command("poll").description("Poll a repo now: fetch its refs and start the runs new commits call for (owner/admin; at most every 30 s)").argument("<repo>", "repository in owner/repo format").option("--repo-id <id>", REPO_ID_HELP).option("-y, --yes", "skip the confirmation")
|
|
1035
|
+
).action(async (repo, opts) => {
|
|
1036
|
+
try {
|
|
1037
|
+
await confirmWrite(`Poll ${repo} now? New commits on its watched refs start the runs their workflows call for.`, opts);
|
|
1038
|
+
const c = await client2(opts);
|
|
1039
|
+
let result;
|
|
1040
|
+
try {
|
|
1041
|
+
result = await c.post("/api/v1/actions/repos/poll", { fullName: repo, ...repoIdBody(opts) });
|
|
1042
|
+
} catch (e) {
|
|
1043
|
+
throw withRetryAfter(e);
|
|
1044
|
+
}
|
|
1045
|
+
output2(opts, result, (r) => {
|
|
1046
|
+
console.log(`polled ${pc5.cyan(safeTerm(r.fullName))} ${plural2(r.createdRunIds.length, "run")} started`);
|
|
1047
|
+
if (r.error) console.log(pc5.red(`poll error: ${safeTerm(r.error)}`));
|
|
1048
|
+
});
|
|
1049
|
+
if (result.error) process.exitCode = 1;
|
|
1050
|
+
} catch (e) {
|
|
1051
|
+
fail3(e, opts);
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
common2(
|
|
1055
|
+
repos.command("set").description("Change a repo's settings: whether pull requests from forks run CI (owner/admin)").argument("<repo>", "repository in owner/repo format").requiredOption("--fork-prs <allow|refuse>", "run pull requests from forks (isolated: no org secrets, no GitHub token), or refuse them").option("--repo-id <id>", REPO_ID_HELP).option("-y, --yes", "skip the confirmation")
|
|
1056
|
+
).action(async (repo, opts) => {
|
|
1057
|
+
try {
|
|
1058
|
+
const forkPullRequests = parseForkPrs(opts.forkPrs);
|
|
1059
|
+
await confirmWrite(
|
|
1060
|
+
forkPullRequests ? `Run pull requests from forks on ${repo}? They run isolated: no org secrets, no GitHub token, and the base branch's workflow definition.` : `Refuse pull requests from forks on ${repo}? Fork pull requests stop running CI.`,
|
|
1061
|
+
opts
|
|
1062
|
+
);
|
|
1063
|
+
const result = await (await client2(opts)).patch("/api/v1/actions/repos", {
|
|
1064
|
+
fullName: repo,
|
|
1065
|
+
forkPullRequests,
|
|
1066
|
+
...repoIdBody(opts)
|
|
1067
|
+
});
|
|
1068
|
+
output2(
|
|
1069
|
+
opts,
|
|
1070
|
+
result,
|
|
1071
|
+
(r) => console.log(`fork PRs ${r.forkPullRequests === false ? "refused" : "allowed"} ${pc5.cyan(safeTerm(r.fullName))}`)
|
|
1072
|
+
);
|
|
1073
|
+
} catch (e) {
|
|
1074
|
+
fail3(e, opts);
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
common2(
|
|
1078
|
+
actions.command("branches").description("List a repo's refs: watched branches and pull requests, then refs with run history only").argument("<repo>", "repository in owner/repo format").option("--search <text>", "only refs containing this text (case-insensitive)").option("--archived", "count archived runs instead of active ones").option("--repo-id <id>", REPO_ID_HELP)
|
|
1079
|
+
).action(async (repo, opts) => {
|
|
1080
|
+
try {
|
|
1081
|
+
const data = await (await client2(opts)).get("/api/v1/actions/repos/branches", {
|
|
1082
|
+
repo,
|
|
1083
|
+
repoId: opts.repoId,
|
|
1084
|
+
q: opts.search,
|
|
1085
|
+
archived: opts.archived ? "1" : void 0
|
|
1086
|
+
});
|
|
1087
|
+
output2(opts, data, (d) => {
|
|
1088
|
+
console.log(`${pc5.bold(safeTerm(d.repo))} ${pc5.dim(`default: ${safeTerm(d.defaultBranch)}`)}`);
|
|
1089
|
+
if (d.branches.length === 0) {
|
|
1090
|
+
console.log("No branches found.");
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
const now = Date.now();
|
|
1094
|
+
for (const b of d.branches) console.log(formatBranchRow(b, now, d.defaultBranch));
|
|
1095
|
+
});
|
|
1096
|
+
} catch (e) {
|
|
1097
|
+
fail3(e, opts);
|
|
1098
|
+
}
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// src/actions-integrations.ts
|
|
1103
|
+
import pc6 from "picocolors";
|
|
1104
|
+
function formatInstallationRow(i) {
|
|
1105
|
+
const head = i.suspended ? pc6.yellow(safeTerm(i.account)) : pc6.cyan(safeTerm(i.account));
|
|
1106
|
+
const parts = [
|
|
1107
|
+
i.accountType ? safeTerm(i.accountType) : "account",
|
|
1108
|
+
i.repoSelection === "all" ? "all repos" : "selected repos",
|
|
1109
|
+
`${i.repos.granted} granted, ${i.repos.enabled} enabled`,
|
|
1110
|
+
...i.suspended ? [pc6.yellow(`suspended ${safeTerm(i.suspendedAt ?? "")}`.trim())] : [],
|
|
1111
|
+
pc6.dim(`installed ${safeTerm(i.installedAt)}`)
|
|
1112
|
+
];
|
|
1113
|
+
return `${head} ${parts.join(" ")}`;
|
|
1114
|
+
}
|
|
1115
|
+
function formatInstallations(data) {
|
|
1116
|
+
if (data.installations.length === 0) {
|
|
1117
|
+
return ["No GitHub App installations. Run `compute actions installations install-url` for where to install it."];
|
|
1118
|
+
}
|
|
1119
|
+
const lines = [];
|
|
1120
|
+
for (const i of data.installations) {
|
|
1121
|
+
lines.push(formatInstallationRow(i));
|
|
1122
|
+
if (i.configureUrl) lines.push(` ${pc6.dim(`configure: ${safeTerm(i.configureUrl)}`)}`);
|
|
1123
|
+
}
|
|
1124
|
+
return lines;
|
|
1125
|
+
}
|
|
1126
|
+
function formatSlack(s) {
|
|
1127
|
+
if (!s.installed) {
|
|
1128
|
+
return ["Slack is not connected. Run `compute actions slack install-url` for where to connect it."];
|
|
1129
|
+
}
|
|
1130
|
+
const channel = s.channelId ? `${s.channelName ? `#${safeTerm(s.channelName)} ` : ""}${pc6.dim(safeTerm(s.channelId))}` : pc6.gray("no channel picked");
|
|
1131
|
+
const brief = s.brief.enabled ? `${s.brief.times.map(safeTerm).join(", ")} ${safeTerm(s.brief.timeZone)}${s.brief.categories.length > 0 ? ` categories: ${s.brief.categories.map(safeTerm).join(", ")}` : ""}` : pc6.gray("off");
|
|
1132
|
+
return [
|
|
1133
|
+
`workspace: ${s.teamName ? safeTerm(s.teamName) : pc6.gray("(unnamed)")}`,
|
|
1134
|
+
`channel: ${channel}`,
|
|
1135
|
+
`notify on: ${s.notifyOn === "failure" ? "failures and cancels" : "every conclusion"}`,
|
|
1136
|
+
`daily brief: ${brief}`
|
|
1137
|
+
];
|
|
1138
|
+
}
|
|
1139
|
+
function formatInstallLink(link, what) {
|
|
1140
|
+
if (!link.configured || link.url === null) {
|
|
1141
|
+
return [what === "github" ? "This deployment has no GitHub App configured." : "This deployment has no Slack app configured."];
|
|
1142
|
+
}
|
|
1143
|
+
return [
|
|
1144
|
+
safeTerm(link.url),
|
|
1145
|
+
pc6.dim(
|
|
1146
|
+
what === "github" ? "Open it signed in as an org owner/admin and press Install GitHub App." : "Open it in a browser signed in as an org owner/admin; it continues to Slack."
|
|
1147
|
+
)
|
|
1148
|
+
];
|
|
1149
|
+
}
|
|
1150
|
+
function registerIntegrationsCommands(actions, common2, deps) {
|
|
1151
|
+
const { client: client2, output: output2, fail: fail3 } = deps;
|
|
1152
|
+
const print = (lines) => {
|
|
1153
|
+
for (const line of lines) console.log(line);
|
|
1154
|
+
};
|
|
1155
|
+
const installations = common2(
|
|
1156
|
+
actions.command("installations").description("List the org's GitHub App installations (account, repo selection and counts, suspension)")
|
|
1157
|
+
).action(async (opts) => {
|
|
1158
|
+
try {
|
|
1159
|
+
const data = await (await client2(opts)).get("/api/v1/actions/installations");
|
|
1160
|
+
output2(opts, data, (d) => print(formatInstallations(d)));
|
|
1161
|
+
} catch (e) {
|
|
1162
|
+
fail3(e, opts);
|
|
1163
|
+
}
|
|
1164
|
+
});
|
|
1165
|
+
common2(
|
|
1166
|
+
installations.command("install-url").description("Print where an owner/admin installs the GitHub App into another account")
|
|
1167
|
+
).action(async (opts) => {
|
|
1168
|
+
try {
|
|
1169
|
+
const data = await (await client2(opts)).get("/api/v1/actions/installations/install-url");
|
|
1170
|
+
output2(opts, data, (d) => print(formatInstallLink(d, "github")));
|
|
1171
|
+
} catch (e) {
|
|
1172
|
+
fail3(e, opts);
|
|
1173
|
+
}
|
|
1174
|
+
});
|
|
1175
|
+
const slack = common2(
|
|
1176
|
+
actions.command("slack").description("Show the org's Slack connection (workspace, channel, notify rule, daily brief; owner/admin)")
|
|
1177
|
+
).action(async (opts) => {
|
|
1178
|
+
try {
|
|
1179
|
+
const data = await (await client2(opts)).get("/api/v1/actions/slack");
|
|
1180
|
+
output2(opts, data, (d) => print(formatSlack(d)));
|
|
1181
|
+
} catch (e) {
|
|
1182
|
+
fail3(e, opts);
|
|
1183
|
+
}
|
|
1184
|
+
});
|
|
1185
|
+
common2(
|
|
1186
|
+
slack.command("install-url").description("Print where an owner/admin connects a Slack workspace")
|
|
273
1187
|
).action(async (opts) => {
|
|
274
1188
|
try {
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
const caps = {};
|
|
278
|
-
for (const entry of opts.cap) {
|
|
279
|
-
const { size, cap } = parseSizeCap(entry);
|
|
280
|
-
caps[size] = cap;
|
|
281
|
-
}
|
|
282
|
-
body.marketCaps = caps;
|
|
283
|
-
}
|
|
284
|
-
if (opts.generalCap !== void 0) {
|
|
285
|
-
body.marketCap = opts.generalCap === "none" ? null : parseMaxPrice(opts.generalCap, void 0);
|
|
286
|
-
}
|
|
287
|
-
if (opts.orderType !== void 0) {
|
|
288
|
-
if (lane === "sandboxes" && opts.orderType === "inherit") {
|
|
289
|
-
body.marketOrderType = null;
|
|
290
|
-
} else if (opts.orderType === "limit" || opts.orderType === "market") {
|
|
291
|
-
body.marketOrderType = opts.orderType;
|
|
292
|
-
} else {
|
|
293
|
-
throw new Error(
|
|
294
|
-
lane === "sandboxes" ? "--order-type must be limit, market, or inherit." : "--order-type must be limit or market."
|
|
295
|
-
);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
if (opts.order !== void 0) {
|
|
299
|
-
if (opts.order === "inherit" && lane === "sandboxes") {
|
|
300
|
-
body.providerOrder = [];
|
|
301
|
-
} else if (opts.order === "default" && lane === "actions") {
|
|
302
|
-
body.providerOrder = [];
|
|
303
|
-
} else {
|
|
304
|
-
body.providerOrder = opts.order.split(",").map((s) => s.trim()).filter(Boolean);
|
|
305
|
-
if (body.providerOrder.length === 0) {
|
|
306
|
-
throw new Error(
|
|
307
|
-
lane === "sandboxes" ? `--order "${opts.order}" names no providers \u2014 pass a comma-separated list or "inherit".` : `--order "${opts.order}" names no providers \u2014 pass a comma-separated list or "default".`
|
|
308
|
-
);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
if (Object.keys(body).length === 0) {
|
|
313
|
-
throw new Error(
|
|
314
|
-
"Nothing to change \u2014 pass --cap, --general-cap, --order-type, or --order."
|
|
315
|
-
);
|
|
316
|
-
}
|
|
317
|
-
const c = await deps.client(opts);
|
|
318
|
-
const res = await c.patch(`/api/v1/${lane}/settings`, body);
|
|
319
|
-
deps.output(opts, res, (s) => printLaneSettings(s, lane));
|
|
1189
|
+
const data = await (await client2(opts)).get("/api/v1/actions/slack/install-url");
|
|
1190
|
+
output2(opts, data, (d) => print(formatInstallLink(d, "slack")));
|
|
320
1191
|
} catch (e) {
|
|
321
|
-
|
|
1192
|
+
fail3(e, opts);
|
|
322
1193
|
}
|
|
323
1194
|
});
|
|
324
1195
|
}
|
|
@@ -373,7 +1244,7 @@ function formatSchedule(data, nextCommand) {
|
|
|
373
1244
|
hourCycle: "h23",
|
|
374
1245
|
timeZoneName: "short"
|
|
375
1246
|
});
|
|
376
|
-
const lines = [
|
|
1247
|
+
const lines = [pc7.bold(`Upcoming fires (${safeTerm(data.timeZone)})`)];
|
|
377
1248
|
const fires = data.upcoming.flatMap((schedule) => schedule.occurrences.map((at) => ({ at, schedule }))).sort((a, b) => a.at.localeCompare(b.at));
|
|
378
1249
|
if (fires.length === 0) lines.push("No upcoming fires.");
|
|
379
1250
|
for (const { at, schedule } of fires) {
|
|
@@ -383,7 +1254,7 @@ function formatSchedule(data, nextCommand) {
|
|
|
383
1254
|
const remaining = schedule.occurrenceCount - schedule.occurrences.length;
|
|
384
1255
|
if (remaining > 0) lines.push(`+${remaining.toLocaleString("en-US")} more scheduled for ${safeTerm(schedule.workflowName || schedule.workflowPath)} ${safeTerm(schedule.repoFullName)} ${safeTerm(schedule.description)}`);
|
|
385
1256
|
}
|
|
386
|
-
lines.push("",
|
|
1257
|
+
lines.push("", pc7.bold(`Past runs (${safeTerm(data.timeZone)})`));
|
|
387
1258
|
if (data.runs.length === 0) lines.push("No past runs found.");
|
|
388
1259
|
for (const run of data.runs) {
|
|
389
1260
|
lines.push([
|
|
@@ -455,7 +1326,7 @@ async function fetchRunSummary(c, runId) {
|
|
|
455
1326
|
} catch (e) {
|
|
456
1327
|
if (!(e instanceof PlatformApiError && e.status === 404)) {
|
|
457
1328
|
console.error(
|
|
458
|
-
|
|
1329
|
+
pc7.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`)
|
|
459
1330
|
);
|
|
460
1331
|
}
|
|
461
1332
|
return null;
|
|
@@ -465,9 +1336,9 @@ function fail(error, opts = {}) {
|
|
|
465
1336
|
if (opts.json) {
|
|
466
1337
|
process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + "\n");
|
|
467
1338
|
} else if (error instanceof PlatformApiError) {
|
|
468
|
-
console.error(
|
|
1339
|
+
console.error(pc7.red(`Error (${error.status}): ${safeTermText(error.message)}`));
|
|
469
1340
|
} else {
|
|
470
|
-
console.error(
|
|
1341
|
+
console.error(pc7.red(`Error: ${safeTermText(error instanceof Error ? error.message : String(error))}`));
|
|
471
1342
|
}
|
|
472
1343
|
process.exit(1);
|
|
473
1344
|
}
|
|
@@ -492,39 +1363,24 @@ function formatDuration(ms) {
|
|
|
492
1363
|
function shortSha(sha) {
|
|
493
1364
|
return sha.slice(0, 8);
|
|
494
1365
|
}
|
|
495
|
-
function conclusionLabel(conclusion) {
|
|
496
|
-
switch (conclusion) {
|
|
497
|
-
case "passed":
|
|
498
|
-
return pc2.green("passed");
|
|
499
|
-
case "failed":
|
|
500
|
-
return pc2.red("failed");
|
|
501
|
-
case "running":
|
|
502
|
-
return pc2.yellow("running");
|
|
503
|
-
case "cancelled":
|
|
504
|
-
return pc2.gray("cancelled");
|
|
505
|
-
case "none":
|
|
506
|
-
return pc2.yellow("queued");
|
|
507
|
-
default:
|
|
508
|
-
return conclusion;
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
1366
|
function formatRunRow(run) {
|
|
512
1367
|
const num = run.runNumber === null ? "-" : `#${run.runNumber}`;
|
|
513
1368
|
return [
|
|
514
1369
|
run.id,
|
|
515
|
-
|
|
1370
|
+
pc7.dim(num),
|
|
516
1371
|
run.workflowName || run.workflowPath,
|
|
517
1372
|
conclusionLabel(run.conclusion),
|
|
518
|
-
|
|
1373
|
+
pc7.dim(`${run.repoFullName}@${run.ref}`),
|
|
519
1374
|
shortSha(run.headSha),
|
|
520
1375
|
formatDuration(run.durationMs),
|
|
521
|
-
run.startedAt
|
|
1376
|
+
run.startedAt,
|
|
1377
|
+
...run.archivedAt ? [pc7.dim("archived")] : []
|
|
522
1378
|
].join(" ");
|
|
523
1379
|
}
|
|
524
1380
|
function formatRunDetail(run, runUrl) {
|
|
525
1381
|
const lines = [];
|
|
526
|
-
lines.push(`${
|
|
527
|
-
lines.push(
|
|
1382
|
+
lines.push(`${pc7.bold(run.workflowName || run.workflowPath)} ${conclusionLabel(run.conclusion)}`);
|
|
1383
|
+
lines.push(pc7.dim(`run ${run.id}${run.runNumber === null ? "" : ` #${run.runNumber}`}`));
|
|
528
1384
|
lines.push(`${run.repoFullName} @ ${run.ref} ${shortSha(run.headSha)} ${run.event}${run.prNumber ? ` PR #${run.prNumber}` : ""}`);
|
|
529
1385
|
lines.push(`title: ${run.title}`);
|
|
530
1386
|
lines.push(`started: ${run.startedAt} duration: ${formatDuration(run.durationMs)}`);
|
|
@@ -535,16 +1391,16 @@ function formatRunDetail(run, runUrl) {
|
|
|
535
1391
|
if (run.benchmarks && run.benchmarks.length > 0) lines.push(`benchmarks: ${resultsSummary(run.benchmarks)}`);
|
|
536
1392
|
if (run.jobs.length > 0) {
|
|
537
1393
|
lines.push("");
|
|
538
|
-
lines.push(
|
|
1394
|
+
lines.push(pc7.bold("jobs"));
|
|
539
1395
|
for (const job of run.jobs) {
|
|
540
1396
|
const placement = job.provider ? `${job.provider}${job.region ? `:${job.region}` : ""}` : "-";
|
|
541
1397
|
lines.push(` ${job.id} ${job.name} ${conclusionLabel(job.state)} ${placement} ${formatDuration(job.durationMs)}`);
|
|
542
1398
|
for (const attempt of job.placementAttempts) {
|
|
543
|
-
lines.push(
|
|
1399
|
+
lines.push(pc7.dim(` placement failed on ${attempt.provider}${attempt.region ? `:${attempt.region}` : ""}: ${attempt.error}`));
|
|
544
1400
|
}
|
|
545
1401
|
for (const step of job.steps) {
|
|
546
1402
|
const exit = step.exitCode === null ? "" : ` (exit ${step.exitCode})`;
|
|
547
|
-
lines.push(
|
|
1403
|
+
lines.push(pc7.dim(` ${step.name} ${step.state}${exit} ${formatDuration(step.durationMs)}`));
|
|
548
1404
|
}
|
|
549
1405
|
}
|
|
550
1406
|
}
|
|
@@ -580,22 +1436,22 @@ function formatRate(n) {
|
|
|
580
1436
|
return n === null ? "-" : `${Math.round(n * 100)}%`;
|
|
581
1437
|
}
|
|
582
1438
|
function formatRunResults(results) {
|
|
583
|
-
if (results.length === 0) return
|
|
1439
|
+
if (results.length === 0) return pc7.dim("no benchmark results on this run");
|
|
584
1440
|
const lines = [];
|
|
585
1441
|
for (const [i, result] of results.entries()) {
|
|
586
1442
|
if (i > 0) lines.push("");
|
|
587
|
-
lines.push(`${
|
|
588
|
-
lines.push(
|
|
1443
|
+
lines.push(`${pc7.bold(safeTerm(result.benchmarkName))} ${safeTerm(result.status)}`);
|
|
1444
|
+
lines.push(pc7.dim(`${safeTerm(result.benchmarkRunId)} ${safeTerm(result.dashboardUrl)}`));
|
|
589
1445
|
const rows = [...overallRows(result)].sort((a, b) => (b.compositeScore ?? -1) - (a.compositeScore ?? -1));
|
|
590
1446
|
if (rows.length === 0) {
|
|
591
|
-
lines.push(
|
|
1447
|
+
lines.push(pc7.dim(result.status === "failed" ? " failed before reporting results" : " no results yet"));
|
|
592
1448
|
continue;
|
|
593
1449
|
}
|
|
594
1450
|
const width = Math.max(8, ...rows.map((p2) => p2.provider.length));
|
|
595
|
-
lines.push(
|
|
1451
|
+
lines.push(pc7.dim(` ${"provider".padEnd(width)} ${"score".padStart(7)} ${"success".padStart(7)} metrics`));
|
|
596
1452
|
for (const p2 of rows) {
|
|
597
1453
|
const metrics = Object.entries(p2.metrics).map(([name, m]) => `${safeTerm(name)} ${formatMetric(m.median)}${m.unit ? safeTerm(m.unit) : ""}`).join(" ");
|
|
598
|
-
const status = p2.skipped ?
|
|
1454
|
+
const status = p2.skipped ? pc7.dim(`skipped${p2.skipReason ? `: ${safeTerm(p2.skipReason)}` : ""}`) : metrics;
|
|
599
1455
|
lines.push(` ${safeTerm(p2.provider).padEnd(width)} ${formatScore(p2.compositeScore).padStart(7)} ${formatRate(p2.successRate).padStart(7)} ${status}`);
|
|
600
1456
|
}
|
|
601
1457
|
}
|
|
@@ -603,18 +1459,18 @@ function formatRunResults(results) {
|
|
|
603
1459
|
}
|
|
604
1460
|
function formatRunInspection(run) {
|
|
605
1461
|
const lines = [];
|
|
606
|
-
lines.push(`${
|
|
607
|
-
lines.push(
|
|
1462
|
+
lines.push(`${pc7.bold("run")} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? "" : ` #${run.runNumber}`}`);
|
|
1463
|
+
lines.push(pc7.dim(run.id));
|
|
608
1464
|
lines.push(`${safeTerm(run.ref)} ${shortSha(run.headSha)} ${safeTerm(run.event)}`);
|
|
609
1465
|
lines.push(`queued: ${run.queuedAt} started: ${run.startedAt} finished: ${run.finishedAt}`);
|
|
610
1466
|
if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);
|
|
611
1467
|
if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);
|
|
612
|
-
if (run.blockedReason) lines.push(
|
|
1468
|
+
if (run.blockedReason) lines.push(pc7.red(`blocked: ${safeTerm(run.blockedReason)}`));
|
|
613
1469
|
if (run.concurrencyGroup) lines.push(`concurrency: ${safeTerm(run.concurrencyGroup)}`);
|
|
614
1470
|
if (run.providerOverride) lines.push(`dispatched to: ${safeTerm(run.providerOverride)}`);
|
|
615
1471
|
if (run.definitionStale) {
|
|
616
1472
|
const parsed = run.workflowParsedFromSha ? shortSha(run.workflowParsedFromSha) : "unknown";
|
|
617
|
-
lines.push(
|
|
1473
|
+
lines.push(pc7.yellow(`definition: stored parse is from ${parsed}, not this head \u2014 context may be newer than the run`));
|
|
618
1474
|
}
|
|
619
1475
|
if (run.dispatchInputs && Object.keys(run.dispatchInputs).length > 0) {
|
|
620
1476
|
lines.push(`inputs: ${Object.entries(run.dispatchInputs).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(" ")}`);
|
|
@@ -625,24 +1481,24 @@ function formatRunInspection(run) {
|
|
|
625
1481
|
}
|
|
626
1482
|
if (run.caches.length > 0) {
|
|
627
1483
|
lines.push("");
|
|
628
|
-
lines.push(
|
|
1484
|
+
lines.push(pc7.bold("caches"));
|
|
629
1485
|
for (const cache of run.caches) {
|
|
630
1486
|
const action = [cache.restoredAt ? "restored" : null, cache.savedAt ? "saved" : null].filter(Boolean).join("+");
|
|
631
|
-
lines.push(` ${safeTerm(cache.key)} ${
|
|
1487
|
+
lines.push(` ${safeTerm(cache.key)} ${pc7.dim(`${action} ${safeTerm(cache.scopeRef)} ${cache.sizeBytes}B`)}`);
|
|
632
1488
|
}
|
|
633
1489
|
}
|
|
634
1490
|
if (run.jobs.length > 0) {
|
|
635
1491
|
lines.push("");
|
|
636
|
-
lines.push(
|
|
1492
|
+
lines.push(pc7.bold("jobs"));
|
|
637
1493
|
for (const job of run.jobs) {
|
|
638
1494
|
const placement = job.provider ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ""}` : "-";
|
|
639
1495
|
lines.push(` ${safeTerm(job.name)} ${conclusionLabel(job.state)} ${placement}`);
|
|
640
|
-
lines.push(
|
|
1496
|
+
lines.push(pc7.dim(` ${job.id}`));
|
|
641
1497
|
if (job.runsOn.length > 0 || job.resolvedRunsOn !== null) {
|
|
642
1498
|
const resolved = job.resolvedRunsOn !== null && job.resolvedRunsOn.join(",") !== job.runsOn.join(",") ? ` \u2192 ${job.resolvedRunsOn.map(safeTerm).join(", ")}` : "";
|
|
643
1499
|
lines.push(` runs-on: ${job.runsOn.map(safeTerm).join(", ") || "(none)"}${resolved}`);
|
|
644
1500
|
}
|
|
645
|
-
if (job.runsOnHasExpression) lines.push(
|
|
1501
|
+
if (job.runsOnHasExpression) lines.push(pc7.dim(" runs-on resolves at runtime (expression)"));
|
|
646
1502
|
if (job.container) lines.push(` container: ${safeTerm(job.container)}`);
|
|
647
1503
|
if (job.runnerImage) lines.push(` image: ${safeTerm(job.runnerImage)}`);
|
|
648
1504
|
if (job.placementHint) {
|
|
@@ -659,9 +1515,9 @@ function formatRunInspection(run) {
|
|
|
659
1515
|
if (job.matrix) {
|
|
660
1516
|
lines.push(` matrix: ${Object.entries(job.matrix).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(" ")}`);
|
|
661
1517
|
}
|
|
662
|
-
if (job.failureReason) lines.push(
|
|
1518
|
+
if (job.failureReason) lines.push(pc7.red(` failed: ${safeTerm(job.failureReason)}`));
|
|
663
1519
|
for (const attempt of job.placementAttempts) {
|
|
664
|
-
lines.push(
|
|
1520
|
+
lines.push(pc7.dim(` placement failed on ${safeTerm(attempt.provider)}${attempt.region ? `:${safeTerm(attempt.region)}` : ""}: ${safeTerm(attempt.error)}`));
|
|
665
1521
|
}
|
|
666
1522
|
}
|
|
667
1523
|
}
|
|
@@ -669,7 +1525,7 @@ function formatRunInspection(run) {
|
|
|
669
1525
|
}
|
|
670
1526
|
function formatRunSummary(summary) {
|
|
671
1527
|
const lines = [];
|
|
672
|
-
lines.push(
|
|
1528
|
+
lines.push(pc7.bold(`failures \u2014 run ${summary.runId} ${conclusionLabel(summary.conclusion)}`));
|
|
673
1529
|
if (summary.failures.length === 0) {
|
|
674
1530
|
lines.push(" no failed jobs");
|
|
675
1531
|
return lines.join("\n");
|
|
@@ -677,7 +1533,7 @@ function formatRunSummary(summary) {
|
|
|
677
1533
|
for (const job of summary.failures) {
|
|
678
1534
|
const placement = job.provider ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ""}` : "-";
|
|
679
1535
|
lines.push(` ${job.id} ${safeTerm(job.name)} ${conclusionLabel(job.conclusion)} ${placement}`);
|
|
680
|
-
if (job.failureReason) lines.push(
|
|
1536
|
+
if (job.failureReason) lines.push(pc7.dim(` ${safeTerm(job.failureReason)}`));
|
|
681
1537
|
for (const step of job.failedSteps) {
|
|
682
1538
|
const exit = step.exitCode === null ? "" : ` (exit ${step.exitCode})`;
|
|
683
1539
|
lines.push(` step ${step.ordinal} ${safeTerm(step.name)}${exit}`);
|
|
@@ -685,7 +1541,7 @@ function formatRunSummary(summary) {
|
|
|
685
1541
|
if (job.excerpt) {
|
|
686
1542
|
const scope = job.excerpt.stepOrdinal === null ? "job log" : `step ${job.excerpt.stepOrdinal}`;
|
|
687
1543
|
const cut = job.excerpt.truncated ? ", truncated" : "";
|
|
688
|
-
lines.push(
|
|
1544
|
+
lines.push(pc7.dim(` \u2500\u2500 ${scope} tail${cut} \u2500\u2500`));
|
|
689
1545
|
for (const line of job.excerpt.text.split("\n")) lines.push(` ${safeTerm(line)}`);
|
|
690
1546
|
}
|
|
691
1547
|
}
|
|
@@ -778,24 +1634,21 @@ async function* followRunLogs(client2, runId, jobs, step) {
|
|
|
778
1634
|
await new Promise((r) => setTimeout(r, 1e3));
|
|
779
1635
|
}
|
|
780
1636
|
}
|
|
781
|
-
function safeTerm(s) {
|
|
782
|
-
return s.replace(/[\u0000-\u001F\u007F-\u009F]/g, "\uFFFD");
|
|
783
|
-
}
|
|
784
1637
|
function formatRunHistory(history) {
|
|
785
1638
|
const lines = [];
|
|
786
1639
|
const parts = Object.entries(history.conclusions).map(([c, n]) => `${n} ${c}`).join(", ");
|
|
787
1640
|
lines.push(`last ${history.runCount} runs: ${parts || "none"}`);
|
|
788
1641
|
if (history.jobs.length > 0) {
|
|
789
1642
|
lines.push("");
|
|
790
|
-
lines.push(
|
|
1643
|
+
lines.push(pc7.bold("jobs"));
|
|
791
1644
|
for (const job of history.jobs) {
|
|
792
1645
|
const rate = job.runs > 0 ? Math.round(job.failedRuns / job.runs * 100) : 0;
|
|
793
|
-
const platform = job.failedBeforeSteps > 0 ?
|
|
1646
|
+
const platform = job.failedBeforeSteps > 0 ? pc7.dim(` (${job.failedBeforeSteps} failed before steps)`) : "";
|
|
794
1647
|
const count = `${job.failedRuns}/${job.runs} runs failed`;
|
|
795
|
-
const label = job.failedRuns > 0 ?
|
|
1648
|
+
const label = job.failedRuns > 0 ? pc7.red(count) : pc7.green(count);
|
|
796
1649
|
lines.push(` ${safeTerm(job.job)} ${label} ${rate}%${platform}`);
|
|
797
1650
|
for (const step of job.steps) {
|
|
798
|
-
lines.push(
|
|
1651
|
+
lines.push(pc7.dim(` step "${safeTerm(step.step)}" failed in ${step.failedRuns} run${step.failedRuns === 1 ? "" : "s"}`));
|
|
799
1652
|
}
|
|
800
1653
|
}
|
|
801
1654
|
}
|
|
@@ -804,46 +1657,39 @@ function formatRunHistory(history) {
|
|
|
804
1657
|
);
|
|
805
1658
|
if (failed.length > 0) {
|
|
806
1659
|
lines.push("");
|
|
807
|
-
lines.push(
|
|
1660
|
+
lines.push(pc7.bold("failed runs"));
|
|
808
1661
|
for (const run of failed) {
|
|
809
|
-
const blame = run.failedJobs.length > 0 ? run.failedJobs.map((j) => safeTerm(j.step === null ? j.job : `${j.job}:${j.step}`)).join(", ") :
|
|
810
|
-
lines.push(` ${shortSha(run.headSha)} ${
|
|
1662
|
+
const blame = run.failedJobs.length > 0 ? run.failedJobs.map((j) => safeTerm(j.step === null ? j.job : `${j.job}:${j.step}`)).join(", ") : pc7.dim("(no failed job recorded)");
|
|
1663
|
+
lines.push(` ${shortSha(run.headSha)} ${pc7.dim(run.startedAt)} ${blame}`);
|
|
811
1664
|
}
|
|
812
1665
|
}
|
|
813
1666
|
return lines.join("\n");
|
|
814
1667
|
}
|
|
1668
|
+
function keyStatusText(p2) {
|
|
1669
|
+
const status = p2.status === "connected" ? pc7.green("connected") : p2.status === "error" ? pc7.red("error") : pc7.gray("unconfigured");
|
|
1670
|
+
const hint = p2.keyHint ? ` ${pc7.dim(safeTerm(p2.keyHint))}` : "";
|
|
1671
|
+
const detail = p2.status === "error" && p2.statusDetail ? ` ${pc7.dim(`(${safeTerm(p2.statusDetail)})`)}` : "";
|
|
1672
|
+
return `${status}${hint}${detail}`;
|
|
1673
|
+
}
|
|
815
1674
|
function formatProviderRow(p2) {
|
|
816
|
-
const icon = p2.usable ?
|
|
817
|
-
const name = p2.usable ?
|
|
1675
|
+
const icon = p2.usable ? pc7.green("\u25CF") : pc7.gray("\u25CB");
|
|
1676
|
+
const name = p2.usable ? pc7.white(p2.provider) : pc7.gray(p2.provider);
|
|
818
1677
|
const flags = [
|
|
819
1678
|
p2.credential,
|
|
820
|
-
p2.actCapable ?
|
|
1679
|
+
p2.actCapable ? pc7.green("act") : pc7.gray("no-act"),
|
|
821
1680
|
p2.regions.length > 0 ? `regions: ${p2.regions.join(",")}` : "no region choice",
|
|
822
|
-
p2.position === null ?
|
|
1681
|
+
p2.position === null ? pc7.gray("not in provider order") : `order #${p2.position}`,
|
|
1682
|
+
...p2.credential !== "ambient" && p2.status !== void 0 ? [keyStatusText(p2)] : []
|
|
823
1683
|
].join(" ");
|
|
824
1684
|
return ` ${icon} ${name} ${flags}`;
|
|
825
1685
|
}
|
|
826
1686
|
function formatVerifyResult(r) {
|
|
827
1687
|
const ok = r.verified === true;
|
|
828
|
-
const head = ok ?
|
|
829
|
-
const detail = r.key.statusDetail ?
|
|
830
|
-
const act = r.key.actCapable ?
|
|
1688
|
+
const head = ok ? pc7.green("verified") : pc7.red("not verified");
|
|
1689
|
+
const detail = r.key.statusDetail ? pc7.dim(` ${r.key.statusDetail}`) : "";
|
|
1690
|
+
const act = r.key.actCapable ? pc7.green(" act-capable") : "";
|
|
831
1691
|
return `${head} ${r.key.provider}${act}${detail}`;
|
|
832
1692
|
}
|
|
833
|
-
function formatRepoRow(r) {
|
|
834
|
-
const head = r.enabled ? pc2.green("enabled") : pc2.dim("disabled");
|
|
835
|
-
const via = r.authType === "github_app" ? "github-app" : r.authType;
|
|
836
|
-
const workflows = r.workflowPaths.length > 0 ? `${r.workflowPaths.length} workflow${r.workflowPaths.length === 1 ? "" : "s"}` : "no workflows yet";
|
|
837
|
-
const error = r.lastPollError ? pc2.red(` poll error: ${safeTerm(r.lastPollError)}`) : "";
|
|
838
|
-
return `${head} ${safeTerm(r.fullName)} ${pc2.dim(`${safeTerm(via)} \xB7 ${safeTerm(r.defaultBranch)} \xB7 ${workflows}`)}${error}`;
|
|
839
|
-
}
|
|
840
|
-
function printDiscovery(d) {
|
|
841
|
-
if (d.error) {
|
|
842
|
-
console.log(pc2.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));
|
|
843
|
-
return;
|
|
844
|
-
}
|
|
845
|
-
console.log(pc2.dim(`discovery: ${d.workflowsFound ? "workflows found" : "no workflows yet"}${d.seeded ? ", cursors seeded" : ""}`));
|
|
846
|
-
}
|
|
847
1693
|
function isPatchedWorkflowTarget(target) {
|
|
848
1694
|
return "workflowPath" in target;
|
|
849
1695
|
}
|
|
@@ -857,16 +1703,18 @@ function patchTouches(patch, path2) {
|
|
|
857
1703
|
}
|
|
858
1704
|
function dispatchBody(workflow, opts) {
|
|
859
1705
|
const patched = isPatchedWorkflowTarget(workflow);
|
|
860
|
-
|
|
1706
|
+
const path2 = patched ? workflow.workflowPath : workflow.path;
|
|
1707
|
+
const pushOnly = workflow.dispatchable === false;
|
|
1708
|
+
if (pushOnly && !opts.manual) {
|
|
861
1709
|
throw new PlatformClientError(
|
|
862
1710
|
"invalid_argument",
|
|
863
|
-
`Workflow "${
|
|
1711
|
+
`Workflow "${path2}" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`
|
|
864
1712
|
);
|
|
865
1713
|
}
|
|
866
|
-
if (
|
|
1714
|
+
if (pushOnly && opts.inputs !== void 0 && opts.inputs.length > 0) {
|
|
867
1715
|
throw new PlatformClientError(
|
|
868
1716
|
"invalid_argument",
|
|
869
|
-
`Workflow "${
|
|
1717
|
+
`Workflow "${path2}" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`
|
|
870
1718
|
);
|
|
871
1719
|
}
|
|
872
1720
|
const ref = opts.ref ?? (patched ? void 0 : workflow.refs[0]);
|
|
@@ -1030,13 +1878,13 @@ function formatVaultRow(item) {
|
|
|
1030
1878
|
...item.source === "organization" ? ["inherited"] : [],
|
|
1031
1879
|
...item.overridesOrganization ? ["overrides org"] : []
|
|
1032
1880
|
];
|
|
1033
|
-
return `${
|
|
1881
|
+
return `${pc7.cyan(safeTerm(item.name))} ${pc7.dim(flags.join(", "))} ${pc7.dim(`updated ${safeTerm(item.updatedAt)}`)}`;
|
|
1034
1882
|
}
|
|
1035
1883
|
function registerActionsCommands(program2) {
|
|
1036
1884
|
const actions = program2.command("actions").alias("ci").description("Drive the benchmarks-platform Actions API").configureOutput({ outputError: usageErrorOutput });
|
|
1037
|
-
const
|
|
1038
|
-
|
|
1039
|
-
actions.command("dispatch").description("Dispatch a workflow_dispatch run (or any workflow with --manual)").argument("<repo>", "repository in owner/repo format").requiredOption("--workflow <path|name>", "workflow path or name").option("--ref <ref>", "git ref to run (default: the workflow's first watched ref)").option("--inputs <pairs...>", "workflow inputs as key=value (workflow_dispatch inputs only)").option("--manual", "run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)").option("--provider <id>", "place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order").option("--provider-region <region>", "region for --provider (same as --provider <id>:<region>)").option("--max-bid <usd>", "max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider").option("--max-bid-per <unit>", "time unit --max-bid is priced in: second, minute, or hour (default: second)").option("--with-changes", "run your local changes: everything the working tree has beyond origin/<ref> is sent as a diff and applied after checkout (default --ref: the current branch)")
|
|
1885
|
+
const common2 = (cmd) => cmd.option("--api-key <key>", "API key (default: $COMPUTE_API_KEY)").option("--base-url <url>", "API base URL (default: https://platform.computesdk.com)").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)").option("--json", "print machine-readable JSON");
|
|
1886
|
+
common2(
|
|
1887
|
+
actions.command("dispatch").description("Dispatch a workflow_dispatch run (or any workflow with --manual)").argument("<repo>", "repository in owner/repo format").requiredOption("--workflow <path|name>", "workflow path or name").option("--ref <ref>", "git ref to run (default: the workflow's first watched ref); also finds a workflow file only this ref has").option("--inputs <pairs...>", "workflow inputs as key=value (workflow_dispatch inputs only)").option("--manual", "run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)").option("--provider <id>", "place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order").option("--provider-region <region>", "region for --provider (same as --provider <id>:<region>)").option("--max-bid <usd>", "max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider").option("--max-bid-per <unit>", "time unit --max-bid is priced in: second, minute, or hour (default: second)").option("--with-changes", "run your local changes: everything the working tree has beyond origin/<ref> is sent as a diff and applied after checkout (default --ref: the current branch)")
|
|
1040
1888
|
).action(async (repo, opts) => {
|
|
1041
1889
|
try {
|
|
1042
1890
|
const c = await client(opts);
|
|
@@ -1047,15 +1895,21 @@ function registerActionsCommands(program2) {
|
|
|
1047
1895
|
if (!ref) throw new PlatformClientError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
|
|
1048
1896
|
local = localChangesPatch(ref, void 0, repo);
|
|
1049
1897
|
} else if (!opts.json && hasLocalChanges()) {
|
|
1050
|
-
console.error(
|
|
1898
|
+
console.error(pc7.dim("You have uncommitted changes. Add --with-changes to run them."));
|
|
1051
1899
|
}
|
|
1052
1900
|
const { workflows } = await c.get(
|
|
1053
1901
|
"/api/v1/actions/workflows",
|
|
1054
1902
|
{ repo }
|
|
1055
1903
|
);
|
|
1056
|
-
|
|
1904
|
+
let workflow = matchWorkflow(workflows, opts.workflow) ?? (local && patchTouches(local.patch, opts.workflow) ? { repoFullName: repo, workflowPath: opts.workflow } : void 0);
|
|
1905
|
+
let refOnly;
|
|
1906
|
+
if (!workflow && ref !== void 0) {
|
|
1907
|
+
refOnly = (await c.get("/api/v1/actions/workflows", { repo, ref })).refOnly ?? [];
|
|
1908
|
+
const match = matchRefOnly(refOnly, opts.workflow);
|
|
1909
|
+
if (match) workflow = { repoFullName: repo, workflowPath: match.path, dispatchable: match.dispatchable };
|
|
1910
|
+
}
|
|
1057
1911
|
if (!workflow) {
|
|
1058
|
-
const choices = workflows
|
|
1912
|
+
const choices = workflowChoices(workflows) + (refOnly && refOnly.length > 0 ? `; only on ${ref}: ${workflowChoices(refOnly)}` : "");
|
|
1059
1913
|
const hint = !opts.withChanges && hasLocalChanges() && /^\.github\/workflows\//.test(opts.workflow) ? " If it only exists in your working tree, add --with-changes." : "";
|
|
1060
1914
|
throw new PlatformClientError(
|
|
1061
1915
|
"workflow_not_found",
|
|
@@ -1071,7 +1925,7 @@ function registerActionsCommands(program2) {
|
|
|
1071
1925
|
);
|
|
1072
1926
|
patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };
|
|
1073
1927
|
} else if (opts.withChanges && !opts.json && ref) {
|
|
1074
|
-
console.error(
|
|
1928
|
+
console.error(pc7.dim(`no local changes beyond origin/${ref.replace(/^refs\/heads\//, "")}; running the ref as is`));
|
|
1075
1929
|
}
|
|
1076
1930
|
const body = dispatchBody(workflow, { ...opts, ref, patchId: patch?.patchId });
|
|
1077
1931
|
const result = await c.post(
|
|
@@ -1081,7 +1935,7 @@ function registerActionsCommands(program2) {
|
|
|
1081
1935
|
const org2 = await c.org();
|
|
1082
1936
|
const url = `${c.baseUrl}/${org2.slug}/actions/runs/${result.runId}`;
|
|
1083
1937
|
output(opts, { ...result, url, ...patch && { patch } }, (r) => {
|
|
1084
|
-
console.log(`${r.created ? "dispatched" : "already running"} ${
|
|
1938
|
+
console.log(`${r.created ? "dispatched" : "already running"} ${pc7.cyan(r.runId)}`);
|
|
1085
1939
|
console.log(`sha: ${r.headSha}${r.patch ? ` + ${r.patch.files} changed file${r.patch.files === 1 ? "" : "s"} (uncommitted)` : ""}`);
|
|
1086
1940
|
console.log(`url: ${r.url}`);
|
|
1087
1941
|
});
|
|
@@ -1089,26 +1943,9 @@ function registerActionsCommands(program2) {
|
|
|
1089
1943
|
fail(e, opts);
|
|
1090
1944
|
}
|
|
1091
1945
|
});
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
try {
|
|
1096
|
-
const { runs } = await (await client(opts)).get(
|
|
1097
|
-
"/api/v1/actions/runs",
|
|
1098
|
-
{ repo, status: opts.status, branch: opts.branch }
|
|
1099
|
-
);
|
|
1100
|
-
output(opts, runs, (rs) => {
|
|
1101
|
-
if (rs.length === 0) {
|
|
1102
|
-
console.log("No runs found.");
|
|
1103
|
-
return;
|
|
1104
|
-
}
|
|
1105
|
-
for (const run of rs) console.log(formatRunRow(run));
|
|
1106
|
-
});
|
|
1107
|
-
} catch (e) {
|
|
1108
|
-
fail(e, opts);
|
|
1109
|
-
}
|
|
1110
|
-
});
|
|
1111
|
-
common(
|
|
1946
|
+
registerRunsCommands(actions, common2, { client, fail, output, formatRunRow });
|
|
1947
|
+
registerWorkflowsCommands(actions, common2, { client, fail, output });
|
|
1948
|
+
common2(
|
|
1112
1949
|
actions.command("schedule").description("List upcoming scheduled fires and past runs in a time window").option("--reliability", "show only reliability runs and workflows (hidden by default)").option("--from <timestamp>", "inclusive start timestamp (default: now)").option("--to <timestamp>", "exclusive end timestamp (default: seven days after --from)").option("--repo <repo>", "repository in owner/repo format").option("--workflow <path...>", "workflow file paths; repeatable").option("--event <event...>", "trigger events: schedule, push, pull_request, workflow_dispatch").option("--status <status...>", "run conclusions: passed, failed, running, cancelled, none (excludes upcoming)").option("--tz <zone>", "IANA time zone (default: local)").option("--limit <n>", "past-run page size (default 100, max 500)").option("--cursor <cursor>", "nextCursor from a prior page; keep the window and filters unchanged")
|
|
1113
1950
|
).action(async (opts) => {
|
|
1114
1951
|
opts.org ?? (opts.org = program2.opts().org);
|
|
@@ -1120,7 +1957,7 @@ function registerActionsCommands(program2) {
|
|
|
1120
1957
|
fail(e, opts);
|
|
1121
1958
|
}
|
|
1122
1959
|
});
|
|
1123
|
-
|
|
1960
|
+
common2(
|
|
1124
1961
|
actions.command("history").description("Recent run history for a workflow \u2014 per-job/step failure rates (is this failure flaky?)").argument("<repo>", "repository in owner/repo format").requiredOption("--workflow <path|name>", "workflow path or name").option("--branch <branch...>", "narrow the window to branches/refs").option("--job <job>", "narrow the rollup to one job name or workflow job id").option("--limit <n>", "runs in the window (default 10, max 50)")
|
|
1125
1962
|
).action(async (repo, opts) => {
|
|
1126
1963
|
try {
|
|
@@ -1143,7 +1980,7 @@ function registerActionsCommands(program2) {
|
|
|
1143
1980
|
fail(e, opts);
|
|
1144
1981
|
}
|
|
1145
1982
|
});
|
|
1146
|
-
|
|
1983
|
+
common2(
|
|
1147
1984
|
actions.command("run").description("Show a run: jobs, provider:region placement, placement attempts").argument("<run-id>", "run ID")
|
|
1148
1985
|
).action(async (runId, opts) => {
|
|
1149
1986
|
try {
|
|
@@ -1163,7 +2000,7 @@ function registerActionsCommands(program2) {
|
|
|
1163
2000
|
fail(e, opts);
|
|
1164
2001
|
}
|
|
1165
2002
|
});
|
|
1166
|
-
|
|
2003
|
+
common2(
|
|
1167
2004
|
actions.command("summary").description("Show a run's failure digest: failed jobs, failed steps, bounded log tails").argument("<run-id>", "run ID")
|
|
1168
2005
|
).action(async (runId, opts) => {
|
|
1169
2006
|
try {
|
|
@@ -1173,7 +2010,7 @@ function registerActionsCommands(program2) {
|
|
|
1173
2010
|
fail(e, opts);
|
|
1174
2011
|
}
|
|
1175
2012
|
});
|
|
1176
|
-
|
|
2013
|
+
common2(
|
|
1177
2014
|
actions.command("benchmarks").description("Show the benchmark runs this run produced: per-provider score and success rate").argument("<run-id>", "run ID")
|
|
1178
2015
|
).action(async (runId, opts) => {
|
|
1179
2016
|
try {
|
|
@@ -1184,7 +2021,7 @@ function registerActionsCommands(program2) {
|
|
|
1184
2021
|
fail(e, opts);
|
|
1185
2022
|
}
|
|
1186
2023
|
});
|
|
1187
|
-
|
|
2024
|
+
common2(
|
|
1188
2025
|
actions.command("inspect").description("Inspect a run: resolved runner image, caches, secret names, concurrency, placement context").argument("<run-id>", "run ID")
|
|
1189
2026
|
).action(async (runId, opts) => {
|
|
1190
2027
|
try {
|
|
@@ -1197,7 +2034,7 @@ function registerActionsCommands(program2) {
|
|
|
1197
2034
|
fail(e, opts);
|
|
1198
2035
|
}
|
|
1199
2036
|
});
|
|
1200
|
-
|
|
2037
|
+
common2(
|
|
1201
2038
|
actions.command("logs").description("Print or follow a run's job logs").argument("<run-id>", "run ID").option("--job <job>", "job ID or name (default: all jobs)").option("--step <step>", 'step ordinal or "runner" (default: whole job)').option("--follow", "stream logs while the run is live")
|
|
1202
2039
|
).action(async (runId, opts) => {
|
|
1203
2040
|
try {
|
|
@@ -1224,7 +2061,7 @@ function registerActionsCommands(program2) {
|
|
|
1224
2061
|
if (opts.json) {
|
|
1225
2062
|
process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + "\n");
|
|
1226
2063
|
} else {
|
|
1227
|
-
if (jobs.length > 1) console.log(
|
|
2064
|
+
if (jobs.length > 1) console.log(pc7.bold(`\u2500\u2500 ${job.name} \u2500\u2500`));
|
|
1228
2065
|
for (const seg of slice.segments) process.stdout.write(seg.text);
|
|
1229
2066
|
}
|
|
1230
2067
|
}
|
|
@@ -1255,8 +2092,8 @@ function registerActionsCommands(program2) {
|
|
|
1255
2092
|
fail(e, opts);
|
|
1256
2093
|
}
|
|
1257
2094
|
});
|
|
1258
|
-
const providers = actions.command("providers").description("List the
|
|
1259
|
-
|
|
2095
|
+
const providers = actions.command("providers").description("List the providers Actions can place on (order, act/usable, key status); keys and rates: compute byok");
|
|
2096
|
+
common2(providers).action(async (opts) => {
|
|
1260
2097
|
try {
|
|
1261
2098
|
const data = await (await client(opts)).get("/api/v1/actions/providers");
|
|
1262
2099
|
output(opts, data, (d) => {
|
|
@@ -1266,11 +2103,11 @@ function registerActionsCommands(program2) {
|
|
|
1266
2103
|
fail(e, opts);
|
|
1267
2104
|
}
|
|
1268
2105
|
});
|
|
1269
|
-
|
|
1270
|
-
providers.command("configure").description("Save the org's credential for a provider (owner/admin
|
|
2106
|
+
common2(
|
|
2107
|
+
providers.command("configure").description("Deprecated: use `compute byok configure`. Save the org's credential for a provider (owner/admin)").argument("<provider>", "provider id (e.g. tensorlake, blaxel)").option("--key <key>", "provider API key (single-field credentials)").option("--field <pair...>", "credential fields as name=value (multi-field providers)").option("--verify", "run the placement probe after saving")
|
|
1271
2108
|
).action(async (provider, opts) => {
|
|
1272
2109
|
try {
|
|
1273
|
-
const c = await
|
|
2110
|
+
const c = await secretValueClient(opts, "provider keys");
|
|
1274
2111
|
let body;
|
|
1275
2112
|
if (opts.field !== void 0) {
|
|
1276
2113
|
if (opts.key !== void 0) throw new Error("Pass either --key or --field, not both.");
|
|
@@ -1288,7 +2125,7 @@ function registerActionsCommands(program2) {
|
|
|
1288
2125
|
`/api/v1/actions/providers/${provider}/verify`
|
|
1289
2126
|
) : void 0;
|
|
1290
2127
|
output(opts, verification ? { key: saved.key, verification } : saved, () => {
|
|
1291
|
-
console.log(`saved ${saved.key.provider} ${
|
|
2128
|
+
console.log(`saved ${saved.key.provider} ${pc7.dim(saved.key.keyHint)} ${saved.key.status}`);
|
|
1292
2129
|
if (verification) console.log(formatVerifyResult(verification));
|
|
1293
2130
|
});
|
|
1294
2131
|
if (verification?.verified === false) process.exitCode = 1;
|
|
@@ -1296,8 +2133,8 @@ function registerActionsCommands(program2) {
|
|
|
1296
2133
|
fail(e, opts);
|
|
1297
2134
|
}
|
|
1298
2135
|
});
|
|
1299
|
-
|
|
1300
|
-
providers.command("verify").description(
|
|
2136
|
+
common2(
|
|
2137
|
+
providers.command("verify").description("Deprecated: use `compute byok verify`. Probe the stored provider key with a real sandbox").argument("<provider>", "provider id")
|
|
1301
2138
|
).action(async (provider, opts) => {
|
|
1302
2139
|
try {
|
|
1303
2140
|
const result = await (await client(opts)).post(
|
|
@@ -1309,8 +2146,8 @@ function registerActionsCommands(program2) {
|
|
|
1309
2146
|
fail(e, opts);
|
|
1310
2147
|
}
|
|
1311
2148
|
});
|
|
1312
|
-
|
|
1313
|
-
providers.command("remove").description("Delete the org's stored credential for a provider").argument("<provider>", "provider id")
|
|
2149
|
+
common2(
|
|
2150
|
+
providers.command("remove").description("Deprecated: use `compute byok remove`. Delete the org's stored credential for a provider").argument("<provider>", "provider id")
|
|
1314
2151
|
).action(async (provider, opts) => {
|
|
1315
2152
|
try {
|
|
1316
2153
|
const result = await (await client(opts)).del(
|
|
@@ -1323,107 +2160,10 @@ function registerActionsCommands(program2) {
|
|
|
1323
2160
|
fail(e, opts);
|
|
1324
2161
|
}
|
|
1325
2162
|
});
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
try {
|
|
1329
|
-
const data = await (await client(opts)).get("/api/v1/actions/repos");
|
|
1330
|
-
output(opts, data, (d) => {
|
|
1331
|
-
for (const r of d.repos) console.log(formatRepoRow(r));
|
|
1332
|
-
});
|
|
1333
|
-
} catch (e) {
|
|
1334
|
-
fail(e, opts);
|
|
1335
|
-
}
|
|
1336
|
-
});
|
|
1337
|
-
common(
|
|
1338
|
-
repos.command("connect").description("Connect a git remote (validated by a real ls-remote; lands enabled)").argument("<cloneUrl>", "http(s) or ssh git remote URL").option("--name <owner/repo>", "repo name override (default: derived from cloneUrl)").option("--branch <branch>", "default branch (default: main, else the remote's first)").option("--token <token>", "credential for private http(s) remotes").option("--username <user>", 'username \u2014 with --token, makes auth "basic" instead of "token"').option("--ssh-key-file <path>", "OpenSSH/PEM private key file for ssh remotes").option("--known-hosts-file <path>", "known_hosts pin for ssh remotes")
|
|
1339
|
-
).action(async (cloneUrl, opts) => {
|
|
1340
|
-
try {
|
|
1341
|
-
let body;
|
|
1342
|
-
if (opts.sshKeyFile !== void 0) {
|
|
1343
|
-
if (opts.token !== void 0 || opts.username !== void 0) {
|
|
1344
|
-
throw new Error("Pass either --ssh-key-file or --token/--username, not both.");
|
|
1345
|
-
}
|
|
1346
|
-
body = {
|
|
1347
|
-
authType: "ssh",
|
|
1348
|
-
credential: readFileSync(opts.sshKeyFile, "utf8"),
|
|
1349
|
-
...opts.knownHostsFile !== void 0 && {
|
|
1350
|
-
knownHosts: readFileSync(opts.knownHostsFile, "utf8")
|
|
1351
|
-
}
|
|
1352
|
-
};
|
|
1353
|
-
} else if (opts.username !== void 0) {
|
|
1354
|
-
if (opts.token === void 0) throw new Error("--username requires --token.");
|
|
1355
|
-
body = { authType: "basic", username: opts.username, credential: opts.token };
|
|
1356
|
-
} else if (opts.token !== void 0) {
|
|
1357
|
-
body = { authType: "token", credential: opts.token };
|
|
1358
|
-
} else {
|
|
1359
|
-
body = { authType: "none" };
|
|
1360
|
-
}
|
|
1361
|
-
if (opts.knownHostsFile !== void 0 && opts.sshKeyFile === void 0) {
|
|
1362
|
-
throw new Error("--known-hosts-file requires --ssh-key-file.");
|
|
1363
|
-
}
|
|
1364
|
-
const result = await (await client(opts)).post("/api/v1/actions/repos", {
|
|
1365
|
-
cloneUrl,
|
|
1366
|
-
...body,
|
|
1367
|
-
...opts.name !== void 0 && { name: opts.name },
|
|
1368
|
-
...opts.branch !== void 0 && { defaultBranch: opts.branch }
|
|
1369
|
-
});
|
|
1370
|
-
output(opts, result, (r) => {
|
|
1371
|
-
console.log(`connected ${pc2.cyan(safeTerm(r.fullName))} ${pc2.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);
|
|
1372
|
-
printDiscovery(r.discovery);
|
|
1373
|
-
});
|
|
1374
|
-
} catch (e) {
|
|
1375
|
-
fail(e, opts);
|
|
1376
|
-
}
|
|
1377
|
-
});
|
|
1378
|
-
common(
|
|
1379
|
-
repos.command("sync").description("Re-read the GitHub App installation so repos granted after install show up (owner/admin key)")
|
|
1380
|
-
).action(async (opts) => {
|
|
1381
|
-
try {
|
|
1382
|
-
const result = await (await client(opts)).post("/api/v1/actions/repos/sync", {});
|
|
1383
|
-
output(opts, result, (r) => {
|
|
1384
|
-
for (const a of r.accounts) {
|
|
1385
|
-
console.log(a.error === null ? `synced ${pc2.cyan(safeTerm(a.account))}` : `failed ${pc2.cyan(safeTerm(a.account))} ${pc2.red(safeTerm(a.error))}`);
|
|
1386
|
-
}
|
|
1387
|
-
console.log(pc2.dim(`${r.repos.length} repos visible`));
|
|
1388
|
-
});
|
|
1389
|
-
if (result.accounts.some((a) => a.error !== null)) process.exitCode = 1;
|
|
1390
|
-
} catch (e) {
|
|
1391
|
-
fail(e, opts);
|
|
1392
|
-
}
|
|
1393
|
-
});
|
|
1394
|
-
common(
|
|
1395
|
-
repos.command("enable").description("Enable a repo the org can already see (granted by a GitHub App install, or a connected remote)").argument("<repo>", "repository in owner/repo format").option("--repo-id <id>", "scope to one row when two installations grant the same name")
|
|
1396
|
-
).action(async (repo, opts) => {
|
|
1397
|
-
try {
|
|
1398
|
-
const result = await (await client(opts)).patch("/api/v1/actions/repos", {
|
|
1399
|
-
fullName: repo,
|
|
1400
|
-
enabled: true,
|
|
1401
|
-
...opts.repoId !== void 0 && { repoId: opts.repoId }
|
|
1402
|
-
});
|
|
1403
|
-
output(opts, result, (r) => {
|
|
1404
|
-
console.log(`enabled ${pc2.cyan(safeTerm(r.fullName))}`);
|
|
1405
|
-
if (r.discovery) printDiscovery(r.discovery);
|
|
1406
|
-
});
|
|
1407
|
-
} catch (e) {
|
|
1408
|
-
fail(e, opts);
|
|
1409
|
-
}
|
|
1410
|
-
});
|
|
1411
|
-
common(
|
|
1412
|
-
repos.command("disable").description("Disable a repo \u2014 it stays connected but no runs are scheduled").argument("<repo>", "repository in owner/repo format").option("--repo-id <id>", "scope to one row when two installations grant the same name")
|
|
1413
|
-
).action(async (repo, opts) => {
|
|
1414
|
-
try {
|
|
1415
|
-
const result = await (await client(opts)).patch("/api/v1/actions/repos", {
|
|
1416
|
-
fullName: repo,
|
|
1417
|
-
enabled: false,
|
|
1418
|
-
...opts.repoId !== void 0 && { repoId: opts.repoId }
|
|
1419
|
-
});
|
|
1420
|
-
output(opts, result, (r) => console.log(`disabled ${pc2.cyan(safeTerm(r.fullName))}`));
|
|
1421
|
-
} catch (e) {
|
|
1422
|
-
fail(e, opts);
|
|
1423
|
-
}
|
|
1424
|
-
});
|
|
2163
|
+
registerReposCommands(actions, common2, { client, fail, output });
|
|
2164
|
+
registerIntegrationsCommands(actions, common2, { client, fail, output });
|
|
1425
2165
|
const vault = actions.command("vault").description("The org vault: secrets and variables (owner/admin key)");
|
|
1426
|
-
const vaultScope = (cmd) =>
|
|
2166
|
+
const vaultScope = (cmd) => common2(cmd).option("--repo <owner/repo>", "scope to a repo's own items instead of the org's").option("--kind <kind>", "secret or variable", "secret");
|
|
1427
2167
|
vaultScope(
|
|
1428
2168
|
vault.command("ls").description("List names and metadata (never values)")
|
|
1429
2169
|
).action(async (opts) => {
|
|
@@ -1447,7 +2187,7 @@ function registerActionsCommands(program2) {
|
|
|
1447
2187
|
'Pipe the value on stdin (e.g. printf %s "$VALUE" | compute actions vault set NAME) or pass --from-file.'
|
|
1448
2188
|
);
|
|
1449
2189
|
}
|
|
1450
|
-
const value =
|
|
2190
|
+
const value = readFileSync2(opts.fromFile ?? 0, "utf8");
|
|
1451
2191
|
const kind = parseVaultKind(opts.kind);
|
|
1452
2192
|
const labels = vaultSetLabels(opts);
|
|
1453
2193
|
const body = vaultSetBody(name, value, { ...opts, kind, labels });
|
|
@@ -1457,9 +2197,9 @@ function registerActionsCommands(program2) {
|
|
|
1457
2197
|
);
|
|
1458
2198
|
output(opts, result, (r) => {
|
|
1459
2199
|
const where = opts.repo ? safeTerm(opts.repo) : "org";
|
|
1460
|
-
console.log(`saved ${
|
|
2200
|
+
console.log(`saved ${pc7.cyan(safeTerm(r.item.name))} ${pc7.dim(`(${r.item.kind}, v${r.item.version}, ${where})`)}`);
|
|
1461
2201
|
if (/\r?\n$/.test(value)) {
|
|
1462
|
-
console.error(
|
|
2202
|
+
console.error(pc7.yellow("note: the stored value ends with a newline; use printf %s rather than echo to avoid one."));
|
|
1463
2203
|
}
|
|
1464
2204
|
});
|
|
1465
2205
|
} catch (e) {
|
|
@@ -1493,7 +2233,7 @@ function registerActionsCommands(program2) {
|
|
|
1493
2233
|
output(opts, result, (r) => {
|
|
1494
2234
|
const where = opts.repo ? safeTerm(opts.repo) : "org";
|
|
1495
2235
|
console.log(
|
|
1496
|
-
`reclassified ${
|
|
2236
|
+
`reclassified ${pc7.cyan(safeTerm(r.item.name))} ${pc7.dim(`(labels: ${r.item.labels.join(", ") || "none"}, v${r.item.version}, ${where})`)}`
|
|
1497
2237
|
);
|
|
1498
2238
|
});
|
|
1499
2239
|
} catch (e) {
|
|
@@ -1506,12 +2246,12 @@ function registerActionsCommands(program2) {
|
|
|
1506
2246
|
try {
|
|
1507
2247
|
const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
|
|
1508
2248
|
const result = await (await client(opts)).del(path2);
|
|
1509
|
-
output(opts, result, (r) => console.log(`deleted ${
|
|
2249
|
+
output(opts, result, (r) => console.log(`deleted ${pc7.cyan(safeTerm(r.name))} ${pc7.dim(`(${r.kind})`)}`));
|
|
1510
2250
|
} catch (e) {
|
|
1511
2251
|
fail(e, opts);
|
|
1512
2252
|
}
|
|
1513
2253
|
});
|
|
1514
|
-
|
|
2254
|
+
common2(
|
|
1515
2255
|
actions.command("cancel").description("Cancel a run").argument("<run-id>", "run ID")
|
|
1516
2256
|
).action(async (runId, opts) => {
|
|
1517
2257
|
try {
|
|
@@ -1525,7 +2265,7 @@ function registerActionsCommands(program2) {
|
|
|
1525
2265
|
fail(e, opts);
|
|
1526
2266
|
}
|
|
1527
2267
|
});
|
|
1528
|
-
|
|
2268
|
+
common2(
|
|
1529
2269
|
actions.command("rerun").description("Re-run a finished run at the same commit").argument("<run-id>", "run ID")
|
|
1530
2270
|
).action(async (runId, opts) => {
|
|
1531
2271
|
try {
|
|
@@ -1536,14 +2276,14 @@ function registerActionsCommands(program2) {
|
|
|
1536
2276
|
const org2 = await c.org();
|
|
1537
2277
|
const url = `${c.baseUrl}/${org2.slug}/actions/runs/${result.runId}`;
|
|
1538
2278
|
output(opts, { ...result, url }, (r) => {
|
|
1539
|
-
console.log(`${r.created ? "rerun dispatched" : "rerun already running"} ${
|
|
2279
|
+
console.log(`${r.created ? "rerun dispatched" : "rerun already running"} ${pc7.cyan(r.runId)}`);
|
|
1540
2280
|
console.log(`url: ${r.url}`);
|
|
1541
2281
|
});
|
|
1542
2282
|
} catch (e) {
|
|
1543
2283
|
fail(e, opts);
|
|
1544
2284
|
}
|
|
1545
2285
|
});
|
|
1546
|
-
|
|
2286
|
+
common2(
|
|
1547
2287
|
actions.command("artifacts").description("List or download a run's artifacts").argument("<run-id>", "run ID").option("--job <job>", "job ID or name (default: all jobs)").option("--out <dir>", "download artifacts into this directory instead of listing")
|
|
1548
2288
|
).action(async (runId, opts) => {
|
|
1549
2289
|
try {
|
|
@@ -1599,7 +2339,7 @@ function registerActionsCommands(program2) {
|
|
|
1599
2339
|
fail(e, opts);
|
|
1600
2340
|
}
|
|
1601
2341
|
});
|
|
1602
|
-
registerSettingsCommands(actions, "actions",
|
|
2342
|
+
registerSettingsCommands(actions, "actions", common2, {
|
|
1603
2343
|
client,
|
|
1604
2344
|
fail,
|
|
1605
2345
|
output,
|
|
@@ -1607,10 +2347,160 @@ function registerActionsCommands(program2) {
|
|
|
1607
2347
|
});
|
|
1608
2348
|
}
|
|
1609
2349
|
|
|
2350
|
+
// src/byok.ts
|
|
2351
|
+
import pc8 from "picocolors";
|
|
2352
|
+
var RATE_UNITS = ["second", "minute", "hour"];
|
|
2353
|
+
var MAX_RATE_USD = 1e3;
|
|
2354
|
+
function providerPath(provider, rest = "") {
|
|
2355
|
+
return `/api/v1/providers/${encodeURIComponent(provider)}${rest}`;
|
|
2356
|
+
}
|
|
2357
|
+
function keyText(key) {
|
|
2358
|
+
if (key.keyHint === null) return pc8.gray("no key");
|
|
2359
|
+
const status = key.status === "connected" ? pc8.green("connected") : key.status === "error" ? pc8.red("error") : pc8.yellow("untested");
|
|
2360
|
+
const hints = key.pairs?.length ? key.pairs.map((p2) => `${safeTerm(p2.keyHint ?? "\u2014")}@${safeTerm(p2.region)}`).join(",") : safeTerm(key.keyHint);
|
|
2361
|
+
return `${status} ${pc8.dim(hints)}`;
|
|
2362
|
+
}
|
|
2363
|
+
function rateText(p2) {
|
|
2364
|
+
return p2.customRate ? `${formatRateAllUnits(p2.customRate.rateUsd)} ${pc8.cyan("custom")}` : `${formatRateAllUnits(p2.platformRate.rateUsd)} ${pc8.dim("platform")}`;
|
|
2365
|
+
}
|
|
2366
|
+
function formatByokRow(p2) {
|
|
2367
|
+
const ready = p2.key.status === "connected";
|
|
2368
|
+
const icon = ready ? pc8.green("\u25CF") : pc8.gray("\u25CB");
|
|
2369
|
+
const name = ready ? pc8.white(safeTerm(p2.provider)) : pc8.gray(safeTerm(p2.provider));
|
|
2370
|
+
return ` ${icon} ${name} ${keyText(p2.key)} ${rateText(p2)}`;
|
|
2371
|
+
}
|
|
2372
|
+
function formatByokDetail(p2) {
|
|
2373
|
+
const lines = [
|
|
2374
|
+
`${pc8.white(safeTerm(p2.provider))} ${keyText(p2.key)}`,
|
|
2375
|
+
` regions ${p2.regions.length > 0 ? p2.regions.map(safeTerm).join(", ") : "account default"}`,
|
|
2376
|
+
` last tested ${p2.key.lastCheckedAt === null ? "\u2014" : safeTerm(p2.key.lastCheckedAt)}`,
|
|
2377
|
+
` platform rate ${formatRateAllUnits(p2.platformRate.rateUsd)}`,
|
|
2378
|
+
` custom rate ${p2.customRate ? formatRateAllUnits(p2.customRate.rateUsd) : pc8.dim("none (costs report at the platform rate)")}`
|
|
2379
|
+
];
|
|
2380
|
+
if (p2.key.status === "error" && p2.key.statusDetail) lines.push(` last error ${pc8.dim(safeTerm(p2.key.statusDetail))}`);
|
|
2381
|
+
return lines.join("\n");
|
|
2382
|
+
}
|
|
2383
|
+
function formatByokVerify(r) {
|
|
2384
|
+
const head = r.verified === true ? pc8.green("verified") : pc8.red("not verified");
|
|
2385
|
+
const detail = r.key.statusDetail ? pc8.dim(` ${safeTerm(r.key.statusDetail)}`) : "";
|
|
2386
|
+
const act = r.key.actCapable ? pc8.green(" act-capable") : "";
|
|
2387
|
+
return `${head} ${safeTerm(r.key.provider)}${act}${detail}`;
|
|
2388
|
+
}
|
|
2389
|
+
function parseRateArgs(usd, per) {
|
|
2390
|
+
const amount = Number(usd);
|
|
2391
|
+
if (usd.trim() === "" || !Number.isFinite(amount) || amount < 0 || amount > MAX_RATE_USD) {
|
|
2392
|
+
throw new Error(`<usd> must be a number from 0 to ${MAX_RATE_USD}`);
|
|
2393
|
+
}
|
|
2394
|
+
const unit = per ?? "hour";
|
|
2395
|
+
if (!RATE_UNITS.includes(unit)) throw new Error("--per must be second, minute or hour");
|
|
2396
|
+
return { usd: amount, per: unit };
|
|
2397
|
+
}
|
|
2398
|
+
function keyBody(opts) {
|
|
2399
|
+
if (opts.field !== void 0) {
|
|
2400
|
+
if (opts.key !== void 0) throw new Error("Pass either --key or --field, not both.");
|
|
2401
|
+
return { fields: parseInputs(opts.field) };
|
|
2402
|
+
}
|
|
2403
|
+
if (opts.key !== void 0) return { key: opts.key };
|
|
2404
|
+
throw new Error("Pass --key <key> or --field name=value.");
|
|
2405
|
+
}
|
|
2406
|
+
function registerByokCommands(program2) {
|
|
2407
|
+
const byok = program2.command("byok").description("The org's BYOK providers: their keys and custom rates, shared by Actions and sandboxes").configureOutput({ outputError: usageErrorOutput });
|
|
2408
|
+
const common2 = (cmd) => cmd.option("--api-key <key>", "API key (default: $COMPUTE_API_KEY)").option("--base-url <url>", "API base URL (default: https://platform.computesdk.com)").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)").option("--json", "print machine-readable JSON");
|
|
2409
|
+
const list = async (opts) => {
|
|
2410
|
+
try {
|
|
2411
|
+
const data = await (await client(opts)).get("/api/v1/providers");
|
|
2412
|
+
output(opts, data, (d) => {
|
|
2413
|
+
for (const p2 of d.providers) console.log(formatByokRow(p2));
|
|
2414
|
+
});
|
|
2415
|
+
} catch (e) {
|
|
2416
|
+
fail(e, opts);
|
|
2417
|
+
}
|
|
2418
|
+
};
|
|
2419
|
+
common2(byok).action(list);
|
|
2420
|
+
common2(byok.command("list").alias("ls").description("Every provider the org may bring a key for, with key state and rate")).action(list);
|
|
2421
|
+
common2(
|
|
2422
|
+
byok.command("show").description("One provider's key state, platform rate and custom rate").argument("<provider>", "provider id (e.g. tensorlake, blaxel)")
|
|
2423
|
+
).action(async (provider, opts) => {
|
|
2424
|
+
try {
|
|
2425
|
+
const data = await (await client(opts)).get(providerPath(provider));
|
|
2426
|
+
output(opts, data, (d) => console.log(formatByokDetail(d.provider)));
|
|
2427
|
+
} catch (e) {
|
|
2428
|
+
fail(e, opts);
|
|
2429
|
+
}
|
|
2430
|
+
});
|
|
2431
|
+
common2(
|
|
2432
|
+
byok.command("configure").description("Save the org's key for a provider; untested until verified (owner/admin)").argument("<provider>", "provider id (e.g. tensorlake, blaxel)").option("--key <key>", "provider API key (single-field credentials)").option("--field <pair...>", "credential fields as name=value (multi-field providers)").option("--verify", "test the key with a real sandbox after saving")
|
|
2433
|
+
).action(async (provider, opts) => {
|
|
2434
|
+
try {
|
|
2435
|
+
const c = await secretValueClient(opts, "provider keys");
|
|
2436
|
+
const saved = await c.put(providerPath(provider, "/key"), keyBody(opts));
|
|
2437
|
+
const verification = opts.verify ? await c.post(providerPath(provider, "/verify")) : void 0;
|
|
2438
|
+
output(opts, verification ? { key: saved.key, verification } : saved, () => {
|
|
2439
|
+
console.log(`saved ${safeTerm(saved.key.provider)} ${pc8.dim(safeTerm(saved.key.keyHint ?? ""))} ${safeTerm(saved.key.status)}`);
|
|
2440
|
+
if (verification) console.log(formatByokVerify(verification));
|
|
2441
|
+
});
|
|
2442
|
+
if (verification?.verified === false) process.exitCode = 1;
|
|
2443
|
+
} catch (e) {
|
|
2444
|
+
fail(e, opts);
|
|
2445
|
+
}
|
|
2446
|
+
});
|
|
2447
|
+
common2(
|
|
2448
|
+
byok.command("verify").description('Test the stored key by placing a real sandbox with it ("Test" in Settings; owner/admin)').argument("<provider>", "provider id")
|
|
2449
|
+
).action(async (provider, opts) => {
|
|
2450
|
+
try {
|
|
2451
|
+
const result = await (await client(opts)).post(providerPath(provider, "/verify"));
|
|
2452
|
+
output(opts, result, (r) => console.log(formatByokVerify(r)));
|
|
2453
|
+
if (result.verified === false) process.exitCode = 1;
|
|
2454
|
+
} catch (e) {
|
|
2455
|
+
fail(e, opts);
|
|
2456
|
+
}
|
|
2457
|
+
});
|
|
2458
|
+
common2(
|
|
2459
|
+
byok.command("remove").alias("rm").description("Delete the org's stored key for a provider; nothing places on it until a new key passes (owner/admin)").argument("<provider>", "provider id").option("-y, --yes", "skip the confirmation")
|
|
2460
|
+
).action(async (provider, opts) => {
|
|
2461
|
+
try {
|
|
2462
|
+
await confirmWrite(`Remove the ${provider} key? Sandboxes and Actions jobs stop placing on ${provider}.`, opts);
|
|
2463
|
+
const result = await (await client(opts)).del(providerPath(provider, "/key"));
|
|
2464
|
+
output(opts, result, (r) => console.log(`deleted ${safeTerm(r.provider)}`));
|
|
2465
|
+
} catch (e) {
|
|
2466
|
+
fail(e, opts);
|
|
2467
|
+
}
|
|
2468
|
+
});
|
|
2469
|
+
const rate = byok.command("rate").description("Custom rates: report sandbox costs at your own price. Reporting only; billing is unchanged");
|
|
2470
|
+
common2(
|
|
2471
|
+
rate.command("set").description("Report a provider's sandbox costs at your own rate, e.g. what you pay it (owner/admin). Doesn't change what you're billed").argument("<provider>", "provider id").argument("<usd>", "the rate in USD").option("--per <unit>", "second, minute or hour", "hour")
|
|
2472
|
+
).action(async (provider, usd, opts) => {
|
|
2473
|
+
try {
|
|
2474
|
+
const body = parseRateArgs(usd, opts.per);
|
|
2475
|
+
const data = await (await client(opts)).put(providerPath(provider, "/rate"), body);
|
|
2476
|
+
output(opts, data, (d) => {
|
|
2477
|
+
console.log(`${safeTerm(d.provider.provider)} costs now report at ${formatRateAllUnits(d.provider.rate.rateUsd)}`);
|
|
2478
|
+
console.log(pc8.dim("Reporting only: billing is unchanged. Applies to sandboxes created from now on."));
|
|
2479
|
+
});
|
|
2480
|
+
} catch (e) {
|
|
2481
|
+
fail(e, opts);
|
|
2482
|
+
}
|
|
2483
|
+
});
|
|
2484
|
+
common2(
|
|
2485
|
+
rate.command("clear").description("Drop a provider's custom rate; its costs report at the platform rate again (owner/admin)").argument("<provider>", "provider id")
|
|
2486
|
+
).action(async (provider, opts) => {
|
|
2487
|
+
try {
|
|
2488
|
+
const data = await (await client(opts)).del(providerPath(provider, "/rate"));
|
|
2489
|
+
output(
|
|
2490
|
+
opts,
|
|
2491
|
+
data,
|
|
2492
|
+
(d) => console.log(`${safeTerm(d.provider.provider)} costs now report at the platform rate, ${formatRateAllUnits(d.provider.platformRate.rateUsd)}`)
|
|
2493
|
+
);
|
|
2494
|
+
} catch (e) {
|
|
2495
|
+
fail(e, opts);
|
|
2496
|
+
}
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
|
|
1610
2500
|
// src/market.ts
|
|
1611
|
-
import
|
|
2501
|
+
import pc9 from "picocolors";
|
|
1612
2502
|
var USD_RE = /^\d+(\.\d+)?([eE][+-]?\d+)?$/;
|
|
1613
|
-
var
|
|
2503
|
+
var RATE_UNITS2 = ["second", "minute", "hour"];
|
|
1614
2504
|
var MARKET_LANES = ["actions", "sandbox"];
|
|
1615
2505
|
function parseMarketLane(value) {
|
|
1616
2506
|
if (value === void 0) return "actions";
|
|
@@ -1653,7 +2543,7 @@ function parseRate(price, per) {
|
|
|
1653
2543
|
"--price needs a unit \u2014 write it as <usd>/<unit> (e.g. --price 0.12/hour) or pass --per hour."
|
|
1654
2544
|
);
|
|
1655
2545
|
}
|
|
1656
|
-
if (!
|
|
2546
|
+
if (!RATE_UNITS2.includes(unit)) {
|
|
1657
2547
|
throw new PlatformClientError(
|
|
1658
2548
|
"invalid_argument",
|
|
1659
2549
|
`The unit must be second, minute, or hour, got "${unit}".`
|
|
@@ -1767,12 +2657,12 @@ function formatRate2(usd, per) {
|
|
|
1767
2657
|
}
|
|
1768
2658
|
function formatListingStatus(ask) {
|
|
1769
2659
|
let label;
|
|
1770
|
-
if (ask.status === "withdrawn") label =
|
|
1771
|
-
else if (ask.status === "paused") label =
|
|
1772
|
-
else if (!ask.live) label =
|
|
1773
|
-
else label =
|
|
2660
|
+
if (ask.status === "withdrawn") label = pc9.gray("withdrawn");
|
|
2661
|
+
else if (ask.status === "paused") label = pc9.yellow("paused");
|
|
2662
|
+
else if (!ask.live) label = pc9.gray("expired");
|
|
2663
|
+
else label = pc9.green("live");
|
|
1774
2664
|
if (ask.pendingUsd !== null && ask.pendingPer !== null) {
|
|
1775
|
-
label +=
|
|
2665
|
+
label += pc9.dim(` \u2192 ${formatRate2(ask.pendingUsd, ask.pendingPer)} next window`);
|
|
1776
2666
|
}
|
|
1777
2667
|
return label;
|
|
1778
2668
|
}
|
|
@@ -1781,22 +2671,22 @@ function formatListingRow(ask) {
|
|
|
1781
2671
|
return [
|
|
1782
2672
|
ask.id,
|
|
1783
2673
|
formatListingStatus(ask),
|
|
1784
|
-
|
|
2674
|
+
pc9.dim(ask.useCase === "sandbox" ? "sandbox" : "actions"),
|
|
1785
2675
|
safeTerm(ask.size),
|
|
1786
2676
|
safeTerm(ask.region ?? "-"),
|
|
1787
2677
|
formatRate2(ask.usd, ask.per),
|
|
1788
|
-
|
|
1789
|
-
|
|
2678
|
+
pc9.dim(`\xD7${ask.maxConcurrent}`),
|
|
2679
|
+
pc9.dim(expiry)
|
|
1790
2680
|
].join(" ");
|
|
1791
2681
|
}
|
|
1792
2682
|
function formatProviderStatus(p2) {
|
|
1793
2683
|
const lines = [];
|
|
1794
|
-
lines.push(`${
|
|
2684
|
+
lines.push(`${pc9.bold(safeTerm(p2.name))} ${pc9.dim(`selling ${safeTerm(p2.provider)}`)}`);
|
|
1795
2685
|
lines.push(`id: ${p2.id}`);
|
|
1796
2686
|
lines.push(
|
|
1797
|
-
`credential: ${p2.executorCredentialConnected ?
|
|
2687
|
+
`credential: ${p2.executorCredentialConnected ? pc9.green("connected") : pc9.yellow("not connected \u2014 your listings cannot fill until `compute market credential connect`")}`
|
|
1798
2688
|
);
|
|
1799
|
-
if (p2.revokedAt) lines.push(
|
|
2689
|
+
if (p2.revokedAt) lines.push(pc9.red(`revoked: ${p2.revokedAt}`));
|
|
1800
2690
|
lines.push(
|
|
1801
2691
|
`lanes: ${(p2.useCases ?? ["actions"]).join(", ")}`
|
|
1802
2692
|
);
|
|
@@ -1814,41 +2704,41 @@ function formatProviderStatus(p2) {
|
|
|
1814
2704
|
}
|
|
1815
2705
|
function formatBook(book) {
|
|
1816
2706
|
const lines = [];
|
|
1817
|
-
const lane = (useCase) =>
|
|
1818
|
-
lines.push(
|
|
1819
|
-
if (book.asks.length === 0) lines.push(
|
|
2707
|
+
const lane = (useCase) => pc9.dim(useCase === "sandbox" ? "sandbox" : "actions");
|
|
2708
|
+
lines.push(pc9.bold("sellers' asking prices"));
|
|
2709
|
+
if (book.asks.length === 0) lines.push(pc9.dim(" no listings are live"));
|
|
1820
2710
|
for (const ask of book.asks) {
|
|
1821
2711
|
const where = ask.region ? safeTerm(ask.region) : "any region";
|
|
1822
|
-
const expiry = ask.expiresAt ?
|
|
2712
|
+
const expiry = ask.expiresAt ? pc9.dim(ask.rollover ? ` renews ${ask.expiresAt}` : ` until ${ask.expiresAt}`) : "";
|
|
1823
2713
|
lines.push(
|
|
1824
2714
|
` ${lane(ask.useCase)} ${formatRate2(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`
|
|
1825
2715
|
);
|
|
1826
2716
|
}
|
|
1827
2717
|
lines.push("");
|
|
1828
|
-
lines.push(
|
|
1829
|
-
if (book.bids.length === 0) lines.push(
|
|
2718
|
+
lines.push(pc9.bold("buyer offers"));
|
|
2719
|
+
if (book.bids.length === 0) lines.push(pc9.dim(" no open offers"));
|
|
1830
2720
|
for (const bid of book.bids) {
|
|
1831
2721
|
const where = bid.region ? safeTerm(bid.region) : "anywhere";
|
|
1832
|
-
const yours = bid.mine ?
|
|
2722
|
+
const yours = bid.mine ? pc9.cyan(" (yours)") : "";
|
|
1833
2723
|
lines.push(
|
|
1834
|
-
` ${lane(bid.useCase)} pays up to ${formatRate2(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${
|
|
2724
|
+
` ${lane(bid.useCase)} pays up to ${formatRate2(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc9.dim(`posted ${bid.createdAt}`)}${yours}`
|
|
1835
2725
|
);
|
|
1836
2726
|
}
|
|
1837
2727
|
lines.push("");
|
|
1838
|
-
lines.push(
|
|
1839
|
-
if (book.fills.length === 0) lines.push(
|
|
2728
|
+
lines.push(pc9.bold("recent sales"));
|
|
2729
|
+
if (book.fills.length === 0) lines.push(pc9.dim(" nothing has sold yet"));
|
|
1840
2730
|
for (const fill of book.fills) {
|
|
1841
|
-
const statusNote = fill.status === "replaced" ?
|
|
2731
|
+
const statusNote = fill.status === "replaced" ? pc9.yellow(" replaced") : fill.status === "closed" ? pc9.gray(" closed") : "";
|
|
1842
2732
|
lines.push(
|
|
1843
|
-
` ${
|
|
2733
|
+
` ${pc9.dim(fill.id)} ${lane(fill.useCase)} ${formatRate2(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? "-")} ${pc9.dim(fill.createdAt)}${statusNote}`
|
|
1844
2734
|
);
|
|
1845
2735
|
}
|
|
1846
2736
|
return lines.join("\n");
|
|
1847
2737
|
}
|
|
1848
2738
|
function formatReplacedFill(fill) {
|
|
1849
2739
|
const settled = formatMoney(fill.settledMicroUsd / 1e6);
|
|
1850
|
-
const job = fill.jobRequeued ?
|
|
1851
|
-
return `replaced ${
|
|
2740
|
+
const job = fill.jobRequeued ? pc9.dim(" \u2014 job re-places on the buyer's next provider") : "";
|
|
2741
|
+
return `replaced ${pc9.cyan(fill.fillId)} settled ${settled}${job}`;
|
|
1852
2742
|
}
|
|
1853
2743
|
function replaceTarget(listingId, fillId) {
|
|
1854
2744
|
if (fillId !== void 0) {
|
|
@@ -1870,9 +2760,9 @@ function replaceTarget(listingId, fillId) {
|
|
|
1870
2760
|
}
|
|
1871
2761
|
function formatSettlementRow(s) {
|
|
1872
2762
|
const period = `${s.periodStart.slice(0, 10)} \u2192 ${s.periodEnd.slice(0, 10)}`;
|
|
1873
|
-
const paid = s.paidAt ?
|
|
2763
|
+
const paid = s.paidAt ? pc9.green(`paid ${s.paidAt.slice(0, 10)}`) : s.invoiceRef ? pc9.yellow(`invoiced ${safeTerm(s.invoiceRef)}`) : pc9.dim("unpaid");
|
|
1874
2764
|
return [
|
|
1875
|
-
|
|
2765
|
+
pc9.dim(period),
|
|
1876
2766
|
`${s.vcpuSeconds.toLocaleString("en-US")} vCPU\xB7s`,
|
|
1877
2767
|
`gross ${formatMoney(s.grossUsd)}`,
|
|
1878
2768
|
`net ${formatMoney(s.netUsd)}`,
|
|
@@ -1906,22 +2796,22 @@ function formatCap(cap) {
|
|
|
1906
2796
|
return cap === null ? "No market cap \u2014 market-placed jobs need their own bid to fill." : `market cap ${formatRate2(cap.usd, cap.per)}`;
|
|
1907
2797
|
}
|
|
1908
2798
|
function formatBidRow(bid) {
|
|
1909
|
-
const status = bid.status === "open" ?
|
|
2799
|
+
const status = bid.status === "open" ? pc9.green("open") : bid.status === "filled" ? pc9.cyan("filled") : pc9.gray("cancelled");
|
|
1910
2800
|
return [
|
|
1911
2801
|
bid.id,
|
|
1912
2802
|
status,
|
|
1913
|
-
|
|
2803
|
+
pc9.dim(bid.useCase === "sandbox" ? "sandbox" : "actions"),
|
|
1914
2804
|
safeTerm(bid.size),
|
|
1915
2805
|
safeTerm(bid.region ?? "any region"),
|
|
1916
2806
|
`\u2264 ${formatRate2(bid.maxUsd, bid.per)}`,
|
|
1917
|
-
|
|
2807
|
+
pc9.dim(bid.expiresAt ? `expires ${bid.expiresAt}` : "standing")
|
|
1918
2808
|
].join(" ");
|
|
1919
2809
|
}
|
|
1920
2810
|
function formatCredits(b) {
|
|
1921
2811
|
const lines = [`available ${formatMoney(b.balanceMicroUsd / MICRO_USD)}`];
|
|
1922
2812
|
if (b.holds.length > 0) {
|
|
1923
2813
|
lines.push(
|
|
1924
|
-
|
|
2814
|
+
pc9.dim(`reserved ${formatMoney(b.heldMicroUsd / MICRO_USD)} across ${b.holds.length} running job${b.holds.length === 1 ? "" : "s"}`)
|
|
1925
2815
|
);
|
|
1926
2816
|
}
|
|
1927
2817
|
return lines.join("\n");
|
|
@@ -1930,29 +2820,29 @@ function formatLedgerRow(e) {
|
|
|
1930
2820
|
const usd = e.microUsd / MICRO_USD;
|
|
1931
2821
|
const amount = usd < 0 ? `-${formatMoney(-usd)}` : `+${formatMoney(usd)}`;
|
|
1932
2822
|
return [
|
|
1933
|
-
|
|
1934
|
-
(usd < 0 ?
|
|
2823
|
+
pc9.dim(e.createdAt.slice(0, 19).replace("T", " ")),
|
|
2824
|
+
(usd < 0 ? pc9.red : pc9.green)(amount.padStart(10)),
|
|
1935
2825
|
safeTerm(e.label),
|
|
1936
|
-
|
|
2826
|
+
pc9.dim(e.jobId ? `job ${e.jobId}` : "")
|
|
1937
2827
|
].join(" ").trimEnd();
|
|
1938
2828
|
}
|
|
1939
2829
|
function formatPurchaseRow(p2) {
|
|
1940
|
-
const cost = p2.costMicroUsd !== null ? formatMoney(p2.costMicroUsd / MICRO_USD) : p2.status === "live" ?
|
|
2830
|
+
const cost = p2.costMicroUsd !== null ? formatMoney(p2.costMicroUsd / MICRO_USD) : p2.status === "live" ? pc9.yellow("running") : "-";
|
|
1941
2831
|
return [
|
|
1942
|
-
|
|
2832
|
+
pc9.dim(p2.startedAt.slice(0, 19).replace("T", " ")),
|
|
1943
2833
|
cost.padStart(10),
|
|
1944
|
-
|
|
1945
|
-
|
|
2834
|
+
pc9.cyan(safeTerm(p2.sellerName)),
|
|
2835
|
+
pc9.dim(`${safeTerm(p2.provider)}/${safeTerm(p2.region ?? "any")}`),
|
|
1946
2836
|
formatRate2(p2.usd, p2.per),
|
|
1947
|
-
p2.secondsBilled !== null ?
|
|
1948
|
-
p2.status === "replaced" ?
|
|
1949
|
-
|
|
2837
|
+
p2.secondsBilled !== null ? pc9.dim(`${p2.secondsBilled}s`) : "",
|
|
2838
|
+
p2.status === "replaced" ? pc9.yellow("replaced") : "",
|
|
2839
|
+
pc9.dim(p2.runId ? `run ${p2.runId}` : p2.sandboxId ? `sandbox ${p2.sandboxId}` : "")
|
|
1950
2840
|
].filter((part) => part !== "").join(" ");
|
|
1951
2841
|
}
|
|
1952
2842
|
function registerMarketCommands(program2) {
|
|
1953
2843
|
const market = program2.command("market").description("Buy and sell compute capacity on the compute market").configureOutput({ outputError: usageErrorOutput });
|
|
1954
|
-
const
|
|
1955
|
-
|
|
2844
|
+
const common2 = (cmd) => cmd.option("--api-key <key>", "API key (default: $COMPUTE_API_KEY)").option("--base-url <url>", "API base URL (default: https://platform.computesdk.com)").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)").option("--json", "print machine-readable JSON");
|
|
2845
|
+
common2(
|
|
1956
2846
|
market.command("listings").alias("list").description("Your listings \u2014 live, paused, expired, and withdrawn")
|
|
1957
2847
|
).action(async (opts) => {
|
|
1958
2848
|
try {
|
|
@@ -1970,7 +2860,7 @@ function registerMarketCommands(program2) {
|
|
|
1970
2860
|
fail(e, opts);
|
|
1971
2861
|
}
|
|
1972
2862
|
});
|
|
1973
|
-
|
|
2863
|
+
common2(
|
|
1974
2864
|
market.command("sell").description("Post a listing: sell capacity at a price").requiredOption("--price <usd/unit>", "price per unit of time (e.g. 0.12/hour)").option("--per <unit>", "unit for a bare --price usd (second, minute, or hour)").option("--size <tier>", "size tier to sell (default: medium, else the provider's first tier)").option("--use-case <lane>", "lane to sell into: actions or sandbox (default: actions)").option("--region <region>", "region to sell in (default: anywhere the provider runs)").option("--capacity <n>", "max simultaneous fills (default: 1)").option("--expires-in <hours>", "delist after this many hours (default: standing)").option("--renew", "re-list for the same window each time it expires (requires --expires-in)")
|
|
1975
2865
|
).action(async (opts) => {
|
|
1976
2866
|
try {
|
|
@@ -1989,21 +2879,21 @@ function registerMarketCommands(program2) {
|
|
|
1989
2879
|
);
|
|
1990
2880
|
}
|
|
1991
2881
|
size = preset.name;
|
|
1992
|
-
console.error(
|
|
2882
|
+
console.error(pc9.dim(`no --size given \u2014 listing at "${size}"`));
|
|
1993
2883
|
}
|
|
1994
2884
|
const result = await c.post(
|
|
1995
2885
|
"/api/v1/market/asks",
|
|
1996
2886
|
sellBody({ ...opts, size, useCase })
|
|
1997
2887
|
);
|
|
1998
2888
|
output(opts, result, (r) => {
|
|
1999
|
-
console.log(`listed ${
|
|
2889
|
+
console.log(`listed ${pc9.cyan(r.ask.id)}`);
|
|
2000
2890
|
console.log(formatListingRow(r.ask));
|
|
2001
2891
|
});
|
|
2002
2892
|
} catch (e) {
|
|
2003
2893
|
fail(e, opts);
|
|
2004
2894
|
}
|
|
2005
2895
|
});
|
|
2006
|
-
|
|
2896
|
+
common2(
|
|
2007
2897
|
market.command("price").description("Reprice a listing").argument("<listing-id>", "listing ID").requiredOption("--price <usd/unit>", "new price per unit of time (e.g. 0.08/hour)").option("--per <unit>", "unit for a bare --price usd (second, minute, or hour)")
|
|
2008
2898
|
).action(async (listingId, opts) => {
|
|
2009
2899
|
try {
|
|
@@ -2012,8 +2902,8 @@ function registerMarketCommands(program2) {
|
|
|
2012
2902
|
listingPatchBody(listingId, { price: opts.price, per: opts.per })
|
|
2013
2903
|
);
|
|
2014
2904
|
output(opts, result, (r) => {
|
|
2015
|
-
const rate = r.ask.pendingUsd !== null && r.ask.pendingPer !== null ? `${formatRate2(r.ask.pendingUsd, r.ask.pendingPer)} ${
|
|
2016
|
-
console.log(`repriced ${
|
|
2905
|
+
const rate = r.ask.pendingUsd !== null && r.ask.pendingPer !== null ? `${formatRate2(r.ask.pendingUsd, r.ask.pendingPer)} ${pc9.dim("(applies next window)")}` : formatRate2(r.ask.usd, r.ask.per);
|
|
2906
|
+
console.log(`repriced ${pc9.cyan(r.ask.id)} ${rate}`);
|
|
2017
2907
|
});
|
|
2018
2908
|
} catch (e) {
|
|
2019
2909
|
fail(e, opts);
|
|
@@ -2026,19 +2916,19 @@ function registerMarketCommands(program2) {
|
|
|
2026
2916
|
listingPatchBody(listingId, { status })
|
|
2027
2917
|
);
|
|
2028
2918
|
output(opts, result, (r) => {
|
|
2029
|
-
console.log(`${status === "live" ? "resumed" : "paused"} ${
|
|
2919
|
+
console.log(`${status === "live" ? "resumed" : "paused"} ${pc9.cyan(r.ask.id)}`);
|
|
2030
2920
|
});
|
|
2031
2921
|
} catch (e) {
|
|
2032
2922
|
fail(e, opts);
|
|
2033
2923
|
}
|
|
2034
2924
|
};
|
|
2035
|
-
|
|
2925
|
+
common2(
|
|
2036
2926
|
market.command("pause").description("Pause a listing \u2014 it stays posted but cannot fill").argument("<listing-id>", "listing ID")
|
|
2037
2927
|
).action((listingId, opts) => setStatus(listingId, "paused", opts));
|
|
2038
|
-
|
|
2928
|
+
common2(
|
|
2039
2929
|
market.command("resume").description("Resume a paused listing").argument("<listing-id>", "listing ID")
|
|
2040
2930
|
).action((listingId, opts) => setStatus(listingId, "live", opts));
|
|
2041
|
-
|
|
2931
|
+
common2(
|
|
2042
2932
|
market.command("withdraw").description("Withdraw a listing \u2014 it leaves the book for good").argument("<listing-id>", "listing ID")
|
|
2043
2933
|
).action(async (listingId, opts) => {
|
|
2044
2934
|
try {
|
|
@@ -2046,13 +2936,13 @@ function registerMarketCommands(program2) {
|
|
|
2046
2936
|
`/api/v1/market/asks?id=${encodeURIComponent(listingId)}`
|
|
2047
2937
|
);
|
|
2048
2938
|
output(opts, result, (r) => {
|
|
2049
|
-
console.log(`withdrew ${
|
|
2939
|
+
console.log(`withdrew ${pc9.cyan(r.ask.id)}`);
|
|
2050
2940
|
});
|
|
2051
2941
|
} catch (e) {
|
|
2052
2942
|
fail(e, opts);
|
|
2053
2943
|
}
|
|
2054
2944
|
});
|
|
2055
|
-
|
|
2945
|
+
common2(
|
|
2056
2946
|
market.command("replace").description(
|
|
2057
2947
|
"Take capacity back: evict a sale, or pause a listing and evict every sale on it.\nAn evicted Actions job restarts on the buyer's next provider; the buyer pays\nonly for the seconds the sale actually ran."
|
|
2058
2948
|
).argument("[listing-id]", "listing to pause and evict every sale on").option("--fill <fill-id>", "evict one sale without touching the listing")
|
|
@@ -2067,14 +2957,14 @@ function registerMarketCommands(program2) {
|
|
|
2067
2957
|
} else {
|
|
2068
2958
|
const result = await c.post(target.path, {});
|
|
2069
2959
|
output(opts, result, (r) => {
|
|
2070
|
-
console.log(`paused ${
|
|
2960
|
+
console.log(`paused ${pc9.cyan(r.listing.id)}`);
|
|
2071
2961
|
if (r.fills.length === 0) {
|
|
2072
|
-
console.log(
|
|
2962
|
+
console.log(pc9.dim(" no live sales to evict"));
|
|
2073
2963
|
return;
|
|
2074
2964
|
}
|
|
2075
2965
|
for (const f of r.fills) {
|
|
2076
2966
|
if (f.ok) console.log(formatReplacedFill(f.fill));
|
|
2077
|
-
else console.log(
|
|
2967
|
+
else console.log(pc9.red(` could not evict a sale \u2014 ${f.error}`));
|
|
2078
2968
|
}
|
|
2079
2969
|
});
|
|
2080
2970
|
if (result.fills.some((f) => !f.ok)) process.exitCode = 1;
|
|
@@ -2084,7 +2974,7 @@ function registerMarketCommands(program2) {
|
|
|
2084
2974
|
}
|
|
2085
2975
|
}
|
|
2086
2976
|
);
|
|
2087
|
-
|
|
2977
|
+
common2(
|
|
2088
2978
|
market.command("book").description("Live prices: sellers' asking prices, buyer offers, recent sales").option("--use-case <lane>", "only this lane: actions or sandbox (default: both)")
|
|
2089
2979
|
).action(async (opts) => {
|
|
2090
2980
|
try {
|
|
@@ -2097,7 +2987,7 @@ function registerMarketCommands(program2) {
|
|
|
2097
2987
|
fail(e, opts);
|
|
2098
2988
|
}
|
|
2099
2989
|
});
|
|
2100
|
-
|
|
2990
|
+
common2(
|
|
2101
2991
|
market.command("settlements").description("Your monthly payout reports")
|
|
2102
2992
|
).action(async (opts) => {
|
|
2103
2993
|
try {
|
|
@@ -2113,7 +3003,7 @@ function registerMarketCommands(program2) {
|
|
|
2113
3003
|
fail(e, opts);
|
|
2114
3004
|
}
|
|
2115
3005
|
});
|
|
2116
|
-
|
|
3006
|
+
common2(
|
|
2117
3007
|
market.command("status").description("Who you are on the market: seller identity, credential, sizes, regions")
|
|
2118
3008
|
).action(async (opts) => {
|
|
2119
3009
|
try {
|
|
@@ -2124,7 +3014,7 @@ function registerMarketCommands(program2) {
|
|
|
2124
3014
|
}
|
|
2125
3015
|
});
|
|
2126
3016
|
const cap = market.command("cap").description("The org market cap: the most a market-placed job pays without its own bid");
|
|
2127
|
-
|
|
3017
|
+
common2(cap.command("show", { isDefault: true }).description("Show the current cap")).action(
|
|
2128
3018
|
async (opts) => {
|
|
2129
3019
|
try {
|
|
2130
3020
|
const { marketCap } = await (await client(opts)).get(
|
|
@@ -2136,7 +3026,7 @@ function registerMarketCommands(program2) {
|
|
|
2136
3026
|
}
|
|
2137
3027
|
}
|
|
2138
3028
|
);
|
|
2139
|
-
|
|
3029
|
+
common2(
|
|
2140
3030
|
cap.command("set").description("Set the cap").requiredOption("--price <usd/unit>", "max price per unit of time (e.g. 0.40/hour)").option("--per <unit>", "unit for a bare --price usd (second, minute, or hour)")
|
|
2141
3031
|
).action(async (opts) => {
|
|
2142
3032
|
try {
|
|
@@ -2150,7 +3040,7 @@ function registerMarketCommands(program2) {
|
|
|
2150
3040
|
fail(e, opts);
|
|
2151
3041
|
}
|
|
2152
3042
|
});
|
|
2153
|
-
|
|
3043
|
+
common2(
|
|
2154
3044
|
cap.command("clear").description("Remove the cap (refused while your placement order still names market)")
|
|
2155
3045
|
).action(async (opts) => {
|
|
2156
3046
|
try {
|
|
@@ -2163,7 +3053,7 @@ function registerMarketCommands(program2) {
|
|
|
2163
3053
|
fail(e, opts);
|
|
2164
3054
|
}
|
|
2165
3055
|
});
|
|
2166
|
-
|
|
3056
|
+
common2(
|
|
2167
3057
|
market.command("bids").description("Your org's standing bids \u2014 open, filled, and cancelled")
|
|
2168
3058
|
).action(async (opts) => {
|
|
2169
3059
|
try {
|
|
@@ -2181,7 +3071,7 @@ function registerMarketCommands(program2) {
|
|
|
2181
3071
|
fail(e, opts);
|
|
2182
3072
|
}
|
|
2183
3073
|
});
|
|
2184
|
-
|
|
3074
|
+
common2(
|
|
2185
3075
|
market.command("bid").description("Post a standing bid: the most you will pay for a size tier").requiredOption("--size <tier>", "size tier to buy (e.g. xlarge)").requiredOption("--price <usd/unit>", "max price per unit of time (e.g. 0.40/hour)").option("--per <unit>", "unit for a bare --price usd (second, minute, or hour)").option("--region <region>", "only fill in this region (default: any)").option("--use-case <lane>", "lane to buy on: actions or sandbox (default: actions)").option("--expires-in <hours>", "cancel after this many hours (default: standing)")
|
|
2186
3076
|
).action(async (opts) => {
|
|
2187
3077
|
try {
|
|
@@ -2190,26 +3080,26 @@ function registerMarketCommands(program2) {
|
|
|
2190
3080
|
bidBody(opts)
|
|
2191
3081
|
);
|
|
2192
3082
|
output(opts, result, (r) => {
|
|
2193
|
-
console.log(`bid placed ${
|
|
3083
|
+
console.log(`bid placed ${pc9.cyan(r.bid.id)}`);
|
|
2194
3084
|
console.log(formatBidRow(r.bid));
|
|
2195
3085
|
});
|
|
2196
3086
|
} catch (e) {
|
|
2197
3087
|
fail(e, opts);
|
|
2198
3088
|
}
|
|
2199
3089
|
});
|
|
2200
|
-
|
|
3090
|
+
common2(
|
|
2201
3091
|
market.command("cancel-bid").description("Cancel an open standing bid").argument("<bid-id>", "bid ID")
|
|
2202
3092
|
).action(async (bidId, opts) => {
|
|
2203
3093
|
try {
|
|
2204
3094
|
const result = await (await client(opts)).del(
|
|
2205
3095
|
`/api/v1/market/bids?id=${encodeURIComponent(bidId)}`
|
|
2206
3096
|
);
|
|
2207
|
-
output(opts, result, (r) => console.log(`cancelled ${
|
|
3097
|
+
output(opts, result, (r) => console.log(`cancelled ${pc9.cyan(r.bid.id)}`));
|
|
2208
3098
|
} catch (e) {
|
|
2209
3099
|
fail(e, opts);
|
|
2210
3100
|
}
|
|
2211
3101
|
});
|
|
2212
|
-
|
|
3102
|
+
common2(
|
|
2213
3103
|
market.command("purchases").description("What the market ran for you: seller, price, duration, and cost, newest first").option("--limit <n>", "purchases per page (max 200, default 50)").option("--cursor <cursor>", "continue from a previous page")
|
|
2214
3104
|
).action(async (opts) => {
|
|
2215
3105
|
try {
|
|
@@ -2220,13 +3110,13 @@ function registerMarketCommands(program2) {
|
|
|
2220
3110
|
return;
|
|
2221
3111
|
}
|
|
2222
3112
|
for (const row of p2.purchases) console.log(formatPurchaseRow(row));
|
|
2223
|
-
if (p2.nextCursor) console.log(
|
|
3113
|
+
if (p2.nextCursor) console.log(pc9.dim(`more: --cursor ${p2.nextCursor}`));
|
|
2224
3114
|
});
|
|
2225
3115
|
} catch (e) {
|
|
2226
3116
|
fail(e, opts);
|
|
2227
3117
|
}
|
|
2228
3118
|
});
|
|
2229
|
-
|
|
3119
|
+
common2(
|
|
2230
3120
|
market.command("credits").description("Prepaid market credits: available balance and reserved holds")
|
|
2231
3121
|
).action(async (opts) => {
|
|
2232
3122
|
try {
|
|
@@ -2238,7 +3128,7 @@ function registerMarketCommands(program2) {
|
|
|
2238
3128
|
fail(e, opts);
|
|
2239
3129
|
}
|
|
2240
3130
|
});
|
|
2241
|
-
|
|
3131
|
+
common2(
|
|
2242
3132
|
market.command("ledger").description("Credit history, newest first: top-ups, charges, holds, refunds").option("--limit <n>", "entries per page (max 200, default 50)").option("--cursor <cursor>", "continue from a previous page")
|
|
2243
3133
|
).action(async (opts) => {
|
|
2244
3134
|
try {
|
|
@@ -2249,13 +3139,13 @@ function registerMarketCommands(program2) {
|
|
|
2249
3139
|
return;
|
|
2250
3140
|
}
|
|
2251
3141
|
for (const entry of p2.entries) console.log(formatLedgerRow(entry));
|
|
2252
|
-
if (p2.nextCursor) console.log(
|
|
3142
|
+
if (p2.nextCursor) console.log(pc9.dim(`more: --cursor ${p2.nextCursor}`));
|
|
2253
3143
|
});
|
|
2254
3144
|
} catch (e) {
|
|
2255
3145
|
fail(e, opts);
|
|
2256
3146
|
}
|
|
2257
3147
|
});
|
|
2258
|
-
|
|
3148
|
+
common2(
|
|
2259
3149
|
market.command("topup").description("Buy prepaid credits \u2014 prints a Stripe checkout link to pay in your browser").argument("<usd>", "amount in USD (e.g. 50)")
|
|
2260
3150
|
).action(async (amount, opts) => {
|
|
2261
3151
|
try {
|
|
@@ -2272,7 +3162,7 @@ function registerMarketCommands(program2) {
|
|
|
2272
3162
|
}
|
|
2273
3163
|
});
|
|
2274
3164
|
const credential = market.command("credential").description("Connect the credential your listings fill under");
|
|
2275
|
-
|
|
3165
|
+
common2(
|
|
2276
3166
|
credential.command("connect").description(
|
|
2277
3167
|
"Save the executor credential your sold capacity runs under. Each field is read from\na <PROVIDER>_<FIELD> env var (e.g. TENSORLAKE_API_KEY) \u2014 never pass secrets in argv;\n--field name=value overrides a field (visible in shell history)"
|
|
2278
3168
|
).option("--field <pairs...>", "credential fields as name=value (prefer env vars for secrets)")
|
|
@@ -2303,7 +3193,7 @@ ${hints}`
|
|
|
2303
3193
|
}
|
|
2304
3194
|
if (resolved.fromFlag.some((name) => provider.credentialFields.find((f) => f.name === name)?.secret)) {
|
|
2305
3195
|
console.error(
|
|
2306
|
-
|
|
3196
|
+
pc9.yellow("note: a secret passed via --field stays in your shell history \u2014 prefer the env vars.")
|
|
2307
3197
|
);
|
|
2308
3198
|
}
|
|
2309
3199
|
const result = await c.post(
|
|
@@ -2311,13 +3201,13 @@ ${hints}`
|
|
|
2311
3201
|
credentialBody(provider.credentialFields, resolved.values)
|
|
2312
3202
|
);
|
|
2313
3203
|
output(opts, result, (r) => {
|
|
2314
|
-
console.log(`connected ${
|
|
3204
|
+
console.log(`connected ${pc9.cyan(safeTerm(r.provider.name))} credential saved`);
|
|
2315
3205
|
});
|
|
2316
3206
|
} catch (e) {
|
|
2317
3207
|
fail(e, opts);
|
|
2318
3208
|
}
|
|
2319
3209
|
});
|
|
2320
|
-
|
|
3210
|
+
common2(
|
|
2321
3211
|
credential.command("disconnect").description("Remove the stored credential \u2014 listings stop filling until a new one connects")
|
|
2322
3212
|
).action(async (opts) => {
|
|
2323
3213
|
try {
|
|
@@ -2325,7 +3215,7 @@ ${hints}`
|
|
|
2325
3215
|
"/api/v1/market/provider/credential"
|
|
2326
3216
|
);
|
|
2327
3217
|
output(opts, result, (r) => {
|
|
2328
|
-
console.log(`disconnected ${
|
|
3218
|
+
console.log(`disconnected ${pc9.cyan(safeTerm(r.provider.name))} credential removed`);
|
|
2329
3219
|
});
|
|
2330
3220
|
} catch (e) {
|
|
2331
3221
|
fail(e, opts);
|
|
@@ -2339,13 +3229,13 @@ import * as os from "os";
|
|
|
2339
3229
|
import * as path from "path";
|
|
2340
3230
|
import * as readline from "readline";
|
|
2341
3231
|
import { Readable } from "stream";
|
|
2342
|
-
import
|
|
3232
|
+
import pc10 from "picocolors";
|
|
2343
3233
|
import * as tar from "tar";
|
|
2344
3234
|
|
|
2345
3235
|
// src/current-instance.ts
|
|
2346
3236
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
2347
3237
|
import { createHash } from "crypto";
|
|
2348
|
-
import { existsSync, mkdirSync as mkdirSync2, readFileSync as
|
|
3238
|
+
import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2349
3239
|
import { homedir } from "os";
|
|
2350
3240
|
import { join as join2 } from "path";
|
|
2351
3241
|
function stateDir() {
|
|
@@ -2368,7 +3258,7 @@ function orgKey(opts) {
|
|
|
2368
3258
|
const key = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY;
|
|
2369
3259
|
if (key) return `key:${createHash("sha256").update(key).digest("hex").slice(0, 12)}`;
|
|
2370
3260
|
try {
|
|
2371
|
-
const raw = JSON.parse(
|
|
3261
|
+
const raw = JSON.parse(readFileSync3(join2(stateDir(), "credentials.json"), "utf8"));
|
|
2372
3262
|
const org2 = raw?.orgId ?? raw?.orgSlug;
|
|
2373
3263
|
if (org2) return `org:${org2}`;
|
|
2374
3264
|
} catch {
|
|
@@ -2377,7 +3267,7 @@ function orgKey(opts) {
|
|
|
2377
3267
|
}
|
|
2378
3268
|
function readStore() {
|
|
2379
3269
|
try {
|
|
2380
|
-
const parsed = JSON.parse(
|
|
3270
|
+
const parsed = JSON.parse(readFileSync3(statePath(), "utf8"));
|
|
2381
3271
|
if (typeof parsed !== "object" || parsed === null) return {};
|
|
2382
3272
|
return parsed;
|
|
2383
3273
|
} catch {
|
|
@@ -2445,6 +3335,55 @@ function shortId(id) {
|
|
|
2445
3335
|
return id.length > 8 ? `${id.slice(0, 4)}\u2026` : id;
|
|
2446
3336
|
}
|
|
2447
3337
|
|
|
3338
|
+
// src/sandbox-billing.ts
|
|
3339
|
+
function printTable(header, rows) {
|
|
3340
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
3341
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
|
|
3342
|
+
console.log(line(header));
|
|
3343
|
+
for (const row of rows) console.log(line(row));
|
|
3344
|
+
}
|
|
3345
|
+
function printCosts(c, customerOnly) {
|
|
3346
|
+
if (customerOnly) console.log("customer sandboxes only");
|
|
3347
|
+
printTable(
|
|
3348
|
+
["PROVIDER", "SANDBOXES", "RUNNING", "RUNNING COST", "SETTLED", "TOTAL"],
|
|
3349
|
+
[
|
|
3350
|
+
[
|
|
3351
|
+
"all",
|
|
3352
|
+
String(c.running.count + c.settled.count),
|
|
3353
|
+
String(c.running.count),
|
|
3354
|
+
formatMoney(c.running.costUsd),
|
|
3355
|
+
`${c.settled.count} \xB7 ${formatMoney(c.settled.costUsd)}`,
|
|
3356
|
+
formatMoney(c.totalUsd)
|
|
3357
|
+
],
|
|
3358
|
+
...c.byProvider.map((p2) => [
|
|
3359
|
+
safeTerm(p2.provider),
|
|
3360
|
+
String(p2.count),
|
|
3361
|
+
p2.running ? String(p2.running.count) : "\u2014",
|
|
3362
|
+
p2.running ? formatMoney(p2.running.costUsd) : "\u2014",
|
|
3363
|
+
p2.settled ? `${p2.settled.count} \xB7 ${formatMoney(p2.settled.costUsd)}` : "\u2014",
|
|
3364
|
+
formatMoney(p2.costUsd)
|
|
3365
|
+
])
|
|
3366
|
+
]
|
|
3367
|
+
);
|
|
3368
|
+
if (c.currency !== "USD") console.log(`currency: ${safeTerm(c.currency)}`);
|
|
3369
|
+
}
|
|
3370
|
+
function registerBillingCommands(group, common2, deps) {
|
|
3371
|
+
common2(
|
|
3372
|
+
group.command("costs").description("Show the org's sandbox spend: running, settled and per provider").option("--customer-only", "exclude idle platform sandboxes (warm pool, CI sync, snapshot builds); Actions job sandboxes stay")
|
|
3373
|
+
).action(async (opts) => {
|
|
3374
|
+
try {
|
|
3375
|
+
const c = await deps.client(opts);
|
|
3376
|
+
const res = await c.get(
|
|
3377
|
+
"/api/v1/sandboxes/costs",
|
|
3378
|
+
opts.customerOnly ? { customerOnly: "true" } : void 0
|
|
3379
|
+
);
|
|
3380
|
+
deps.output(opts, res, (data) => printCosts(data, opts.customerOnly === true));
|
|
3381
|
+
} catch (e) {
|
|
3382
|
+
deps.fail(e, opts);
|
|
3383
|
+
}
|
|
3384
|
+
});
|
|
3385
|
+
}
|
|
3386
|
+
|
|
2448
3387
|
// src/sandboxes.ts
|
|
2449
3388
|
function shellQuote(arg) {
|
|
2450
3389
|
return `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
@@ -2461,16 +3400,16 @@ function formatLocalTime(iso) {
|
|
|
2461
3400
|
function printSandbox(s, verbose = false) {
|
|
2462
3401
|
const p2 = s.placement;
|
|
2463
3402
|
console.log(
|
|
2464
|
-
`${
|
|
3403
|
+
`${pc10.cyan(s.id)} ${s.status} ${p2?.box?.provider ?? s.provider ?? "\u2014"} ${p2?.size ?? "\u2014"} ${p2 ? shortRate(p2.rate) : "\u2014"}`
|
|
2465
3404
|
);
|
|
2466
3405
|
if (s.label) {
|
|
2467
3406
|
console.log(` label: ${s.label} created: ${formatLocalTime(s.createdAt)}`);
|
|
2468
3407
|
}
|
|
2469
|
-
if (s.destroyError) console.log(` destroyError: ${
|
|
3408
|
+
if (s.destroyError) console.log(` destroyError: ${pc10.red(s.destroyError)}`);
|
|
2470
3409
|
if (!verbose) return;
|
|
2471
3410
|
console.log(` providerSandboxId: ${s.providerSandboxId ?? "\u2014"} commands: ${s.commandCount}`);
|
|
2472
3411
|
if (s.image !== void 0) {
|
|
2473
|
-
console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${
|
|
3412
|
+
console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc10.dim(`(requested: ${s.requestedImage})`)}` : ""}`);
|
|
2474
3413
|
}
|
|
2475
3414
|
if (p2) {
|
|
2476
3415
|
const box = p2.box ? ` / ${p2.box.sizeName ?? "custom"}${p2.box.resources ? ` (${p2.box.resources.cpus ?? "?"} vCPU / ${p2.box.resources.memoryMb ?? "?"} MB)` : ""}` : "";
|
|
@@ -2488,7 +3427,7 @@ function printSandbox(s, verbose = false) {
|
|
|
2488
3427
|
var perHour = (n) => n === void 0 ? "\u2014" : formatRateAllUnits(rateAllUnits({ usd: n, per: "hour" }));
|
|
2489
3428
|
var usdAmount = (n) => n === void 0 ? "\u2014" : formatMoney(n);
|
|
2490
3429
|
function printQuote(q, timeoutMs) {
|
|
2491
|
-
console.log(`quote: ${q.ok ?
|
|
3430
|
+
console.log(`quote: ${q.ok ? pc10.green("ok") : pc10.red(q.reason ?? "unfillable")}`);
|
|
2492
3431
|
const box = q.placement?.box;
|
|
2493
3432
|
console.log(
|
|
2494
3433
|
` size: ${q.placement?.size ?? "\u2014"} provider: ${q.placement?.provider ?? "\u2014"}` + (box ? ` box: ${box.sizeName ?? "custom"} (${box.provider}${box.resources ? `, ${box.resources.cpus ?? "?"} vCPU / ${box.resources.memoryMb ?? "?"} MB` : ""})` : "")
|
|
@@ -2507,17 +3446,17 @@ function printQuote(q, timeoutMs) {
|
|
|
2507
3446
|
);
|
|
2508
3447
|
console.log(` cap: ${q.maxPrice ? formatUsdPer(q.maxPrice) : perHour(q.marketCapUsdPerHour)}`);
|
|
2509
3448
|
console.log(` protection limit: ${perHour(q.protectionLimitUsdPerHour)}`);
|
|
2510
|
-
if (!q.ok && q.topUpPath) console.log(` ${
|
|
2511
|
-
if (q.liveAskDepth !== void 0) console.log(` ${
|
|
3449
|
+
if (!q.ok && q.topUpPath) console.log(` ${pc10.dim(`\u2192 ${q.topUpPath}`)}`);
|
|
3450
|
+
if (q.liveAskDepth !== void 0) console.log(` ${pc10.dim(`live asks: ${q.liveAskDepth}`)}`);
|
|
2512
3451
|
}
|
|
2513
3452
|
function printProcess(p2) {
|
|
2514
3453
|
const exit = p2.status === "exited" ? `exit=${p2.exitCode ?? "?"}${p2.signal ? ` (${p2.signal})` : ""}` : "";
|
|
2515
3454
|
const stdin = p2.stdin && p2.status === "running" ? " [stdin open]" : "";
|
|
2516
|
-
console.log(`${
|
|
3455
|
+
console.log(`${pc10.cyan(p2.jobId)} ${p2.status}${exit ? " " + exit : ""}${stdin} ${p2.command}`);
|
|
2517
3456
|
}
|
|
2518
3457
|
function printSnapshot(s) {
|
|
2519
|
-
const state = s.deletedAt !== null ? ` ${
|
|
2520
|
-
console.log(`${
|
|
3458
|
+
const state = s.deletedAt !== null ? ` ${pc10.dim(`(deleted ${s.deletedAt})`)}` : "";
|
|
3459
|
+
console.log(`${pc10.cyan(s.id)} ${s.providerSnapshotId}${state}`);
|
|
2521
3460
|
console.log(
|
|
2522
3461
|
` provider: ${s.provider}${s.region ? ` (${s.region})` : ""} label: ${s.label ?? "\u2014"} created: ${s.createdAt}${s.expiresAt ? ` expires: ${s.expiresAt}` : ""}`
|
|
2523
3462
|
);
|
|
@@ -2620,7 +3559,7 @@ function resolveSandbox(argId, opts) {
|
|
|
2620
3559
|
if (!r) throw new Error(NO_INSTANCE_HINT);
|
|
2621
3560
|
if (r.source !== "argument" && !opts.json && !opts.quiet) {
|
|
2622
3561
|
console.error(
|
|
2623
|
-
|
|
3562
|
+
pc10.dim(
|
|
2624
3563
|
`instance ${shortId(r.id)} (${r.source === "env" ? "COMPUTE_INSTANCE" : `current for ${r.dir}`})`
|
|
2625
3564
|
)
|
|
2626
3565
|
);
|
|
@@ -2631,7 +3570,7 @@ function resolveSandbox(argId, opts) {
|
|
|
2631
3570
|
clearStale: (error) => {
|
|
2632
3571
|
if (r.source === "file" && error instanceof PlatformApiError && error.status === 404 && readFileCurrent(org2) === r.id) {
|
|
2633
3572
|
clearCurrentInstance(org2);
|
|
2634
|
-
console.error(
|
|
3573
|
+
console.error(pc10.dim(`cleared stale current instance ${shortId(r.id)}`));
|
|
2635
3574
|
}
|
|
2636
3575
|
}
|
|
2637
3576
|
};
|
|
@@ -2685,6 +3624,24 @@ function fmtTimeout(ms) {
|
|
|
2685
3624
|
return `${ms}ms`;
|
|
2686
3625
|
}
|
|
2687
3626
|
var PLATFORM_DEFAULT_TIMEOUT_MS = 30 * 6e4;
|
|
3627
|
+
var LIST_SORTS = ["created", "name", "cost", "runtime"];
|
|
3628
|
+
function listQuery(opts) {
|
|
3629
|
+
if (opts.sort !== void 0 && !LIST_SORTS.includes(opts.sort)) {
|
|
3630
|
+
throw new Error(`--sort must be one of ${LIST_SORTS.join(", ")}`);
|
|
3631
|
+
}
|
|
3632
|
+
if (opts.direction !== void 0 && opts.direction !== "asc" && opts.direction !== "desc") {
|
|
3633
|
+
throw new Error("--direction must be asc or desc");
|
|
3634
|
+
}
|
|
3635
|
+
return {
|
|
3636
|
+
status: opts.status,
|
|
3637
|
+
customerOnly: opts.customerOnly ? "true" : void 0,
|
|
3638
|
+
q: opts.search,
|
|
3639
|
+
sort: opts.sort,
|
|
3640
|
+
direction: opts.direction,
|
|
3641
|
+
limit: opts.limit,
|
|
3642
|
+
cursor: opts.cursor
|
|
3643
|
+
};
|
|
3644
|
+
}
|
|
2688
3645
|
function registerSandboxesCommands(program2) {
|
|
2689
3646
|
const cmd = program2.command("instances").alias("sandboxes").alias("sbx").description("Create and drive compute instances through the platform").enablePositionalOptions().configureOutput({ outputError: usageErrorOutput });
|
|
2690
3647
|
addCreateFlags(
|
|
@@ -2697,7 +3654,7 @@ function registerSandboxesCommands(program2) {
|
|
|
2697
3654
|
if (opts.use !== false) {
|
|
2698
3655
|
setCurrentInstance(res.sandbox.id, orgKey(opts));
|
|
2699
3656
|
if (!opts.json && !opts.quiet) {
|
|
2700
|
-
console.error(
|
|
3657
|
+
console.error(pc10.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));
|
|
2701
3658
|
}
|
|
2702
3659
|
}
|
|
2703
3660
|
emitResult(opts, res.sandbox, (s) => s.id, (s) => printSandbox(s, opts.verbose));
|
|
@@ -2734,13 +3691,13 @@ function registerSandboxesCommands(program2) {
|
|
|
2734
3691
|
fail(e, opts);
|
|
2735
3692
|
}
|
|
2736
3693
|
});
|
|
2737
|
-
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) => {
|
|
3694
|
+
cmd.command("list").description("List sandboxes").option("--status <status>", "active (not destroyed) | creating | running | destroyed").option("--customer-only", "exclude idle platform sandboxes (warm pool, CI sync, snapshot builds); Actions job sandboxes stay").option("--search <text>", "match label, id, provider, provider sandbox id or product (Sandboxes, Actions)").option("--sort <column>", "created (default, newest first) | name | cost | runtime").option("--direction <dir>", "asc | desc (default: asc for name, desc for the others)").option("--limit <n>", "page size").option("--cursor <cursor>", "page cursor from a previous response (pass the same --sort and --direction)").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) => {
|
|
2738
3695
|
try {
|
|
2739
3696
|
checkQuietJson(opts);
|
|
2740
3697
|
const c = await client(opts);
|
|
2741
3698
|
const res = await c.get(
|
|
2742
3699
|
"/api/v1/sandboxes",
|
|
2743
|
-
|
|
3700
|
+
listQuery(opts)
|
|
2744
3701
|
);
|
|
2745
3702
|
emitResult(
|
|
2746
3703
|
opts,
|
|
@@ -2748,7 +3705,7 @@ function registerSandboxesCommands(program2) {
|
|
|
2748
3705
|
(page) => page.sandboxes.map((s) => s.id).join("\n"),
|
|
2749
3706
|
(page) => {
|
|
2750
3707
|
page.sandboxes.forEach((s) => printSandbox(s, opts.verbose));
|
|
2751
|
-
if (page.nextCursor) console.log(
|
|
3708
|
+
if (page.nextCursor) console.log(pc10.dim(`nextCursor: ${page.nextCursor}`));
|
|
2752
3709
|
}
|
|
2753
3710
|
);
|
|
2754
3711
|
} catch (e) {
|
|
@@ -2821,7 +3778,7 @@ function registerSandboxesCommands(program2) {
|
|
|
2821
3778
|
if (readFileCurrent(org2) === resolved.id) {
|
|
2822
3779
|
clearCurrentInstance(org2);
|
|
2823
3780
|
if (!opts.json) {
|
|
2824
|
-
console.error(
|
|
3781
|
+
console.error(pc10.dim(`cleared current instance ${shortId(resolved.id)}`));
|
|
2825
3782
|
}
|
|
2826
3783
|
}
|
|
2827
3784
|
output(opts, res.sandbox, printSandbox);
|
|
@@ -2840,9 +3797,9 @@ function registerSandboxesCommands(program2) {
|
|
|
2840
3797
|
if (opts.keep && opts.detach) throw new Error("--keep and --detach are mutually exclusive.");
|
|
2841
3798
|
const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
|
|
2842
3799
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2843
|
-
const
|
|
2844
|
-
if (
|
|
2845
|
-
await runInstanceCommand(
|
|
3800
|
+
const command2 = lead.command;
|
|
3801
|
+
if (command2.length === 0) throw new Error("missing command to run");
|
|
3802
|
+
await runInstanceCommand(command2, opts);
|
|
2846
3803
|
} catch (e) {
|
|
2847
3804
|
fail(e, opts);
|
|
2848
3805
|
}
|
|
@@ -2857,15 +3814,15 @@ function registerSandboxesCommands(program2) {
|
|
|
2857
3814
|
}
|
|
2858
3815
|
const lead = takeLeadingOptions(rawCommand, SERVE_LEAD_OPTS);
|
|
2859
3816
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2860
|
-
const
|
|
2861
|
-
if (
|
|
3817
|
+
const command2 = lead.command;
|
|
3818
|
+
if (command2.length === 0) throw new Error("missing command to serve");
|
|
2862
3819
|
if (opts.port === void 0) throw new Error("--port is required");
|
|
2863
3820
|
const port = Number(opts.port);
|
|
2864
3821
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
2865
3822
|
throw new Error("--port must be an integer between 1 and 65535");
|
|
2866
3823
|
}
|
|
2867
3824
|
const resolved = resolveSandbox(argId, opts);
|
|
2868
|
-
await serveInstanceCommand(resolved.id,
|
|
3825
|
+
await serveInstanceCommand(resolved.id, command2, port, opts);
|
|
2869
3826
|
} catch (e) {
|
|
2870
3827
|
fail(e, opts);
|
|
2871
3828
|
}
|
|
@@ -2879,14 +3836,14 @@ function registerSandboxesCommands(program2) {
|
|
|
2879
3836
|
}
|
|
2880
3837
|
const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
|
|
2881
3838
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2882
|
-
const
|
|
2883
|
-
if (
|
|
3839
|
+
const command2 = lead.command;
|
|
3840
|
+
if (command2.length === 0) throw new Error("missing command to run");
|
|
2884
3841
|
const resolved = resolveSandbox(argId, opts);
|
|
2885
3842
|
const c = await client(opts);
|
|
2886
3843
|
const res = await c.post(
|
|
2887
3844
|
`/api/v1/sandboxes/${resolved.id}/commands`,
|
|
2888
3845
|
{
|
|
2889
|
-
command:
|
|
3846
|
+
command: command2.map(shellQuote).join(" "),
|
|
2890
3847
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
2891
3848
|
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
|
|
2892
3849
|
...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
|
|
@@ -2915,14 +3872,14 @@ function registerSandboxesCommands(program2) {
|
|
|
2915
3872
|
const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);
|
|
2916
3873
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2917
3874
|
checkQuietJson(opts);
|
|
2918
|
-
const
|
|
2919
|
-
if (
|
|
3875
|
+
const command2 = lead.command;
|
|
3876
|
+
if (command2.length === 0) throw new Error("missing command to spawn");
|
|
2920
3877
|
const resolved = resolveSandbox(argId, opts);
|
|
2921
3878
|
const c = await client(opts);
|
|
2922
3879
|
const res = await c.post(
|
|
2923
3880
|
`/api/v1/sandboxes/${resolved.id}/processes`,
|
|
2924
3881
|
{
|
|
2925
|
-
command:
|
|
3882
|
+
command: command2.map(shellQuote).join(" "),
|
|
2926
3883
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
2927
3884
|
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
|
|
2928
3885
|
...opts.stdin ? { stdin: true } : {}
|
|
@@ -3014,7 +3971,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3014
3971
|
data = opts.base64 ? piped.toString("base64") : piped.toString("utf8");
|
|
3015
3972
|
}
|
|
3016
3973
|
if (data === void 0 || data === "") {
|
|
3017
|
-
console.error(
|
|
3974
|
+
console.error(pc10.red("Pass --data, --file, or pipe stdin"));
|
|
3018
3975
|
process.exit(1);
|
|
3019
3976
|
}
|
|
3020
3977
|
if (opts.base64 && opts.data !== void 0) {
|
|
@@ -3062,7 +4019,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3062
4019
|
output(opts, res, (view) => {
|
|
3063
4020
|
if (view.type === "directory") {
|
|
3064
4021
|
for (const e of view.entries) {
|
|
3065
|
-
console.log(`${e.type === "directory" ?
|
|
4022
|
+
console.log(`${e.type === "directory" ? pc10.blue("d") : " "} ${e.name}${e.size !== void 0 ? ` ${pc10.dim(String(e.size))}` : ""}`);
|
|
3066
4023
|
}
|
|
3067
4024
|
} else {
|
|
3068
4025
|
console.log(`${view.path} file ${view.content.length} chars`);
|
|
@@ -3089,7 +4046,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3089
4046
|
const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, { path: p2 });
|
|
3090
4047
|
output(opts, res, (view) => {
|
|
3091
4048
|
if (view.type !== "file") {
|
|
3092
|
-
console.error(
|
|
4049
|
+
console.error(pc10.red(`${view.path} is a directory`));
|
|
3093
4050
|
process.exit(1);
|
|
3094
4051
|
}
|
|
3095
4052
|
process.stdout.write(view.content);
|
|
@@ -3126,7 +4083,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3126
4083
|
});
|
|
3127
4084
|
}
|
|
3128
4085
|
if (content === void 0) {
|
|
3129
|
-
console.error(
|
|
4086
|
+
console.error(pc10.red("Pass --content, --file, or pipe stdin"));
|
|
3130
4087
|
process.exit(1);
|
|
3131
4088
|
}
|
|
3132
4089
|
const c = await client(opts);
|
|
@@ -3246,12 +4203,9 @@ function registerSandboxesCommands(program2) {
|
|
|
3246
4203
|
for (const sub of cmd.commands) {
|
|
3247
4204
|
sub.option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)");
|
|
3248
4205
|
}
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
(sub) => sub.option("--api-key <key>", "platform API key (or COMPUTE_API_KEY)").option("--base-url <url>", "platform base URL").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "allow non-computesdk.com base URLs").option("--json", "print the raw response"),
|
|
3253
|
-
{ client, fail, output, usageErrorOutput }
|
|
3254
|
-
);
|
|
4206
|
+
const nestedCommon = (sub) => sub.option("--api-key <key>", "platform API key (or COMPUTE_API_KEY)").option("--base-url <url>", "platform base URL").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "allow non-computesdk.com base URLs").option("--json", "print the raw response");
|
|
4207
|
+
registerSettingsCommands(cmd, "sandboxes", nestedCommon, { client, fail, output, usageErrorOutput });
|
|
4208
|
+
registerBillingCommands(cmd, nestedCommon, { client, fail, output });
|
|
3255
4209
|
}
|
|
3256
4210
|
async function followProcess(c, sandboxId, jobId) {
|
|
3257
4211
|
let exitCode = 0;
|
|
@@ -3265,11 +4219,11 @@ async function followProcess(c, sandboxId, jobId) {
|
|
|
3265
4219
|
exitCode = typeof payload.exitCode === "number" ? payload.exitCode : 128;
|
|
3266
4220
|
return finish();
|
|
3267
4221
|
} else if (event === "error") {
|
|
3268
|
-
console.error(
|
|
4222
|
+
console.error(pc10.red(`Error: ${String(payload.error ?? "stream error")}`));
|
|
3269
4223
|
return finish(1);
|
|
3270
4224
|
}
|
|
3271
4225
|
}
|
|
3272
|
-
console.error(
|
|
4226
|
+
console.error(pc10.yellow("stream ended before the process exited"));
|
|
3273
4227
|
return finish(2);
|
|
3274
4228
|
function finish(code) {
|
|
3275
4229
|
if (code !== void 0) exitCode = code;
|
|
@@ -3285,15 +4239,15 @@ function printDetachSummary(sandboxId, jobId, timeoutText) {
|
|
|
3285
4239
|
function runTimeoutText(opts) {
|
|
3286
4240
|
return opts.timeoutMs ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}` : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;
|
|
3287
4241
|
}
|
|
3288
|
-
async function runInstanceCommand(
|
|
4242
|
+
async function runInstanceCommand(command2, opts) {
|
|
3289
4243
|
const c = await client(opts);
|
|
3290
4244
|
const created = await c.post("/api/v1/sandboxes", buildCreateBody(opts));
|
|
3291
4245
|
const sandbox = created.sandbox;
|
|
3292
4246
|
const org2 = orgKey(opts);
|
|
3293
|
-
console.error(
|
|
4247
|
+
console.error(pc10.dim(`instance ${sandbox.id}`));
|
|
3294
4248
|
const spawned = await c.post(
|
|
3295
4249
|
`/api/v1/sandboxes/${sandbox.id}/processes`,
|
|
3296
|
-
{ command:
|
|
4250
|
+
{ command: command2.map(shellQuote).join(" ") }
|
|
3297
4251
|
).catch(async (e) => {
|
|
3298
4252
|
try {
|
|
3299
4253
|
await c.del(`/api/v1/sandboxes/${sandbox.id}`);
|
|
@@ -3368,7 +4322,7 @@ async function runInstanceCommand(command, opts) {
|
|
|
3368
4322
|
setCurrentInstance(sandbox.id, org2);
|
|
3369
4323
|
if (opts.quiet) console.log(sandbox.id);
|
|
3370
4324
|
else {
|
|
3371
|
-
console.error(
|
|
4325
|
+
console.error(pc10.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));
|
|
3372
4326
|
console.log(sandbox.id);
|
|
3373
4327
|
}
|
|
3374
4328
|
} else {
|
|
@@ -3376,7 +4330,7 @@ async function runInstanceCommand(command, opts) {
|
|
|
3376
4330
|
await c.del(`/api/v1/sandboxes/${sandbox.id}`);
|
|
3377
4331
|
} catch (e) {
|
|
3378
4332
|
console.error(
|
|
3379
|
-
|
|
4333
|
+
pc10.red(`destroy failed for ${sandbox.id}: ${e instanceof Error ? e.message : String(e)}`)
|
|
3380
4334
|
);
|
|
3381
4335
|
if (exitCode === null || exitCode === 0) exitCode = 1;
|
|
3382
4336
|
}
|
|
@@ -3388,12 +4342,12 @@ async function runInstanceCommand(command, opts) {
|
|
|
3388
4342
|
}
|
|
3389
4343
|
var SERVE_POLL_MS = 3e4;
|
|
3390
4344
|
var SERVE_DEFAULT_WAIT_MS = 12e4;
|
|
3391
|
-
async function serveInstanceCommand(id,
|
|
4345
|
+
async function serveInstanceCommand(id, command2, port, opts) {
|
|
3392
4346
|
const c = await client(opts);
|
|
3393
4347
|
const spawned = await c.post(
|
|
3394
4348
|
`/api/v1/sandboxes/${id}/processes`,
|
|
3395
4349
|
{
|
|
3396
|
-
command:
|
|
4350
|
+
command: command2.map(shellQuote).join(" "),
|
|
3397
4351
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
3398
4352
|
...opts.env?.length ? { env: parseInputs(opts.env) } : {}
|
|
3399
4353
|
}
|
|
@@ -3404,7 +4358,7 @@ async function serveInstanceCommand(id, command, port, opts) {
|
|
|
3404
4358
|
if (!opts.json) {
|
|
3405
4359
|
const logs = `${proc.stdout}${proc.stderr}`.trimEnd().split("\n");
|
|
3406
4360
|
if (logs.length > 0 && logs[0] !== "") {
|
|
3407
|
-
console.error(
|
|
4361
|
+
console.error(pc10.dim("--- last log lines ---"));
|
|
3408
4362
|
for (const line of logs.slice(-50)) console.error(safeTerm(line));
|
|
3409
4363
|
}
|
|
3410
4364
|
}
|
|
@@ -3459,9 +4413,9 @@ async function serveInstanceCommand(id, command, port, opts) {
|
|
|
3459
4413
|
});
|
|
3460
4414
|
}
|
|
3461
4415
|
function printServeJobFooter(sandboxId, jobId) {
|
|
3462
|
-
console.error(
|
|
3463
|
-
console.error(
|
|
3464
|
-
console.error(
|
|
4416
|
+
console.error(pc10.dim(` job ${jobId}`));
|
|
4417
|
+
console.error(pc10.dim(` logs: compute instances logs ${sandboxId} ${jobId}`));
|
|
4418
|
+
console.error(pc10.dim(` kill: compute instances kill ${sandboxId} ${jobId}`));
|
|
3465
4419
|
}
|
|
3466
4420
|
var CP_PROGRESS_MIN_BYTES = 10 * 1024 * 1024;
|
|
3467
4421
|
function assertTransferUrl(raw) {
|
|
@@ -3619,8 +4573,8 @@ function formatBytes(n) {
|
|
|
3619
4573
|
}
|
|
3620
4574
|
|
|
3621
4575
|
// src/agents.ts
|
|
3622
|
-
import
|
|
3623
|
-
import { readFileSync as
|
|
4576
|
+
import pc11 from "picocolors";
|
|
4577
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
3624
4578
|
function formatLocalTime2(iso) {
|
|
3625
4579
|
if (iso === null) return "\u2014";
|
|
3626
4580
|
const d = new Date(iso);
|
|
@@ -3630,7 +4584,7 @@ function formatLocalTime2(iso) {
|
|
|
3630
4584
|
}
|
|
3631
4585
|
function printAgent(a) {
|
|
3632
4586
|
console.log(
|
|
3633
|
-
`${
|
|
4587
|
+
`${pc11.cyan(safeTerm(a.name))} ${a.id.slice(0, 8)} ${a.harness}${a.model ? ` ${safeTerm(a.model)}` : ""} sessions: ${a.sessionCount} created: ${formatLocalTime2(a.createdAt)}`
|
|
3634
4588
|
);
|
|
3635
4589
|
}
|
|
3636
4590
|
function printAgentDetail(a) {
|
|
@@ -3641,13 +4595,13 @@ function printAgentDetail(a) {
|
|
|
3641
4595
|
}
|
|
3642
4596
|
function printSession(s) {
|
|
3643
4597
|
console.log(
|
|
3644
|
-
`${
|
|
4598
|
+
`${pc11.cyan(s.id)} ${s.status} sandbox: ${s.sandboxId ?? "\u2014"} ${formatLocalTime2(s.createdAt)}${s.error ? ` ${pc11.red(safeTerm(s.error))}` : ""}`
|
|
3645
4599
|
);
|
|
3646
4600
|
}
|
|
3647
4601
|
function printEvent(e) {
|
|
3648
4602
|
const payload = e.payload ?? {};
|
|
3649
4603
|
if (e.kind === "user") {
|
|
3650
|
-
console.log(`${
|
|
4604
|
+
console.log(`${pc11.green("you")} #${e.seq} ${safeTerm(String(payload.message ?? ""))}`);
|
|
3651
4605
|
return;
|
|
3652
4606
|
}
|
|
3653
4607
|
if (e.kind === "turn") {
|
|
@@ -3655,12 +4609,12 @@ function printEvent(e) {
|
|
|
3655
4609
|
for (const ev of events) {
|
|
3656
4610
|
const o = ev;
|
|
3657
4611
|
const text = o.text ?? o.message ?? o.content;
|
|
3658
|
-
if (typeof text === "string") console.log(
|
|
3659
|
-
else console.log(
|
|
4612
|
+
if (typeof text === "string") console.log(pc11.dim(`#${e.seq}`) + ` ${safeTerm(text)}`);
|
|
4613
|
+
else console.log(pc11.dim(`#${e.seq} ${safeTerm(JSON.stringify(o))}`));
|
|
3660
4614
|
}
|
|
3661
4615
|
return;
|
|
3662
4616
|
}
|
|
3663
|
-
console.log(
|
|
4617
|
+
console.log(pc11.dim(`#${e.seq} ${e.kind} ${safeTerm(JSON.stringify(payload))}`));
|
|
3664
4618
|
}
|
|
3665
4619
|
function authOpts(cmd) {
|
|
3666
4620
|
return cmd.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("--org <slug>", "organization slug (or COMPUTE_ORG)").option("--json", "print the raw response");
|
|
@@ -3696,7 +4650,7 @@ function registerAgentsCommands(program2) {
|
|
|
3696
4650
|
).action(
|
|
3697
4651
|
async (name, opts) => {
|
|
3698
4652
|
try {
|
|
3699
|
-
const prompt = opts.prompt ?? (opts.promptFile ?
|
|
4653
|
+
const prompt = opts.prompt ?? (opts.promptFile ? readFileSync4(opts.promptFile, "utf8") : void 0);
|
|
3700
4654
|
if (!prompt?.trim()) fail(new Error("--prompt or --prompt-file is required"), opts);
|
|
3701
4655
|
const volume = opts.volumeDisk !== void 0 || opts.volumePath !== void 0 ? { diskId: opts.volumeDisk, path: opts.volumePath } : void 0;
|
|
3702
4656
|
const c = await client(opts);
|
|
@@ -3711,7 +4665,7 @@ function registerAgentsCommands(program2) {
|
|
|
3711
4665
|
});
|
|
3712
4666
|
output(opts, res, (r) => {
|
|
3713
4667
|
printAgentDetail(r.agent);
|
|
3714
|
-
console.error(
|
|
4668
|
+
console.error(pc11.dim(`agent ${r.agent.name} created \u2014 run it with \`compute agents run ${r.agent.name} "\u2026"\``));
|
|
3715
4669
|
});
|
|
3716
4670
|
} catch (e) {
|
|
3717
4671
|
fail(e, opts);
|
|
@@ -3734,7 +4688,7 @@ function registerAgentsCommands(program2) {
|
|
|
3734
4688
|
).action(
|
|
3735
4689
|
async (ref, opts) => {
|
|
3736
4690
|
try {
|
|
3737
|
-
const prompt = opts.prompt ?? (opts.promptFile ?
|
|
4691
|
+
const prompt = opts.prompt ?? (opts.promptFile ? readFileSync4(opts.promptFile, "utf8") : void 0);
|
|
3738
4692
|
const body = {
|
|
3739
4693
|
name: opts.name,
|
|
3740
4694
|
prompt,
|
|
@@ -3765,7 +4719,7 @@ function registerAgentsCommands(program2) {
|
|
|
3765
4719
|
const c = await client(opts);
|
|
3766
4720
|
if (!opts.yes) {
|
|
3767
4721
|
const res = await c.get(`/api/v1/agents/${encodeURIComponent(ref)}`);
|
|
3768
|
-
console.error(`Deleting agent ${
|
|
4722
|
+
console.error(`Deleting agent ${pc11.cyan(res.agent.name)} (${res.agent.id}). Pass -y to confirm.`);
|
|
3769
4723
|
process.exit(1);
|
|
3770
4724
|
}
|
|
3771
4725
|
await c.del(`/api/v1/agents/${encodeURIComponent(ref)}`);
|
|
@@ -3802,7 +4756,7 @@ function registerAgentsCommands(program2) {
|
|
|
3802
4756
|
output(opts, res, (r) => {
|
|
3803
4757
|
printSession(r.session);
|
|
3804
4758
|
for (const e of r.events) printEvent(e);
|
|
3805
|
-
console.error(
|
|
4759
|
+
console.error(pc11.dim(`session ${r.session.id} \u2014 continue with \`compute agents send ${r.session.id} "\u2026"\``));
|
|
3806
4760
|
});
|
|
3807
4761
|
} catch (e) {
|
|
3808
4762
|
fail(e, opts);
|
|
@@ -3888,11 +4842,625 @@ function registerAgentsCommands(program2) {
|
|
|
3888
4842
|
});
|
|
3889
4843
|
}
|
|
3890
4844
|
|
|
4845
|
+
// src/bench.ts
|
|
4846
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL3 } from "@computesdk/platform";
|
|
4847
|
+
|
|
4848
|
+
// src/net.ts
|
|
4849
|
+
function isFetchFailure(error) {
|
|
4850
|
+
return error instanceof TypeError && /fetch failed/i.test(error.message);
|
|
4851
|
+
}
|
|
4852
|
+
function describeFetchFailure(error, url) {
|
|
4853
|
+
let target = url;
|
|
4854
|
+
try {
|
|
4855
|
+
const parsed = new URL(url);
|
|
4856
|
+
target = `${parsed.origin}${parsed.pathname}`;
|
|
4857
|
+
} catch {
|
|
4858
|
+
}
|
|
4859
|
+
const cause = error.cause;
|
|
4860
|
+
const described = new TypeError(`fetch failed (${target})${cause instanceof Error ? `: ${cause.message}` : ""}`);
|
|
4861
|
+
described.cause = cause;
|
|
4862
|
+
return described;
|
|
4863
|
+
}
|
|
4864
|
+
function requestUrl(input) {
|
|
4865
|
+
if (typeof input === "string") return input;
|
|
4866
|
+
if (input instanceof URL) return input.href;
|
|
4867
|
+
return input.url;
|
|
4868
|
+
}
|
|
4869
|
+
function withFetchFailureContext(fetchImpl) {
|
|
4870
|
+
return async (input, init) => {
|
|
4871
|
+
try {
|
|
4872
|
+
return await fetchImpl(input, init);
|
|
4873
|
+
} catch (error) {
|
|
4874
|
+
if (isFetchFailure(error)) throw describeFetchFailure(error, requestUrl(input));
|
|
4875
|
+
throw error;
|
|
4876
|
+
}
|
|
4877
|
+
};
|
|
4878
|
+
}
|
|
4879
|
+
|
|
4880
|
+
// src/session.ts
|
|
4881
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL2, isSecurePlatformTransport as isSecurePlatformTransport2, isTrustedPlatformHost as isTrustedPlatformHost2 } from "@computesdk/platform";
|
|
4882
|
+
function envBaseUrl(env = process.env) {
|
|
4883
|
+
return env.COMPUTE_PLATFORM_URL || env.BENCHMARKS_PLATFORM_URL || void 0;
|
|
4884
|
+
}
|
|
4885
|
+
function assertComputeKeyDestination(baseUrl) {
|
|
4886
|
+
const url = baseUrl.replace(/\/+$/, "");
|
|
4887
|
+
if (!isTrustedPlatformHost2(url)) {
|
|
4888
|
+
throw new Error(
|
|
4889
|
+
`Refusing to send COMPUTE_API_KEY to ${url}: it is not a computesdk.com or localhost host. To use a key with a host you trust, set BENCHMARKS_PLATFORM_API_KEY for it instead.`
|
|
4890
|
+
);
|
|
4891
|
+
}
|
|
4892
|
+
if (!isSecurePlatformTransport2(url)) {
|
|
4893
|
+
throw new Error(`Refusing to send COMPUTE_API_KEY over plaintext HTTP to ${url}; use https://.`);
|
|
4894
|
+
}
|
|
4895
|
+
}
|
|
4896
|
+
function benchAuthOverrides(opts = {}, env = process.env) {
|
|
4897
|
+
const baseUrl = opts.baseUrl ?? envBaseUrl(env);
|
|
4898
|
+
const apiKey = env.COMPUTE_API_KEY || void 0;
|
|
4899
|
+
if (apiKey) assertComputeKeyDestination(baseUrl ?? DEFAULT_BASE_URL2);
|
|
4900
|
+
return { baseUrl, apiKey };
|
|
4901
|
+
}
|
|
4902
|
+
async function benchAuth(opts = {}) {
|
|
4903
|
+
const { resolveAuth } = await import("@benchsdk/cli");
|
|
4904
|
+
return resolveAuth(benchAuthOverrides(opts));
|
|
4905
|
+
}
|
|
4906
|
+
function errorReason(body) {
|
|
4907
|
+
if (typeof body !== "string" || body === "") return void 0;
|
|
4908
|
+
try {
|
|
4909
|
+
const parsed = JSON.parse(body);
|
|
4910
|
+
const reason = parsed.message ?? parsed.error;
|
|
4911
|
+
return typeof reason === "string" ? reason : void 0;
|
|
4912
|
+
} catch {
|
|
4913
|
+
return body.slice(0, 200);
|
|
4914
|
+
}
|
|
4915
|
+
}
|
|
4916
|
+
function httpStatus(error) {
|
|
4917
|
+
const status = error?.status;
|
|
4918
|
+
return typeof status === "number" ? status : void 0;
|
|
4919
|
+
}
|
|
4920
|
+
async function apiKeyOrganization(auth, apiKey) {
|
|
4921
|
+
const url = `${auth.apiBaseUrl}/actions/org`;
|
|
4922
|
+
let response;
|
|
4923
|
+
try {
|
|
4924
|
+
response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
|
|
4925
|
+
} catch (error) {
|
|
4926
|
+
throw isFetchFailure(error) ? describeFetchFailure(error, url) : error;
|
|
4927
|
+
}
|
|
4928
|
+
const text = await response.text();
|
|
4929
|
+
if (!response.ok) {
|
|
4930
|
+
const reason = errorReason(text);
|
|
4931
|
+
throw new Error(
|
|
4932
|
+
`This API key has no user identity, and its organization could not be read (${response.status}${reason ? `: ${reason}` : ""}).`
|
|
4933
|
+
);
|
|
4934
|
+
}
|
|
4935
|
+
const org2 = JSON.parse(text);
|
|
4936
|
+
return { id: org2.organizationId, name: org2.name, slug: org2.slug };
|
|
4937
|
+
}
|
|
4938
|
+
async function fetchWhoami(auth) {
|
|
4939
|
+
const { getMe } = await import("@benchsdk/cli");
|
|
4940
|
+
try {
|
|
4941
|
+
return await getMe(auth);
|
|
4942
|
+
} catch (error) {
|
|
4943
|
+
if (isFetchFailure(error)) throw describeFetchFailure(error, `${auth.apiBaseUrl}/me`);
|
|
4944
|
+
if (httpStatus(error) !== 401) throw error;
|
|
4945
|
+
const reason = errorReason(error.body);
|
|
4946
|
+
if (auth.apiKey && !auth.token && reason === "User credential required") {
|
|
4947
|
+
const org2 = await apiKeyOrganization(auth, auth.apiKey);
|
|
4948
|
+
return { user: null, activeOrganizationId: org2.id, organizations: [org2], credential: "api_key" };
|
|
4949
|
+
}
|
|
4950
|
+
throw new Error(
|
|
4951
|
+
`Authentication failed (401 Unauthorized)${reason ? `: ${reason}` : ""}. Check COMPUTE_API_KEY / the stored login, or run \`compute login\`.`
|
|
4952
|
+
);
|
|
4953
|
+
}
|
|
4954
|
+
}
|
|
4955
|
+
function formatWhoami(me) {
|
|
4956
|
+
const active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
4957
|
+
const who = me.user ? me.user.email ?? me.user.name ?? me.user.id : "API key (no user identity)";
|
|
4958
|
+
return [
|
|
4959
|
+
who,
|
|
4960
|
+
`active org: ${active ? `${active.slug} (${active.id})` : "\u2014"}${me.organizations.length > 1 ? " \u2014 change with `compute org use <slug>`" : ""}`
|
|
4961
|
+
];
|
|
4962
|
+
}
|
|
4963
|
+
|
|
4964
|
+
// src/bench.ts
|
|
4965
|
+
var BENCH_COMMANDS = /* @__PURE__ */ new Set(["bench", "benchmark"]);
|
|
4966
|
+
var RUNNER_VERBS = /* @__PURE__ */ new Set(["run", "check", "__manifest"]);
|
|
4967
|
+
function parseBenchDispatch(args) {
|
|
4968
|
+
let org2;
|
|
4969
|
+
let i = 0;
|
|
4970
|
+
while (i < args.length && !BENCH_COMMANDS.has(args[i])) {
|
|
4971
|
+
const arg = args[i];
|
|
4972
|
+
if (arg === "--org" && i + 1 < args.length) {
|
|
4973
|
+
org2 = args[i + 1];
|
|
4974
|
+
i += 2;
|
|
4975
|
+
} else if (arg.startsWith("--org=")) {
|
|
4976
|
+
org2 = arg.slice("--org=".length);
|
|
4977
|
+
i += 1;
|
|
4978
|
+
} else {
|
|
4979
|
+
return null;
|
|
4980
|
+
}
|
|
4981
|
+
}
|
|
4982
|
+
if (i >= args.length) return null;
|
|
4983
|
+
const argv = args.slice(i + 1);
|
|
4984
|
+
return org2 ? { argv, org: org2 } : { argv };
|
|
4985
|
+
}
|
|
4986
|
+
function baseUrlFlag(argv) {
|
|
4987
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
4988
|
+
const arg = argv[i];
|
|
4989
|
+
if (arg === "--") return void 0;
|
|
4990
|
+
if (arg === "--base-url") return argv[i + 1];
|
|
4991
|
+
if (arg.startsWith("--base-url=")) return arg.slice("--base-url=".length);
|
|
4992
|
+
}
|
|
4993
|
+
return void 0;
|
|
4994
|
+
}
|
|
4995
|
+
function hasOrgFlag(argv) {
|
|
4996
|
+
for (const arg of argv) {
|
|
4997
|
+
if (arg === "--") return false;
|
|
4998
|
+
if (arg === "--org" || arg.startsWith("--org=")) return true;
|
|
4999
|
+
}
|
|
5000
|
+
return false;
|
|
5001
|
+
}
|
|
5002
|
+
function benchInvocation(argv, env, computeOrg) {
|
|
5003
|
+
const out = {};
|
|
5004
|
+
if (env.COMPUTE_PLATFORM_URL && !env.BENCHMARKS_PLATFORM_URL) {
|
|
5005
|
+
out.BENCHMARKS_PLATFORM_URL = env.COMPUTE_PLATFORM_URL;
|
|
5006
|
+
}
|
|
5007
|
+
if (env.COMPUTE_API_KEY && !env.BENCHMARKS_PLATFORM_API_KEY) {
|
|
5008
|
+
assertComputeKeyDestination(
|
|
5009
|
+
baseUrlFlag(argv) || env.BENCHMARKS_PLATFORM_URL || env.COMPUTE_PLATFORM_URL || DEFAULT_BASE_URL3
|
|
5010
|
+
);
|
|
5011
|
+
out.BENCHMARKS_PLATFORM_API_KEY = env.COMPUTE_API_KEY;
|
|
5012
|
+
}
|
|
5013
|
+
const org2 = computeOrg || env.COMPUTE_ORG;
|
|
5014
|
+
if (!org2 || RUNNER_VERBS.has(argv[0]) || hasOrgFlag(argv)) return { argv, env: out };
|
|
5015
|
+
return { argv: ["--org", org2, ...argv], env: out };
|
|
5016
|
+
}
|
|
5017
|
+
async function runBench(dispatch) {
|
|
5018
|
+
const inv = benchInvocation(dispatch.argv, process.env, dispatch.org);
|
|
5019
|
+
Object.assign(process.env, inv.env);
|
|
5020
|
+
globalThis.fetch = withFetchFailureContext(globalThis.fetch);
|
|
5021
|
+
const { run } = await import("@benchsdk/runner");
|
|
5022
|
+
await run(inv.argv);
|
|
5023
|
+
}
|
|
5024
|
+
|
|
5025
|
+
// src/manifest.ts
|
|
5026
|
+
import { createRequire } from "module";
|
|
5027
|
+
import { existsSync as existsSync2, readFileSync as readFileSync5, realpathSync } from "fs";
|
|
5028
|
+
import { dirname as dirname2, join as join4, sep } from "path";
|
|
5029
|
+
var MANIFEST_COMMAND = "__manifest";
|
|
5030
|
+
function resolvedPackage(name, fromDir) {
|
|
5031
|
+
const require2 = createRequire(join4(fromDir, "noop.js"));
|
|
5032
|
+
let dir = dirname2(require2.resolve(name));
|
|
5033
|
+
for (; ; ) {
|
|
5034
|
+
const file = join4(dir, "package.json");
|
|
5035
|
+
if (existsSync2(file)) {
|
|
5036
|
+
const pkg = JSON.parse(readFileSync5(file, "utf-8"));
|
|
5037
|
+
if (pkg.name === name) return { dir, version: pkg.version };
|
|
5038
|
+
}
|
|
5039
|
+
const parent = dirname2(dir);
|
|
5040
|
+
if (parent === dir) throw new Error(`package.json for ${name} not found from ${fromDir}`);
|
|
5041
|
+
dir = parent;
|
|
5042
|
+
}
|
|
5043
|
+
}
|
|
5044
|
+
function isLinkedPackage(realDir) {
|
|
5045
|
+
return !realDir.split(sep).includes("node_modules");
|
|
5046
|
+
}
|
|
5047
|
+
function packageVersion(name, resolved) {
|
|
5048
|
+
const entry = { package: name, version: resolved.version };
|
|
5049
|
+
if (isLinkedPackage(realpathSync(resolved.dir))) {
|
|
5050
|
+
entry.linked = true;
|
|
5051
|
+
entry.released = false;
|
|
5052
|
+
}
|
|
5053
|
+
return entry;
|
|
5054
|
+
}
|
|
5055
|
+
function bundledBench(fromDir) {
|
|
5056
|
+
const runner = resolvedPackage("@benchsdk/runner", fromDir);
|
|
5057
|
+
const cli = resolvedPackage("@benchsdk/cli", runner.dir);
|
|
5058
|
+
return {
|
|
5059
|
+
runner: packageVersion("@benchsdk/runner", runner),
|
|
5060
|
+
cli: packageVersion("@benchsdk/cli", cli)
|
|
5061
|
+
};
|
|
5062
|
+
}
|
|
5063
|
+
function isHidden(cmd) {
|
|
5064
|
+
return cmd._hidden === true;
|
|
5065
|
+
}
|
|
5066
|
+
function flagsOf(cmd) {
|
|
5067
|
+
const flags = cmd.createHelp().visibleOptions(cmd).map((o) => o.long ?? o.short).filter((f) => Boolean(f));
|
|
5068
|
+
return [...new Set(flags)];
|
|
5069
|
+
}
|
|
5070
|
+
function argsOf(cmd) {
|
|
5071
|
+
return cmd.registeredArguments.map((a) => {
|
|
5072
|
+
const name = `${a.name()}${a.variadic ? "..." : ""}`;
|
|
5073
|
+
return a.required ? `<${name}>` : `[${name}]`;
|
|
5074
|
+
});
|
|
5075
|
+
}
|
|
5076
|
+
function summaryOf(cmd) {
|
|
5077
|
+
return (cmd.summary() || cmd.description()).split("\n")[0].trim();
|
|
5078
|
+
}
|
|
5079
|
+
function aliasPaths(names) {
|
|
5080
|
+
let paths = [[]];
|
|
5081
|
+
for (const choices of names) paths = paths.flatMap((p2) => choices.map((c) => [...p2, c]));
|
|
5082
|
+
return paths.slice(1);
|
|
5083
|
+
}
|
|
5084
|
+
function walk(cmd, ancestors, skip, out) {
|
|
5085
|
+
for (const sub of cmd.commands) {
|
|
5086
|
+
if (isHidden(sub) || ancestors.length === 0 && skip.has(sub.name())) continue;
|
|
5087
|
+
const names = [...ancestors, [sub.name(), ...sub.aliases()]];
|
|
5088
|
+
out.push({
|
|
5089
|
+
path: names.map((n) => n[0]),
|
|
5090
|
+
aliases: aliasPaths(names),
|
|
5091
|
+
args: argsOf(sub),
|
|
5092
|
+
flags: flagsOf(sub),
|
|
5093
|
+
summary: summaryOf(sub)
|
|
5094
|
+
});
|
|
5095
|
+
walk(sub, names, skip, out);
|
|
5096
|
+
}
|
|
5097
|
+
}
|
|
5098
|
+
function buildCliManifest(program2, options) {
|
|
5099
|
+
const [benchName, ...benchAliases] = [...BENCH_COMMANDS];
|
|
5100
|
+
const commands = [];
|
|
5101
|
+
walk(program2, [], /* @__PURE__ */ new Set([benchName]), commands);
|
|
5102
|
+
return {
|
|
5103
|
+
schemaVersion: 1,
|
|
5104
|
+
bin: "compute",
|
|
5105
|
+
package: "@computesdk/cli",
|
|
5106
|
+
version: options.version,
|
|
5107
|
+
source: { repo: "computesdk/computesdk", released: options.released },
|
|
5108
|
+
globalFlags: flagsOf(program2),
|
|
5109
|
+
commands,
|
|
5110
|
+
passthrough: {
|
|
5111
|
+
bench: {
|
|
5112
|
+
path: [benchName],
|
|
5113
|
+
aliases: benchAliases.map((a) => [a]),
|
|
5114
|
+
...bundledBench(options.packageDir)
|
|
5115
|
+
}
|
|
5116
|
+
}
|
|
5117
|
+
};
|
|
5118
|
+
}
|
|
5119
|
+
function manifestJson(manifest) {
|
|
5120
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
5121
|
+
`;
|
|
5122
|
+
}
|
|
5123
|
+
function manifestMatches(fileContent, generated) {
|
|
5124
|
+
let committed;
|
|
5125
|
+
try {
|
|
5126
|
+
committed = JSON.parse(fileContent);
|
|
5127
|
+
} catch {
|
|
5128
|
+
return false;
|
|
5129
|
+
}
|
|
5130
|
+
if (committed.source) delete committed.source.ref;
|
|
5131
|
+
return JSON.stringify(committed) === JSON.stringify(generated);
|
|
5132
|
+
}
|
|
5133
|
+
function registerManifestCommand(program2, options) {
|
|
5134
|
+
program2.command(MANIFEST_COMMAND, { hidden: true }).description("Print the command tree as JSON (for the benchmarks platform surface map)").option("--released", "mark the manifest as describing a version published to npm").option("--check <file>", "exit 1 unless <file> equals the generated manifest (ignoring source.ref)").action((opts) => {
|
|
5135
|
+
const manifest = buildCliManifest(program2, {
|
|
5136
|
+
version: options.version,
|
|
5137
|
+
released: Boolean(opts.released),
|
|
5138
|
+
packageDir: options.packageDir
|
|
5139
|
+
});
|
|
5140
|
+
if (opts.check) {
|
|
5141
|
+
if (!manifestMatches(readFileSync5(opts.check, "utf-8"), manifest)) {
|
|
5142
|
+
console.error(
|
|
5143
|
+
`${opts.check} is out of date. Regenerate it with \`pnpm --filter @computesdk/cli run manifest\`.`
|
|
5144
|
+
);
|
|
5145
|
+
process.exit(1);
|
|
5146
|
+
}
|
|
5147
|
+
console.log(`${opts.check} matches the ${manifest.commands.length}-command manifest.`);
|
|
5148
|
+
return;
|
|
5149
|
+
}
|
|
5150
|
+
process.stdout.write(manifestJson(manifest));
|
|
5151
|
+
});
|
|
5152
|
+
}
|
|
5153
|
+
|
|
5154
|
+
// src/org-members.ts
|
|
5155
|
+
import pc12 from "picocolors";
|
|
5156
|
+
var ORG_PATH = "/api/v1/organizations/current";
|
|
5157
|
+
var MEMBER_ROLES = ["member", "admin"];
|
|
5158
|
+
var USER_LOGIN_HINT = "This needs a user login, and org API keys have no user: run `compute login`, and drop --api-key / unset COMPUTE_API_KEY.";
|
|
5159
|
+
function isOrgApiKey(key) {
|
|
5160
|
+
return /^(bp|csdk)_/.test(key);
|
|
5161
|
+
}
|
|
5162
|
+
var segment = (id) => encodeURIComponent(id);
|
|
5163
|
+
function orgName(opts) {
|
|
5164
|
+
return opts.org || process.env.COMPUTE_ORG || void 0;
|
|
5165
|
+
}
|
|
5166
|
+
async function orgClient(opts) {
|
|
5167
|
+
return new ActionsClient(await resolveActionsAuth(opts));
|
|
5168
|
+
}
|
|
5169
|
+
async function userClient(opts, what) {
|
|
5170
|
+
const auth = await resolveActionsAuth(opts);
|
|
5171
|
+
if (isOrgApiKey(auth.apiKey)) {
|
|
5172
|
+
throw new PlatformClientError(
|
|
5173
|
+
"user_credential_required",
|
|
5174
|
+
`${what} needs a user login, and org API keys have no user. Run \`compute login\`, and drop --api-key / unset COMPUTE_API_KEY.`
|
|
5175
|
+
);
|
|
5176
|
+
}
|
|
5177
|
+
return new ActionsClient(auth);
|
|
5178
|
+
}
|
|
5179
|
+
function apiHint(error) {
|
|
5180
|
+
const body = error.body;
|
|
5181
|
+
if (body && typeof body === "object" && typeof body.hint === "string") {
|
|
5182
|
+
return body.hint;
|
|
5183
|
+
}
|
|
5184
|
+
return error.code === "user_credential_required" ? USER_LOGIN_HINT : void 0;
|
|
5185
|
+
}
|
|
5186
|
+
function fail2(error, opts = {}) {
|
|
5187
|
+
const hint = error instanceof PlatformApiError ? apiHint(error) : void 0;
|
|
5188
|
+
if (opts.json) {
|
|
5189
|
+
const envelope = toErrorEnvelope(error);
|
|
5190
|
+
if (hint) envelope.error.hint = hint;
|
|
5191
|
+
process.stderr.write(JSON.stringify(envelope) + "\n");
|
|
5192
|
+
} else if (error instanceof PlatformApiError) {
|
|
5193
|
+
const code = error.code !== codeForStatus(error.status) ? ` ${error.code}` : "";
|
|
5194
|
+
console.error(pc12.red(`Error (${error.status}${code}): ${error.message}`));
|
|
5195
|
+
if (hint) console.error(pc12.dim(`hint: ${hint}`));
|
|
5196
|
+
} else {
|
|
5197
|
+
console.error(pc12.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
|
|
5198
|
+
}
|
|
5199
|
+
process.exit(1);
|
|
5200
|
+
}
|
|
5201
|
+
function memberRole(role, ownerMessage) {
|
|
5202
|
+
if (role === "owner") throw new PlatformClientError("invalid_argument", ownerMessage);
|
|
5203
|
+
if (!MEMBER_ROLES.includes(role)) {
|
|
5204
|
+
throw new PlatformClientError("invalid_argument", `Invalid role "${role}" \u2014 use member or admin.`);
|
|
5205
|
+
}
|
|
5206
|
+
return role;
|
|
5207
|
+
}
|
|
5208
|
+
function printTable2(header, rows) {
|
|
5209
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
5210
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
|
|
5211
|
+
console.log(line(header));
|
|
5212
|
+
for (const row of rows) console.log(line(row));
|
|
5213
|
+
}
|
|
5214
|
+
function printMembers(res) {
|
|
5215
|
+
if (res.members.length === 0) {
|
|
5216
|
+
console.log("No members.");
|
|
5217
|
+
return;
|
|
5218
|
+
}
|
|
5219
|
+
printTable2(
|
|
5220
|
+
["EMAIL", "ROLE", "NAME", "MEMBER ID", "JOINED"],
|
|
5221
|
+
res.members.map((m) => [safeTerm(m.email), safeTerm(m.role), safeTerm(m.name ?? "\u2014"), safeTerm(m.id), safeTerm(m.createdAt)])
|
|
5222
|
+
);
|
|
5223
|
+
}
|
|
5224
|
+
function printOrgInvitations(res) {
|
|
5225
|
+
if (res.invitations.length === 0) {
|
|
5226
|
+
console.log("No pending invitations.");
|
|
5227
|
+
return;
|
|
5228
|
+
}
|
|
5229
|
+
printTable2(
|
|
5230
|
+
["ID", "EMAIL", "ROLE", "EXPIRES", "LINK"],
|
|
5231
|
+
res.invitations.map((i) => [safeTerm(i.id), safeTerm(i.email), safeTerm(i.role), safeTerm(i.expiresAt), safeTerm(i.url)])
|
|
5232
|
+
);
|
|
5233
|
+
}
|
|
5234
|
+
function printUserInvitations(res) {
|
|
5235
|
+
if (res.invitations.length === 0) {
|
|
5236
|
+
console.log("No pending invitations.");
|
|
5237
|
+
return;
|
|
5238
|
+
}
|
|
5239
|
+
printTable2(
|
|
5240
|
+
["ID", "ORG", "ROLE", "EXPIRES", "ORG NAME"],
|
|
5241
|
+
res.invitations.map((i) => [
|
|
5242
|
+
safeTerm(i.id),
|
|
5243
|
+
safeTerm(i.organization.slug),
|
|
5244
|
+
safeTerm(i.role),
|
|
5245
|
+
safeTerm(i.expiresAt),
|
|
5246
|
+
safeTerm(i.organization.name)
|
|
5247
|
+
])
|
|
5248
|
+
);
|
|
5249
|
+
console.log(pc12.dim("Accept with `compute invitations accept <id>`; decline with `compute invitations decline <id> -y`."));
|
|
5250
|
+
}
|
|
5251
|
+
function printInvitationDetail(inv) {
|
|
5252
|
+
const rows = [
|
|
5253
|
+
["invitation", safeTerm(inv.id)],
|
|
5254
|
+
["org", `${safeTerm(inv.organization.slug)} (${safeTerm(inv.organization.name)})`],
|
|
5255
|
+
["email", safeTerm(inv.email)],
|
|
5256
|
+
["role", safeTerm(inv.role)],
|
|
5257
|
+
["status", safeTerm(inv.status)],
|
|
5258
|
+
["expires", safeTerm(inv.expiresAt)],
|
|
5259
|
+
["link", safeTerm(inv.url)]
|
|
5260
|
+
];
|
|
5261
|
+
for (const [k, v] of rows) console.log(`${k.padEnd(10)} ${v}`);
|
|
5262
|
+
}
|
|
5263
|
+
function printInvite(res) {
|
|
5264
|
+
const inv = res.invitation;
|
|
5265
|
+
console.log(`Invited ${safeTerm(inv.email)} as ${safeTerm(inv.role)} (invitation ${safeTerm(inv.id)}, expires ${safeTerm(inv.expiresAt)}).`);
|
|
5266
|
+
if (res.emailSent) {
|
|
5267
|
+
console.log(`Emailed ${safeTerm(inv.email)} the invitation link.`);
|
|
5268
|
+
} else {
|
|
5269
|
+
const reason = res.emailError ? ` (${safeTerm(res.emailError)})` : "";
|
|
5270
|
+
console.log(pc12.yellow(`The invitation email was not sent${reason}; share the link instead.`));
|
|
5271
|
+
}
|
|
5272
|
+
console.log(`Link: ${safeTerm(inv.url)}`);
|
|
5273
|
+
}
|
|
5274
|
+
function findMember(members, ref) {
|
|
5275
|
+
const lower = ref.toLowerCase();
|
|
5276
|
+
return members.find((m) => m.id === ref) ?? members.find((m) => m.userId === ref) ?? members.find((m) => m.email.toLowerCase() === lower);
|
|
5277
|
+
}
|
|
5278
|
+
async function resolveMember(c, ref, opts) {
|
|
5279
|
+
const { members } = await c.get(`${ORG_PATH}/members`);
|
|
5280
|
+
const member = findMember(members, ref);
|
|
5281
|
+
if (!member) {
|
|
5282
|
+
const org2 = orgName(opts);
|
|
5283
|
+
throw new PlatformClientError("not_found", `No member ${ref} in ${org2 ? `org ${org2}` : "this organization"}.`);
|
|
5284
|
+
}
|
|
5285
|
+
return member;
|
|
5286
|
+
}
|
|
5287
|
+
var EMAIL = /^[^\s@]+@[^\s@]+$/;
|
|
5288
|
+
function command(parent, name) {
|
|
5289
|
+
return parent.command(name).configureOutput({ outputError: usageErrorOutput });
|
|
5290
|
+
}
|
|
5291
|
+
function common(cmd) {
|
|
5292
|
+
return cmd.option("--api-key <key>", "API key (default: $COMPUTE_API_KEY)").option("--base-url <url>", "API base URL (default: https://platform.computesdk.com)").option("--org <slug>", "organization slug for this command, for a user login (or $COMPUTE_ORG)").option("--allow-untrusted-host", "send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)").option("--json", "print machine-readable JSON");
|
|
5293
|
+
}
|
|
5294
|
+
function registerOrgMemberCommands(org2) {
|
|
5295
|
+
common(
|
|
5296
|
+
command(org2, "members").description("List the organization's members with their roles")
|
|
5297
|
+
).action(async (opts) => {
|
|
5298
|
+
try {
|
|
5299
|
+
const c = await orgClient(opts);
|
|
5300
|
+
output(opts, await c.get(`${ORG_PATH}/members`), printMembers);
|
|
5301
|
+
} catch (e) {
|
|
5302
|
+
fail2(e, opts);
|
|
5303
|
+
}
|
|
5304
|
+
});
|
|
5305
|
+
const invitations = common(
|
|
5306
|
+
command(org2, "invitations").description("List the organization's pending invitations with their links (owner/admin)").allowExcessArguments(false)
|
|
5307
|
+
).action(async (opts) => {
|
|
5308
|
+
try {
|
|
5309
|
+
const c = await orgClient(opts);
|
|
5310
|
+
output(opts, await c.get(`${ORG_PATH}/invitations`), printOrgInvitations);
|
|
5311
|
+
} catch (e) {
|
|
5312
|
+
fail2(e, opts);
|
|
5313
|
+
}
|
|
5314
|
+
});
|
|
5315
|
+
common(
|
|
5316
|
+
command(invitations, "cancel").description("Cancel a pending invitation; its link stops working (owner/admin)").argument("<invitationId>", "invitation id (see `compute org invitations`)").option("-y, --yes", "skip the confirmation")
|
|
5317
|
+
).action(async (invitationId, opts) => {
|
|
5318
|
+
try {
|
|
5319
|
+
await confirmWrite(`Cancel invitation ${invitationId}? Its link stops working.`, opts);
|
|
5320
|
+
const c = await orgClient(opts);
|
|
5321
|
+
const res = await c.del(`${ORG_PATH}/invitations/${segment(invitationId)}`);
|
|
5322
|
+
output(
|
|
5323
|
+
opts,
|
|
5324
|
+
res,
|
|
5325
|
+
(r) => console.log(`Cancelled the invitation for ${safeTerm(r.invitation.email)} (${r.invitation.id}).`)
|
|
5326
|
+
);
|
|
5327
|
+
} catch (e) {
|
|
5328
|
+
fail2(e, opts);
|
|
5329
|
+
}
|
|
5330
|
+
});
|
|
5331
|
+
common(
|
|
5332
|
+
command(org2, "invite").description("Invite someone to the organization by email and print the invite link (owner/admin)").argument("<email>", "email address to invite").option("--role <role>", "member | admin (owners are invited in the web app)", "member").option("-y, --yes", "skip the confirmation")
|
|
5333
|
+
).action(async (email, opts) => {
|
|
5334
|
+
try {
|
|
5335
|
+
const role = memberRole(opts.role, "Owner invitations require the web app.");
|
|
5336
|
+
if (!EMAIL.test(email)) {
|
|
5337
|
+
throw new PlatformClientError("invalid_argument", `Invalid email "${email}".`);
|
|
5338
|
+
}
|
|
5339
|
+
const target = orgName(opts);
|
|
5340
|
+
await confirmWrite(`Invite ${email} as ${role}${target ? ` to ${target}` : ""}?`, opts);
|
|
5341
|
+
const c = await orgClient(opts);
|
|
5342
|
+
output(opts, await c.post(`${ORG_PATH}/invitations`, { email, role }), printInvite);
|
|
5343
|
+
} catch (e) {
|
|
5344
|
+
fail2(e, opts);
|
|
5345
|
+
}
|
|
5346
|
+
});
|
|
5347
|
+
const member = command(org2, "member").description("Change a member's role or remove a member (owner/admin)");
|
|
5348
|
+
common(
|
|
5349
|
+
command(member, "set-role").description("Change a member's role between member and admin (owner roles change in the web app)").argument("<member>", "member id or email (see `compute org members`)").argument("<role>", "member | admin").option("-y, --yes", "skip the confirmation")
|
|
5350
|
+
).action(async (ref, roleArg, opts) => {
|
|
5351
|
+
try {
|
|
5352
|
+
const role = memberRole(roleArg, "Owner role changes require the web app.");
|
|
5353
|
+
const c = await orgClient(opts);
|
|
5354
|
+
const target = await resolveMember(c, ref, opts);
|
|
5355
|
+
await confirmWrite(`Change ${target.email} from ${target.role} to ${role}?`, opts);
|
|
5356
|
+
const res = await c.patch(`${ORG_PATH}/members/${segment(target.id)}`, { role });
|
|
5357
|
+
output(opts, res, (r) => console.log(`${safeTerm(r.member.email)} is now ${safeTerm(r.member.role)}.`));
|
|
5358
|
+
} catch (e) {
|
|
5359
|
+
fail2(e, opts);
|
|
5360
|
+
}
|
|
5361
|
+
});
|
|
5362
|
+
common(
|
|
5363
|
+
command(member, "remove").alias("rm").description("Remove a member from the organization (owners are removed in the web app)").argument("<member>", "member id or email (see `compute org members`)").option("-y, --yes", "skip the confirmation")
|
|
5364
|
+
).action(async (ref, opts) => {
|
|
5365
|
+
try {
|
|
5366
|
+
const c = await orgClient(opts);
|
|
5367
|
+
const target = await resolveMember(c, ref, opts);
|
|
5368
|
+
const org3 = orgName(opts);
|
|
5369
|
+
await confirmWrite(
|
|
5370
|
+
`Remove ${target.email} (${target.role}) from ${org3 ?? "the organization"}? They lose access at once.`,
|
|
5371
|
+
opts
|
|
5372
|
+
);
|
|
5373
|
+
const res = await c.del(`${ORG_PATH}/members/${segment(target.id)}`);
|
|
5374
|
+
output(
|
|
5375
|
+
opts,
|
|
5376
|
+
res,
|
|
5377
|
+
(r) => console.log(`Removed ${safeTerm(r.removed.email)} (${safeTerm(r.removed.role)}) from ${org3 ?? "the organization"}.`)
|
|
5378
|
+
);
|
|
5379
|
+
} catch (e) {
|
|
5380
|
+
fail2(e, opts);
|
|
5381
|
+
}
|
|
5382
|
+
});
|
|
5383
|
+
common(
|
|
5384
|
+
command(org2, "leave").description("Leave the organization (needs a user login; the last owner cannot leave)").option("-y, --yes", "skip the confirmation")
|
|
5385
|
+
).action(async (opts) => {
|
|
5386
|
+
try {
|
|
5387
|
+
const c = await userClient(opts, "`compute org leave`");
|
|
5388
|
+
const org3 = orgName(opts);
|
|
5389
|
+
await confirmWrite(`Leave ${org3 ?? "the active organization"}? You lose access to it at once.`, opts);
|
|
5390
|
+
const res = await c.post(`${ORG_PATH}/leave`, {});
|
|
5391
|
+
output(opts, res, () => {
|
|
5392
|
+
console.log(`Left ${org3 ?? "the organization"}.`);
|
|
5393
|
+
console.log(
|
|
5394
|
+
pc12.dim("If your login was granted for that organization, it no longer works: run `compute login` again.")
|
|
5395
|
+
);
|
|
5396
|
+
});
|
|
5397
|
+
} catch (e) {
|
|
5398
|
+
fail2(e, opts);
|
|
5399
|
+
}
|
|
5400
|
+
});
|
|
5401
|
+
}
|
|
5402
|
+
function registerInvitationsCommands(program2) {
|
|
5403
|
+
const invitations = common(
|
|
5404
|
+
command(program2, "invitations").description("Your pending invitations to other organizations (needs a user login)").allowExcessArguments(false)
|
|
5405
|
+
).action(async (opts) => {
|
|
5406
|
+
try {
|
|
5407
|
+
const c = await userClient(opts, "`compute invitations`");
|
|
5408
|
+
output(opts, await c.get("/api/v1/me/invitations"), printUserInvitations);
|
|
5409
|
+
} catch (e) {
|
|
5410
|
+
fail2(e, opts);
|
|
5411
|
+
}
|
|
5412
|
+
});
|
|
5413
|
+
common(
|
|
5414
|
+
command(invitations, "show").description("Show one of your invitations").argument("<invitationId>", "invitation id (see `compute invitations`)")
|
|
5415
|
+
).action(async (invitationId, opts) => {
|
|
5416
|
+
try {
|
|
5417
|
+
const c = await userClient(opts, "`compute invitations show`");
|
|
5418
|
+
const res = await c.get(`/api/v1/invitations/${segment(invitationId)}`);
|
|
5419
|
+
output(opts, res, (r) => printInvitationDetail(r.invitation));
|
|
5420
|
+
} catch (e) {
|
|
5421
|
+
fail2(e, opts);
|
|
5422
|
+
}
|
|
5423
|
+
});
|
|
5424
|
+
common(
|
|
5425
|
+
command(invitations, "accept").description("Accept an invitation and join its organization (no confirmation)").argument("<invitationId>", "invitation id (see `compute invitations`)").option("-y, --yes", "accepted for symmetry with decline; accept never asks")
|
|
5426
|
+
).action(async (invitationId, opts) => {
|
|
5427
|
+
try {
|
|
5428
|
+
const c = await userClient(opts, "`compute invitations accept`");
|
|
5429
|
+
const res = await c.post(`/api/v1/invitations/${segment(invitationId)}/accept`, {});
|
|
5430
|
+
output(opts, res, (r) => {
|
|
5431
|
+
const slug = safeTerm(r.organization.slug);
|
|
5432
|
+
console.log(`Joined ${slug} as ${safeTerm(r.member.role)}.`);
|
|
5433
|
+
console.log(pc12.dim(`Switch to it with \`compute org use ${slug}\`, or pass --org ${slug}.`));
|
|
5434
|
+
});
|
|
5435
|
+
} catch (e) {
|
|
5436
|
+
fail2(e, opts);
|
|
5437
|
+
}
|
|
5438
|
+
});
|
|
5439
|
+
common(
|
|
5440
|
+
command(invitations, "decline").description("Decline an invitation").argument("<invitationId>", "invitation id (see `compute invitations`)").option("-y, --yes", "skip the confirmation")
|
|
5441
|
+
).action(async (invitationId, opts) => {
|
|
5442
|
+
try {
|
|
5443
|
+
const c = await userClient(opts, "`compute invitations decline`");
|
|
5444
|
+
await confirmWrite(`Decline invitation ${invitationId}? Its link stops working.`, opts);
|
|
5445
|
+
const res = await c.post(
|
|
5446
|
+
`/api/v1/invitations/${segment(invitationId)}/decline`,
|
|
5447
|
+
{}
|
|
5448
|
+
);
|
|
5449
|
+
output(opts, res, (r) => {
|
|
5450
|
+
const org2 = r.invitation.organization?.slug;
|
|
5451
|
+
console.log(org2 ? `Declined the invitation to ${safeTerm(org2)}.` : `Declined invitation ${r.invitation.id}.`);
|
|
5452
|
+
});
|
|
5453
|
+
} catch (e) {
|
|
5454
|
+
fail2(e, opts);
|
|
5455
|
+
}
|
|
5456
|
+
});
|
|
5457
|
+
}
|
|
5458
|
+
|
|
3891
5459
|
// src/index.ts
|
|
3892
5460
|
var __filename2 = fileURLToPath(import.meta.url);
|
|
3893
|
-
var __dirname2 =
|
|
5461
|
+
var __dirname2 = dirname3(__filename2);
|
|
3894
5462
|
var packageJson = JSON.parse(
|
|
3895
|
-
|
|
5463
|
+
readFileSync6(join5(__dirname2, "..", "package.json"), "utf-8")
|
|
3896
5464
|
);
|
|
3897
5465
|
var isDevBuild = import.meta.url.includes("worktrees") || import.meta.url.includes("/packages/cli/");
|
|
3898
5466
|
var VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;
|
|
@@ -3906,17 +5474,10 @@ process.stderr.on("error", (err) => {
|
|
|
3906
5474
|
});
|
|
3907
5475
|
var program = new Command();
|
|
3908
5476
|
program.name("compute").description("ComputeSDK CLI").version(VERSION).enablePositionalOptions().passThroughOptions();
|
|
3909
|
-
function envBaseUrl() {
|
|
3910
|
-
return process.env.COMPUTE_PLATFORM_URL ?? process.env.BENCHMARKS_PLATFORM_URL;
|
|
3911
|
-
}
|
|
3912
|
-
async function benchAuth(opts = {}) {
|
|
3913
|
-
const { resolveAuth } = await import("@benchsdk/cli");
|
|
3914
|
-
return resolveAuth({ baseUrl: opts.baseUrl ?? envBaseUrl() });
|
|
3915
|
-
}
|
|
3916
5477
|
async function printSessionLine(options) {
|
|
3917
5478
|
try {
|
|
3918
|
-
const { getMe } = await import("@benchsdk/cli");
|
|
3919
|
-
const me = await getMe(await
|
|
5479
|
+
const { getMe, resolveAuth } = await import("@benchsdk/cli");
|
|
5480
|
+
const me = await getMe(await resolveAuth({ baseUrl: options?.baseUrl ?? envBaseUrl() }));
|
|
3920
5481
|
const active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
3921
5482
|
const who = me.user.email ?? me.user.name ?? me.user.id;
|
|
3922
5483
|
if (active) {
|
|
@@ -3943,18 +5504,18 @@ async function runLogout() {
|
|
|
3943
5504
|
program.option("--login", "force re-authentication").option("--logout", "clear stored credentials").option("--org <slug>", "organization slug override for this invocation (or $COMPUTE_ORG)").action(async (opts) => {
|
|
3944
5505
|
if (opts.logout) {
|
|
3945
5506
|
console.log();
|
|
3946
|
-
p.intro(
|
|
5507
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3947
5508
|
await runLogout();
|
|
3948
5509
|
p.log.success("Logged out. Stored credentials removed.");
|
|
3949
|
-
p.outro(
|
|
5510
|
+
p.outro(pc13.green("Done!"));
|
|
3950
5511
|
process.exit(0);
|
|
3951
5512
|
}
|
|
3952
5513
|
if (opts.login) {
|
|
3953
5514
|
console.log();
|
|
3954
|
-
p.intro(
|
|
5515
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3955
5516
|
await runLogin();
|
|
3956
5517
|
await printSessionLine();
|
|
3957
|
-
p.outro(
|
|
5518
|
+
p.outro(pc13.green("Authenticated!"));
|
|
3958
5519
|
process.exit(0);
|
|
3959
5520
|
}
|
|
3960
5521
|
program.help();
|
|
@@ -3965,23 +5526,23 @@ program.hook("preAction", (thisCommand) => {
|
|
|
3965
5526
|
});
|
|
3966
5527
|
program.command("providers").description("List all providers and their configuration status").action(async () => {
|
|
3967
5528
|
console.log();
|
|
3968
|
-
p.intro(
|
|
5529
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3969
5530
|
const statuses = getProviderStatus();
|
|
3970
5531
|
console.log();
|
|
3971
5532
|
for (const status of statuses) {
|
|
3972
|
-
const icon = status.ready ?
|
|
3973
|
-
const name = status.ready ?
|
|
3974
|
-
const detail = status.ready ?
|
|
5533
|
+
const icon = status.ready ? pc13.green("\u25CF") : pc13.gray("\u25CB");
|
|
5534
|
+
const name = status.ready ? pc13.white(status.name) : pc13.gray(status.name);
|
|
5535
|
+
const detail = status.ready ? pc13.green("ready") : pc13.gray(`missing: ${status.missing.join(", ")}`);
|
|
3975
5536
|
console.log(` ${icon} ${name} ${detail}`);
|
|
3976
5537
|
}
|
|
3977
5538
|
console.log();
|
|
3978
5539
|
});
|
|
3979
5540
|
program.command("login").description("Authenticate with ComputeSDK (OAuth device flow)").option("--base-url <url>", "platform URL to authenticate against").action(async (opts) => {
|
|
3980
5541
|
console.log();
|
|
3981
|
-
p.intro(
|
|
5542
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3982
5543
|
await runLogin({ baseUrl: opts.baseUrl });
|
|
3983
5544
|
await printSessionLine({ baseUrl: opts.baseUrl });
|
|
3984
|
-
p.outro(
|
|
5545
|
+
p.outro(pc13.green("Authenticated!"));
|
|
3985
5546
|
});
|
|
3986
5547
|
program.command("logout").description("Clear stored credentials").option("--json", "print machine-readable JSON").action(async (opts) => {
|
|
3987
5548
|
await runLogout();
|
|
@@ -3990,24 +5551,19 @@ program.command("logout").description("Clear stored credentials").option("--json
|
|
|
3990
5551
|
return;
|
|
3991
5552
|
}
|
|
3992
5553
|
console.log();
|
|
3993
|
-
p.intro(
|
|
5554
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3994
5555
|
p.log.success("Logged out. Stored credentials removed.");
|
|
3995
|
-
p.outro(
|
|
5556
|
+
p.outro(pc13.green("Done!"));
|
|
3996
5557
|
});
|
|
3997
5558
|
async function printWhoami(options = {}) {
|
|
3998
|
-
const
|
|
3999
|
-
const me = await getMe(await benchAuth({ baseUrl: options.baseUrl }));
|
|
5559
|
+
const me = await fetchWhoami(await benchAuth({ baseUrl: options.baseUrl }));
|
|
4000
5560
|
if (options.json) {
|
|
4001
5561
|
console.log(JSON.stringify(me, null, 2));
|
|
4002
5562
|
return;
|
|
4003
5563
|
}
|
|
4004
|
-
const
|
|
4005
|
-
console.log(me.user.email ?? me.user.name ?? me.user.id);
|
|
4006
|
-
console.log(
|
|
4007
|
-
`active org: ${active ? `${active.slug} (${active.id})` : "\u2014"}${me.organizations.length > 1 ? " \u2014 change with `compute org use <slug>`" : ""}`
|
|
4008
|
-
);
|
|
5564
|
+
for (const line of formatWhoami(me)) console.log(line);
|
|
4009
5565
|
}
|
|
4010
|
-
var org = program.command("org").description("Manage the active organization");
|
|
5566
|
+
var org = program.command("org").description("Manage the active organization, its members and invitations");
|
|
4011
5567
|
org.command("list").description("List your organizations").option("--json", "print machine-readable JSON").action(async (opts) => {
|
|
4012
5568
|
const { listOrganizations, getMe } = await import("@benchsdk/cli");
|
|
4013
5569
|
const auth = await benchAuth();
|
|
@@ -4017,8 +5573,8 @@ org.command("list").description("List your organizations").option("--json", "pri
|
|
|
4017
5573
|
return;
|
|
4018
5574
|
}
|
|
4019
5575
|
for (const o of organizations) {
|
|
4020
|
-
const marker = o.id === me.activeOrganizationId ?
|
|
4021
|
-
console.log(`${marker} ${
|
|
5576
|
+
const marker = o.id === me.activeOrganizationId ? pc13.green("*") : " ";
|
|
5577
|
+
console.log(`${marker} ${pc13.cyan(o.slug)} ${o.name ?? ""} ${pc13.dim(o.id)}`);
|
|
4022
5578
|
}
|
|
4023
5579
|
});
|
|
4024
5580
|
org.command("use <slug>").description("Set the active organization (persisted to the stored login)").action(async (slug) => {
|
|
@@ -4048,23 +5604,30 @@ org.command("use <slug>").description("Set the active organization (persisted to
|
|
|
4048
5604
|
console.log(`Active organization set to ${result.organization.slug} (${result.organization.id})`);
|
|
4049
5605
|
});
|
|
4050
5606
|
org.command("current").description("Show the current user and active organization").option("--base-url <url>", "platform URL to query").option("--json", "print machine-readable JSON").action((opts) => printWhoami(opts));
|
|
5607
|
+
registerOrgMemberCommands(org);
|
|
4051
5608
|
program.command("whoami").description("Show the current user and active organization").option("--base-url <url>", "platform URL to query").option("--json", "print machine-readable JSON").action((opts) => printWhoami(opts));
|
|
5609
|
+
registerInvitationsCommands(program);
|
|
4052
5610
|
registerActionsCommands(program);
|
|
5611
|
+
registerByokCommands(program);
|
|
4053
5612
|
registerMarketCommands(program);
|
|
4054
5613
|
registerSandboxesCommands(program);
|
|
4055
5614
|
registerAgentsCommands(program);
|
|
4056
|
-
program.command("bench").description("Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, artifacts, export, ...)").allowUnknownOption().helpOption(false).action(() => {
|
|
5615
|
+
program.command("bench").description("Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, fork, artifacts, export, ...)").allowUnknownOption().helpOption(false).action(() => {
|
|
5616
|
+
});
|
|
5617
|
+
registerManifestCommand(program, {
|
|
5618
|
+
version: packageJson.version,
|
|
5619
|
+
packageDir: join5(__dirname2, "..")
|
|
4057
5620
|
});
|
|
4058
5621
|
async function main() {
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
await
|
|
5622
|
+
const bench = parseBenchDispatch(process.argv.slice(2));
|
|
5623
|
+
if (bench) {
|
|
5624
|
+
await runBench(bench);
|
|
4062
5625
|
return;
|
|
4063
5626
|
}
|
|
4064
5627
|
await program.parseAsync(process.argv);
|
|
4065
5628
|
}
|
|
4066
5629
|
main().catch((error) => {
|
|
4067
|
-
console.error(
|
|
5630
|
+
console.error(pc13.red(`
|
|
4068
5631
|
Error: ${error.message}`));
|
|
4069
5632
|
process.exit(1);
|
|
4070
5633
|
});
|