@computesdk/cli 2.6.4 → 2.6.6
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 +2990 -0
- package/dist/index.js +2398 -707
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
package/dist/index.js
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
import "dotenv/config";
|
|
5
|
-
import { Command } from "commander";
|
|
5
|
+
import { Command as Command4 } 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,14 @@ function getProviderStatus() {
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
// src/actions.ts
|
|
68
|
-
import
|
|
69
|
-
import
|
|
68
|
+
import { Option as Option2 } from "commander";
|
|
69
|
+
import pc7 from "picocolors";
|
|
70
|
+
import { mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
70
71
|
import { spawnSync } from "child_process";
|
|
71
72
|
|
|
72
73
|
// src/settings.ts
|
|
73
|
-
import
|
|
74
|
+
import { Option } from "commander";
|
|
75
|
+
import pc2 from "picocolors";
|
|
74
76
|
|
|
75
77
|
// src/actions-client.ts
|
|
76
78
|
import {
|
|
@@ -107,43 +109,30 @@ var ActionsClient = class extends PlatformClient {
|
|
|
107
109
|
}
|
|
108
110
|
};
|
|
109
111
|
|
|
110
|
-
// src/
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const perSecond = rate.per === "second" ? rate.usd : rate.per === "minute" ? rate.usd / SECONDS_PER_MINUTE : rate.usd / SECONDS_PER_HOUR;
|
|
115
|
-
return {
|
|
116
|
-
perSecond,
|
|
117
|
-
perMinute: perSecond * SECONDS_PER_MINUTE,
|
|
118
|
-
perHour: perSecond * SECONDS_PER_HOUR
|
|
119
|
-
};
|
|
112
|
+
// src/term.ts
|
|
113
|
+
import pc from "picocolors";
|
|
114
|
+
function safeTerm(s) {
|
|
115
|
+
return s.replace(/[\u0000-\u001F\u007F-\u009F]/g, "\uFFFD");
|
|
120
116
|
}
|
|
121
|
-
function
|
|
122
|
-
|
|
123
|
-
if (usd === 0) return "$0";
|
|
124
|
-
const decimals = Math.min(100, Math.max(0, 3 - Math.floor(Math.log10(Math.abs(usd)))));
|
|
125
|
-
const fixed = usd.toFixed(decimals);
|
|
126
|
-
const trimmed = fixed.includes(".") ? fixed.replace(/0+$/, "").replace(/\.$/, "") : fixed;
|
|
127
|
-
return `$${trimmed}`;
|
|
117
|
+
function safeTermText(s) {
|
|
118
|
+
return s.replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g, "\uFFFD");
|
|
128
119
|
}
|
|
129
|
-
function
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
120
|
+
function conclusionLabel(conclusion) {
|
|
121
|
+
switch (conclusion) {
|
|
122
|
+
case "passed":
|
|
123
|
+
return pc.green("passed");
|
|
124
|
+
case "failed":
|
|
125
|
+
return pc.red("failed");
|
|
126
|
+
case "running":
|
|
127
|
+
return pc.yellow("running");
|
|
128
|
+
case "cancelled":
|
|
129
|
+
return pc.gray("cancelled");
|
|
130
|
+
case "none":
|
|
131
|
+
return pc.yellow("queued");
|
|
132
|
+
// Anything else is the server's string verbatim.
|
|
133
|
+
default:
|
|
134
|
+
return safeTerm(conclusion);
|
|
135
135
|
}
|
|
136
|
-
const s = abs.toLocaleString("en-US", {
|
|
137
|
-
minimumFractionDigits: 2,
|
|
138
|
-
maximumFractionDigits: 2
|
|
139
|
-
});
|
|
140
|
-
return `${sign}$${s}`;
|
|
141
|
-
}
|
|
142
|
-
function formatRateAllUnits(rate) {
|
|
143
|
-
return `${formatUsd(rate.perHour)}/hr \xB7 ${formatUsd(rate.perMinute)}/min \xB7 ${formatUsd(rate.perSecond)}/s`;
|
|
144
|
-
}
|
|
145
|
-
function formatUsdPer(rate) {
|
|
146
|
-
return formatRateAllUnits(rateAllUnits(rate));
|
|
147
136
|
}
|
|
148
137
|
|
|
149
138
|
// src/settings.ts
|
|
@@ -175,150 +164,1018 @@ function parseMaxPrice(value, per) {
|
|
|
175
164
|
}
|
|
176
165
|
return { usd, per: unit };
|
|
177
166
|
}
|
|
178
|
-
function parseSizeCap(entry) {
|
|
179
|
-
const eq = entry.indexOf("=");
|
|
180
|
-
const size = eq === -1 ? entry : entry.slice(0, eq);
|
|
181
|
-
if (!PLATFORM_SIZES.includes(size)) {
|
|
182
|
-
throw new Error(
|
|
183
|
-
`Invalid --cap "${entry}" \u2014 size must be one of ${PLATFORM_SIZES.join(", ")}.`
|
|
184
|
-
);
|
|
185
|
-
}
|
|
186
|
-
const value = eq === -1 ? "" : entry.slice(eq + 1);
|
|
187
|
-
if (value === "none") return { size, cap: null };
|
|
188
|
-
const cap = parseMaxPrice(value, void 0);
|
|
189
|
-
if (!cap) {
|
|
190
|
-
throw new Error(
|
|
191
|
-
`Invalid --cap "${entry}" \u2014 expected <size>=<usd>/<unit> (e.g. small=0.11/hour) or <size>=none.`
|
|
192
|
-
);
|
|
193
|
-
}
|
|
194
|
-
return { size, cap };
|
|
167
|
+
function parseSizeCap(entry) {
|
|
168
|
+
const eq = entry.indexOf("=");
|
|
169
|
+
const size = eq === -1 ? entry : entry.slice(0, eq);
|
|
170
|
+
if (!PLATFORM_SIZES.includes(size)) {
|
|
171
|
+
throw new Error(
|
|
172
|
+
`Invalid --cap "${entry}" \u2014 size must be one of ${PLATFORM_SIZES.join(", ")}.`
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
const value = eq === -1 ? "" : entry.slice(eq + 1);
|
|
176
|
+
if (value === "none") return { size, cap: null };
|
|
177
|
+
const cap = parseMaxPrice(value, void 0);
|
|
178
|
+
if (!cap) {
|
|
179
|
+
throw new Error(
|
|
180
|
+
`Invalid --cap "${entry}" \u2014 expected <size>=<usd>/<unit> (e.g. small=0.11/hour) or <size>=none.`
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
return { size, cap };
|
|
184
|
+
}
|
|
185
|
+
var MAX_WARM_POOL_SIZE = 16;
|
|
186
|
+
var MAX_SNAPSHOT_POOL_SIZE = 32;
|
|
187
|
+
function parseResourcesFlag(entry) {
|
|
188
|
+
const eq = entry.indexOf("=");
|
|
189
|
+
const provider = eq === -1 ? "" : entry.slice(0, eq).trim();
|
|
190
|
+
const preset = eq === -1 ? "" : entry.slice(eq + 1).trim();
|
|
191
|
+
if (provider === "" || preset === "") {
|
|
192
|
+
throw new PlatformClientError(
|
|
193
|
+
"invalid_argument",
|
|
194
|
+
`Invalid --resources "${entry}" \u2014 expected <provider>=<preset> (e.g. blaxel=large) or <provider>=none.`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return { provider, preset: preset === "none" ? null : preset };
|
|
198
|
+
}
|
|
199
|
+
function parsePoolFlag(flag, entry, max) {
|
|
200
|
+
const eq = entry.indexOf("=");
|
|
201
|
+
const key = eq === -1 ? "" : entry.slice(0, eq).trim();
|
|
202
|
+
const value = eq === -1 ? "" : entry.slice(eq + 1).trim();
|
|
203
|
+
const size = Number(value);
|
|
204
|
+
if (key === "" || !/^\d+$/.test(value) || size > max) {
|
|
205
|
+
throw new PlatformClientError(
|
|
206
|
+
"invalid_argument",
|
|
207
|
+
`Invalid ${flag} "${entry}" \u2014 expected <provider>[:<region>]=<n> with n in 0..${max} (0 clears it).`
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
return { key, size };
|
|
211
|
+
}
|
|
212
|
+
function parseWarmPoolFlag(entry) {
|
|
213
|
+
return parsePoolFlag("--warm-pool", entry, MAX_WARM_POOL_SIZE);
|
|
214
|
+
}
|
|
215
|
+
function parseSnapshotPoolFlag(entry) {
|
|
216
|
+
return parsePoolFlag("--snapshot-pool", entry, MAX_SNAPSHOT_POOL_SIZE);
|
|
217
|
+
}
|
|
218
|
+
function poolPatch(entries, parse) {
|
|
219
|
+
const pool = {};
|
|
220
|
+
for (const entry of entries) {
|
|
221
|
+
const { key, size } = parse(entry);
|
|
222
|
+
pool[key] = size;
|
|
223
|
+
}
|
|
224
|
+
return pool;
|
|
225
|
+
}
|
|
226
|
+
function formatResources(r) {
|
|
227
|
+
const parts = [];
|
|
228
|
+
if (r.cpus !== void 0) parts.push(`${r.cpus} vCPU`);
|
|
229
|
+
if (r.memoryMb !== void 0) parts.push(`${r.memoryMb} MB`);
|
|
230
|
+
if (r.ephemeralDiskMb) parts.push(`${r.ephemeralDiskMb} MB disk`);
|
|
231
|
+
return parts.join(" / ") || "\u2014";
|
|
232
|
+
}
|
|
233
|
+
var BYOK_MODES = ["off", "first", "fallback", "only"];
|
|
234
|
+
var BYOK_MODE_HELP = {
|
|
235
|
+
off: "not used: managed accounts only",
|
|
236
|
+
first: "your keys first, then managed accounts",
|
|
237
|
+
fallback: "managed accounts first, then your keys",
|
|
238
|
+
only: "your keys only, never managed accounts"
|
|
239
|
+
};
|
|
240
|
+
var arrow = (list) => list.join(" \u2192 ");
|
|
241
|
+
function printLaneRouting(r, lane) {
|
|
242
|
+
const label = (text) => text.padEnd(12);
|
|
243
|
+
const managed = r.managed.length > 0 ? arrow(r.managed) : pc2.dim("no managed account is live");
|
|
244
|
+
console.log(
|
|
245
|
+
`${label("Routing")}${r.routing === "default" ? `ComputeSDK default ${pc2.dim(`(${managed})`)}` : `custom: ${managed}`}`
|
|
246
|
+
);
|
|
247
|
+
console.log(`${label("BYOK")}${r.byok.mode} ${pc2.dim(`(${BYOK_MODE_HELP[r.byok.mode]})`)}`);
|
|
248
|
+
if (r.byok.mode !== "off") {
|
|
249
|
+
const list = r.byok.order.length > 0 ? arrow(r.byok.order) : "\u2014";
|
|
250
|
+
const order = lane === "sandboxes" && r.byok.inherits === true ? `${list} ${pc2.dim("(inherited from the Actions router)")}` : r.byok.order.length > 0 ? list : pc2.dim("none set \u2014 add keys with `compute byok configure`");
|
|
251
|
+
console.log(`${label("BYOK order")}${order}`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function printLaneSettings(s) {
|
|
255
|
+
const resources = Object.entries(s.providerResources ?? {});
|
|
256
|
+
console.log("resources:");
|
|
257
|
+
if (resources.length === 0) console.log(" \u2014");
|
|
258
|
+
for (const [provider, r] of resources) {
|
|
259
|
+
const preset = s.providerResourcePresets?.[provider];
|
|
260
|
+
console.log(preset ? ` ${provider} ${preset} (${formatResources(r)})` : ` ${provider} ${formatResources(r)}`);
|
|
261
|
+
}
|
|
262
|
+
const pool = Object.entries(s.warmPool ?? {});
|
|
263
|
+
console.log("warm pool:");
|
|
264
|
+
if (pool.length === 0) console.log(" \u2014");
|
|
265
|
+
for (const [entry, floor] of pool) console.log(` ${entry} ${floor}`);
|
|
266
|
+
if (s.snapshotPool !== void 0) {
|
|
267
|
+
const snap = Object.entries(s.snapshotPool);
|
|
268
|
+
console.log("snapshot pool:");
|
|
269
|
+
if (snap.length === 0) console.log(" \u2014");
|
|
270
|
+
for (const [entry, cap] of snap) console.log(` ${safeTerm(entry)} ${cap}`);
|
|
271
|
+
}
|
|
272
|
+
if (s.snapshotSummary !== void 0) printSnapshotSummary(s.snapshotSummary);
|
|
273
|
+
}
|
|
274
|
+
function printSnapshotSummary(summary) {
|
|
275
|
+
const capped = summary.workflows.filter((w) => w.snapshotCap !== null);
|
|
276
|
+
console.log("workflow snapshot caps:");
|
|
277
|
+
if (capped.length === 0) console.log(` ${pc2.dim("\u2014 (every workflow uses the dynamic pool)")}`);
|
|
278
|
+
for (const w of capped) {
|
|
279
|
+
const cap = w.snapshotCap === 0 ? "off" : String(w.snapshotCap);
|
|
280
|
+
console.log(` ${safeTerm(w.repoFullName)} ${safeTerm(w.path)} ${cap}`);
|
|
281
|
+
}
|
|
282
|
+
console.log("live snapshots:");
|
|
283
|
+
if (summary.live.length === 0) console.log(" \u2014");
|
|
284
|
+
for (const row of summary.live) {
|
|
285
|
+
console.log(` ${safeTerm(row.repoFullName)} ${row.workflowPath === null ? pc2.dim("(no workflow)") : safeTerm(row.workflowPath)} ${row.count}`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function settingsFail(e, opts, lane, verb, deps) {
|
|
289
|
+
if (e instanceof PlatformApiError && e.status === 403) {
|
|
290
|
+
return deps.fail(
|
|
291
|
+
new PlatformApiError(
|
|
292
|
+
403,
|
|
293
|
+
`Only org owners/admins can ${verb} ${lane} settings`,
|
|
294
|
+
e.body
|
|
295
|
+
),
|
|
296
|
+
opts
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
return deps.fail(e, opts);
|
|
300
|
+
}
|
|
301
|
+
function providerList(flag, value) {
|
|
302
|
+
const list = value.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
303
|
+
if (list.length === 0) throw new Error(`${flag} "${value}" names no providers \u2014 pass a comma-separated list.`);
|
|
304
|
+
return list;
|
|
305
|
+
}
|
|
306
|
+
function registerSettingsCommands(group, lane, common2, deps) {
|
|
307
|
+
const routerName = lane === "sandboxes" ? "Sandboxes" : "Actions";
|
|
308
|
+
const show = async (c) => {
|
|
309
|
+
const [routing, settings2] = await Promise.all([
|
|
310
|
+
c.get(`/api/v1/${lane}/routing`),
|
|
311
|
+
c.get(`/api/v1/${lane}/settings`)
|
|
312
|
+
]);
|
|
313
|
+
return { routing, settings: settings2 };
|
|
314
|
+
};
|
|
315
|
+
const print = ({ routing, settings: settings2 }) => {
|
|
316
|
+
printLaneRouting(routing, lane);
|
|
317
|
+
printLaneSettings(settings2);
|
|
318
|
+
};
|
|
319
|
+
const settings = common2(
|
|
320
|
+
group.command("settings").description(`Show the ${routerName} router: managed routing, BYOK use, sizes and pools`).configureOutput({
|
|
321
|
+
outputError: (str, write) => deps.usageErrorOutput(str, write)
|
|
322
|
+
})
|
|
323
|
+
).action(async (opts) => {
|
|
324
|
+
try {
|
|
325
|
+
deps.output(opts, await show(await deps.client(opts)), print);
|
|
326
|
+
} catch (e) {
|
|
327
|
+
settingsFail(e, opts, lane, "view", deps);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
const set = common2(
|
|
331
|
+
settings.command("set").description(`Change the ${routerName} router (owner/admin)`).option(
|
|
332
|
+
"--routing <default|providers>",
|
|
333
|
+
'managed routing: "default" for ComputeSDK routing, or your own managed-account order (e.g. daytona,e2b)'
|
|
334
|
+
).option("--byok <mode>", `use your own keys: ${BYOK_MODES.join(" | ")}`).option(
|
|
335
|
+
"--byok-order <providers>",
|
|
336
|
+
lane === "sandboxes" ? 'your own providers in order (e.g. tensorlake,blaxel); "inherit" uses the Actions BYOK order' : "your own providers in order (e.g. tensorlake,blaxel)"
|
|
337
|
+
).addOption(new Option("--order <providers>").hideHelp())
|
|
338
|
+
);
|
|
339
|
+
set.option(
|
|
340
|
+
"--resources <provider=preset>",
|
|
341
|
+
"per-provider size preset (e.g. blaxel=large); <provider>=none clears it (repeatable)",
|
|
342
|
+
(v, a) => a.concat(v),
|
|
343
|
+
[]
|
|
344
|
+
).option(
|
|
345
|
+
"--warm-pool <provider[:region]=n>",
|
|
346
|
+
`warm pool size per BYOK entry, 0..${MAX_WARM_POOL_SIZE}; 0 clears it (repeatable)`,
|
|
347
|
+
(v, a) => a.concat(v),
|
|
348
|
+
[]
|
|
349
|
+
);
|
|
350
|
+
if (lane === "actions") {
|
|
351
|
+
set.option(
|
|
352
|
+
"--snapshot-pool <provider[:region]=n>",
|
|
353
|
+
`snapshot cap per BYOK entry, 0..${MAX_SNAPSHOT_POOL_SIZE}; 0 clears it (repeatable)`,
|
|
354
|
+
(v, a) => a.concat(v),
|
|
355
|
+
[]
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
set.addOption(new Option("--cap <size=rate>").hideHelp().argParser((v, a = []) => a.concat(v)).default([])).addOption(new Option("--general-cap <rate|none>").hideHelp()).addOption(new Option("--order-type <type>").hideHelp());
|
|
359
|
+
set.action(async (opts) => {
|
|
360
|
+
try {
|
|
361
|
+
const routing = {};
|
|
362
|
+
if (opts.routing !== void 0) {
|
|
363
|
+
routing.routing = opts.routing === "default" ? "default" : providerList("--routing", opts.routing);
|
|
364
|
+
}
|
|
365
|
+
if (opts.byok !== void 0) {
|
|
366
|
+
if (!BYOK_MODES.includes(opts.byok)) {
|
|
367
|
+
throw new Error(`--byok must be one of ${BYOK_MODES.join(", ")}.`);
|
|
368
|
+
}
|
|
369
|
+
routing.byok = opts.byok;
|
|
370
|
+
}
|
|
371
|
+
if (opts.byokOrder !== void 0 && opts.order !== void 0) {
|
|
372
|
+
throw new Error("--order is the old name of --byok-order; pass one.");
|
|
373
|
+
}
|
|
374
|
+
const byokOrder = opts.byokOrder ?? opts.order;
|
|
375
|
+
if (byokOrder !== void 0) {
|
|
376
|
+
const flag = opts.byokOrder !== void 0 ? "--byok-order" : "--order";
|
|
377
|
+
routing.byokOrder = byokOrder === "inherit" && lane === "sandboxes" || byokOrder === "default" && lane === "actions" ? [] : providerList(flag, byokOrder);
|
|
378
|
+
}
|
|
379
|
+
const settingsBody = {};
|
|
380
|
+
if (opts.cap.length > 0) {
|
|
381
|
+
const caps = {};
|
|
382
|
+
for (const entry of opts.cap) {
|
|
383
|
+
const { size, cap } = parseSizeCap(entry);
|
|
384
|
+
caps[size] = cap;
|
|
385
|
+
}
|
|
386
|
+
settingsBody.marketCaps = caps;
|
|
387
|
+
}
|
|
388
|
+
if (opts.generalCap !== void 0) {
|
|
389
|
+
settingsBody.marketCap = opts.generalCap === "none" ? null : parseMaxPrice(opts.generalCap, void 0);
|
|
390
|
+
}
|
|
391
|
+
if (opts.orderType !== void 0) {
|
|
392
|
+
if (lane === "sandboxes" && opts.orderType === "inherit") {
|
|
393
|
+
settingsBody.marketOrderType = null;
|
|
394
|
+
} else if (opts.orderType === "limit" || opts.orderType === "market") {
|
|
395
|
+
settingsBody.marketOrderType = opts.orderType;
|
|
396
|
+
} else {
|
|
397
|
+
throw new Error("--order-type must be limit or market.");
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (opts.resources && opts.resources.length > 0) {
|
|
401
|
+
const resources = {};
|
|
402
|
+
for (const entry of opts.resources) {
|
|
403
|
+
const { provider, preset } = parseResourcesFlag(entry);
|
|
404
|
+
resources[provider] = preset;
|
|
405
|
+
}
|
|
406
|
+
settingsBody.providerResources = resources;
|
|
407
|
+
}
|
|
408
|
+
if (opts.warmPool && opts.warmPool.length > 0) {
|
|
409
|
+
settingsBody.warmPool = poolPatch(opts.warmPool, parseWarmPoolFlag);
|
|
410
|
+
}
|
|
411
|
+
if (opts.snapshotPool && opts.snapshotPool.length > 0) {
|
|
412
|
+
settingsBody.snapshotPool = poolPatch(opts.snapshotPool, parseSnapshotPoolFlag);
|
|
413
|
+
}
|
|
414
|
+
if (Object.keys(routing).length > 0 && Object.keys(settingsBody).length > 0) {
|
|
415
|
+
throw new Error(
|
|
416
|
+
"Change routing (--routing, --byok, --byok-order) and sizes or pools in separate commands."
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
if (Object.keys(routing).length === 0 && Object.keys(settingsBody).length === 0) {
|
|
420
|
+
throw new Error(
|
|
421
|
+
lane === "sandboxes" ? "Nothing to change \u2014 pass --routing, --byok, --byok-order, --resources, or --warm-pool." : "Nothing to change \u2014 pass --routing, --byok, --byok-order, --resources, --warm-pool, or --snapshot-pool."
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
const c = await deps.client(opts);
|
|
425
|
+
if (Object.keys(routing).length > 0) await c.patch(`/api/v1/${lane}/routing`, routing);
|
|
426
|
+
if (Object.keys(settingsBody).length > 0) await c.patch(`/api/v1/${lane}/settings`, settingsBody);
|
|
427
|
+
deps.output(opts, await show(c), print);
|
|
428
|
+
} catch (e) {
|
|
429
|
+
settingsFail(e, opts, lane, "change", deps);
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// src/actions-repos.ts
|
|
435
|
+
import pc5 from "picocolors";
|
|
436
|
+
import { readFileSync } from "fs";
|
|
437
|
+
|
|
438
|
+
// src/actions-workflows.ts
|
|
439
|
+
import pc4 from "picocolors";
|
|
440
|
+
|
|
441
|
+
// src/actions-runs.ts
|
|
442
|
+
import pc3 from "picocolors";
|
|
443
|
+
|
|
444
|
+
// src/confirm.ts
|
|
445
|
+
import { createInterface } from "readline/promises";
|
|
446
|
+
async function confirmWrite(question, opts) {
|
|
447
|
+
if (opts.yes) return;
|
|
448
|
+
if (!process.stdin.isTTY) {
|
|
449
|
+
throw new PlatformClientError("confirmation_required", `${question} Pass -y to confirm.`);
|
|
450
|
+
}
|
|
451
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
452
|
+
let answer;
|
|
453
|
+
try {
|
|
454
|
+
answer = await rl.question(`${question} [y/N] `);
|
|
455
|
+
} finally {
|
|
456
|
+
rl.close();
|
|
457
|
+
}
|
|
458
|
+
if (!/^y(es)?$/i.test(answer.trim())) {
|
|
459
|
+
throw new PlatformClientError("cancelled", "Cancelled; nothing was changed.");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// src/actions-runs.ts
|
|
464
|
+
var WORKFLOW_PATH_PREFIX = ".github/";
|
|
465
|
+
function plural(n, noun) {
|
|
466
|
+
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
467
|
+
}
|
|
468
|
+
function resolveWorkflowPaths(workflows, selectors) {
|
|
469
|
+
const paths = [];
|
|
470
|
+
for (const selector of selectors) {
|
|
471
|
+
const matchers = [
|
|
472
|
+
(w) => w.path === selector,
|
|
473
|
+
(w) => w.name === selector,
|
|
474
|
+
(w) => w.path.split("/").pop() === selector,
|
|
475
|
+
(w) => w.id === selector
|
|
476
|
+
];
|
|
477
|
+
let found = [];
|
|
478
|
+
for (const matches of matchers) {
|
|
479
|
+
found = workflows.filter(matches);
|
|
480
|
+
if (found.length > 0) break;
|
|
481
|
+
}
|
|
482
|
+
if (found.length === 0) {
|
|
483
|
+
const choices = [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(", ") || "none";
|
|
484
|
+
throw new PlatformClientError("workflow_not_found", `No workflow "${selector}". Available: ${choices}`);
|
|
485
|
+
}
|
|
486
|
+
for (const w of found) if (!paths.includes(w.path)) paths.push(w.path);
|
|
487
|
+
}
|
|
488
|
+
return paths;
|
|
489
|
+
}
|
|
490
|
+
async function runFilterQuery(c, repo, opts) {
|
|
491
|
+
let workflow;
|
|
492
|
+
if (opts.workflow && opts.workflow.length > 0) {
|
|
493
|
+
const lookups = opts.workflow.filter((s) => !s.startsWith(WORKFLOW_PATH_PREFIX));
|
|
494
|
+
const catalog = lookups.length === 0 ? [] : (await c.get("/api/v1/actions/workflows", { repo, include: "all" })).workflows;
|
|
495
|
+
workflow = [];
|
|
496
|
+
for (const selector of opts.workflow) {
|
|
497
|
+
const paths = selector.startsWith(WORKFLOW_PATH_PREFIX) ? [selector] : resolveWorkflowPaths(catalog, [selector]);
|
|
498
|
+
for (const path2 of paths) if (!workflow.includes(path2)) workflow.push(path2);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return {
|
|
502
|
+
repo,
|
|
503
|
+
status: opts.status,
|
|
504
|
+
branch: opts.branch,
|
|
505
|
+
event: opts.event,
|
|
506
|
+
workflow,
|
|
507
|
+
q: opts.search,
|
|
508
|
+
archived: opts.archived ? "only" : void 0,
|
|
509
|
+
reliability: opts.reliability ? "1" : void 0
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
function parseDayCursor(value) {
|
|
513
|
+
const comma = value.lastIndexOf(",");
|
|
514
|
+
if (comma <= 0 || comma === value.length - 1) {
|
|
515
|
+
throw new PlatformClientError(
|
|
516
|
+
"invalid_argument",
|
|
517
|
+
`Invalid --cursor "${value}". Expected <startedAt>,<id>, as printed after a page.`
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
return { startedAt: value.slice(0, comma), id: value.slice(comma + 1) };
|
|
521
|
+
}
|
|
522
|
+
async function listDayRuns(c, day, query, { all, cursor }) {
|
|
523
|
+
const runs = [];
|
|
524
|
+
const seen = /* @__PURE__ */ new Set();
|
|
525
|
+
let next = cursor ?? null;
|
|
526
|
+
for (; ; ) {
|
|
527
|
+
const page = await c.get(`/api/v1/actions/runs/day/${encodeURIComponent(day)}`, {
|
|
528
|
+
...query,
|
|
529
|
+
cursorStartedAt: next?.startedAt,
|
|
530
|
+
cursorId: next?.id
|
|
531
|
+
});
|
|
532
|
+
runs.push(...page.runs);
|
|
533
|
+
next = page.nextCursor ?? null;
|
|
534
|
+
if (!all || next === null) return { runs, nextCursor: next };
|
|
535
|
+
const key = `${next.startedAt},${next.id}`;
|
|
536
|
+
if (seen.has(key)) throw new PlatformClientError("invalid_argument", `The platform repeated cursor ${key}; stopping.`);
|
|
537
|
+
seen.add(key);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function formatRunDays(days) {
|
|
541
|
+
if (days.length === 0) return "No runs found.";
|
|
542
|
+
return days.map((d) => `${safeTerm(d.day)} ${plural(d.count, "run")}`).join("\n");
|
|
543
|
+
}
|
|
544
|
+
function formatDayCursor(cursor) {
|
|
545
|
+
return `more: --cursor ${safeTerm(cursor.startedAt)},${safeTerm(cursor.id)}`;
|
|
546
|
+
}
|
|
547
|
+
function archiveQuestion(count, archived) {
|
|
548
|
+
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.`;
|
|
549
|
+
}
|
|
550
|
+
function notFoundIds(error) {
|
|
551
|
+
if (!(error instanceof PlatformApiError)) return [];
|
|
552
|
+
const ids = error.details?.notFound;
|
|
553
|
+
return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
|
|
554
|
+
}
|
|
555
|
+
function registerRunsCommands(actions, common2, deps) {
|
|
556
|
+
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)");
|
|
557
|
+
const printRuns = (runs2) => {
|
|
558
|
+
if (runs2.length === 0) {
|
|
559
|
+
console.log("No runs found.");
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
for (const run of runs2) console.log(deps.formatRunRow(run));
|
|
563
|
+
};
|
|
564
|
+
const runs = actions.command("runs").description("List recent runs (every repo, or one), or one day's runs with --day");
|
|
565
|
+
common2(
|
|
566
|
+
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")
|
|
567
|
+
).action(async (repo, opts) => {
|
|
568
|
+
try {
|
|
569
|
+
if (opts.day === void 0 && (opts.all || opts.timeZone !== void 0 || opts.cursor !== void 0)) {
|
|
570
|
+
throw new PlatformClientError("invalid_argument", "--all, --time-zone and --cursor page one day's runs: pass --day <YYYY-MM-DD>.");
|
|
571
|
+
}
|
|
572
|
+
const cursor = opts.cursor === void 0 ? void 0 : parseDayCursor(opts.cursor);
|
|
573
|
+
const c = await deps.client(opts);
|
|
574
|
+
const query = await runFilterQuery(c, repo, opts);
|
|
575
|
+
if (opts.day !== void 0) {
|
|
576
|
+
const page = await listDayRuns(c, opts.day, { ...query, timeZone: opts.timeZone }, { all: opts.all === true, cursor });
|
|
577
|
+
deps.output(opts, page, (p2) => {
|
|
578
|
+
printRuns(p2.runs);
|
|
579
|
+
if (p2.nextCursor) console.log(pc3.dim(formatDayCursor(p2.nextCursor)));
|
|
580
|
+
});
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
const { runs: list } = await c.get("/api/v1/actions/runs", query);
|
|
584
|
+
deps.output(opts, list, printRuns);
|
|
585
|
+
} catch (e) {
|
|
586
|
+
deps.fail(e, opts);
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
common2(
|
|
590
|
+
withFilters(
|
|
591
|
+
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)")
|
|
592
|
+
).option("--time-zone <iana>", "the time zone days are read in (default: UTC)")
|
|
593
|
+
).action(async (repo, opts) => {
|
|
594
|
+
try {
|
|
595
|
+
const c = await deps.client(opts);
|
|
596
|
+
const query = await runFilterQuery(c, repo, opts);
|
|
597
|
+
const data = await c.get("/api/v1/actions/run-days", { ...query, timeZone: opts.timeZone });
|
|
598
|
+
deps.output(opts, data, (d) => console.log(formatRunDays(d.days)));
|
|
599
|
+
} catch (e) {
|
|
600
|
+
deps.fail(e, opts);
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
for (const archived of [true, false]) {
|
|
604
|
+
const verb = archived ? "archive" : "unarchive";
|
|
605
|
+
common2(
|
|
606
|
+
runs.command(verb).description(
|
|
607
|
+
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)"
|
|
608
|
+
).argument("<run-id...>", "run IDs").option("-y, --yes", "skip the confirmation")
|
|
609
|
+
).action(async (runIds, opts) => {
|
|
610
|
+
try {
|
|
611
|
+
await confirmWrite(archiveQuestion(runIds.length, archived), opts);
|
|
612
|
+
const result = await (await deps.client(opts)).post("/api/v1/actions/runs/archive", {
|
|
613
|
+
runIds,
|
|
614
|
+
archived
|
|
615
|
+
});
|
|
616
|
+
deps.output(opts, result, (r) => console.log(`${verb}d ${plural(r.archived, "run")}`));
|
|
617
|
+
} catch (e) {
|
|
618
|
+
const missing = notFoundIds(e);
|
|
619
|
+
if (!opts.json && missing.length > 0 && e instanceof PlatformApiError) {
|
|
620
|
+
deps.fail(new PlatformApiError(e.status, `${e.message} \u2014 not found: ${missing.join(", ")}`, e.body), opts);
|
|
621
|
+
}
|
|
622
|
+
deps.fail(e, opts);
|
|
623
|
+
}
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/actions-workflows.ts
|
|
629
|
+
function formatAgo(iso, now = Date.now()) {
|
|
630
|
+
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1e3));
|
|
631
|
+
if (s < 60) return `${s}s ago`;
|
|
632
|
+
const m = Math.floor(s / 60);
|
|
633
|
+
if (m < 60) return `${m}m ago`;
|
|
634
|
+
const h = Math.floor(m / 60);
|
|
635
|
+
if (h < 48) return `${h}h ago`;
|
|
636
|
+
return `${Math.floor(h / 24)}d ago`;
|
|
637
|
+
}
|
|
638
|
+
function orderText(order) {
|
|
639
|
+
return order && order.length > 0 ? order.map(safeTerm).join(",") : "inherits";
|
|
640
|
+
}
|
|
641
|
+
function snapshotText(cap) {
|
|
642
|
+
if (cap === null || cap === void 0) return "dynamic";
|
|
643
|
+
return cap === 0 ? "off" : String(cap);
|
|
644
|
+
}
|
|
645
|
+
function formatWorkflowInputs(inputs) {
|
|
646
|
+
return inputs.map((i) => {
|
|
647
|
+
const name = safeTerm(i.name);
|
|
648
|
+
if (i.required) return `${name}* (required)`;
|
|
649
|
+
return i.default !== "" ? `${name} default=${safeTerm(i.default)}` : name;
|
|
650
|
+
}).join(", ");
|
|
651
|
+
}
|
|
652
|
+
function stateLabel(w) {
|
|
653
|
+
if (w.repoEnabled === false) return pc4.gray("\u25CB repo disabled");
|
|
654
|
+
if (w.enabled === false || w.userDisabledAt) return pc4.gray("\u25CB disabled (user)");
|
|
655
|
+
return pc4.green("\u25CF enabled");
|
|
656
|
+
}
|
|
657
|
+
function formatWorkflowRow(w, now = Date.now()) {
|
|
658
|
+
const last = w.lastRun ? `${conclusionLabel(w.lastRun.conclusion)} ${formatAgo(w.lastRun.queuedAt, now)}` : "never";
|
|
659
|
+
const inputs = formatWorkflowInputs(w.inputs ?? []);
|
|
660
|
+
return [
|
|
661
|
+
stateLabel(w),
|
|
662
|
+
pc4.dim(safeTerm(w.repoFullName)),
|
|
663
|
+
`${safeTerm(w.path)} (${safeTerm(w.name)})`,
|
|
664
|
+
`order: ${orderText(w.providerOrder)}`,
|
|
665
|
+
`snapshots: ${snapshotText(w.snapshotCap)}`,
|
|
666
|
+
`last: ${last}`,
|
|
667
|
+
...inputs ? [pc4.dim(`inputs: ${inputs}`)] : []
|
|
668
|
+
].join(" ");
|
|
669
|
+
}
|
|
670
|
+
function formatRefOnlyRow(w) {
|
|
671
|
+
const inputs = formatWorkflowInputs(w.inputs);
|
|
672
|
+
return [
|
|
673
|
+
pc4.cyan("\u25C7 ref-only"),
|
|
674
|
+
`${safeTerm(w.path)} (${safeTerm(w.name)})`,
|
|
675
|
+
w.dispatchable ? inputs ? `inputs: ${inputs}` : pc4.dim("no inputs") : pc4.dim("push-only: dispatch with --manual")
|
|
676
|
+
].join(" ");
|
|
677
|
+
}
|
|
678
|
+
function matchRefOnly(refOnly, selector) {
|
|
679
|
+
const byPath = refOnly.find((w) => w.path === selector);
|
|
680
|
+
if (byPath) return byPath;
|
|
681
|
+
const byName = refOnly.filter((w) => w.name === selector);
|
|
682
|
+
if (byName.length > 1) {
|
|
683
|
+
throw new PlatformClientError(
|
|
684
|
+
"invalid_argument",
|
|
685
|
+
`"${selector}" matches ${byName.length} workflows only on this ref: ${byName.map((w) => safeTerm(w.path)).join(", ")}. Pass the path.`
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
return byName[0];
|
|
689
|
+
}
|
|
690
|
+
function workflowChoices(workflows) {
|
|
691
|
+
return [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(", ") || "none";
|
|
692
|
+
}
|
|
693
|
+
function resolveControlTarget(catalog, repo, selector) {
|
|
694
|
+
const inRepo = catalog.filter((w) => w.repoFullName === repo);
|
|
695
|
+
let paths;
|
|
696
|
+
try {
|
|
697
|
+
paths = resolveWorkflowPaths(inRepo, [selector]);
|
|
698
|
+
} catch (e) {
|
|
699
|
+
if (e instanceof PlatformClientError && e.code === "workflow_not_found") {
|
|
700
|
+
throw new PlatformClientError("workflow_not_found", `No workflow "${selector}" in ${repo}. Available: ${workflowChoices(inRepo)}`);
|
|
701
|
+
}
|
|
702
|
+
throw e;
|
|
703
|
+
}
|
|
704
|
+
if (paths.length > 1) {
|
|
705
|
+
throw new PlatformClientError(
|
|
706
|
+
"invalid_argument",
|
|
707
|
+
`"${selector}" matches ${paths.length} workflows in ${repo}: ${paths.join(", ")}. Pass the path.`
|
|
708
|
+
);
|
|
709
|
+
}
|
|
710
|
+
return paths[0];
|
|
711
|
+
}
|
|
712
|
+
function setControls(opts) {
|
|
713
|
+
const controls = {};
|
|
714
|
+
if (opts.order !== void 0 && opts.inheritOrder) {
|
|
715
|
+
throw new PlatformClientError("invalid_argument", "Pass --order or --inherit-order, not both.");
|
|
716
|
+
}
|
|
717
|
+
if (opts.snapshotCap !== void 0 && opts.dynamicSnapshots) {
|
|
718
|
+
throw new PlatformClientError("invalid_argument", "Pass --snapshot-cap or --dynamic-snapshots, not both.");
|
|
719
|
+
}
|
|
720
|
+
if (opts.inheritOrder) controls.providerOrder = null;
|
|
721
|
+
if (opts.order !== void 0) {
|
|
722
|
+
const order = opts.order.split(",").map((s) => s.trim()).filter(Boolean);
|
|
723
|
+
if (order.length === 0) {
|
|
724
|
+
throw new PlatformClientError(
|
|
725
|
+
"invalid_argument",
|
|
726
|
+
`--order "${opts.order}" names no providers \u2014 pass a comma-separated list, or --inherit-order.`
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
controls.providerOrder = order;
|
|
730
|
+
}
|
|
731
|
+
if (opts.dynamicSnapshots) controls.snapshotCap = null;
|
|
732
|
+
if (opts.snapshotCap !== void 0) {
|
|
733
|
+
if (!/^\d+$/.test(opts.snapshotCap.trim())) {
|
|
734
|
+
throw new PlatformClientError(
|
|
735
|
+
"invalid_argument",
|
|
736
|
+
`Invalid --snapshot-cap "${opts.snapshotCap}". Expected a whole number (0 turns snapshots off), or --dynamic-snapshots.`
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
controls.snapshotCap = Number(opts.snapshotCap.trim());
|
|
740
|
+
}
|
|
741
|
+
if (Object.keys(controls).length === 0) {
|
|
742
|
+
throw new PlatformClientError(
|
|
743
|
+
"invalid_argument",
|
|
744
|
+
"Nothing to change \u2014 pass --order, --inherit-order, --snapshot-cap or --dynamic-snapshots."
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
return controls;
|
|
748
|
+
}
|
|
749
|
+
function describeControls(c) {
|
|
750
|
+
const parts = [];
|
|
751
|
+
if (c.providerOrder !== void 0) parts.push(`order: ${orderText(c.providerOrder)}`);
|
|
752
|
+
if (c.snapshotCap !== void 0) parts.push(`snapshots: ${snapshotText(c.snapshotCap)}`);
|
|
753
|
+
return parts.join(", ");
|
|
754
|
+
}
|
|
755
|
+
function formatControlsResult(verb, r) {
|
|
756
|
+
const detail = verb === "set" ? ` order: ${orderText(r.providerOrder)} snapshots: ${snapshotText(r.snapshotCap)}` : "";
|
|
757
|
+
return `${verb} ${pc4.cyan(safeTerm(r.repoFullName))} ${safeTerm(r.path)}${detail}`;
|
|
758
|
+
}
|
|
759
|
+
function registerWorkflowsCommands(actions, common2, deps) {
|
|
760
|
+
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");
|
|
761
|
+
common2(
|
|
762
|
+
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)")
|
|
763
|
+
).action(async (repo, opts) => {
|
|
764
|
+
try {
|
|
765
|
+
if (opts.ref !== void 0 && repo === void 0) {
|
|
766
|
+
throw new PlatformClientError("invalid_argument", "--ref needs a repo: compute actions workflows <owner/repo> --ref <ref>.");
|
|
767
|
+
}
|
|
768
|
+
const c = await deps.client(opts);
|
|
769
|
+
const data = await c.get("/api/v1/actions/workflows", {
|
|
770
|
+
repo,
|
|
771
|
+
include: opts.all ? "all" : void 0,
|
|
772
|
+
ref: opts.ref
|
|
773
|
+
});
|
|
774
|
+
deps.output(opts, data, (d) => {
|
|
775
|
+
if (d.workflows.length === 0 && (d.refOnly ?? []).length === 0) {
|
|
776
|
+
console.log("No workflows found.");
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
for (const w of d.workflows) console.log(formatWorkflowRow(w));
|
|
780
|
+
if (opts.ref !== void 0) {
|
|
781
|
+
const refOnly = d.refOnly ?? [];
|
|
782
|
+
console.log(pc4.dim(refOnly.length === 0 ? `only on ${safeTerm(opts.ref)}: none` : `only on ${safeTerm(opts.ref)}:`));
|
|
783
|
+
for (const w of refOnly) console.log(formatRefOnlyRow(w));
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
} catch (e) {
|
|
787
|
+
deps.fail(e, opts);
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
async function writeControls(repo, selector, controls, question, verb, opts) {
|
|
791
|
+
await confirmWrite(question, opts);
|
|
792
|
+
const c = await deps.client(opts);
|
|
793
|
+
const { workflows: catalog } = await c.get("/api/v1/actions/workflows", {
|
|
794
|
+
repo,
|
|
795
|
+
include: "all"
|
|
796
|
+
});
|
|
797
|
+
const path2 = resolveControlTarget(catalog, repo, selector);
|
|
798
|
+
const result = await c.patch("/api/v1/actions/workflows", {
|
|
799
|
+
repoFullName: repo,
|
|
800
|
+
path: path2,
|
|
801
|
+
...controls
|
|
802
|
+
});
|
|
803
|
+
deps.output(opts, result, (r) => console.log(formatControlsResult(verb, r)));
|
|
804
|
+
}
|
|
805
|
+
for (const enabled of [true, false]) {
|
|
806
|
+
const verb = enabled ? "enable" : "disable";
|
|
807
|
+
common2(
|
|
808
|
+
workflows.command(verb).description(
|
|
809
|
+
enabled ? "Turn a workflow back on (owner/admin)" : "Turn a workflow off: no pushes, schedules or dispatches run it until enabled (owner/admin)"
|
|
810
|
+
).argument("<repo>", "repository in owner/repo format").argument("<workflow>", "workflow path, name, file name (ci.yml) or id").option("-y, --yes", "skip the confirmation")
|
|
811
|
+
).action(async (repo, selector, opts) => {
|
|
812
|
+
try {
|
|
813
|
+
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.`;
|
|
814
|
+
await writeControls(repo, selector, { enabled }, question, `${verb}d`, opts);
|
|
815
|
+
} catch (e) {
|
|
816
|
+
deps.fail(e, opts);
|
|
817
|
+
}
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
common2(
|
|
821
|
+
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>", "this workflow walks exactly these BYOK providers instead of the Actions router (e.g. e2b,blaxel)").option("--inherit-order", "drop the workflow's order: it follows the Actions router").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")
|
|
822
|
+
).action(async (repo, selector, opts) => {
|
|
823
|
+
try {
|
|
824
|
+
const controls = setControls(opts);
|
|
825
|
+
await writeControls(
|
|
826
|
+
repo,
|
|
827
|
+
selector,
|
|
828
|
+
controls,
|
|
829
|
+
`Change workflow "${selector}" in ${repo} (${describeControls(controls)})?`,
|
|
830
|
+
"set",
|
|
831
|
+
opts
|
|
832
|
+
);
|
|
833
|
+
} catch (e) {
|
|
834
|
+
deps.fail(e, opts);
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// src/actions-repos.ts
|
|
840
|
+
var FORK_PRS = { allow: true, refuse: false };
|
|
841
|
+
function plural2(n, noun) {
|
|
842
|
+
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
843
|
+
}
|
|
844
|
+
function formatIn(iso, now = Date.now()) {
|
|
845
|
+
const s = Math.max(0, Math.round((Date.parse(iso) - now) / 1e3));
|
|
846
|
+
if (s < 60) return `in ${s}s`;
|
|
847
|
+
const m = Math.round(s / 60);
|
|
848
|
+
if (m < 60) return `in ${m}m`;
|
|
849
|
+
const h = Math.round(m / 60);
|
|
850
|
+
if (h < 48) return `in ${h}h`;
|
|
851
|
+
return `in ${Math.round(h / 24)}d`;
|
|
852
|
+
}
|
|
853
|
+
function pollText(r, now) {
|
|
854
|
+
if (!r.enabled) return null;
|
|
855
|
+
if (r.pollSchedule === "never") return "not polled yet";
|
|
856
|
+
if (!r.nextPollDueAt) return null;
|
|
857
|
+
return Date.parse(r.nextPollDueAt) <= now ? "poll due" : `next poll ${formatIn(r.nextPollDueAt, now)}`;
|
|
858
|
+
}
|
|
859
|
+
function formatRepoRow(r, now = Date.now()) {
|
|
860
|
+
const head = r.enabled ? pc5.green("enabled") : pc5.dim("disabled");
|
|
861
|
+
const via = r.authType === "github_app" ? "github-app" : r.authType;
|
|
862
|
+
const parts = [
|
|
863
|
+
safeTerm(via),
|
|
864
|
+
safeTerm(r.defaultBranch),
|
|
865
|
+
r.workflowPaths.length > 0 ? plural2(r.workflowPaths.length, "workflow") : "no workflows yet"
|
|
866
|
+
];
|
|
867
|
+
if (r.runs) {
|
|
868
|
+
parts.push(plural2(r.runs.total, "run"));
|
|
869
|
+
if (r.runs.lastRunState && r.runs.lastRunQueuedAt) {
|
|
870
|
+
parts.push(`last ${conclusionLabel(r.runs.lastRunState)} ${formatAgo(r.runs.lastRunQueuedAt, now)}`);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
const poll = pollText(r, now);
|
|
874
|
+
if (poll) parts.push(poll);
|
|
875
|
+
if (r.forkPullRequests) parts.push("fork PRs on");
|
|
876
|
+
const error = r.lastPollError ? pc5.red(` poll error: ${safeTerm(r.lastPollError)}`) : "";
|
|
877
|
+
return `${head} ${safeTerm(r.fullName)} ${pc5.dim(parts.join(" \xB7 "))}${error}`;
|
|
878
|
+
}
|
|
879
|
+
function formatBranchRow(b, now = Date.now(), defaultBranch) {
|
|
880
|
+
const isDefault = defaultBranch !== void 0 && b.ref === `refs/heads/${defaultBranch}`;
|
|
881
|
+
const at = Number.isNaN(Date.parse(b.lastRunAt)) ? null : formatAgo(b.lastRunAt, now);
|
|
882
|
+
return [
|
|
883
|
+
safeTerm(b.ref) + (isDefault ? pc5.dim(" (default)") : ""),
|
|
884
|
+
...b.prNumber !== null ? [`PR #${b.prNumber}`] : [],
|
|
885
|
+
b.watched ? pc5.green("watched") : pc5.dim("history only"),
|
|
886
|
+
plural2(b.runCount, "run"),
|
|
887
|
+
...at ? [b.runCount > 0 ? `last ${at}` : pc5.dim(`moved ${at}`)] : [],
|
|
888
|
+
...b.latestRunId ? [pc5.dim(safeTerm(b.latestRunId))] : []
|
|
889
|
+
].join(" ");
|
|
890
|
+
}
|
|
891
|
+
function printDiscovery(d) {
|
|
892
|
+
if (d.error) {
|
|
893
|
+
console.log(pc5.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
console.log(pc5.dim(`discovery: ${d.workflowsFound ? "workflows found" : "no workflows yet"}${d.seeded ? ", cursors seeded" : ""}`));
|
|
897
|
+
}
|
|
898
|
+
function withRetryAfter(error) {
|
|
899
|
+
if (!(error instanceof PlatformApiError) || error.status !== 429) return error;
|
|
900
|
+
const next = error.details?.nextAllowedAt;
|
|
901
|
+
if (typeof next !== "string") return error;
|
|
902
|
+
const rewritten = new PlatformApiError(error.status, `${error.message}; retry after ${next} (${formatIn(next)})`, error.body);
|
|
903
|
+
rewritten.retryAfterMs = error.retryAfterMs;
|
|
904
|
+
return rewritten;
|
|
905
|
+
}
|
|
906
|
+
function parseForkPrs(value) {
|
|
907
|
+
if (!Object.prototype.hasOwnProperty.call(FORK_PRS, value)) {
|
|
908
|
+
throw new PlatformClientError("invalid_argument", `Invalid --fork-prs "${value}". Expected allow or refuse.`);
|
|
909
|
+
}
|
|
910
|
+
return FORK_PRS[value];
|
|
911
|
+
}
|
|
912
|
+
var repoIdBody = (opts) => opts.repoId !== void 0 ? { repoId: opts.repoId } : {};
|
|
913
|
+
var REPO_ID_HELP = "scope to one row when two installations grant the same name";
|
|
914
|
+
function registerReposCommands(actions, common2, deps) {
|
|
915
|
+
const { client: client2, output: output2, fail: fail3 } = deps;
|
|
916
|
+
const repos = actions.command("repos").description("List the org's connected repositories: run counts, last run and next poll");
|
|
917
|
+
common2(repos).action(async (opts) => {
|
|
918
|
+
try {
|
|
919
|
+
const data = await (await client2(opts)).get("/api/v1/actions/repos");
|
|
920
|
+
output2(opts, data, (d) => {
|
|
921
|
+
if (d.repos.length === 0) {
|
|
922
|
+
console.log("No repositories connected.");
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
for (const r of d.repos) console.log(formatRepoRow(r));
|
|
926
|
+
});
|
|
927
|
+
} catch (e) {
|
|
928
|
+
fail3(e, opts);
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
common2(
|
|
932
|
+
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")
|
|
933
|
+
).action(async (cloneUrl, opts) => {
|
|
934
|
+
try {
|
|
935
|
+
let body;
|
|
936
|
+
if (opts.sshKeyFile !== void 0) {
|
|
937
|
+
if (opts.token !== void 0 || opts.username !== void 0) {
|
|
938
|
+
throw new Error("Pass either --ssh-key-file or --token/--username, not both.");
|
|
939
|
+
}
|
|
940
|
+
body = {
|
|
941
|
+
authType: "ssh",
|
|
942
|
+
credential: readFileSync(opts.sshKeyFile, "utf8"),
|
|
943
|
+
...opts.knownHostsFile !== void 0 && {
|
|
944
|
+
knownHosts: readFileSync(opts.knownHostsFile, "utf8")
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
} else if (opts.username !== void 0) {
|
|
948
|
+
if (opts.token === void 0) throw new Error("--username requires --token.");
|
|
949
|
+
body = { authType: "basic", username: opts.username, credential: opts.token };
|
|
950
|
+
} else if (opts.token !== void 0) {
|
|
951
|
+
body = { authType: "token", credential: opts.token };
|
|
952
|
+
} else {
|
|
953
|
+
body = { authType: "none" };
|
|
954
|
+
}
|
|
955
|
+
if (opts.knownHostsFile !== void 0 && opts.sshKeyFile === void 0) {
|
|
956
|
+
throw new Error("--known-hosts-file requires --ssh-key-file.");
|
|
957
|
+
}
|
|
958
|
+
const result = await (await client2(opts)).post("/api/v1/actions/repos", {
|
|
959
|
+
cloneUrl,
|
|
960
|
+
...body,
|
|
961
|
+
...opts.name !== void 0 && { name: opts.name },
|
|
962
|
+
...opts.branch !== void 0 && { defaultBranch: opts.branch }
|
|
963
|
+
});
|
|
964
|
+
output2(opts, result, (r) => {
|
|
965
|
+
console.log(`connected ${pc5.cyan(safeTerm(r.fullName))} ${pc5.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);
|
|
966
|
+
printDiscovery(r.discovery);
|
|
967
|
+
});
|
|
968
|
+
} catch (e) {
|
|
969
|
+
fail3(e, opts);
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
common2(
|
|
973
|
+
repos.command("sync").description("Re-read the GitHub App installation so repos granted after install show up (owner/admin key)")
|
|
974
|
+
).action(async (opts) => {
|
|
975
|
+
try {
|
|
976
|
+
const result = await (await client2(opts)).post("/api/v1/actions/repos/sync", {});
|
|
977
|
+
output2(opts, result, (r) => {
|
|
978
|
+
for (const a of r.accounts) {
|
|
979
|
+
console.log(a.error === null ? `synced ${pc5.cyan(safeTerm(a.account))}` : `failed ${pc5.cyan(safeTerm(a.account))} ${pc5.red(safeTerm(a.error))}`);
|
|
980
|
+
}
|
|
981
|
+
console.log(pc5.dim(`${r.repos.length} repos visible`));
|
|
982
|
+
});
|
|
983
|
+
if (result.accounts.some((a) => a.error !== null)) process.exitCode = 1;
|
|
984
|
+
} catch (e) {
|
|
985
|
+
fail3(e, opts);
|
|
986
|
+
}
|
|
987
|
+
});
|
|
988
|
+
common2(
|
|
989
|
+
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)
|
|
990
|
+
).action(async (repo, opts) => {
|
|
991
|
+
try {
|
|
992
|
+
const result = await (await client2(opts)).patch("/api/v1/actions/repos", {
|
|
993
|
+
fullName: repo,
|
|
994
|
+
enabled: true,
|
|
995
|
+
...repoIdBody(opts)
|
|
996
|
+
});
|
|
997
|
+
output2(opts, result, (r) => {
|
|
998
|
+
console.log(`enabled ${pc5.cyan(safeTerm(r.fullName))}`);
|
|
999
|
+
if (r.discovery) printDiscovery(r.discovery);
|
|
1000
|
+
});
|
|
1001
|
+
} catch (e) {
|
|
1002
|
+
fail3(e, opts);
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
common2(
|
|
1006
|
+
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)
|
|
1007
|
+
).action(async (repo, opts) => {
|
|
1008
|
+
try {
|
|
1009
|
+
const result = await (await client2(opts)).patch("/api/v1/actions/repos", {
|
|
1010
|
+
fullName: repo,
|
|
1011
|
+
enabled: false,
|
|
1012
|
+
...repoIdBody(opts)
|
|
1013
|
+
});
|
|
1014
|
+
output2(opts, result, (r) => console.log(`disabled ${pc5.cyan(safeTerm(r.fullName))}`));
|
|
1015
|
+
} catch (e) {
|
|
1016
|
+
fail3(e, opts);
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
common2(
|
|
1020
|
+
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")
|
|
1021
|
+
).action(async (repo, opts) => {
|
|
1022
|
+
try {
|
|
1023
|
+
await confirmWrite(`Poll ${repo} now? New commits on its watched refs start the runs their workflows call for.`, opts);
|
|
1024
|
+
const c = await client2(opts);
|
|
1025
|
+
let result;
|
|
1026
|
+
try {
|
|
1027
|
+
result = await c.post("/api/v1/actions/repos/poll", { fullName: repo, ...repoIdBody(opts) });
|
|
1028
|
+
} catch (e) {
|
|
1029
|
+
throw withRetryAfter(e);
|
|
1030
|
+
}
|
|
1031
|
+
output2(opts, result, (r) => {
|
|
1032
|
+
console.log(`polled ${pc5.cyan(safeTerm(r.fullName))} ${plural2(r.createdRunIds.length, "run")} started`);
|
|
1033
|
+
if (r.error) console.log(pc5.red(`poll error: ${safeTerm(r.error)}`));
|
|
1034
|
+
});
|
|
1035
|
+
if (result.error) process.exitCode = 1;
|
|
1036
|
+
} catch (e) {
|
|
1037
|
+
fail3(e, opts);
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
common2(
|
|
1041
|
+
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")
|
|
1042
|
+
).action(async (repo, opts) => {
|
|
1043
|
+
try {
|
|
1044
|
+
const forkPullRequests = parseForkPrs(opts.forkPrs);
|
|
1045
|
+
await confirmWrite(
|
|
1046
|
+
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.`,
|
|
1047
|
+
opts
|
|
1048
|
+
);
|
|
1049
|
+
const result = await (await client2(opts)).patch("/api/v1/actions/repos", {
|
|
1050
|
+
fullName: repo,
|
|
1051
|
+
forkPullRequests,
|
|
1052
|
+
...repoIdBody(opts)
|
|
1053
|
+
});
|
|
1054
|
+
output2(
|
|
1055
|
+
opts,
|
|
1056
|
+
result,
|
|
1057
|
+
(r) => console.log(`fork PRs ${r.forkPullRequests === false ? "refused" : "allowed"} ${pc5.cyan(safeTerm(r.fullName))}`)
|
|
1058
|
+
);
|
|
1059
|
+
} catch (e) {
|
|
1060
|
+
fail3(e, opts);
|
|
1061
|
+
}
|
|
1062
|
+
});
|
|
1063
|
+
common2(
|
|
1064
|
+
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)
|
|
1065
|
+
).action(async (repo, opts) => {
|
|
1066
|
+
try {
|
|
1067
|
+
const data = await (await client2(opts)).get("/api/v1/actions/repos/branches", {
|
|
1068
|
+
repo,
|
|
1069
|
+
repoId: opts.repoId,
|
|
1070
|
+
q: opts.search,
|
|
1071
|
+
archived: opts.archived ? "1" : void 0
|
|
1072
|
+
});
|
|
1073
|
+
output2(opts, data, (d) => {
|
|
1074
|
+
console.log(`${pc5.bold(safeTerm(d.repo))} ${pc5.dim(`default: ${safeTerm(d.defaultBranch)}`)}`);
|
|
1075
|
+
if (d.branches.length === 0) {
|
|
1076
|
+
console.log("No branches found.");
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
const now = Date.now();
|
|
1080
|
+
for (const b of d.branches) console.log(formatBranchRow(b, now, d.defaultBranch));
|
|
1081
|
+
});
|
|
1082
|
+
} catch (e) {
|
|
1083
|
+
fail3(e, opts);
|
|
1084
|
+
}
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// src/actions-integrations.ts
|
|
1089
|
+
import pc6 from "picocolors";
|
|
1090
|
+
function formatInstallationRow(i) {
|
|
1091
|
+
const head = i.suspended ? pc6.yellow(safeTerm(i.account)) : pc6.cyan(safeTerm(i.account));
|
|
1092
|
+
const parts = [
|
|
1093
|
+
i.accountType ? safeTerm(i.accountType) : "account",
|
|
1094
|
+
i.repoSelection === "all" ? "all repos" : "selected repos",
|
|
1095
|
+
`${i.repos.granted} granted, ${i.repos.enabled} enabled`,
|
|
1096
|
+
...i.suspended ? [pc6.yellow(`suspended ${safeTerm(i.suspendedAt ?? "")}`.trim())] : [],
|
|
1097
|
+
pc6.dim(`installed ${safeTerm(i.installedAt)}`)
|
|
1098
|
+
];
|
|
1099
|
+
return `${head} ${parts.join(" ")}`;
|
|
195
1100
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const sandbox = lane === "sandboxes";
|
|
200
|
-
const orderType = s.marketOrderType ?? (sandbox ? "inherit" : "\u2014");
|
|
201
|
-
const orderSuffix = sandbox && s.marketOrderType == null ? pc.dim(` (Actions: ${s.actionsMarketOrderType ?? "\u2014"})`) : "";
|
|
202
|
-
console.log(`order type: ${orderType}${orderSuffix}`);
|
|
203
|
-
const capSuffix = sandbox && s.marketCap == null ? pc.dim(` (inherits Actions: ${fmtRate(s.actionsMarketCap)})`) : "";
|
|
204
|
-
console.log(`general cap: ${fmtRate(s.marketCap)}${capSuffix}`);
|
|
205
|
-
console.log("per-size caps:");
|
|
206
|
-
for (const size of PLATFORM_SIZES) {
|
|
207
|
-
const cap = s.marketCaps?.[size];
|
|
208
|
-
console.log(
|
|
209
|
-
` ${size.padEnd(7)} ${fmtRate(cap)}${cap ? "" : fmtRef(s.referencePrices?.[size])}`
|
|
210
|
-
);
|
|
1101
|
+
function formatInstallations(data) {
|
|
1102
|
+
if (data.installations.length === 0) {
|
|
1103
|
+
return ["No GitHub App installations. Run `compute actions installations install-url` for where to install it."];
|
|
211
1104
|
}
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
if (resources.length === 0) console.log(" \u2014");
|
|
217
|
-
for (const [provider, r] of resources) {
|
|
218
|
-
console.log(
|
|
219
|
-
` ${provider} ${r.cpus ?? "?"} vCPU / ${r.memoryMb ?? "?"} MB${r.ephemeralDiskMb ? ` / ${r.ephemeralDiskMb} MB disk` : ""}`
|
|
220
|
-
);
|
|
1105
|
+
const lines = [];
|
|
1106
|
+
for (const i of data.installations) {
|
|
1107
|
+
lines.push(formatInstallationRow(i));
|
|
1108
|
+
if (i.configureUrl) lines.push(` ${pc6.dim(`configure: ${safeTerm(i.configureUrl)}`)}`);
|
|
221
1109
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const snap = Object.entries(s.snapshotPool);
|
|
228
|
-
console.log("snapshot pool:");
|
|
229
|
-
if (snap.length === 0) console.log(" \u2014");
|
|
230
|
-
for (const [entry, cap] of snap) console.log(` ${entry} ${cap}`);
|
|
1110
|
+
return lines;
|
|
1111
|
+
}
|
|
1112
|
+
function formatSlack(s) {
|
|
1113
|
+
if (!s.installed) {
|
|
1114
|
+
return ["Slack is not connected. Run `compute actions slack install-url` for where to connect it."];
|
|
231
1115
|
}
|
|
1116
|
+
const channel = s.channelId ? `${s.channelName ? `#${safeTerm(s.channelName)} ` : ""}${pc6.dim(safeTerm(s.channelId))}` : pc6.gray("no channel picked");
|
|
1117
|
+
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");
|
|
1118
|
+
return [
|
|
1119
|
+
`workspace: ${s.teamName ? safeTerm(s.teamName) : pc6.gray("(unnamed)")}`,
|
|
1120
|
+
`channel: ${channel}`,
|
|
1121
|
+
`notify on: ${s.notifyOn === "failure" ? "failures and cancels" : "every conclusion"}`,
|
|
1122
|
+
`daily brief: ${brief}`
|
|
1123
|
+
];
|
|
232
1124
|
}
|
|
233
|
-
function
|
|
234
|
-
if (
|
|
235
|
-
return
|
|
236
|
-
new PlatformApiError(
|
|
237
|
-
403,
|
|
238
|
-
`Only org owners/admins can ${verb} ${lane} settings`,
|
|
239
|
-
e.body
|
|
240
|
-
),
|
|
241
|
-
opts
|
|
242
|
-
);
|
|
1125
|
+
function formatInstallLink(link, what) {
|
|
1126
|
+
if (!link.configured || link.url === null) {
|
|
1127
|
+
return [what === "github" ? "This deployment has no GitHub App configured." : "This deployment has no Slack app configured."];
|
|
243
1128
|
}
|
|
244
|
-
return
|
|
1129
|
+
return [
|
|
1130
|
+
safeTerm(link.url),
|
|
1131
|
+
pc6.dim(
|
|
1132
|
+
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."
|
|
1133
|
+
)
|
|
1134
|
+
];
|
|
245
1135
|
}
|
|
246
|
-
function
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
1136
|
+
function registerIntegrationsCommands(actions, common2, deps) {
|
|
1137
|
+
const { client: client2, output: output2, fail: fail3 } = deps;
|
|
1138
|
+
const print = (lines) => {
|
|
1139
|
+
for (const line of lines) console.log(line);
|
|
1140
|
+
};
|
|
1141
|
+
const installations = common2(
|
|
1142
|
+
actions.command("installations").description("List the org's GitHub App installations (account, repo selection and counts, suspension)")
|
|
251
1143
|
).action(async (opts) => {
|
|
252
1144
|
try {
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
deps.output(opts, res, (s) => printLaneSettings(s, lane));
|
|
1145
|
+
const data = await (await client2(opts)).get("/api/v1/actions/installations");
|
|
1146
|
+
output2(opts, data, (d) => print(formatInstallations(d)));
|
|
256
1147
|
} catch (e) {
|
|
257
|
-
|
|
1148
|
+
fail3(e, opts);
|
|
258
1149
|
}
|
|
259
1150
|
});
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
"--cap <size=rate>",
|
|
263
|
-
"per-size cap: <size>=<usd>/<unit> or <size>=none to clear (repeatable)",
|
|
264
|
-
(v, a) => a.concat(v),
|
|
265
|
-
[]
|
|
266
|
-
).option("--general-cap <rate|none>", 'whole-lane price cap (e.g. 0.40/hour); "none" clears it').option(
|
|
267
|
-
"--order-type <type>",
|
|
268
|
-
lane === "sandboxes" ? "market order type: limit | market | inherit (the Actions value)" : "market order type: limit | market"
|
|
269
|
-
).option(
|
|
270
|
-
"--order <providers>",
|
|
271
|
-
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
|
-
)
|
|
1151
|
+
common2(
|
|
1152
|
+
installations.command("install-url").description("Print where an owner/admin installs the GitHub App into another account")
|
|
273
1153
|
).action(async (opts) => {
|
|
274
1154
|
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));
|
|
1155
|
+
const data = await (await client2(opts)).get("/api/v1/actions/installations/install-url");
|
|
1156
|
+
output2(opts, data, (d) => print(formatInstallLink(d, "github")));
|
|
320
1157
|
} catch (e) {
|
|
321
|
-
|
|
1158
|
+
fail3(e, opts);
|
|
1159
|
+
}
|
|
1160
|
+
});
|
|
1161
|
+
const slack = common2(
|
|
1162
|
+
actions.command("slack").description("Show the org's Slack connection (workspace, channel, notify rule, daily brief; owner/admin)")
|
|
1163
|
+
).action(async (opts) => {
|
|
1164
|
+
try {
|
|
1165
|
+
const data = await (await client2(opts)).get("/api/v1/actions/slack");
|
|
1166
|
+
output2(opts, data, (d) => print(formatSlack(d)));
|
|
1167
|
+
} catch (e) {
|
|
1168
|
+
fail3(e, opts);
|
|
1169
|
+
}
|
|
1170
|
+
});
|
|
1171
|
+
common2(
|
|
1172
|
+
slack.command("install-url").description("Print where an owner/admin connects a Slack workspace")
|
|
1173
|
+
).action(async (opts) => {
|
|
1174
|
+
try {
|
|
1175
|
+
const data = await (await client2(opts)).get("/api/v1/actions/slack/install-url");
|
|
1176
|
+
output2(opts, data, (d) => print(formatInstallLink(d, "slack")));
|
|
1177
|
+
} catch (e) {
|
|
1178
|
+
fail3(e, opts);
|
|
322
1179
|
}
|
|
323
1180
|
});
|
|
324
1181
|
}
|
|
@@ -373,7 +1230,7 @@ function formatSchedule(data, nextCommand) {
|
|
|
373
1230
|
hourCycle: "h23",
|
|
374
1231
|
timeZoneName: "short"
|
|
375
1232
|
});
|
|
376
|
-
const lines = [
|
|
1233
|
+
const lines = [pc7.bold(`Upcoming fires (${safeTerm(data.timeZone)})`)];
|
|
377
1234
|
const fires = data.upcoming.flatMap((schedule) => schedule.occurrences.map((at) => ({ at, schedule }))).sort((a, b) => a.at.localeCompare(b.at));
|
|
378
1235
|
if (fires.length === 0) lines.push("No upcoming fires.");
|
|
379
1236
|
for (const { at, schedule } of fires) {
|
|
@@ -383,7 +1240,7 @@ function formatSchedule(data, nextCommand) {
|
|
|
383
1240
|
const remaining = schedule.occurrenceCount - schedule.occurrences.length;
|
|
384
1241
|
if (remaining > 0) lines.push(`+${remaining.toLocaleString("en-US")} more scheduled for ${safeTerm(schedule.workflowName || schedule.workflowPath)} ${safeTerm(schedule.repoFullName)} ${safeTerm(schedule.description)}`);
|
|
385
1242
|
}
|
|
386
|
-
lines.push("",
|
|
1243
|
+
lines.push("", pc7.bold(`Past runs (${safeTerm(data.timeZone)})`));
|
|
387
1244
|
if (data.runs.length === 0) lines.push("No past runs found.");
|
|
388
1245
|
for (const run of data.runs) {
|
|
389
1246
|
lines.push([
|
|
@@ -455,7 +1312,7 @@ async function fetchRunSummary(c, runId) {
|
|
|
455
1312
|
} catch (e) {
|
|
456
1313
|
if (!(e instanceof PlatformApiError && e.status === 404)) {
|
|
457
1314
|
console.error(
|
|
458
|
-
|
|
1315
|
+
pc7.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`)
|
|
459
1316
|
);
|
|
460
1317
|
}
|
|
461
1318
|
return null;
|
|
@@ -465,9 +1322,9 @@ function fail(error, opts = {}) {
|
|
|
465
1322
|
if (opts.json) {
|
|
466
1323
|
process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + "\n");
|
|
467
1324
|
} else if (error instanceof PlatformApiError) {
|
|
468
|
-
console.error(
|
|
1325
|
+
console.error(pc7.red(`Error (${error.status}): ${safeTermText(error.message)}`));
|
|
469
1326
|
} else {
|
|
470
|
-
console.error(
|
|
1327
|
+
console.error(pc7.red(`Error: ${safeTermText(error instanceof Error ? error.message : String(error))}`));
|
|
471
1328
|
}
|
|
472
1329
|
process.exit(1);
|
|
473
1330
|
}
|
|
@@ -492,39 +1349,24 @@ function formatDuration(ms) {
|
|
|
492
1349
|
function shortSha(sha) {
|
|
493
1350
|
return sha.slice(0, 8);
|
|
494
1351
|
}
|
|
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
1352
|
function formatRunRow(run) {
|
|
512
1353
|
const num = run.runNumber === null ? "-" : `#${run.runNumber}`;
|
|
513
1354
|
return [
|
|
514
1355
|
run.id,
|
|
515
|
-
|
|
1356
|
+
pc7.dim(num),
|
|
516
1357
|
run.workflowName || run.workflowPath,
|
|
517
1358
|
conclusionLabel(run.conclusion),
|
|
518
|
-
|
|
1359
|
+
pc7.dim(`${run.repoFullName}@${run.ref}`),
|
|
519
1360
|
shortSha(run.headSha),
|
|
520
1361
|
formatDuration(run.durationMs),
|
|
521
|
-
run.startedAt
|
|
1362
|
+
run.startedAt,
|
|
1363
|
+
...run.archivedAt ? [pc7.dim("archived")] : []
|
|
522
1364
|
].join(" ");
|
|
523
1365
|
}
|
|
524
1366
|
function formatRunDetail(run, runUrl) {
|
|
525
1367
|
const lines = [];
|
|
526
|
-
lines.push(`${
|
|
527
|
-
lines.push(
|
|
1368
|
+
lines.push(`${pc7.bold(run.workflowName || run.workflowPath)} ${conclusionLabel(run.conclusion)}`);
|
|
1369
|
+
lines.push(pc7.dim(`run ${run.id}${run.runNumber === null ? "" : ` #${run.runNumber}`}`));
|
|
528
1370
|
lines.push(`${run.repoFullName} @ ${run.ref} ${shortSha(run.headSha)} ${run.event}${run.prNumber ? ` PR #${run.prNumber}` : ""}`);
|
|
529
1371
|
lines.push(`title: ${run.title}`);
|
|
530
1372
|
lines.push(`started: ${run.startedAt} duration: ${formatDuration(run.durationMs)}`);
|
|
@@ -535,16 +1377,16 @@ function formatRunDetail(run, runUrl) {
|
|
|
535
1377
|
if (run.benchmarks && run.benchmarks.length > 0) lines.push(`benchmarks: ${resultsSummary(run.benchmarks)}`);
|
|
536
1378
|
if (run.jobs.length > 0) {
|
|
537
1379
|
lines.push("");
|
|
538
|
-
lines.push(
|
|
1380
|
+
lines.push(pc7.bold("jobs"));
|
|
539
1381
|
for (const job of run.jobs) {
|
|
540
1382
|
const placement = job.provider ? `${job.provider}${job.region ? `:${job.region}` : ""}` : "-";
|
|
541
1383
|
lines.push(` ${job.id} ${job.name} ${conclusionLabel(job.state)} ${placement} ${formatDuration(job.durationMs)}`);
|
|
542
1384
|
for (const attempt of job.placementAttempts) {
|
|
543
|
-
lines.push(
|
|
1385
|
+
lines.push(pc7.dim(` placement failed on ${attempt.provider}${attempt.region ? `:${attempt.region}` : ""}: ${attempt.error}`));
|
|
544
1386
|
}
|
|
545
1387
|
for (const step of job.steps) {
|
|
546
1388
|
const exit = step.exitCode === null ? "" : ` (exit ${step.exitCode})`;
|
|
547
|
-
lines.push(
|
|
1389
|
+
lines.push(pc7.dim(` ${step.name} ${step.state}${exit} ${formatDuration(step.durationMs)}`));
|
|
548
1390
|
}
|
|
549
1391
|
}
|
|
550
1392
|
}
|
|
@@ -580,22 +1422,22 @@ function formatRate(n) {
|
|
|
580
1422
|
return n === null ? "-" : `${Math.round(n * 100)}%`;
|
|
581
1423
|
}
|
|
582
1424
|
function formatRunResults(results) {
|
|
583
|
-
if (results.length === 0) return
|
|
1425
|
+
if (results.length === 0) return pc7.dim("no benchmark results on this run");
|
|
584
1426
|
const lines = [];
|
|
585
1427
|
for (const [i, result] of results.entries()) {
|
|
586
1428
|
if (i > 0) lines.push("");
|
|
587
|
-
lines.push(`${
|
|
588
|
-
lines.push(
|
|
1429
|
+
lines.push(`${pc7.bold(safeTerm(result.benchmarkName))} ${safeTerm(result.status)}`);
|
|
1430
|
+
lines.push(pc7.dim(`${safeTerm(result.benchmarkRunId)} ${safeTerm(result.dashboardUrl)}`));
|
|
589
1431
|
const rows = [...overallRows(result)].sort((a, b) => (b.compositeScore ?? -1) - (a.compositeScore ?? -1));
|
|
590
1432
|
if (rows.length === 0) {
|
|
591
|
-
lines.push(
|
|
1433
|
+
lines.push(pc7.dim(result.status === "failed" ? " failed before reporting results" : " no results yet"));
|
|
592
1434
|
continue;
|
|
593
1435
|
}
|
|
594
1436
|
const width = Math.max(8, ...rows.map((p2) => p2.provider.length));
|
|
595
|
-
lines.push(
|
|
1437
|
+
lines.push(pc7.dim(` ${"provider".padEnd(width)} ${"score".padStart(7)} ${"success".padStart(7)} metrics`));
|
|
596
1438
|
for (const p2 of rows) {
|
|
597
1439
|
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 ?
|
|
1440
|
+
const status = p2.skipped ? pc7.dim(`skipped${p2.skipReason ? `: ${safeTerm(p2.skipReason)}` : ""}`) : metrics;
|
|
599
1441
|
lines.push(` ${safeTerm(p2.provider).padEnd(width)} ${formatScore(p2.compositeScore).padStart(7)} ${formatRate(p2.successRate).padStart(7)} ${status}`);
|
|
600
1442
|
}
|
|
601
1443
|
}
|
|
@@ -603,18 +1445,18 @@ function formatRunResults(results) {
|
|
|
603
1445
|
}
|
|
604
1446
|
function formatRunInspection(run) {
|
|
605
1447
|
const lines = [];
|
|
606
|
-
lines.push(`${
|
|
607
|
-
lines.push(
|
|
1448
|
+
lines.push(`${pc7.bold("run")} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? "" : ` #${run.runNumber}`}`);
|
|
1449
|
+
lines.push(pc7.dim(run.id));
|
|
608
1450
|
lines.push(`${safeTerm(run.ref)} ${shortSha(run.headSha)} ${safeTerm(run.event)}`);
|
|
609
1451
|
lines.push(`queued: ${run.queuedAt} started: ${run.startedAt} finished: ${run.finishedAt}`);
|
|
610
1452
|
if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);
|
|
611
1453
|
if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);
|
|
612
|
-
if (run.blockedReason) lines.push(
|
|
1454
|
+
if (run.blockedReason) lines.push(pc7.red(`blocked: ${safeTerm(run.blockedReason)}`));
|
|
613
1455
|
if (run.concurrencyGroup) lines.push(`concurrency: ${safeTerm(run.concurrencyGroup)}`);
|
|
614
1456
|
if (run.providerOverride) lines.push(`dispatched to: ${safeTerm(run.providerOverride)}`);
|
|
615
1457
|
if (run.definitionStale) {
|
|
616
1458
|
const parsed = run.workflowParsedFromSha ? shortSha(run.workflowParsedFromSha) : "unknown";
|
|
617
|
-
lines.push(
|
|
1459
|
+
lines.push(pc7.yellow(`definition: stored parse is from ${parsed}, not this head \u2014 context may be newer than the run`));
|
|
618
1460
|
}
|
|
619
1461
|
if (run.dispatchInputs && Object.keys(run.dispatchInputs).length > 0) {
|
|
620
1462
|
lines.push(`inputs: ${Object.entries(run.dispatchInputs).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(" ")}`);
|
|
@@ -625,24 +1467,24 @@ function formatRunInspection(run) {
|
|
|
625
1467
|
}
|
|
626
1468
|
if (run.caches.length > 0) {
|
|
627
1469
|
lines.push("");
|
|
628
|
-
lines.push(
|
|
1470
|
+
lines.push(pc7.bold("caches"));
|
|
629
1471
|
for (const cache of run.caches) {
|
|
630
1472
|
const action = [cache.restoredAt ? "restored" : null, cache.savedAt ? "saved" : null].filter(Boolean).join("+");
|
|
631
|
-
lines.push(` ${safeTerm(cache.key)} ${
|
|
1473
|
+
lines.push(` ${safeTerm(cache.key)} ${pc7.dim(`${action} ${safeTerm(cache.scopeRef)} ${cache.sizeBytes}B`)}`);
|
|
632
1474
|
}
|
|
633
1475
|
}
|
|
634
1476
|
if (run.jobs.length > 0) {
|
|
635
1477
|
lines.push("");
|
|
636
|
-
lines.push(
|
|
1478
|
+
lines.push(pc7.bold("jobs"));
|
|
637
1479
|
for (const job of run.jobs) {
|
|
638
1480
|
const placement = job.provider ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ""}` : "-";
|
|
639
1481
|
lines.push(` ${safeTerm(job.name)} ${conclusionLabel(job.state)} ${placement}`);
|
|
640
|
-
lines.push(
|
|
1482
|
+
lines.push(pc7.dim(` ${job.id}`));
|
|
641
1483
|
if (job.runsOn.length > 0 || job.resolvedRunsOn !== null) {
|
|
642
1484
|
const resolved = job.resolvedRunsOn !== null && job.resolvedRunsOn.join(",") !== job.runsOn.join(",") ? ` \u2192 ${job.resolvedRunsOn.map(safeTerm).join(", ")}` : "";
|
|
643
1485
|
lines.push(` runs-on: ${job.runsOn.map(safeTerm).join(", ") || "(none)"}${resolved}`);
|
|
644
1486
|
}
|
|
645
|
-
if (job.runsOnHasExpression) lines.push(
|
|
1487
|
+
if (job.runsOnHasExpression) lines.push(pc7.dim(" runs-on resolves at runtime (expression)"));
|
|
646
1488
|
if (job.container) lines.push(` container: ${safeTerm(job.container)}`);
|
|
647
1489
|
if (job.runnerImage) lines.push(` image: ${safeTerm(job.runnerImage)}`);
|
|
648
1490
|
if (job.placementHint) {
|
|
@@ -659,9 +1501,9 @@ function formatRunInspection(run) {
|
|
|
659
1501
|
if (job.matrix) {
|
|
660
1502
|
lines.push(` matrix: ${Object.entries(job.matrix).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(" ")}`);
|
|
661
1503
|
}
|
|
662
|
-
if (job.failureReason) lines.push(
|
|
1504
|
+
if (job.failureReason) lines.push(pc7.red(` failed: ${safeTerm(job.failureReason)}`));
|
|
663
1505
|
for (const attempt of job.placementAttempts) {
|
|
664
|
-
lines.push(
|
|
1506
|
+
lines.push(pc7.dim(` placement failed on ${safeTerm(attempt.provider)}${attempt.region ? `:${safeTerm(attempt.region)}` : ""}: ${safeTerm(attempt.error)}`));
|
|
665
1507
|
}
|
|
666
1508
|
}
|
|
667
1509
|
}
|
|
@@ -669,7 +1511,7 @@ function formatRunInspection(run) {
|
|
|
669
1511
|
}
|
|
670
1512
|
function formatRunSummary(summary) {
|
|
671
1513
|
const lines = [];
|
|
672
|
-
lines.push(
|
|
1514
|
+
lines.push(pc7.bold(`failures \u2014 run ${summary.runId} ${conclusionLabel(summary.conclusion)}`));
|
|
673
1515
|
if (summary.failures.length === 0) {
|
|
674
1516
|
lines.push(" no failed jobs");
|
|
675
1517
|
return lines.join("\n");
|
|
@@ -677,7 +1519,7 @@ function formatRunSummary(summary) {
|
|
|
677
1519
|
for (const job of summary.failures) {
|
|
678
1520
|
const placement = job.provider ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ""}` : "-";
|
|
679
1521
|
lines.push(` ${job.id} ${safeTerm(job.name)} ${conclusionLabel(job.conclusion)} ${placement}`);
|
|
680
|
-
if (job.failureReason) lines.push(
|
|
1522
|
+
if (job.failureReason) lines.push(pc7.dim(` ${safeTerm(job.failureReason)}`));
|
|
681
1523
|
for (const step of job.failedSteps) {
|
|
682
1524
|
const exit = step.exitCode === null ? "" : ` (exit ${step.exitCode})`;
|
|
683
1525
|
lines.push(` step ${step.ordinal} ${safeTerm(step.name)}${exit}`);
|
|
@@ -685,7 +1527,7 @@ function formatRunSummary(summary) {
|
|
|
685
1527
|
if (job.excerpt) {
|
|
686
1528
|
const scope = job.excerpt.stepOrdinal === null ? "job log" : `step ${job.excerpt.stepOrdinal}`;
|
|
687
1529
|
const cut = job.excerpt.truncated ? ", truncated" : "";
|
|
688
|
-
lines.push(
|
|
1530
|
+
lines.push(pc7.dim(` \u2500\u2500 ${scope} tail${cut} \u2500\u2500`));
|
|
689
1531
|
for (const line of job.excerpt.text.split("\n")) lines.push(` ${safeTerm(line)}`);
|
|
690
1532
|
}
|
|
691
1533
|
}
|
|
@@ -778,24 +1620,21 @@ async function* followRunLogs(client2, runId, jobs, step) {
|
|
|
778
1620
|
await new Promise((r) => setTimeout(r, 1e3));
|
|
779
1621
|
}
|
|
780
1622
|
}
|
|
781
|
-
function safeTerm(s) {
|
|
782
|
-
return s.replace(/[\u0000-\u001F\u007F-\u009F]/g, "\uFFFD");
|
|
783
|
-
}
|
|
784
1623
|
function formatRunHistory(history) {
|
|
785
1624
|
const lines = [];
|
|
786
1625
|
const parts = Object.entries(history.conclusions).map(([c, n]) => `${n} ${c}`).join(", ");
|
|
787
1626
|
lines.push(`last ${history.runCount} runs: ${parts || "none"}`);
|
|
788
1627
|
if (history.jobs.length > 0) {
|
|
789
1628
|
lines.push("");
|
|
790
|
-
lines.push(
|
|
1629
|
+
lines.push(pc7.bold("jobs"));
|
|
791
1630
|
for (const job of history.jobs) {
|
|
792
1631
|
const rate = job.runs > 0 ? Math.round(job.failedRuns / job.runs * 100) : 0;
|
|
793
|
-
const platform = job.failedBeforeSteps > 0 ?
|
|
1632
|
+
const platform = job.failedBeforeSteps > 0 ? pc7.dim(` (${job.failedBeforeSteps} failed before steps)`) : "";
|
|
794
1633
|
const count = `${job.failedRuns}/${job.runs} runs failed`;
|
|
795
|
-
const label = job.failedRuns > 0 ?
|
|
1634
|
+
const label = job.failedRuns > 0 ? pc7.red(count) : pc7.green(count);
|
|
796
1635
|
lines.push(` ${safeTerm(job.job)} ${label} ${rate}%${platform}`);
|
|
797
1636
|
for (const step of job.steps) {
|
|
798
|
-
lines.push(
|
|
1637
|
+
lines.push(pc7.dim(` step "${safeTerm(step.step)}" failed in ${step.failedRuns} run${step.failedRuns === 1 ? "" : "s"}`));
|
|
799
1638
|
}
|
|
800
1639
|
}
|
|
801
1640
|
}
|
|
@@ -804,46 +1643,39 @@ function formatRunHistory(history) {
|
|
|
804
1643
|
);
|
|
805
1644
|
if (failed.length > 0) {
|
|
806
1645
|
lines.push("");
|
|
807
|
-
lines.push(
|
|
1646
|
+
lines.push(pc7.bold("failed runs"));
|
|
808
1647
|
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)} ${
|
|
1648
|
+
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)");
|
|
1649
|
+
lines.push(` ${shortSha(run.headSha)} ${pc7.dim(run.startedAt)} ${blame}`);
|
|
811
1650
|
}
|
|
812
1651
|
}
|
|
813
1652
|
return lines.join("\n");
|
|
814
1653
|
}
|
|
1654
|
+
function keyStatusText(p2) {
|
|
1655
|
+
const status = p2.status === "connected" ? pc7.green("connected") : p2.status === "error" ? pc7.red("error") : pc7.gray("unconfigured");
|
|
1656
|
+
const hint = p2.keyHint ? ` ${pc7.dim(safeTerm(p2.keyHint))}` : "";
|
|
1657
|
+
const detail = p2.status === "error" && p2.statusDetail ? ` ${pc7.dim(`(${safeTerm(p2.statusDetail)})`)}` : "";
|
|
1658
|
+
return `${status}${hint}${detail}`;
|
|
1659
|
+
}
|
|
815
1660
|
function formatProviderRow(p2) {
|
|
816
|
-
const icon = p2.usable ?
|
|
817
|
-
const name = p2.usable ?
|
|
1661
|
+
const icon = p2.usable ? pc7.green("\u25CF") : pc7.gray("\u25CB");
|
|
1662
|
+
const name = p2.usable ? pc7.white(p2.provider) : pc7.gray(p2.provider);
|
|
818
1663
|
const flags = [
|
|
819
1664
|
p2.credential,
|
|
820
|
-
p2.actCapable ?
|
|
1665
|
+
p2.actCapable ? pc7.green("act") : pc7.gray("no-act"),
|
|
821
1666
|
p2.regions.length > 0 ? `regions: ${p2.regions.join(",")}` : "no region choice",
|
|
822
|
-
p2.position === null ?
|
|
1667
|
+
p2.position === null ? pc7.gray("not in provider order") : `order #${p2.position}`,
|
|
1668
|
+
...p2.credential !== "ambient" && p2.status !== void 0 ? [keyStatusText(p2)] : []
|
|
823
1669
|
].join(" ");
|
|
824
1670
|
return ` ${icon} ${name} ${flags}`;
|
|
825
1671
|
}
|
|
826
1672
|
function formatVerifyResult(r) {
|
|
827
1673
|
const ok = r.verified === true;
|
|
828
|
-
const head = ok ?
|
|
829
|
-
const detail = r.key.statusDetail ?
|
|
830
|
-
const act = r.key.actCapable ?
|
|
1674
|
+
const head = ok ? pc7.green("verified") : pc7.red("not verified");
|
|
1675
|
+
const detail = r.key.statusDetail ? pc7.dim(` ${r.key.statusDetail}`) : "";
|
|
1676
|
+
const act = r.key.actCapable ? pc7.green(" act-capable") : "";
|
|
831
1677
|
return `${head} ${r.key.provider}${act}${detail}`;
|
|
832
1678
|
}
|
|
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
1679
|
function isPatchedWorkflowTarget(target) {
|
|
848
1680
|
return "workflowPath" in target;
|
|
849
1681
|
}
|
|
@@ -857,16 +1689,18 @@ function patchTouches(patch, path2) {
|
|
|
857
1689
|
}
|
|
858
1690
|
function dispatchBody(workflow, opts) {
|
|
859
1691
|
const patched = isPatchedWorkflowTarget(workflow);
|
|
860
|
-
|
|
1692
|
+
const path2 = patched ? workflow.workflowPath : workflow.path;
|
|
1693
|
+
const pushOnly = workflow.dispatchable === false;
|
|
1694
|
+
if (pushOnly && !opts.manual) {
|
|
861
1695
|
throw new PlatformClientError(
|
|
862
1696
|
"invalid_argument",
|
|
863
|
-
`Workflow "${
|
|
1697
|
+
`Workflow "${path2}" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`
|
|
864
1698
|
);
|
|
865
1699
|
}
|
|
866
|
-
if (
|
|
1700
|
+
if (pushOnly && opts.inputs !== void 0 && opts.inputs.length > 0) {
|
|
867
1701
|
throw new PlatformClientError(
|
|
868
1702
|
"invalid_argument",
|
|
869
|
-
`Workflow "${
|
|
1703
|
+
`Workflow "${path2}" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`
|
|
870
1704
|
);
|
|
871
1705
|
}
|
|
872
1706
|
const ref = opts.ref ?? (patched ? void 0 : workflow.refs[0]);
|
|
@@ -1030,13 +1864,13 @@ function formatVaultRow(item) {
|
|
|
1030
1864
|
...item.source === "organization" ? ["inherited"] : [],
|
|
1031
1865
|
...item.overridesOrganization ? ["overrides org"] : []
|
|
1032
1866
|
];
|
|
1033
|
-
return `${
|
|
1867
|
+
return `${pc7.cyan(safeTerm(item.name))} ${pc7.dim(flags.join(", "))} ${pc7.dim(`updated ${safeTerm(item.updatedAt)}`)}`;
|
|
1034
1868
|
}
|
|
1035
1869
|
function registerActionsCommands(program2) {
|
|
1036
1870
|
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
|
|
1871
|
+
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");
|
|
1872
|
+
common2(
|
|
1873
|
+
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 Actions router").option("--provider-region <region>", "region for --provider (same as --provider <id>:<region>)").addOption(new Option2("--max-bid <usd>").hideHelp()).addOption(new Option2("--max-bid-per <unit>").hideHelp()).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
1874
|
).action(async (repo, opts) => {
|
|
1041
1875
|
try {
|
|
1042
1876
|
const c = await client(opts);
|
|
@@ -1047,15 +1881,21 @@ function registerActionsCommands(program2) {
|
|
|
1047
1881
|
if (!ref) throw new PlatformClientError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
|
|
1048
1882
|
local = localChangesPatch(ref, void 0, repo);
|
|
1049
1883
|
} else if (!opts.json && hasLocalChanges()) {
|
|
1050
|
-
console.error(
|
|
1884
|
+
console.error(pc7.dim("You have uncommitted changes. Add --with-changes to run them."));
|
|
1051
1885
|
}
|
|
1052
1886
|
const { workflows } = await c.get(
|
|
1053
1887
|
"/api/v1/actions/workflows",
|
|
1054
1888
|
{ repo }
|
|
1055
1889
|
);
|
|
1056
|
-
|
|
1890
|
+
let workflow = matchWorkflow(workflows, opts.workflow) ?? (local && patchTouches(local.patch, opts.workflow) ? { repoFullName: repo, workflowPath: opts.workflow } : void 0);
|
|
1891
|
+
let refOnly;
|
|
1892
|
+
if (!workflow && ref !== void 0) {
|
|
1893
|
+
refOnly = (await c.get("/api/v1/actions/workflows", { repo, ref })).refOnly ?? [];
|
|
1894
|
+
const match = matchRefOnly(refOnly, opts.workflow);
|
|
1895
|
+
if (match) workflow = { repoFullName: repo, workflowPath: match.path, dispatchable: match.dispatchable };
|
|
1896
|
+
}
|
|
1057
1897
|
if (!workflow) {
|
|
1058
|
-
const choices = workflows
|
|
1898
|
+
const choices = workflowChoices(workflows) + (refOnly && refOnly.length > 0 ? `; only on ${ref}: ${workflowChoices(refOnly)}` : "");
|
|
1059
1899
|
const hint = !opts.withChanges && hasLocalChanges() && /^\.github\/workflows\//.test(opts.workflow) ? " If it only exists in your working tree, add --with-changes." : "";
|
|
1060
1900
|
throw new PlatformClientError(
|
|
1061
1901
|
"workflow_not_found",
|
|
@@ -1071,7 +1911,7 @@ function registerActionsCommands(program2) {
|
|
|
1071
1911
|
);
|
|
1072
1912
|
patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };
|
|
1073
1913
|
} else if (opts.withChanges && !opts.json && ref) {
|
|
1074
|
-
console.error(
|
|
1914
|
+
console.error(pc7.dim(`no local changes beyond origin/${ref.replace(/^refs\/heads\//, "")}; running the ref as is`));
|
|
1075
1915
|
}
|
|
1076
1916
|
const body = dispatchBody(workflow, { ...opts, ref, patchId: patch?.patchId });
|
|
1077
1917
|
const result = await c.post(
|
|
@@ -1081,7 +1921,7 @@ function registerActionsCommands(program2) {
|
|
|
1081
1921
|
const org2 = await c.org();
|
|
1082
1922
|
const url = `${c.baseUrl}/${org2.slug}/actions/runs/${result.runId}`;
|
|
1083
1923
|
output(opts, { ...result, url, ...patch && { patch } }, (r) => {
|
|
1084
|
-
console.log(`${r.created ? "dispatched" : "already running"} ${
|
|
1924
|
+
console.log(`${r.created ? "dispatched" : "already running"} ${pc7.cyan(r.runId)}`);
|
|
1085
1925
|
console.log(`sha: ${r.headSha}${r.patch ? ` + ${r.patch.files} changed file${r.patch.files === 1 ? "" : "s"} (uncommitted)` : ""}`);
|
|
1086
1926
|
console.log(`url: ${r.url}`);
|
|
1087
1927
|
});
|
|
@@ -1089,26 +1929,9 @@ function registerActionsCommands(program2) {
|
|
|
1089
1929
|
fail(e, opts);
|
|
1090
1930
|
}
|
|
1091
1931
|
});
|
|
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(
|
|
1932
|
+
registerRunsCommands(actions, common2, { client, fail, output, formatRunRow });
|
|
1933
|
+
registerWorkflowsCommands(actions, common2, { client, fail, output });
|
|
1934
|
+
common2(
|
|
1112
1935
|
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
1936
|
).action(async (opts) => {
|
|
1114
1937
|
opts.org ?? (opts.org = program2.opts().org);
|
|
@@ -1120,7 +1943,7 @@ function registerActionsCommands(program2) {
|
|
|
1120
1943
|
fail(e, opts);
|
|
1121
1944
|
}
|
|
1122
1945
|
});
|
|
1123
|
-
|
|
1946
|
+
common2(
|
|
1124
1947
|
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
1948
|
).action(async (repo, opts) => {
|
|
1126
1949
|
try {
|
|
@@ -1143,7 +1966,7 @@ function registerActionsCommands(program2) {
|
|
|
1143
1966
|
fail(e, opts);
|
|
1144
1967
|
}
|
|
1145
1968
|
});
|
|
1146
|
-
|
|
1969
|
+
common2(
|
|
1147
1970
|
actions.command("run").description("Show a run: jobs, provider:region placement, placement attempts").argument("<run-id>", "run ID")
|
|
1148
1971
|
).action(async (runId, opts) => {
|
|
1149
1972
|
try {
|
|
@@ -1163,7 +1986,7 @@ function registerActionsCommands(program2) {
|
|
|
1163
1986
|
fail(e, opts);
|
|
1164
1987
|
}
|
|
1165
1988
|
});
|
|
1166
|
-
|
|
1989
|
+
common2(
|
|
1167
1990
|
actions.command("summary").description("Show a run's failure digest: failed jobs, failed steps, bounded log tails").argument("<run-id>", "run ID")
|
|
1168
1991
|
).action(async (runId, opts) => {
|
|
1169
1992
|
try {
|
|
@@ -1173,7 +1996,7 @@ function registerActionsCommands(program2) {
|
|
|
1173
1996
|
fail(e, opts);
|
|
1174
1997
|
}
|
|
1175
1998
|
});
|
|
1176
|
-
|
|
1999
|
+
common2(
|
|
1177
2000
|
actions.command("benchmarks").description("Show the benchmark runs this run produced: per-provider score and success rate").argument("<run-id>", "run ID")
|
|
1178
2001
|
).action(async (runId, opts) => {
|
|
1179
2002
|
try {
|
|
@@ -1184,7 +2007,7 @@ function registerActionsCommands(program2) {
|
|
|
1184
2007
|
fail(e, opts);
|
|
1185
2008
|
}
|
|
1186
2009
|
});
|
|
1187
|
-
|
|
2010
|
+
common2(
|
|
1188
2011
|
actions.command("inspect").description("Inspect a run: resolved runner image, caches, secret names, concurrency, placement context").argument("<run-id>", "run ID")
|
|
1189
2012
|
).action(async (runId, opts) => {
|
|
1190
2013
|
try {
|
|
@@ -1197,7 +2020,7 @@ function registerActionsCommands(program2) {
|
|
|
1197
2020
|
fail(e, opts);
|
|
1198
2021
|
}
|
|
1199
2022
|
});
|
|
1200
|
-
|
|
2023
|
+
common2(
|
|
1201
2024
|
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
2025
|
).action(async (runId, opts) => {
|
|
1203
2026
|
try {
|
|
@@ -1224,7 +2047,7 @@ function registerActionsCommands(program2) {
|
|
|
1224
2047
|
if (opts.json) {
|
|
1225
2048
|
process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + "\n");
|
|
1226
2049
|
} else {
|
|
1227
|
-
if (jobs.length > 1) console.log(
|
|
2050
|
+
if (jobs.length > 1) console.log(pc7.bold(`\u2500\u2500 ${job.name} \u2500\u2500`));
|
|
1228
2051
|
for (const seg of slice.segments) process.stdout.write(seg.text);
|
|
1229
2052
|
}
|
|
1230
2053
|
}
|
|
@@ -1240,190 +2063,93 @@ function registerActionsCommands(program2) {
|
|
|
1240
2063
|
}
|
|
1241
2064
|
return;
|
|
1242
2065
|
}
|
|
1243
|
-
for await (const { job, slice } of followRunLogs(c, runId, jobs, opts.step)) {
|
|
1244
|
-
if (opts.json) {
|
|
1245
|
-
process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + "\n");
|
|
1246
|
-
} else {
|
|
1247
|
-
for (const seg of slice.segments) {
|
|
1248
|
-
const text = seg.text.replace(/\n/g, `
|
|
1249
|
-
[${job.name}] `);
|
|
1250
|
-
process.stdout.write(`[${job.name}] ${text}`);
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
} catch (e) {
|
|
1255
|
-
fail(e, opts);
|
|
1256
|
-
}
|
|
1257
|
-
});
|
|
1258
|
-
const providers = actions.command("providers").description("List the org's registered compute providers (regions, act/usable status)");
|
|
1259
|
-
common(providers).action(async (opts) => {
|
|
1260
|
-
try {
|
|
1261
|
-
const data = await (await client(opts)).get("/api/v1/actions/providers");
|
|
1262
|
-
output(opts, data, (d) => {
|
|
1263
|
-
for (const p2 of d.providers) console.log(formatProviderRow(p2));
|
|
1264
|
-
});
|
|
1265
|
-
} catch (e) {
|
|
1266
|
-
fail(e, opts);
|
|
1267
|
-
}
|
|
1268
|
-
});
|
|
1269
|
-
common(
|
|
1270
|
-
providers.command("configure").description("Save the org's credential for a provider (owner/admin API key)").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
|
-
).action(async (provider, opts) => {
|
|
1272
|
-
try {
|
|
1273
|
-
const c = await client(opts);
|
|
1274
|
-
let body;
|
|
1275
|
-
if (opts.field !== void 0) {
|
|
1276
|
-
if (opts.key !== void 0) throw new Error("Pass either --key or --field, not both.");
|
|
1277
|
-
body = { fields: parseInputs(opts.field) };
|
|
1278
|
-
} else if (opts.key !== void 0) {
|
|
1279
|
-
body = { key: opts.key };
|
|
1280
|
-
} else {
|
|
1281
|
-
throw new Error("Pass --key <key> or --field name=value.");
|
|
1282
|
-
}
|
|
1283
|
-
const saved = await c.put(
|
|
1284
|
-
`/api/v1/actions/providers/${provider}/key`,
|
|
1285
|
-
body
|
|
1286
|
-
);
|
|
1287
|
-
const verification = opts.verify ? await c.post(
|
|
1288
|
-
`/api/v1/actions/providers/${provider}/verify`
|
|
1289
|
-
) : void 0;
|
|
1290
|
-
output(opts, verification ? { key: saved.key, verification } : saved, () => {
|
|
1291
|
-
console.log(`saved ${saved.key.provider} ${pc2.dim(saved.key.keyHint)} ${saved.key.status}`);
|
|
1292
|
-
if (verification) console.log(formatVerifyResult(verification));
|
|
1293
|
-
});
|
|
1294
|
-
if (verification?.verified === false) process.exitCode = 1;
|
|
1295
|
-
} catch (e) {
|
|
1296
|
-
fail(e, opts);
|
|
1297
|
-
}
|
|
1298
|
-
});
|
|
1299
|
-
common(
|
|
1300
|
-
providers.command("verify").description('Probe the stored provider key with a real sandbox ("Test" in Settings)').argument("<provider>", "provider id")
|
|
1301
|
-
).action(async (provider, opts) => {
|
|
1302
|
-
try {
|
|
1303
|
-
const result = await (await client(opts)).post(
|
|
1304
|
-
`/api/v1/actions/providers/${provider}/verify`
|
|
1305
|
-
);
|
|
1306
|
-
output(opts, result, (r) => console.log(formatVerifyResult(r)));
|
|
1307
|
-
if (result.verified === false) process.exitCode = 1;
|
|
1308
|
-
} catch (e) {
|
|
1309
|
-
fail(e, opts);
|
|
1310
|
-
}
|
|
1311
|
-
});
|
|
1312
|
-
common(
|
|
1313
|
-
providers.command("remove").description("Delete the org's stored credential for a provider").argument("<provider>", "provider id")
|
|
1314
|
-
).action(async (provider, opts) => {
|
|
1315
|
-
try {
|
|
1316
|
-
const result = await (await client(opts)).del(
|
|
1317
|
-
`/api/v1/actions/providers/${provider}/key`
|
|
1318
|
-
);
|
|
1319
|
-
output(opts, result, (r) => {
|
|
1320
|
-
console.log(r.deleted ? `deleted ${r.provider}` : `no key stored for ${r.provider}`);
|
|
1321
|
-
});
|
|
1322
|
-
} catch (e) {
|
|
1323
|
-
fail(e, opts);
|
|
1324
|
-
}
|
|
1325
|
-
});
|
|
1326
|
-
const repos = actions.command("repos").description("List the org's connected repositories");
|
|
1327
|
-
common(repos).action(async (opts) => {
|
|
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
|
-
});
|
|
2066
|
+
for await (const { job, slice } of followRunLogs(c, runId, jobs, opts.step)) {
|
|
2067
|
+
if (opts.json) {
|
|
2068
|
+
process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + "\n");
|
|
2069
|
+
} else {
|
|
2070
|
+
for (const seg of slice.segments) {
|
|
2071
|
+
const text = seg.text.replace(/\n/g, `
|
|
2072
|
+
[${job.name}] `);
|
|
2073
|
+
process.stdout.write(`[${job.name}] ${text}`);
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
1374
2077
|
} catch (e) {
|
|
1375
2078
|
fail(e, opts);
|
|
1376
2079
|
}
|
|
1377
2080
|
});
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
).action(async (opts) => {
|
|
2081
|
+
const providers = actions.command("providers").description("List the providers Actions can place on (order, act/usable, key status); keys and rates: compute byok");
|
|
2082
|
+
common2(providers).action(async (opts) => {
|
|
1381
2083
|
try {
|
|
1382
|
-
const
|
|
1383
|
-
output(opts,
|
|
1384
|
-
for (const
|
|
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`));
|
|
2084
|
+
const data = await (await client(opts)).get("/api/v1/actions/providers");
|
|
2085
|
+
output(opts, data, (d) => {
|
|
2086
|
+
for (const p2 of d.providers) console.log(formatProviderRow(p2));
|
|
1388
2087
|
});
|
|
1389
|
-
if (result.accounts.some((a) => a.error !== null)) process.exitCode = 1;
|
|
1390
2088
|
} catch (e) {
|
|
1391
2089
|
fail(e, opts);
|
|
1392
2090
|
}
|
|
1393
2091
|
});
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
).action(async (
|
|
2092
|
+
common2(
|
|
2093
|
+
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")
|
|
2094
|
+
).action(async (provider, opts) => {
|
|
1397
2095
|
try {
|
|
1398
|
-
const
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
2096
|
+
const c = await secretValueClient(opts, "provider keys");
|
|
2097
|
+
let body;
|
|
2098
|
+
if (opts.field !== void 0) {
|
|
2099
|
+
if (opts.key !== void 0) throw new Error("Pass either --key or --field, not both.");
|
|
2100
|
+
body = { fields: parseInputs(opts.field) };
|
|
2101
|
+
} else if (opts.key !== void 0) {
|
|
2102
|
+
body = { key: opts.key };
|
|
2103
|
+
} else {
|
|
2104
|
+
throw new Error("Pass --key <key> or --field name=value.");
|
|
2105
|
+
}
|
|
2106
|
+
const saved = await c.put(
|
|
2107
|
+
`/api/v1/actions/providers/${provider}/key`,
|
|
2108
|
+
body
|
|
2109
|
+
);
|
|
2110
|
+
const verification = opts.verify ? await c.post(
|
|
2111
|
+
`/api/v1/actions/providers/${provider}/verify`
|
|
2112
|
+
) : void 0;
|
|
2113
|
+
output(opts, verification ? { key: saved.key, verification } : saved, () => {
|
|
2114
|
+
console.log(`saved ${saved.key.provider} ${pc7.dim(saved.key.keyHint)} ${saved.key.status}`);
|
|
2115
|
+
if (verification) console.log(formatVerifyResult(verification));
|
|
1406
2116
|
});
|
|
2117
|
+
if (verification?.verified === false) process.exitCode = 1;
|
|
1407
2118
|
} catch (e) {
|
|
1408
2119
|
fail(e, opts);
|
|
1409
2120
|
}
|
|
1410
2121
|
});
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
).action(async (
|
|
2122
|
+
common2(
|
|
2123
|
+
providers.command("verify").description("Deprecated: use `compute byok verify`. Probe the stored provider key with a real sandbox").argument("<provider>", "provider id")
|
|
2124
|
+
).action(async (provider, opts) => {
|
|
1414
2125
|
try {
|
|
1415
|
-
const result = await (await client(opts)).
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
2126
|
+
const result = await (await client(opts)).post(
|
|
2127
|
+
`/api/v1/actions/providers/${provider}/verify`
|
|
2128
|
+
);
|
|
2129
|
+
output(opts, result, (r) => console.log(formatVerifyResult(r)));
|
|
2130
|
+
if (result.verified === false) process.exitCode = 1;
|
|
2131
|
+
} catch (e) {
|
|
2132
|
+
fail(e, opts);
|
|
2133
|
+
}
|
|
2134
|
+
});
|
|
2135
|
+
common2(
|
|
2136
|
+
providers.command("remove").description("Deprecated: use `compute byok remove`. Delete the org's stored credential for a provider").argument("<provider>", "provider id")
|
|
2137
|
+
).action(async (provider, opts) => {
|
|
2138
|
+
try {
|
|
2139
|
+
const result = await (await client(opts)).del(
|
|
2140
|
+
`/api/v1/actions/providers/${provider}/key`
|
|
2141
|
+
);
|
|
2142
|
+
output(opts, result, (r) => {
|
|
2143
|
+
console.log(r.deleted ? `deleted ${r.provider}` : `no key stored for ${r.provider}`);
|
|
1419
2144
|
});
|
|
1420
|
-
output(opts, result, (r) => console.log(`disabled ${pc2.cyan(safeTerm(r.fullName))}`));
|
|
1421
2145
|
} catch (e) {
|
|
1422
2146
|
fail(e, opts);
|
|
1423
2147
|
}
|
|
1424
2148
|
});
|
|
2149
|
+
registerReposCommands(actions, common2, { client, fail, output });
|
|
2150
|
+
registerIntegrationsCommands(actions, common2, { client, fail, output });
|
|
1425
2151
|
const vault = actions.command("vault").description("The org vault: secrets and variables (owner/admin key)");
|
|
1426
|
-
const vaultScope = (cmd) =>
|
|
2152
|
+
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
2153
|
vaultScope(
|
|
1428
2154
|
vault.command("ls").description("List names and metadata (never values)")
|
|
1429
2155
|
).action(async (opts) => {
|
|
@@ -1447,7 +2173,7 @@ function registerActionsCommands(program2) {
|
|
|
1447
2173
|
'Pipe the value on stdin (e.g. printf %s "$VALUE" | compute actions vault set NAME) or pass --from-file.'
|
|
1448
2174
|
);
|
|
1449
2175
|
}
|
|
1450
|
-
const value =
|
|
2176
|
+
const value = readFileSync2(opts.fromFile ?? 0, "utf8");
|
|
1451
2177
|
const kind = parseVaultKind(opts.kind);
|
|
1452
2178
|
const labels = vaultSetLabels(opts);
|
|
1453
2179
|
const body = vaultSetBody(name, value, { ...opts, kind, labels });
|
|
@@ -1457,9 +2183,9 @@ function registerActionsCommands(program2) {
|
|
|
1457
2183
|
);
|
|
1458
2184
|
output(opts, result, (r) => {
|
|
1459
2185
|
const where = opts.repo ? safeTerm(opts.repo) : "org";
|
|
1460
|
-
console.log(`saved ${
|
|
2186
|
+
console.log(`saved ${pc7.cyan(safeTerm(r.item.name))} ${pc7.dim(`(${r.item.kind}, v${r.item.version}, ${where})`)}`);
|
|
1461
2187
|
if (/\r?\n$/.test(value)) {
|
|
1462
|
-
console.error(
|
|
2188
|
+
console.error(pc7.yellow("note: the stored value ends with a newline; use printf %s rather than echo to avoid one."));
|
|
1463
2189
|
}
|
|
1464
2190
|
});
|
|
1465
2191
|
} catch (e) {
|
|
@@ -1493,7 +2219,7 @@ function registerActionsCommands(program2) {
|
|
|
1493
2219
|
output(opts, result, (r) => {
|
|
1494
2220
|
const where = opts.repo ? safeTerm(opts.repo) : "org";
|
|
1495
2221
|
console.log(
|
|
1496
|
-
`reclassified ${
|
|
2222
|
+
`reclassified ${pc7.cyan(safeTerm(r.item.name))} ${pc7.dim(`(labels: ${r.item.labels.join(", ") || "none"}, v${r.item.version}, ${where})`)}`
|
|
1497
2223
|
);
|
|
1498
2224
|
});
|
|
1499
2225
|
} catch (e) {
|
|
@@ -1506,12 +2232,12 @@ function registerActionsCommands(program2) {
|
|
|
1506
2232
|
try {
|
|
1507
2233
|
const path2 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
|
|
1508
2234
|
const result = await (await client(opts)).del(path2);
|
|
1509
|
-
output(opts, result, (r) => console.log(`deleted ${
|
|
2235
|
+
output(opts, result, (r) => console.log(`deleted ${pc7.cyan(safeTerm(r.name))} ${pc7.dim(`(${r.kind})`)}`));
|
|
1510
2236
|
} catch (e) {
|
|
1511
2237
|
fail(e, opts);
|
|
1512
2238
|
}
|
|
1513
2239
|
});
|
|
1514
|
-
|
|
2240
|
+
common2(
|
|
1515
2241
|
actions.command("cancel").description("Cancel a run").argument("<run-id>", "run ID")
|
|
1516
2242
|
).action(async (runId, opts) => {
|
|
1517
2243
|
try {
|
|
@@ -1525,7 +2251,7 @@ function registerActionsCommands(program2) {
|
|
|
1525
2251
|
fail(e, opts);
|
|
1526
2252
|
}
|
|
1527
2253
|
});
|
|
1528
|
-
|
|
2254
|
+
common2(
|
|
1529
2255
|
actions.command("rerun").description("Re-run a finished run at the same commit").argument("<run-id>", "run ID")
|
|
1530
2256
|
).action(async (runId, opts) => {
|
|
1531
2257
|
try {
|
|
@@ -1536,14 +2262,14 @@ function registerActionsCommands(program2) {
|
|
|
1536
2262
|
const org2 = await c.org();
|
|
1537
2263
|
const url = `${c.baseUrl}/${org2.slug}/actions/runs/${result.runId}`;
|
|
1538
2264
|
output(opts, { ...result, url }, (r) => {
|
|
1539
|
-
console.log(`${r.created ? "rerun dispatched" : "rerun already running"} ${
|
|
2265
|
+
console.log(`${r.created ? "rerun dispatched" : "rerun already running"} ${pc7.cyan(r.runId)}`);
|
|
1540
2266
|
console.log(`url: ${r.url}`);
|
|
1541
2267
|
});
|
|
1542
2268
|
} catch (e) {
|
|
1543
2269
|
fail(e, opts);
|
|
1544
2270
|
}
|
|
1545
2271
|
});
|
|
1546
|
-
|
|
2272
|
+
common2(
|
|
1547
2273
|
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
2274
|
).action(async (runId, opts) => {
|
|
1549
2275
|
try {
|
|
@@ -1599,7 +2325,7 @@ function registerActionsCommands(program2) {
|
|
|
1599
2325
|
fail(e, opts);
|
|
1600
2326
|
}
|
|
1601
2327
|
});
|
|
1602
|
-
registerSettingsCommands(actions, "actions",
|
|
2328
|
+
registerSettingsCommands(actions, "actions", common2, {
|
|
1603
2329
|
client,
|
|
1604
2330
|
fail,
|
|
1605
2331
|
output,
|
|
@@ -1607,10 +2333,201 @@ function registerActionsCommands(program2) {
|
|
|
1607
2333
|
});
|
|
1608
2334
|
}
|
|
1609
2335
|
|
|
2336
|
+
// src/byok.ts
|
|
2337
|
+
import pc8 from "picocolors";
|
|
2338
|
+
|
|
2339
|
+
// src/rate-display.ts
|
|
2340
|
+
var SECONDS_PER_MINUTE = 60;
|
|
2341
|
+
var SECONDS_PER_HOUR = 3600;
|
|
2342
|
+
function rateAllUnits(rate) {
|
|
2343
|
+
const perSecond = rate.per === "second" ? rate.usd : rate.per === "minute" ? rate.usd / SECONDS_PER_MINUTE : rate.usd / SECONDS_PER_HOUR;
|
|
2344
|
+
return {
|
|
2345
|
+
perSecond,
|
|
2346
|
+
perMinute: perSecond * SECONDS_PER_MINUTE,
|
|
2347
|
+
perHour: perSecond * SECONDS_PER_HOUR
|
|
2348
|
+
};
|
|
2349
|
+
}
|
|
2350
|
+
function formatUsd(usd) {
|
|
2351
|
+
if (!Number.isFinite(usd)) return "$\u2014";
|
|
2352
|
+
if (usd === 0) return "$0";
|
|
2353
|
+
const decimals = Math.min(100, Math.max(0, 3 - Math.floor(Math.log10(Math.abs(usd)))));
|
|
2354
|
+
const fixed = usd.toFixed(decimals);
|
|
2355
|
+
const trimmed = fixed.includes(".") ? fixed.replace(/0+$/, "").replace(/\.$/, "") : fixed;
|
|
2356
|
+
return `$${trimmed}`;
|
|
2357
|
+
}
|
|
2358
|
+
function formatMoney(usd) {
|
|
2359
|
+
if (!Number.isFinite(usd)) return "$\u2014";
|
|
2360
|
+
const sign = usd < 0 ? "-" : "";
|
|
2361
|
+
const abs = Math.abs(usd);
|
|
2362
|
+
if (abs !== 0 && abs < 0.01) {
|
|
2363
|
+
return `${sign}${formatUsd(abs)}`;
|
|
2364
|
+
}
|
|
2365
|
+
const s = abs.toLocaleString("en-US", {
|
|
2366
|
+
minimumFractionDigits: 2,
|
|
2367
|
+
maximumFractionDigits: 2
|
|
2368
|
+
});
|
|
2369
|
+
return `${sign}$${s}`;
|
|
2370
|
+
}
|
|
2371
|
+
function formatRateAllUnits(rate) {
|
|
2372
|
+
return `${formatUsd(rate.perHour)}/hr \xB7 ${formatUsd(rate.perMinute)}/min \xB7 ${formatUsd(rate.perSecond)}/s`;
|
|
2373
|
+
}
|
|
2374
|
+
function formatUsdPer(rate) {
|
|
2375
|
+
return formatRateAllUnits(rateAllUnits(rate));
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
// src/byok.ts
|
|
2379
|
+
var RATE_UNITS = ["second", "minute", "hour"];
|
|
2380
|
+
var MAX_RATE_USD = 1e3;
|
|
2381
|
+
function providerPath(provider, rest = "") {
|
|
2382
|
+
return `/api/v1/providers/${encodeURIComponent(provider)}${rest}`;
|
|
2383
|
+
}
|
|
2384
|
+
function keyText(key) {
|
|
2385
|
+
if (key.keyHint === null) return pc8.gray("no key");
|
|
2386
|
+
const status = key.status === "connected" ? pc8.green("connected") : key.status === "error" ? pc8.red("error") : pc8.yellow("untested");
|
|
2387
|
+
const hints = key.pairs?.length ? key.pairs.map((p2) => `${safeTerm(p2.keyHint ?? "\u2014")}@${safeTerm(p2.region)}`).join(",") : safeTerm(key.keyHint);
|
|
2388
|
+
return `${status} ${pc8.dim(hints)}`;
|
|
2389
|
+
}
|
|
2390
|
+
function rateText(p2) {
|
|
2391
|
+
return p2.customRate ? `${formatRateAllUnits(p2.customRate.rateUsd)} ${pc8.cyan("custom")}` : `${formatRateAllUnits(p2.platformRate.rateUsd)} ${pc8.dim("platform")}`;
|
|
2392
|
+
}
|
|
2393
|
+
function formatByokRow(p2) {
|
|
2394
|
+
const ready = p2.key.status === "connected";
|
|
2395
|
+
const icon = ready ? pc8.green("\u25CF") : pc8.gray("\u25CB");
|
|
2396
|
+
const name = ready ? pc8.white(safeTerm(p2.provider)) : pc8.gray(safeTerm(p2.provider));
|
|
2397
|
+
return ` ${icon} ${name} ${keyText(p2.key)} ${rateText(p2)}`;
|
|
2398
|
+
}
|
|
2399
|
+
function formatByokDetail(p2) {
|
|
2400
|
+
const lines = [
|
|
2401
|
+
`${pc8.white(safeTerm(p2.provider))} ${keyText(p2.key)}`,
|
|
2402
|
+
` regions ${p2.regions.length > 0 ? p2.regions.map(safeTerm).join(", ") : "account default"}`,
|
|
2403
|
+
` last tested ${p2.key.lastCheckedAt === null ? "\u2014" : safeTerm(p2.key.lastCheckedAt)}`,
|
|
2404
|
+
` platform rate ${formatRateAllUnits(p2.platformRate.rateUsd)}`,
|
|
2405
|
+
` custom rate ${p2.customRate ? formatRateAllUnits(p2.customRate.rateUsd) : pc8.dim("none (costs report at the platform rate)")}`
|
|
2406
|
+
];
|
|
2407
|
+
if (p2.key.status === "error" && p2.key.statusDetail) lines.push(` last error ${pc8.dim(safeTerm(p2.key.statusDetail))}`);
|
|
2408
|
+
return lines.join("\n");
|
|
2409
|
+
}
|
|
2410
|
+
function formatByokVerify(r) {
|
|
2411
|
+
const head = r.verified === true ? pc8.green("verified") : pc8.red("not verified");
|
|
2412
|
+
const detail = r.key.statusDetail ? pc8.dim(` ${safeTerm(r.key.statusDetail)}`) : "";
|
|
2413
|
+
const act = r.key.actCapable ? pc8.green(" act-capable") : "";
|
|
2414
|
+
return `${head} ${safeTerm(r.key.provider)}${act}${detail}`;
|
|
2415
|
+
}
|
|
2416
|
+
function parseRateArgs(usd, per) {
|
|
2417
|
+
const amount = Number(usd);
|
|
2418
|
+
if (usd.trim() === "" || !Number.isFinite(amount) || amount < 0 || amount > MAX_RATE_USD) {
|
|
2419
|
+
throw new Error(`<usd> must be a number from 0 to ${MAX_RATE_USD}`);
|
|
2420
|
+
}
|
|
2421
|
+
const unit = per ?? "hour";
|
|
2422
|
+
if (!RATE_UNITS.includes(unit)) throw new Error("--per must be second, minute or hour");
|
|
2423
|
+
return { usd: amount, per: unit };
|
|
2424
|
+
}
|
|
2425
|
+
function keyBody(opts) {
|
|
2426
|
+
if (opts.field !== void 0) {
|
|
2427
|
+
if (opts.key !== void 0) throw new Error("Pass either --key or --field, not both.");
|
|
2428
|
+
return { fields: parseInputs(opts.field) };
|
|
2429
|
+
}
|
|
2430
|
+
if (opts.key !== void 0) return { key: opts.key };
|
|
2431
|
+
throw new Error("Pass --key <key> or --field name=value.");
|
|
2432
|
+
}
|
|
2433
|
+
function registerByokCommands(program2) {
|
|
2434
|
+
const byok = program2.command("byok").description("The org's BYOK providers: their keys and custom rates, shared by Actions and sandboxes").configureOutput({ outputError: usageErrorOutput });
|
|
2435
|
+
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");
|
|
2436
|
+
const list = async (opts) => {
|
|
2437
|
+
try {
|
|
2438
|
+
const data = await (await client(opts)).get("/api/v1/providers");
|
|
2439
|
+
output(opts, data, (d) => {
|
|
2440
|
+
for (const p2 of d.providers) console.log(formatByokRow(p2));
|
|
2441
|
+
});
|
|
2442
|
+
} catch (e) {
|
|
2443
|
+
fail(e, opts);
|
|
2444
|
+
}
|
|
2445
|
+
};
|
|
2446
|
+
common2(byok).action(list);
|
|
2447
|
+
common2(byok.command("list").alias("ls").description("Every provider the org may bring a key for, with key state and rate")).action(list);
|
|
2448
|
+
common2(
|
|
2449
|
+
byok.command("show").description("One provider's key state, platform rate and custom rate").argument("<provider>", "provider id (e.g. tensorlake, blaxel)")
|
|
2450
|
+
).action(async (provider, opts) => {
|
|
2451
|
+
try {
|
|
2452
|
+
const data = await (await client(opts)).get(providerPath(provider));
|
|
2453
|
+
output(opts, data, (d) => console.log(formatByokDetail(d.provider)));
|
|
2454
|
+
} catch (e) {
|
|
2455
|
+
fail(e, opts);
|
|
2456
|
+
}
|
|
2457
|
+
});
|
|
2458
|
+
common2(
|
|
2459
|
+
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")
|
|
2460
|
+
).action(async (provider, opts) => {
|
|
2461
|
+
try {
|
|
2462
|
+
const c = await secretValueClient(opts, "provider keys");
|
|
2463
|
+
const saved = await c.put(providerPath(provider, "/key"), keyBody(opts));
|
|
2464
|
+
const verification = opts.verify ? await c.post(providerPath(provider, "/verify")) : void 0;
|
|
2465
|
+
output(opts, verification ? { key: saved.key, verification } : saved, () => {
|
|
2466
|
+
console.log(`saved ${safeTerm(saved.key.provider)} ${pc8.dim(safeTerm(saved.key.keyHint ?? ""))} ${safeTerm(saved.key.status)}`);
|
|
2467
|
+
if (verification) console.log(formatByokVerify(verification));
|
|
2468
|
+
});
|
|
2469
|
+
if (verification?.verified === false) process.exitCode = 1;
|
|
2470
|
+
} catch (e) {
|
|
2471
|
+
fail(e, opts);
|
|
2472
|
+
}
|
|
2473
|
+
});
|
|
2474
|
+
common2(
|
|
2475
|
+
byok.command("verify").description('Test the stored key by placing a real sandbox with it ("Test" in Settings; owner/admin)').argument("<provider>", "provider id")
|
|
2476
|
+
).action(async (provider, opts) => {
|
|
2477
|
+
try {
|
|
2478
|
+
const result = await (await client(opts)).post(providerPath(provider, "/verify"));
|
|
2479
|
+
output(opts, result, (r) => console.log(formatByokVerify(r)));
|
|
2480
|
+
if (result.verified === false) process.exitCode = 1;
|
|
2481
|
+
} catch (e) {
|
|
2482
|
+
fail(e, opts);
|
|
2483
|
+
}
|
|
2484
|
+
});
|
|
2485
|
+
common2(
|
|
2486
|
+
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")
|
|
2487
|
+
).action(async (provider, opts) => {
|
|
2488
|
+
try {
|
|
2489
|
+
await confirmWrite(`Remove the ${provider} key? Sandboxes and Actions jobs stop placing on ${provider}.`, opts);
|
|
2490
|
+
const result = await (await client(opts)).del(providerPath(provider, "/key"));
|
|
2491
|
+
output(opts, result, (r) => console.log(`deleted ${safeTerm(r.provider)}`));
|
|
2492
|
+
} catch (e) {
|
|
2493
|
+
fail(e, opts);
|
|
2494
|
+
}
|
|
2495
|
+
});
|
|
2496
|
+
const rate = byok.command("rate").description("Custom rates: report sandbox costs at your own price. Reporting only; billing is unchanged");
|
|
2497
|
+
common2(
|
|
2498
|
+
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")
|
|
2499
|
+
).action(async (provider, usd, opts) => {
|
|
2500
|
+
try {
|
|
2501
|
+
const body = parseRateArgs(usd, opts.per);
|
|
2502
|
+
const data = await (await client(opts)).put(providerPath(provider, "/rate"), body);
|
|
2503
|
+
output(opts, data, (d) => {
|
|
2504
|
+
console.log(`${safeTerm(d.provider.provider)} costs now report at ${formatRateAllUnits(d.provider.rate.rateUsd)}`);
|
|
2505
|
+
console.log(pc8.dim("Reporting only: billing is unchanged. Applies to sandboxes created from now on."));
|
|
2506
|
+
});
|
|
2507
|
+
} catch (e) {
|
|
2508
|
+
fail(e, opts);
|
|
2509
|
+
}
|
|
2510
|
+
});
|
|
2511
|
+
common2(
|
|
2512
|
+
rate.command("clear").description("Drop a provider's custom rate; its costs report at the platform rate again (owner/admin)").argument("<provider>", "provider id")
|
|
2513
|
+
).action(async (provider, opts) => {
|
|
2514
|
+
try {
|
|
2515
|
+
const data = await (await client(opts)).del(providerPath(provider, "/rate"));
|
|
2516
|
+
output(
|
|
2517
|
+
opts,
|
|
2518
|
+
data,
|
|
2519
|
+
(d) => console.log(`${safeTerm(d.provider.provider)} costs now report at the platform rate, ${formatRateAllUnits(d.provider.platformRate.rateUsd)}`)
|
|
2520
|
+
);
|
|
2521
|
+
} catch (e) {
|
|
2522
|
+
fail(e, opts);
|
|
2523
|
+
}
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
|
|
1610
2527
|
// src/market.ts
|
|
1611
|
-
import
|
|
2528
|
+
import pc9 from "picocolors";
|
|
1612
2529
|
var USD_RE = /^\d+(\.\d+)?([eE][+-]?\d+)?$/;
|
|
1613
|
-
var
|
|
2530
|
+
var RATE_UNITS2 = ["second", "minute", "hour"];
|
|
1614
2531
|
var MARKET_LANES = ["actions", "sandbox"];
|
|
1615
2532
|
function parseMarketLane(value) {
|
|
1616
2533
|
if (value === void 0) return "actions";
|
|
@@ -1653,7 +2570,7 @@ function parseRate(price, per) {
|
|
|
1653
2570
|
"--price needs a unit \u2014 write it as <usd>/<unit> (e.g. --price 0.12/hour) or pass --per hour."
|
|
1654
2571
|
);
|
|
1655
2572
|
}
|
|
1656
|
-
if (!
|
|
2573
|
+
if (!RATE_UNITS2.includes(unit)) {
|
|
1657
2574
|
throw new PlatformClientError(
|
|
1658
2575
|
"invalid_argument",
|
|
1659
2576
|
`The unit must be second, minute, or hour, got "${unit}".`
|
|
@@ -1767,12 +2684,12 @@ function formatRate2(usd, per) {
|
|
|
1767
2684
|
}
|
|
1768
2685
|
function formatListingStatus(ask) {
|
|
1769
2686
|
let label;
|
|
1770
|
-
if (ask.status === "withdrawn") label =
|
|
1771
|
-
else if (ask.status === "paused") label =
|
|
1772
|
-
else if (!ask.live) label =
|
|
1773
|
-
else label =
|
|
2687
|
+
if (ask.status === "withdrawn") label = pc9.gray("withdrawn");
|
|
2688
|
+
else if (ask.status === "paused") label = pc9.yellow("paused");
|
|
2689
|
+
else if (!ask.live) label = pc9.gray("expired");
|
|
2690
|
+
else label = pc9.green("live");
|
|
1774
2691
|
if (ask.pendingUsd !== null && ask.pendingPer !== null) {
|
|
1775
|
-
label +=
|
|
2692
|
+
label += pc9.dim(` \u2192 ${formatRate2(ask.pendingUsd, ask.pendingPer)} next window`);
|
|
1776
2693
|
}
|
|
1777
2694
|
return label;
|
|
1778
2695
|
}
|
|
@@ -1781,22 +2698,22 @@ function formatListingRow(ask) {
|
|
|
1781
2698
|
return [
|
|
1782
2699
|
ask.id,
|
|
1783
2700
|
formatListingStatus(ask),
|
|
1784
|
-
|
|
2701
|
+
pc9.dim(ask.useCase === "sandbox" ? "sandbox" : "actions"),
|
|
1785
2702
|
safeTerm(ask.size),
|
|
1786
2703
|
safeTerm(ask.region ?? "-"),
|
|
1787
2704
|
formatRate2(ask.usd, ask.per),
|
|
1788
|
-
|
|
1789
|
-
|
|
2705
|
+
pc9.dim(`\xD7${ask.maxConcurrent}`),
|
|
2706
|
+
pc9.dim(expiry)
|
|
1790
2707
|
].join(" ");
|
|
1791
2708
|
}
|
|
1792
2709
|
function formatProviderStatus(p2) {
|
|
1793
2710
|
const lines = [];
|
|
1794
|
-
lines.push(`${
|
|
2711
|
+
lines.push(`${pc9.bold(safeTerm(p2.name))} ${pc9.dim(`selling ${safeTerm(p2.provider)}`)}`);
|
|
1795
2712
|
lines.push(`id: ${p2.id}`);
|
|
1796
2713
|
lines.push(
|
|
1797
|
-
`credential: ${p2.executorCredentialConnected ?
|
|
2714
|
+
`credential: ${p2.executorCredentialConnected ? pc9.green("connected") : pc9.yellow("not connected \u2014 your listings cannot fill until `compute market credential connect`")}`
|
|
1798
2715
|
);
|
|
1799
|
-
if (p2.revokedAt) lines.push(
|
|
2716
|
+
if (p2.revokedAt) lines.push(pc9.red(`revoked: ${p2.revokedAt}`));
|
|
1800
2717
|
lines.push(
|
|
1801
2718
|
`lanes: ${(p2.useCases ?? ["actions"]).join(", ")}`
|
|
1802
2719
|
);
|
|
@@ -1814,41 +2731,41 @@ function formatProviderStatus(p2) {
|
|
|
1814
2731
|
}
|
|
1815
2732
|
function formatBook(book) {
|
|
1816
2733
|
const lines = [];
|
|
1817
|
-
const lane = (useCase) =>
|
|
1818
|
-
lines.push(
|
|
1819
|
-
if (book.asks.length === 0) lines.push(
|
|
2734
|
+
const lane = (useCase) => pc9.dim(useCase === "sandbox" ? "sandbox" : "actions");
|
|
2735
|
+
lines.push(pc9.bold("sellers' asking prices"));
|
|
2736
|
+
if (book.asks.length === 0) lines.push(pc9.dim(" no listings are live"));
|
|
1820
2737
|
for (const ask of book.asks) {
|
|
1821
2738
|
const where = ask.region ? safeTerm(ask.region) : "any region";
|
|
1822
|
-
const expiry = ask.expiresAt ?
|
|
2739
|
+
const expiry = ask.expiresAt ? pc9.dim(ask.rollover ? ` renews ${ask.expiresAt}` : ` until ${ask.expiresAt}`) : "";
|
|
1823
2740
|
lines.push(
|
|
1824
2741
|
` ${lane(ask.useCase)} ${formatRate2(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`
|
|
1825
2742
|
);
|
|
1826
2743
|
}
|
|
1827
2744
|
lines.push("");
|
|
1828
|
-
lines.push(
|
|
1829
|
-
if (book.bids.length === 0) lines.push(
|
|
2745
|
+
lines.push(pc9.bold("buyer offers"));
|
|
2746
|
+
if (book.bids.length === 0) lines.push(pc9.dim(" no open offers"));
|
|
1830
2747
|
for (const bid of book.bids) {
|
|
1831
2748
|
const where = bid.region ? safeTerm(bid.region) : "anywhere";
|
|
1832
|
-
const yours = bid.mine ?
|
|
2749
|
+
const yours = bid.mine ? pc9.cyan(" (yours)") : "";
|
|
1833
2750
|
lines.push(
|
|
1834
|
-
` ${lane(bid.useCase)} pays up to ${formatRate2(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${
|
|
2751
|
+
` ${lane(bid.useCase)} pays up to ${formatRate2(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc9.dim(`posted ${bid.createdAt}`)}${yours}`
|
|
1835
2752
|
);
|
|
1836
2753
|
}
|
|
1837
2754
|
lines.push("");
|
|
1838
|
-
lines.push(
|
|
1839
|
-
if (book.fills.length === 0) lines.push(
|
|
2755
|
+
lines.push(pc9.bold("recent sales"));
|
|
2756
|
+
if (book.fills.length === 0) lines.push(pc9.dim(" nothing has sold yet"));
|
|
1840
2757
|
for (const fill of book.fills) {
|
|
1841
|
-
const statusNote = fill.status === "replaced" ?
|
|
2758
|
+
const statusNote = fill.status === "replaced" ? pc9.yellow(" replaced") : fill.status === "closed" ? pc9.gray(" closed") : "";
|
|
1842
2759
|
lines.push(
|
|
1843
|
-
` ${
|
|
2760
|
+
` ${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
2761
|
);
|
|
1845
2762
|
}
|
|
1846
2763
|
return lines.join("\n");
|
|
1847
2764
|
}
|
|
1848
2765
|
function formatReplacedFill(fill) {
|
|
1849
2766
|
const settled = formatMoney(fill.settledMicroUsd / 1e6);
|
|
1850
|
-
const job = fill.jobRequeued ?
|
|
1851
|
-
return `replaced ${
|
|
2767
|
+
const job = fill.jobRequeued ? pc9.dim(" \u2014 job re-places on the buyer's next provider") : "";
|
|
2768
|
+
return `replaced ${pc9.cyan(fill.fillId)} settled ${settled}${job}`;
|
|
1852
2769
|
}
|
|
1853
2770
|
function replaceTarget(listingId, fillId) {
|
|
1854
2771
|
if (fillId !== void 0) {
|
|
@@ -1870,9 +2787,9 @@ function replaceTarget(listingId, fillId) {
|
|
|
1870
2787
|
}
|
|
1871
2788
|
function formatSettlementRow(s) {
|
|
1872
2789
|
const period = `${s.periodStart.slice(0, 10)} \u2192 ${s.periodEnd.slice(0, 10)}`;
|
|
1873
|
-
const paid = s.paidAt ?
|
|
2790
|
+
const paid = s.paidAt ? pc9.green(`paid ${s.paidAt.slice(0, 10)}`) : s.invoiceRef ? pc9.yellow(`invoiced ${safeTerm(s.invoiceRef)}`) : pc9.dim("unpaid");
|
|
1874
2791
|
return [
|
|
1875
|
-
|
|
2792
|
+
pc9.dim(period),
|
|
1876
2793
|
`${s.vcpuSeconds.toLocaleString("en-US")} vCPU\xB7s`,
|
|
1877
2794
|
`gross ${formatMoney(s.grossUsd)}`,
|
|
1878
2795
|
`net ${formatMoney(s.netUsd)}`,
|
|
@@ -1906,22 +2823,22 @@ function formatCap(cap) {
|
|
|
1906
2823
|
return cap === null ? "No market cap \u2014 market-placed jobs need their own bid to fill." : `market cap ${formatRate2(cap.usd, cap.per)}`;
|
|
1907
2824
|
}
|
|
1908
2825
|
function formatBidRow(bid) {
|
|
1909
|
-
const status = bid.status === "open" ?
|
|
2826
|
+
const status = bid.status === "open" ? pc9.green("open") : bid.status === "filled" ? pc9.cyan("filled") : pc9.gray("cancelled");
|
|
1910
2827
|
return [
|
|
1911
2828
|
bid.id,
|
|
1912
2829
|
status,
|
|
1913
|
-
|
|
2830
|
+
pc9.dim(bid.useCase === "sandbox" ? "sandbox" : "actions"),
|
|
1914
2831
|
safeTerm(bid.size),
|
|
1915
2832
|
safeTerm(bid.region ?? "any region"),
|
|
1916
2833
|
`\u2264 ${formatRate2(bid.maxUsd, bid.per)}`,
|
|
1917
|
-
|
|
2834
|
+
pc9.dim(bid.expiresAt ? `expires ${bid.expiresAt}` : "standing")
|
|
1918
2835
|
].join(" ");
|
|
1919
2836
|
}
|
|
1920
2837
|
function formatCredits(b) {
|
|
1921
2838
|
const lines = [`available ${formatMoney(b.balanceMicroUsd / MICRO_USD)}`];
|
|
1922
2839
|
if (b.holds.length > 0) {
|
|
1923
2840
|
lines.push(
|
|
1924
|
-
|
|
2841
|
+
pc9.dim(`reserved ${formatMoney(b.heldMicroUsd / MICRO_USD)} across ${b.holds.length} running job${b.holds.length === 1 ? "" : "s"}`)
|
|
1925
2842
|
);
|
|
1926
2843
|
}
|
|
1927
2844
|
return lines.join("\n");
|
|
@@ -1930,29 +2847,29 @@ function formatLedgerRow(e) {
|
|
|
1930
2847
|
const usd = e.microUsd / MICRO_USD;
|
|
1931
2848
|
const amount = usd < 0 ? `-${formatMoney(-usd)}` : `+${formatMoney(usd)}`;
|
|
1932
2849
|
return [
|
|
1933
|
-
|
|
1934
|
-
(usd < 0 ?
|
|
2850
|
+
pc9.dim(e.createdAt.slice(0, 19).replace("T", " ")),
|
|
2851
|
+
(usd < 0 ? pc9.red : pc9.green)(amount.padStart(10)),
|
|
1935
2852
|
safeTerm(e.label),
|
|
1936
|
-
|
|
2853
|
+
pc9.dim(e.jobId ? `job ${e.jobId}` : "")
|
|
1937
2854
|
].join(" ").trimEnd();
|
|
1938
2855
|
}
|
|
1939
2856
|
function formatPurchaseRow(p2) {
|
|
1940
|
-
const cost = p2.costMicroUsd !== null ? formatMoney(p2.costMicroUsd / MICRO_USD) : p2.status === "live" ?
|
|
2857
|
+
const cost = p2.costMicroUsd !== null ? formatMoney(p2.costMicroUsd / MICRO_USD) : p2.status === "live" ? pc9.yellow("running") : "-";
|
|
1941
2858
|
return [
|
|
1942
|
-
|
|
2859
|
+
pc9.dim(p2.startedAt.slice(0, 19).replace("T", " ")),
|
|
1943
2860
|
cost.padStart(10),
|
|
1944
|
-
|
|
1945
|
-
|
|
2861
|
+
pc9.cyan(safeTerm(p2.sellerName)),
|
|
2862
|
+
pc9.dim(`${safeTerm(p2.provider)}/${safeTerm(p2.region ?? "any")}`),
|
|
1946
2863
|
formatRate2(p2.usd, p2.per),
|
|
1947
|
-
p2.secondsBilled !== null ?
|
|
1948
|
-
p2.status === "replaced" ?
|
|
1949
|
-
|
|
2864
|
+
p2.secondsBilled !== null ? pc9.dim(`${p2.secondsBilled}s`) : "",
|
|
2865
|
+
p2.status === "replaced" ? pc9.yellow("replaced") : "",
|
|
2866
|
+
pc9.dim(p2.runId ? `run ${p2.runId}` : p2.sandboxId ? `sandbox ${p2.sandboxId}` : "")
|
|
1950
2867
|
].filter((part) => part !== "").join(" ");
|
|
1951
2868
|
}
|
|
1952
2869
|
function registerMarketCommands(program2) {
|
|
1953
|
-
const market = program2.command("market").description("Buy and sell compute capacity on the compute market").configureOutput({ outputError: usageErrorOutput });
|
|
1954
|
-
const
|
|
1955
|
-
|
|
2870
|
+
const market = program2.command("market", { hidden: true }).description("Buy and sell compute capacity on the compute market").configureOutput({ outputError: usageErrorOutput });
|
|
2871
|
+
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");
|
|
2872
|
+
common2(
|
|
1956
2873
|
market.command("listings").alias("list").description("Your listings \u2014 live, paused, expired, and withdrawn")
|
|
1957
2874
|
).action(async (opts) => {
|
|
1958
2875
|
try {
|
|
@@ -1970,7 +2887,7 @@ function registerMarketCommands(program2) {
|
|
|
1970
2887
|
fail(e, opts);
|
|
1971
2888
|
}
|
|
1972
2889
|
});
|
|
1973
|
-
|
|
2890
|
+
common2(
|
|
1974
2891
|
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
2892
|
).action(async (opts) => {
|
|
1976
2893
|
try {
|
|
@@ -1989,21 +2906,21 @@ function registerMarketCommands(program2) {
|
|
|
1989
2906
|
);
|
|
1990
2907
|
}
|
|
1991
2908
|
size = preset.name;
|
|
1992
|
-
console.error(
|
|
2909
|
+
console.error(pc9.dim(`no --size given \u2014 listing at "${size}"`));
|
|
1993
2910
|
}
|
|
1994
2911
|
const result = await c.post(
|
|
1995
2912
|
"/api/v1/market/asks",
|
|
1996
2913
|
sellBody({ ...opts, size, useCase })
|
|
1997
2914
|
);
|
|
1998
2915
|
output(opts, result, (r) => {
|
|
1999
|
-
console.log(`listed ${
|
|
2916
|
+
console.log(`listed ${pc9.cyan(r.ask.id)}`);
|
|
2000
2917
|
console.log(formatListingRow(r.ask));
|
|
2001
2918
|
});
|
|
2002
2919
|
} catch (e) {
|
|
2003
2920
|
fail(e, opts);
|
|
2004
2921
|
}
|
|
2005
2922
|
});
|
|
2006
|
-
|
|
2923
|
+
common2(
|
|
2007
2924
|
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
2925
|
).action(async (listingId, opts) => {
|
|
2009
2926
|
try {
|
|
@@ -2012,8 +2929,8 @@ function registerMarketCommands(program2) {
|
|
|
2012
2929
|
listingPatchBody(listingId, { price: opts.price, per: opts.per })
|
|
2013
2930
|
);
|
|
2014
2931
|
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 ${
|
|
2932
|
+
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);
|
|
2933
|
+
console.log(`repriced ${pc9.cyan(r.ask.id)} ${rate}`);
|
|
2017
2934
|
});
|
|
2018
2935
|
} catch (e) {
|
|
2019
2936
|
fail(e, opts);
|
|
@@ -2026,19 +2943,19 @@ function registerMarketCommands(program2) {
|
|
|
2026
2943
|
listingPatchBody(listingId, { status })
|
|
2027
2944
|
);
|
|
2028
2945
|
output(opts, result, (r) => {
|
|
2029
|
-
console.log(`${status === "live" ? "resumed" : "paused"} ${
|
|
2946
|
+
console.log(`${status === "live" ? "resumed" : "paused"} ${pc9.cyan(r.ask.id)}`);
|
|
2030
2947
|
});
|
|
2031
2948
|
} catch (e) {
|
|
2032
2949
|
fail(e, opts);
|
|
2033
2950
|
}
|
|
2034
2951
|
};
|
|
2035
|
-
|
|
2952
|
+
common2(
|
|
2036
2953
|
market.command("pause").description("Pause a listing \u2014 it stays posted but cannot fill").argument("<listing-id>", "listing ID")
|
|
2037
2954
|
).action((listingId, opts) => setStatus(listingId, "paused", opts));
|
|
2038
|
-
|
|
2955
|
+
common2(
|
|
2039
2956
|
market.command("resume").description("Resume a paused listing").argument("<listing-id>", "listing ID")
|
|
2040
2957
|
).action((listingId, opts) => setStatus(listingId, "live", opts));
|
|
2041
|
-
|
|
2958
|
+
common2(
|
|
2042
2959
|
market.command("withdraw").description("Withdraw a listing \u2014 it leaves the book for good").argument("<listing-id>", "listing ID")
|
|
2043
2960
|
).action(async (listingId, opts) => {
|
|
2044
2961
|
try {
|
|
@@ -2046,13 +2963,13 @@ function registerMarketCommands(program2) {
|
|
|
2046
2963
|
`/api/v1/market/asks?id=${encodeURIComponent(listingId)}`
|
|
2047
2964
|
);
|
|
2048
2965
|
output(opts, result, (r) => {
|
|
2049
|
-
console.log(`withdrew ${
|
|
2966
|
+
console.log(`withdrew ${pc9.cyan(r.ask.id)}`);
|
|
2050
2967
|
});
|
|
2051
2968
|
} catch (e) {
|
|
2052
2969
|
fail(e, opts);
|
|
2053
2970
|
}
|
|
2054
2971
|
});
|
|
2055
|
-
|
|
2972
|
+
common2(
|
|
2056
2973
|
market.command("replace").description(
|
|
2057
2974
|
"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
2975
|
).argument("[listing-id]", "listing to pause and evict every sale on").option("--fill <fill-id>", "evict one sale without touching the listing")
|
|
@@ -2067,14 +2984,14 @@ function registerMarketCommands(program2) {
|
|
|
2067
2984
|
} else {
|
|
2068
2985
|
const result = await c.post(target.path, {});
|
|
2069
2986
|
output(opts, result, (r) => {
|
|
2070
|
-
console.log(`paused ${
|
|
2987
|
+
console.log(`paused ${pc9.cyan(r.listing.id)}`);
|
|
2071
2988
|
if (r.fills.length === 0) {
|
|
2072
|
-
console.log(
|
|
2989
|
+
console.log(pc9.dim(" no live sales to evict"));
|
|
2073
2990
|
return;
|
|
2074
2991
|
}
|
|
2075
2992
|
for (const f of r.fills) {
|
|
2076
2993
|
if (f.ok) console.log(formatReplacedFill(f.fill));
|
|
2077
|
-
else console.log(
|
|
2994
|
+
else console.log(pc9.red(` could not evict a sale \u2014 ${f.error}`));
|
|
2078
2995
|
}
|
|
2079
2996
|
});
|
|
2080
2997
|
if (result.fills.some((f) => !f.ok)) process.exitCode = 1;
|
|
@@ -2084,7 +3001,7 @@ function registerMarketCommands(program2) {
|
|
|
2084
3001
|
}
|
|
2085
3002
|
}
|
|
2086
3003
|
);
|
|
2087
|
-
|
|
3004
|
+
common2(
|
|
2088
3005
|
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
3006
|
).action(async (opts) => {
|
|
2090
3007
|
try {
|
|
@@ -2097,7 +3014,7 @@ function registerMarketCommands(program2) {
|
|
|
2097
3014
|
fail(e, opts);
|
|
2098
3015
|
}
|
|
2099
3016
|
});
|
|
2100
|
-
|
|
3017
|
+
common2(
|
|
2101
3018
|
market.command("settlements").description("Your monthly payout reports")
|
|
2102
3019
|
).action(async (opts) => {
|
|
2103
3020
|
try {
|
|
@@ -2113,7 +3030,7 @@ function registerMarketCommands(program2) {
|
|
|
2113
3030
|
fail(e, opts);
|
|
2114
3031
|
}
|
|
2115
3032
|
});
|
|
2116
|
-
|
|
3033
|
+
common2(
|
|
2117
3034
|
market.command("status").description("Who you are on the market: seller identity, credential, sizes, regions")
|
|
2118
3035
|
).action(async (opts) => {
|
|
2119
3036
|
try {
|
|
@@ -2124,7 +3041,7 @@ function registerMarketCommands(program2) {
|
|
|
2124
3041
|
}
|
|
2125
3042
|
});
|
|
2126
3043
|
const cap = market.command("cap").description("The org market cap: the most a market-placed job pays without its own bid");
|
|
2127
|
-
|
|
3044
|
+
common2(cap.command("show", { isDefault: true }).description("Show the current cap")).action(
|
|
2128
3045
|
async (opts) => {
|
|
2129
3046
|
try {
|
|
2130
3047
|
const { marketCap } = await (await client(opts)).get(
|
|
@@ -2136,7 +3053,7 @@ function registerMarketCommands(program2) {
|
|
|
2136
3053
|
}
|
|
2137
3054
|
}
|
|
2138
3055
|
);
|
|
2139
|
-
|
|
3056
|
+
common2(
|
|
2140
3057
|
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
3058
|
).action(async (opts) => {
|
|
2142
3059
|
try {
|
|
@@ -2150,7 +3067,7 @@ function registerMarketCommands(program2) {
|
|
|
2150
3067
|
fail(e, opts);
|
|
2151
3068
|
}
|
|
2152
3069
|
});
|
|
2153
|
-
|
|
3070
|
+
common2(
|
|
2154
3071
|
cap.command("clear").description("Remove the cap (refused while your placement order still names market)")
|
|
2155
3072
|
).action(async (opts) => {
|
|
2156
3073
|
try {
|
|
@@ -2163,7 +3080,7 @@ function registerMarketCommands(program2) {
|
|
|
2163
3080
|
fail(e, opts);
|
|
2164
3081
|
}
|
|
2165
3082
|
});
|
|
2166
|
-
|
|
3083
|
+
common2(
|
|
2167
3084
|
market.command("bids").description("Your org's standing bids \u2014 open, filled, and cancelled")
|
|
2168
3085
|
).action(async (opts) => {
|
|
2169
3086
|
try {
|
|
@@ -2181,7 +3098,7 @@ function registerMarketCommands(program2) {
|
|
|
2181
3098
|
fail(e, opts);
|
|
2182
3099
|
}
|
|
2183
3100
|
});
|
|
2184
|
-
|
|
3101
|
+
common2(
|
|
2185
3102
|
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
3103
|
).action(async (opts) => {
|
|
2187
3104
|
try {
|
|
@@ -2190,26 +3107,26 @@ function registerMarketCommands(program2) {
|
|
|
2190
3107
|
bidBody(opts)
|
|
2191
3108
|
);
|
|
2192
3109
|
output(opts, result, (r) => {
|
|
2193
|
-
console.log(`bid placed ${
|
|
3110
|
+
console.log(`bid placed ${pc9.cyan(r.bid.id)}`);
|
|
2194
3111
|
console.log(formatBidRow(r.bid));
|
|
2195
3112
|
});
|
|
2196
3113
|
} catch (e) {
|
|
2197
3114
|
fail(e, opts);
|
|
2198
3115
|
}
|
|
2199
3116
|
});
|
|
2200
|
-
|
|
3117
|
+
common2(
|
|
2201
3118
|
market.command("cancel-bid").description("Cancel an open standing bid").argument("<bid-id>", "bid ID")
|
|
2202
3119
|
).action(async (bidId, opts) => {
|
|
2203
3120
|
try {
|
|
2204
3121
|
const result = await (await client(opts)).del(
|
|
2205
3122
|
`/api/v1/market/bids?id=${encodeURIComponent(bidId)}`
|
|
2206
3123
|
);
|
|
2207
|
-
output(opts, result, (r) => console.log(`cancelled ${
|
|
3124
|
+
output(opts, result, (r) => console.log(`cancelled ${pc9.cyan(r.bid.id)}`));
|
|
2208
3125
|
} catch (e) {
|
|
2209
3126
|
fail(e, opts);
|
|
2210
3127
|
}
|
|
2211
3128
|
});
|
|
2212
|
-
|
|
3129
|
+
common2(
|
|
2213
3130
|
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
3131
|
).action(async (opts) => {
|
|
2215
3132
|
try {
|
|
@@ -2220,13 +3137,13 @@ function registerMarketCommands(program2) {
|
|
|
2220
3137
|
return;
|
|
2221
3138
|
}
|
|
2222
3139
|
for (const row of p2.purchases) console.log(formatPurchaseRow(row));
|
|
2223
|
-
if (p2.nextCursor) console.log(
|
|
3140
|
+
if (p2.nextCursor) console.log(pc9.dim(`more: --cursor ${p2.nextCursor}`));
|
|
2224
3141
|
});
|
|
2225
3142
|
} catch (e) {
|
|
2226
3143
|
fail(e, opts);
|
|
2227
3144
|
}
|
|
2228
3145
|
});
|
|
2229
|
-
|
|
3146
|
+
common2(
|
|
2230
3147
|
market.command("credits").description("Prepaid market credits: available balance and reserved holds")
|
|
2231
3148
|
).action(async (opts) => {
|
|
2232
3149
|
try {
|
|
@@ -2238,7 +3155,7 @@ function registerMarketCommands(program2) {
|
|
|
2238
3155
|
fail(e, opts);
|
|
2239
3156
|
}
|
|
2240
3157
|
});
|
|
2241
|
-
|
|
3158
|
+
common2(
|
|
2242
3159
|
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
3160
|
).action(async (opts) => {
|
|
2244
3161
|
try {
|
|
@@ -2249,13 +3166,13 @@ function registerMarketCommands(program2) {
|
|
|
2249
3166
|
return;
|
|
2250
3167
|
}
|
|
2251
3168
|
for (const entry of p2.entries) console.log(formatLedgerRow(entry));
|
|
2252
|
-
if (p2.nextCursor) console.log(
|
|
3169
|
+
if (p2.nextCursor) console.log(pc9.dim(`more: --cursor ${p2.nextCursor}`));
|
|
2253
3170
|
});
|
|
2254
3171
|
} catch (e) {
|
|
2255
3172
|
fail(e, opts);
|
|
2256
3173
|
}
|
|
2257
3174
|
});
|
|
2258
|
-
|
|
3175
|
+
common2(
|
|
2259
3176
|
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
3177
|
).action(async (amount, opts) => {
|
|
2261
3178
|
try {
|
|
@@ -2272,7 +3189,7 @@ function registerMarketCommands(program2) {
|
|
|
2272
3189
|
}
|
|
2273
3190
|
});
|
|
2274
3191
|
const credential = market.command("credential").description("Connect the credential your listings fill under");
|
|
2275
|
-
|
|
3192
|
+
common2(
|
|
2276
3193
|
credential.command("connect").description(
|
|
2277
3194
|
"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
3195
|
).option("--field <pairs...>", "credential fields as name=value (prefer env vars for secrets)")
|
|
@@ -2303,7 +3220,7 @@ ${hints}`
|
|
|
2303
3220
|
}
|
|
2304
3221
|
if (resolved.fromFlag.some((name) => provider.credentialFields.find((f) => f.name === name)?.secret)) {
|
|
2305
3222
|
console.error(
|
|
2306
|
-
|
|
3223
|
+
pc9.yellow("note: a secret passed via --field stays in your shell history \u2014 prefer the env vars.")
|
|
2307
3224
|
);
|
|
2308
3225
|
}
|
|
2309
3226
|
const result = await c.post(
|
|
@@ -2311,13 +3228,13 @@ ${hints}`
|
|
|
2311
3228
|
credentialBody(provider.credentialFields, resolved.values)
|
|
2312
3229
|
);
|
|
2313
3230
|
output(opts, result, (r) => {
|
|
2314
|
-
console.log(`connected ${
|
|
3231
|
+
console.log(`connected ${pc9.cyan(safeTerm(r.provider.name))} credential saved`);
|
|
2315
3232
|
});
|
|
2316
3233
|
} catch (e) {
|
|
2317
3234
|
fail(e, opts);
|
|
2318
3235
|
}
|
|
2319
3236
|
});
|
|
2320
|
-
|
|
3237
|
+
common2(
|
|
2321
3238
|
credential.command("disconnect").description("Remove the stored credential \u2014 listings stop filling until a new one connects")
|
|
2322
3239
|
).action(async (opts) => {
|
|
2323
3240
|
try {
|
|
@@ -2325,7 +3242,7 @@ ${hints}`
|
|
|
2325
3242
|
"/api/v1/market/provider/credential"
|
|
2326
3243
|
);
|
|
2327
3244
|
output(opts, result, (r) => {
|
|
2328
|
-
console.log(`disconnected ${
|
|
3245
|
+
console.log(`disconnected ${pc9.cyan(safeTerm(r.provider.name))} credential removed`);
|
|
2329
3246
|
});
|
|
2330
3247
|
} catch (e) {
|
|
2331
3248
|
fail(e, opts);
|
|
@@ -2339,13 +3256,14 @@ import * as os from "os";
|
|
|
2339
3256
|
import * as path from "path";
|
|
2340
3257
|
import * as readline from "readline";
|
|
2341
3258
|
import { Readable } from "stream";
|
|
2342
|
-
import
|
|
3259
|
+
import { Option as Option3 } from "commander";
|
|
3260
|
+
import pc10 from "picocolors";
|
|
2343
3261
|
import * as tar from "tar";
|
|
2344
3262
|
|
|
2345
3263
|
// src/current-instance.ts
|
|
2346
3264
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
2347
3265
|
import { createHash } from "crypto";
|
|
2348
|
-
import { existsSync, mkdirSync as mkdirSync2, readFileSync as
|
|
3266
|
+
import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2349
3267
|
import { homedir } from "os";
|
|
2350
3268
|
import { join as join2 } from "path";
|
|
2351
3269
|
function stateDir() {
|
|
@@ -2368,7 +3286,7 @@ function orgKey(opts) {
|
|
|
2368
3286
|
const key = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY;
|
|
2369
3287
|
if (key) return `key:${createHash("sha256").update(key).digest("hex").slice(0, 12)}`;
|
|
2370
3288
|
try {
|
|
2371
|
-
const raw = JSON.parse(
|
|
3289
|
+
const raw = JSON.parse(readFileSync3(join2(stateDir(), "credentials.json"), "utf8"));
|
|
2372
3290
|
const org2 = raw?.orgId ?? raw?.orgSlug;
|
|
2373
3291
|
if (org2) return `org:${org2}`;
|
|
2374
3292
|
} catch {
|
|
@@ -2377,7 +3295,7 @@ function orgKey(opts) {
|
|
|
2377
3295
|
}
|
|
2378
3296
|
function readStore() {
|
|
2379
3297
|
try {
|
|
2380
|
-
const parsed = JSON.parse(
|
|
3298
|
+
const parsed = JSON.parse(readFileSync3(statePath(), "utf8"));
|
|
2381
3299
|
if (typeof parsed !== "object" || parsed === null) return {};
|
|
2382
3300
|
return parsed;
|
|
2383
3301
|
} catch {
|
|
@@ -2445,6 +3363,55 @@ function shortId(id) {
|
|
|
2445
3363
|
return id.length > 8 ? `${id.slice(0, 4)}\u2026` : id;
|
|
2446
3364
|
}
|
|
2447
3365
|
|
|
3366
|
+
// src/sandbox-billing.ts
|
|
3367
|
+
function printTable(header, rows) {
|
|
3368
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
3369
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
|
|
3370
|
+
console.log(line(header));
|
|
3371
|
+
for (const row of rows) console.log(line(row));
|
|
3372
|
+
}
|
|
3373
|
+
function printCosts(c, customerOnly) {
|
|
3374
|
+
if (customerOnly) console.log("customer sandboxes only");
|
|
3375
|
+
printTable(
|
|
3376
|
+
["PROVIDER", "SANDBOXES", "RUNNING", "RUNNING COST", "SETTLED", "TOTAL"],
|
|
3377
|
+
[
|
|
3378
|
+
[
|
|
3379
|
+
"all",
|
|
3380
|
+
String(c.running.count + c.settled.count),
|
|
3381
|
+
String(c.running.count),
|
|
3382
|
+
formatMoney(c.running.costUsd),
|
|
3383
|
+
`${c.settled.count} \xB7 ${formatMoney(c.settled.costUsd)}`,
|
|
3384
|
+
formatMoney(c.totalUsd)
|
|
3385
|
+
],
|
|
3386
|
+
...c.byProvider.map((p2) => [
|
|
3387
|
+
safeTerm(p2.provider),
|
|
3388
|
+
String(p2.count),
|
|
3389
|
+
p2.running ? String(p2.running.count) : "\u2014",
|
|
3390
|
+
p2.running ? formatMoney(p2.running.costUsd) : "\u2014",
|
|
3391
|
+
p2.settled ? `${p2.settled.count} \xB7 ${formatMoney(p2.settled.costUsd)}` : "\u2014",
|
|
3392
|
+
formatMoney(p2.costUsd)
|
|
3393
|
+
])
|
|
3394
|
+
]
|
|
3395
|
+
);
|
|
3396
|
+
if (c.currency !== "USD") console.log(`currency: ${safeTerm(c.currency)}`);
|
|
3397
|
+
}
|
|
3398
|
+
function registerBillingCommands(group, common2, deps) {
|
|
3399
|
+
common2(
|
|
3400
|
+
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")
|
|
3401
|
+
).action(async (opts) => {
|
|
3402
|
+
try {
|
|
3403
|
+
const c = await deps.client(opts);
|
|
3404
|
+
const res = await c.get(
|
|
3405
|
+
"/api/v1/sandboxes/costs",
|
|
3406
|
+
opts.customerOnly ? { customerOnly: "true" } : void 0
|
|
3407
|
+
);
|
|
3408
|
+
deps.output(opts, res, (data) => printCosts(data, opts.customerOnly === true));
|
|
3409
|
+
} catch (e) {
|
|
3410
|
+
deps.fail(e, opts);
|
|
3411
|
+
}
|
|
3412
|
+
});
|
|
3413
|
+
}
|
|
3414
|
+
|
|
2448
3415
|
// src/sandboxes.ts
|
|
2449
3416
|
function shellQuote(arg) {
|
|
2450
3417
|
return `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
@@ -2452,6 +3419,16 @@ function shellQuote(arg) {
|
|
|
2452
3419
|
function shortRate(rate) {
|
|
2453
3420
|
return `${formatUsd(rateAllUnits(rate).perHour)}/h`;
|
|
2454
3421
|
}
|
|
3422
|
+
function placementLane(source) {
|
|
3423
|
+
if (source === "house") return "managed";
|
|
3424
|
+
if (source === "own-key") return "BYOK";
|
|
3425
|
+
return source ?? "\u2014";
|
|
3426
|
+
}
|
|
3427
|
+
function billedBy(source, provider) {
|
|
3428
|
+
if (source === "house") return "billed from your ComputeSDK credit";
|
|
3429
|
+
if (source === "own-key") return `billed by ${provider} to your account`;
|
|
3430
|
+
return "billed from your ComputeSDK credit";
|
|
3431
|
+
}
|
|
2455
3432
|
function formatLocalTime(iso) {
|
|
2456
3433
|
const d = new Date(iso);
|
|
2457
3434
|
if (Number.isNaN(d.getTime())) return iso;
|
|
@@ -2461,63 +3438,77 @@ function formatLocalTime(iso) {
|
|
|
2461
3438
|
function printSandbox(s, verbose = false) {
|
|
2462
3439
|
const p2 = s.placement;
|
|
2463
3440
|
console.log(
|
|
2464
|
-
`${
|
|
3441
|
+
`${pc10.cyan(s.id)} ${s.status} ${p2?.box?.provider ?? s.provider ?? "\u2014"} \xB7 ${placementLane(p2?.source)} ${p2?.size ?? "\u2014"} ${p2 ? shortRate(p2.rate) : "\u2014"}`
|
|
2465
3442
|
);
|
|
2466
3443
|
if (s.label) {
|
|
2467
3444
|
console.log(` label: ${s.label} created: ${formatLocalTime(s.createdAt)}`);
|
|
2468
3445
|
}
|
|
2469
|
-
if (s.destroyError) console.log(` destroyError: ${
|
|
3446
|
+
if (s.destroyError) console.log(` destroyError: ${pc10.red(s.destroyError)}`);
|
|
2470
3447
|
if (!verbose) return;
|
|
2471
3448
|
console.log(` providerSandboxId: ${s.providerSandboxId ?? "\u2014"} commands: ${s.commandCount}`);
|
|
2472
3449
|
if (s.image !== void 0) {
|
|
2473
|
-
console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${
|
|
3450
|
+
console.log(` image: ${s.image ?? "\u2014"}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc10.dim(`(requested: ${s.requestedImage})`)}` : ""}`);
|
|
2474
3451
|
}
|
|
2475
3452
|
if (p2) {
|
|
2476
3453
|
const box = p2.box ? ` / ${p2.box.sizeName ?? "custom"}${p2.box.resources ? ` (${p2.box.resources.cpus ?? "?"} vCPU / ${p2.box.resources.memoryMb ?? "?"} MB)` : ""}` : "";
|
|
3454
|
+
const provider = p2.box?.provider ?? s.provider ?? "the provider";
|
|
2477
3455
|
console.log(
|
|
2478
|
-
` placement: ${p2.source}${box}
|
|
3456
|
+
` placement: ${placementLane(p2.source)}${box} rate: ${formatUsdPer(p2.rate)} ${pc10.dim(billedBy(p2.source, provider))}`
|
|
2479
3457
|
);
|
|
2480
3458
|
}
|
|
2481
3459
|
const attach = "attach" in s ? s.attach : void 0;
|
|
2482
3460
|
if (attach !== void 0) {
|
|
2483
3461
|
console.log(
|
|
2484
|
-
attach === null ? " attach: none (
|
|
3462
|
+
attach === null ? " attach: none (managed account or platform provider \u2014 drive it through ComputeSDK)" : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ""}`
|
|
2485
3463
|
);
|
|
2486
3464
|
}
|
|
2487
3465
|
}
|
|
2488
|
-
var perHour = (n) => n === void 0 ? "\u2014" : formatRateAllUnits(rateAllUnits({ usd: n, per: "hour" }));
|
|
2489
3466
|
var usdAmount = (n) => n === void 0 ? "\u2014" : formatMoney(n);
|
|
3467
|
+
function walkEntry(entry) {
|
|
3468
|
+
if (entry.startsWith("managed/")) return `${entry.slice("managed/".length)} (managed)`;
|
|
3469
|
+
if (entry === "market" || entry.startsWith("market:")) return entry;
|
|
3470
|
+
return `${entry} (BYOK)`;
|
|
3471
|
+
}
|
|
3472
|
+
function quoteRefusal(q) {
|
|
3473
|
+
switch (q.reason) {
|
|
3474
|
+
case "insufficient_credits":
|
|
3475
|
+
return `not enough ComputeSDK credit for the hold (need ${usdAmount(q.requiredHoldUsd)}, have ${usdAmount(q.creditBalanceUsd)})`;
|
|
3476
|
+
case "no_provider_configured":
|
|
3477
|
+
return "nothing in the router can place this size: no live managed account prices it, and no BYOK key covers it";
|
|
3478
|
+
default:
|
|
3479
|
+
return q.reason ?? "nothing in the router can place it";
|
|
3480
|
+
}
|
|
3481
|
+
}
|
|
2490
3482
|
function printQuote(q, timeoutMs) {
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
if (q.liveAskDepth !== void 0) console.log(` ${pc4.dim(`live asks: ${q.liveAskDepth}`)}`);
|
|
3483
|
+
const row = (label, value) => console.log(`${label.padEnd(10)} ${value}`);
|
|
3484
|
+
if (!q.ok || !q.placement) {
|
|
3485
|
+
row("Lands on", pc10.red(`nowhere \u2014 ${quoteRefusal(q)}`));
|
|
3486
|
+
if (q.reason === "insufficient_credits" && q.topUpPath) row("Top up", q.topUpPath);
|
|
3487
|
+
} else {
|
|
3488
|
+
const p2 = q.placement;
|
|
3489
|
+
const provider = p2.box?.provider ?? p2.provider;
|
|
3490
|
+
row("Lands on", `${provider} \xB7 ${placementLane(p2.source)} \xB7 ${p2.size ?? p2.box?.sizeName ?? "custom size"}`);
|
|
3491
|
+
row("Rate", q.rateUsd ? formatRateAllUnits(q.rateUsd) : q.rate ? formatUsdPer(q.rate) : "\u2014");
|
|
3492
|
+
if (p2.source === "own-key") {
|
|
3493
|
+
row("Billing", `billed by ${provider} to your account`);
|
|
3494
|
+
} else if (q.requiredHoldUsd !== void 0) {
|
|
3495
|
+
const timeout = timeoutMs !== void 0 ? ` for ${timeoutMs}ms` : " for the timeout";
|
|
3496
|
+
row("Billing", `from your ComputeSDK credit: ${usdAmount(q.requiredHoldUsd)} held${timeout}, settled at actual runtime (balance ${usdAmount(q.creditBalanceUsd)})`);
|
|
3497
|
+
} else {
|
|
3498
|
+
row("Billing", `from your ComputeSDK credit (balance ${usdAmount(q.creditBalanceUsd)})`);
|
|
3499
|
+
if (q.estimatedCostUsd !== void 0) row("Estimate", usdAmount(q.estimatedCostUsd));
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
row("Tries", q.providerOrder.map(walkEntry).join(" \u2192 ") || "\u2014");
|
|
2512
3503
|
}
|
|
2513
3504
|
function printProcess(p2) {
|
|
2514
3505
|
const exit = p2.status === "exited" ? `exit=${p2.exitCode ?? "?"}${p2.signal ? ` (${p2.signal})` : ""}` : "";
|
|
2515
3506
|
const stdin = p2.stdin && p2.status === "running" ? " [stdin open]" : "";
|
|
2516
|
-
console.log(`${
|
|
3507
|
+
console.log(`${pc10.cyan(p2.jobId)} ${p2.status}${exit ? " " + exit : ""}${stdin} ${p2.command}`);
|
|
2517
3508
|
}
|
|
2518
3509
|
function printSnapshot(s) {
|
|
2519
|
-
const state = s.deletedAt !== null ? ` ${
|
|
2520
|
-
console.log(`${
|
|
3510
|
+
const state = s.deletedAt !== null ? ` ${pc10.dim(`(deleted ${s.deletedAt})`)}` : "";
|
|
3511
|
+
console.log(`${pc10.cyan(s.id)} ${s.providerSnapshotId}${state}`);
|
|
2521
3512
|
console.log(
|
|
2522
3513
|
` provider: ${s.provider}${s.region ? ` (${s.region})` : ""} label: ${s.label ?? "\u2014"} created: ${s.createdAt}${s.expiresAt ? ` expires: ${s.expiresAt}` : ""}`
|
|
2523
3514
|
);
|
|
@@ -2620,7 +3611,7 @@ function resolveSandbox(argId, opts) {
|
|
|
2620
3611
|
if (!r) throw new Error(NO_INSTANCE_HINT);
|
|
2621
3612
|
if (r.source !== "argument" && !opts.json && !opts.quiet) {
|
|
2622
3613
|
console.error(
|
|
2623
|
-
|
|
3614
|
+
pc10.dim(
|
|
2624
3615
|
`instance ${shortId(r.id)} (${r.source === "env" ? "COMPUTE_INSTANCE" : `current for ${r.dir}`})`
|
|
2625
3616
|
)
|
|
2626
3617
|
);
|
|
@@ -2631,7 +3622,7 @@ function resolveSandbox(argId, opts) {
|
|
|
2631
3622
|
clearStale: (error) => {
|
|
2632
3623
|
if (r.source === "file" && error instanceof PlatformApiError && error.status === 404 && readFileCurrent(org2) === r.id) {
|
|
2633
3624
|
clearCurrentInstance(org2);
|
|
2634
|
-
console.error(
|
|
3625
|
+
console.error(pc10.dim(`cleared stale current instance ${shortId(r.id)}`));
|
|
2635
3626
|
}
|
|
2636
3627
|
}
|
|
2637
3628
|
};
|
|
@@ -2653,7 +3644,16 @@ function resolveTwoArgTarget(argId, resourceId, opts, label) {
|
|
|
2653
3644
|
return { resolved: resolveSandbox(argId, opts), resource: resourceId };
|
|
2654
3645
|
}
|
|
2655
3646
|
function addCreateFlags(c) {
|
|
2656
|
-
return c.option("--
|
|
3647
|
+
return c.option("--provider <names>", "place only on these providers, through your router (its BYOK mode and order), e.g. daytona or daytona,e2b").option("--byok", "use only your own keys for this create").option("--managed", "use only ComputeSDK managed accounts for this create").addOption(new Option3("--order <providers>").hideHelp()).option("--size <size>", "platform size: small (1 vCPU/2 GB), medium, large, xlarge (8/16 GB); default medium").option("--label <label>", "label for the sandbox").option("--image <image>", "container image to boot").option("--snapshot-id <id>", "provider snapshot to resume").option("--cpus <n>", "CPU cores (raw resources \u2014 mutually exclusive with --size)").option("--memory-mb <n>", "memory in MB (raw resources)").option("--disk-mb <n>", "ephemeral disk in MB (raw resources)").addOption(new Option3("--max-price <usd/unit>").hideHelp()).addOption(new Option3("--max-price-per <unit>").hideHelp()).addOption(new Option3("--market").hideHelp()).addOption(new Option3("--order-type <type>").hideHelp()).option("--timeout-ms <ms>", "sandbox timeout in ms (provider minimums apply, e.g. blaxel \u22655m)").option("--secret <name>", "vault secret name to inject (repeatable)", (v, a) => a.concat(v), []);
|
|
3648
|
+
}
|
|
3649
|
+
function providerNames(value) {
|
|
3650
|
+
const names = value.split(",").map((name) => name.trim()).filter(Boolean);
|
|
3651
|
+
if (names.length === 0) throw new Error(`--provider "${value}" names no providers.`);
|
|
3652
|
+
return names;
|
|
3653
|
+
}
|
|
3654
|
+
function accountMode(opts) {
|
|
3655
|
+
if (opts.byok && opts.managed) throw new Error("--byok and --managed are mutually exclusive.");
|
|
3656
|
+
return opts.byok ? "only" : opts.managed ? "off" : void 0;
|
|
2657
3657
|
}
|
|
2658
3658
|
function buildCreateBody(opts) {
|
|
2659
3659
|
const resources = {};
|
|
@@ -2661,6 +3661,15 @@ function buildCreateBody(opts) {
|
|
|
2661
3661
|
if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);
|
|
2662
3662
|
if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);
|
|
2663
3663
|
const body = {};
|
|
3664
|
+
if (opts.provider && opts.order) {
|
|
3665
|
+
throw new Error("--provider narrows your router; --order skips it. Pass one.");
|
|
3666
|
+
}
|
|
3667
|
+
if (opts.provider) body.only = providerNames(opts.provider);
|
|
3668
|
+
const mode = accountMode(opts);
|
|
3669
|
+
if (mode !== void 0) {
|
|
3670
|
+
if (opts.order) throw new Error("--byok/--managed apply to your router; --order skips it.");
|
|
3671
|
+
body.byok = mode;
|
|
3672
|
+
}
|
|
2664
3673
|
if (opts.order) body.providerOrder = opts.order.split(",").map((s) => s.trim());
|
|
2665
3674
|
if (opts.size) body.size = opts.size;
|
|
2666
3675
|
if (opts.label) body.label = opts.label;
|
|
@@ -2685,19 +3694,43 @@ function fmtTimeout(ms) {
|
|
|
2685
3694
|
return `${ms}ms`;
|
|
2686
3695
|
}
|
|
2687
3696
|
var PLATFORM_DEFAULT_TIMEOUT_MS = 30 * 6e4;
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
3697
|
+
var LIST_SORTS = ["created", "name", "cost", "runtime"];
|
|
3698
|
+
function listQuery(opts) {
|
|
3699
|
+
if (opts.sort !== void 0 && !LIST_SORTS.includes(opts.sort)) {
|
|
3700
|
+
throw new Error(`--sort must be one of ${LIST_SORTS.join(", ")}`);
|
|
3701
|
+
}
|
|
3702
|
+
if (opts.direction !== void 0 && opts.direction !== "asc" && opts.direction !== "desc") {
|
|
3703
|
+
throw new Error("--direction must be asc or desc");
|
|
3704
|
+
}
|
|
3705
|
+
return {
|
|
3706
|
+
status: opts.status,
|
|
3707
|
+
customerOnly: opts.customerOnly ? "true" : void 0,
|
|
3708
|
+
q: opts.search,
|
|
3709
|
+
sort: opts.sort,
|
|
3710
|
+
direction: opts.direction,
|
|
3711
|
+
limit: opts.limit,
|
|
3712
|
+
cursor: opts.cursor
|
|
3713
|
+
};
|
|
3714
|
+
}
|
|
3715
|
+
function registerCreate(command2, { providerShorthand = false } = {}) {
|
|
3716
|
+
addCreateFlags(command2).option("--no-use", "do not mark the new instance as this directory's current instance").option("-q, --quiet", "print only the new instance ID").option("--verbose", "print the full instance details").option("--api-key <key>", "platform API key (or COMPUTE_API_KEY)").option("--base-url <url>", "platform base URL").option("--allow-untrusted-host", "allow non-computesdk.com base URLs").option("--json", "print the raw response").action(async (...args) => {
|
|
3717
|
+
const operands = providerShorthand ? args[0] : [];
|
|
3718
|
+
const opts = args[providerShorthand ? 1 : 0];
|
|
2693
3719
|
try {
|
|
2694
3720
|
checkQuietJson(opts);
|
|
3721
|
+
const named = shorthandProviders(operands);
|
|
3722
|
+
if (named.length > 0) {
|
|
3723
|
+
if (opts.provider) throw new Error("Name providers either as words/flags or with --provider, not both.");
|
|
3724
|
+
opts.provider = named.join(",");
|
|
3725
|
+
}
|
|
3726
|
+
const body = buildCreateBody(opts);
|
|
2695
3727
|
const c = await client(opts);
|
|
2696
|
-
|
|
3728
|
+
if (!opts.json && !opts.quiet) await previewPlacement(c, opts);
|
|
3729
|
+
const res = await c.post("/api/v1/sandboxes", body);
|
|
2697
3730
|
if (opts.use !== false) {
|
|
2698
3731
|
setCurrentInstance(res.sandbox.id, orgKey(opts));
|
|
2699
3732
|
if (!opts.json && !opts.quiet) {
|
|
2700
|
-
console.error(
|
|
3733
|
+
console.error(pc10.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));
|
|
2701
3734
|
}
|
|
2702
3735
|
}
|
|
2703
3736
|
emitResult(opts, res.sandbox, (s) => s.id, (s) => printSandbox(s, opts.verbose));
|
|
@@ -2705,42 +3738,94 @@ function registerSandboxesCommands(program2) {
|
|
|
2705
3738
|
fail(e, opts);
|
|
2706
3739
|
}
|
|
2707
3740
|
});
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
3741
|
+
}
|
|
3742
|
+
async function previewPlacement(c, opts) {
|
|
3743
|
+
if (opts.order || opts.market || opts.orderType || opts.maxPrice) return;
|
|
3744
|
+
const mode = accountMode(opts);
|
|
3745
|
+
const params = {
|
|
3746
|
+
size: opts.size,
|
|
3747
|
+
cpus: opts.cpus,
|
|
3748
|
+
memoryMb: opts.memoryMb,
|
|
3749
|
+
ephemeralDiskMb: opts.diskMb,
|
|
3750
|
+
timeoutMs: opts.timeoutMs,
|
|
3751
|
+
only: opts.provider === void 0 ? void 0 : providerNames(opts.provider).join(","),
|
|
3752
|
+
byok: mode
|
|
3753
|
+
};
|
|
3754
|
+
let quote;
|
|
3755
|
+
try {
|
|
3756
|
+
quote = (await c.get("/api/v1/sandboxes/quote", params)).quote;
|
|
3757
|
+
} catch {
|
|
3758
|
+
return;
|
|
3759
|
+
}
|
|
3760
|
+
if (!quote.ok || !quote.placement) {
|
|
3761
|
+
console.error(pc10.dim(`\u2192 the router can't place this: ${quoteRefusal(quote)}`));
|
|
3762
|
+
return;
|
|
3763
|
+
}
|
|
3764
|
+
const p2 = quote.placement;
|
|
3765
|
+
const provider = p2.box?.provider ?? p2.provider;
|
|
3766
|
+
console.error(
|
|
3767
|
+
pc10.dim(`\u2192 placing on ${provider} \xB7 ${placementLane(p2.source)} \xB7 ${p2.size ?? p2.box?.sizeName ?? "custom size"} (${billedBy(p2.source, provider)}) \u2026`)
|
|
3768
|
+
);
|
|
3769
|
+
}
|
|
3770
|
+
function shorthandProviders(operands) {
|
|
3771
|
+
return operands.map((operand) => {
|
|
3772
|
+
const name = operand.startsWith("--") ? operand.slice(2) : operand;
|
|
3773
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
|
|
3774
|
+
throw new Error(`"${operand}" isn't a provider name \u2014 use e.g. \`compute new vercel\` or \`compute new --vercel\`.`);
|
|
2735
3775
|
}
|
|
3776
|
+
return name;
|
|
2736
3777
|
});
|
|
2737
|
-
|
|
3778
|
+
}
|
|
3779
|
+
function registerSandboxesCommands(program2) {
|
|
3780
|
+
const cmd = program2.command("instances").alias("sandboxes").alias("sbx").description("Create and drive compute instances through the platform").enablePositionalOptions().configureOutput({ outputError: usageErrorOutput });
|
|
3781
|
+
registerCreate(
|
|
3782
|
+
cmd.command("create").description("Create a sandbox through your Sandboxes router (`compute sandboxes route` shows where it lands)")
|
|
3783
|
+
);
|
|
3784
|
+
registerCreate(
|
|
3785
|
+
program2.command("new").description("Create a sandbox (short for `compute sandboxes create`); `compute new vercel` or `--vercel` picks the provider").argument("[providers...]", "only these providers, through your router (vercel, --vercel, e2b, \u2026)").allowUnknownOption().configureOutput({ outputError: usageErrorOutput }),
|
|
3786
|
+
{ providerShorthand: true }
|
|
3787
|
+
);
|
|
3788
|
+
for (const name of ["route", "quote"]) {
|
|
3789
|
+
const command2 = cmd.command(name, { hidden: name === "quote" }).description("Show where a sandbox create would land, how it is billed, and the price \u2014 creates nothing").option("--size <size>", "platform size: small, medium (default), large, xlarge").option("--provider <names>", "only these providers, through your router (e.g. daytona)").option("--byok", "only your own keys").option("--managed", "only ComputeSDK managed accounts").option("--cpus <n>", "CPU cores (raw resources instead of --size)").option("--memory-mb <n>", "memory in MB").option("--disk-mb <n>", "ephemeral disk in MB").option("--region <region>", "pin the placement region").option("--timeout-ms <ms>", "sandbox timeout in ms; a managed account holds credit for it").addOption(new Option3("--order-type <type>").hideHelp()).addOption(new Option3("--market").hideHelp()).addOption(new Option3("--max-price <usd/unit>").hideHelp()).addOption(new Option3("--max-price-per <unit>").hideHelp()).option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response");
|
|
3790
|
+
command2.action(async (opts) => {
|
|
3791
|
+
try {
|
|
3792
|
+
const c = await client(opts);
|
|
3793
|
+
const params = {
|
|
3794
|
+
size: opts.size,
|
|
3795
|
+
only: opts.provider === void 0 ? void 0 : providerNames(opts.provider).join(","),
|
|
3796
|
+
byok: accountMode(opts),
|
|
3797
|
+
cpus: opts.cpus,
|
|
3798
|
+
memoryMb: opts.memoryMb,
|
|
3799
|
+
ephemeralDiskMb: opts.diskMb,
|
|
3800
|
+
region: opts.region,
|
|
3801
|
+
timeoutMs: opts.timeoutMs,
|
|
3802
|
+
orderType: opts.market ? "market" : opts.orderType
|
|
3803
|
+
};
|
|
3804
|
+
if (opts.orderType && opts.market) {
|
|
3805
|
+
throw new Error("--market and --order-type are mutually exclusive.");
|
|
3806
|
+
}
|
|
3807
|
+
const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);
|
|
3808
|
+
if (maxPrice) {
|
|
3809
|
+
params.maxPriceUsd = String(maxPrice.usd);
|
|
3810
|
+
params.maxPricePer = maxPrice.per;
|
|
3811
|
+
}
|
|
3812
|
+
const res = await c.get(
|
|
3813
|
+
"/api/v1/sandboxes/quote",
|
|
3814
|
+
params
|
|
3815
|
+
);
|
|
3816
|
+
output(opts, res.quote, (quote) => printQuote(quote, opts.timeoutMs));
|
|
3817
|
+
} catch (e) {
|
|
3818
|
+
fail(e, opts);
|
|
3819
|
+
}
|
|
3820
|
+
});
|
|
3821
|
+
}
|
|
3822
|
+
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
3823
|
try {
|
|
2739
3824
|
checkQuietJson(opts);
|
|
2740
3825
|
const c = await client(opts);
|
|
2741
3826
|
const res = await c.get(
|
|
2742
3827
|
"/api/v1/sandboxes",
|
|
2743
|
-
|
|
3828
|
+
listQuery(opts)
|
|
2744
3829
|
);
|
|
2745
3830
|
emitResult(
|
|
2746
3831
|
opts,
|
|
@@ -2748,7 +3833,7 @@ function registerSandboxesCommands(program2) {
|
|
|
2748
3833
|
(page) => page.sandboxes.map((s) => s.id).join("\n"),
|
|
2749
3834
|
(page) => {
|
|
2750
3835
|
page.sandboxes.forEach((s) => printSandbox(s, opts.verbose));
|
|
2751
|
-
if (page.nextCursor) console.log(
|
|
3836
|
+
if (page.nextCursor) console.log(pc10.dim(`nextCursor: ${page.nextCursor}`));
|
|
2752
3837
|
}
|
|
2753
3838
|
);
|
|
2754
3839
|
} catch (e) {
|
|
@@ -2821,7 +3906,7 @@ function registerSandboxesCommands(program2) {
|
|
|
2821
3906
|
if (readFileCurrent(org2) === resolved.id) {
|
|
2822
3907
|
clearCurrentInstance(org2);
|
|
2823
3908
|
if (!opts.json) {
|
|
2824
|
-
console.error(
|
|
3909
|
+
console.error(pc10.dim(`cleared current instance ${shortId(resolved.id)}`));
|
|
2825
3910
|
}
|
|
2826
3911
|
}
|
|
2827
3912
|
output(opts, res.sandbox, printSandbox);
|
|
@@ -2840,9 +3925,9 @@ function registerSandboxesCommands(program2) {
|
|
|
2840
3925
|
if (opts.keep && opts.detach) throw new Error("--keep and --detach are mutually exclusive.");
|
|
2841
3926
|
const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
|
|
2842
3927
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2843
|
-
const
|
|
2844
|
-
if (
|
|
2845
|
-
await runInstanceCommand(
|
|
3928
|
+
const command2 = lead.command;
|
|
3929
|
+
if (command2.length === 0) throw new Error("missing command to run");
|
|
3930
|
+
await runInstanceCommand(command2, opts);
|
|
2846
3931
|
} catch (e) {
|
|
2847
3932
|
fail(e, opts);
|
|
2848
3933
|
}
|
|
@@ -2857,15 +3942,15 @@ function registerSandboxesCommands(program2) {
|
|
|
2857
3942
|
}
|
|
2858
3943
|
const lead = takeLeadingOptions(rawCommand, SERVE_LEAD_OPTS);
|
|
2859
3944
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2860
|
-
const
|
|
2861
|
-
if (
|
|
3945
|
+
const command2 = lead.command;
|
|
3946
|
+
if (command2.length === 0) throw new Error("missing command to serve");
|
|
2862
3947
|
if (opts.port === void 0) throw new Error("--port is required");
|
|
2863
3948
|
const port = Number(opts.port);
|
|
2864
3949
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
2865
3950
|
throw new Error("--port must be an integer between 1 and 65535");
|
|
2866
3951
|
}
|
|
2867
3952
|
const resolved = resolveSandbox(argId, opts);
|
|
2868
|
-
await serveInstanceCommand(resolved.id,
|
|
3953
|
+
await serveInstanceCommand(resolved.id, command2, port, opts);
|
|
2869
3954
|
} catch (e) {
|
|
2870
3955
|
fail(e, opts);
|
|
2871
3956
|
}
|
|
@@ -2879,14 +3964,14 @@ function registerSandboxesCommands(program2) {
|
|
|
2879
3964
|
}
|
|
2880
3965
|
const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);
|
|
2881
3966
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2882
|
-
const
|
|
2883
|
-
if (
|
|
3967
|
+
const command2 = lead.command;
|
|
3968
|
+
if (command2.length === 0) throw new Error("missing command to run");
|
|
2884
3969
|
const resolved = resolveSandbox(argId, opts);
|
|
2885
3970
|
const c = await client(opts);
|
|
2886
3971
|
const res = await c.post(
|
|
2887
3972
|
`/api/v1/sandboxes/${resolved.id}/commands`,
|
|
2888
3973
|
{
|
|
2889
|
-
command:
|
|
3974
|
+
command: command2.map(shellQuote).join(" "),
|
|
2890
3975
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
2891
3976
|
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
|
|
2892
3977
|
...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
|
|
@@ -2915,14 +4000,14 @@ function registerSandboxesCommands(program2) {
|
|
|
2915
4000
|
const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);
|
|
2916
4001
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
2917
4002
|
checkQuietJson(opts);
|
|
2918
|
-
const
|
|
2919
|
-
if (
|
|
4003
|
+
const command2 = lead.command;
|
|
4004
|
+
if (command2.length === 0) throw new Error("missing command to spawn");
|
|
2920
4005
|
const resolved = resolveSandbox(argId, opts);
|
|
2921
4006
|
const c = await client(opts);
|
|
2922
4007
|
const res = await c.post(
|
|
2923
4008
|
`/api/v1/sandboxes/${resolved.id}/processes`,
|
|
2924
4009
|
{
|
|
2925
|
-
command:
|
|
4010
|
+
command: command2.map(shellQuote).join(" "),
|
|
2926
4011
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
2927
4012
|
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
|
|
2928
4013
|
...opts.stdin ? { stdin: true } : {}
|
|
@@ -3014,7 +4099,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3014
4099
|
data = opts.base64 ? piped.toString("base64") : piped.toString("utf8");
|
|
3015
4100
|
}
|
|
3016
4101
|
if (data === void 0 || data === "") {
|
|
3017
|
-
console.error(
|
|
4102
|
+
console.error(pc10.red("Pass --data, --file, or pipe stdin"));
|
|
3018
4103
|
process.exit(1);
|
|
3019
4104
|
}
|
|
3020
4105
|
if (opts.base64 && opts.data !== void 0) {
|
|
@@ -3062,7 +4147,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3062
4147
|
output(opts, res, (view) => {
|
|
3063
4148
|
if (view.type === "directory") {
|
|
3064
4149
|
for (const e of view.entries) {
|
|
3065
|
-
console.log(`${e.type === "directory" ?
|
|
4150
|
+
console.log(`${e.type === "directory" ? pc10.blue("d") : " "} ${e.name}${e.size !== void 0 ? ` ${pc10.dim(String(e.size))}` : ""}`);
|
|
3066
4151
|
}
|
|
3067
4152
|
} else {
|
|
3068
4153
|
console.log(`${view.path} file ${view.content.length} chars`);
|
|
@@ -3089,7 +4174,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3089
4174
|
const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, { path: p2 });
|
|
3090
4175
|
output(opts, res, (view) => {
|
|
3091
4176
|
if (view.type !== "file") {
|
|
3092
|
-
console.error(
|
|
4177
|
+
console.error(pc10.red(`${view.path} is a directory`));
|
|
3093
4178
|
process.exit(1);
|
|
3094
4179
|
}
|
|
3095
4180
|
process.stdout.write(view.content);
|
|
@@ -3126,7 +4211,7 @@ function registerSandboxesCommands(program2) {
|
|
|
3126
4211
|
});
|
|
3127
4212
|
}
|
|
3128
4213
|
if (content === void 0) {
|
|
3129
|
-
console.error(
|
|
4214
|
+
console.error(pc10.red("Pass --content, --file, or pipe stdin"));
|
|
3130
4215
|
process.exit(1);
|
|
3131
4216
|
}
|
|
3132
4217
|
const c = await client(opts);
|
|
@@ -3246,12 +4331,9 @@ function registerSandboxesCommands(program2) {
|
|
|
3246
4331
|
for (const sub of cmd.commands) {
|
|
3247
4332
|
sub.option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)");
|
|
3248
4333
|
}
|
|
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
|
-
);
|
|
4334
|
+
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");
|
|
4335
|
+
registerSettingsCommands(cmd, "sandboxes", nestedCommon, { client, fail, output, usageErrorOutput });
|
|
4336
|
+
registerBillingCommands(cmd, nestedCommon, { client, fail, output });
|
|
3255
4337
|
}
|
|
3256
4338
|
async function followProcess(c, sandboxId, jobId) {
|
|
3257
4339
|
let exitCode = 0;
|
|
@@ -3265,11 +4347,11 @@ async function followProcess(c, sandboxId, jobId) {
|
|
|
3265
4347
|
exitCode = typeof payload.exitCode === "number" ? payload.exitCode : 128;
|
|
3266
4348
|
return finish();
|
|
3267
4349
|
} else if (event === "error") {
|
|
3268
|
-
console.error(
|
|
4350
|
+
console.error(pc10.red(`Error: ${String(payload.error ?? "stream error")}`));
|
|
3269
4351
|
return finish(1);
|
|
3270
4352
|
}
|
|
3271
4353
|
}
|
|
3272
|
-
console.error(
|
|
4354
|
+
console.error(pc10.yellow("stream ended before the process exited"));
|
|
3273
4355
|
return finish(2);
|
|
3274
4356
|
function finish(code) {
|
|
3275
4357
|
if (code !== void 0) exitCode = code;
|
|
@@ -3285,15 +4367,15 @@ function printDetachSummary(sandboxId, jobId, timeoutText) {
|
|
|
3285
4367
|
function runTimeoutText(opts) {
|
|
3286
4368
|
return opts.timeoutMs ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}` : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;
|
|
3287
4369
|
}
|
|
3288
|
-
async function runInstanceCommand(
|
|
4370
|
+
async function runInstanceCommand(command2, opts) {
|
|
3289
4371
|
const c = await client(opts);
|
|
3290
4372
|
const created = await c.post("/api/v1/sandboxes", buildCreateBody(opts));
|
|
3291
4373
|
const sandbox = created.sandbox;
|
|
3292
4374
|
const org2 = orgKey(opts);
|
|
3293
|
-
console.error(
|
|
4375
|
+
console.error(pc10.dim(`instance ${sandbox.id}`));
|
|
3294
4376
|
const spawned = await c.post(
|
|
3295
4377
|
`/api/v1/sandboxes/${sandbox.id}/processes`,
|
|
3296
|
-
{ command:
|
|
4378
|
+
{ command: command2.map(shellQuote).join(" ") }
|
|
3297
4379
|
).catch(async (e) => {
|
|
3298
4380
|
try {
|
|
3299
4381
|
await c.del(`/api/v1/sandboxes/${sandbox.id}`);
|
|
@@ -3368,7 +4450,7 @@ async function runInstanceCommand(command, opts) {
|
|
|
3368
4450
|
setCurrentInstance(sandbox.id, org2);
|
|
3369
4451
|
if (opts.quiet) console.log(sandbox.id);
|
|
3370
4452
|
else {
|
|
3371
|
-
console.error(
|
|
4453
|
+
console.error(pc10.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));
|
|
3372
4454
|
console.log(sandbox.id);
|
|
3373
4455
|
}
|
|
3374
4456
|
} else {
|
|
@@ -3376,7 +4458,7 @@ async function runInstanceCommand(command, opts) {
|
|
|
3376
4458
|
await c.del(`/api/v1/sandboxes/${sandbox.id}`);
|
|
3377
4459
|
} catch (e) {
|
|
3378
4460
|
console.error(
|
|
3379
|
-
|
|
4461
|
+
pc10.red(`destroy failed for ${sandbox.id}: ${e instanceof Error ? e.message : String(e)}`)
|
|
3380
4462
|
);
|
|
3381
4463
|
if (exitCode === null || exitCode === 0) exitCode = 1;
|
|
3382
4464
|
}
|
|
@@ -3388,12 +4470,12 @@ async function runInstanceCommand(command, opts) {
|
|
|
3388
4470
|
}
|
|
3389
4471
|
var SERVE_POLL_MS = 3e4;
|
|
3390
4472
|
var SERVE_DEFAULT_WAIT_MS = 12e4;
|
|
3391
|
-
async function serveInstanceCommand(id,
|
|
4473
|
+
async function serveInstanceCommand(id, command2, port, opts) {
|
|
3392
4474
|
const c = await client(opts);
|
|
3393
4475
|
const spawned = await c.post(
|
|
3394
4476
|
`/api/v1/sandboxes/${id}/processes`,
|
|
3395
4477
|
{
|
|
3396
|
-
command:
|
|
4478
|
+
command: command2.map(shellQuote).join(" "),
|
|
3397
4479
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
3398
4480
|
...opts.env?.length ? { env: parseInputs(opts.env) } : {}
|
|
3399
4481
|
}
|
|
@@ -3404,7 +4486,7 @@ async function serveInstanceCommand(id, command, port, opts) {
|
|
|
3404
4486
|
if (!opts.json) {
|
|
3405
4487
|
const logs = `${proc.stdout}${proc.stderr}`.trimEnd().split("\n");
|
|
3406
4488
|
if (logs.length > 0 && logs[0] !== "") {
|
|
3407
|
-
console.error(
|
|
4489
|
+
console.error(pc10.dim("--- last log lines ---"));
|
|
3408
4490
|
for (const line of logs.slice(-50)) console.error(safeTerm(line));
|
|
3409
4491
|
}
|
|
3410
4492
|
}
|
|
@@ -3459,9 +4541,9 @@ async function serveInstanceCommand(id, command, port, opts) {
|
|
|
3459
4541
|
});
|
|
3460
4542
|
}
|
|
3461
4543
|
function printServeJobFooter(sandboxId, jobId) {
|
|
3462
|
-
console.error(
|
|
3463
|
-
console.error(
|
|
3464
|
-
console.error(
|
|
4544
|
+
console.error(pc10.dim(` job ${jobId}`));
|
|
4545
|
+
console.error(pc10.dim(` logs: compute instances logs ${sandboxId} ${jobId}`));
|
|
4546
|
+
console.error(pc10.dim(` kill: compute instances kill ${sandboxId} ${jobId}`));
|
|
3465
4547
|
}
|
|
3466
4548
|
var CP_PROGRESS_MIN_BYTES = 10 * 1024 * 1024;
|
|
3467
4549
|
function assertTransferUrl(raw) {
|
|
@@ -3619,8 +4701,8 @@ function formatBytes(n) {
|
|
|
3619
4701
|
}
|
|
3620
4702
|
|
|
3621
4703
|
// src/agents.ts
|
|
3622
|
-
import
|
|
3623
|
-
import { readFileSync as
|
|
4704
|
+
import pc11 from "picocolors";
|
|
4705
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
3624
4706
|
function formatLocalTime2(iso) {
|
|
3625
4707
|
if (iso === null) return "\u2014";
|
|
3626
4708
|
const d = new Date(iso);
|
|
@@ -3630,7 +4712,7 @@ function formatLocalTime2(iso) {
|
|
|
3630
4712
|
}
|
|
3631
4713
|
function printAgent(a) {
|
|
3632
4714
|
console.log(
|
|
3633
|
-
`${
|
|
4715
|
+
`${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
4716
|
);
|
|
3635
4717
|
}
|
|
3636
4718
|
function printAgentDetail(a) {
|
|
@@ -3641,13 +4723,13 @@ function printAgentDetail(a) {
|
|
|
3641
4723
|
}
|
|
3642
4724
|
function printSession(s) {
|
|
3643
4725
|
console.log(
|
|
3644
|
-
`${
|
|
4726
|
+
`${pc11.cyan(s.id)} ${s.status} sandbox: ${s.sandboxId ?? "\u2014"} ${formatLocalTime2(s.createdAt)}${s.error ? ` ${pc11.red(safeTerm(s.error))}` : ""}`
|
|
3645
4727
|
);
|
|
3646
4728
|
}
|
|
3647
4729
|
function printEvent(e) {
|
|
3648
4730
|
const payload = e.payload ?? {};
|
|
3649
4731
|
if (e.kind === "user") {
|
|
3650
|
-
console.log(`${
|
|
4732
|
+
console.log(`${pc11.green("you")} #${e.seq} ${safeTerm(String(payload.message ?? ""))}`);
|
|
3651
4733
|
return;
|
|
3652
4734
|
}
|
|
3653
4735
|
if (e.kind === "turn") {
|
|
@@ -3655,12 +4737,12 @@ function printEvent(e) {
|
|
|
3655
4737
|
for (const ev of events) {
|
|
3656
4738
|
const o = ev;
|
|
3657
4739
|
const text = o.text ?? o.message ?? o.content;
|
|
3658
|
-
if (typeof text === "string") console.log(
|
|
3659
|
-
else console.log(
|
|
4740
|
+
if (typeof text === "string") console.log(pc11.dim(`#${e.seq}`) + ` ${safeTerm(text)}`);
|
|
4741
|
+
else console.log(pc11.dim(`#${e.seq} ${safeTerm(JSON.stringify(o))}`));
|
|
3660
4742
|
}
|
|
3661
4743
|
return;
|
|
3662
4744
|
}
|
|
3663
|
-
console.log(
|
|
4745
|
+
console.log(pc11.dim(`#${e.seq} ${e.kind} ${safeTerm(JSON.stringify(payload))}`));
|
|
3664
4746
|
}
|
|
3665
4747
|
function authOpts(cmd) {
|
|
3666
4748
|
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 +4778,7 @@ function registerAgentsCommands(program2) {
|
|
|
3696
4778
|
).action(
|
|
3697
4779
|
async (name, opts) => {
|
|
3698
4780
|
try {
|
|
3699
|
-
const prompt = opts.prompt ?? (opts.promptFile ?
|
|
4781
|
+
const prompt = opts.prompt ?? (opts.promptFile ? readFileSync4(opts.promptFile, "utf8") : void 0);
|
|
3700
4782
|
if (!prompt?.trim()) fail(new Error("--prompt or --prompt-file is required"), opts);
|
|
3701
4783
|
const volume = opts.volumeDisk !== void 0 || opts.volumePath !== void 0 ? { diskId: opts.volumeDisk, path: opts.volumePath } : void 0;
|
|
3702
4784
|
const c = await client(opts);
|
|
@@ -3711,7 +4793,7 @@ function registerAgentsCommands(program2) {
|
|
|
3711
4793
|
});
|
|
3712
4794
|
output(opts, res, (r) => {
|
|
3713
4795
|
printAgentDetail(r.agent);
|
|
3714
|
-
console.error(
|
|
4796
|
+
console.error(pc11.dim(`agent ${r.agent.name} created \u2014 run it with \`compute agents run ${r.agent.name} "\u2026"\``));
|
|
3715
4797
|
});
|
|
3716
4798
|
} catch (e) {
|
|
3717
4799
|
fail(e, opts);
|
|
@@ -3734,7 +4816,7 @@ function registerAgentsCommands(program2) {
|
|
|
3734
4816
|
).action(
|
|
3735
4817
|
async (ref, opts) => {
|
|
3736
4818
|
try {
|
|
3737
|
-
const prompt = opts.prompt ?? (opts.promptFile ?
|
|
4819
|
+
const prompt = opts.prompt ?? (opts.promptFile ? readFileSync4(opts.promptFile, "utf8") : void 0);
|
|
3738
4820
|
const body = {
|
|
3739
4821
|
name: opts.name,
|
|
3740
4822
|
prompt,
|
|
@@ -3765,7 +4847,7 @@ function registerAgentsCommands(program2) {
|
|
|
3765
4847
|
const c = await client(opts);
|
|
3766
4848
|
if (!opts.yes) {
|
|
3767
4849
|
const res = await c.get(`/api/v1/agents/${encodeURIComponent(ref)}`);
|
|
3768
|
-
console.error(`Deleting agent ${
|
|
4850
|
+
console.error(`Deleting agent ${pc11.cyan(res.agent.name)} (${res.agent.id}). Pass -y to confirm.`);
|
|
3769
4851
|
process.exit(1);
|
|
3770
4852
|
}
|
|
3771
4853
|
await c.del(`/api/v1/agents/${encodeURIComponent(ref)}`);
|
|
@@ -3802,7 +4884,7 @@ function registerAgentsCommands(program2) {
|
|
|
3802
4884
|
output(opts, res, (r) => {
|
|
3803
4885
|
printSession(r.session);
|
|
3804
4886
|
for (const e of r.events) printEvent(e);
|
|
3805
|
-
console.error(
|
|
4887
|
+
console.error(pc11.dim(`session ${r.session.id} \u2014 continue with \`compute agents send ${r.session.id} "\u2026"\``));
|
|
3806
4888
|
});
|
|
3807
4889
|
} catch (e) {
|
|
3808
4890
|
fail(e, opts);
|
|
@@ -3888,11 +4970,625 @@ function registerAgentsCommands(program2) {
|
|
|
3888
4970
|
});
|
|
3889
4971
|
}
|
|
3890
4972
|
|
|
4973
|
+
// src/bench.ts
|
|
4974
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL3 } from "@computesdk/platform";
|
|
4975
|
+
|
|
4976
|
+
// src/net.ts
|
|
4977
|
+
function isFetchFailure(error) {
|
|
4978
|
+
return error instanceof TypeError && /fetch failed/i.test(error.message);
|
|
4979
|
+
}
|
|
4980
|
+
function describeFetchFailure(error, url) {
|
|
4981
|
+
let target = url;
|
|
4982
|
+
try {
|
|
4983
|
+
const parsed = new URL(url);
|
|
4984
|
+
target = `${parsed.origin}${parsed.pathname}`;
|
|
4985
|
+
} catch {
|
|
4986
|
+
}
|
|
4987
|
+
const cause = error.cause;
|
|
4988
|
+
const described = new TypeError(`fetch failed (${target})${cause instanceof Error ? `: ${cause.message}` : ""}`);
|
|
4989
|
+
described.cause = cause;
|
|
4990
|
+
return described;
|
|
4991
|
+
}
|
|
4992
|
+
function requestUrl(input) {
|
|
4993
|
+
if (typeof input === "string") return input;
|
|
4994
|
+
if (input instanceof URL) return input.href;
|
|
4995
|
+
return input.url;
|
|
4996
|
+
}
|
|
4997
|
+
function withFetchFailureContext(fetchImpl) {
|
|
4998
|
+
return async (input, init) => {
|
|
4999
|
+
try {
|
|
5000
|
+
return await fetchImpl(input, init);
|
|
5001
|
+
} catch (error) {
|
|
5002
|
+
if (isFetchFailure(error)) throw describeFetchFailure(error, requestUrl(input));
|
|
5003
|
+
throw error;
|
|
5004
|
+
}
|
|
5005
|
+
};
|
|
5006
|
+
}
|
|
5007
|
+
|
|
5008
|
+
// src/session.ts
|
|
5009
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL2, isSecurePlatformTransport as isSecurePlatformTransport2, isTrustedPlatformHost as isTrustedPlatformHost2 } from "@computesdk/platform";
|
|
5010
|
+
function envBaseUrl(env = process.env) {
|
|
5011
|
+
return env.COMPUTE_PLATFORM_URL || env.BENCHMARKS_PLATFORM_URL || void 0;
|
|
5012
|
+
}
|
|
5013
|
+
function assertComputeKeyDestination(baseUrl) {
|
|
5014
|
+
const url = baseUrl.replace(/\/+$/, "");
|
|
5015
|
+
if (!isTrustedPlatformHost2(url)) {
|
|
5016
|
+
throw new Error(
|
|
5017
|
+
`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.`
|
|
5018
|
+
);
|
|
5019
|
+
}
|
|
5020
|
+
if (!isSecurePlatformTransport2(url)) {
|
|
5021
|
+
throw new Error(`Refusing to send COMPUTE_API_KEY over plaintext HTTP to ${url}; use https://.`);
|
|
5022
|
+
}
|
|
5023
|
+
}
|
|
5024
|
+
function benchAuthOverrides(opts = {}, env = process.env) {
|
|
5025
|
+
const baseUrl = opts.baseUrl ?? envBaseUrl(env);
|
|
5026
|
+
const apiKey = env.COMPUTE_API_KEY || void 0;
|
|
5027
|
+
if (apiKey) assertComputeKeyDestination(baseUrl ?? DEFAULT_BASE_URL2);
|
|
5028
|
+
return { baseUrl, apiKey };
|
|
5029
|
+
}
|
|
5030
|
+
async function benchAuth(opts = {}) {
|
|
5031
|
+
const { resolveAuth } = await import("@benchsdk/cli");
|
|
5032
|
+
return resolveAuth(benchAuthOverrides(opts));
|
|
5033
|
+
}
|
|
5034
|
+
function errorReason(body) {
|
|
5035
|
+
if (typeof body !== "string" || body === "") return void 0;
|
|
5036
|
+
try {
|
|
5037
|
+
const parsed = JSON.parse(body);
|
|
5038
|
+
const reason = parsed.message ?? parsed.error;
|
|
5039
|
+
return typeof reason === "string" ? reason : void 0;
|
|
5040
|
+
} catch {
|
|
5041
|
+
return body.slice(0, 200);
|
|
5042
|
+
}
|
|
5043
|
+
}
|
|
5044
|
+
function httpStatus(error) {
|
|
5045
|
+
const status = error?.status;
|
|
5046
|
+
return typeof status === "number" ? status : void 0;
|
|
5047
|
+
}
|
|
5048
|
+
async function apiKeyOrganization(auth, apiKey) {
|
|
5049
|
+
const url = `${auth.apiBaseUrl}/actions/org`;
|
|
5050
|
+
let response;
|
|
5051
|
+
try {
|
|
5052
|
+
response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
|
|
5053
|
+
} catch (error) {
|
|
5054
|
+
throw isFetchFailure(error) ? describeFetchFailure(error, url) : error;
|
|
5055
|
+
}
|
|
5056
|
+
const text = await response.text();
|
|
5057
|
+
if (!response.ok) {
|
|
5058
|
+
const reason = errorReason(text);
|
|
5059
|
+
throw new Error(
|
|
5060
|
+
`This API key has no user identity, and its organization could not be read (${response.status}${reason ? `: ${reason}` : ""}).`
|
|
5061
|
+
);
|
|
5062
|
+
}
|
|
5063
|
+
const org2 = JSON.parse(text);
|
|
5064
|
+
return { id: org2.organizationId, name: org2.name, slug: org2.slug };
|
|
5065
|
+
}
|
|
5066
|
+
async function fetchWhoami(auth) {
|
|
5067
|
+
const { getMe } = await import("@benchsdk/cli");
|
|
5068
|
+
try {
|
|
5069
|
+
return await getMe(auth);
|
|
5070
|
+
} catch (error) {
|
|
5071
|
+
if (isFetchFailure(error)) throw describeFetchFailure(error, `${auth.apiBaseUrl}/me`);
|
|
5072
|
+
if (httpStatus(error) !== 401) throw error;
|
|
5073
|
+
const reason = errorReason(error.body);
|
|
5074
|
+
if (auth.apiKey && !auth.token && reason === "User credential required") {
|
|
5075
|
+
const org2 = await apiKeyOrganization(auth, auth.apiKey);
|
|
5076
|
+
return { user: null, activeOrganizationId: org2.id, organizations: [org2], credential: "api_key" };
|
|
5077
|
+
}
|
|
5078
|
+
throw new Error(
|
|
5079
|
+
`Authentication failed (401 Unauthorized)${reason ? `: ${reason}` : ""}. Check COMPUTE_API_KEY / the stored login, or run \`compute login\`.`
|
|
5080
|
+
);
|
|
5081
|
+
}
|
|
5082
|
+
}
|
|
5083
|
+
function formatWhoami(me) {
|
|
5084
|
+
const active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
5085
|
+
const who = me.user ? me.user.email ?? me.user.name ?? me.user.id : "API key (no user identity)";
|
|
5086
|
+
return [
|
|
5087
|
+
who,
|
|
5088
|
+
`active org: ${active ? `${active.slug} (${active.id})` : "\u2014"}${me.organizations.length > 1 ? " \u2014 change with `compute org use <slug>`" : ""}`
|
|
5089
|
+
];
|
|
5090
|
+
}
|
|
5091
|
+
|
|
5092
|
+
// src/bench.ts
|
|
5093
|
+
var BENCH_COMMANDS = /* @__PURE__ */ new Set(["bench", "benchmark"]);
|
|
5094
|
+
var RUNNER_VERBS = /* @__PURE__ */ new Set(["run", "check", "__manifest"]);
|
|
5095
|
+
function parseBenchDispatch(args) {
|
|
5096
|
+
let org2;
|
|
5097
|
+
let i = 0;
|
|
5098
|
+
while (i < args.length && !BENCH_COMMANDS.has(args[i])) {
|
|
5099
|
+
const arg = args[i];
|
|
5100
|
+
if (arg === "--org" && i + 1 < args.length) {
|
|
5101
|
+
org2 = args[i + 1];
|
|
5102
|
+
i += 2;
|
|
5103
|
+
} else if (arg.startsWith("--org=")) {
|
|
5104
|
+
org2 = arg.slice("--org=".length);
|
|
5105
|
+
i += 1;
|
|
5106
|
+
} else {
|
|
5107
|
+
return null;
|
|
5108
|
+
}
|
|
5109
|
+
}
|
|
5110
|
+
if (i >= args.length) return null;
|
|
5111
|
+
const argv = args.slice(i + 1);
|
|
5112
|
+
return org2 ? { argv, org: org2 } : { argv };
|
|
5113
|
+
}
|
|
5114
|
+
function baseUrlFlag(argv) {
|
|
5115
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
5116
|
+
const arg = argv[i];
|
|
5117
|
+
if (arg === "--") return void 0;
|
|
5118
|
+
if (arg === "--base-url") return argv[i + 1];
|
|
5119
|
+
if (arg.startsWith("--base-url=")) return arg.slice("--base-url=".length);
|
|
5120
|
+
}
|
|
5121
|
+
return void 0;
|
|
5122
|
+
}
|
|
5123
|
+
function hasOrgFlag(argv) {
|
|
5124
|
+
for (const arg of argv) {
|
|
5125
|
+
if (arg === "--") return false;
|
|
5126
|
+
if (arg === "--org" || arg.startsWith("--org=")) return true;
|
|
5127
|
+
}
|
|
5128
|
+
return false;
|
|
5129
|
+
}
|
|
5130
|
+
function benchInvocation(argv, env, computeOrg) {
|
|
5131
|
+
const out = {};
|
|
5132
|
+
if (env.COMPUTE_PLATFORM_URL && !env.BENCHMARKS_PLATFORM_URL) {
|
|
5133
|
+
out.BENCHMARKS_PLATFORM_URL = env.COMPUTE_PLATFORM_URL;
|
|
5134
|
+
}
|
|
5135
|
+
if (env.COMPUTE_API_KEY && !env.BENCHMARKS_PLATFORM_API_KEY) {
|
|
5136
|
+
assertComputeKeyDestination(
|
|
5137
|
+
baseUrlFlag(argv) || env.BENCHMARKS_PLATFORM_URL || env.COMPUTE_PLATFORM_URL || DEFAULT_BASE_URL3
|
|
5138
|
+
);
|
|
5139
|
+
out.BENCHMARKS_PLATFORM_API_KEY = env.COMPUTE_API_KEY;
|
|
5140
|
+
}
|
|
5141
|
+
const org2 = computeOrg || env.COMPUTE_ORG;
|
|
5142
|
+
if (!org2 || RUNNER_VERBS.has(argv[0]) || hasOrgFlag(argv)) return { argv, env: out };
|
|
5143
|
+
return { argv: ["--org", org2, ...argv], env: out };
|
|
5144
|
+
}
|
|
5145
|
+
async function runBench(dispatch) {
|
|
5146
|
+
const inv = benchInvocation(dispatch.argv, process.env, dispatch.org);
|
|
5147
|
+
Object.assign(process.env, inv.env);
|
|
5148
|
+
globalThis.fetch = withFetchFailureContext(globalThis.fetch);
|
|
5149
|
+
const { run } = await import("@benchsdk/runner");
|
|
5150
|
+
await run(inv.argv);
|
|
5151
|
+
}
|
|
5152
|
+
|
|
5153
|
+
// src/manifest.ts
|
|
5154
|
+
import { createRequire } from "module";
|
|
5155
|
+
import { existsSync as existsSync2, readFileSync as readFileSync5, realpathSync } from "fs";
|
|
5156
|
+
import { dirname as dirname2, join as join4, sep } from "path";
|
|
5157
|
+
var MANIFEST_COMMAND = "__manifest";
|
|
5158
|
+
function resolvedPackage(name, fromDir) {
|
|
5159
|
+
const require2 = createRequire(join4(fromDir, "noop.js"));
|
|
5160
|
+
let dir = dirname2(require2.resolve(name));
|
|
5161
|
+
for (; ; ) {
|
|
5162
|
+
const file = join4(dir, "package.json");
|
|
5163
|
+
if (existsSync2(file)) {
|
|
5164
|
+
const pkg = JSON.parse(readFileSync5(file, "utf-8"));
|
|
5165
|
+
if (pkg.name === name) return { dir, version: pkg.version };
|
|
5166
|
+
}
|
|
5167
|
+
const parent = dirname2(dir);
|
|
5168
|
+
if (parent === dir) throw new Error(`package.json for ${name} not found from ${fromDir}`);
|
|
5169
|
+
dir = parent;
|
|
5170
|
+
}
|
|
5171
|
+
}
|
|
5172
|
+
function isLinkedPackage(realDir) {
|
|
5173
|
+
return !realDir.split(sep).includes("node_modules");
|
|
5174
|
+
}
|
|
5175
|
+
function packageVersion(name, resolved) {
|
|
5176
|
+
const entry = { package: name, version: resolved.version };
|
|
5177
|
+
if (isLinkedPackage(realpathSync(resolved.dir))) {
|
|
5178
|
+
entry.linked = true;
|
|
5179
|
+
entry.released = false;
|
|
5180
|
+
}
|
|
5181
|
+
return entry;
|
|
5182
|
+
}
|
|
5183
|
+
function bundledBench(fromDir) {
|
|
5184
|
+
const runner = resolvedPackage("@benchsdk/runner", fromDir);
|
|
5185
|
+
const cli = resolvedPackage("@benchsdk/cli", runner.dir);
|
|
5186
|
+
return {
|
|
5187
|
+
runner: packageVersion("@benchsdk/runner", runner),
|
|
5188
|
+
cli: packageVersion("@benchsdk/cli", cli)
|
|
5189
|
+
};
|
|
5190
|
+
}
|
|
5191
|
+
function isHidden(cmd) {
|
|
5192
|
+
return cmd._hidden === true;
|
|
5193
|
+
}
|
|
5194
|
+
function flagsOf(cmd) {
|
|
5195
|
+
const flags = cmd.createHelp().visibleOptions(cmd).map((o) => o.long ?? o.short).filter((f) => Boolean(f));
|
|
5196
|
+
return [...new Set(flags)];
|
|
5197
|
+
}
|
|
5198
|
+
function argsOf(cmd) {
|
|
5199
|
+
return cmd.registeredArguments.map((a) => {
|
|
5200
|
+
const name = `${a.name()}${a.variadic ? "..." : ""}`;
|
|
5201
|
+
return a.required ? `<${name}>` : `[${name}]`;
|
|
5202
|
+
});
|
|
5203
|
+
}
|
|
5204
|
+
function summaryOf(cmd) {
|
|
5205
|
+
return (cmd.summary() || cmd.description()).split("\n")[0].trim();
|
|
5206
|
+
}
|
|
5207
|
+
function aliasPaths(names) {
|
|
5208
|
+
let paths = [[]];
|
|
5209
|
+
for (const choices of names) paths = paths.flatMap((p2) => choices.map((c) => [...p2, c]));
|
|
5210
|
+
return paths.slice(1);
|
|
5211
|
+
}
|
|
5212
|
+
function walk(cmd, ancestors, skip, out) {
|
|
5213
|
+
for (const sub of cmd.commands) {
|
|
5214
|
+
if (isHidden(sub) || ancestors.length === 0 && skip.has(sub.name())) continue;
|
|
5215
|
+
const names = [...ancestors, [sub.name(), ...sub.aliases()]];
|
|
5216
|
+
out.push({
|
|
5217
|
+
path: names.map((n) => n[0]),
|
|
5218
|
+
aliases: aliasPaths(names),
|
|
5219
|
+
args: argsOf(sub),
|
|
5220
|
+
flags: flagsOf(sub),
|
|
5221
|
+
summary: summaryOf(sub)
|
|
5222
|
+
});
|
|
5223
|
+
walk(sub, names, skip, out);
|
|
5224
|
+
}
|
|
5225
|
+
}
|
|
5226
|
+
function buildCliManifest(program2, options) {
|
|
5227
|
+
const [benchName, ...benchAliases] = [...BENCH_COMMANDS];
|
|
5228
|
+
const commands = [];
|
|
5229
|
+
walk(program2, [], /* @__PURE__ */ new Set([benchName]), commands);
|
|
5230
|
+
return {
|
|
5231
|
+
schemaVersion: 1,
|
|
5232
|
+
bin: "compute",
|
|
5233
|
+
package: "@computesdk/cli",
|
|
5234
|
+
version: options.version,
|
|
5235
|
+
source: { repo: "computesdk/computesdk", released: options.released },
|
|
5236
|
+
globalFlags: flagsOf(program2),
|
|
5237
|
+
commands,
|
|
5238
|
+
passthrough: {
|
|
5239
|
+
bench: {
|
|
5240
|
+
path: [benchName],
|
|
5241
|
+
aliases: benchAliases.map((a) => [a]),
|
|
5242
|
+
...bundledBench(options.packageDir)
|
|
5243
|
+
}
|
|
5244
|
+
}
|
|
5245
|
+
};
|
|
5246
|
+
}
|
|
5247
|
+
function manifestJson(manifest) {
|
|
5248
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
5249
|
+
`;
|
|
5250
|
+
}
|
|
5251
|
+
function manifestMatches(fileContent, generated) {
|
|
5252
|
+
let committed;
|
|
5253
|
+
try {
|
|
5254
|
+
committed = JSON.parse(fileContent);
|
|
5255
|
+
} catch {
|
|
5256
|
+
return false;
|
|
5257
|
+
}
|
|
5258
|
+
if (committed.source) delete committed.source.ref;
|
|
5259
|
+
return JSON.stringify(committed) === JSON.stringify(generated);
|
|
5260
|
+
}
|
|
5261
|
+
function registerManifestCommand(program2, options) {
|
|
5262
|
+
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) => {
|
|
5263
|
+
const manifest = buildCliManifest(program2, {
|
|
5264
|
+
version: options.version,
|
|
5265
|
+
released: Boolean(opts.released),
|
|
5266
|
+
packageDir: options.packageDir
|
|
5267
|
+
});
|
|
5268
|
+
if (opts.check) {
|
|
5269
|
+
if (!manifestMatches(readFileSync5(opts.check, "utf-8"), manifest)) {
|
|
5270
|
+
console.error(
|
|
5271
|
+
`${opts.check} is out of date. Regenerate it with \`pnpm --filter @computesdk/cli run manifest\`.`
|
|
5272
|
+
);
|
|
5273
|
+
process.exit(1);
|
|
5274
|
+
}
|
|
5275
|
+
console.log(`${opts.check} matches the ${manifest.commands.length}-command manifest.`);
|
|
5276
|
+
return;
|
|
5277
|
+
}
|
|
5278
|
+
process.stdout.write(manifestJson(manifest));
|
|
5279
|
+
});
|
|
5280
|
+
}
|
|
5281
|
+
|
|
5282
|
+
// src/org-members.ts
|
|
5283
|
+
import pc12 from "picocolors";
|
|
5284
|
+
var ORG_PATH = "/api/v1/organizations/current";
|
|
5285
|
+
var MEMBER_ROLES = ["member", "admin"];
|
|
5286
|
+
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.";
|
|
5287
|
+
function isOrgApiKey(key) {
|
|
5288
|
+
return /^(bp|csdk)_/.test(key);
|
|
5289
|
+
}
|
|
5290
|
+
var segment = (id) => encodeURIComponent(id);
|
|
5291
|
+
function orgName(opts) {
|
|
5292
|
+
return opts.org || process.env.COMPUTE_ORG || void 0;
|
|
5293
|
+
}
|
|
5294
|
+
async function orgClient(opts) {
|
|
5295
|
+
return new ActionsClient(await resolveActionsAuth(opts));
|
|
5296
|
+
}
|
|
5297
|
+
async function userClient(opts, what) {
|
|
5298
|
+
const auth = await resolveActionsAuth(opts);
|
|
5299
|
+
if (isOrgApiKey(auth.apiKey)) {
|
|
5300
|
+
throw new PlatformClientError(
|
|
5301
|
+
"user_credential_required",
|
|
5302
|
+
`${what} needs a user login, and org API keys have no user. Run \`compute login\`, and drop --api-key / unset COMPUTE_API_KEY.`
|
|
5303
|
+
);
|
|
5304
|
+
}
|
|
5305
|
+
return new ActionsClient(auth);
|
|
5306
|
+
}
|
|
5307
|
+
function apiHint(error) {
|
|
5308
|
+
const body = error.body;
|
|
5309
|
+
if (body && typeof body === "object" && typeof body.hint === "string") {
|
|
5310
|
+
return body.hint;
|
|
5311
|
+
}
|
|
5312
|
+
return error.code === "user_credential_required" ? USER_LOGIN_HINT : void 0;
|
|
5313
|
+
}
|
|
5314
|
+
function fail2(error, opts = {}) {
|
|
5315
|
+
const hint = error instanceof PlatformApiError ? apiHint(error) : void 0;
|
|
5316
|
+
if (opts.json) {
|
|
5317
|
+
const envelope = toErrorEnvelope(error);
|
|
5318
|
+
if (hint) envelope.error.hint = hint;
|
|
5319
|
+
process.stderr.write(JSON.stringify(envelope) + "\n");
|
|
5320
|
+
} else if (error instanceof PlatformApiError) {
|
|
5321
|
+
const code = error.code !== codeForStatus(error.status) ? ` ${error.code}` : "";
|
|
5322
|
+
console.error(pc12.red(`Error (${error.status}${code}): ${error.message}`));
|
|
5323
|
+
if (hint) console.error(pc12.dim(`hint: ${hint}`));
|
|
5324
|
+
} else {
|
|
5325
|
+
console.error(pc12.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
|
|
5326
|
+
}
|
|
5327
|
+
process.exit(1);
|
|
5328
|
+
}
|
|
5329
|
+
function memberRole(role, ownerMessage) {
|
|
5330
|
+
if (role === "owner") throw new PlatformClientError("invalid_argument", ownerMessage);
|
|
5331
|
+
if (!MEMBER_ROLES.includes(role)) {
|
|
5332
|
+
throw new PlatformClientError("invalid_argument", `Invalid role "${role}" \u2014 use member or admin.`);
|
|
5333
|
+
}
|
|
5334
|
+
return role;
|
|
5335
|
+
}
|
|
5336
|
+
function printTable2(header, rows) {
|
|
5337
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
5338
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
|
|
5339
|
+
console.log(line(header));
|
|
5340
|
+
for (const row of rows) console.log(line(row));
|
|
5341
|
+
}
|
|
5342
|
+
function printMembers(res) {
|
|
5343
|
+
if (res.members.length === 0) {
|
|
5344
|
+
console.log("No members.");
|
|
5345
|
+
return;
|
|
5346
|
+
}
|
|
5347
|
+
printTable2(
|
|
5348
|
+
["EMAIL", "ROLE", "NAME", "MEMBER ID", "JOINED"],
|
|
5349
|
+
res.members.map((m) => [safeTerm(m.email), safeTerm(m.role), safeTerm(m.name ?? "\u2014"), safeTerm(m.id), safeTerm(m.createdAt)])
|
|
5350
|
+
);
|
|
5351
|
+
}
|
|
5352
|
+
function printOrgInvitations(res) {
|
|
5353
|
+
if (res.invitations.length === 0) {
|
|
5354
|
+
console.log("No pending invitations.");
|
|
5355
|
+
return;
|
|
5356
|
+
}
|
|
5357
|
+
printTable2(
|
|
5358
|
+
["ID", "EMAIL", "ROLE", "EXPIRES", "LINK"],
|
|
5359
|
+
res.invitations.map((i) => [safeTerm(i.id), safeTerm(i.email), safeTerm(i.role), safeTerm(i.expiresAt), safeTerm(i.url)])
|
|
5360
|
+
);
|
|
5361
|
+
}
|
|
5362
|
+
function printUserInvitations(res) {
|
|
5363
|
+
if (res.invitations.length === 0) {
|
|
5364
|
+
console.log("No pending invitations.");
|
|
5365
|
+
return;
|
|
5366
|
+
}
|
|
5367
|
+
printTable2(
|
|
5368
|
+
["ID", "ORG", "ROLE", "EXPIRES", "ORG NAME"],
|
|
5369
|
+
res.invitations.map((i) => [
|
|
5370
|
+
safeTerm(i.id),
|
|
5371
|
+
safeTerm(i.organization.slug),
|
|
5372
|
+
safeTerm(i.role),
|
|
5373
|
+
safeTerm(i.expiresAt),
|
|
5374
|
+
safeTerm(i.organization.name)
|
|
5375
|
+
])
|
|
5376
|
+
);
|
|
5377
|
+
console.log(pc12.dim("Accept with `compute invitations accept <id>`; decline with `compute invitations decline <id> -y`."));
|
|
5378
|
+
}
|
|
5379
|
+
function printInvitationDetail(inv) {
|
|
5380
|
+
const rows = [
|
|
5381
|
+
["invitation", safeTerm(inv.id)],
|
|
5382
|
+
["org", `${safeTerm(inv.organization.slug)} (${safeTerm(inv.organization.name)})`],
|
|
5383
|
+
["email", safeTerm(inv.email)],
|
|
5384
|
+
["role", safeTerm(inv.role)],
|
|
5385
|
+
["status", safeTerm(inv.status)],
|
|
5386
|
+
["expires", safeTerm(inv.expiresAt)],
|
|
5387
|
+
["link", safeTerm(inv.url)]
|
|
5388
|
+
];
|
|
5389
|
+
for (const [k, v] of rows) console.log(`${k.padEnd(10)} ${v}`);
|
|
5390
|
+
}
|
|
5391
|
+
function printInvite(res) {
|
|
5392
|
+
const inv = res.invitation;
|
|
5393
|
+
console.log(`Invited ${safeTerm(inv.email)} as ${safeTerm(inv.role)} (invitation ${safeTerm(inv.id)}, expires ${safeTerm(inv.expiresAt)}).`);
|
|
5394
|
+
if (res.emailSent) {
|
|
5395
|
+
console.log(`Emailed ${safeTerm(inv.email)} the invitation link.`);
|
|
5396
|
+
} else {
|
|
5397
|
+
const reason = res.emailError ? ` (${safeTerm(res.emailError)})` : "";
|
|
5398
|
+
console.log(pc12.yellow(`The invitation email was not sent${reason}; share the link instead.`));
|
|
5399
|
+
}
|
|
5400
|
+
console.log(`Link: ${safeTerm(inv.url)}`);
|
|
5401
|
+
}
|
|
5402
|
+
function findMember(members, ref) {
|
|
5403
|
+
const lower = ref.toLowerCase();
|
|
5404
|
+
return members.find((m) => m.id === ref) ?? members.find((m) => m.userId === ref) ?? members.find((m) => m.email.toLowerCase() === lower);
|
|
5405
|
+
}
|
|
5406
|
+
async function resolveMember(c, ref, opts) {
|
|
5407
|
+
const { members } = await c.get(`${ORG_PATH}/members`);
|
|
5408
|
+
const member = findMember(members, ref);
|
|
5409
|
+
if (!member) {
|
|
5410
|
+
const org2 = orgName(opts);
|
|
5411
|
+
throw new PlatformClientError("not_found", `No member ${ref} in ${org2 ? `org ${org2}` : "this organization"}.`);
|
|
5412
|
+
}
|
|
5413
|
+
return member;
|
|
5414
|
+
}
|
|
5415
|
+
var EMAIL = /^[^\s@]+@[^\s@]+$/;
|
|
5416
|
+
function command(parent, name) {
|
|
5417
|
+
return parent.command(name).configureOutput({ outputError: usageErrorOutput });
|
|
5418
|
+
}
|
|
5419
|
+
function common(cmd) {
|
|
5420
|
+
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");
|
|
5421
|
+
}
|
|
5422
|
+
function registerOrgMemberCommands(org2) {
|
|
5423
|
+
common(
|
|
5424
|
+
command(org2, "members").description("List the organization's members with their roles")
|
|
5425
|
+
).action(async (opts) => {
|
|
5426
|
+
try {
|
|
5427
|
+
const c = await orgClient(opts);
|
|
5428
|
+
output(opts, await c.get(`${ORG_PATH}/members`), printMembers);
|
|
5429
|
+
} catch (e) {
|
|
5430
|
+
fail2(e, opts);
|
|
5431
|
+
}
|
|
5432
|
+
});
|
|
5433
|
+
const invitations = common(
|
|
5434
|
+
command(org2, "invitations").description("List the organization's pending invitations with their links (owner/admin)").allowExcessArguments(false)
|
|
5435
|
+
).action(async (opts) => {
|
|
5436
|
+
try {
|
|
5437
|
+
const c = await orgClient(opts);
|
|
5438
|
+
output(opts, await c.get(`${ORG_PATH}/invitations`), printOrgInvitations);
|
|
5439
|
+
} catch (e) {
|
|
5440
|
+
fail2(e, opts);
|
|
5441
|
+
}
|
|
5442
|
+
});
|
|
5443
|
+
common(
|
|
5444
|
+
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")
|
|
5445
|
+
).action(async (invitationId, opts) => {
|
|
5446
|
+
try {
|
|
5447
|
+
await confirmWrite(`Cancel invitation ${invitationId}? Its link stops working.`, opts);
|
|
5448
|
+
const c = await orgClient(opts);
|
|
5449
|
+
const res = await c.del(`${ORG_PATH}/invitations/${segment(invitationId)}`);
|
|
5450
|
+
output(
|
|
5451
|
+
opts,
|
|
5452
|
+
res,
|
|
5453
|
+
(r) => console.log(`Cancelled the invitation for ${safeTerm(r.invitation.email)} (${r.invitation.id}).`)
|
|
5454
|
+
);
|
|
5455
|
+
} catch (e) {
|
|
5456
|
+
fail2(e, opts);
|
|
5457
|
+
}
|
|
5458
|
+
});
|
|
5459
|
+
common(
|
|
5460
|
+
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")
|
|
5461
|
+
).action(async (email, opts) => {
|
|
5462
|
+
try {
|
|
5463
|
+
const role = memberRole(opts.role, "Owner invitations require the web app.");
|
|
5464
|
+
if (!EMAIL.test(email)) {
|
|
5465
|
+
throw new PlatformClientError("invalid_argument", `Invalid email "${email}".`);
|
|
5466
|
+
}
|
|
5467
|
+
const target = orgName(opts);
|
|
5468
|
+
await confirmWrite(`Invite ${email} as ${role}${target ? ` to ${target}` : ""}?`, opts);
|
|
5469
|
+
const c = await orgClient(opts);
|
|
5470
|
+
output(opts, await c.post(`${ORG_PATH}/invitations`, { email, role }), printInvite);
|
|
5471
|
+
} catch (e) {
|
|
5472
|
+
fail2(e, opts);
|
|
5473
|
+
}
|
|
5474
|
+
});
|
|
5475
|
+
const member = command(org2, "member").description("Change a member's role or remove a member (owner/admin)");
|
|
5476
|
+
common(
|
|
5477
|
+
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")
|
|
5478
|
+
).action(async (ref, roleArg, opts) => {
|
|
5479
|
+
try {
|
|
5480
|
+
const role = memberRole(roleArg, "Owner role changes require the web app.");
|
|
5481
|
+
const c = await orgClient(opts);
|
|
5482
|
+
const target = await resolveMember(c, ref, opts);
|
|
5483
|
+
await confirmWrite(`Change ${target.email} from ${target.role} to ${role}?`, opts);
|
|
5484
|
+
const res = await c.patch(`${ORG_PATH}/members/${segment(target.id)}`, { role });
|
|
5485
|
+
output(opts, res, (r) => console.log(`${safeTerm(r.member.email)} is now ${safeTerm(r.member.role)}.`));
|
|
5486
|
+
} catch (e) {
|
|
5487
|
+
fail2(e, opts);
|
|
5488
|
+
}
|
|
5489
|
+
});
|
|
5490
|
+
common(
|
|
5491
|
+
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")
|
|
5492
|
+
).action(async (ref, opts) => {
|
|
5493
|
+
try {
|
|
5494
|
+
const c = await orgClient(opts);
|
|
5495
|
+
const target = await resolveMember(c, ref, opts);
|
|
5496
|
+
const org3 = orgName(opts);
|
|
5497
|
+
await confirmWrite(
|
|
5498
|
+
`Remove ${target.email} (${target.role}) from ${org3 ?? "the organization"}? They lose access at once.`,
|
|
5499
|
+
opts
|
|
5500
|
+
);
|
|
5501
|
+
const res = await c.del(`${ORG_PATH}/members/${segment(target.id)}`);
|
|
5502
|
+
output(
|
|
5503
|
+
opts,
|
|
5504
|
+
res,
|
|
5505
|
+
(r) => console.log(`Removed ${safeTerm(r.removed.email)} (${safeTerm(r.removed.role)}) from ${org3 ?? "the organization"}.`)
|
|
5506
|
+
);
|
|
5507
|
+
} catch (e) {
|
|
5508
|
+
fail2(e, opts);
|
|
5509
|
+
}
|
|
5510
|
+
});
|
|
5511
|
+
common(
|
|
5512
|
+
command(org2, "leave").description("Leave the organization (needs a user login; the last owner cannot leave)").option("-y, --yes", "skip the confirmation")
|
|
5513
|
+
).action(async (opts) => {
|
|
5514
|
+
try {
|
|
5515
|
+
const c = await userClient(opts, "`compute org leave`");
|
|
5516
|
+
const org3 = orgName(opts);
|
|
5517
|
+
await confirmWrite(`Leave ${org3 ?? "the active organization"}? You lose access to it at once.`, opts);
|
|
5518
|
+
const res = await c.post(`${ORG_PATH}/leave`, {});
|
|
5519
|
+
output(opts, res, () => {
|
|
5520
|
+
console.log(`Left ${org3 ?? "the organization"}.`);
|
|
5521
|
+
console.log(
|
|
5522
|
+
pc12.dim("If your login was granted for that organization, it no longer works: run `compute login` again.")
|
|
5523
|
+
);
|
|
5524
|
+
});
|
|
5525
|
+
} catch (e) {
|
|
5526
|
+
fail2(e, opts);
|
|
5527
|
+
}
|
|
5528
|
+
});
|
|
5529
|
+
}
|
|
5530
|
+
function registerInvitationsCommands(program2) {
|
|
5531
|
+
const invitations = common(
|
|
5532
|
+
command(program2, "invitations").description("Your pending invitations to other organizations (needs a user login)").allowExcessArguments(false)
|
|
5533
|
+
).action(async (opts) => {
|
|
5534
|
+
try {
|
|
5535
|
+
const c = await userClient(opts, "`compute invitations`");
|
|
5536
|
+
output(opts, await c.get("/api/v1/me/invitations"), printUserInvitations);
|
|
5537
|
+
} catch (e) {
|
|
5538
|
+
fail2(e, opts);
|
|
5539
|
+
}
|
|
5540
|
+
});
|
|
5541
|
+
common(
|
|
5542
|
+
command(invitations, "show").description("Show one of your invitations").argument("<invitationId>", "invitation id (see `compute invitations`)")
|
|
5543
|
+
).action(async (invitationId, opts) => {
|
|
5544
|
+
try {
|
|
5545
|
+
const c = await userClient(opts, "`compute invitations show`");
|
|
5546
|
+
const res = await c.get(`/api/v1/invitations/${segment(invitationId)}`);
|
|
5547
|
+
output(opts, res, (r) => printInvitationDetail(r.invitation));
|
|
5548
|
+
} catch (e) {
|
|
5549
|
+
fail2(e, opts);
|
|
5550
|
+
}
|
|
5551
|
+
});
|
|
5552
|
+
common(
|
|
5553
|
+
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")
|
|
5554
|
+
).action(async (invitationId, opts) => {
|
|
5555
|
+
try {
|
|
5556
|
+
const c = await userClient(opts, "`compute invitations accept`");
|
|
5557
|
+
const res = await c.post(`/api/v1/invitations/${segment(invitationId)}/accept`, {});
|
|
5558
|
+
output(opts, res, (r) => {
|
|
5559
|
+
const slug = safeTerm(r.organization.slug);
|
|
5560
|
+
console.log(`Joined ${slug} as ${safeTerm(r.member.role)}.`);
|
|
5561
|
+
console.log(pc12.dim(`Switch to it with \`compute org use ${slug}\`, or pass --org ${slug}.`));
|
|
5562
|
+
});
|
|
5563
|
+
} catch (e) {
|
|
5564
|
+
fail2(e, opts);
|
|
5565
|
+
}
|
|
5566
|
+
});
|
|
5567
|
+
common(
|
|
5568
|
+
command(invitations, "decline").description("Decline an invitation").argument("<invitationId>", "invitation id (see `compute invitations`)").option("-y, --yes", "skip the confirmation")
|
|
5569
|
+
).action(async (invitationId, opts) => {
|
|
5570
|
+
try {
|
|
5571
|
+
const c = await userClient(opts, "`compute invitations decline`");
|
|
5572
|
+
await confirmWrite(`Decline invitation ${invitationId}? Its link stops working.`, opts);
|
|
5573
|
+
const res = await c.post(
|
|
5574
|
+
`/api/v1/invitations/${segment(invitationId)}/decline`,
|
|
5575
|
+
{}
|
|
5576
|
+
);
|
|
5577
|
+
output(opts, res, (r) => {
|
|
5578
|
+
const org2 = r.invitation.organization?.slug;
|
|
5579
|
+
console.log(org2 ? `Declined the invitation to ${safeTerm(org2)}.` : `Declined invitation ${r.invitation.id}.`);
|
|
5580
|
+
});
|
|
5581
|
+
} catch (e) {
|
|
5582
|
+
fail2(e, opts);
|
|
5583
|
+
}
|
|
5584
|
+
});
|
|
5585
|
+
}
|
|
5586
|
+
|
|
3891
5587
|
// src/index.ts
|
|
3892
5588
|
var __filename2 = fileURLToPath(import.meta.url);
|
|
3893
|
-
var __dirname2 =
|
|
5589
|
+
var __dirname2 = dirname3(__filename2);
|
|
3894
5590
|
var packageJson = JSON.parse(
|
|
3895
|
-
|
|
5591
|
+
readFileSync6(join5(__dirname2, "..", "package.json"), "utf-8")
|
|
3896
5592
|
);
|
|
3897
5593
|
var isDevBuild = import.meta.url.includes("worktrees") || import.meta.url.includes("/packages/cli/");
|
|
3898
5594
|
var VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;
|
|
@@ -3904,19 +5600,12 @@ process.stderr.on("error", (err) => {
|
|
|
3904
5600
|
if (err.code === "EPIPE") return;
|
|
3905
5601
|
throw err;
|
|
3906
5602
|
});
|
|
3907
|
-
var program = new
|
|
5603
|
+
var program = new Command4();
|
|
3908
5604
|
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
5605
|
async function printSessionLine(options) {
|
|
3917
5606
|
try {
|
|
3918
|
-
const { getMe } = await import("@benchsdk/cli");
|
|
3919
|
-
const me = await getMe(await
|
|
5607
|
+
const { getMe, resolveAuth } = await import("@benchsdk/cli");
|
|
5608
|
+
const me = await getMe(await resolveAuth({ baseUrl: options?.baseUrl ?? envBaseUrl() }));
|
|
3920
5609
|
const active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
3921
5610
|
const who = me.user.email ?? me.user.name ?? me.user.id;
|
|
3922
5611
|
if (active) {
|
|
@@ -3943,18 +5632,18 @@ async function runLogout() {
|
|
|
3943
5632
|
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
5633
|
if (opts.logout) {
|
|
3945
5634
|
console.log();
|
|
3946
|
-
p.intro(
|
|
5635
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3947
5636
|
await runLogout();
|
|
3948
5637
|
p.log.success("Logged out. Stored credentials removed.");
|
|
3949
|
-
p.outro(
|
|
5638
|
+
p.outro(pc13.green("Done!"));
|
|
3950
5639
|
process.exit(0);
|
|
3951
5640
|
}
|
|
3952
5641
|
if (opts.login) {
|
|
3953
5642
|
console.log();
|
|
3954
|
-
p.intro(
|
|
5643
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3955
5644
|
await runLogin();
|
|
3956
5645
|
await printSessionLine();
|
|
3957
|
-
p.outro(
|
|
5646
|
+
p.outro(pc13.green("Authenticated!"));
|
|
3958
5647
|
process.exit(0);
|
|
3959
5648
|
}
|
|
3960
5649
|
program.help();
|
|
@@ -3965,23 +5654,23 @@ program.hook("preAction", (thisCommand) => {
|
|
|
3965
5654
|
});
|
|
3966
5655
|
program.command("providers").description("List all providers and their configuration status").action(async () => {
|
|
3967
5656
|
console.log();
|
|
3968
|
-
p.intro(
|
|
5657
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3969
5658
|
const statuses = getProviderStatus();
|
|
3970
5659
|
console.log();
|
|
3971
5660
|
for (const status of statuses) {
|
|
3972
|
-
const icon = status.ready ?
|
|
3973
|
-
const name = status.ready ?
|
|
3974
|
-
const detail = status.ready ?
|
|
5661
|
+
const icon = status.ready ? pc13.green("\u25CF") : pc13.gray("\u25CB");
|
|
5662
|
+
const name = status.ready ? pc13.white(status.name) : pc13.gray(status.name);
|
|
5663
|
+
const detail = status.ready ? pc13.green("ready") : pc13.gray(`missing: ${status.missing.join(", ")}`);
|
|
3975
5664
|
console.log(` ${icon} ${name} ${detail}`);
|
|
3976
5665
|
}
|
|
3977
5666
|
console.log();
|
|
3978
5667
|
});
|
|
3979
5668
|
program.command("login").description("Authenticate with ComputeSDK (OAuth device flow)").option("--base-url <url>", "platform URL to authenticate against").action(async (opts) => {
|
|
3980
5669
|
console.log();
|
|
3981
|
-
p.intro(
|
|
5670
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3982
5671
|
await runLogin({ baseUrl: opts.baseUrl });
|
|
3983
5672
|
await printSessionLine({ baseUrl: opts.baseUrl });
|
|
3984
|
-
p.outro(
|
|
5673
|
+
p.outro(pc13.green("Authenticated!"));
|
|
3985
5674
|
});
|
|
3986
5675
|
program.command("logout").description("Clear stored credentials").option("--json", "print machine-readable JSON").action(async (opts) => {
|
|
3987
5676
|
await runLogout();
|
|
@@ -3990,24 +5679,19 @@ program.command("logout").description("Clear stored credentials").option("--json
|
|
|
3990
5679
|
return;
|
|
3991
5680
|
}
|
|
3992
5681
|
console.log();
|
|
3993
|
-
p.intro(
|
|
5682
|
+
p.intro(pc13.cyan(`@computesdk/cli v${VERSION}`));
|
|
3994
5683
|
p.log.success("Logged out. Stored credentials removed.");
|
|
3995
|
-
p.outro(
|
|
5684
|
+
p.outro(pc13.green("Done!"));
|
|
3996
5685
|
});
|
|
3997
5686
|
async function printWhoami(options = {}) {
|
|
3998
|
-
const
|
|
3999
|
-
const me = await getMe(await benchAuth({ baseUrl: options.baseUrl }));
|
|
5687
|
+
const me = await fetchWhoami(await benchAuth({ baseUrl: options.baseUrl }));
|
|
4000
5688
|
if (options.json) {
|
|
4001
5689
|
console.log(JSON.stringify(me, null, 2));
|
|
4002
5690
|
return;
|
|
4003
5691
|
}
|
|
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
|
-
);
|
|
5692
|
+
for (const line of formatWhoami(me)) console.log(line);
|
|
4009
5693
|
}
|
|
4010
|
-
var org = program.command("org").description("Manage the active organization");
|
|
5694
|
+
var org = program.command("org").description("Manage the active organization, its members and invitations");
|
|
4011
5695
|
org.command("list").description("List your organizations").option("--json", "print machine-readable JSON").action(async (opts) => {
|
|
4012
5696
|
const { listOrganizations, getMe } = await import("@benchsdk/cli");
|
|
4013
5697
|
const auth = await benchAuth();
|
|
@@ -4017,8 +5701,8 @@ org.command("list").description("List your organizations").option("--json", "pri
|
|
|
4017
5701
|
return;
|
|
4018
5702
|
}
|
|
4019
5703
|
for (const o of organizations) {
|
|
4020
|
-
const marker = o.id === me.activeOrganizationId ?
|
|
4021
|
-
console.log(`${marker} ${
|
|
5704
|
+
const marker = o.id === me.activeOrganizationId ? pc13.green("*") : " ";
|
|
5705
|
+
console.log(`${marker} ${pc13.cyan(o.slug)} ${o.name ?? ""} ${pc13.dim(o.id)}`);
|
|
4022
5706
|
}
|
|
4023
5707
|
});
|
|
4024
5708
|
org.command("use <slug>").description("Set the active organization (persisted to the stored login)").action(async (slug) => {
|
|
@@ -4048,23 +5732,30 @@ org.command("use <slug>").description("Set the active organization (persisted to
|
|
|
4048
5732
|
console.log(`Active organization set to ${result.organization.slug} (${result.organization.id})`);
|
|
4049
5733
|
});
|
|
4050
5734
|
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));
|
|
5735
|
+
registerOrgMemberCommands(org);
|
|
4051
5736
|
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));
|
|
5737
|
+
registerInvitationsCommands(program);
|
|
4052
5738
|
registerActionsCommands(program);
|
|
5739
|
+
registerByokCommands(program);
|
|
4053
5740
|
registerMarketCommands(program);
|
|
4054
5741
|
registerSandboxesCommands(program);
|
|
4055
5742
|
registerAgentsCommands(program);
|
|
4056
|
-
program.command("bench").description("Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, artifacts, export, ...)").allowUnknownOption().helpOption(false).action(() => {
|
|
5743
|
+
program.command("bench").description("Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, fork, artifacts, export, ...)").allowUnknownOption().helpOption(false).action(() => {
|
|
5744
|
+
});
|
|
5745
|
+
registerManifestCommand(program, {
|
|
5746
|
+
version: packageJson.version,
|
|
5747
|
+
packageDir: join5(__dirname2, "..")
|
|
4057
5748
|
});
|
|
4058
5749
|
async function main() {
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
await
|
|
5750
|
+
const bench = parseBenchDispatch(process.argv.slice(2));
|
|
5751
|
+
if (bench) {
|
|
5752
|
+
await runBench(bench);
|
|
4062
5753
|
return;
|
|
4063
5754
|
}
|
|
4064
5755
|
await program.parseAsync(process.argv);
|
|
4065
5756
|
}
|
|
4066
5757
|
main().catch((error) => {
|
|
4067
|
-
console.error(
|
|
5758
|
+
console.error(pc13.red(`
|
|
4068
5759
|
Error: ${error.message}`));
|
|
4069
5760
|
process.exit(1);
|
|
4070
5761
|
});
|