@computesdk/cli 2.6.12 → 2.6.14
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 +183 -6
- package/checkpoint-provenance.json +6 -0
- package/checkpoint-runner.cjs +14 -0
- package/checkpoint.cjs +1949 -0
- package/cli-manifest.json +362 -5
- package/dist/index.js +1795 -558
- package/dist/index.js.map +1 -1
- package/package.json +9 -5
package/dist/index.js
CHANGED
|
@@ -1,78 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
|
+
};
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
2
11
|
|
|
3
|
-
//
|
|
4
|
-
import "
|
|
5
|
-
import { Command as Command4 } from "commander";
|
|
6
|
-
import * as p from "@clack/prompts";
|
|
7
|
-
import pc14 from "picocolors";
|
|
8
|
-
import { readFileSync as readFileSync6 } from "fs";
|
|
12
|
+
// ../../node_modules/.pnpm/tsup@8.5.0_jiti@2.7.0_postcss@8.5.6_tsx@4.20.3_typescript@5.8.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js
|
|
13
|
+
import path from "path";
|
|
9
14
|
import { fileURLToPath } from "url";
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
var PROVIDER_ENV = {
|
|
14
|
-
e2b: { authOptions: [["E2B_API_KEY"]], configKeys: { E2B_API_KEY: "apiKey" } },
|
|
15
|
-
railway: { authOptions: [["RAILWAY_API_TOKEN"]], configKeys: { RAILWAY_API_TOKEN: "token" } },
|
|
16
|
-
modal: {
|
|
17
|
-
authOptions: [["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"]],
|
|
18
|
-
configKeys: { MODAL_TOKEN_ID: "tokenId", MODAL_TOKEN_SECRET: "tokenSecret" }
|
|
19
|
-
},
|
|
20
|
-
vercel: {
|
|
21
|
-
authOptions: [["VERCEL_TOKEN", "VERCEL_TEAM_ID", "VERCEL_PROJECT_ID"], ["VERCEL_OIDC_TOKEN"]],
|
|
22
|
-
configKeys: {
|
|
23
|
-
VERCEL_TOKEN: "token",
|
|
24
|
-
VERCEL_TEAM_ID: "teamId",
|
|
25
|
-
VERCEL_PROJECT_ID: "projectId"
|
|
26
|
-
}
|
|
27
|
-
},
|
|
28
|
-
daytona: { authOptions: [["DAYTONA_API_KEY"]], configKeys: { DAYTONA_API_KEY: "apiKey" } },
|
|
29
|
-
namespace: {
|
|
30
|
-
authOptions: [["NSC_TOKEN"], ["NSC_TOKEN_FILE"]],
|
|
31
|
-
configKeys: { NSC_TOKEN: "token", NSC_TOKEN_FILE: "tokenFile" }
|
|
32
|
-
},
|
|
33
|
-
blaxel: {
|
|
34
|
-
authOptions: [["BL_API_KEY", "BL_WORKSPACE"]],
|
|
35
|
-
configKeys: { BL_API_KEY: "apiKey", BL_WORKSPACE: "workspace" }
|
|
36
|
-
},
|
|
37
|
-
codesandbox: { authOptions: [["CSB_API_KEY"]], configKeys: { CSB_API_KEY: "apiKey" } },
|
|
38
|
-
render: { authOptions: [["RENDER_API_KEY"]], configKeys: { RENDER_API_KEY: "apiKey" } }
|
|
39
|
-
};
|
|
40
|
-
var PROVIDER_NAMES = Object.keys(PROVIDER_ENV);
|
|
41
|
-
function missingEnvVars(provider) {
|
|
42
|
-
const spec = PROVIDER_ENV[provider];
|
|
43
|
-
if (!spec) return [];
|
|
44
|
-
let best = null;
|
|
45
|
-
for (const option of spec.authOptions) {
|
|
46
|
-
const missing = option.filter((name) => !process.env[name]);
|
|
47
|
-
if (missing.length === 0) return [];
|
|
48
|
-
if (!best || missing.length < best.length) best = missing;
|
|
49
|
-
}
|
|
50
|
-
return best ?? [];
|
|
51
|
-
}
|
|
52
|
-
function isProviderAuthComplete(provider) {
|
|
53
|
-
return missingEnvVars(provider).length === 0;
|
|
54
|
-
}
|
|
55
|
-
function getProviderStatus() {
|
|
56
|
-
const statuses = [];
|
|
57
|
-
for (const provider of PROVIDER_NAMES) {
|
|
58
|
-
statuses.push({
|
|
59
|
-
name: provider,
|
|
60
|
-
ready: isProviderAuthComplete(provider),
|
|
61
|
-
missing: missingEnvVars(provider)
|
|
62
|
-
});
|
|
15
|
+
var init_esm_shims = __esm({
|
|
16
|
+
"../../node_modules/.pnpm/tsup@8.5.0_jiti@2.7.0_postcss@8.5.6_tsx@4.20.3_typescript@5.8.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js"() {
|
|
17
|
+
"use strict";
|
|
63
18
|
}
|
|
64
|
-
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// src/actions.ts
|
|
68
|
-
import { Option as Option2 } from "commander";
|
|
69
|
-
import pc7 from "picocolors";
|
|
70
|
-
import { mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
71
|
-
import { spawnSync } from "child_process";
|
|
72
|
-
|
|
73
|
-
// src/settings.ts
|
|
74
|
-
import { Option } from "commander";
|
|
75
|
-
import pc2 from "picocolors";
|
|
19
|
+
});
|
|
76
20
|
|
|
77
21
|
// src/actions-client.ts
|
|
78
22
|
import {
|
|
@@ -89,7 +33,6 @@ import {
|
|
|
89
33
|
resolvePlatformAuth,
|
|
90
34
|
toErrorEnvelope
|
|
91
35
|
} from "@computesdk/platform";
|
|
92
|
-
var CLI_CREDENTIALS_HINT = "Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.";
|
|
93
36
|
function resolveActionsAuth(opts, resolveStored) {
|
|
94
37
|
return resolvePlatformAuth(opts, resolveStored, CLI_CREDENTIALS_HINT);
|
|
95
38
|
}
|
|
@@ -97,17 +40,25 @@ function encodeWatchCursor(id, jobId, step, offset) {
|
|
|
97
40
|
const stepPart = step === null ? "-" : step === "runner" ? "runner" : String(step);
|
|
98
41
|
return `${id}:${jobId}:${stepPart}:${offset}`;
|
|
99
42
|
}
|
|
100
|
-
var ActionsClient
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
43
|
+
var CLI_CREDENTIALS_HINT, ActionsClient;
|
|
44
|
+
var init_actions_client = __esm({
|
|
45
|
+
"src/actions-client.ts"() {
|
|
46
|
+
"use strict";
|
|
47
|
+
init_esm_shims();
|
|
48
|
+
CLI_CREDENTIALS_HINT = "Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.";
|
|
49
|
+
ActionsClient = class extends PlatformClient {
|
|
50
|
+
constructor() {
|
|
51
|
+
super(...arguments);
|
|
52
|
+
this.orgPromise = null;
|
|
53
|
+
}
|
|
54
|
+
/** The credential's org — fetched once, needed for dashboard URLs. */
|
|
55
|
+
org() {
|
|
56
|
+
this.orgPromise ?? (this.orgPromise = this.get("/api/v1/actions/org"));
|
|
57
|
+
return this.orgPromise;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
109
60
|
}
|
|
110
|
-
};
|
|
61
|
+
});
|
|
111
62
|
|
|
112
63
|
// src/term.ts
|
|
113
64
|
import pc from "picocolors";
|
|
@@ -134,9 +85,16 @@ function conclusionLabel(conclusion) {
|
|
|
134
85
|
return safeTerm(conclusion);
|
|
135
86
|
}
|
|
136
87
|
}
|
|
88
|
+
var init_term = __esm({
|
|
89
|
+
"src/term.ts"() {
|
|
90
|
+
"use strict";
|
|
91
|
+
init_esm_shims();
|
|
92
|
+
}
|
|
93
|
+
});
|
|
137
94
|
|
|
138
95
|
// src/settings.ts
|
|
139
|
-
|
|
96
|
+
import { Option } from "commander";
|
|
97
|
+
import pc2 from "picocolors";
|
|
140
98
|
function parseMaxPrice(value, per) {
|
|
141
99
|
if (value === void 0) {
|
|
142
100
|
if (per !== void 0) throw new Error("--max-price-per requires --max-price.");
|
|
@@ -182,8 +140,6 @@ function parseSizeCap(entry) {
|
|
|
182
140
|
}
|
|
183
141
|
return { size, cap };
|
|
184
142
|
}
|
|
185
|
-
var MAX_WARM_POOL_SIZE = 16;
|
|
186
|
-
var MAX_SNAPSHOT_POOL_SIZE = 32;
|
|
187
143
|
function parseResourcesFlag(entry) {
|
|
188
144
|
const eq = entry.indexOf("=");
|
|
189
145
|
const provider = eq === -1 ? "" : entry.slice(0, eq).trim();
|
|
@@ -230,20 +186,6 @@ function formatResources(r) {
|
|
|
230
186
|
if (r.ephemeralDiskMb) parts.push(`${r.ephemeralDiskMb} MB disk`);
|
|
231
187
|
return parts.join(" / ") || "\u2014";
|
|
232
188
|
}
|
|
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 MANAGED_STRATEGIES = ["computesdk", "cheapest"];
|
|
241
|
-
var STRATEGY_LABEL = {
|
|
242
|
-
computesdk: "ComputeSDK (recommended)",
|
|
243
|
-
cheapest: "Cheapest",
|
|
244
|
-
custom: "Custom"
|
|
245
|
-
};
|
|
246
|
-
var arrow = (list) => list.join(" \u2192 ");
|
|
247
189
|
function printLaneRouting(r, lane) {
|
|
248
190
|
const label = (text) => text.padEnd(12);
|
|
249
191
|
const managed = r.managed.length > 0 ? arrow(r.managed) : pc2.dim("no managed account is live");
|
|
@@ -253,8 +195,8 @@ function printLaneRouting(r, lane) {
|
|
|
253
195
|
console.log(`${label("Order")}${managed}${size}`);
|
|
254
196
|
console.log(`${label("BYOK")}${r.byok.mode} ${pc2.dim(`(${BYOK_MODE_HELP[r.byok.mode]})`)}`);
|
|
255
197
|
if (r.byok.mode !== "off") {
|
|
256
|
-
const
|
|
257
|
-
const order = lane === "sandboxes" && r.byok.inherits === true ? `${
|
|
198
|
+
const list2 = r.byok.order.length > 0 ? arrow(r.byok.order) : "\u2014";
|
|
199
|
+
const order = lane === "sandboxes" && r.byok.inherits === true ? `${list2} ${pc2.dim("(inherited from the Actions router)")}` : r.byok.order.length > 0 ? list2 : pc2.dim("none set \u2014 add keys with `compute byok configure`");
|
|
258
200
|
console.log(`${label("BYOK order")}${order}`);
|
|
259
201
|
}
|
|
260
202
|
}
|
|
@@ -306,9 +248,9 @@ function settingsFail(e, opts, lane, verb, deps) {
|
|
|
306
248
|
return deps.fail(e, opts);
|
|
307
249
|
}
|
|
308
250
|
function providerList(flag, value) {
|
|
309
|
-
const
|
|
310
|
-
if (
|
|
311
|
-
return
|
|
251
|
+
const list2 = value.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
252
|
+
if (list2.length === 0) throw new Error(`${flag} "${value}" names no providers \u2014 pass a comma-separated list.`);
|
|
253
|
+
return list2;
|
|
312
254
|
}
|
|
313
255
|
function registerSettingsCommands(group, lane, common2, deps) {
|
|
314
256
|
const routerName = lane === "sandboxes" ? "Sandboxes" : "Actions";
|
|
@@ -437,16 +379,32 @@ function registerSettingsCommands(group, lane, common2, deps) {
|
|
|
437
379
|
}
|
|
438
380
|
});
|
|
439
381
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
382
|
+
var PLATFORM_SIZES, MAX_WARM_POOL_SIZE, MAX_SNAPSHOT_POOL_SIZE, BYOK_MODES, BYOK_MODE_HELP, MANAGED_STRATEGIES, STRATEGY_LABEL, arrow;
|
|
383
|
+
var init_settings = __esm({
|
|
384
|
+
"src/settings.ts"() {
|
|
385
|
+
"use strict";
|
|
386
|
+
init_esm_shims();
|
|
387
|
+
init_actions_client();
|
|
388
|
+
init_term();
|
|
389
|
+
PLATFORM_SIZES = ["small", "medium", "large", "xlarge", "2xlarge", "3xlarge"];
|
|
390
|
+
MAX_WARM_POOL_SIZE = 16;
|
|
391
|
+
MAX_SNAPSHOT_POOL_SIZE = 32;
|
|
392
|
+
BYOK_MODES = ["off", "first", "fallback", "only"];
|
|
393
|
+
BYOK_MODE_HELP = {
|
|
394
|
+
off: "not used: managed accounts only",
|
|
395
|
+
first: "your keys first, then managed accounts",
|
|
396
|
+
fallback: "managed accounts first, then your keys",
|
|
397
|
+
only: "your keys only, never managed accounts"
|
|
398
|
+
};
|
|
399
|
+
MANAGED_STRATEGIES = ["computesdk", "cheapest"];
|
|
400
|
+
STRATEGY_LABEL = {
|
|
401
|
+
computesdk: "ComputeSDK (recommended)",
|
|
402
|
+
cheapest: "Cheapest",
|
|
403
|
+
custom: "Custom"
|
|
404
|
+
};
|
|
405
|
+
arrow = (list2) => list2.join(" \u2192 ");
|
|
406
|
+
}
|
|
407
|
+
});
|
|
450
408
|
|
|
451
409
|
// src/confirm.ts
|
|
452
410
|
import { createInterface } from "readline/promises";
|
|
@@ -466,9 +424,16 @@ async function confirmWrite(question, opts) {
|
|
|
466
424
|
throw new PlatformClientError("cancelled", "Cancelled; nothing was changed.");
|
|
467
425
|
}
|
|
468
426
|
}
|
|
427
|
+
var init_confirm = __esm({
|
|
428
|
+
"src/confirm.ts"() {
|
|
429
|
+
"use strict";
|
|
430
|
+
init_esm_shims();
|
|
431
|
+
init_actions_client();
|
|
432
|
+
}
|
|
433
|
+
});
|
|
469
434
|
|
|
470
435
|
// src/actions-runs.ts
|
|
471
|
-
|
|
436
|
+
import pc3 from "picocolors";
|
|
472
437
|
function plural(n, noun) {
|
|
473
438
|
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
474
439
|
}
|
|
@@ -502,7 +467,7 @@ async function runFilterQuery(c, repo, opts) {
|
|
|
502
467
|
workflow = [];
|
|
503
468
|
for (const selector of opts.workflow) {
|
|
504
469
|
const paths = selector.startsWith(WORKFLOW_PATH_PREFIX) ? [selector] : resolveWorkflowPaths(catalog, [selector]);
|
|
505
|
-
for (const
|
|
470
|
+
for (const path6 of paths) if (!workflow.includes(path6)) workflow.push(path6);
|
|
506
471
|
}
|
|
507
472
|
}
|
|
508
473
|
return {
|
|
@@ -587,8 +552,8 @@ function registerRunsCommands(actions, common2, deps) {
|
|
|
587
552
|
});
|
|
588
553
|
return;
|
|
589
554
|
}
|
|
590
|
-
const { runs:
|
|
591
|
-
deps.output(opts,
|
|
555
|
+
const { runs: list2 } = await c.get("/api/v1/actions/runs", query);
|
|
556
|
+
deps.output(opts, list2, printRuns);
|
|
592
557
|
} catch (e) {
|
|
593
558
|
deps.fail(e, opts);
|
|
594
559
|
}
|
|
@@ -631,8 +596,20 @@ function registerRunsCommands(actions, common2, deps) {
|
|
|
631
596
|
});
|
|
632
597
|
}
|
|
633
598
|
}
|
|
599
|
+
var WORKFLOW_PATH_PREFIX;
|
|
600
|
+
var init_actions_runs = __esm({
|
|
601
|
+
"src/actions-runs.ts"() {
|
|
602
|
+
"use strict";
|
|
603
|
+
init_esm_shims();
|
|
604
|
+
init_actions_client();
|
|
605
|
+
init_confirm();
|
|
606
|
+
init_term();
|
|
607
|
+
WORKFLOW_PATH_PREFIX = ".github/";
|
|
608
|
+
}
|
|
609
|
+
});
|
|
634
610
|
|
|
635
611
|
// src/actions-workflows.ts
|
|
612
|
+
import pc4 from "picocolors";
|
|
636
613
|
function formatAgo(iso, now = Date.now()) {
|
|
637
614
|
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1e3));
|
|
638
615
|
if (s < 60) return `${s}s ago`;
|
|
@@ -801,10 +778,10 @@ function registerWorkflowsCommands(actions, common2, deps) {
|
|
|
801
778
|
repo,
|
|
802
779
|
include: "all"
|
|
803
780
|
});
|
|
804
|
-
const
|
|
781
|
+
const path6 = resolveControlTarget(catalog, repo, selector);
|
|
805
782
|
const result = await c.patch("/api/v1/actions/workflows", {
|
|
806
783
|
repoFullName: repo,
|
|
807
|
-
path:
|
|
784
|
+
path: path6,
|
|
808
785
|
...controls
|
|
809
786
|
});
|
|
810
787
|
deps.output(opts, result, (r) => console.log(formatControlsResult(verb, r)));
|
|
@@ -842,9 +819,20 @@ function registerWorkflowsCommands(actions, common2, deps) {
|
|
|
842
819
|
}
|
|
843
820
|
});
|
|
844
821
|
}
|
|
822
|
+
var init_actions_workflows = __esm({
|
|
823
|
+
"src/actions-workflows.ts"() {
|
|
824
|
+
"use strict";
|
|
825
|
+
init_esm_shims();
|
|
826
|
+
init_actions_client();
|
|
827
|
+
init_actions_runs();
|
|
828
|
+
init_confirm();
|
|
829
|
+
init_term();
|
|
830
|
+
}
|
|
831
|
+
});
|
|
845
832
|
|
|
846
833
|
// src/actions-repos.ts
|
|
847
|
-
|
|
834
|
+
import pc5 from "picocolors";
|
|
835
|
+
import { readFileSync } from "fs";
|
|
848
836
|
function plural2(n, noun) {
|
|
849
837
|
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
850
838
|
}
|
|
@@ -916,8 +904,6 @@ function parseForkPrs(value) {
|
|
|
916
904
|
}
|
|
917
905
|
return FORK_PRS[value];
|
|
918
906
|
}
|
|
919
|
-
var repoIdBody = (opts) => opts.repoId !== void 0 ? { repoId: opts.repoId } : {};
|
|
920
|
-
var REPO_ID_HELP = "scope to one row when two installations grant the same name";
|
|
921
907
|
function registerReposCommands(actions, common2, deps) {
|
|
922
908
|
const { client: client2, output: output2, fail: fail3 } = deps;
|
|
923
909
|
const repos = actions.command("repos").description("List the org's connected repositories: run counts, last run and next poll");
|
|
@@ -1091,6 +1077,20 @@ function registerReposCommands(actions, common2, deps) {
|
|
|
1091
1077
|
}
|
|
1092
1078
|
});
|
|
1093
1079
|
}
|
|
1080
|
+
var FORK_PRS, repoIdBody, REPO_ID_HELP;
|
|
1081
|
+
var init_actions_repos = __esm({
|
|
1082
|
+
"src/actions-repos.ts"() {
|
|
1083
|
+
"use strict";
|
|
1084
|
+
init_esm_shims();
|
|
1085
|
+
init_actions_client();
|
|
1086
|
+
init_actions_workflows();
|
|
1087
|
+
init_confirm();
|
|
1088
|
+
init_term();
|
|
1089
|
+
FORK_PRS = { allow: true, refuse: false };
|
|
1090
|
+
repoIdBody = (opts) => opts.repoId !== void 0 ? { repoId: opts.repoId } : {};
|
|
1091
|
+
REPO_ID_HELP = "scope to one row when two installations grant the same name";
|
|
1092
|
+
}
|
|
1093
|
+
});
|
|
1094
1094
|
|
|
1095
1095
|
// src/actions-integrations.ts
|
|
1096
1096
|
import pc6 from "picocolors";
|
|
@@ -1186,8 +1186,19 @@ function registerIntegrationsCommands(actions, common2, deps) {
|
|
|
1186
1186
|
}
|
|
1187
1187
|
});
|
|
1188
1188
|
}
|
|
1189
|
+
var init_actions_integrations = __esm({
|
|
1190
|
+
"src/actions-integrations.ts"() {
|
|
1191
|
+
"use strict";
|
|
1192
|
+
init_esm_shims();
|
|
1193
|
+
init_term();
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1189
1196
|
|
|
1190
1197
|
// src/actions.ts
|
|
1198
|
+
import { Option as Option2 } from "commander";
|
|
1199
|
+
import pc7 from "picocolors";
|
|
1200
|
+
import { mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
1201
|
+
import { spawnSync } from "child_process";
|
|
1191
1202
|
import { basename, join } from "path";
|
|
1192
1203
|
function sanitizePathPart(name) {
|
|
1193
1204
|
const base = basename(name);
|
|
@@ -1337,8 +1348,8 @@ function fail(error, opts = {}) {
|
|
|
1337
1348
|
}
|
|
1338
1349
|
function usageErrorOutput(str, write, argv = process.argv) {
|
|
1339
1350
|
if (argv.includes("--json")) {
|
|
1340
|
-
const
|
|
1341
|
-
write(JSON.stringify(toErrorEnvelope(new PlatformClientError("invalid_argument",
|
|
1351
|
+
const message2 = str.replace(/^error:\s*/i, "").trim();
|
|
1352
|
+
write(JSON.stringify(toErrorEnvelope(new PlatformClientError("invalid_argument", message2))) + "\n");
|
|
1342
1353
|
} else {
|
|
1343
1354
|
write(str);
|
|
1344
1355
|
}
|
|
@@ -1686,9 +1697,9 @@ function formatVerifyResult(r) {
|
|
|
1686
1697
|
function isPatchedWorkflowTarget(target) {
|
|
1687
1698
|
return "workflowPath" in target;
|
|
1688
1699
|
}
|
|
1689
|
-
function patchTouches(patch,
|
|
1690
|
-
const plain = `+++ b/${
|
|
1691
|
-
const quoted = `+++ "b/${
|
|
1700
|
+
function patchTouches(patch, path6) {
|
|
1701
|
+
const plain = `+++ b/${path6}`;
|
|
1702
|
+
const quoted = `+++ "b/${path6}"`;
|
|
1692
1703
|
return patch.split("\n").some((line) => {
|
|
1693
1704
|
const header = line.replace(/\t.*$/, "");
|
|
1694
1705
|
return header === plain || header === quoted;
|
|
@@ -1696,18 +1707,18 @@ function patchTouches(patch, path2) {
|
|
|
1696
1707
|
}
|
|
1697
1708
|
function dispatchBody(workflow, opts) {
|
|
1698
1709
|
const patched = isPatchedWorkflowTarget(workflow);
|
|
1699
|
-
const
|
|
1710
|
+
const path6 = patched ? workflow.workflowPath : workflow.path;
|
|
1700
1711
|
const pushOnly = workflow.dispatchable === false;
|
|
1701
1712
|
if (pushOnly && !opts.manual) {
|
|
1702
1713
|
throw new PlatformClientError(
|
|
1703
1714
|
"invalid_argument",
|
|
1704
|
-
`Workflow "${
|
|
1715
|
+
`Workflow "${path6}" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`
|
|
1705
1716
|
);
|
|
1706
1717
|
}
|
|
1707
1718
|
if (pushOnly && opts.inputs !== void 0 && opts.inputs.length > 0) {
|
|
1708
1719
|
throw new PlatformClientError(
|
|
1709
1720
|
"invalid_argument",
|
|
1710
|
-
`Workflow "${
|
|
1721
|
+
`Workflow "${path6}" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`
|
|
1711
1722
|
);
|
|
1712
1723
|
}
|
|
1713
1724
|
const ref = opts.ref ?? (patched ? void 0 : workflow.refs[0]);
|
|
@@ -1729,10 +1740,6 @@ function dispatchBody(workflow, opts) {
|
|
|
1729
1740
|
...opts.patchId !== void 0 && { patchId: opts.patchId }
|
|
1730
1741
|
};
|
|
1731
1742
|
}
|
|
1732
|
-
var runGit = (args) => {
|
|
1733
|
-
const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
1734
|
-
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
1735
|
-
};
|
|
1736
1743
|
function remoteNamesRepo(remote, repo) {
|
|
1737
1744
|
const normalized = remote.trim().replace(/\.git$/, "").replace(/\/+$/, "");
|
|
1738
1745
|
return normalized.toLowerCase().endsWith(`/${repo.toLowerCase()}`) || normalized.toLowerCase().endsWith(`:${repo.toLowerCase()}`);
|
|
@@ -1807,13 +1814,13 @@ function parseVaultKind(kind) {
|
|
|
1807
1814
|
if (kind === void 0 || kind === "secret" || kind === "variable") return kind ?? "secret";
|
|
1808
1815
|
throw new PlatformClientError("invalid_argument", `--kind must be secret or variable, got "${kind}".`);
|
|
1809
1816
|
}
|
|
1810
|
-
function vaultPath(
|
|
1817
|
+
function vaultPath(path6, params) {
|
|
1811
1818
|
const search = new URLSearchParams();
|
|
1812
1819
|
for (const [key, value] of Object.entries(params)) {
|
|
1813
1820
|
if (value !== void 0) search.set(key, value);
|
|
1814
1821
|
}
|
|
1815
1822
|
const query = search.toString();
|
|
1816
|
-
return query ? `${
|
|
1823
|
+
return query ? `${path6}?${query}` : path6;
|
|
1817
1824
|
}
|
|
1818
1825
|
function vaultSetBody(name, value, opts) {
|
|
1819
1826
|
if (value === "") throw new PlatformClientError("invalid_argument", "The value is empty.");
|
|
@@ -2161,8 +2168,8 @@ function registerActionsCommands(program2) {
|
|
|
2161
2168
|
vault.command("ls").description("List names and metadata (never values)")
|
|
2162
2169
|
).action(async (opts) => {
|
|
2163
2170
|
try {
|
|
2164
|
-
const
|
|
2165
|
-
const data = await (await client(opts)).get(
|
|
2171
|
+
const path6 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind) });
|
|
2172
|
+
const data = await (await client(opts)).get(path6);
|
|
2166
2173
|
output(opts, data, (d) => {
|
|
2167
2174
|
for (const item of d.items) console.log(formatVaultRow(item));
|
|
2168
2175
|
});
|
|
@@ -2237,8 +2244,8 @@ function registerActionsCommands(program2) {
|
|
|
2237
2244
|
vault.command("rm").description("Delete an item (with --repo, only the repo's override)").argument("<name>", "item name")
|
|
2238
2245
|
).action(async (name, opts) => {
|
|
2239
2246
|
try {
|
|
2240
|
-
const
|
|
2241
|
-
const result = await (await client(opts)).del(
|
|
2247
|
+
const path6 = vaultPath("/api/v1/vault", { repo: opts.repo, kind: parseVaultKind(opts.kind), name });
|
|
2248
|
+
const result = await (await client(opts)).del(path6);
|
|
2242
2249
|
output(opts, result, (r) => console.log(`deleted ${pc7.cyan(safeTerm(r.name))} ${pc7.dim(`(${r.kind})`)}`));
|
|
2243
2250
|
} catch (e) {
|
|
2244
2251
|
fail(e, opts);
|
|
@@ -2339,110 +2346,646 @@ function registerActionsCommands(program2) {
|
|
|
2339
2346
|
usageErrorOutput
|
|
2340
2347
|
});
|
|
2341
2348
|
}
|
|
2349
|
+
var runGit;
|
|
2350
|
+
var init_actions = __esm({
|
|
2351
|
+
"src/actions.ts"() {
|
|
2352
|
+
"use strict";
|
|
2353
|
+
init_esm_shims();
|
|
2354
|
+
init_settings();
|
|
2355
|
+
init_actions_repos();
|
|
2356
|
+
init_actions_integrations();
|
|
2357
|
+
init_actions_runs();
|
|
2358
|
+
init_actions_workflows();
|
|
2359
|
+
init_term();
|
|
2360
|
+
init_actions_client();
|
|
2361
|
+
runGit = (args) => {
|
|
2362
|
+
const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
2363
|
+
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
});
|
|
2342
2367
|
|
|
2343
|
-
// src/
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2368
|
+
// src/exec.ts
|
|
2369
|
+
function execCommand(args) {
|
|
2370
|
+
return args.length === 1 ? args[0] : args.map((arg) => `'${arg.replace(/'/g, `'\\''`)}'`).join(" ");
|
|
2371
|
+
}
|
|
2372
|
+
function execTimeout(opts) {
|
|
2373
|
+
if (opts.detach && (opts.stream || opts.timeout !== void 0 || opts.timeoutMs !== void 0)) {
|
|
2374
|
+
throw new PlatformClientError("invalid_argument", "--detach cannot be combined with --stream or a command timeout.");
|
|
2375
|
+
}
|
|
2376
|
+
if (opts.timeout !== void 0 && opts.timeoutMs !== void 0) {
|
|
2377
|
+
throw new PlatformClientError("invalid_argument", "Use --timeout (seconds) or --timeout-ms, not both.");
|
|
2378
|
+
}
|
|
2379
|
+
const raw = opts.timeout ?? opts.timeoutMs;
|
|
2380
|
+
if (raw === void 0) return void 0;
|
|
2381
|
+
const ms = Number(raw) * (opts.timeout !== void 0 ? 1e3 : 1);
|
|
2382
|
+
if (raw.trim() === "" || !Number.isSafeInteger(ms) || ms < 0 || ms > 2147483647) {
|
|
2383
|
+
throw new PlatformClientError("invalid_argument", "Timeout must be a non-negative duration up to 2147483647 ms (0 means no command time limit).");
|
|
2384
|
+
}
|
|
2385
|
+
return ms;
|
|
2386
|
+
}
|
|
2387
|
+
async function execute(c, sandboxId, body, opts) {
|
|
2388
|
+
const timeoutMs = execTimeout(opts);
|
|
2389
|
+
if (!opts.detach && !opts.stream && timeoutMs !== 0 && (timeoutMs === void 0 || timeoutMs <= BUFFERED_MAX_MS)) {
|
|
2390
|
+
const res = await c.post(
|
|
2391
|
+
`/api/v1/sandboxes/${sandboxId}/commands`,
|
|
2392
|
+
{ ...body, ...timeoutMs !== void 0 ? { timeoutMs } : {} }
|
|
2393
|
+
);
|
|
2394
|
+
output(opts, res, (r) => {
|
|
2395
|
+
process.stdout.write(r.stdout);
|
|
2396
|
+
if (r.stderr) process.stderr.write(r.stderr);
|
|
2397
|
+
if (!r.stdout) console.log(`exit ${r.exitCode} (${r.durationMs}ms)`);
|
|
2398
|
+
});
|
|
2399
|
+
if (res.exitCode !== 0) process.exitCode = res.exitCode;
|
|
2400
|
+
return;
|
|
2401
|
+
}
|
|
2402
|
+
const { process: job } = await c.post(
|
|
2403
|
+
`/api/v1/sandboxes/${sandboxId}/processes`,
|
|
2404
|
+
body
|
|
2405
|
+
);
|
|
2406
|
+
if (opts.detach) {
|
|
2407
|
+
output(opts, job, (p2) => {
|
|
2408
|
+
console.log(p2.jobId);
|
|
2409
|
+
console.error(`Follow: compute logs ${sandboxId} ${p2.jobId} --follow`);
|
|
2410
|
+
});
|
|
2411
|
+
return;
|
|
2412
|
+
}
|
|
2413
|
+
await streamJob(c, sandboxId, job.jobId, timeoutMs ?? BUFFERED_MAX_MS, opts);
|
|
2414
|
+
}
|
|
2415
|
+
async function streamJob(c, sandboxId, jobId, timeoutMs, opts) {
|
|
2416
|
+
const base = `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`;
|
|
2417
|
+
const controller = new AbortController();
|
|
2418
|
+
let stopCode;
|
|
2419
|
+
let stopping;
|
|
2420
|
+
let killError;
|
|
2421
|
+
const stop = (code, signal) => {
|
|
2422
|
+
if (stopping) return;
|
|
2423
|
+
stopCode = code;
|
|
2424
|
+
stopping = c.post(`${base}/kill`, { signal }, { signal: AbortSignal.timeout(1e4) }).then(() => void 0).catch(() => {
|
|
2425
|
+
killError = `Could not stop job ${jobId}; run compute instances kill ${sandboxId} ${jobId}.`;
|
|
2426
|
+
if (!opts.json) console.error(killError);
|
|
2427
|
+
}).finally(() => controller.abort());
|
|
2355
2428
|
};
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
const
|
|
2361
|
-
const
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2429
|
+
const onInterrupt = () => stop(130, "SIGINT");
|
|
2430
|
+
const onTerminate = () => stop(143, "SIGTERM");
|
|
2431
|
+
process.on("SIGINT", onInterrupt);
|
|
2432
|
+
process.on("SIGTERM", onTerminate);
|
|
2433
|
+
const deadline = timeoutMs === 0 ? void 0 : Date.now() + timeoutMs;
|
|
2434
|
+
const timer = timeoutMs === 0 ? void 0 : setTimeout(() => stop(124, "SIGKILL"), timeoutMs);
|
|
2435
|
+
let stdoutOffset = 0;
|
|
2436
|
+
let stderrOffset = 0;
|
|
2437
|
+
try {
|
|
2438
|
+
while (stopCode === void 0) {
|
|
2439
|
+
const remaining = deadline === void 0 ? 1e3 : deadline - Date.now();
|
|
2440
|
+
if (remaining <= 0) {
|
|
2441
|
+
stop(124, "SIGKILL");
|
|
2442
|
+
break;
|
|
2443
|
+
}
|
|
2444
|
+
const { process: status } = await c.post(
|
|
2445
|
+
`${base}/wait`,
|
|
2446
|
+
{ timeoutMs: Math.min(1e3, remaining) },
|
|
2447
|
+
{ signal: controller.signal }
|
|
2448
|
+
);
|
|
2449
|
+
const emit = (event, data) => {
|
|
2450
|
+
if (opts.json) process.stdout.write(JSON.stringify({ event, ...data }) + "\n");
|
|
2451
|
+
else if (event === "stdout") process.stdout.write(String(data.chunk));
|
|
2452
|
+
else if (event === "stderr") process.stderr.write(String(data.chunk));
|
|
2453
|
+
};
|
|
2454
|
+
if (status.stdout.length > stdoutOffset) emit("stdout", { chunk: status.stdout.slice(stdoutOffset) });
|
|
2455
|
+
if (status.stderr.length > stderrOffset) emit("stderr", { chunk: status.stderr.slice(stderrOffset) });
|
|
2456
|
+
stdoutOffset = status.stdout.length;
|
|
2457
|
+
stderrOffset = status.stderr.length;
|
|
2458
|
+
if (status.status === "exited") {
|
|
2459
|
+
const code = status.exitCode ?? 128;
|
|
2460
|
+
emit("exit", { exitCode: code });
|
|
2461
|
+
if (code !== 0) process.exitCode = code;
|
|
2462
|
+
return;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
} catch (error) {
|
|
2466
|
+
if (stopCode === void 0) {
|
|
2467
|
+
const recovery = `Job ${jobId} remains available: compute logs ${sandboxId} ${jobId} --follow`;
|
|
2468
|
+
if (error instanceof Error) {
|
|
2469
|
+
error.message += `. ${recovery}`;
|
|
2470
|
+
throw error;
|
|
2471
|
+
}
|
|
2472
|
+
throw new Error(`${String(error)}. ${recovery}`);
|
|
2473
|
+
}
|
|
2474
|
+
} finally {
|
|
2475
|
+
clearTimeout(timer);
|
|
2476
|
+
process.removeListener("SIGINT", onInterrupt);
|
|
2477
|
+
process.removeListener("SIGTERM", onTerminate);
|
|
2478
|
+
await stopping;
|
|
2479
|
+
if (stopCode !== void 0) {
|
|
2480
|
+
process.exitCode = stopCode;
|
|
2481
|
+
if (opts.json) process.stdout.write(JSON.stringify({ event: "exit", exitCode: stopCode, ...killError ? { error: killError } : {} }) + "\n");
|
|
2482
|
+
}
|
|
2371
2483
|
}
|
|
2372
|
-
const s = abs.toLocaleString("en-US", {
|
|
2373
|
-
minimumFractionDigits: 2,
|
|
2374
|
-
maximumFractionDigits: 2
|
|
2375
|
-
});
|
|
2376
|
-
return `${sign}$${s}`;
|
|
2377
|
-
}
|
|
2378
|
-
function formatRateAllUnits(rate) {
|
|
2379
|
-
return `${formatUsd(rate.perHour)}/hr \xB7 ${formatUsd(rate.perMinute)}/min \xB7 ${formatUsd(rate.perSecond)}/s`;
|
|
2380
|
-
}
|
|
2381
|
-
function formatUsdPer(rate) {
|
|
2382
|
-
return formatRateAllUnits(rateAllUnits(rate));
|
|
2383
2484
|
}
|
|
2485
|
+
var BUFFERED_MAX_MS;
|
|
2486
|
+
var init_exec = __esm({
|
|
2487
|
+
"src/exec.ts"() {
|
|
2488
|
+
"use strict";
|
|
2489
|
+
init_esm_shims();
|
|
2490
|
+
init_actions_client();
|
|
2491
|
+
init_actions();
|
|
2492
|
+
BUFFERED_MAX_MS = 29e4;
|
|
2493
|
+
}
|
|
2494
|
+
});
|
|
2384
2495
|
|
|
2385
|
-
// src/
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
if (
|
|
2393
|
-
const
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
}
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
const
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2496
|
+
// src/sync-fs.ts
|
|
2497
|
+
async function treeOperation(input, requireModule2, exclude) {
|
|
2498
|
+
const fs5 = requireModule2("node:fs");
|
|
2499
|
+
const path6 = requireModule2("node:path");
|
|
2500
|
+
const crypto = requireModule2("node:crypto");
|
|
2501
|
+
const root = path6.resolve(input.root);
|
|
2502
|
+
if (root.split(path6.sep).includes(".git")) throw new Error("Sync cannot target .git.");
|
|
2503
|
+
if (root === path6.parse(root).root) throw new Error("Sync requires a project directory, not a filesystem root.");
|
|
2504
|
+
const checked = (relative2) => {
|
|
2505
|
+
if (path6.isAbsolute(relative2) || relative2.split(/[\\/]/).some((s) => s === ".." || s === ".git") || relative2.includes("\0")) {
|
|
2506
|
+
throw new Error("Unsafe sync path: " + relative2);
|
|
2507
|
+
}
|
|
2508
|
+
const full = path6.join(root, relative2);
|
|
2509
|
+
let cursor = path6.parse(full).root;
|
|
2510
|
+
const parts = full.slice(cursor.length).split(path6.sep);
|
|
2511
|
+
for (const segment2 of parts.slice(0, -1)) {
|
|
2512
|
+
cursor = path6.join(cursor, segment2);
|
|
2513
|
+
try {
|
|
2514
|
+
if (fs5.lstatSync(cursor).isSymbolicLink()) throw new Error("Sync cannot traverse symlink: " + cursor);
|
|
2515
|
+
} catch (error) {
|
|
2516
|
+
if (error.code !== "ENOENT") throw error;
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
return full;
|
|
2520
|
+
};
|
|
2521
|
+
checked("");
|
|
2522
|
+
try {
|
|
2523
|
+
const stat = fs5.lstatSync(root);
|
|
2524
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Sync requires a real directory: " + root);
|
|
2525
|
+
} catch (error) {
|
|
2526
|
+
if (error.code !== "ENOENT" || !input.missing) throw error;
|
|
2527
|
+
if (!input.directories && !input.remove) return [];
|
|
2528
|
+
fs5.mkdirSync(root, { recursive: true });
|
|
2529
|
+
}
|
|
2530
|
+
for (const expected of input.remove ?? []) {
|
|
2531
|
+
const relative2 = expected.path;
|
|
2532
|
+
const full = checked(relative2);
|
|
2533
|
+
if (!relative2) throw new Error("Cannot delete the sync root.");
|
|
2534
|
+
const stat = fs5.lstatSync(full);
|
|
2535
|
+
const type = stat.isSymbolicLink() ? "symlink" : stat.isDirectory() ? "directory" : "file";
|
|
2536
|
+
let hash;
|
|
2537
|
+
if (type === "file") {
|
|
2538
|
+
const digest = crypto.createHash("sha256");
|
|
2539
|
+
for await (const chunk of fs5.createReadStream(full)) digest.update(chunk);
|
|
2540
|
+
hash = digest.digest("hex");
|
|
2541
|
+
}
|
|
2542
|
+
if (type !== expected.type || type === "file" && (hash !== expected.hash || (stat.mode & 511) !== expected.mode) || type === "symlink" && fs5.readlinkSync(full) !== expected.link) throw new Error("Destination changed before deletion: " + relative2);
|
|
2543
|
+
if (stat.isDirectory()) fs5.rmdirSync(full);
|
|
2544
|
+
else fs5.unlinkSync(full);
|
|
2545
|
+
}
|
|
2546
|
+
for (const entry of input.directories ?? []) {
|
|
2547
|
+
const full = checked(entry.path);
|
|
2548
|
+
try {
|
|
2549
|
+
if (!fs5.lstatSync(full).isDirectory()) throw new Error("Sync type conflict: " + entry.path);
|
|
2550
|
+
} catch (error) {
|
|
2551
|
+
if (error.code !== "ENOENT") throw error;
|
|
2552
|
+
fs5.mkdirSync(full, { mode: entry.mode | 448 });
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
if (input.remove || input.directories) return [];
|
|
2556
|
+
const result = [];
|
|
2557
|
+
for (const entry of input.entries ?? []) {
|
|
2558
|
+
const full = checked(entry.path);
|
|
2559
|
+
const stat = fs5.lstatSync(full);
|
|
2560
|
+
const type = stat.isSymbolicLink() ? "symlink" : stat.isDirectory() ? "directory" : stat.isFile() ? "file" : void 0;
|
|
2561
|
+
if (!type || type !== entry.type || (stat.mode & 511) !== entry.mode) throw new Error("Project changed during snapshot scan: " + entry.path);
|
|
2562
|
+
if (exclude?.(entry.path, type === "directory")) continue;
|
|
2563
|
+
if (type === "symlink") {
|
|
2564
|
+
const link = fs5.readlinkSync(full);
|
|
2565
|
+
const target = path6.resolve(path6.dirname(full), link);
|
|
2566
|
+
if (!input.destination && (path6.isAbsolute(link) || target !== root && !target.startsWith(root + path6.sep))) throw new Error("Symlink points outside sync root: " + entry.path);
|
|
2567
|
+
if (link !== entry.link) throw new Error("Project changed during snapshot scan: " + entry.path);
|
|
2568
|
+
}
|
|
2569
|
+
result.push({
|
|
2570
|
+
...entry,
|
|
2571
|
+
...input.destination && type === "file" && stat.nlink > 1 ? { links: stat.nlink } : {},
|
|
2572
|
+
...input.destination && type === "directory" && fs5.existsSync(path6.join(full, ".git")) ? { protected: true } : {}
|
|
2573
|
+
});
|
|
2427
2574
|
}
|
|
2428
|
-
|
|
2429
|
-
if (!RATE_UNITS.includes(unit)) throw new Error("--per must be second, minute or hour");
|
|
2430
|
-
return { usd: amount, per: unit };
|
|
2575
|
+
return result;
|
|
2431
2576
|
}
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2577
|
+
var localTree;
|
|
2578
|
+
var init_sync_fs = __esm({
|
|
2579
|
+
"src/sync-fs.ts"() {
|
|
2580
|
+
"use strict";
|
|
2581
|
+
init_esm_shims();
|
|
2582
|
+
localTree = async (input, exclude) => {
|
|
2583
|
+
const { scanLocalTree: scanLocalTree2 } = await Promise.resolve().then(() => (init_snapshot_engine(), snapshot_engine_exports));
|
|
2584
|
+
return scanLocalTree2(input, exclude);
|
|
2585
|
+
};
|
|
2436
2586
|
}
|
|
2437
|
-
|
|
2438
|
-
|
|
2587
|
+
});
|
|
2588
|
+
|
|
2589
|
+
// src/snapshot-engine.ts
|
|
2590
|
+
var snapshot_engine_exports = {};
|
|
2591
|
+
__export(snapshot_engine_exports, {
|
|
2592
|
+
ENGINE_FILE: () => ENGINE_FILE,
|
|
2593
|
+
SnapshotSession: () => SnapshotSession,
|
|
2594
|
+
endpointRoot: () => endpointRoot,
|
|
2595
|
+
exactSelector: () => exactSelector,
|
|
2596
|
+
ignoredPaths: () => ignoredPaths,
|
|
2597
|
+
indexEntries: () => indexEntries,
|
|
2598
|
+
scanLocalTree: () => scanLocalTree,
|
|
2599
|
+
selectSnapshot: () => selectSnapshot
|
|
2600
|
+
});
|
|
2601
|
+
import * as fs from "fs";
|
|
2602
|
+
import * as path2 from "path";
|
|
2603
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2604
|
+
import { tmpdir } from "os";
|
|
2605
|
+
import { execFile } from "child_process";
|
|
2606
|
+
import { promisify } from "util";
|
|
2607
|
+
import { randomUUID, createHash as createHash2 } from "crypto";
|
|
2608
|
+
import { createRequire } from "module";
|
|
2609
|
+
function exactSelector(value) {
|
|
2610
|
+
if (/[*?]/.test(value)) throw new Error("Snapshot sync cannot address literal * or ? in a path: " + value);
|
|
2611
|
+
return value.split(path2.sep).join("/");
|
|
2612
|
+
}
|
|
2613
|
+
function ignoredPaths(root, exclude) {
|
|
2614
|
+
const paths = ["**/.git", "**/.git/**"];
|
|
2615
|
+
if (!exclude || !fs.existsSync(root)) return paths;
|
|
2616
|
+
const visit = (dir) => {
|
|
2617
|
+
for (const entry of fs.readdirSync(path2.join(root, dir), { withFileTypes: true })) {
|
|
2618
|
+
const name = dir ? dir + "/" + entry.name : entry.name;
|
|
2619
|
+
if (entry.name === ".git" || exclude(name, entry.isDirectory())) paths.push(exactSelector(path2.join(root, name)));
|
|
2620
|
+
else if (entry.isDirectory()) visit(name);
|
|
2621
|
+
}
|
|
2622
|
+
};
|
|
2623
|
+
visit("");
|
|
2624
|
+
return paths;
|
|
2439
2625
|
}
|
|
2440
|
-
function
|
|
2441
|
-
const
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2626
|
+
function indexEntries(config, root) {
|
|
2627
|
+
const result = [];
|
|
2628
|
+
for (const [absolute, entry] of Object.entries(config.files)) {
|
|
2629
|
+
if (absolute === root) continue;
|
|
2630
|
+
const relative2 = path2.posix.relative(root, absolute);
|
|
2631
|
+
if (!relative2 || relative2.startsWith("/") || relative2.includes("\\") || relative2.split("/").some((p2) => !p2 || p2 === ".." || p2 === "." || p2 === ".git") || relative2.includes("\0")) throw new Error("Unsafe checkpoint file index.");
|
|
2632
|
+
if (!["dir", "file", "symlink"].includes(entry.type)) throw new Error("Unsupported checkpoint entry.");
|
|
2633
|
+
result.push({
|
|
2634
|
+
path: relative2,
|
|
2635
|
+
type: entry.type === "dir" ? "directory" : entry.type,
|
|
2636
|
+
mode: entry.mode & 511,
|
|
2637
|
+
...entry.sha ? { hash: entry.sha } : {},
|
|
2638
|
+
...entry.link !== void 0 ? { link: entry.link } : {}
|
|
2639
|
+
});
|
|
2640
|
+
}
|
|
2641
|
+
return result.sort((a, b) => a.path.localeCompare(b.path));
|
|
2642
|
+
}
|
|
2643
|
+
function selectSnapshot(store, manifestKey, root, copy, destination, destinationRoot) {
|
|
2644
|
+
if (!/^manifests\/[a-f0-9-]+\.json$/.test(manifestKey)) throw new Error("Invalid snapshot manifest key.");
|
|
2645
|
+
const manifest = JSON.parse(fs.readFileSync(path2.join(store, manifestKey), "utf8"));
|
|
2646
|
+
if (!/^sha256:[a-f0-9]{64}$/.test(manifest.config?.digest)) throw new Error("Invalid snapshot config digest.");
|
|
2647
|
+
const configHex = manifest.config.digest.slice(7);
|
|
2648
|
+
const bytes = fs.readFileSync(path2.join(store, "blobs", configHex));
|
|
2649
|
+
if (createHash2("sha256").update(bytes).digest("hex") !== configHex) throw new Error("Snapshot config digest mismatch.");
|
|
2650
|
+
const raw = JSON.parse(bytes.toString("utf8"));
|
|
2651
|
+
const config = raw.computesdk?.kind === "sandbox-checkpoint" ? raw.computesdk : raw;
|
|
2652
|
+
const files = {};
|
|
2653
|
+
const wantedLayers = /* @__PURE__ */ new Set();
|
|
2654
|
+
const dest = new Map(destination.entries.map((e) => [e.path, e]));
|
|
2655
|
+
for (const entry of copy) {
|
|
2656
|
+
const absolute = path2.posix.join(root, entry.path);
|
|
2657
|
+
const captured = config.files[absolute];
|
|
2658
|
+
if (!captured || captured.type !== (entry.type === "directory" ? "dir" : entry.type) || captured.sha !== entry.hash || captured.link !== entry.link || (captured.mode & 511) !== entry.mode) throw new Error("Source changed during snapshot capture; rerun sync.");
|
|
2659
|
+
files[absolute] = { ...captured, mode: entry.mode };
|
|
2660
|
+
if (entry.type !== "directory") wantedLayers.add(captured.layer);
|
|
2661
|
+
let parent = path2.posix.dirname(absolute);
|
|
2662
|
+
while (parent === root || parent.startsWith(root + "/")) {
|
|
2663
|
+
const index = config.files[parent];
|
|
2664
|
+
if (!index || index.type !== "dir") throw new Error("Snapshot is missing a parent directory.");
|
|
2665
|
+
const relative2 = path2.posix.relative(root, parent);
|
|
2666
|
+
const mode = relative2 ? dest.get(relative2)?.mode : destination.config.files[destinationRoot]?.mode;
|
|
2667
|
+
files[parent] ?? (files[parent] = { ...index, mode: (mode ?? index.mode) & 511 });
|
|
2668
|
+
if (parent === root) break;
|
|
2669
|
+
parent = path2.posix.dirname(parent);
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
config.files = files;
|
|
2673
|
+
const allLayers = manifest.layers;
|
|
2674
|
+
const indexes = allLayers.map((layer, index) => wantedLayers.has(config.capture.paths.indexOf(layer.annotations["com.computesdk.checkpoint.root"])) ? index : -1).filter((index) => index >= 0);
|
|
2675
|
+
manifest.layers = indexes.map((index) => allLayers[index]);
|
|
2676
|
+
if (raw.rootfs) raw.rootfs.diff_ids = indexes.map((index) => raw.rootfs.diff_ids[index]);
|
|
2677
|
+
const selected = Buffer.from(JSON.stringify(raw));
|
|
2678
|
+
const hex = createHash2("sha256").update(selected).digest("hex");
|
|
2679
|
+
fs.writeFileSync(path2.join(store, "blobs", hex), selected, { mode: 384 });
|
|
2680
|
+
manifest.config = { ...manifest.config, digest: "sha256:" + hex, size: selected.length };
|
|
2681
|
+
const key = "manifests/selected.json";
|
|
2682
|
+
fs.writeFileSync(path2.join(store, key), JSON.stringify(manifest), { mode: 384 });
|
|
2683
|
+
return key;
|
|
2684
|
+
}
|
|
2685
|
+
async function scanLocalTree(input, exclude) {
|
|
2686
|
+
const session = new SnapshotSession();
|
|
2687
|
+
try {
|
|
2688
|
+
if (input.remove || input.directories) return session.guard({ local: input.root }, input);
|
|
2689
|
+
return (await session.scan({ local: input.root }, !!input.missing, exclude)).entries;
|
|
2690
|
+
} finally {
|
|
2691
|
+
await session.close();
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
var executeFile, ENGINE_FILE, RUNNER_FILE, endpointRoot, requireModule, SnapshotSession;
|
|
2695
|
+
var init_snapshot_engine = __esm({
|
|
2696
|
+
"src/snapshot-engine.ts"() {
|
|
2697
|
+
"use strict";
|
|
2698
|
+
init_esm_shims();
|
|
2699
|
+
init_exec();
|
|
2700
|
+
init_sync_fs();
|
|
2701
|
+
executeFile = promisify(execFile);
|
|
2702
|
+
ENGINE_FILE = fileURLToPath2(new URL("../checkpoint.cjs", import.meta.url));
|
|
2703
|
+
RUNNER_FILE = fileURLToPath2(new URL("../checkpoint-runner.cjs", import.meta.url));
|
|
2704
|
+
endpointRoot = (e) => "local" in e ? e.local : e.remote;
|
|
2705
|
+
requireModule = createRequire(import.meta.url);
|
|
2706
|
+
SnapshotSession = class {
|
|
2707
|
+
constructor(c) {
|
|
2708
|
+
this.c = c;
|
|
2709
|
+
this.temp = fs.realpathSync(fs.mkdtempSync(path2.join(tmpdir(), "compute-sync-")));
|
|
2710
|
+
this.remoteRoots = /* @__PURE__ */ new Map();
|
|
2711
|
+
}
|
|
2712
|
+
async command(id, script) {
|
|
2713
|
+
const result = await this.c.post(`/api/v1/sandboxes/${id}/commands`, {
|
|
2714
|
+
command: execCommand(["node", "--input-type=commonjs", "-e", script]),
|
|
2715
|
+
timeoutMs: 29e4
|
|
2716
|
+
});
|
|
2717
|
+
if (result.exitCode !== 0) throw new Error(`Snapshot sync failed: ${result.stderr || result.stdout || "Node.js is required in the sandbox."}`);
|
|
2718
|
+
return result.stdout;
|
|
2719
|
+
}
|
|
2720
|
+
async remoteRoot(id) {
|
|
2721
|
+
const existing = this.remoteRoots.get(id);
|
|
2722
|
+
if (existing) return existing;
|
|
2723
|
+
const root = JSON.parse(await this.command(id, `const fs=require('node:fs');console.log(JSON.stringify(fs.mkdtempSync(require('node:path').join(require('node:os').tmpdir(),'compute-sync-'))))`));
|
|
2724
|
+
if (typeof root !== "string" || !root.startsWith("/") || !path2.posix.basename(root).startsWith("compute-sync-")) throw new Error("Invalid snapshot work directory.");
|
|
2725
|
+
this.remoteRoots.set(id, root);
|
|
2726
|
+
await this.write(id, path2.posix.join(root, "checkpoint.cjs"), fs.readFileSync(ENGINE_FILE, "utf8"));
|
|
2727
|
+
await this.write(id, path2.posix.join(root, "runner.cjs"), fs.readFileSync(RUNNER_FILE, "utf8"));
|
|
2728
|
+
return root;
|
|
2729
|
+
}
|
|
2730
|
+
async write(id, file, content) {
|
|
2731
|
+
await this.c.post(`/api/v1/sandboxes/${id}/files`, { path: file, content });
|
|
2732
|
+
}
|
|
2733
|
+
async read(id, file) {
|
|
2734
|
+
const response = await this.c.get(`/api/v1/sandboxes/${id}/files`, { path: file });
|
|
2735
|
+
if (response.type !== "file" || response.content === void 0) throw new Error("Snapshot result file is unavailable.");
|
|
2736
|
+
return response.content;
|
|
2737
|
+
}
|
|
2738
|
+
async operation(id, operation, args) {
|
|
2739
|
+
const root = id ? await this.remoteRoot(id) : this.temp;
|
|
2740
|
+
const payload = path2.join(root, randomUUID() + ".args.json");
|
|
2741
|
+
const resultPath = path2.join(root, randomUUID() + ".result.json");
|
|
2742
|
+
const json = JSON.stringify({ ...args, resultPath });
|
|
2743
|
+
if (id) {
|
|
2744
|
+
await this.write(id, payload, json);
|
|
2745
|
+
const res = await this.c.post(`/api/v1/sandboxes/${id}/commands`, {
|
|
2746
|
+
command: execCommand(["node", path2.posix.join(root, "runner.cjs"), path2.posix.join(root, "checkpoint.cjs"), operation, payload]),
|
|
2747
|
+
timeoutMs: 29e4
|
|
2748
|
+
});
|
|
2749
|
+
if (res.exitCode !== 0) {
|
|
2750
|
+
let detail = res.stderr || res.stdout;
|
|
2751
|
+
try {
|
|
2752
|
+
detail = await this.read(id, resultPath);
|
|
2753
|
+
} catch {
|
|
2754
|
+
}
|
|
2755
|
+
throw new Error(`Snapshot ${operation} failed: ${detail}`);
|
|
2756
|
+
}
|
|
2757
|
+
return JSON.parse(await this.read(id, resultPath));
|
|
2758
|
+
}
|
|
2759
|
+
fs.writeFileSync(payload, json, { mode: 384 });
|
|
2760
|
+
try {
|
|
2761
|
+
await executeFile(process.execPath, [RUNNER_FILE, ENGINE_FILE, operation, payload], { timeout: 3e5, maxBuffer: 1024 * 1024 });
|
|
2762
|
+
} catch (error) {
|
|
2763
|
+
const detail = fs.existsSync(resultPath) ? fs.readFileSync(resultPath, "utf8") : error.message;
|
|
2764
|
+
throw new Error(`Snapshot ${operation} failed: ${detail}`);
|
|
2765
|
+
}
|
|
2766
|
+
return JSON.parse(fs.readFileSync(resultPath, "utf8"));
|
|
2767
|
+
}
|
|
2768
|
+
async guard(endpoint, request) {
|
|
2769
|
+
const input = { root: endpointRoot(endpoint), ...request };
|
|
2770
|
+
if ("local" in endpoint) return treeOperation(input, requireModule);
|
|
2771
|
+
const root = await this.remoteRoot(endpoint.id);
|
|
2772
|
+
const payload = path2.posix.join(root, randomUUID() + ".guard.json");
|
|
2773
|
+
const resultPath = payload + ".result";
|
|
2774
|
+
await this.write(endpoint.id, payload, JSON.stringify(input));
|
|
2775
|
+
await this.command(endpoint.id, `const fs=require('node:fs');(${treeOperation.toString()})(JSON.parse(fs.readFileSync(${JSON.stringify(payload)},'utf8')),require).then(entries=>fs.writeFileSync(${JSON.stringify(resultPath)},JSON.stringify(entries))).catch(e=>{console.error(e.message);process.exitCode=1})`);
|
|
2776
|
+
return JSON.parse(await this.read(endpoint.id, resultPath));
|
|
2777
|
+
}
|
|
2778
|
+
async scan(endpoint, destination = false, exclude) {
|
|
2779
|
+
const root = endpointRoot(endpoint);
|
|
2780
|
+
await this.guard(endpoint, { missing: destination });
|
|
2781
|
+
const result = await this.operation("id" in endpoint ? endpoint.id : void 0, "scan", {
|
|
2782
|
+
paths: [root],
|
|
2783
|
+
exclude: "local" in endpoint ? ignoredPaths(root, exclude) : ["**/.git", "**/.git/**"]
|
|
2784
|
+
});
|
|
2785
|
+
if (result.missing.length && !(destination && result.missing.length === 1 && result.missing[0] === root)) throw new Error("Snapshot scan could not read all project paths: " + result.missing.join(", "));
|
|
2786
|
+
const entries = await this.guard(endpoint, { missing: destination, destination, entries: indexEntries(result.config, root) });
|
|
2787
|
+
return { config: result.config, entries };
|
|
2788
|
+
}
|
|
2789
|
+
async diff(source, destination) {
|
|
2790
|
+
const toConfig = (entries) => ({ files: Object.fromEntries(entries.map((e) => [e.path, { type: e.type === "directory" ? "dir" : e.type, mode: e.mode, sha: e.hash, link: e.link }])) });
|
|
2791
|
+
const a = path2.join(this.temp, randomUUID() + ".json"), b = path2.join(this.temp, randomUUID() + ".json");
|
|
2792
|
+
fs.writeFileSync(a, JSON.stringify(toConfig(destination)), { mode: 384 });
|
|
2793
|
+
fs.writeFileSync(b, JSON.stringify(toConfig(source)), { mode: 384 });
|
|
2794
|
+
return (await this.operation(void 0, "diff", { a: { configPath: a }, b: { configPath: b } })).diff;
|
|
2795
|
+
}
|
|
2796
|
+
async close() {
|
|
2797
|
+
try {
|
|
2798
|
+
for (const [id, root] of this.remoteRoots) {
|
|
2799
|
+
try {
|
|
2800
|
+
await this.command(id, `require('node:fs').rmSync(${JSON.stringify(root)},{recursive:true,force:true})`);
|
|
2801
|
+
} catch {
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2804
|
+
} finally {
|
|
2805
|
+
fs.rmSync(this.temp, { recursive: true, force: true });
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
});
|
|
2811
|
+
|
|
2812
|
+
// src/index.ts
|
|
2813
|
+
init_esm_shims();
|
|
2814
|
+
import "dotenv/config";
|
|
2815
|
+
import { Command as Command4, Option as Option4 } from "commander";
|
|
2816
|
+
import * as p from "@clack/prompts";
|
|
2817
|
+
import pc14 from "picocolors";
|
|
2818
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
2819
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2820
|
+
import { dirname as dirname3, join as join9 } from "path";
|
|
2821
|
+
|
|
2822
|
+
// src/providers.ts
|
|
2823
|
+
init_esm_shims();
|
|
2824
|
+
var PROVIDER_ENV = {
|
|
2825
|
+
e2b: { authOptions: [["E2B_API_KEY"]], configKeys: { E2B_API_KEY: "apiKey" } },
|
|
2826
|
+
railway: { authOptions: [["RAILWAY_API_TOKEN"]], configKeys: { RAILWAY_API_TOKEN: "token" } },
|
|
2827
|
+
modal: {
|
|
2828
|
+
authOptions: [["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"]],
|
|
2829
|
+
configKeys: { MODAL_TOKEN_ID: "tokenId", MODAL_TOKEN_SECRET: "tokenSecret" }
|
|
2830
|
+
},
|
|
2831
|
+
vercel: {
|
|
2832
|
+
authOptions: [["VERCEL_TOKEN", "VERCEL_TEAM_ID", "VERCEL_PROJECT_ID"], ["VERCEL_OIDC_TOKEN"]],
|
|
2833
|
+
configKeys: {
|
|
2834
|
+
VERCEL_TOKEN: "token",
|
|
2835
|
+
VERCEL_TEAM_ID: "teamId",
|
|
2836
|
+
VERCEL_PROJECT_ID: "projectId"
|
|
2837
|
+
}
|
|
2838
|
+
},
|
|
2839
|
+
daytona: { authOptions: [["DAYTONA_API_KEY"]], configKeys: { DAYTONA_API_KEY: "apiKey" } },
|
|
2840
|
+
namespace: {
|
|
2841
|
+
authOptions: [["NSC_TOKEN"], ["NSC_TOKEN_FILE"]],
|
|
2842
|
+
configKeys: { NSC_TOKEN: "token", NSC_TOKEN_FILE: "tokenFile" }
|
|
2843
|
+
},
|
|
2844
|
+
blaxel: {
|
|
2845
|
+
authOptions: [["BL_API_KEY", "BL_WORKSPACE"]],
|
|
2846
|
+
configKeys: { BL_API_KEY: "apiKey", BL_WORKSPACE: "workspace" }
|
|
2847
|
+
},
|
|
2848
|
+
codesandbox: { authOptions: [["CSB_API_KEY"]], configKeys: { CSB_API_KEY: "apiKey" } },
|
|
2849
|
+
render: { authOptions: [["RENDER_API_KEY"]], configKeys: { RENDER_API_KEY: "apiKey" } }
|
|
2850
|
+
};
|
|
2851
|
+
var PROVIDER_NAMES = Object.keys(PROVIDER_ENV);
|
|
2852
|
+
function missingEnvVars(provider) {
|
|
2853
|
+
const spec = PROVIDER_ENV[provider];
|
|
2854
|
+
if (!spec) return [];
|
|
2855
|
+
let best = null;
|
|
2856
|
+
for (const option of spec.authOptions) {
|
|
2857
|
+
const missing = option.filter((name) => !process.env[name]);
|
|
2858
|
+
if (missing.length === 0) return [];
|
|
2859
|
+
if (!best || missing.length < best.length) best = missing;
|
|
2860
|
+
}
|
|
2861
|
+
return best ?? [];
|
|
2862
|
+
}
|
|
2863
|
+
function isProviderAuthComplete(provider) {
|
|
2864
|
+
return missingEnvVars(provider).length === 0;
|
|
2865
|
+
}
|
|
2866
|
+
function getProviderStatus() {
|
|
2867
|
+
const statuses = [];
|
|
2868
|
+
for (const provider of PROVIDER_NAMES) {
|
|
2869
|
+
statuses.push({
|
|
2870
|
+
name: provider,
|
|
2871
|
+
ready: isProviderAuthComplete(provider),
|
|
2872
|
+
missing: missingEnvVars(provider)
|
|
2873
|
+
});
|
|
2874
|
+
}
|
|
2875
|
+
return statuses;
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2878
|
+
// src/index.ts
|
|
2879
|
+
init_actions();
|
|
2880
|
+
|
|
2881
|
+
// src/byok.ts
|
|
2882
|
+
init_esm_shims();
|
|
2883
|
+
init_actions();
|
|
2884
|
+
init_confirm();
|
|
2885
|
+
import pc8 from "picocolors";
|
|
2886
|
+
|
|
2887
|
+
// src/rate-display.ts
|
|
2888
|
+
init_esm_shims();
|
|
2889
|
+
var SECONDS_PER_MINUTE = 60;
|
|
2890
|
+
var SECONDS_PER_HOUR = 3600;
|
|
2891
|
+
function rateAllUnits(rate) {
|
|
2892
|
+
const perSecond = rate.per === "second" ? rate.usd : rate.per === "minute" ? rate.usd / SECONDS_PER_MINUTE : rate.usd / SECONDS_PER_HOUR;
|
|
2893
|
+
return {
|
|
2894
|
+
perSecond,
|
|
2895
|
+
perMinute: perSecond * SECONDS_PER_MINUTE,
|
|
2896
|
+
perHour: perSecond * SECONDS_PER_HOUR
|
|
2897
|
+
};
|
|
2898
|
+
}
|
|
2899
|
+
function formatUsd(usd) {
|
|
2900
|
+
if (!Number.isFinite(usd)) return "$\u2014";
|
|
2901
|
+
if (usd === 0) return "$0";
|
|
2902
|
+
const decimals = Math.min(100, Math.max(0, 3 - Math.floor(Math.log10(Math.abs(usd)))));
|
|
2903
|
+
const fixed = usd.toFixed(decimals);
|
|
2904
|
+
const trimmed = fixed.includes(".") ? fixed.replace(/0+$/, "").replace(/\.$/, "") : fixed;
|
|
2905
|
+
return `$${trimmed}`;
|
|
2906
|
+
}
|
|
2907
|
+
function formatMoney(usd) {
|
|
2908
|
+
if (!Number.isFinite(usd)) return "$\u2014";
|
|
2909
|
+
const sign = usd < 0 ? "-" : "";
|
|
2910
|
+
const abs = Math.abs(usd);
|
|
2911
|
+
if (abs !== 0 && abs < 0.01) {
|
|
2912
|
+
return `${sign}${formatUsd(abs)}`;
|
|
2913
|
+
}
|
|
2914
|
+
const s = abs.toLocaleString("en-US", {
|
|
2915
|
+
minimumFractionDigits: 2,
|
|
2916
|
+
maximumFractionDigits: 2
|
|
2917
|
+
});
|
|
2918
|
+
return `${sign}$${s}`;
|
|
2919
|
+
}
|
|
2920
|
+
function formatRateAllUnits(rate) {
|
|
2921
|
+
return `${formatUsd(rate.perHour)}/hr \xB7 ${formatUsd(rate.perMinute)}/min \xB7 ${formatUsd(rate.perSecond)}/s`;
|
|
2922
|
+
}
|
|
2923
|
+
function formatUsdPer(rate) {
|
|
2924
|
+
return formatRateAllUnits(rateAllUnits(rate));
|
|
2925
|
+
}
|
|
2926
|
+
|
|
2927
|
+
// src/byok.ts
|
|
2928
|
+
init_term();
|
|
2929
|
+
var RATE_UNITS = ["second", "minute", "hour"];
|
|
2930
|
+
var MAX_RATE_USD = 1e3;
|
|
2931
|
+
function providerPath(provider, rest = "") {
|
|
2932
|
+
return `/api/v1/providers/${encodeURIComponent(provider)}${rest}`;
|
|
2933
|
+
}
|
|
2934
|
+
function keyText(key) {
|
|
2935
|
+
if (key.keyHint === null) return pc8.gray("no key");
|
|
2936
|
+
const status = key.status === "connected" ? pc8.green("connected") : key.status === "error" ? pc8.red("error") : pc8.yellow("untested");
|
|
2937
|
+
const hints = key.pairs?.length ? key.pairs.map((p2) => `${safeTerm(p2.keyHint ?? "\u2014")}@${safeTerm(p2.region)}`).join(",") : safeTerm(key.keyHint);
|
|
2938
|
+
return `${status} ${pc8.dim(hints)}`;
|
|
2939
|
+
}
|
|
2940
|
+
function rateText(p2) {
|
|
2941
|
+
return p2.customRate ? `${formatRateAllUnits(p2.customRate.rateUsd)} ${pc8.cyan("custom")}` : `${formatRateAllUnits(p2.platformRate.rateUsd)} ${pc8.dim("platform")}`;
|
|
2942
|
+
}
|
|
2943
|
+
function formatByokRow(p2) {
|
|
2944
|
+
const ready = p2.key.status === "connected";
|
|
2945
|
+
const icon = ready ? pc8.green("\u25CF") : pc8.gray("\u25CB");
|
|
2946
|
+
const name = ready ? pc8.white(safeTerm(p2.provider)) : pc8.gray(safeTerm(p2.provider));
|
|
2947
|
+
return ` ${icon} ${name} ${keyText(p2.key)} ${rateText(p2)}`;
|
|
2948
|
+
}
|
|
2949
|
+
function formatByokDetail(p2) {
|
|
2950
|
+
const lines = [
|
|
2951
|
+
`${pc8.white(safeTerm(p2.provider))} ${keyText(p2.key)}`,
|
|
2952
|
+
` regions ${p2.regions.length > 0 ? p2.regions.map(safeTerm).join(", ") : "account default"}`,
|
|
2953
|
+
` last tested ${p2.key.lastCheckedAt === null ? "\u2014" : safeTerm(p2.key.lastCheckedAt)}`,
|
|
2954
|
+
` platform rate ${formatRateAllUnits(p2.platformRate.rateUsd)}`,
|
|
2955
|
+
` custom rate ${p2.customRate ? formatRateAllUnits(p2.customRate.rateUsd) : pc8.dim("none (costs report at the platform rate)")}`
|
|
2956
|
+
];
|
|
2957
|
+
if (p2.key.status === "error" && p2.key.statusDetail) lines.push(` last error ${pc8.dim(safeTerm(p2.key.statusDetail))}`);
|
|
2958
|
+
return lines.join("\n");
|
|
2959
|
+
}
|
|
2960
|
+
function formatByokVerify(r) {
|
|
2961
|
+
const head = r.verified === true ? pc8.green("verified") : pc8.red("not verified");
|
|
2962
|
+
const detail = r.key.statusDetail ? pc8.dim(` ${safeTerm(r.key.statusDetail)}`) : "";
|
|
2963
|
+
const act = r.key.actCapable ? pc8.green(" act-capable") : "";
|
|
2964
|
+
return `${head} ${safeTerm(r.key.provider)}${act}${detail}`;
|
|
2965
|
+
}
|
|
2966
|
+
function parseRateArgs(usd, per) {
|
|
2967
|
+
const amount = Number(usd);
|
|
2968
|
+
if (usd.trim() === "" || !Number.isFinite(amount) || amount < 0 || amount > MAX_RATE_USD) {
|
|
2969
|
+
throw new Error(`<usd> must be a number from 0 to ${MAX_RATE_USD}`);
|
|
2970
|
+
}
|
|
2971
|
+
const unit = per ?? "hour";
|
|
2972
|
+
if (!RATE_UNITS.includes(unit)) throw new Error("--per must be second, minute or hour");
|
|
2973
|
+
return { usd: amount, per: unit };
|
|
2974
|
+
}
|
|
2975
|
+
function keyBody(opts) {
|
|
2976
|
+
if (opts.field !== void 0) {
|
|
2977
|
+
if (opts.key !== void 0) throw new Error("Pass either --key or --field, not both.");
|
|
2978
|
+
return { fields: parseInputs(opts.field) };
|
|
2979
|
+
}
|
|
2980
|
+
if (opts.key !== void 0) return { key: opts.key };
|
|
2981
|
+
throw new Error("Pass --key <key> or --field name=value.");
|
|
2982
|
+
}
|
|
2983
|
+
function registerByokCommands(program2) {
|
|
2984
|
+
const byok = program2.command("byok").description("The org's BYOK providers: their keys and custom rates, shared by Actions and sandboxes").configureOutput({ outputError: usageErrorOutput });
|
|
2985
|
+
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");
|
|
2986
|
+
const list2 = async (opts) => {
|
|
2987
|
+
try {
|
|
2988
|
+
const data = await (await client(opts)).get("/api/v1/providers");
|
|
2446
2989
|
output(opts, data, (d) => {
|
|
2447
2990
|
for (const p2 of d.providers) console.log(formatByokRow(p2));
|
|
2448
2991
|
});
|
|
@@ -2450,8 +2993,8 @@ function registerByokCommands(program2) {
|
|
|
2450
2993
|
fail(e, opts);
|
|
2451
2994
|
}
|
|
2452
2995
|
};
|
|
2453
|
-
common2(byok).action(
|
|
2454
|
-
common2(byok.command("list").alias("ls").description("Every provider the org may bring a key for, with key state and rate")).action(
|
|
2996
|
+
common2(byok).action(list2);
|
|
2997
|
+
common2(byok.command("list").alias("ls").description("Every provider the org may bring a key for, with key state and rate")).action(list2);
|
|
2455
2998
|
common2(
|
|
2456
2999
|
byok.command("show").description("One provider's key state, platform rate and custom rate").argument("<provider>", "provider id (e.g. tensorlake, blaxel)")
|
|
2457
3000
|
).action(async (provider, opts) => {
|
|
@@ -2532,6 +3075,9 @@ function registerByokCommands(program2) {
|
|
|
2532
3075
|
}
|
|
2533
3076
|
|
|
2534
3077
|
// src/market.ts
|
|
3078
|
+
init_esm_shims();
|
|
3079
|
+
init_actions_client();
|
|
3080
|
+
init_actions();
|
|
2535
3081
|
import pc9 from "picocolors";
|
|
2536
3082
|
var USD_RE = /^\d+(\.\d+)?([eE][+-]?\d+)?$/;
|
|
2537
3083
|
var RATE_UNITS2 = ["second", "minute", "hour"];
|
|
@@ -3258,6 +3804,8 @@ ${hints}`
|
|
|
3258
3804
|
}
|
|
3259
3805
|
|
|
3260
3806
|
// src/credits.ts
|
|
3807
|
+
init_esm_shims();
|
|
3808
|
+
init_actions();
|
|
3261
3809
|
import pc10 from "picocolors";
|
|
3262
3810
|
var MICRO_USD2 = 1e6;
|
|
3263
3811
|
function registerCreditsCommands(program2) {
|
|
@@ -3315,6 +3863,7 @@ function registerCreditsCommands(program2) {
|
|
|
3315
3863
|
}
|
|
3316
3864
|
|
|
3317
3865
|
// src/option-inheritance.ts
|
|
3866
|
+
init_esm_shims();
|
|
3318
3867
|
var GIVEN = /* @__PURE__ */ new Set(["cli", "env"]);
|
|
3319
3868
|
function inheritParentOptions(program2) {
|
|
3320
3869
|
return program2.hook("preAction", (_hooked, actionCommand) => {
|
|
@@ -3331,16 +3880,20 @@ function inheritParentOptions(program2) {
|
|
|
3331
3880
|
}
|
|
3332
3881
|
|
|
3333
3882
|
// src/sandboxes.ts
|
|
3334
|
-
|
|
3883
|
+
init_esm_shims();
|
|
3884
|
+
init_actions_client();
|
|
3885
|
+
init_actions();
|
|
3886
|
+
import * as fs4 from "fs";
|
|
3335
3887
|
import * as os from "os";
|
|
3336
|
-
import * as
|
|
3888
|
+
import * as path5 from "path";
|
|
3337
3889
|
import * as readline from "readline";
|
|
3338
|
-
import { Readable } from "stream";
|
|
3339
|
-
import { Option as Option3 } from "commander";
|
|
3890
|
+
import { Readable as Readable2 } from "stream";
|
|
3891
|
+
import { Command as Command3, Option as Option3 } from "commander";
|
|
3340
3892
|
import pc11 from "picocolors";
|
|
3341
|
-
import * as
|
|
3893
|
+
import * as tar2 from "tar";
|
|
3342
3894
|
|
|
3343
3895
|
// src/current-instance.ts
|
|
3896
|
+
init_esm_shims();
|
|
3344
3897
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
3345
3898
|
import { createHash } from "crypto";
|
|
3346
3899
|
import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
@@ -3410,89 +3963,735 @@ function withStoreLock(fn) {
|
|
|
3410
3963
|
}
|
|
3411
3964
|
}
|
|
3412
3965
|
}
|
|
3413
|
-
function setCurrentInstance(sandboxId, org2, dir = dirKey()) {
|
|
3414
|
-
withStoreLock(() => {
|
|
3415
|
-
const store = readStore();
|
|
3416
|
-
(store[dir] ?? (store[dir] = {}))[org2] = sandboxId;
|
|
3417
|
-
writeStore(store);
|
|
3966
|
+
function setCurrentInstance(sandboxId, org2, dir = dirKey()) {
|
|
3967
|
+
withStoreLock(() => {
|
|
3968
|
+
const store = readStore();
|
|
3969
|
+
(store[dir] ?? (store[dir] = {}))[org2] = sandboxId;
|
|
3970
|
+
writeStore(store);
|
|
3971
|
+
});
|
|
3972
|
+
}
|
|
3973
|
+
function clearCurrentInstance(org2, dir = dirKey()) {
|
|
3974
|
+
return withStoreLock(() => {
|
|
3975
|
+
const store = readStore();
|
|
3976
|
+
const prev = store[dir]?.[org2];
|
|
3977
|
+
if (prev === void 0) return void 0;
|
|
3978
|
+
delete store[dir][org2];
|
|
3979
|
+
if (Object.keys(store[dir]).length === 0) delete store[dir];
|
|
3980
|
+
writeStore(store);
|
|
3981
|
+
return prev;
|
|
3982
|
+
});
|
|
3983
|
+
}
|
|
3984
|
+
function readFileCurrent(org2, dir = dirKey()) {
|
|
3985
|
+
return readStore()[dir]?.[org2];
|
|
3986
|
+
}
|
|
3987
|
+
function resolveInstanceId(arg, opts, dir = dirKey()) {
|
|
3988
|
+
if (isUuid(arg)) return { id: arg, source: "argument" };
|
|
3989
|
+
const env = process.env.COMPUTE_INSTANCE;
|
|
3990
|
+
if (env) return { id: env, source: "env" };
|
|
3991
|
+
const file = readFileCurrent(orgKey(opts), dir);
|
|
3992
|
+
if (file) return { id: file, source: "file", dir };
|
|
3993
|
+
return void 0;
|
|
3994
|
+
}
|
|
3995
|
+
function shortId(id) {
|
|
3996
|
+
return id.length > 8 ? `${id.slice(0, 4)}\u2026` : id;
|
|
3997
|
+
}
|
|
3998
|
+
|
|
3999
|
+
// src/sandboxes.ts
|
|
4000
|
+
init_settings();
|
|
4001
|
+
|
|
4002
|
+
// src/sandbox-billing.ts
|
|
4003
|
+
init_esm_shims();
|
|
4004
|
+
init_term();
|
|
4005
|
+
function printTable(header, rows) {
|
|
4006
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
4007
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
|
|
4008
|
+
console.log(line(header));
|
|
4009
|
+
for (const row of rows) console.log(line(row));
|
|
4010
|
+
}
|
|
4011
|
+
function printCosts(c, customerOnly) {
|
|
4012
|
+
if (customerOnly) console.log("customer sandboxes only");
|
|
4013
|
+
printTable(
|
|
4014
|
+
["PROVIDER", "SANDBOXES", "RUNNING", "RUNNING COST", "SETTLED", "TOTAL"],
|
|
4015
|
+
[
|
|
4016
|
+
[
|
|
4017
|
+
"all",
|
|
4018
|
+
String(c.running.count + c.settled.count),
|
|
4019
|
+
String(c.running.count),
|
|
4020
|
+
formatMoney(c.running.costUsd),
|
|
4021
|
+
`${c.settled.count} \xB7 ${formatMoney(c.settled.costUsd)}`,
|
|
4022
|
+
formatMoney(c.totalUsd)
|
|
4023
|
+
],
|
|
4024
|
+
...c.byProvider.map((p2) => [
|
|
4025
|
+
safeTerm(p2.provider),
|
|
4026
|
+
String(p2.count),
|
|
4027
|
+
p2.running ? String(p2.running.count) : "\u2014",
|
|
4028
|
+
p2.running ? formatMoney(p2.running.costUsd) : "\u2014",
|
|
4029
|
+
p2.settled ? `${p2.settled.count} \xB7 ${formatMoney(p2.settled.costUsd)}` : "\u2014",
|
|
4030
|
+
formatMoney(p2.costUsd)
|
|
4031
|
+
])
|
|
4032
|
+
]
|
|
4033
|
+
);
|
|
4034
|
+
if (c.currency !== "USD") console.log(`currency: ${safeTerm(c.currency)}`);
|
|
4035
|
+
}
|
|
4036
|
+
function registerBillingCommands(group, common2, deps) {
|
|
4037
|
+
common2(
|
|
4038
|
+
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")
|
|
4039
|
+
).action(async (opts) => {
|
|
4040
|
+
try {
|
|
4041
|
+
const c = await deps.client(opts);
|
|
4042
|
+
const res = await c.get(
|
|
4043
|
+
"/api/v1/sandboxes/costs",
|
|
4044
|
+
opts.customerOnly ? { customerOnly: "true" } : void 0
|
|
4045
|
+
);
|
|
4046
|
+
deps.output(opts, res, (data) => printCosts(data, opts.customerOnly === true));
|
|
4047
|
+
} catch (e) {
|
|
4048
|
+
deps.fail(e, opts);
|
|
4049
|
+
}
|
|
4050
|
+
});
|
|
4051
|
+
}
|
|
4052
|
+
|
|
4053
|
+
// src/sync.ts
|
|
4054
|
+
init_esm_shims();
|
|
4055
|
+
init_actions();
|
|
4056
|
+
import * as fs3 from "fs";
|
|
4057
|
+
import * as path4 from "path";
|
|
4058
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
4059
|
+
import { Readable } from "stream";
|
|
4060
|
+
import { pipeline } from "stream/promises";
|
|
4061
|
+
import { setTimeout as delay } from "timers/promises";
|
|
4062
|
+
import ignore from "ignore";
|
|
4063
|
+
import * as tar from "tar";
|
|
4064
|
+
init_snapshot_engine();
|
|
4065
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
4066
|
+
|
|
4067
|
+
// src/sync-retention.ts
|
|
4068
|
+
init_esm_shims();
|
|
4069
|
+
import * as fs2 from "fs";
|
|
4070
|
+
import * as path3 from "path";
|
|
4071
|
+
import { createRequire as createRequire2 } from "module";
|
|
4072
|
+
async function publish(input, requireModule2) {
|
|
4073
|
+
const fs5 = requireModule2("node:fs");
|
|
4074
|
+
const path6 = requireModule2("node:path");
|
|
4075
|
+
const crypto = requireModule2("node:crypto");
|
|
4076
|
+
const checkUrl = (value) => {
|
|
4077
|
+
const url = new URL(value);
|
|
4078
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) throw new Error("Insecure retained snapshot upload URL.");
|
|
4079
|
+
};
|
|
4080
|
+
for (const object of input.upload.objects) {
|
|
4081
|
+
if (!/^blobs\/[a-f0-9]{64}$/.test(object.key)) throw new Error("Invalid retained snapshot object key.");
|
|
4082
|
+
checkUrl(object.url);
|
|
4083
|
+
const file = path6.join(input.store, object.key);
|
|
4084
|
+
const hash = crypto.createHash("sha256");
|
|
4085
|
+
for await (const chunk of fs5.createReadStream(file)) hash.update(chunk);
|
|
4086
|
+
if (hash.digest("hex") !== object.key.slice(6)) throw new Error("Retained snapshot blob digest mismatch.");
|
|
4087
|
+
const response2 = await fetch(object.url, {
|
|
4088
|
+
method: "PUT",
|
|
4089
|
+
redirect: "error",
|
|
4090
|
+
signal: AbortSignal.timeout(29e4),
|
|
4091
|
+
headers: { "content-length": String(fs5.statSync(file).size) },
|
|
4092
|
+
// @ts-expect-error Node streams require duplex, which DOM fetch types omit.
|
|
4093
|
+
body: fs5.createReadStream(file),
|
|
4094
|
+
duplex: "half"
|
|
4095
|
+
});
|
|
4096
|
+
if (!response2.ok) throw new Error(`Retained snapshot upload failed (${response2.status}).`);
|
|
4097
|
+
await response2.body?.cancel();
|
|
4098
|
+
}
|
|
4099
|
+
checkUrl(input.upload.manifestPutUrl);
|
|
4100
|
+
const response = await fetch(input.upload.manifestPutUrl, {
|
|
4101
|
+
method: "PUT",
|
|
4102
|
+
redirect: "error",
|
|
4103
|
+
signal: AbortSignal.timeout(29e4),
|
|
4104
|
+
headers: { "content-type": "application/json" },
|
|
4105
|
+
body: input.upload.manifestJson
|
|
4106
|
+
});
|
|
4107
|
+
if (!response.ok) throw new Error(`Retained snapshot manifest upload failed (${response.status}).`);
|
|
4108
|
+
await response.body?.cancel();
|
|
4109
|
+
}
|
|
4110
|
+
async function retainCapture(c, session, source, sourceStore, metadataStore, manifestKey, anchorId, paths) {
|
|
4111
|
+
const manifest = JSON.parse(fs2.readFileSync(path3.join(metadataStore, manifestKey), "utf8"));
|
|
4112
|
+
const registered = await c.post(`/api/v1/sandboxes/${anchorId}/sync-snapshots`, { manifest, paths });
|
|
4113
|
+
const input = { store: sourceStore, upload: registered.upload, manifest };
|
|
4114
|
+
if ("local" in source) await publish(input, createRequire2(import.meta.url));
|
|
4115
|
+
else {
|
|
4116
|
+
const payload = path3.posix.join(await session.remoteRoot(source.id), "retained-upload.json");
|
|
4117
|
+
await session.write(source.id, payload, JSON.stringify(input));
|
|
4118
|
+
await session.command(source.id, `(${publish.toString()})(JSON.parse(require('node:fs').readFileSync(${JSON.stringify(payload)},'utf8')),require).catch(e=>{console.error(e.message);process.exitCode=1})`);
|
|
4119
|
+
}
|
|
4120
|
+
const completed = await c.post(`/api/v1/snapshots/${registered.snapshot.id}/sync`, {});
|
|
4121
|
+
return { id: completed.snapshot.id, expiresAt: completed.snapshot.expiresAt };
|
|
4122
|
+
}
|
|
4123
|
+
|
|
4124
|
+
// src/sync.ts
|
|
4125
|
+
function syncEndpoint(value, opts) {
|
|
4126
|
+
const match = /^([^:]*):(\/.*)$/.exec(value);
|
|
4127
|
+
if (!match || /^[a-zA-Z]:[\\/]/.test(value)) return { local: path4.resolve(value) };
|
|
4128
|
+
const id = match[1] || resolveInstanceId(void 0, opts)?.id;
|
|
4129
|
+
if (!id || !isUuid(id)) throw new Error("Use a sandbox UUID or select one with compute new / compute use <id>.");
|
|
4130
|
+
const remote = path4.posix.normalize(match[2]);
|
|
4131
|
+
if (remote === "/" || remote.split("/").includes(".git")) throw new Error("Sync requires a project directory outside .git.");
|
|
4132
|
+
return { id, remote };
|
|
4133
|
+
}
|
|
4134
|
+
function sourceFilter(root) {
|
|
4135
|
+
const git = spawnSync3("git", ["-C", root, "rev-parse", "--show-toplevel"], { encoding: "utf8" });
|
|
4136
|
+
const filterRoot = git.status === 0 ? git.stdout.trim() : root;
|
|
4137
|
+
const prefix = path4.relative(filterRoot, root).split(path4.sep).join("/");
|
|
4138
|
+
const cache = /* @__PURE__ */ new Map();
|
|
4139
|
+
const rulesFor = (dir) => {
|
|
4140
|
+
if (cache.has(dir)) return cache.get(dir);
|
|
4141
|
+
const inherited = dir ? rulesFor(path4.posix.dirname(dir) === "." ? "" : path4.posix.dirname(dir)) : [];
|
|
4142
|
+
let rules = inherited;
|
|
4143
|
+
try {
|
|
4144
|
+
rules = [...inherited, { base: dir, rules: ignore().add(fs3.readFileSync(path4.join(filterRoot, dir, ".gitignore"), "utf8")) }];
|
|
4145
|
+
} catch (error) {
|
|
4146
|
+
if (error.code !== "ENOENT") throw error;
|
|
4147
|
+
}
|
|
4148
|
+
cache.set(dir, rules);
|
|
4149
|
+
return rules;
|
|
4150
|
+
};
|
|
4151
|
+
return (name, directory) => {
|
|
4152
|
+
if (name.split("/").includes(".git")) return true;
|
|
4153
|
+
name = prefix ? prefix + "/" + name : name;
|
|
4154
|
+
const parent = path4.posix.dirname(name);
|
|
4155
|
+
let ignored = false;
|
|
4156
|
+
for (const { base, rules } of rulesFor(parent === "." ? "" : parent)) {
|
|
4157
|
+
const relative2 = (base ? name.slice(base.length + 1) : name) + (directory ? "/" : "");
|
|
4158
|
+
const result = rules.test(relative2);
|
|
4159
|
+
if (result.ignored) ignored = true;
|
|
4160
|
+
if (result.unignored) ignored = false;
|
|
4161
|
+
}
|
|
4162
|
+
return ignored;
|
|
4163
|
+
};
|
|
4164
|
+
}
|
|
4165
|
+
async function planSync(session, source, destination, remove, excluded = () => false) {
|
|
4166
|
+
const difference = await session.diff(source, destination);
|
|
4167
|
+
const changes = /* @__PURE__ */ new Set([...difference.added, ...difference.changed.map((e) => e.path)]);
|
|
4168
|
+
const deleted = new Set(difference.deleted);
|
|
4169
|
+
const src = new Map(source.map((e) => [e.path, e]));
|
|
4170
|
+
const dst = new Map(destination.map((e) => [e.path, e]));
|
|
4171
|
+
const copy = [];
|
|
4172
|
+
for (const entry of source) {
|
|
4173
|
+
const previous = dst.get(entry.path);
|
|
4174
|
+
if (previous && previous.type !== entry.type) throw new Error(`Sync type conflict at ${entry.path}; move or remove the destination entry first.`);
|
|
4175
|
+
if (changes.has(entry.path) && (!previous || entry.type !== "directory")) {
|
|
4176
|
+
if (previous?.links && previous.links > 1) throw new Error(`Sync cannot overwrite a hard-linked destination file: ${entry.path}. Move or unlink it first.`);
|
|
4177
|
+
copy.push(entry);
|
|
4178
|
+
}
|
|
4179
|
+
}
|
|
4180
|
+
const ignoredPaths2 = destination.filter((e) => excluded(e.path, e.type === "directory")).map((e) => e.path);
|
|
4181
|
+
const protectedPaths = destination.filter((e) => e.protected || excluded(e.path, e.type === "directory")).map((e) => e.path);
|
|
4182
|
+
const removed = remove ? destination.filter((e) => !e.protected && deleted.has(e.path) && !src.has(e.path) && !ignoredPaths2.some((p2) => e.path === p2 || e.path.startsWith(p2 + "/")) && !protectedPaths.some((p2) => p2.startsWith(e.path + "/"))) : [];
|
|
4183
|
+
removed.sort((a, b) => b.path.split("/").length - a.path.split("/").length || b.path.localeCompare(a.path));
|
|
4184
|
+
return { copy, remove: removed };
|
|
4185
|
+
}
|
|
4186
|
+
function transferUrl(raw) {
|
|
4187
|
+
const url = new URL(raw);
|
|
4188
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) throw new Error("Insecure sync transfer URL.");
|
|
4189
|
+
return raw;
|
|
4190
|
+
}
|
|
4191
|
+
async function download(c, source, target) {
|
|
4192
|
+
const created = await c.post(`/api/v1/sandboxes/${source.id}/transfers`, { direction: "download", path: source.remote });
|
|
4193
|
+
const response = await fetch(transferUrl(created.downloadUrl), { redirect: "error" });
|
|
4194
|
+
if (!response.ok || !response.body) throw new Error(`Sync download failed (${response.status}).`);
|
|
4195
|
+
const file = path4.join(target, "source.tar.gz");
|
|
4196
|
+
await pipeline(Readable.fromWeb(response.body), fs3.createWriteStream(file, { mode: 384 }));
|
|
4197
|
+
const wrapper = path4.posix.basename(source.remote);
|
|
4198
|
+
const validate = (name, entry) => {
|
|
4199
|
+
const parts = name.replace(/\/$/, "").split("/");
|
|
4200
|
+
if (parts[0] !== wrapper || parts.some((p2) => p2 === ".." || p2 === "" || p2 === ".") || name.includes("\\")) throw new Error("Unsafe sync archive entry.");
|
|
4201
|
+
if (parts.includes(".git")) return false;
|
|
4202
|
+
if (!["File", "Directory"].includes(entry.type ?? "")) throw new Error("Unsupported sync archive entry.");
|
|
4203
|
+
return true;
|
|
4204
|
+
};
|
|
4205
|
+
let invalid;
|
|
4206
|
+
await tar.list({ file, onReadEntry: (entry) => {
|
|
4207
|
+
try {
|
|
4208
|
+
validate(entry.path, entry);
|
|
4209
|
+
} catch (error) {
|
|
4210
|
+
invalid = error;
|
|
4211
|
+
}
|
|
4212
|
+
entry.resume();
|
|
4213
|
+
} });
|
|
4214
|
+
if (invalid) throw invalid;
|
|
4215
|
+
const unpacked = path4.join(target, "unpacked");
|
|
4216
|
+
fs3.mkdirSync(unpacked);
|
|
4217
|
+
await tar.extract({ file, cwd: unpacked, filter: (name, entry) => validate(name, entry), strict: true });
|
|
4218
|
+
return path4.join(unpacked, wrapper);
|
|
4219
|
+
}
|
|
4220
|
+
async function upload(c, destination, root, entries, temp) {
|
|
4221
|
+
if (!entries.length) return;
|
|
4222
|
+
const archive = path4.join(temp, "changes.tar.gz");
|
|
4223
|
+
await tar.create({ file: archive, gzip: true, cwd: root, noDirRecurse: true, portable: true }, entries.map((e) => e.path));
|
|
4224
|
+
const created = await c.post(`/api/v1/sandboxes/${destination.id}/transfers`, { direction: "upload", path: destination.remote });
|
|
4225
|
+
const response = await fetch(transferUrl(created.uploadUrl), {
|
|
4226
|
+
method: "PUT",
|
|
4227
|
+
redirect: "error",
|
|
4228
|
+
headers: { "content-type": "application/gzip", "content-length": String(fs3.statSync(archive).size) },
|
|
4229
|
+
// @ts-expect-error Node fetch accepts a web stream with duplex.
|
|
4230
|
+
body: Readable.toWeb(fs3.createReadStream(archive)),
|
|
4231
|
+
duplex: "half"
|
|
4232
|
+
});
|
|
4233
|
+
if (!response.ok) throw new Error(`Sync upload failed (${response.status}).`);
|
|
4234
|
+
await c.post(`/api/v1/sandboxes/${destination.id}/transfers/${created.transferId}/complete`, {});
|
|
4235
|
+
}
|
|
4236
|
+
async function syncOnce(c, source, destination, opts) {
|
|
4237
|
+
if ("local" in source && "local" in destination) throw new Error("Sync requires at least one sandbox endpoint ([id]:/path).");
|
|
4238
|
+
if ("id" in source && "id" in destination && source.id.toLowerCase() === destination.id.toLowerCase() && (source.remote === destination.remote || source.remote.startsWith(destination.remote + "/") || destination.remote.startsWith(source.remote + "/"))) throw new Error("Source and destination sync directories must not overlap.");
|
|
4239
|
+
const session = new SnapshotSession(c);
|
|
4240
|
+
try {
|
|
4241
|
+
const excluded = "local" in source ? sourceFilter(source.local) : () => false;
|
|
4242
|
+
const src = await session.scan(source, false, "local" in source ? excluded : void 0);
|
|
4243
|
+
const dst = await session.scan(destination, true);
|
|
4244
|
+
const plan = await planSync(session, src.entries, dst.entries, !!opts.delete, excluded);
|
|
4245
|
+
if (opts.dryRun) return plan;
|
|
4246
|
+
if (!plan.copy.length && !plan.remove.length) {
|
|
4247
|
+
await session.guard(destination, { missing: true, directories: [] });
|
|
4248
|
+
return plan;
|
|
4249
|
+
}
|
|
4250
|
+
if (plan.copy.length) {
|
|
4251
|
+
const sourceRoot = endpointRoot(source);
|
|
4252
|
+
const captureRoot = "id" in source ? await session.remoteRoot(source.id) : session.temp;
|
|
4253
|
+
const sourceStore = path4.posix.join(captureRoot, "store");
|
|
4254
|
+
const checkpointId = randomUUID2();
|
|
4255
|
+
const capture = await session.operation("id" in source ? source.id : void 0, "capture", {
|
|
4256
|
+
checkpointId,
|
|
4257
|
+
paths: [sourceRoot, ...src.entries.filter((e) => e.type === "directory" && !e.path.includes("/")).map((e) => path4.posix.join(sourceRoot, e.path))],
|
|
4258
|
+
exclude: "local" in source ? ignoredPaths(source.local, excluded) : ["**/.git", "**/.git/**"],
|
|
4259
|
+
store: { kind: "fs", root: sourceStore }
|
|
4260
|
+
});
|
|
4261
|
+
if (capture.missing?.length) throw new Error("Source changed during snapshot capture.");
|
|
4262
|
+
if (capture.manifestKey !== `manifests/${checkpointId}.json`) throw new Error("Invalid snapshot manifest key.");
|
|
4263
|
+
const store = "local" in source ? sourceStore : path4.join(session.temp, "metadata");
|
|
4264
|
+
if ("id" in source) {
|
|
4265
|
+
fs3.mkdirSync(path4.join(store, "manifests"), { recursive: true });
|
|
4266
|
+
fs3.mkdirSync(path4.join(store, "blobs"));
|
|
4267
|
+
const manifestText = await session.read(source.id, path4.posix.join(sourceStore, capture.manifestKey));
|
|
4268
|
+
const metadata = JSON.parse(manifestText);
|
|
4269
|
+
if (!/^sha256:[a-f0-9]{64}$/.test(metadata.config?.digest)) throw new Error("Invalid snapshot config digest.");
|
|
4270
|
+
fs3.writeFileSync(path4.join(store, capture.manifestKey), manifestText);
|
|
4271
|
+
fs3.writeFileSync(path4.join(store, "blobs", metadata.config.digest.slice(7)), await session.read(source.id, path4.posix.join(sourceStore, "blobs", metadata.config.digest.slice(7))));
|
|
4272
|
+
}
|
|
4273
|
+
plan.snapshot = await retainCapture(c, session, source, sourceStore, store, capture.manifestKey, "id" in source ? source.id : destination.id, [sourceRoot]);
|
|
4274
|
+
const manifest = selectSnapshot(store, capture.manifestKey, sourceRoot, plan.copy, dst, endpointRoot(destination));
|
|
4275
|
+
let bundle = path4.join(session.temp, "bundle");
|
|
4276
|
+
fs3.mkdirSync(path4.join(bundle, "blobs"), { recursive: true });
|
|
4277
|
+
fs3.mkdirSync(path4.join(bundle, "manifests"));
|
|
4278
|
+
const selected = JSON.parse(fs3.readFileSync(path4.join(store, manifest), "utf8"));
|
|
4279
|
+
const refs = [selected.config, ...selected.layers];
|
|
4280
|
+
const entries = [
|
|
4281
|
+
{ path: "blobs", type: "directory", mode: 448 },
|
|
4282
|
+
{ path: "manifests", type: "directory", mode: 448 },
|
|
4283
|
+
{ path: manifest, type: "file", mode: 384 }
|
|
4284
|
+
];
|
|
4285
|
+
fs3.copyFileSync(path4.join(store, manifest), path4.join(bundle, manifest));
|
|
4286
|
+
for (const ref of refs) {
|
|
4287
|
+
if (!/^sha256:[a-f0-9]{64}$/.test(ref.digest)) throw new Error("Invalid snapshot blob digest.");
|
|
4288
|
+
const relative2 = "blobs/" + ref.digest.slice(7);
|
|
4289
|
+
if ("local" in source || ref === selected.config) fs3.copyFileSync(path4.join(store, relative2), path4.join(bundle, relative2));
|
|
4290
|
+
entries.push({ path: relative2, type: "file", mode: 384 });
|
|
4291
|
+
}
|
|
4292
|
+
if ("id" in source) {
|
|
4293
|
+
const remoteBundle = path4.posix.join(captureRoot, "selected-store");
|
|
4294
|
+
const layers = refs.slice(1).map((ref) => ref.digest.slice(7));
|
|
4295
|
+
const layerList = path4.posix.join(captureRoot, "selected-layers.json");
|
|
4296
|
+
await session.write(source.id, layerList, JSON.stringify(layers));
|
|
4297
|
+
await session.command(source.id, `const fs=require('node:fs'),p=require('node:path'),dest=${JSON.stringify(remoteBundle)},src=${JSON.stringify(sourceStore)};fs.mkdirSync(p.join(dest,'blobs'),{recursive:true});fs.mkdirSync(p.join(dest,'manifests'));for(const hex of JSON.parse(fs.readFileSync(${JSON.stringify(layerList)},'utf8')))fs.copyFileSync(p.join(src,'blobs',hex),p.join(dest,'blobs',hex));`);
|
|
4298
|
+
await session.write(source.id, path4.posix.join(remoteBundle, manifest), fs3.readFileSync(path4.join(bundle, manifest), "utf8"));
|
|
4299
|
+
const configFile = "blobs/" + selected.config.digest.slice(7);
|
|
4300
|
+
await session.write(source.id, path4.posix.join(remoteBundle, configFile), fs3.readFileSync(path4.join(bundle, configFile), "utf8"));
|
|
4301
|
+
bundle = await download(c, { id: source.id, remote: remoteBundle }, session.temp);
|
|
4302
|
+
}
|
|
4303
|
+
let restoreStore = bundle;
|
|
4304
|
+
if ("id" in destination) {
|
|
4305
|
+
restoreStore = path4.posix.join(await session.remoteRoot(destination.id), "bundle");
|
|
4306
|
+
await session.guard({ id: destination.id, remote: restoreStore }, { missing: true, directories: entries.filter((e) => e.type === "directory") });
|
|
4307
|
+
await upload(c, { id: destination.id, remote: restoreStore }, bundle, entries, session.temp);
|
|
4308
|
+
}
|
|
4309
|
+
const current = await session.scan(destination, true);
|
|
4310
|
+
if (JSON.stringify(current.entries) !== JSON.stringify(dst.entries)) throw new Error("Destination changed during sync; rerun to try again.");
|
|
4311
|
+
await session.guard(destination, { missing: true, directories: plan.copy.filter((e) => e.type === "directory") });
|
|
4312
|
+
const restored = await session.operation("id" in destination ? destination.id : void 0, "restore", {
|
|
4313
|
+
checkpointId: "selected",
|
|
4314
|
+
manifestUrl: void 0,
|
|
4315
|
+
// The engine reads the selected manifest from its fs object store.
|
|
4316
|
+
store: { kind: "fs", root: restoreStore },
|
|
4317
|
+
destDir: endpointRoot(destination),
|
|
4318
|
+
strictArch: false
|
|
4319
|
+
});
|
|
4320
|
+
if (restored.failures.length) throw new Error("Snapshot restore was incomplete.");
|
|
4321
|
+
}
|
|
4322
|
+
if (plan.remove.length) {
|
|
4323
|
+
await session.guard(destination, { remove: plan.remove });
|
|
4324
|
+
}
|
|
4325
|
+
return plan;
|
|
4326
|
+
} finally {
|
|
4327
|
+
await session.close();
|
|
4328
|
+
}
|
|
4329
|
+
}
|
|
4330
|
+
function printSync(plan, opts) {
|
|
4331
|
+
const result = { dryRun: !!opts.dryRun, copied: plan.copy.map((e) => e.path), deleted: plan.remove.map((e) => e.path), ...plan.snapshot ? { snapshot: plan.snapshot } : {} };
|
|
4332
|
+
if (opts.json) {
|
|
4333
|
+
console.log(JSON.stringify(result));
|
|
4334
|
+
return;
|
|
4335
|
+
}
|
|
4336
|
+
output(opts, result, () => {
|
|
4337
|
+
if (opts.dryRun) {
|
|
4338
|
+
for (const entry of plan.copy) console.log(`copy ${safeTerm(entry.path)}`);
|
|
4339
|
+
for (const entry of plan.remove) console.log(`delete ${safeTerm(entry.path)}`);
|
|
4340
|
+
}
|
|
4341
|
+
if (plan.snapshot) console.log(`Snapshot ${plan.snapshot.id} retained until ${plan.snapshot.expiresAt}.`);
|
|
4342
|
+
console.log(`${opts.dryRun ? "Would sync" : "Synced"} ${plan.copy.length} entries; ${plan.remove.length} deleted${opts.dryRun ? " (dry run)" : ""}.`);
|
|
4343
|
+
});
|
|
4344
|
+
}
|
|
4345
|
+
function registerSyncCommand(program2) {
|
|
4346
|
+
program2.command("sync <source> <destination>").description("One-way directory sync: local paths or [sandbox-id]:/path (empty ID selects the current sandbox)").option("--delete", "delete destination-only entries, preserving .git and ignored local source paths").option("--dry-run", "show changes without modifying the destination").option("--watch", "repeat one-way sync every 2 seconds until interrupted").option("--api-key <key>").option("--base-url <url>").option("--org <slug>").option("--allow-untrusted-host").option("--json", "print a JSON result per sync pass (JSON Lines with --watch)").action(async (src, dst, opts) => {
|
|
4347
|
+
const stop = new AbortController();
|
|
4348
|
+
const interrupt = () => stop.abort();
|
|
4349
|
+
try {
|
|
4350
|
+
if (opts.watch && opts.dryRun) throw new Error("--watch and --dry-run cannot be combined.");
|
|
4351
|
+
const source = syncEndpoint(src, opts);
|
|
4352
|
+
const destination = syncEndpoint(dst, opts);
|
|
4353
|
+
const c = await client(opts);
|
|
4354
|
+
if (opts.watch && !opts.json) console.error("Watching for changes (one-way sync, every 2 seconds). Press Ctrl-C to stop.");
|
|
4355
|
+
if (opts.watch) {
|
|
4356
|
+
process.on("SIGINT", interrupt);
|
|
4357
|
+
process.on("SIGTERM", interrupt);
|
|
4358
|
+
}
|
|
4359
|
+
do {
|
|
4360
|
+
const plan = await syncOnce(c, source, destination, opts);
|
|
4361
|
+
if (!opts.watch || plan.copy.length || plan.remove.length) printSync(plan, opts);
|
|
4362
|
+
if (!opts.watch || stop.signal.aborted) break;
|
|
4363
|
+
try {
|
|
4364
|
+
await delay(2e3, void 0, { signal: stop.signal });
|
|
4365
|
+
} catch {
|
|
4366
|
+
break;
|
|
4367
|
+
}
|
|
4368
|
+
} while (!stop.signal.aborted);
|
|
4369
|
+
} catch (error) {
|
|
4370
|
+
fail(error, opts);
|
|
4371
|
+
} finally {
|
|
4372
|
+
process.removeListener("SIGINT", interrupt);
|
|
4373
|
+
process.removeListener("SIGTERM", interrupt);
|
|
4374
|
+
}
|
|
4375
|
+
});
|
|
4376
|
+
}
|
|
4377
|
+
|
|
4378
|
+
// src/sandboxes.ts
|
|
4379
|
+
init_sync_fs();
|
|
4380
|
+
|
|
4381
|
+
// src/onboarding.ts
|
|
4382
|
+
init_esm_shims();
|
|
4383
|
+
init_actions_client();
|
|
4384
|
+
init_actions();
|
|
4385
|
+
import { loadCredentials } from "@benchsdk/cli";
|
|
4386
|
+
|
|
4387
|
+
// src/login.ts
|
|
4388
|
+
init_esm_shims();
|
|
4389
|
+
import { createHash as createHash3 } from "crypto";
|
|
4390
|
+
import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5, renameSync as renameSync2, rmSync as rmSync3, readdirSync as readdirSync2 } from "fs";
|
|
4391
|
+
import { homedir as homedir2 } from "os";
|
|
4392
|
+
import { join as join6 } from "path";
|
|
4393
|
+
import { spawn } from "child_process";
|
|
4394
|
+
import { setTimeout as delay2 } from "timers/promises";
|
|
4395
|
+
import {
|
|
4396
|
+
BENCH_OAUTH_CLIENT_ID,
|
|
4397
|
+
BENCH_OAUTH_SCOPE,
|
|
4398
|
+
getMe,
|
|
4399
|
+
saveCredentials,
|
|
4400
|
+
setActiveOrganization
|
|
4401
|
+
} from "@benchsdk/cli";
|
|
4402
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL3, isSecurePlatformTransport as isSecurePlatformTransport3, isTrustedPlatformHost as isTrustedPlatformHost3 } from "@computesdk/platform";
|
|
4403
|
+
|
|
4404
|
+
// src/session.ts
|
|
4405
|
+
init_esm_shims();
|
|
4406
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL2, isSecurePlatformTransport as isSecurePlatformTransport2, isTrustedPlatformHost as isTrustedPlatformHost2 } from "@computesdk/platform";
|
|
4407
|
+
|
|
4408
|
+
// src/net.ts
|
|
4409
|
+
init_esm_shims();
|
|
4410
|
+
function isFetchFailure(error) {
|
|
4411
|
+
return error instanceof TypeError && /fetch failed/i.test(error.message);
|
|
4412
|
+
}
|
|
4413
|
+
function describeFetchFailure(error, url) {
|
|
4414
|
+
let target = url;
|
|
4415
|
+
try {
|
|
4416
|
+
const parsed = new URL(url);
|
|
4417
|
+
target = `${parsed.origin}${parsed.pathname}`;
|
|
4418
|
+
} catch {
|
|
4419
|
+
}
|
|
4420
|
+
const cause = error.cause;
|
|
4421
|
+
const described = new TypeError(`fetch failed (${target})${cause instanceof Error ? `: ${cause.message}` : ""}`);
|
|
4422
|
+
described.cause = cause;
|
|
4423
|
+
return described;
|
|
4424
|
+
}
|
|
4425
|
+
function requestUrl(input) {
|
|
4426
|
+
if (typeof input === "string") return input;
|
|
4427
|
+
if (input instanceof URL) return input.href;
|
|
4428
|
+
return input.url;
|
|
4429
|
+
}
|
|
4430
|
+
function withFetchFailureContext(fetchImpl) {
|
|
4431
|
+
return async (input, init) => {
|
|
4432
|
+
try {
|
|
4433
|
+
return await fetchImpl(input, init);
|
|
4434
|
+
} catch (error) {
|
|
4435
|
+
if (isFetchFailure(error)) throw describeFetchFailure(error, requestUrl(input));
|
|
4436
|
+
throw error;
|
|
4437
|
+
}
|
|
4438
|
+
};
|
|
4439
|
+
}
|
|
4440
|
+
|
|
4441
|
+
// src/session.ts
|
|
4442
|
+
function envBaseUrl(env = process.env) {
|
|
4443
|
+
return env.COMPUTE_PLATFORM_URL || env.BENCHMARKS_PLATFORM_URL || void 0;
|
|
4444
|
+
}
|
|
4445
|
+
function assertComputeKeyDestination(baseUrl) {
|
|
4446
|
+
const url = baseUrl.replace(/\/+$/, "");
|
|
4447
|
+
if (!isTrustedPlatformHost2(url)) {
|
|
4448
|
+
throw new Error(
|
|
4449
|
+
`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.`
|
|
4450
|
+
);
|
|
4451
|
+
}
|
|
4452
|
+
if (!isSecurePlatformTransport2(url)) {
|
|
4453
|
+
throw new Error(`Refusing to send COMPUTE_API_KEY over plaintext HTTP to ${url}; use https://.`);
|
|
4454
|
+
}
|
|
4455
|
+
}
|
|
4456
|
+
function benchAuthOverrides(opts = {}, env = process.env) {
|
|
4457
|
+
const baseUrl = opts.baseUrl ?? envBaseUrl(env);
|
|
4458
|
+
const apiKey = env.COMPUTE_API_KEY || void 0;
|
|
4459
|
+
if (apiKey) assertComputeKeyDestination(baseUrl ?? DEFAULT_BASE_URL2);
|
|
4460
|
+
return { baseUrl, apiKey };
|
|
4461
|
+
}
|
|
4462
|
+
async function benchAuth(opts = {}) {
|
|
4463
|
+
const { resolveAuth } = await import("@benchsdk/cli");
|
|
4464
|
+
return resolveAuth(benchAuthOverrides(opts));
|
|
4465
|
+
}
|
|
4466
|
+
function errorReason(body) {
|
|
4467
|
+
if (typeof body !== "string" || body === "") return void 0;
|
|
4468
|
+
try {
|
|
4469
|
+
const parsed = JSON.parse(body);
|
|
4470
|
+
const reason = parsed.message ?? parsed.error;
|
|
4471
|
+
return typeof reason === "string" ? reason : void 0;
|
|
4472
|
+
} catch {
|
|
4473
|
+
return body.slice(0, 200);
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
function httpStatus(error) {
|
|
4477
|
+
const status = error?.status;
|
|
4478
|
+
return typeof status === "number" ? status : void 0;
|
|
4479
|
+
}
|
|
4480
|
+
async function apiKeyOrganization(auth, apiKey) {
|
|
4481
|
+
const url = `${auth.apiBaseUrl}/actions/org`;
|
|
4482
|
+
let response;
|
|
4483
|
+
try {
|
|
4484
|
+
response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
|
|
4485
|
+
} catch (error) {
|
|
4486
|
+
throw isFetchFailure(error) ? describeFetchFailure(error, url) : error;
|
|
4487
|
+
}
|
|
4488
|
+
const text = await response.text();
|
|
4489
|
+
if (!response.ok) {
|
|
4490
|
+
const reason = errorReason(text);
|
|
4491
|
+
throw new Error(
|
|
4492
|
+
`This API key has no user identity, and its organization could not be read (${response.status}${reason ? `: ${reason}` : ""}).`
|
|
4493
|
+
);
|
|
4494
|
+
}
|
|
4495
|
+
const org2 = JSON.parse(text);
|
|
4496
|
+
return { id: org2.organizationId, name: org2.name, slug: org2.slug };
|
|
4497
|
+
}
|
|
4498
|
+
async function fetchWhoami(auth) {
|
|
4499
|
+
const { getMe: getMe2 } = await import("@benchsdk/cli");
|
|
4500
|
+
try {
|
|
4501
|
+
return await getMe2(auth);
|
|
4502
|
+
} catch (error) {
|
|
4503
|
+
if (isFetchFailure(error)) throw describeFetchFailure(error, `${auth.apiBaseUrl}/me`);
|
|
4504
|
+
if (httpStatus(error) !== 401) throw error;
|
|
4505
|
+
const reason = errorReason(error.body);
|
|
4506
|
+
if (auth.apiKey && !auth.token && reason === "User credential required") {
|
|
4507
|
+
const org2 = await apiKeyOrganization(auth, auth.apiKey);
|
|
4508
|
+
return { user: null, activeOrganizationId: org2.id, organizations: [org2], credential: "api_key" };
|
|
4509
|
+
}
|
|
4510
|
+
throw new Error(
|
|
4511
|
+
`Authentication failed (401 Unauthorized)${reason ? `: ${reason}` : ""}. Check COMPUTE_API_KEY / the stored login, or run \`compute login\`.`
|
|
4512
|
+
);
|
|
4513
|
+
}
|
|
4514
|
+
}
|
|
4515
|
+
function formatWhoami(me) {
|
|
4516
|
+
const active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
4517
|
+
const who = me.user ? me.user.email ?? me.user.name ?? me.user.id : "API key (no user identity)";
|
|
4518
|
+
return [
|
|
4519
|
+
who,
|
|
4520
|
+
`active org: ${active ? `${active.slug} (${active.id})` : "\u2014"}${me.organizations.length > 1 ? " \u2014 change with `compute org use <slug>`" : ""}`
|
|
4521
|
+
];
|
|
4522
|
+
}
|
|
4523
|
+
|
|
4524
|
+
// src/login.ts
|
|
4525
|
+
function openBrowser(url) {
|
|
4526
|
+
const command2 = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
|
|
4527
|
+
const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
|
|
4528
|
+
return new Promise((resolve3) => {
|
|
4529
|
+
const child = spawn(command2, args, { stdio: "ignore", timeout: 5e3 });
|
|
4530
|
+
child.once("error", () => resolve3(false));
|
|
4531
|
+
child.once("close", (code) => resolve3(code === 0));
|
|
3418
4532
|
});
|
|
3419
4533
|
}
|
|
3420
|
-
function
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
writeStore(store);
|
|
3428
|
-
return prev;
|
|
4534
|
+
async function postForm(url, params, timeoutMs = 3e4) {
|
|
4535
|
+
const response = await fetch(url, {
|
|
4536
|
+
method: "POST",
|
|
4537
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
4538
|
+
body: new URLSearchParams(params),
|
|
4539
|
+
signal: AbortSignal.timeout(Math.max(1, Math.min(3e4, timeoutMs))),
|
|
4540
|
+
redirect: "error"
|
|
3429
4541
|
});
|
|
4542
|
+
const body = await response.json();
|
|
4543
|
+
if (!response.ok && !body.error) throw new Error(`Sign-in failed (${response.status}). Run compute login to retry.`);
|
|
4544
|
+
return body;
|
|
3430
4545
|
}
|
|
3431
|
-
function
|
|
3432
|
-
return
|
|
4546
|
+
function stateDir2() {
|
|
4547
|
+
return process.env.BENCHSDK_STATE_DIR ?? join6(homedir2(), ".benchsdk");
|
|
3433
4548
|
}
|
|
3434
|
-
function
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
4549
|
+
function pendingPath(baseUrl) {
|
|
4550
|
+
return join6(stateDir2(), `compute-login-${createHash3("sha256").update(baseUrl).digest("hex")}.json`);
|
|
4551
|
+
}
|
|
4552
|
+
function readPending(baseUrl, includeExpired = false) {
|
|
4553
|
+
try {
|
|
4554
|
+
const pending = JSON.parse(readFileSync7(pendingPath(baseUrl), "utf8"));
|
|
4555
|
+
if (pending.baseUrl === baseUrl && pending.device && Number.isFinite(pending.expiresAt) && (includeExpired || pending.expiresAt > Date.now())) return pending;
|
|
4556
|
+
} catch {
|
|
4557
|
+
}
|
|
3440
4558
|
return void 0;
|
|
3441
4559
|
}
|
|
3442
|
-
function
|
|
3443
|
-
|
|
4560
|
+
function savePending(pending) {
|
|
4561
|
+
mkdirSync4(stateDir2(), { recursive: true });
|
|
4562
|
+
const file = pendingPath(pending.baseUrl);
|
|
4563
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
4564
|
+
writeFileSync5(tmp, JSON.stringify(pending), { mode: 384 });
|
|
4565
|
+
renameSync2(tmp, file);
|
|
3444
4566
|
}
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
function printTable(header, rows) {
|
|
3448
|
-
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
|
|
3449
|
-
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
|
|
3450
|
-
console.log(line(header));
|
|
3451
|
-
for (const row of rows) console.log(line(row));
|
|
4567
|
+
function removePending(baseUrl, deviceCode) {
|
|
4568
|
+
if (readPending(baseUrl, true)?.device.device_code === deviceCode) rmSync3(pendingPath(baseUrl), { force: true });
|
|
3452
4569
|
}
|
|
3453
|
-
function
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
`${c.settled.count} \xB7 ${formatMoney(c.settled.costUsd)}`,
|
|
3464
|
-
formatMoney(c.totalUsd)
|
|
3465
|
-
],
|
|
3466
|
-
...c.byProvider.map((p2) => [
|
|
3467
|
-
safeTerm(p2.provider),
|
|
3468
|
-
String(p2.count),
|
|
3469
|
-
p2.running ? String(p2.running.count) : "\u2014",
|
|
3470
|
-
p2.running ? formatMoney(p2.running.costUsd) : "\u2014",
|
|
3471
|
-
p2.settled ? `${p2.settled.count} \xB7 ${formatMoney(p2.settled.costUsd)}` : "\u2014",
|
|
3472
|
-
formatMoney(p2.costUsd)
|
|
3473
|
-
])
|
|
3474
|
-
]
|
|
3475
|
-
);
|
|
3476
|
-
if (c.currency !== "USD") console.log(`currency: ${safeTerm(c.currency)}`);
|
|
4570
|
+
function clearPendingLogins() {
|
|
4571
|
+
let files;
|
|
4572
|
+
try {
|
|
4573
|
+
files = readdirSync2(stateDir2());
|
|
4574
|
+
} catch {
|
|
4575
|
+
return;
|
|
4576
|
+
}
|
|
4577
|
+
for (const file of files) {
|
|
4578
|
+
if (/^compute-login-[a-f0-9]{64}\.json$/.test(file)) rmSync3(join6(stateDir2(), file), { force: true });
|
|
4579
|
+
}
|
|
3477
4580
|
}
|
|
3478
|
-
function
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
4581
|
+
async function login(options = {}) {
|
|
4582
|
+
const baseUrl = (options.baseUrl || envBaseUrl() || DEFAULT_BASE_URL3).replace(/\/+$/, "").replace(/\/api\/v1$/, "");
|
|
4583
|
+
if (!isTrustedPlatformHost3(baseUrl) || !isSecurePlatformTransport3(baseUrl)) {
|
|
4584
|
+
throw new Error("Sign in against a trusted ComputeSDK HTTPS host (or localhost for development).");
|
|
4585
|
+
}
|
|
4586
|
+
const resource = `${baseUrl}/api/v1`;
|
|
4587
|
+
const authUrl = `${baseUrl}/api/auth`;
|
|
4588
|
+
const pending = options.new ? void 0 : readPending(baseUrl);
|
|
4589
|
+
if (options.json && options.wait && !pending) {
|
|
4590
|
+
throw new Error("No pending sign-in. Run compute login --json first to get the sign-in URL.");
|
|
4591
|
+
}
|
|
4592
|
+
const device = pending?.device ?? await postForm(`${authUrl}/device/code`, {
|
|
4593
|
+
client_id: BENCH_OAUTH_CLIENT_ID,
|
|
4594
|
+
scope: BENCH_OAUTH_SCOPE,
|
|
4595
|
+
resource
|
|
3492
4596
|
});
|
|
4597
|
+
if (device.error) throw new Error(device.error_description || device.error);
|
|
4598
|
+
const verificationUrl = device.verification_uri_complete || device.verification_uri;
|
|
4599
|
+
if (!device.device_code || !device.user_code || !verificationUrl || !Number.isFinite(device.expires_in) || device.expires_in <= 0 || device.interval !== void 0 && (!Number.isFinite(device.interval) || device.interval <= 0)) {
|
|
4600
|
+
throw new Error("Invalid sign-in response. Run compute login to retry.");
|
|
4601
|
+
}
|
|
4602
|
+
const parsedUrl = new URL(verificationUrl);
|
|
4603
|
+
if (parsedUrl.origin !== new URL(baseUrl).origin || parsedUrl.username || parsedUrl.password) {
|
|
4604
|
+
throw new Error("The sign-in server returned an unexpected verification URL.");
|
|
4605
|
+
}
|
|
4606
|
+
const expiresAt = pending?.expiresAt ?? Date.now() + device.expires_in * 1e3;
|
|
4607
|
+
savePending({ baseUrl, device, expiresAt });
|
|
4608
|
+
if (options.json && !options.wait) {
|
|
4609
|
+
console.log(JSON.stringify({ verificationUrl, code: device.user_code, expiresAt: new Date(expiresAt).toISOString() }));
|
|
4610
|
+
return;
|
|
4611
|
+
}
|
|
4612
|
+
if (!options.json) {
|
|
4613
|
+
console.error(`Sign in to ComputeSDK: ${verificationUrl}`);
|
|
4614
|
+
console.error(`Confirm code: ${device.user_code}`);
|
|
4615
|
+
console.error("Waiting for approval. Press Ctrl-C to cancel.");
|
|
4616
|
+
if (options.browser !== false && !await openBrowser(verificationUrl)) {
|
|
4617
|
+
console.error("Could not open a browser. Open the sign-in URL above to continue.");
|
|
4618
|
+
}
|
|
4619
|
+
}
|
|
4620
|
+
let intervalMs = (device.interval ?? 5) * 1e3;
|
|
4621
|
+
while (Date.now() + intervalMs < expiresAt) {
|
|
4622
|
+
await delay2(intervalMs);
|
|
4623
|
+
const token = await postForm(`${authUrl}/oauth2/token`, {
|
|
4624
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
4625
|
+
device_code: device.device_code,
|
|
4626
|
+
client_id: BENCH_OAUTH_CLIENT_ID,
|
|
4627
|
+
resource
|
|
4628
|
+
}, expiresAt - Date.now());
|
|
4629
|
+
if (token.error === "authorization_pending") continue;
|
|
4630
|
+
if (token.error === "slow_down") {
|
|
4631
|
+
intervalMs += 5e3;
|
|
4632
|
+
device.interval = intervalMs / 1e3;
|
|
4633
|
+
savePending({ baseUrl, device, expiresAt });
|
|
4634
|
+
continue;
|
|
4635
|
+
}
|
|
4636
|
+
if (token.error === "access_denied") {
|
|
4637
|
+
removePending(baseUrl, device.device_code);
|
|
4638
|
+
throw new Error("Sign-in was denied. Run compute login to try again.");
|
|
4639
|
+
}
|
|
4640
|
+
if (token.error === "expired_token") break;
|
|
4641
|
+
if (token.error) throw new Error(token.error_description || token.error);
|
|
4642
|
+
if (!token.access_token || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {
|
|
4643
|
+
throw new Error("Invalid sign-in token response. Run compute login to retry.");
|
|
4644
|
+
}
|
|
4645
|
+
const credentials = {
|
|
4646
|
+
baseUrl,
|
|
4647
|
+
token: token.access_token,
|
|
4648
|
+
refreshToken: token.refresh_token,
|
|
4649
|
+
tokenExpiresAt: Date.now() + token.expires_in * 1e3,
|
|
4650
|
+
kind: "oauth",
|
|
4651
|
+
clientId: BENCH_OAUTH_CLIENT_ID
|
|
4652
|
+
};
|
|
4653
|
+
await saveCredentials(credentials);
|
|
4654
|
+
removePending(baseUrl, device.device_code);
|
|
4655
|
+
const auth = { ...credentials, apiBaseUrl: resource, authBaseUrl: authUrl };
|
|
4656
|
+
const me = await getMe(auth);
|
|
4657
|
+
const requestedOrg = options.org || process.env.COMPUTE_ORG;
|
|
4658
|
+
const override = requestedOrg ? me.organizations.find((o) => o.slug === requestedOrg) : void 0;
|
|
4659
|
+
if (requestedOrg && !override) {
|
|
4660
|
+
throw new Error(`Signed in, but not a member of organization ${requestedOrg}. Run compute org list.`);
|
|
4661
|
+
}
|
|
4662
|
+
let active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
4663
|
+
if (!me.activeOrganizationId && me.organizations.length === 1) {
|
|
4664
|
+
active = (await setActiveOrganization(auth, me.organizations[0].slug)).organization ?? void 0;
|
|
4665
|
+
}
|
|
4666
|
+
const effective = override ?? active;
|
|
4667
|
+
if (!effective) throw new Error("Signed in, but no active organization. Run compute org list, then compute org use <slug>.");
|
|
4668
|
+
await saveCredentials({
|
|
4669
|
+
...credentials,
|
|
4670
|
+
...active ? { orgSlug: active.slug, orgId: active.id } : {}
|
|
4671
|
+
});
|
|
4672
|
+
if (options.json) console.log(JSON.stringify({ signedIn: true, organization: effective.slug }));
|
|
4673
|
+
else console.error(`Signed in. ${override ? "Using" : "Active"} organization: ${effective.slug}.`);
|
|
4674
|
+
return;
|
|
4675
|
+
}
|
|
4676
|
+
removePending(baseUrl, device.device_code);
|
|
4677
|
+
throw new Error("Sign-in code expired. Run compute login to get a new code.");
|
|
4678
|
+
}
|
|
4679
|
+
|
|
4680
|
+
// src/onboarding.ts
|
|
4681
|
+
async function creationClient(opts) {
|
|
4682
|
+
const interactive = process.stdin.isTTY && process.stderr.isTTY && !process.env.CI && !opts.json && !opts.quiet && !opts.apiKey && !process.env.COMPUTE_API_KEY && !process.env.BENCHMARKS_PLATFORM_API_KEY && !process.env.BENCHMARKS_PLATFORM_TOKEN;
|
|
4683
|
+
const credentials = interactive ? await loadCredentials() : void 0;
|
|
4684
|
+
try {
|
|
4685
|
+
return await client(opts);
|
|
4686
|
+
} catch (error) {
|
|
4687
|
+
if (!(error instanceof PlatformClientError) || error.code !== "no_credentials" || !interactive || credentials?.token || credentials?.apiKey || credentials?.refreshToken) throw error;
|
|
4688
|
+
await login({ baseUrl: opts.baseUrl, browser: opts.browser, org: opts.org });
|
|
4689
|
+
return client(opts);
|
|
4690
|
+
}
|
|
3493
4691
|
}
|
|
3494
4692
|
|
|
3495
4693
|
// src/sandboxes.ts
|
|
4694
|
+
init_exec();
|
|
3496
4695
|
function shellQuote(arg) {
|
|
3497
4696
|
return `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
3498
4697
|
}
|
|
@@ -3600,12 +4799,18 @@ var AUTH_LEAD_OPTS = [
|
|
|
3600
4799
|
{ aliases: ["--org"], key: "org", flag: "value" },
|
|
3601
4800
|
{ aliases: ["--json"], key: "json", flag: "bool" }
|
|
3602
4801
|
];
|
|
3603
|
-
var
|
|
4802
|
+
var COMMAND_LEAD_OPTS = [
|
|
3604
4803
|
...AUTH_LEAD_OPTS,
|
|
3605
4804
|
{ aliases: ["--cwd"], key: "cwd", flag: "value" },
|
|
3606
4805
|
{ aliases: ["-e", "--env"], key: "env", flag: "repeat" },
|
|
3607
4806
|
{ aliases: ["--timeout-ms"], key: "timeoutMs", flag: "value" }
|
|
3608
4807
|
];
|
|
4808
|
+
var EXEC_LEAD_OPTS = [
|
|
4809
|
+
...COMMAND_LEAD_OPTS,
|
|
4810
|
+
{ aliases: ["--timeout"], key: "timeout", flag: "value" },
|
|
4811
|
+
{ aliases: ["--stream"], key: "stream", flag: "bool" },
|
|
4812
|
+
{ aliases: ["-d", "--detach"], key: "detach", flag: "bool" }
|
|
4813
|
+
];
|
|
3609
4814
|
var SPAWN_LEAD_OPTS = [
|
|
3610
4815
|
...AUTH_LEAD_OPTS,
|
|
3611
4816
|
{ aliases: ["-q", "--quiet"], key: "quiet", flag: "bool" },
|
|
@@ -3685,7 +4890,7 @@ function emitResult(opts, data, quietLine, render) {
|
|
|
3685
4890
|
}
|
|
3686
4891
|
output(opts, data, render);
|
|
3687
4892
|
}
|
|
3688
|
-
var NO_INSTANCE_HINT = "No
|
|
4893
|
+
var NO_INSTANCE_HINT = "No sandbox selected. Run `compute new`, pass an ID, or run `compute use <id>`.";
|
|
3689
4894
|
function resolveSandbox(argId, opts) {
|
|
3690
4895
|
const r = resolveInstanceId(argId, opts);
|
|
3691
4896
|
if (!r) throw new Error(NO_INSTANCE_HINT);
|
|
@@ -3846,8 +5051,10 @@ async function showSandboxOptions(opts) {
|
|
|
3846
5051
|
output(opts, await c.get("/api/v1/sandboxes/options"), printSandboxOptions);
|
|
3847
5052
|
}
|
|
3848
5053
|
function registerCreate(command2, { providerShorthand = false } = {}) {
|
|
3849
|
-
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");
|
|
3850
|
-
if (providerShorthand)
|
|
5054
|
+
addCreateFlags(command2).option("--no-use", "do not mark the new instance as this directory's current instance").option("--no-browser", "print the sign-in URL instead of opening a browser").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");
|
|
5055
|
+
if (providerShorthand) {
|
|
5056
|
+
command2.option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--list", "list what you can create on, with prices, instead of creating (= compute sandboxes options)");
|
|
5057
|
+
}
|
|
3851
5058
|
command2.action(async (...args) => {
|
|
3852
5059
|
const operands = providerShorthand ? args[0] : [];
|
|
3853
5060
|
const opts = args[providerShorthand ? 1 : 0];
|
|
@@ -3858,23 +5065,43 @@ function registerCreate(command2, { providerShorthand = false } = {}) {
|
|
|
3858
5065
|
return;
|
|
3859
5066
|
}
|
|
3860
5067
|
checkQuietJson(opts);
|
|
3861
|
-
const
|
|
5068
|
+
const { providers, project } = splitCreateOperands(operands);
|
|
5069
|
+
if (project) await localTree({ root: project }, sourceFilter(project));
|
|
5070
|
+
const named = shorthandProviders(providers);
|
|
3862
5071
|
if (named.length > 0) {
|
|
3863
5072
|
if (opts.provider) throw new Error("Name providers either as words/flags or with --provider, not both.");
|
|
3864
5073
|
opts.provider = named.join(",");
|
|
3865
5074
|
}
|
|
3866
5075
|
const body = buildCreateBody(opts);
|
|
3867
|
-
const c = await
|
|
5076
|
+
const c = await creationClient(opts);
|
|
3868
5077
|
if (!opts.json && !opts.quiet) await previewPlacement(c, opts);
|
|
3869
5078
|
const res = await c.post("/api/v1/sandboxes", body);
|
|
5079
|
+
let projectSync;
|
|
5080
|
+
if (project) {
|
|
5081
|
+
try {
|
|
5082
|
+
projectSync = await syncOnce(c, { local: project }, { id: res.sandbox.id, remote: "/app" }, opts);
|
|
5083
|
+
} catch (error) {
|
|
5084
|
+
let destroyed = false;
|
|
5085
|
+
try {
|
|
5086
|
+
const cleanup = await c.del(`/api/v1/sandboxes/${res.sandbox.id}`);
|
|
5087
|
+
destroyed = cleanup.sandbox.status === "destroyed";
|
|
5088
|
+
} catch {
|
|
5089
|
+
}
|
|
5090
|
+
throw new Error(`Initial sync failed for ${res.sandbox.id}: ${error instanceof Error ? error.message : String(error)}. ` + (destroyed ? "The new sandbox was destroyed." : `Cleanup unconfirmed; run compute destroy ${res.sandbox.id}.`));
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
3870
5093
|
if (opts.use !== false) {
|
|
3871
5094
|
setCurrentInstance(res.sandbox.id, orgKey(opts));
|
|
3872
5095
|
if (!opts.json && !opts.quiet) {
|
|
3873
5096
|
console.error(pc11.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));
|
|
3874
5097
|
}
|
|
3875
5098
|
}
|
|
3876
|
-
|
|
3877
|
-
|
|
5099
|
+
const detail = { ...res.sandbox, ...projectSync?.snapshot ? { syncSnapshot: projectSync.snapshot } : {} };
|
|
5100
|
+
emitResult(opts, detail, (s) => s.id, (s) => {
|
|
5101
|
+
printSandbox(s, opts.verbose);
|
|
5102
|
+
if (s.syncSnapshot) console.log(`Snapshot ${s.syncSnapshot.id} retained until ${s.syncSnapshot.expiresAt}.`);
|
|
5103
|
+
});
|
|
5104
|
+
if (!opts.json && !opts.quiet) printNextSteps(res.sandbox.id, opts, project ? "/app" : void 0);
|
|
3878
5105
|
} catch (e) {
|
|
3879
5106
|
fail(e, opts);
|
|
3880
5107
|
}
|
|
@@ -3908,13 +5135,13 @@ async function previewPlacement(c, opts) {
|
|
|
3908
5135
|
pc11.dim(`\u2192 placing on ${provider} \xB7 ${placementLane(p2.source)} \xB7 ${p2.size ?? p2.box?.sizeName ?? "custom size"} (${billedBy(p2.source, provider)}) \u2026`)
|
|
3909
5136
|
);
|
|
3910
5137
|
}
|
|
3911
|
-
function printNextSteps(id, opts) {
|
|
5138
|
+
function printNextSteps(id, opts, cwd) {
|
|
3912
5139
|
const context = `${opts.org ? ` --org ${opts.org}` : ""}${opts.baseUrl ? ` --base-url ${opts.baseUrl}` : ""}`;
|
|
5140
|
+
const target = opts.use === false || process.env.COMPUTE_INSTANCE && process.env.COMPUTE_INSTANCE !== id ? ` ${id}` : "";
|
|
3913
5141
|
const steps = [
|
|
3914
|
-
[`compute
|
|
3915
|
-
[`compute
|
|
3916
|
-
[`compute
|
|
3917
|
-
[`compute sandboxes destroy ${id}${context}`, "stop billing"]
|
|
5142
|
+
[`compute exec${target}${context}${cwd ? ` --cwd ${cwd}` : ""} echo hello`, "run your first command"],
|
|
5143
|
+
[`compute list${context}`, "see your sandboxes"],
|
|
5144
|
+
[`compute destroy${target}${context}`, "stop billing"]
|
|
3918
5145
|
];
|
|
3919
5146
|
const width = Math.max(...steps.map(([command2]) => command2.length));
|
|
3920
5147
|
console.error("");
|
|
@@ -3922,6 +5149,12 @@ function printNextSteps(id, opts) {
|
|
|
3922
5149
|
for (const [command2, does] of steps) console.error(` ${command2.padEnd(width)} ${pc11.dim(does)}`);
|
|
3923
5150
|
console.error(pc11.dim("It runs and bills until it times out or is destroyed."));
|
|
3924
5151
|
}
|
|
5152
|
+
function splitCreateOperands(operands) {
|
|
5153
|
+
const index = operands.findIndex((value) => value === "." || value === ".." || value.startsWith("./") || value.startsWith("../") || path5.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value));
|
|
5154
|
+
if (index === -1) return { providers: operands };
|
|
5155
|
+
if (index !== operands.length - 1) throw new Error("Put the local project directory after the providers: compute new e2b ./my-app.");
|
|
5156
|
+
return { providers: operands.slice(0, index), project: path5.resolve(operands[index]) };
|
|
5157
|
+
}
|
|
3925
5158
|
function shorthandProviders(operands) {
|
|
3926
5159
|
return operands.map((operand) => {
|
|
3927
5160
|
const name = operand.startsWith("--") ? operand.slice(2) : operand;
|
|
@@ -3937,9 +5170,21 @@ function registerSandboxesCommands(program2) {
|
|
|
3937
5170
|
cmd.command("create").description("Create a sandbox through your Sandboxes router (`compute sandboxes route` shows where it lands)")
|
|
3938
5171
|
);
|
|
3939
5172
|
registerCreate(
|
|
3940
|
-
program2.command("new").description("Create a sandbox
|
|
5173
|
+
program2.command("new").description("Create a sandbox; compute new e2b . creates on e2b and syncs a local project to /app").argument("[providersAndPath...]", "provider names followed by an optional local directory (e.g. e2b ./my-app)").allowUnknownOption().configureOutput({ outputError: usageErrorOutput }),
|
|
3941
5174
|
{ providerShorthand: true }
|
|
3942
5175
|
);
|
|
5176
|
+
registerSandboxOperations(cmd);
|
|
5177
|
+
const shortcuts = new Command3().enablePositionalOptions();
|
|
5178
|
+
registerSandboxOperations(shortcuts);
|
|
5179
|
+
const rootCommands = /* @__PURE__ */ new Set(["list", "get", "use", "destroy", "run", "serve", "exec", "spawn", "ps", "logs", "kill", "wait", "cp", "url"]);
|
|
5180
|
+
for (const sub of shortcuts.commands) {
|
|
5181
|
+
if (rootCommands.has(sub.name())) {
|
|
5182
|
+
sub.configureOutput({ outputError: usageErrorOutput });
|
|
5183
|
+
program2.addCommand(sub);
|
|
5184
|
+
}
|
|
5185
|
+
}
|
|
5186
|
+
}
|
|
5187
|
+
function registerSandboxOperations(cmd) {
|
|
3943
5188
|
cmd.command("options").description("List what you can create sandboxes on: managed accounts with prices per size, and your BYOK providers, in router order").option("--api-key <key>", "platform API key (or COMPUTE_API_KEY)").option("--base-url <url>", "platform base URL").option("--allow-untrusted-host", "allow non-computesdk.com base URLs").option("--json", "print the raw response").action(async (opts) => {
|
|
3944
5189
|
try {
|
|
3945
5190
|
await showSandboxOptions(opts);
|
|
@@ -4078,14 +5323,14 @@ function registerSandboxesCommands(program2) {
|
|
|
4078
5323
|
});
|
|
4079
5324
|
addCreateFlags(
|
|
4080
5325
|
cmd.command("run [command...]").description(
|
|
4081
|
-
"Create an instance, run a command on it, and tear it down. `run
|
|
5326
|
+
"Create an instance, run a command on it, and tear it down. `run <cmd>` waits and destroys; `--keep` waits and keeps; `-d` returns immediately."
|
|
4082
5327
|
)
|
|
4083
|
-
).option("--keep", "keep the instance after the command exits (it becomes this directory's current instance)").option("-d, --detach", "start the command and return immediately (instance becomes current)").option("--yes", "non-interactive: Ctrl-C destroys without asking").option("-q, --quiet", "with --detach, print only the instance ID").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (rawCommand, rawOpts) => {
|
|
5328
|
+
).option("--no-browser", "print the sign-in URL instead of opening a browser").option("--keep", "keep the instance after the command exits (it becomes this directory's current instance)").option("-d, --detach", "start the command and return immediately (instance becomes current)").option("--yes", "non-interactive: Ctrl-C destroys without asking").option("-q, --quiet", "with --detach, print only the instance ID").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (rawCommand, rawOpts) => {
|
|
4084
5329
|
let opts = rawOpts;
|
|
4085
5330
|
try {
|
|
4086
5331
|
checkQuietJson(opts);
|
|
4087
5332
|
if (opts.keep && opts.detach) throw new Error("--keep and --detach are mutually exclusive.");
|
|
4088
|
-
const lead = takeLeadingOptions(rawCommand,
|
|
5333
|
+
const lead = takeLeadingOptions(rawCommand, COMMAND_LEAD_OPTS);
|
|
4089
5334
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
4090
5335
|
const command2 = lead.command;
|
|
4091
5336
|
if (command2.length === 0) throw new Error("missing command to run");
|
|
@@ -4117,7 +5362,7 @@ function registerSandboxesCommands(program2) {
|
|
|
4117
5362
|
fail(e, opts);
|
|
4118
5363
|
}
|
|
4119
5364
|
});
|
|
4120
|
-
cmd.command("exec [sandboxId] [command...]").description("Run a
|
|
5365
|
+
cmd.command("exec [sandboxId] [command...]").description("Run a shell command or argv in a sandbox; --stream follows output, --detach returns a job ID").option("--cwd <dir>", "working directory").option("-e, --env <key=value>", "environment variable (repeatable)", (v, a) => a.concat(v), []).option("--timeout <seconds>", "command timeout in seconds (0: no command time limit)").option("--timeout-ms <ms>", "command timeout in ms (legacy spelling)").option("--stream", "print stdout and stderr while the command runs").option("-d, --detach", "start a background process and print its job ID").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").passThroughOptions().action(async (argId, rawCommand, rawOpts) => {
|
|
4121
5366
|
let opts = rawOpts;
|
|
4122
5367
|
try {
|
|
4123
5368
|
if (argId !== void 0 && !isUuid(argId)) {
|
|
@@ -4128,26 +5373,17 @@ function registerSandboxesCommands(program2) {
|
|
|
4128
5373
|
opts = mergeLeadOpts(rawOpts, lead.inline);
|
|
4129
5374
|
const command2 = lead.command;
|
|
4130
5375
|
if (command2.length === 0) throw new Error("missing command to run");
|
|
5376
|
+
execTimeout(opts);
|
|
4131
5377
|
const resolved = resolveSandbox(argId, opts);
|
|
4132
5378
|
const c = await client(opts);
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
{
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
|
|
4139
|
-
...opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}
|
|
4140
|
-
}
|
|
4141
|
-
).catch((e) => {
|
|
5379
|
+
await execute(c, resolved.id, {
|
|
5380
|
+
command: execCommand(command2),
|
|
5381
|
+
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
5382
|
+
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}
|
|
5383
|
+
}, opts).catch((e) => {
|
|
4142
5384
|
resolved.clearStale(e);
|
|
4143
5385
|
throw e;
|
|
4144
5386
|
});
|
|
4145
|
-
output(opts, res, (r) => {
|
|
4146
|
-
process.stdout.write(r.stdout);
|
|
4147
|
-
if (r.stderr) process.stderr.write(r.stderr);
|
|
4148
|
-
if (!r.stdout) console.log(`exit ${r.exitCode} (${r.durationMs}ms)`);
|
|
4149
|
-
});
|
|
4150
|
-
if (res.exitCode !== 0) process.exitCode = res.exitCode;
|
|
4151
5387
|
} catch (e) {
|
|
4152
5388
|
fail(e, opts);
|
|
4153
5389
|
}
|
|
@@ -4169,7 +5405,7 @@ function registerSandboxesCommands(program2) {
|
|
|
4169
5405
|
const res = await c.post(
|
|
4170
5406
|
`/api/v1/sandboxes/${resolved.id}/processes`,
|
|
4171
5407
|
{
|
|
4172
|
-
command: command2
|
|
5408
|
+
command: execCommand(command2),
|
|
4173
5409
|
...opts.cwd ? { cwd: opts.cwd } : {},
|
|
4174
5410
|
...opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {},
|
|
4175
5411
|
...opts.stdin ? { stdin: true } : {}
|
|
@@ -4190,7 +5426,7 @@ function registerSandboxesCommands(program2) {
|
|
|
4190
5426
|
const res = await c.get(
|
|
4191
5427
|
`/api/v1/sandboxes/${resolved.id}/processes`
|
|
4192
5428
|
);
|
|
4193
|
-
output(opts, res.processes, (
|
|
5429
|
+
output(opts, res.processes, (list2) => list2.forEach(printProcess));
|
|
4194
5430
|
} catch (e) {
|
|
4195
5431
|
fail(e, opts);
|
|
4196
5432
|
}
|
|
@@ -4253,10 +5489,10 @@ function registerSandboxesCommands(program2) {
|
|
|
4253
5489
|
data = opts.base64 ? (await readFile(opts.file)).toString("base64") : await readFile(opts.file, "utf8");
|
|
4254
5490
|
}
|
|
4255
5491
|
if (data === void 0 && !process.stdin.isTTY) {
|
|
4256
|
-
const piped = await new Promise((
|
|
5492
|
+
const piped = await new Promise((resolve3) => {
|
|
4257
5493
|
const chunks = [];
|
|
4258
5494
|
process.stdin.on("data", (chunk) => chunks.push(chunk));
|
|
4259
|
-
process.stdin.on("end", () =>
|
|
5495
|
+
process.stdin.on("end", () => resolve3(Buffer.concat(chunks)));
|
|
4260
5496
|
});
|
|
4261
5497
|
data = opts.base64 ? piped.toString("base64") : piped.toString("utf8");
|
|
4262
5498
|
}
|
|
@@ -4290,17 +5526,17 @@ function registerSandboxesCommands(program2) {
|
|
|
4290
5526
|
fail(e, opts);
|
|
4291
5527
|
}
|
|
4292
5528
|
});
|
|
4293
|
-
cmd.command("ls [pathOrSandboxId] [path]").description("List a directory (or stat a path) inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId,
|
|
5529
|
+
cmd.command("ls [pathOrSandboxId] [path]").description("List a directory (or stat a path) inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path6, opts) => {
|
|
4294
5530
|
try {
|
|
4295
5531
|
let resolved;
|
|
4296
5532
|
let p2;
|
|
4297
5533
|
if (argId !== void 0 && !isUuid(argId)) {
|
|
4298
|
-
if (
|
|
5534
|
+
if (path6 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
|
|
4299
5535
|
resolved = resolveSandbox(void 0, opts);
|
|
4300
5536
|
p2 = argId;
|
|
4301
5537
|
} else {
|
|
4302
5538
|
resolved = resolveSandbox(argId, opts);
|
|
4303
|
-
p2 =
|
|
5539
|
+
p2 = path6 ?? "/";
|
|
4304
5540
|
}
|
|
4305
5541
|
const c = await client(opts);
|
|
4306
5542
|
const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, {
|
|
@@ -4319,18 +5555,18 @@ function registerSandboxesCommands(program2) {
|
|
|
4319
5555
|
fail(e, opts);
|
|
4320
5556
|
}
|
|
4321
5557
|
});
|
|
4322
|
-
cmd.command("cat [pathOrSandboxId] [path]").description("Print a file's contents").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId,
|
|
5558
|
+
cmd.command("cat [pathOrSandboxId] [path]").description("Print a file's contents").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path6, opts) => {
|
|
4323
5559
|
try {
|
|
4324
5560
|
let resolved;
|
|
4325
5561
|
let p2;
|
|
4326
5562
|
if (argId !== void 0 && !isUuid(argId)) {
|
|
4327
|
-
if (
|
|
5563
|
+
if (path6 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
|
|
4328
5564
|
resolved = resolveSandbox(void 0, opts);
|
|
4329
5565
|
p2 = argId;
|
|
4330
5566
|
} else {
|
|
4331
5567
|
resolved = resolveSandbox(argId, opts);
|
|
4332
|
-
if (
|
|
4333
|
-
p2 =
|
|
5568
|
+
if (path6 === void 0) throw new Error("missing path");
|
|
5569
|
+
p2 = path6;
|
|
4334
5570
|
}
|
|
4335
5571
|
const c = await client(opts);
|
|
4336
5572
|
const res = await c.get(`/api/v1/sandboxes/${resolved.id}/files`, { path: p2 });
|
|
@@ -4346,18 +5582,18 @@ function registerSandboxesCommands(program2) {
|
|
|
4346
5582
|
fail(e, opts);
|
|
4347
5583
|
}
|
|
4348
5584
|
});
|
|
4349
|
-
cmd.command("write [pathOrSandboxId] [path]").description("Write a file inside the sandbox (--content or --file <local>, else stdin)").option("--content <text>", "file contents").option("--file <local>", "read contents from a local file").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId,
|
|
5585
|
+
cmd.command("write [pathOrSandboxId] [path]").description("Write a file inside the sandbox (--content or --file <local>, else stdin)").option("--content <text>", "file contents").option("--file <local>", "read contents from a local file").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path6, opts) => {
|
|
4350
5586
|
try {
|
|
4351
5587
|
let resolved;
|
|
4352
5588
|
let p2;
|
|
4353
5589
|
if (argId !== void 0 && !isUuid(argId)) {
|
|
4354
|
-
if (
|
|
5590
|
+
if (path6 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
|
|
4355
5591
|
resolved = resolveSandbox(void 0, opts);
|
|
4356
5592
|
p2 = argId;
|
|
4357
5593
|
} else {
|
|
4358
5594
|
resolved = resolveSandbox(argId, opts);
|
|
4359
|
-
if (
|
|
4360
|
-
p2 =
|
|
5595
|
+
if (path6 === void 0) throw new Error("missing path");
|
|
5596
|
+
p2 = path6;
|
|
4361
5597
|
}
|
|
4362
5598
|
let content = opts.content;
|
|
4363
5599
|
if (content === void 0 && opts.file) {
|
|
@@ -4365,11 +5601,11 @@ function registerSandboxesCommands(program2) {
|
|
|
4365
5601
|
content = await readFile(opts.file, "utf8");
|
|
4366
5602
|
}
|
|
4367
5603
|
if (content === void 0 && !process.stdin.isTTY) {
|
|
4368
|
-
content = await new Promise((
|
|
5604
|
+
content = await new Promise((resolve3) => {
|
|
4369
5605
|
let data = "";
|
|
4370
5606
|
process.stdin.setEncoding("utf8");
|
|
4371
5607
|
process.stdin.on("data", (chunk) => data += chunk);
|
|
4372
|
-
process.stdin.on("end", () =>
|
|
5608
|
+
process.stdin.on("end", () => resolve3(data));
|
|
4373
5609
|
});
|
|
4374
5610
|
}
|
|
4375
5611
|
if (content === void 0) {
|
|
@@ -4386,18 +5622,18 @@ function registerSandboxesCommands(program2) {
|
|
|
4386
5622
|
fail(e, opts);
|
|
4387
5623
|
}
|
|
4388
5624
|
});
|
|
4389
|
-
cmd.command("mkdir [pathOrSandboxId] [path]").description("Create a directory (parents included)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId,
|
|
5625
|
+
cmd.command("mkdir [pathOrSandboxId] [path]").description("Create a directory (parents included)").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path6, opts) => {
|
|
4390
5626
|
try {
|
|
4391
5627
|
let resolved;
|
|
4392
5628
|
let p2;
|
|
4393
5629
|
if (argId !== void 0 && !isUuid(argId)) {
|
|
4394
|
-
if (
|
|
5630
|
+
if (path6 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
|
|
4395
5631
|
resolved = resolveSandbox(void 0, opts);
|
|
4396
5632
|
p2 = argId;
|
|
4397
5633
|
} else {
|
|
4398
5634
|
resolved = resolveSandbox(argId, opts);
|
|
4399
|
-
if (
|
|
4400
|
-
p2 =
|
|
5635
|
+
if (path6 === void 0) throw new Error("missing path");
|
|
5636
|
+
p2 = path6;
|
|
4401
5637
|
}
|
|
4402
5638
|
const c = await client(opts);
|
|
4403
5639
|
const res = await c.post(`/api/v1/sandboxes/${resolved.id}/files`, {
|
|
@@ -4409,18 +5645,18 @@ function registerSandboxesCommands(program2) {
|
|
|
4409
5645
|
fail(e, opts);
|
|
4410
5646
|
}
|
|
4411
5647
|
});
|
|
4412
|
-
cmd.command("rm [pathOrSandboxId] [path]").description("Remove a file or directory inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId,
|
|
5648
|
+
cmd.command("rm [pathOrSandboxId] [path]").description("Remove a file or directory inside the sandbox").option("--api-key <key>").option("--base-url <url>").option("--allow-untrusted-host").option("--json", "print the raw response").action(async (argId, path6, opts) => {
|
|
4413
5649
|
try {
|
|
4414
5650
|
let resolved;
|
|
4415
5651
|
let p2;
|
|
4416
5652
|
if (argId !== void 0 && !isUuid(argId)) {
|
|
4417
|
-
if (
|
|
5653
|
+
if (path6 !== void 0) throw new Error(`"${argId}" is not a sandbox ID \u2014 expected a UUID.`);
|
|
4418
5654
|
resolved = resolveSandbox(void 0, opts);
|
|
4419
5655
|
p2 = argId;
|
|
4420
5656
|
} else {
|
|
4421
5657
|
resolved = resolveSandbox(argId, opts);
|
|
4422
|
-
if (
|
|
4423
|
-
p2 =
|
|
5658
|
+
if (path6 === void 0) throw new Error("missing path");
|
|
5659
|
+
p2 = path6;
|
|
4424
5660
|
}
|
|
4425
5661
|
const c = await client(opts);
|
|
4426
5662
|
const res = await c.del(
|
|
@@ -4460,7 +5696,7 @@ function registerSandboxesCommands(program2) {
|
|
|
4460
5696
|
const res = await c.get(
|
|
4461
5697
|
`/api/v1/sandboxes/${resolved.id}/snapshots`
|
|
4462
5698
|
);
|
|
4463
|
-
output(opts, res.snapshots, (
|
|
5699
|
+
output(opts, res.snapshots, (list2) => list2.forEach(printSnapshot));
|
|
4464
5700
|
} catch (e) {
|
|
4465
5701
|
fail(e, opts);
|
|
4466
5702
|
}
|
|
@@ -4529,12 +5765,20 @@ function printDetachSummary(sandboxId, jobId, timeoutText) {
|
|
|
4529
5765
|
function runTimeoutText(opts) {
|
|
4530
5766
|
return opts.timeoutMs ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}` : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;
|
|
4531
5767
|
}
|
|
5768
|
+
function confirmedDestroyedSandbox(result, id) {
|
|
5769
|
+
if (result?.sandbox?.status !== "destroyed") {
|
|
5770
|
+
throw new Error("Teardown was not confirmed; run compute destroy " + id);
|
|
5771
|
+
}
|
|
5772
|
+
return result.sandbox;
|
|
5773
|
+
}
|
|
4532
5774
|
async function runInstanceCommand(command2, opts) {
|
|
4533
|
-
const
|
|
4534
|
-
const
|
|
5775
|
+
const startedAt = Date.now();
|
|
5776
|
+
const body = buildCreateBody(opts);
|
|
5777
|
+
const c = await creationClient(opts);
|
|
5778
|
+
const created = await c.post("/api/v1/sandboxes", body);
|
|
4535
5779
|
const sandbox = created.sandbox;
|
|
4536
5780
|
const org2 = orgKey(opts);
|
|
4537
|
-
console.error(pc11.dim(`instance ${sandbox.id}`));
|
|
5781
|
+
if (!opts.json) console.error(pc11.dim(`instance ${sandbox.id}`));
|
|
4538
5782
|
const spawned = await c.post(
|
|
4539
5783
|
`/api/v1/sandboxes/${sandbox.id}/processes`,
|
|
4540
5784
|
{ command: command2.map(shellQuote).join(" ") }
|
|
@@ -4548,7 +5792,8 @@ async function runInstanceCommand(command2, opts) {
|
|
|
4548
5792
|
const jobId = spawned.process.jobId;
|
|
4549
5793
|
if (opts.detach) {
|
|
4550
5794
|
setCurrentInstance(sandbox.id, org2);
|
|
4551
|
-
if (opts.
|
|
5795
|
+
if (opts.json) console.log(JSON.stringify({ type: "detached", sandboxId: sandbox.id, jobId }));
|
|
5796
|
+
else if (opts.quiet) console.log(sandbox.id);
|
|
4552
5797
|
else printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
|
|
4553
5798
|
return;
|
|
4554
5799
|
}
|
|
@@ -4556,21 +5801,29 @@ async function runInstanceCommand(command2, opts) {
|
|
|
4556
5801
|
let destroyRequested = false;
|
|
4557
5802
|
let detachRequested = false;
|
|
4558
5803
|
let prompting = false;
|
|
5804
|
+
let deleted = false;
|
|
5805
|
+
let kept = false;
|
|
5806
|
+
let settledCostUsd;
|
|
5807
|
+
let cleanupError;
|
|
4559
5808
|
let printedOut = 0;
|
|
4560
5809
|
let printedErr = 0;
|
|
4561
5810
|
const flush = (p2) => {
|
|
4562
5811
|
if (prompting) return;
|
|
4563
5812
|
if (p2.stdout.length > printedOut) {
|
|
4564
|
-
|
|
5813
|
+
const data = p2.stdout.slice(printedOut);
|
|
5814
|
+
if (opts.json) console.log(JSON.stringify({ type: "stdout", data }));
|
|
5815
|
+
else process.stdout.write(data);
|
|
4565
5816
|
printedOut = p2.stdout.length;
|
|
4566
5817
|
}
|
|
4567
5818
|
if (p2.stderr.length > printedErr) {
|
|
4568
|
-
|
|
5819
|
+
const data = p2.stderr.slice(printedErr);
|
|
5820
|
+
if (opts.json) console.log(JSON.stringify({ type: "stderr", data }));
|
|
5821
|
+
else process.stderr.write(data);
|
|
4569
5822
|
printedErr = p2.stderr.length;
|
|
4570
5823
|
}
|
|
4571
5824
|
};
|
|
4572
5825
|
const onSignal = () => {
|
|
4573
|
-
if (!process.stdin.isTTY || opts.yes || prompting) {
|
|
5826
|
+
if (!process.stdin.isTTY || opts.json || opts.yes || prompting) {
|
|
4574
5827
|
if (prompting) return;
|
|
4575
5828
|
destroyRequested = true;
|
|
4576
5829
|
return;
|
|
@@ -4606,29 +5859,48 @@ async function runInstanceCommand(command2, opts) {
|
|
|
4606
5859
|
process.removeListener("SIGINT", onSignal);
|
|
4607
5860
|
process.removeListener("SIGTERM", onSignal);
|
|
4608
5861
|
if (detachRequested) {
|
|
5862
|
+
kept = true;
|
|
4609
5863
|
setCurrentInstance(sandbox.id, org2);
|
|
4610
|
-
printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
|
|
5864
|
+
if (!opts.json) printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));
|
|
4611
5865
|
} else if (opts.keep && exitCode !== null) {
|
|
5866
|
+
kept = true;
|
|
4612
5867
|
setCurrentInstance(sandbox.id, org2);
|
|
4613
|
-
if (opts.quiet) console.log(sandbox.id);
|
|
4614
|
-
else {
|
|
5868
|
+
if (!opts.json && opts.quiet) console.log(sandbox.id);
|
|
5869
|
+
else if (!opts.json) {
|
|
4615
5870
|
console.error(pc11.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));
|
|
4616
5871
|
console.log(sandbox.id);
|
|
4617
5872
|
}
|
|
4618
5873
|
} else {
|
|
4619
5874
|
try {
|
|
4620
|
-
await c.del(`/api/v1/sandboxes/${sandbox.id}`);
|
|
5875
|
+
const result = await c.del(`/api/v1/sandboxes/${sandbox.id}`);
|
|
5876
|
+
const cost = confirmedDestroyedSandbox(result, sandbox.id).cost;
|
|
5877
|
+
deleted = true;
|
|
5878
|
+
if (cost?.settled && cost.costUsd !== null && Number.isFinite(cost.costUsd)) settledCostUsd = cost.costUsd;
|
|
4621
5879
|
} catch (e) {
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
);
|
|
4625
|
-
if (exitCode === null || exitCode === 0) exitCode = 1;
|
|
5880
|
+
cleanupError = e instanceof Error ? e.message : String(e);
|
|
5881
|
+
if (!opts.json) console.error(pc11.red(`destroy failed for ${sandbox.id}: ${safeTerm(cleanupError)}`));
|
|
4626
5882
|
}
|
|
4627
5883
|
const orgNow = orgKey(opts);
|
|
4628
5884
|
if (readFileCurrent(orgNow) === sandbox.id) clearCurrentInstance(orgNow);
|
|
4629
5885
|
}
|
|
5886
|
+
const summary = {
|
|
5887
|
+
type: "summary",
|
|
5888
|
+
sandboxId: sandbox.id,
|
|
5889
|
+
jobId,
|
|
5890
|
+
exitCode,
|
|
5891
|
+
elapsedSeconds: (Date.now() - startedAt) / 1e3,
|
|
5892
|
+
provider: sandbox.placement?.box?.provider ?? sandbox.provider,
|
|
5893
|
+
deleted,
|
|
5894
|
+
kept,
|
|
5895
|
+
...cleanupError ? { cleanupError } : {},
|
|
5896
|
+
...settledCostUsd !== void 0 ? { costUsd: settledCostUsd } : {}
|
|
5897
|
+
};
|
|
5898
|
+
if (opts.json) console.log(JSON.stringify(summary));
|
|
5899
|
+
else console.error(pc11.dim(
|
|
5900
|
+
`exit ${exitCode ?? "unknown"} \xB7 ${summary.elapsedSeconds.toFixed(1)}s \xB7 ${safeTerm(summary.provider ?? "unknown provider")}` + (settledCostUsd !== void 0 ? ` \xB7 $${settledCostUsd.toFixed(4)}` : "") + ` \xB7 ${sandbox.id} ${deleted ? "deleted" : summary.kept ? "kept" : "cleanup unconfirmed"}`
|
|
5901
|
+
));
|
|
4630
5902
|
}
|
|
4631
|
-
process.exitCode = detachRequested ? 0 : exitCode ?? (destroyRequested ? 130 : 1);
|
|
5903
|
+
process.exitCode = detachRequested ? 0 : cleanupError && exitCode === 0 ? 1 : exitCode ?? (destroyRequested ? 130 : 1);
|
|
4632
5904
|
}
|
|
4633
5905
|
var SERVE_POLL_MS = 3e4;
|
|
4634
5906
|
var SERVE_DEFAULT_WAIT_MS = 12e4;
|
|
@@ -4722,10 +5994,10 @@ function assertTransferUrl(raw) {
|
|
|
4722
5994
|
}
|
|
4723
5995
|
}
|
|
4724
5996
|
function tarEntryIsSafe(p2, entry) {
|
|
4725
|
-
if (
|
|
5997
|
+
if (path5.isAbsolute(p2) || p2.split("/").includes("..")) return false;
|
|
4726
5998
|
const { type, linkpath } = entry;
|
|
4727
5999
|
if ((type === "Link" || type === "SymbolicLink") && linkpath) {
|
|
4728
|
-
if (
|
|
6000
|
+
if (path5.isAbsolute(linkpath) || linkpath.split("/").includes("..")) return false;
|
|
4729
6001
|
}
|
|
4730
6002
|
return true;
|
|
4731
6003
|
}
|
|
@@ -4772,13 +6044,13 @@ function cpProgress(total, opts) {
|
|
|
4772
6044
|
};
|
|
4773
6045
|
}
|
|
4774
6046
|
async function cpUpload(c, sandboxId, localPath, remotePath, opts) {
|
|
4775
|
-
const abs =
|
|
4776
|
-
|
|
4777
|
-
const tmpDir =
|
|
4778
|
-
const tmp =
|
|
6047
|
+
const abs = path5.resolve(localPath);
|
|
6048
|
+
fs4.statSync(abs);
|
|
6049
|
+
const tmpDir = fs4.mkdtempSync(path5.join(os.tmpdir(), "compute-cp-up-"));
|
|
6050
|
+
const tmp = path5.join(tmpDir, "archive.tar.gz");
|
|
4779
6051
|
try {
|
|
4780
|
-
await
|
|
4781
|
-
const size =
|
|
6052
|
+
await tar2.create({ gzip: true, file: tmp, cwd: path5.dirname(abs) }, [path5.basename(abs)]);
|
|
6053
|
+
const size = fs4.statSync(tmp).size;
|
|
4782
6054
|
const created = await c.post(
|
|
4783
6055
|
`/api/v1/sandboxes/${sandboxId}/transfers`,
|
|
4784
6056
|
{ direction: "upload", path: remotePath }
|
|
@@ -4787,13 +6059,13 @@ async function cpUpload(c, sandboxId, localPath, remotePath, opts) {
|
|
|
4787
6059
|
assertTransferUrl(created.uploadUrl);
|
|
4788
6060
|
const progress = cpProgress(size, opts);
|
|
4789
6061
|
try {
|
|
4790
|
-
const stream =
|
|
6062
|
+
const stream = fs4.createReadStream(tmp);
|
|
4791
6063
|
stream.on("data", (chunk) => progress.bump(typeof chunk === "string" ? chunk.length : chunk.byteLength));
|
|
4792
6064
|
const res = await fetch(created.uploadUrl, {
|
|
4793
6065
|
method: "PUT",
|
|
4794
6066
|
headers: { "content-length": String(size), "content-type": "application/gzip" },
|
|
4795
6067
|
// @ts-expect-error Readable.toWeb body is supported at runtime; DOM types lag
|
|
4796
|
-
body:
|
|
6068
|
+
body: Readable2.toWeb(stream),
|
|
4797
6069
|
duplex: "half"
|
|
4798
6070
|
});
|
|
4799
6071
|
if (!res.ok) throw new Error(`upload failed: HTTP ${res.status}`);
|
|
@@ -4805,7 +6077,7 @@ async function cpUpload(c, sandboxId, localPath, remotePath, opts) {
|
|
|
4805
6077
|
{}
|
|
4806
6078
|
);
|
|
4807
6079
|
} finally {
|
|
4808
|
-
|
|
6080
|
+
fs4.rmSync(tmpDir, { recursive: true, force: true });
|
|
4809
6081
|
}
|
|
4810
6082
|
}
|
|
4811
6083
|
async function cpDownload(c, sandboxId, remotePath, localDir, opts) {
|
|
@@ -4817,13 +6089,13 @@ async function cpDownload(c, sandboxId, remotePath, localDir, opts) {
|
|
|
4817
6089
|
assertTransferUrl(created.downloadUrl);
|
|
4818
6090
|
const res = await fetch(created.downloadUrl);
|
|
4819
6091
|
if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`);
|
|
4820
|
-
const tmpDir =
|
|
4821
|
-
const tmp =
|
|
6092
|
+
const tmpDir = fs4.mkdtempSync(path5.join(os.tmpdir(), "compute-cp-dl-"));
|
|
6093
|
+
const tmp = path5.join(tmpDir, "archive.tar.gz");
|
|
4822
6094
|
try {
|
|
4823
6095
|
const progress = cpProgress(created.bytes ?? 0, opts);
|
|
4824
|
-
const ws =
|
|
6096
|
+
const ws = fs4.createWriteStream(tmp);
|
|
4825
6097
|
try {
|
|
4826
|
-
await new Promise((
|
|
6098
|
+
await new Promise((resolve3, reject) => {
|
|
4827
6099
|
ws.once("error", reject);
|
|
4828
6100
|
const reader = res.body.getReader();
|
|
4829
6101
|
const pump = async () => {
|
|
@@ -4835,7 +6107,7 @@ async function cpDownload(c, sandboxId, remotePath, localDir, opts) {
|
|
|
4835
6107
|
}
|
|
4836
6108
|
};
|
|
4837
6109
|
pump().then(
|
|
4838
|
-
() => ws.end(() =>
|
|
6110
|
+
() => ws.end(() => resolve3()),
|
|
4839
6111
|
reject
|
|
4840
6112
|
);
|
|
4841
6113
|
});
|
|
@@ -4843,11 +6115,11 @@ async function cpDownload(c, sandboxId, remotePath, localDir, opts) {
|
|
|
4843
6115
|
ws.destroy();
|
|
4844
6116
|
}
|
|
4845
6117
|
progress.done();
|
|
4846
|
-
|
|
4847
|
-
await
|
|
4848
|
-
return { path: localDir, bytes: created.bytes ??
|
|
6118
|
+
fs4.mkdirSync(localDir, { recursive: true });
|
|
6119
|
+
await tar2.extract({ file: tmp, cwd: localDir, filter: tarEntryIsSafe });
|
|
6120
|
+
return { path: localDir, bytes: created.bytes ?? fs4.statSync(tmp).size, files: created.files ?? 0 };
|
|
4849
6121
|
} finally {
|
|
4850
|
-
|
|
6122
|
+
fs4.rmSync(tmpDir, { recursive: true, force: true });
|
|
4851
6123
|
}
|
|
4852
6124
|
}
|
|
4853
6125
|
function formatBytes(n) {
|
|
@@ -4863,8 +6135,10 @@ function formatBytes(n) {
|
|
|
4863
6135
|
}
|
|
4864
6136
|
|
|
4865
6137
|
// src/agents.ts
|
|
6138
|
+
init_esm_shims();
|
|
6139
|
+
init_actions();
|
|
4866
6140
|
import pc12 from "picocolors";
|
|
4867
|
-
import { readFileSync as
|
|
6141
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
4868
6142
|
function formatLocalTime2(iso) {
|
|
4869
6143
|
if (iso === null) return "\u2014";
|
|
4870
6144
|
const d = new Date(iso);
|
|
@@ -4940,7 +6214,7 @@ function registerAgentsCommands(program2) {
|
|
|
4940
6214
|
).action(
|
|
4941
6215
|
async (name, opts) => {
|
|
4942
6216
|
try {
|
|
4943
|
-
const prompt = opts.prompt ?? (opts.promptFile ?
|
|
6217
|
+
const prompt = opts.prompt ?? (opts.promptFile ? readFileSync8(opts.promptFile, "utf8") : void 0);
|
|
4944
6218
|
if (!prompt?.trim()) fail(new Error("--prompt or --prompt-file is required"), opts);
|
|
4945
6219
|
const volume = opts.volumeDisk !== void 0 || opts.volumePath !== void 0 ? { diskId: opts.volumeDisk, path: opts.volumePath } : void 0;
|
|
4946
6220
|
const c = await client(opts);
|
|
@@ -4978,7 +6252,7 @@ function registerAgentsCommands(program2) {
|
|
|
4978
6252
|
).action(
|
|
4979
6253
|
async (ref, opts) => {
|
|
4980
6254
|
try {
|
|
4981
|
-
const prompt = opts.prompt ?? (opts.promptFile ?
|
|
6255
|
+
const prompt = opts.prompt ?? (opts.promptFile ? readFileSync8(opts.promptFile, "utf8") : void 0);
|
|
4982
6256
|
const body = {
|
|
4983
6257
|
name: opts.name,
|
|
4984
6258
|
prompt,
|
|
@@ -5036,12 +6310,12 @@ function registerAgentsCommands(program2) {
|
|
|
5036
6310
|
);
|
|
5037
6311
|
authOpts(
|
|
5038
6312
|
cmd.command("run <ref> [message]").description("Start a session on a routed sandbox and optionally send a first message").option("--resume <sessionId>", "resume a stopped conversation on a new sandbox using its persistent disk").option("--size <size>", "platform size for the session's sandbox")
|
|
5039
|
-
).action(async (ref,
|
|
6313
|
+
).action(async (ref, message2, opts) => {
|
|
5040
6314
|
try {
|
|
5041
6315
|
const c = await client(opts);
|
|
5042
6316
|
const res = await c.post(
|
|
5043
6317
|
`/api/v1/agents/${encodeURIComponent(ref)}/sessions`,
|
|
5044
|
-
{ message, size: opts.size, resumeSessionId: opts.resume }
|
|
6318
|
+
{ message: message2, size: opts.size, resumeSessionId: opts.resume }
|
|
5045
6319
|
);
|
|
5046
6320
|
output(opts, res, (r) => {
|
|
5047
6321
|
printSession(r.session);
|
|
@@ -5067,12 +6341,12 @@ function registerAgentsCommands(program2) {
|
|
|
5067
6341
|
);
|
|
5068
6342
|
authOpts(
|
|
5069
6343
|
cmd.command("send <sessionId> <message>").description("Send a message; the agent runs a turn")
|
|
5070
|
-
).action(async (sessionId,
|
|
6344
|
+
).action(async (sessionId, message2, opts) => {
|
|
5071
6345
|
try {
|
|
5072
6346
|
const c = await client(opts);
|
|
5073
6347
|
const res = await c.post(
|
|
5074
6348
|
`/api/v1/agent-sessions/${encodeURIComponent(sessionId)}/events`,
|
|
5075
|
-
{ message }
|
|
6349
|
+
{ message: message2 }
|
|
5076
6350
|
);
|
|
5077
6351
|
output(opts, res, (r) => {
|
|
5078
6352
|
for (const e of r.events) printEvent(e);
|
|
@@ -5132,126 +6406,73 @@ function registerAgentsCommands(program2) {
|
|
|
5132
6406
|
});
|
|
5133
6407
|
}
|
|
5134
6408
|
|
|
5135
|
-
// src/
|
|
5136
|
-
|
|
6409
|
+
// src/index.ts
|
|
6410
|
+
init_actions();
|
|
5137
6411
|
|
|
5138
|
-
// src/
|
|
5139
|
-
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
function
|
|
5143
|
-
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
described.cause = cause;
|
|
5152
|
-
return described;
|
|
5153
|
-
}
|
|
5154
|
-
function requestUrl(input) {
|
|
5155
|
-
if (typeof input === "string") return input;
|
|
5156
|
-
if (input instanceof URL) return input.href;
|
|
5157
|
-
return input.url;
|
|
5158
|
-
}
|
|
5159
|
-
function withFetchFailureContext(fetchImpl) {
|
|
5160
|
-
return async (input, init) => {
|
|
5161
|
-
try {
|
|
5162
|
-
return await fetchImpl(input, init);
|
|
5163
|
-
} catch (error) {
|
|
5164
|
-
if (isFetchFailure(error)) throw describeFetchFailure(error, requestUrl(input));
|
|
5165
|
-
throw error;
|
|
5166
|
-
}
|
|
6412
|
+
// src/status.ts
|
|
6413
|
+
init_esm_shims();
|
|
6414
|
+
init_actions();
|
|
6415
|
+
var message = (error) => error instanceof Error ? error.message : String(error);
|
|
6416
|
+
async function getStatus(opts) {
|
|
6417
|
+
const status = {
|
|
6418
|
+
authenticated: false,
|
|
6419
|
+
ready: false,
|
|
6420
|
+
organization: null,
|
|
6421
|
+
credits: null,
|
|
6422
|
+
sandbox: null,
|
|
6423
|
+
routing: null,
|
|
6424
|
+
issues: []
|
|
5167
6425
|
};
|
|
5168
|
-
}
|
|
5169
|
-
|
|
5170
|
-
// src/session.ts
|
|
5171
|
-
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL2, isSecurePlatformTransport as isSecurePlatformTransport2, isTrustedPlatformHost as isTrustedPlatformHost2 } from "@computesdk/platform";
|
|
5172
|
-
function envBaseUrl(env = process.env) {
|
|
5173
|
-
return env.COMPUTE_PLATFORM_URL || env.BENCHMARKS_PLATFORM_URL || void 0;
|
|
5174
|
-
}
|
|
5175
|
-
function assertComputeKeyDestination(baseUrl) {
|
|
5176
|
-
const url = baseUrl.replace(/\/+$/, "");
|
|
5177
|
-
if (!isTrustedPlatformHost2(url)) {
|
|
5178
|
-
throw new Error(
|
|
5179
|
-
`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.`
|
|
5180
|
-
);
|
|
5181
|
-
}
|
|
5182
|
-
if (!isSecurePlatformTransport2(url)) {
|
|
5183
|
-
throw new Error(`Refusing to send COMPUTE_API_KEY over plaintext HTTP to ${url}; use https://.`);
|
|
5184
|
-
}
|
|
5185
|
-
}
|
|
5186
|
-
function benchAuthOverrides(opts = {}, env = process.env) {
|
|
5187
|
-
const baseUrl = opts.baseUrl ?? envBaseUrl(env);
|
|
5188
|
-
const apiKey = env.COMPUTE_API_KEY || void 0;
|
|
5189
|
-
if (apiKey) assertComputeKeyDestination(baseUrl ?? DEFAULT_BASE_URL2);
|
|
5190
|
-
return { baseUrl, apiKey };
|
|
5191
|
-
}
|
|
5192
|
-
async function benchAuth(opts = {}) {
|
|
5193
|
-
const { resolveAuth } = await import("@benchsdk/cli");
|
|
5194
|
-
return resolveAuth(benchAuthOverrides(opts));
|
|
5195
|
-
}
|
|
5196
|
-
function errorReason(body) {
|
|
5197
|
-
if (typeof body !== "string" || body === "") return void 0;
|
|
5198
|
-
try {
|
|
5199
|
-
const parsed = JSON.parse(body);
|
|
5200
|
-
const reason = parsed.message ?? parsed.error;
|
|
5201
|
-
return typeof reason === "string" ? reason : void 0;
|
|
5202
|
-
} catch {
|
|
5203
|
-
return body.slice(0, 200);
|
|
5204
|
-
}
|
|
5205
|
-
}
|
|
5206
|
-
function httpStatus(error) {
|
|
5207
|
-
const status = error?.status;
|
|
5208
|
-
return typeof status === "number" ? status : void 0;
|
|
5209
|
-
}
|
|
5210
|
-
async function apiKeyOrganization(auth, apiKey) {
|
|
5211
|
-
const url = `${auth.apiBaseUrl}/actions/org`;
|
|
5212
|
-
let response;
|
|
5213
|
-
try {
|
|
5214
|
-
response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
|
|
5215
|
-
} catch (error) {
|
|
5216
|
-
throw isFetchFailure(error) ? describeFetchFailure(error, url) : error;
|
|
5217
|
-
}
|
|
5218
|
-
const text = await response.text();
|
|
5219
|
-
if (!response.ok) {
|
|
5220
|
-
const reason = errorReason(text);
|
|
5221
|
-
throw new Error(
|
|
5222
|
-
`This API key has no user identity, and its organization could not be read (${response.status}${reason ? `: ${reason}` : ""}).`
|
|
5223
|
-
);
|
|
5224
|
-
}
|
|
5225
|
-
const org2 = JSON.parse(text);
|
|
5226
|
-
return { id: org2.organizationId, name: org2.name, slug: org2.slug };
|
|
5227
|
-
}
|
|
5228
|
-
async function fetchWhoami(auth) {
|
|
5229
|
-
const { getMe } = await import("@benchsdk/cli");
|
|
5230
6426
|
try {
|
|
5231
|
-
|
|
6427
|
+
const c = await client(opts);
|
|
6428
|
+
const selected = resolveInstanceId(void 0, opts);
|
|
6429
|
+
const [org2, balance, route, sandbox] = await Promise.allSettled([
|
|
6430
|
+
c.org(),
|
|
6431
|
+
c.get("/api/v1/billing/balance"),
|
|
6432
|
+
c.get("/api/v1/sandboxes/quote"),
|
|
6433
|
+
selected ? c.get(`/api/v1/sandboxes/${selected.id}`) : Promise.resolve(null)
|
|
6434
|
+
]);
|
|
6435
|
+
if (org2.status === "fulfilled") {
|
|
6436
|
+
status.authenticated = true;
|
|
6437
|
+
status.organization = org2.value;
|
|
6438
|
+
} else status.issues.push(`Authentication / organization: ${message(org2.reason)}`);
|
|
6439
|
+
if (balance.status === "fulfilled") {
|
|
6440
|
+
status.credits = { balanceUsd: balance.value.balanceMicroUsd / 1e6, heldUsd: balance.value.heldMicroUsd / 1e6 };
|
|
6441
|
+
} else status.issues.push(`Credits: ${message(balance.reason)}`);
|
|
6442
|
+
if (route.status === "fulfilled") {
|
|
6443
|
+
status.routing = { ready: route.value.quote.ok, ...route.value.quote.reason ? { reason: route.value.quote.reason } : {} };
|
|
6444
|
+
} else status.issues.push(`Routing: ${message(route.reason)}`);
|
|
6445
|
+
if (sandbox.status === "fulfilled" && sandbox.value) {
|
|
6446
|
+
const s = sandbox.value.sandbox;
|
|
6447
|
+
status.sandbox = { id: s.id, status: s.status, provider: s.provider };
|
|
6448
|
+
} else if (sandbox.status === "rejected") {
|
|
6449
|
+
status.sandbox = { id: selected.id, status: "unknown", provider: null };
|
|
6450
|
+
status.issues.push(`Selected sandbox: ${message(sandbox.reason)}`);
|
|
6451
|
+
}
|
|
6452
|
+
status.ready = status.authenticated && status.routing?.ready === true;
|
|
5232
6453
|
} catch (error) {
|
|
5233
|
-
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
`Authentication
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
}
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
`active org: ${active ? `${active.slug} (${active.id})` : "\u2014"}${me.organizations.length > 1 ? " \u2014 change with `compute org use <slug>`" : ""}`
|
|
5251
|
-
];
|
|
6454
|
+
status.issues.push(message(error));
|
|
6455
|
+
}
|
|
6456
|
+
return status;
|
|
6457
|
+
}
|
|
6458
|
+
function registerStatusCommand(program2) {
|
|
6459
|
+
program2.command("status").description("Show authentication, effective organization, credits, selected sandbox and routing readiness").option("--api-key <key>").option("--base-url <url>").option("--org <slug>").option("--allow-untrusted-host").option("--json", "print machine-readable JSON").option("--check", "exit 1 unless authenticated and the default sandbox route is ready").action(async (opts) => {
|
|
6460
|
+
const status = await getStatus(opts);
|
|
6461
|
+
output(opts, status, (s) => {
|
|
6462
|
+
console.log(`Authentication: ${s.authenticated ? "verified" : "not verified \u2014 run compute login"}`);
|
|
6463
|
+
console.log(`Organization: ${safeTerm(s.organization?.slug ?? "unavailable")}`);
|
|
6464
|
+
console.log(`Credits: ${s.credits ? `$${s.credits.balanceUsd.toFixed(2)} ($${s.credits.heldUsd.toFixed(2)} held)` : "unavailable"}`);
|
|
6465
|
+
console.log(`Sandbox: ${s.sandbox ? safeTerm(`${s.sandbox.id} \xB7 ${s.sandbox.status} \xB7 ${s.sandbox.provider ?? "unknown provider"}`) : "none selected \u2014 run compute new"}`);
|
|
6466
|
+
console.log(`Routing: ${s.routing ? s.routing.ready ? "ready" : safeTerm(s.routing.reason ?? "unavailable") : "unavailable"}`);
|
|
6467
|
+
for (const issue of s.issues) console.log(safeTerm(issue));
|
|
6468
|
+
});
|
|
6469
|
+
if (opts.check && !status.ready) process.exitCode = 1;
|
|
6470
|
+
});
|
|
5252
6471
|
}
|
|
5253
6472
|
|
|
5254
6473
|
// src/bench.ts
|
|
6474
|
+
init_esm_shims();
|
|
6475
|
+
import { DEFAULT_BASE_URL as DEFAULT_BASE_URL4 } from "@computesdk/platform";
|
|
5255
6476
|
var BENCH_COMMANDS = /* @__PURE__ */ new Set(["bench", "benchmark"]);
|
|
5256
6477
|
var RUNNER_VERBS = /* @__PURE__ */ new Set(["run", "check", "__manifest"]);
|
|
5257
6478
|
function parseBenchDispatch(args) {
|
|
@@ -5296,7 +6517,7 @@ function benchInvocation(argv, env, computeOrg) {
|
|
|
5296
6517
|
}
|
|
5297
6518
|
if (env.COMPUTE_API_KEY && !env.BENCHMARKS_PLATFORM_API_KEY) {
|
|
5298
6519
|
assertComputeKeyDestination(
|
|
5299
|
-
baseUrlFlag(argv) || env.BENCHMARKS_PLATFORM_URL || env.COMPUTE_PLATFORM_URL ||
|
|
6520
|
+
baseUrlFlag(argv) || env.BENCHMARKS_PLATFORM_URL || env.COMPUTE_PLATFORM_URL || DEFAULT_BASE_URL4
|
|
5300
6521
|
);
|
|
5301
6522
|
out.BENCHMARKS_PLATFORM_API_KEY = env.COMPUTE_API_KEY;
|
|
5302
6523
|
}
|
|
@@ -5313,17 +6534,18 @@ async function runBench(dispatch) {
|
|
|
5313
6534
|
}
|
|
5314
6535
|
|
|
5315
6536
|
// src/manifest.ts
|
|
5316
|
-
|
|
5317
|
-
import {
|
|
5318
|
-
import {
|
|
6537
|
+
init_esm_shims();
|
|
6538
|
+
import { createRequire as createRequire3 } from "module";
|
|
6539
|
+
import { existsSync as existsSync3, readFileSync as readFileSync9, realpathSync as realpathSync2 } from "fs";
|
|
6540
|
+
import { dirname as dirname2, join as join8, sep as sep3 } from "path";
|
|
5319
6541
|
var MANIFEST_COMMAND = "__manifest";
|
|
5320
6542
|
function resolvedPackage(name, fromDir) {
|
|
5321
|
-
const require2 =
|
|
6543
|
+
const require2 = createRequire3(join8(fromDir, "noop.js"));
|
|
5322
6544
|
let dir = dirname2(require2.resolve(name));
|
|
5323
6545
|
for (; ; ) {
|
|
5324
|
-
const file =
|
|
5325
|
-
if (
|
|
5326
|
-
const pkg = JSON.parse(
|
|
6546
|
+
const file = join8(dir, "package.json");
|
|
6547
|
+
if (existsSync3(file)) {
|
|
6548
|
+
const pkg = JSON.parse(readFileSync9(file, "utf-8"));
|
|
5327
6549
|
if (pkg.name === name) return { dir, version: pkg.version };
|
|
5328
6550
|
}
|
|
5329
6551
|
const parent = dirname2(dir);
|
|
@@ -5332,11 +6554,11 @@ function resolvedPackage(name, fromDir) {
|
|
|
5332
6554
|
}
|
|
5333
6555
|
}
|
|
5334
6556
|
function isLinkedPackage(realDir) {
|
|
5335
|
-
return !realDir.split(
|
|
6557
|
+
return !realDir.split(sep3).includes("node_modules");
|
|
5336
6558
|
}
|
|
5337
6559
|
function packageVersion(name, resolved) {
|
|
5338
6560
|
const entry = { package: name, version: resolved.version };
|
|
5339
|
-
if (isLinkedPackage(
|
|
6561
|
+
if (isLinkedPackage(realpathSync2(resolved.dir))) {
|
|
5340
6562
|
entry.linked = true;
|
|
5341
6563
|
entry.released = false;
|
|
5342
6564
|
}
|
|
@@ -5428,7 +6650,7 @@ function registerManifestCommand(program2, options) {
|
|
|
5428
6650
|
packageDir: options.packageDir
|
|
5429
6651
|
});
|
|
5430
6652
|
if (opts.check) {
|
|
5431
|
-
if (!manifestMatches(
|
|
6653
|
+
if (!manifestMatches(readFileSync9(opts.check, "utf-8"), manifest)) {
|
|
5432
6654
|
console.error(
|
|
5433
6655
|
`${opts.check} is out of date. Regenerate it with \`pnpm --filter @computesdk/cli run manifest\`.`
|
|
5434
6656
|
);
|
|
@@ -5442,6 +6664,11 @@ function registerManifestCommand(program2, options) {
|
|
|
5442
6664
|
}
|
|
5443
6665
|
|
|
5444
6666
|
// src/org-members.ts
|
|
6667
|
+
init_esm_shims();
|
|
6668
|
+
init_actions_client();
|
|
6669
|
+
init_actions();
|
|
6670
|
+
init_confirm();
|
|
6671
|
+
init_term();
|
|
5445
6672
|
import pc13 from "picocolors";
|
|
5446
6673
|
var ORG_PATH = "/api/v1/organizations/current";
|
|
5447
6674
|
var MEMBER_ROLES = ["member", "admin"];
|
|
@@ -5747,10 +6974,10 @@ function registerInvitationsCommands(program2) {
|
|
|
5747
6974
|
}
|
|
5748
6975
|
|
|
5749
6976
|
// src/index.ts
|
|
5750
|
-
var __filename2 =
|
|
6977
|
+
var __filename2 = fileURLToPath3(import.meta.url);
|
|
5751
6978
|
var __dirname2 = dirname3(__filename2);
|
|
5752
6979
|
var packageJson = JSON.parse(
|
|
5753
|
-
|
|
6980
|
+
readFileSync10(join9(__dirname2, "..", "package.json"), "utf-8")
|
|
5754
6981
|
);
|
|
5755
6982
|
var isDevBuild = import.meta.url.includes("worktrees") || import.meta.url.includes("/packages/cli/");
|
|
5756
6983
|
var VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;
|
|
@@ -5764,11 +6991,17 @@ process.stderr.on("error", (err) => {
|
|
|
5764
6991
|
});
|
|
5765
6992
|
var program = new Command4();
|
|
5766
6993
|
inheritParentOptions(program);
|
|
5767
|
-
program.name("compute").description("ComputeSDK CLI").version(VERSION).enablePositionalOptions().passThroughOptions();
|
|
6994
|
+
program.name("compute").description("ComputeSDK CLI").version(VERSION, "-v, --version", "print the CLI version").enablePositionalOptions().passThroughOptions();
|
|
6995
|
+
program.addOption(new Option4("-V", "print the CLI version").hideHelp());
|
|
6996
|
+
program.on("option:V", () => {
|
|
6997
|
+
console.log(VERSION);
|
|
6998
|
+
process.exit(0);
|
|
6999
|
+
});
|
|
7000
|
+
program.addHelpText("before", "Run code on a cloud sandbox:\n compute new\n compute exec echo hello\n compute destroy\n");
|
|
5768
7001
|
async function printSessionLine(options) {
|
|
5769
7002
|
try {
|
|
5770
|
-
const { getMe, resolveAuth } = await import("@benchsdk/cli");
|
|
5771
|
-
const me = await
|
|
7003
|
+
const { getMe: getMe2, resolveAuth } = await import("@benchsdk/cli");
|
|
7004
|
+
const me = await getMe2(await resolveAuth({ baseUrl: options?.baseUrl ?? envBaseUrl() }));
|
|
5772
7005
|
const active = me.organizations.find((o) => o.id === me.activeOrganizationId);
|
|
5773
7006
|
const who = me.user.email ?? me.user.name ?? me.user.id;
|
|
5774
7007
|
if (active) {
|
|
@@ -5783,14 +7016,12 @@ async function printSessionLine(options) {
|
|
|
5783
7016
|
}
|
|
5784
7017
|
}
|
|
5785
7018
|
async function runLogin(options) {
|
|
5786
|
-
|
|
5787
|
-
await oauthLogin({
|
|
5788
|
-
baseUrl: options?.baseUrl ?? envBaseUrl()
|
|
5789
|
-
});
|
|
7019
|
+
await login(options);
|
|
5790
7020
|
}
|
|
5791
7021
|
async function runLogout() {
|
|
5792
7022
|
const { clearCredentials } = await import("@benchsdk/cli");
|
|
5793
7023
|
await clearCredentials();
|
|
7024
|
+
clearPendingLogins();
|
|
5794
7025
|
}
|
|
5795
7026
|
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) => {
|
|
5796
7027
|
if (opts.logout) {
|
|
@@ -5828,10 +7059,14 @@ program.command("providers").description("List all providers and their configura
|
|
|
5828
7059
|
}
|
|
5829
7060
|
console.log();
|
|
5830
7061
|
});
|
|
5831
|
-
program.command("login").description("Authenticate with ComputeSDK (OAuth device flow)").option("--base-url <url>", "platform URL to authenticate against").action(async (opts) => {
|
|
5832
|
-
|
|
5833
|
-
|
|
5834
|
-
|
|
7062
|
+
program.command("login").description("Authenticate with ComputeSDK (OAuth device flow)").option("--base-url <url>", "platform URL to authenticate against").option("--no-browser", "print the sign-in URL instead of opening a browser").option("--json", "return a sign-in URL and code immediately; use --wait to complete login").option("--wait", "wait for approval (default without --json)").option("--new", "replace the pending sign-in with a new code").action(async (opts) => {
|
|
7063
|
+
try {
|
|
7064
|
+
await runLogin(opts);
|
|
7065
|
+
} catch (error) {
|
|
7066
|
+
fail(error, opts);
|
|
7067
|
+
return;
|
|
7068
|
+
}
|
|
7069
|
+
if (opts.json) return;
|
|
5835
7070
|
await printSessionLine({ baseUrl: opts.baseUrl });
|
|
5836
7071
|
p.outro(pc14.green("Authenticated!"));
|
|
5837
7072
|
});
|
|
@@ -5856,9 +7091,9 @@ async function printWhoami(options = {}) {
|
|
|
5856
7091
|
}
|
|
5857
7092
|
var org = program.command("org").description("Manage the active organization, its members and invitations");
|
|
5858
7093
|
org.command("list").description("List your organizations").option("--json", "print machine-readable JSON").action(async (opts) => {
|
|
5859
|
-
const { listOrganizations, getMe } = await import("@benchsdk/cli");
|
|
7094
|
+
const { listOrganizations, getMe: getMe2 } = await import("@benchsdk/cli");
|
|
5860
7095
|
const auth = await benchAuth();
|
|
5861
|
-
const [organizations, me] = await Promise.all([listOrganizations(auth),
|
|
7096
|
+
const [organizations, me] = await Promise.all([listOrganizations(auth), getMe2(auth)]);
|
|
5862
7097
|
if (opts.json) {
|
|
5863
7098
|
console.log(JSON.stringify(organizations, null, 2));
|
|
5864
7099
|
return;
|
|
@@ -5869,14 +7104,14 @@ org.command("list").description("List your organizations").option("--json", "pri
|
|
|
5869
7104
|
}
|
|
5870
7105
|
});
|
|
5871
7106
|
org.command("use <slug>").description("Set the active organization (persisted to the stored login)").action(async (slug) => {
|
|
5872
|
-
const { loadCredentials, saveCredentials, createApiClient, setActiveOrganization } = await import("@benchsdk/cli");
|
|
5873
|
-
const credentials = await
|
|
7107
|
+
const { loadCredentials: loadCredentials2, saveCredentials: saveCredentials2, createApiClient, setActiveOrganization: setActiveOrganization2 } = await import("@benchsdk/cli");
|
|
7108
|
+
const credentials = await loadCredentials2() ?? {};
|
|
5874
7109
|
const { auth } = await createApiClient({ baseUrl: envBaseUrl() });
|
|
5875
|
-
const result = await
|
|
7110
|
+
const result = await setActiveOrganization2(auth, slug);
|
|
5876
7111
|
if (!result.organization) {
|
|
5877
7112
|
throw new Error(`Could not set active organization to ${slug}`);
|
|
5878
7113
|
}
|
|
5879
|
-
await
|
|
7114
|
+
await saveCredentials2({
|
|
5880
7115
|
...credentials,
|
|
5881
7116
|
baseUrl: auth.baseUrl,
|
|
5882
7117
|
// An API-key login must not be rewritten as an OAuth one — keep its
|
|
@@ -5902,13 +7137,15 @@ registerActionsCommands(program);
|
|
|
5902
7137
|
registerByokCommands(program);
|
|
5903
7138
|
registerMarketCommands(program);
|
|
5904
7139
|
registerCreditsCommands(program);
|
|
7140
|
+
registerStatusCommand(program);
|
|
5905
7141
|
registerSandboxesCommands(program);
|
|
7142
|
+
registerSyncCommand(program);
|
|
5906
7143
|
registerAgentsCommands(program);
|
|
5907
7144
|
program.command("bench").description("Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, fork, artifacts, export, ...)").allowUnknownOption().helpOption(false).action(() => {
|
|
5908
7145
|
});
|
|
5909
7146
|
registerManifestCommand(program, {
|
|
5910
7147
|
version: packageJson.version,
|
|
5911
|
-
packageDir:
|
|
7148
|
+
packageDir: join9(__dirname2, "..")
|
|
5912
7149
|
});
|
|
5913
7150
|
async function main() {
|
|
5914
7151
|
const bench = parseBenchDispatch(process.argv.slice(2));
|