sandcovery 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4987 @@
1
+ import { Bn as TaggedError, Br as isString, Ct as fail, E as decodeUnknownSync, En as ClockRef, Hn as seconds, Ir as hasProperty, Jn as isSuccess, O as fromJsonString, Qt as tapError, Tt as flatMap, Un as toMillis, Ut as retry, Vn as millis, Xt as sync, Yn as try_, Yt as suspend, _ as String$1, an as void_, ar as getOrThrowWith, cr as isSome, g as Record, gt as catchDefect, h as Number$1, kn as currentTimeMillis$1, ln as spaced, lt as acquireUseRelease, m as NullOr, n as Boolean, rr as getOrElse, sr as isNone, t as ArraySchema, u as Literals, un as upTo, ur as map, v as Struct, vt as catchTag, w as decodeUnknownOption, xt as die } from "./Schema-CoX0a2_o.mjs";
2
+ import { C as NotFound, D as Forbidden, E as SandboxStatus, F as CREDIT_PURCHASE_MIN_MICRO_USD, M as ProviderSort, N as CARD_FEE_TERMS, O as Conflict, P as CREDIT_PURCHASE_MAX_MICRO_USD, R as MICRO_USD_PER_DOLLAR, S as Unauthorized, _ as KeyKind, h as SANDCOVERY_X_HANDLE, j as DEFAULT_SLUG, l as MONTH_TEXT, t as Sandcovery, v as SpendLimit, x as Unsupported, z as NO_MARKUP_TERMS } from "./src-BoT9S6C3.mjs";
3
+ import { WebSocket } from "node:http";
4
+ import net from "node:net";
5
+ import readline from "node:readline";
6
+ import { spawn } from "node:child_process";
7
+ import crypto$1, { createHash } from "node:crypto";
8
+ import { once } from "node:events";
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { text } from "node:stream/consumers";
12
+ import os from "node:os";
13
+ // ../../node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/Clock.js
14
+ /**
15
+ * Context reference for the active time service in the environment.
16
+ *
17
+ * **When to use**
18
+ *
19
+ * Use when you need to access or provide the full time service, including sleep
20
+ * operations, rather than a single timestamp accessor.
21
+ *
22
+ * **Example** (Accessing the Clock service)
23
+ *
24
+ * ```ts import.meta.vitest
25
+ * import { Clock, Effect } from "effect"
26
+ *
27
+ * const testClock: Clock.Clock = {
28
+ * currentTimeMillisUnsafe: () => 1_000,
29
+ * currentTimeMillis: Effect.succeed(1_000),
30
+ * monotonicTimeNanosUnsafe: () => 1_000_000_000n,
31
+ * monotonicTimeNanos: Effect.succeed(1_000_000_000n),
32
+ * currentTimeNanosUnsafe: () => 1_000_000_000n,
33
+ * currentTimeNanos: Effect.succeed(1_000_000_000n),
34
+ * sleep: () => Effect.void
35
+ * }
36
+ *
37
+ * const program = Effect.gen(function*() {
38
+ * const clock = yield* Clock.Clock
39
+ * return clock.currentTimeMillisUnsafe()
40
+ * })
41
+ *
42
+ * await Effect.runPromise(Effect.provideService(program, Clock.Clock, testClock)) // => 1_000
43
+ * ```
44
+ *
45
+ * @see {@link clockWith} for using the current Clock service inside an effect
46
+ * @see {@link currentTimeMillis} for reading the current time in milliseconds
47
+ * @see {@link currentTimeNanos} for reading the current time in nanoseconds
48
+ *
49
+ * @stability stable
50
+ * @category services
51
+ * @since 2.0.0
52
+ */
53
+ const Clock = ClockRef;
54
+ /**
55
+ * Returns an Effect that succeeds with the current Unix time in milliseconds.
56
+ *
57
+ * **When to use**
58
+ *
59
+ * Use to create wall-clock timestamps from the active `Clock` service with
60
+ * millisecond precision.
61
+ *
62
+ * **Gotchas**
63
+ *
64
+ * The value can move backward or forward when the system wall clock is
65
+ * corrected, so it is not suitable for measuring elapsed time.
66
+ *
67
+ * **Example** (Reading milliseconds)
68
+ *
69
+ * ```ts import.meta.vitest
70
+ * import { Clock, Effect } from "effect"
71
+ *
72
+ * const testClock: Clock.Clock = {
73
+ * currentTimeMillisUnsafe: () => 1_000,
74
+ * currentTimeMillis: Effect.succeed(1_000),
75
+ * monotonicTimeNanosUnsafe: () => 1_000_000_000n,
76
+ * monotonicTimeNanos: Effect.succeed(1_000_000_000n),
77
+ * currentTimeNanosUnsafe: () => 1_000_000_000n,
78
+ * currentTimeNanos: Effect.succeed(1_000_000_000n),
79
+ * sleep: () => Effect.void
80
+ * }
81
+ *
82
+ * await Effect.runPromise(Effect.provideService(Clock.currentTimeMillis, Clock.Clock, testClock)) // => 1_000
83
+ * ```
84
+ *
85
+ * @see {@link currentTimeNanos} for nanosecond precision
86
+ * @see {@link monotonicTimeNanos} for measuring elapsed time
87
+ * @see {@link clockWith} for accessing the full Clock service
88
+ *
89
+ * @stability stable
90
+ * @category accessors
91
+ * @since 2.0.0
92
+ */
93
+ const currentTimeMillis = currentTimeMillis$1;
94
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
95
+ /**
96
+ * A no-operation function that does nothing.
97
+ * This can be used as a placeholder or default function.
98
+ *
99
+ * @example
100
+ * noop(); // Does nothing
101
+ *
102
+ * @returns This function does not return anything.
103
+ */
104
+ function noop() {}
105
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/math/clamp.mjs
106
+ /**
107
+ * Clamps a number within the specified bounds.
108
+ *
109
+ * This function takes a number and one or two bounds, and returns the number clamped within the specified bounds.
110
+ * If only one bound is provided, it returns the minimum of the value and the bound.
111
+ *
112
+ * @param value - The number to clamp.
113
+ * @param bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided.
114
+ * @param [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit.
115
+ * @returns The clamped number within the specified bounds.
116
+ *
117
+ * @example
118
+ * const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5
119
+ * const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15
120
+ * const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5
121
+ * const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15
122
+ */
123
+ function clamp(value, bound1, bound2) {
124
+ if (bound2 == null) return Math.min(value, bound1);
125
+ return Math.min(Math.max(value, bound1), bound2);
126
+ }
127
+ // src/cli/detached.ts
128
+ const READY = "ready\n";
129
+ const PRIVATE_DIRECTORY_MODE = 448;
130
+ const PRIVATE_SOCKET_MODE = 384;
131
+ const TERMINAL_ERRORS = [
132
+ NotFound,
133
+ Unauthorized,
134
+ Forbidden,
135
+ Conflict,
136
+ Unsupported
137
+ ];
138
+ const decodeUnserved = decodeUnknownOption(Struct({ code: Literals([
139
+ "ECONNREFUSED",
140
+ "ECONNRESET",
141
+ "ENOENT"
142
+ ]) }));
143
+ const isTerminal = (cause) => TERMINAL_ERRORS.some((kind) => cause instanceof kind);
144
+ const socketOf = ({ name, settingsFile }) => {
145
+ const directory = path.dirname(settingsFile);
146
+ if (process.platform !== "win32") return path.join(directory, `${name}.sock`);
147
+ const digest = createHash("sha256").update(directory).digest("hex");
148
+ return String.raw`\\.\pipe\sandcovery-${name}-${digest.slice(0, 16)}`;
149
+ };
150
+ const answers = async (socketPath) => {
151
+ const socket = net.connect(socketPath);
152
+ try {
153
+ await once(socket, "connect");
154
+ return true;
155
+ } catch (error) {
156
+ if (isSome(decodeUnserved(error))) return false;
157
+ throw error;
158
+ } finally {
159
+ socket.destroy();
160
+ }
161
+ };
162
+ const listened = async (server, socketPath) => {
163
+ const { promise, resolve } = Promise.withResolvers();
164
+ server.once("error", resolve);
165
+ server.listen(socketPath, () => {
166
+ server.off("error", resolve);
167
+ resolve(void 0);
168
+ });
169
+ return await promise;
170
+ };
171
+ const servedAt = async (server, socketPath) => {
172
+ const windows = process.platform === "win32";
173
+ if (!windows) {
174
+ const directory = path.dirname(socketPath);
175
+ fs.mkdirSync(directory, {
176
+ mode: PRIVATE_DIRECTORY_MODE,
177
+ recursive: true
178
+ });
179
+ fs.chmodSync(directory, PRIVATE_DIRECTORY_MODE);
180
+ }
181
+ const failure = await listened(server, socketPath);
182
+ if (failure === void 0) {
183
+ if (!windows) fs.chmodSync(socketPath, PRIVATE_SOCKET_MODE);
184
+ return true;
185
+ }
186
+ if (failure.code !== "EADDRINUSE" || windows || await answers(socketPath)) return false;
187
+ fs.rmSync(socketPath, { force: true });
188
+ return await servedAt(server, socketPath);
189
+ };
190
+ const spawned = async ({ entry, env }) => {
191
+ const child = spawn(process.execPath, [entry], {
192
+ detached: true,
193
+ env: {
194
+ ...process.env,
195
+ ...env
196
+ },
197
+ stdio: [
198
+ "ignore",
199
+ "pipe",
200
+ "ignore"
201
+ ]
202
+ });
203
+ try {
204
+ await Promise.race([once(child.stdout, "data"), once(child, "exit")]);
205
+ } finally {
206
+ child.stdout.destroy();
207
+ child.unref();
208
+ }
209
+ };
210
+ const servedOrSpawned = async ({ attempt, entry, env }) => {
211
+ try {
212
+ return await attempt();
213
+ } catch (error) {
214
+ if (isNone(decodeUnserved(error))) throw error;
215
+ await spawned({
216
+ entry,
217
+ env
218
+ });
219
+ return await attempt();
220
+ }
221
+ };
222
+ // src/cli/kubectl-idle.ts
223
+ const IDLE_WATCHER_ENV = "__SANDCOVERY_KUBECTL_IDLE";
224
+ const IDLE_MS = 9e5;
225
+ const HEARTBEAT_MS = 6e4;
226
+ const DESTROY_TIMEOUT_MS = 3e4;
227
+ const REFUSED_STATUSES = /* @__PURE__ */ new Set([
228
+ 400,
229
+ 401,
230
+ 403,
231
+ 404,
232
+ 409,
233
+ 410,
234
+ 422
235
+ ]);
236
+ const decodeWatcher = decodeUnknownSync(fromJsonString(Struct({
237
+ idleMs: Number$1,
238
+ socketPath: String$1
239
+ })));
240
+ const decodeHold = decodeUnknownOption(fromJsonString(Struct({ origin: String$1 })));
241
+ const decodeAnswered = decodeUnknownOption(Struct({ cause: Struct({ status: Number$1 }) }));
242
+ const decodeCluster = decodeUnknownOption(fromJsonString(Struct({
243
+ expires_at: String$1,
244
+ key: String$1,
245
+ sandbox: String$1
246
+ })));
247
+ const idleSocket = (settingsFile) => socketOf({
248
+ name: "kubectl-idle",
249
+ settingsFile
250
+ });
251
+ const statusOf$1 = (failure) => getOrElse(map(decodeAnswered(failure), ({ cause }) => cause.status), () => 0);
252
+ const refused = (failure) => isTerminal(failure) || REFUSED_STATUSES.has(statusOf$1(failure));
253
+ const deadlinesOf = ({ cluster, destroying, due, holders }) => cluster === null ? [] : [cluster.expiresAt, ...holders === 0 && destroying === null ? [due] : []];
254
+ const ended = async ({ cluster, origin }) => {
255
+ try {
256
+ await new Sandcovery({
257
+ apiKey: cluster.key,
258
+ baseUrl: origin
259
+ }).sandboxes.destroy(cluster.sandbox, { signal: AbortSignal.timeout(DESTROY_TIMEOUT_MS) });
260
+ return true;
261
+ } catch (error) {
262
+ if (!(error instanceof Error)) throw error;
263
+ return refused(error);
264
+ }
265
+ };
266
+ const destroyed = async ({ entry, origin, settle }) => {
267
+ const { cluster } = entry;
268
+ if (cluster !== null && await ended({
269
+ cluster,
270
+ origin
271
+ })) {
272
+ if (entry.cluster?.sandbox === cluster.sandbox) entry.cluster = null;
273
+ } else entry.due = Date.now() + HEARTBEAT_MS;
274
+ entry.destroying = null;
275
+ settle();
276
+ };
277
+ const attached = (entry, line) => {
278
+ const cluster = decodeCluster(line);
279
+ if (isNone(cluster)) return false;
280
+ const { expires_at, key, sandbox } = cluster.value;
281
+ const expiresAt = Date.parse(expires_at);
282
+ if (Number.isNaN(expiresAt)) return false;
283
+ entry.cluster = {
284
+ expiresAt,
285
+ key,
286
+ sandbox
287
+ };
288
+ return true;
289
+ };
290
+ const watchIdle = async (config) => {
291
+ const { idleMs, socketPath } = decodeWatcher(config);
292
+ const watched = /* @__PURE__ */ new Map();
293
+ const listener = net.createServer();
294
+ const state = {
295
+ connections: 0,
296
+ timer: null
297
+ };
298
+ const check = () => {
299
+ const now = Date.now();
300
+ if (state.timer !== null) clearTimeout(state.timer);
301
+ for (const [origin, entry] of watched) {
302
+ if (entry.cluster !== null && now >= entry.cluster.expiresAt) entry.cluster = null;
303
+ if (entry.cluster !== null && entry.holders === 0 && entry.destroying === null && now >= entry.due) entry.destroying = destroyed({
304
+ entry,
305
+ origin,
306
+ settle: check
307
+ });
308
+ if (entry.cluster === null && entry.holders === 0 && entry.destroying === null) watched.delete(origin);
309
+ }
310
+ if (state.connections === 0 && watched.size === 0) {
311
+ listener.close();
312
+ return;
313
+ }
314
+ const next = Math.min(now + HEARTBEAT_MS, ...[...watched.values()].flatMap(deadlinesOf));
315
+ state.timer = setTimeout(check, clamp(next - now, 0, HEARTBEAT_MS));
316
+ };
317
+ const held = async (connection, origin) => {
318
+ const entry = watched.get(origin) ?? {
319
+ cluster: null,
320
+ destroying: null,
321
+ due: Date.now() + idleMs,
322
+ holders: 0
323
+ };
324
+ entry.holders += 1;
325
+ watched.set(origin, entry);
326
+ await entry.destroying;
327
+ connection.write(READY);
328
+ return entry;
329
+ };
330
+ listener.on("connection", (connection) => {
331
+ const hold = { entry: null };
332
+ const lines = readline.createInterface({ input: connection });
333
+ state.connections += 1;
334
+ connection.on("error", noop);
335
+ const received = async (line) => {
336
+ if (hold.entry !== null) {
337
+ if (!attached(await hold.entry, line)) connection.destroy();
338
+ return;
339
+ }
340
+ const asked = decodeHold(line);
341
+ if (isNone(asked)) {
342
+ connection.destroy();
343
+ return;
344
+ }
345
+ hold.entry = held(connection, asked.value.origin);
346
+ };
347
+ const released = async () => {
348
+ const entry = await hold.entry;
349
+ state.connections -= 1;
350
+ lines.close();
351
+ if (entry !== null) {
352
+ entry.holders -= 1;
353
+ entry.due = Date.now() + idleMs;
354
+ }
355
+ check();
356
+ };
357
+ lines.on("line", (line) => {
358
+ received(line);
359
+ });
360
+ connection.once("close", () => {
361
+ released();
362
+ });
363
+ });
364
+ const serving = await servedAt(listener, socketPath);
365
+ process.stdout.write(READY);
366
+ if (serving) state.timer = setTimeout(check, HEARTBEAT_MS);
367
+ };
368
+ const connected = async (socketPath) => {
369
+ const socket = net.connect(socketPath);
370
+ const { promise, reject, resolve } = Promise.withResolvers();
371
+ socket.once("connect", () => {
372
+ resolve(socket);
373
+ });
374
+ socket.once("error", reject);
375
+ return await promise;
376
+ };
377
+ const readied = async (socket) => {
378
+ const { promise, reject, resolve } = Promise.withResolvers();
379
+ socket.once("data", () => {
380
+ resolve(null);
381
+ });
382
+ socket.once("close", () => {
383
+ reject(/* @__PURE__ */ new Error("The idle watcher stopped before it answered."));
384
+ });
385
+ await promise;
386
+ };
387
+ const holdCluster = async ({ entry, origin, settingsFile }) => {
388
+ const socketPath = idleSocket(settingsFile);
389
+ const socket = await servedOrSpawned({
390
+ attempt: async () => await connected(socketPath),
391
+ entry,
392
+ env: { [IDLE_WATCHER_ENV]: JSON.stringify({
393
+ idleMs: IDLE_MS,
394
+ socketPath
395
+ }) }
396
+ });
397
+ socket.on("error", noop);
398
+ const ready = readied(socket);
399
+ socket.write(`${JSON.stringify({ origin })}\n`);
400
+ try {
401
+ await ready;
402
+ } catch (error) {
403
+ socket.destroy();
404
+ throw error;
405
+ }
406
+ return {
407
+ attach: (cluster) => {
408
+ socket.write(`${JSON.stringify(cluster)}\n`);
409
+ },
410
+ release: () => {
411
+ socket.end();
412
+ socket.unref();
413
+ }
414
+ };
415
+ };
416
+ // ../cli-core/src/canceled.ts
417
+ var Canceled = class extends TaggedError("Canceled") {};
418
+ // ../cli-core/src/failure.ts
419
+ const classExitCodes = {
420
+ authentication: 1,
421
+ bug: 1,
422
+ config: 1,
423
+ conflict: 1,
424
+ limit: 1,
425
+ missing_input: 2,
426
+ network: 1,
427
+ not_found: 1,
428
+ permission: 1,
429
+ platform: 1,
430
+ rate_limit: 1,
431
+ unknown_outcome: 1,
432
+ usage: 2
433
+ };
434
+ const blockedClasses = /* @__PURE__ */ new Set([
435
+ "authentication",
436
+ "limit",
437
+ "missing_input",
438
+ "permission",
439
+ "usage"
440
+ ]);
441
+ const reasons = {
442
+ agreement_accepted: "conflict",
443
+ agreement_changed: "conflict",
444
+ agreement_not_accepted: "conflict",
445
+ api_error: "platform",
446
+ campaign_funding_active: "conflict",
447
+ campaign_match_delivered: "conflict",
448
+ campaign_request_denied: "conflict",
449
+ campaign_status_locked: "conflict",
450
+ concurrency_limit_reached: "limit",
451
+ confirmation_required: "missing_input",
452
+ conflict: "conflict",
453
+ contract_locked: "conflict",
454
+ domain_taken: "conflict",
455
+ internal_error: "bug",
456
+ invalid_arguments: "usage",
457
+ invalid_config: "config",
458
+ login_locked: "conflict",
459
+ login_required: "authentication",
460
+ market_information_locked: "conflict",
461
+ missing_command: "usage",
462
+ missing_installation: "missing_input",
463
+ missing_job: "missing_input",
464
+ missing_key: "missing_input",
465
+ missing_path: "missing_input",
466
+ missing_port: "missing_input",
467
+ missing_process: "missing_input",
468
+ missing_provider: "missing_input",
469
+ missing_query: "missing_input",
470
+ missing_run: "missing_input",
471
+ missing_sandbox: "missing_input",
472
+ missing_site: "missing_input",
473
+ missing_url: "missing_input",
474
+ missing_value: "missing_input",
475
+ mode_not_entitled: "conflict",
476
+ network_error: "network",
477
+ no_contact: "not_found",
478
+ no_provider_available: "platform",
479
+ not_found: "not_found",
480
+ out_of_credits: "limit",
481
+ permission_denied: "permission",
482
+ proof_not_found: "conflict",
483
+ provider_error: "platform",
484
+ rate_limited: "rate_limit",
485
+ redirected: "network",
486
+ site_exists: "conflict",
487
+ site_taken: "conflict",
488
+ site_unverified: "conflict",
489
+ spawn_failed: "platform",
490
+ spend_limit_reached: "limit",
491
+ stale_login: "conflict",
492
+ subscription_required: "limit",
493
+ team_has_site: "conflict",
494
+ token_expired: "authentication",
495
+ token_scope_required: "permission",
496
+ tool_refused: "conflict",
497
+ turn_failed: "platform",
498
+ unknown_command: "usage",
499
+ unknown_option: "usage",
500
+ unknown_outcome: "unknown_outcome",
501
+ unsupported: "conflict"
502
+ };
503
+ var CliFailure = class extends TaggedError("CliFailure") {};
504
+ const exitCodeOf = (reason) => classExitCodes[reasons[reason]];
505
+ const statusOf = ({ blocked, reason }) => blocked === true || blockedClasses.has(reasons[reason]) ? "action_required" : "error";
506
+ const usageFailure = ({ help, issues, message, reason = "invalid_arguments" }) => new CliFailure({
507
+ issues,
508
+ message,
509
+ reason,
510
+ recovery: [{
511
+ instruction: "See all options",
512
+ next: { argv: [...help, "--help"] }
513
+ }]
514
+ });
515
+ // ../cli-core/src/characters.ts
516
+ const between = (character, low, high) => character.length === 1 && character >= low && character <= high;
517
+ const isDigit = (character) => between(character, "0", "9");
518
+ const isUpper = (character) => between(character, "A", "Z");
519
+ const isWordCharacter = (character) => isDigit(character) || isUpper(character) || between(character, "a", "z") || character === "_";
520
+ const consistsOf = (text, allowed) => text !== "" && text.split("").every(allowed);
521
+ const isDigits = (text) => consistsOf(text, isDigit);
522
+ const codePoints = (text) => Array.from(text, (point) => point);
523
+ // ../cli-core/src/sanitize.ts
524
+ const ESC = 27;
525
+ const BEL = 7;
526
+ const TAB = 9;
527
+ const LINE_FEED = 10;
528
+ const CARRIAGE_RETURN = 13;
529
+ const DELETE = 127;
530
+ const C1_END = 159;
531
+ const SPACE = 32;
532
+ const CSI_FINAL_START = 64;
533
+ const CSI_FINAL_END = 126;
534
+ const C1_CSI = 155;
535
+ const C1_OSC = 157;
536
+ const C1_ST = 156;
537
+ const stringIntroducers = /* @__PURE__ */ new Set([
538
+ "P",
539
+ "X",
540
+ "^",
541
+ "_"
542
+ ]);
543
+ const c1StringIntroducers = /* @__PURE__ */ new Set([
544
+ 144,
545
+ 152,
546
+ 158,
547
+ 159
548
+ ]);
549
+ const formatRanges = [
550
+ [1564, 1564],
551
+ [8203, 8207],
552
+ [8234, 8238],
553
+ [8288, 8303],
554
+ [65279, 65279]
555
+ ];
556
+ const isFormatCharacter = (point) => formatRanges.some(([low, high]) => point >= low && point <= high);
557
+ const keptControls = /* @__PURE__ */ new Set([
558
+ TAB,
559
+ LINE_FEED,
560
+ CARRIAGE_RETURN
561
+ ]);
562
+ const isC0Control = (point) => point < SPACE && !keptControls.has(point);
563
+ const isC1Control = (point) => point >= DELETE && point <= C1_END;
564
+ const isStrippedControl = (point) => isC0Control(point) || isC1Control(point);
565
+ const pointAt = (characters, index) => characters[index]?.codePointAt(0) ?? -1;
566
+ const skipControlSequence = (characters, start) => {
567
+ let index = start;
568
+ while (index < characters.length) {
569
+ const point = pointAt(characters, index);
570
+ if (point >= CSI_FINAL_START && point <= CSI_FINAL_END) return index + 1;
571
+ index += 1;
572
+ }
573
+ return index;
574
+ };
575
+ const skipUntilTerminator = (characters, start, { bell }) => {
576
+ let index = start;
577
+ while (index < characters.length) {
578
+ const point = pointAt(characters, index);
579
+ if (bell && point === BEL || point === C1_ST) return index + 1;
580
+ if (point === ESC && characters[index + 1] === "\\") return index + 2;
581
+ index += 1;
582
+ }
583
+ return index;
584
+ };
585
+ const skipEscape = (characters, start) => {
586
+ const introducer = characters[start + 1];
587
+ if (introducer === "[") return skipControlSequence(characters, start + 2);
588
+ if (introducer === "]") return skipUntilTerminator(characters, start + 2, { bell: true });
589
+ if (introducer !== void 0 && stringIntroducers.has(introducer)) return skipUntilTerminator(characters, start + 2, { bell: false });
590
+ return Math.min(start + 2, characters.length);
591
+ };
592
+ const skipC1 = (characters, start, point) => {
593
+ if (point === C1_CSI) return skipControlSequence(characters, start + 1);
594
+ if (point === C1_OSC) return skipUntilTerminator(characters, start + 1, { bell: true });
595
+ return c1StringIntroducers.has(point) ? skipUntilTerminator(characters, start + 1, { bell: false }) : start + 1;
596
+ };
597
+ const escapedPoint = (point) => point > 255 ? `\\u{${point.toString(16)}}` : `\\x${point.toString(16).padStart(2, "0")}`;
598
+ const escapeUnprintable = (text) => codePoints(text).map((character) => {
599
+ const point = character.codePointAt(0) ?? 0;
600
+ return isStrippedControl(point) || isFormatCharacter(point) ? escapedPoint(point) : character;
601
+ }).join("");
602
+ const remoteText = (text) => {
603
+ const characters = codePoints(text);
604
+ const kept = [];
605
+ let index = 0;
606
+ while (index < characters.length) {
607
+ const point = pointAt(characters, index);
608
+ if (point === ESC) index = skipEscape(characters, index);
609
+ else if (isC1Control(point)) index = skipC1(characters, index, point);
610
+ else {
611
+ if (!isStrippedControl(point) && !isFormatCharacter(point)) kept.push(characters[index] ?? "");
612
+ index += 1;
613
+ }
614
+ }
615
+ return kept.join("");
616
+ };
617
+ const remoteLine = (text) => remoteText(text).replaceAll("\r\n", "\\n").replaceAll("\n", "\\n").replaceAll("\r", "\\r");
618
+ const remoteCell = ({ separated, text }) => {
619
+ const tab = separated ? "\\t" : " ";
620
+ return remoteLine(text).replaceAll(" ", () => tab);
621
+ };
622
+ // ../cli-core/src/theme.ts
623
+ const weights = {
624
+ bold: [1, 22],
625
+ faint: [2, 22],
626
+ underline: [4, 24]
627
+ };
628
+ const hues = {
629
+ cyan: [36, 39],
630
+ green: [32, 39],
631
+ magenta: [35, 39],
632
+ red: [31, 39],
633
+ yellow: [33, 39]
634
+ };
635
+ const wrap = ([open, close], text) => `\u001B[${String(open)}m${text}\u001B[${String(close)}m`;
636
+ const weighted = (style, weight, text) => style.rich && style.color ? wrap(weights[weight], text) : text;
637
+ const tinted = (style, hue, text) => style.rich && style.color ? wrap(hues[hue], text) : text;
638
+ const richGlyphs = {
639
+ error: "✗",
640
+ success: "✓",
641
+ warning: "!"
642
+ };
643
+ const glyphHues = {
644
+ error: "red",
645
+ success: "green",
646
+ warning: "yellow"
647
+ };
648
+ const glyph = (style, kind) => tinted(style, glyphHues[kind], richGlyphs[kind]);
649
+ const plainPrefixes = {
650
+ error: "Error:",
651
+ warning: "Warning:"
652
+ };
653
+ const plainPrefix = (style, kind) => style.color ? wrap(hues[glyphHues[kind]], plainPrefixes[kind]) : plainPrefixes[kind];
654
+ const ellipsis = (style) => style.rich ? "…" : "...";
655
+ const theme = {
656
+ command: (style, text) => tinted(style, "cyan", text),
657
+ heading: (style, text) => style.rich && style.color ? wrap(weights.bold, wrap(hues.magenta, text)) : text,
658
+ link: (style, text) => weighted(style, "underline", text),
659
+ name: (style, text) => weighted(style, "bold", text),
660
+ optional: (style, text) => weighted(style, "faint", text),
661
+ outcome: (style, text) => weighted(style, "bold", text)
662
+ };
663
+ const SPINNER_FRAMES = [
664
+ "⠋",
665
+ "⠙",
666
+ "⠹",
667
+ "⠸",
668
+ "⠼",
669
+ "⠴",
670
+ "⠦",
671
+ "⠧",
672
+ "⠇",
673
+ "⠏"
674
+ ];
675
+ const spinnerFrame = (tick) => SPINNER_FRAMES[tick % SPINNER_FRAMES.length] ?? "";
676
+ const clearLine = "\r\x1B[2K";
677
+ // ../cli-core/src/parse.ts
678
+ const distance = (left, right) => {
679
+ const rightCharacters = codePoints(right);
680
+ const previous = Array.from({ length: rightCharacters.length + 1 }, (_, index) => index);
681
+ for (const [row, leftCharacter] of codePoints(left).entries()) {
682
+ let diagonal = previous[0] ?? 0;
683
+ previous[0] = row + 1;
684
+ for (const [column, rightCharacter] of rightCharacters.entries()) {
685
+ const above = previous[column + 1] ?? 0;
686
+ const before = previous[column] ?? 0;
687
+ previous[column + 1] = Math.min(above + 1, before + 1, diagonal + (leftCharacter === rightCharacter ? 0 : 1));
688
+ diagonal = above;
689
+ }
690
+ }
691
+ return previous[rightCharacters.length] ?? 0;
692
+ };
693
+ const closest = ({ candidates, token }) => {
694
+ const limit = Math.max(1, Math.floor(token.length / 3));
695
+ const [best, runnerUp] = candidates.flatMap((candidate) => {
696
+ const score = distance(token, candidate);
697
+ return score <= limit ? [{
698
+ candidate,
699
+ score
700
+ }] : [];
701
+ }).toSorted((left, right) => left.score - right.score);
702
+ if (best === void 0 || runnerUp !== void 0 && runnerUp.score === best.score) return;
703
+ return best.candidate;
704
+ };
705
+ const findOption = ({ name, options }) => options.find((option) => option.name === name);
706
+ const gluedValue = ({ head, shorts }) => {
707
+ const flags = [];
708
+ for (const character of head.slice(1, -1)) {
709
+ const option = shorts.get(character);
710
+ if (option === void 0) return;
711
+ flags.push(character);
712
+ if (option.kind === "value") {
713
+ const hint = option.hint ?? "<VALUE>";
714
+ return {
715
+ separated: [...flags.map((flag) => `-${flag}`), hint].join(" "),
716
+ spelled: `-${flags.join("")}${hint}`
717
+ };
718
+ }
719
+ }
720
+ };
721
+ const readShort = ({ explicit, head, options }) => {
722
+ const shorts = new Map(options.flatMap((option) => option.short === void 0 ? [] : [[option.short, option]]));
723
+ const glued = gluedValue({
724
+ head,
725
+ shorts
726
+ });
727
+ return {
728
+ explicit,
729
+ negated: false,
730
+ option: head.length === 2 ? shorts.get(head.slice(1)) : void 0,
731
+ spelled: glued?.spelled ?? head,
732
+ suggestion: glued?.separated
733
+ };
734
+ };
735
+ const readLong = ({ explicit, head, options }) => {
736
+ const name = head.slice(2);
737
+ const direct = findOption({
738
+ name,
739
+ options
740
+ });
741
+ if (direct !== void 0 || !name.startsWith("no-")) return {
742
+ explicit,
743
+ negated: false,
744
+ option: direct,
745
+ spelled: head
746
+ };
747
+ const negated = findOption({
748
+ name: name.slice(3),
749
+ options
750
+ });
751
+ const usable = negated?.negatable === true && negated.kind === "flag";
752
+ return {
753
+ explicit,
754
+ negated: usable,
755
+ option: usable ? negated : void 0,
756
+ spelled: head
757
+ };
758
+ };
759
+ const readOptionToken = ({ options, token }) => {
760
+ const equals = token.indexOf("=");
761
+ const head = equals === -1 ? token : token.slice(0, equals);
762
+ const explicit = equals === -1 ? null : token.slice(equals + 1);
763
+ const read = head.startsWith("--") ? readLong({
764
+ explicit,
765
+ head,
766
+ options
767
+ }) : readShort({
768
+ explicit,
769
+ head,
770
+ options
771
+ });
772
+ if (read.option !== void 0) return read;
773
+ const similar = closest({
774
+ candidates: [...new Set(options.map((option) => `--${option.name}`))],
775
+ token: head
776
+ });
777
+ return {
778
+ ...read,
779
+ suggestion: similar ?? read.suggestion
780
+ };
781
+ };
782
+ const booleanText = /* @__PURE__ */ new Map([["false", false], ["true", true]]);
783
+ const isOptionToken = (token) => token.startsWith("-") && token !== "-";
784
+ const isOptionValue = (token) => !isOptionToken(token) || Number.isFinite(Number(token));
785
+ const flagOf = (options, name) => {
786
+ const value = options[name];
787
+ return value?.kind === "flag" ? value.value : void 0;
788
+ };
789
+ const valuesOf = (options, name) => {
790
+ const value = options[name];
791
+ return value?.kind === "value" ? value.values : [];
792
+ };
793
+ const lastValue = (options, name) => valuesOf(options, name).at(-1);
794
+ const rerunArgv = ({ arguments: positionals, options, path }) => {
795
+ const flags = Object.entries(options).flatMap(([name, value]) => {
796
+ if (name === "token") return [];
797
+ if (value.kind === "flag") return [value.value ? `--${name}` : `--no-${name}`];
798
+ return value.values.flatMap((text) => [`--${name}`, text]);
799
+ });
800
+ return [
801
+ ...path,
802
+ ...Object.values(positionals).flat(),
803
+ ...flags
804
+ ];
805
+ };
806
+ const record = (state, option, next) => {
807
+ const previous = state.values.get(option.name);
808
+ state.used.push(option.name);
809
+ if (previous === void 0) {
810
+ state.values.set(option.name, next);
811
+ return;
812
+ }
813
+ const repeat = option.repeat ?? "error";
814
+ if (repeat === "error") {
815
+ state.issues.push({
816
+ field: `--${option.name}`,
817
+ message: `Can't use --${option.name} more than once.`,
818
+ reason: "invalid_arguments"
819
+ });
820
+ return;
821
+ }
822
+ if (repeat === "append" && previous.kind === "value" && next.kind === "value") {
823
+ state.values.set(option.name, {
824
+ kind: "value",
825
+ values: [...previous.values, ...next.values]
826
+ });
827
+ return;
828
+ }
829
+ state.values.set(option.name, next);
830
+ };
831
+ const takePositional = (state, token) => {
832
+ state.positionals.push(token);
833
+ state.index += 1;
834
+ };
835
+ const unknownOption = (state, read) => {
836
+ const hint = read.suggestion === void 0 ? "" : ` Did you mean ${read.suggestion}?`;
837
+ state.issues.push({
838
+ field: read.spelled,
839
+ message: `Unknown option ${read.spelled} for ${state.command}.${hint}`,
840
+ reason: "unknown_option"
841
+ });
842
+ };
843
+ const takeFlag = (state, read, option) => {
844
+ const parsed = read.explicit === null ? !read.negated : booleanText.get(read.explicit.toLowerCase());
845
+ if (parsed === void 0 || read.negated && read.explicit !== null) {
846
+ state.issues.push({
847
+ field: `--${option.name}`,
848
+ message: `--${option.name} takes no value other than true or false.`,
849
+ reason: "invalid_arguments"
850
+ });
851
+ return;
852
+ }
853
+ record(state, option, {
854
+ kind: "flag",
855
+ value: parsed
856
+ });
857
+ };
858
+ const takeValue = (state, read, option) => {
859
+ if (read.explicit !== null) {
860
+ record(state, option, {
861
+ kind: "value",
862
+ values: [read.explicit]
863
+ });
864
+ return;
865
+ }
866
+ const next = state.tokens[state.index];
867
+ if (next === void 0 || !isOptionValue(next)) {
868
+ const example = option.hint === void 0 ? "" : `, such as ${option.hint}`;
869
+ state.issues.push({
870
+ field: `--${option.name}`,
871
+ message: `--${option.name} needs a value${example}.`,
872
+ reason: "invalid_arguments"
873
+ });
874
+ return;
875
+ }
876
+ record(state, option, {
877
+ kind: "value",
878
+ values: [next]
879
+ });
880
+ state.index += 1;
881
+ };
882
+ const takeOption = (state, token) => {
883
+ const read = readOptionToken({
884
+ options: state.options,
885
+ token
886
+ });
887
+ state.index += 1;
888
+ if (read.option === void 0) unknownOption(state, read);
889
+ else if (read.option.kind === "flag") takeFlag(state, read, read.option);
890
+ else takeValue(state, read, read.option);
891
+ };
892
+ const assignArguments = ({ argumentSpecs, command, issues, positionals }) => {
893
+ const assigned = /* @__PURE__ */ new Map();
894
+ let cursor = 0;
895
+ for (const spec of argumentSpecs) {
896
+ const taken = spec.variadic === true ? positionals.slice(cursor) : positionals.slice(cursor, cursor + 1);
897
+ assigned.set(spec.name, taken);
898
+ cursor += taken.length;
899
+ if (spec.optional !== true && taken.length === 0) {
900
+ const missing = spec.missing ?? {
901
+ message: `Can't run ${command} without <${spec.name}>.`,
902
+ reason: "invalid_arguments"
903
+ };
904
+ issues.push({
905
+ field: `<${spec.name}>`,
906
+ message: missing.message,
907
+ reason: missing.reason
908
+ });
909
+ }
910
+ }
911
+ const extra = positionals.slice(cursor);
912
+ if (extra.length > 0) issues.push({
913
+ field: extra.join(" "),
914
+ message: `Unexpected argument ${extra.join(" ")} for ${command}.`,
915
+ reason: "invalid_arguments"
916
+ });
917
+ return Object.fromEntries(assigned);
918
+ };
919
+ const parseLeaf = ({ arguments: argumentSpecs, command, options, tokens }) => {
920
+ const state = {
921
+ command,
922
+ index: 0,
923
+ issues: [],
924
+ literal: false,
925
+ options,
926
+ positionals: [],
927
+ tokens,
928
+ used: [],
929
+ values: /* @__PURE__ */ new Map()
930
+ };
931
+ while (state.index < tokens.length) {
932
+ const token = tokens[state.index] ?? "";
933
+ if (state.literal || !isOptionToken(token)) takePositional(state, token);
934
+ else if (token === "--") {
935
+ state.literal = true;
936
+ state.index += 1;
937
+ } else takeOption(state, token);
938
+ }
939
+ const argumentIssues = [];
940
+ const assigned = assignArguments({
941
+ argumentSpecs,
942
+ command,
943
+ issues: argumentIssues,
944
+ positionals: state.positionals
945
+ });
946
+ const unknown = state.issues.findIndex((issue) => issue.reason === "unknown_option");
947
+ return {
948
+ input: {
949
+ arguments: assigned,
950
+ options: Object.fromEntries(state.values),
951
+ used: state.used
952
+ },
953
+ issues: unknown === -1 ? [...state.issues, ...argumentIssues] : state.issues.slice(0, unknown + 1)
954
+ };
955
+ };
956
+ const parseFailure = ({ bin, issues, path }) => {
957
+ const [first] = issues;
958
+ const several = issues.length > 1;
959
+ return usageFailure({
960
+ help: path,
961
+ issues: issues.map(({ field, message }) => ({
962
+ field,
963
+ message
964
+ })),
965
+ message: several ? `Can't run ${[bin, ...path].join(" ")}. ${String(issues.length)} inputs are invalid.` : first?.message ?? "",
966
+ reason: first?.reason ?? "invalid_arguments"
967
+ });
968
+ };
969
+ // ../cli-core/src/mode.ts
970
+ const DEFAULT_WIDTH = 80;
971
+ const terminalOf = (stream) => ({
972
+ columns: stream.columns,
973
+ tty: stream.isTTY === true
974
+ });
975
+ const falsy = /* @__PURE__ */ new Set([
976
+ "",
977
+ "0",
978
+ "false"
979
+ ]);
980
+ const enabledVariable = (value) => value !== void 0 && !falsy.has(value.trim().toLowerCase());
981
+ const nonempty = (value) => value !== void 0 && value !== "";
982
+ const colorPreference = ({ env, noColor }) => {
983
+ if (noColor || nonempty(env.NO_COLOR)) return false;
984
+ const forced = env.FORCE_COLOR;
985
+ if (forced === void 0) return;
986
+ return forced !== "0" && forced.toLowerCase() !== "false";
987
+ };
988
+ const streamStyle = ({ accessible, color, env, terminal }) => {
989
+ const rich = terminal.tty && env.TERM !== "dumb" && !accessible;
990
+ return {
991
+ color: color ?? rich,
992
+ rich,
993
+ tty: terminal.tty,
994
+ width: terminal.columns !== void 0 && terminal.columns > 0 ? terminal.columns : DEFAULT_WIDTH
995
+ };
996
+ };
997
+ const interactionAllowed = (input, ci) => {
998
+ if (!(input.stdin.tty && input.stderr.tty && !input.payloadStdin) || input.json || ci || input.nonInteractive === true) return false;
999
+ return input.agent === void 0 || input.nonInteractive === false;
1000
+ };
1001
+ const resolveMode = (input) => {
1002
+ const { accessible } = input;
1003
+ const ci = enabledVariable(input.env.CI);
1004
+ const color = colorPreference(input);
1005
+ return {
1006
+ accessible,
1007
+ agent: input.agent,
1008
+ ci,
1009
+ format: input.json ? "json" : "human",
1010
+ githubActions: input.env.GITHUB_ACTIONS === "true",
1011
+ interactive: interactionAllowed(input, ci),
1012
+ stderr: streamStyle({
1013
+ accessible,
1014
+ color,
1015
+ env: input.env,
1016
+ terminal: input.stderr
1017
+ }),
1018
+ stdin: { tty: input.stdin.tty },
1019
+ stdout: streamStyle({
1020
+ accessible,
1021
+ color,
1022
+ env: input.env,
1023
+ terminal: input.stdout
1024
+ })
1025
+ };
1026
+ };
1027
+ const AGENT_VARIABLES = [
1028
+ "AGENT",
1029
+ "AI_AGENT",
1030
+ "AUGMENT_AGENT",
1031
+ "CLAUDECODE",
1032
+ "CLAUDE_CODE",
1033
+ "CODEX_SANDBOX",
1034
+ "CURSOR_AGENT",
1035
+ "GEMINI_CLI",
1036
+ "OPENCODE"
1037
+ ];
1038
+ const productVariable = ({ bin, name }) => `${bin.toUpperCase()}_${name}`;
1039
+ const guidanceOn = ({ bin, env = process.env }) => !enabledVariable(env[productVariable({
1040
+ bin,
1041
+ name: "GUIDANCE_DISABLED"
1042
+ })]);
1043
+ const accessibleOn = ({ bin, env = process.env }) => enabledVariable(env[productVariable({
1044
+ bin,
1045
+ name: "ACCESSIBLE"
1046
+ })]);
1047
+ const modeOf = ({ bin, env = process.env, io, json, noColor, nonInteractive, payloadStdin }) => resolveMode({
1048
+ accessible: accessibleOn({
1049
+ bin,
1050
+ env
1051
+ }),
1052
+ agent: AGENT_VARIABLES.find((name) => enabledVariable(env[name])),
1053
+ env,
1054
+ json,
1055
+ noColor,
1056
+ nonInteractive: nonInteractive ?? null,
1057
+ payloadStdin,
1058
+ stderr: terminalOf(io.stderr),
1059
+ stdin: terminalOf(io.stdin),
1060
+ stdout: terminalOf(io.stdout)
1061
+ });
1062
+ // ../cli-core/src/config.ts
1063
+ const LOCK_POLL = millis(50);
1064
+ const LOCK_STALE_MS = toMillis(seconds(90));
1065
+ const LOCK_WAIT = seconds(20);
1066
+ var LockHeld = class extends TaggedError("LockHeld") {};
1067
+ const configDirectory = ({ bin, cwd, override }) => override === void 0 ? path.join(os.homedir(), ".config", bin) : path.resolve(cwd ?? process.cwd(), override);
1068
+ const writePrivateFile = ({ file, text }) => {
1069
+ const directory = path.dirname(file);
1070
+ fs.mkdirSync(directory, {
1071
+ mode: 448,
1072
+ recursive: true
1073
+ });
1074
+ const pending = path.join(directory, `.${path.basename(file)}.${crypto$1.randomBytes(8).toString("hex")}.tmp`);
1075
+ fs.writeFileSync(pending, text, {
1076
+ flag: "wx",
1077
+ mode: 384
1078
+ });
1079
+ fs.renameSync(pending, file);
1080
+ };
1081
+ const createNew = (file) => sync(() => {
1082
+ fs.mkdirSync(path.dirname(file), {
1083
+ mode: 448,
1084
+ recursive: true
1085
+ });
1086
+ const fd = fs.openSync(file, "wx", 384);
1087
+ const created = fs.fstatSync(fd);
1088
+ fs.closeSync(fd);
1089
+ return created;
1090
+ }).pipe(catchDefect((defect) => hasProperty(defect, "code") && defect.code === "EEXIST" ? fail(new LockHeld()) : die(defect)));
1091
+ const fileMatches = (file, matches) => {
1092
+ const held = fs.statSync(file, { throwIfNoEntry: false });
1093
+ return held !== void 0 && matches(held);
1094
+ };
1095
+ const removeIf = (file, matches) => sync(() => {
1096
+ if (fileMatches(file, matches)) fs.rmSync(file, { force: true });
1097
+ });
1098
+ const staleAt = (now) => (held) => now - held.mtimeMs > LOCK_STALE_MS;
1099
+ const sameAs = (own) => (held) => held.ino === own.ino && held.mtimeMs === own.mtimeMs;
1100
+ const removeStaleLock = ({ lock, now }) => {
1101
+ const takeover = `${lock}.takeover`;
1102
+ return acquireUseRelease(createNew(takeover), () => removeIf(lock, staleAt(now)), (own) => removeIf(takeover, sameAs(own))).pipe(catchTag("LockHeld", () => removeIf(takeover, staleAt(now))));
1103
+ };
1104
+ const takeLock = ({ bin, lock }) => suspend(() => createNew(lock)).pipe(tapError(() => currentTimeMillis.pipe(flatMap((now) => fileMatches(lock, staleAt(now)) ? removeStaleLock({
1105
+ lock,
1106
+ now
1107
+ }) : void_))), retry(spaced(LOCK_POLL).pipe(upTo({ duration: LOCK_WAIT }))), catchTag("LockHeld", () => fail(new CliFailure({
1108
+ blocked: true,
1109
+ context: [{
1110
+ label: "Lock",
1111
+ value: lock
1112
+ }],
1113
+ message: `Can't update the saved login. Another ${bin} command is updating it.`,
1114
+ notes: [`Run the command again once the other ${bin} command finishes.`],
1115
+ reason: "login_locked",
1116
+ retryable: true
1117
+ }))));
1118
+ const withFileLock = ({ bin, file, work }) => {
1119
+ const lock = `${file}.lock`;
1120
+ return acquireUseRelease(takeLock({
1121
+ bin,
1122
+ lock
1123
+ }), () => work, (own) => removeIf(lock, sameAs(own)));
1124
+ };
1125
+ // package.json
1126
+ var version = "0.5.1";
1127
+ // ../format/src/display.ts
1128
+ const LOCALE = "en-US";
1129
+ const UTC = "UTC";
1130
+ new Intl.DateTimeFormat(LOCALE, {
1131
+ day: "numeric",
1132
+ month: "short",
1133
+ timeZone: UTC,
1134
+ year: "numeric"
1135
+ });
1136
+ new Intl.DateTimeFormat(LOCALE, {
1137
+ day: "numeric",
1138
+ month: "long",
1139
+ timeZone: UTC,
1140
+ year: "numeric"
1141
+ });
1142
+ new Intl.DateTimeFormat(LOCALE, {
1143
+ hour: "numeric",
1144
+ minute: "2-digit",
1145
+ timeZone: UTC,
1146
+ timeZoneName: "short"
1147
+ });
1148
+ new Intl.DateTimeFormat(LOCALE, {
1149
+ month: "long",
1150
+ timeZone: UTC,
1151
+ year: "numeric"
1152
+ });
1153
+ new Intl.DateTimeFormat(LOCALE, {
1154
+ day: "numeric",
1155
+ month: "short",
1156
+ timeZone: UTC
1157
+ });
1158
+ const monthName = new Intl.DateTimeFormat(LOCALE, {
1159
+ month: "long",
1160
+ timeZone: UTC
1161
+ });
1162
+ Array.from({ length: 12 }, (_, month) => monthName.format(Date.UTC(2e3, month)));
1163
+ new Intl.DateTimeFormat(LOCALE, {
1164
+ day: "numeric",
1165
+ hour: "numeric",
1166
+ minute: "2-digit",
1167
+ month: "short",
1168
+ timeZone: "America/New_York",
1169
+ timeZoneName: "short",
1170
+ year: "numeric"
1171
+ });
1172
+ new Intl.DateTimeFormat(LOCALE, {
1173
+ day: "2-digit",
1174
+ hour: "2-digit",
1175
+ hourCycle: "h23",
1176
+ minute: "2-digit",
1177
+ month: "2-digit",
1178
+ timeZoneName: "short",
1179
+ year: "numeric"
1180
+ });
1181
+ const moneyFormats = {
1182
+ exact: new Intl.NumberFormat(LOCALE, {
1183
+ currency: "USD",
1184
+ maximumFractionDigits: 2,
1185
+ minimumFractionDigits: 2,
1186
+ style: "currency"
1187
+ }),
1188
+ signed: new Intl.NumberFormat(LOCALE, {
1189
+ currency: "USD",
1190
+ maximumFractionDigits: 2,
1191
+ minimumFractionDigits: 2,
1192
+ signDisplay: "exceptZero",
1193
+ style: "currency"
1194
+ }),
1195
+ subcent: new Intl.NumberFormat(LOCALE, {
1196
+ currency: "USD",
1197
+ maximumSignificantDigits: 3,
1198
+ style: "currency"
1199
+ }),
1200
+ trimmed: new Intl.NumberFormat(LOCALE, {
1201
+ currency: "USD",
1202
+ style: "currency",
1203
+ trailingZeroDisplay: "stripIfInteger"
1204
+ }),
1205
+ whole: new Intl.NumberFormat(LOCALE, {
1206
+ currency: "USD",
1207
+ maximumFractionDigits: 0,
1208
+ style: "currency"
1209
+ })
1210
+ };
1211
+ const formatMoney = ({ cents, style }) => moneyFormats[style].format(cents / 100);
1212
+ const countFormats = {
1213
+ compact: new Intl.NumberFormat(LOCALE, {
1214
+ maximumFractionDigits: 1,
1215
+ notation: "compact"
1216
+ }),
1217
+ whole: new Intl.NumberFormat(LOCALE, { maximumFractionDigits: 0 })
1218
+ };
1219
+ const formatCount = ({ count, style = "whole" }) => countFormats[style].format(count);
1220
+ const plural = new Intl.PluralRules(LOCALE);
1221
+ const counted = ({ count, one, other }) => `${formatCount({ count })} ${plural.select(count) === "one" ? one : other}`;
1222
+ const unitFormat = ({ unit }) => new Intl.NumberFormat(LOCALE, {
1223
+ style: "unit",
1224
+ unit,
1225
+ unitDisplay: "long"
1226
+ });
1227
+ unitFormat({ unit: "hour" }), unitFormat({ unit: "minute" }), unitFormat({ unit: "month" }), unitFormat({ unit: "second" });
1228
+ const percentFormats = {
1229
+ rate: new Intl.NumberFormat(LOCALE, {
1230
+ maximumFractionDigits: 2,
1231
+ minimumFractionDigits: 2,
1232
+ style: "percent"
1233
+ }),
1234
+ whole: new Intl.NumberFormat(LOCALE, {
1235
+ maximumFractionDigits: 0,
1236
+ style: "percent"
1237
+ })
1238
+ };
1239
+ const formatPercent = ({ rate, style }) => percentFormats[style].format(rate);
1240
+ // ../sandcovery-contract/src/problem-report-limits.ts
1241
+ const PROBLEM_REPORT_MAX = 2e3;
1242
+ // src/cli/spec.ts
1243
+ const BIN = "sandcovery";
1244
+ const SETUP_MARK = "# added by sandcovery setup";
1245
+ const NULLABLE_TEXT = "string | null";
1246
+ const NULLABLE_NUMBER = "number | null";
1247
+ const NULLABLE_OBJECT = "object | null";
1248
+ const SANDBOX = "<SANDBOX>";
1249
+ const SPEND_LIMIT = "spend-limit";
1250
+ const NEEDS_MANAGEMENT = "Needs a management key.";
1251
+ const NEEDS_PERSON = "Needs a management key, which acts for the owner who minted it, or a login.";
1252
+ const CLEARABLE = {
1253
+ "expires-at": "expires_at",
1254
+ "max-concurrent": "max_concurrent_sandboxes",
1255
+ "max-ttl": "max_ttl_seconds",
1256
+ provider: "allowed_providers",
1257
+ "spend-limit": "spend_limit"
1258
+ };
1259
+ const flag = (option) => ({
1260
+ ...option,
1261
+ kind: "flag",
1262
+ negatable: true,
1263
+ repeat: "last"
1264
+ });
1265
+ const json = flag({
1266
+ name: "json",
1267
+ summary: "Print the result as one JSON document"
1268
+ });
1269
+ const baseUrl = {
1270
+ defaultText: "https://www.sandcovery.com; SANDCOVERY_BASE_URL also sets it",
1271
+ hint: "<URL>",
1272
+ kind: "value",
1273
+ name: "base-url",
1274
+ summary: "Sandcovery origin to send requests to"
1275
+ };
1276
+ const usageKey = {
1277
+ hint: "<KEY>",
1278
+ kind: "value",
1279
+ name: "key",
1280
+ summary: "Show only this API key, by its ID"
1281
+ };
1282
+ const yes = flag({
1283
+ name: "yes",
1284
+ short: "y",
1285
+ summary: "Confirm without a prompt, after a person has approved"
1286
+ });
1287
+ const limit = (noun) => ({
1288
+ defaultText: "20",
1289
+ hint: "<NUMBER>",
1290
+ kind: "value",
1291
+ name: "limit",
1292
+ short: "n",
1293
+ summary: `Number of ${noun} on the page, from 1 to ${String(100)}`
1294
+ });
1295
+ const next = {
1296
+ hint: "<CURSOR>",
1297
+ kind: "value",
1298
+ name: "next",
1299
+ summary: "Continue after a page, from the cursor that page printed"
1300
+ };
1301
+ const env = {
1302
+ hint: "<NAME=VALUE>",
1303
+ kind: "value",
1304
+ name: "env",
1305
+ repeat: "append",
1306
+ short: "e",
1307
+ summary: "Environment variable to set; repeat for each one"
1308
+ };
1309
+ const provider = (summary) => ({
1310
+ hint: "<PROVIDER>",
1311
+ kind: "value",
1312
+ name: "provider",
1313
+ repeat: "append",
1314
+ short: "p",
1315
+ summary
1316
+ });
1317
+ const required = ({ message, name, reason, summary }) => ({
1318
+ missing: {
1319
+ message,
1320
+ reason
1321
+ },
1322
+ name,
1323
+ summary
1324
+ });
1325
+ const sandboxArgument = (verb) => required({
1326
+ message: `Can't ${verb} without a sandbox ID.`,
1327
+ name: "sandbox",
1328
+ reason: "missing_sandbox",
1329
+ summary: "Sandbox ID, such as sbx_ and a UUID, as sandcovery sandboxes list prints it"
1330
+ });
1331
+ const keyArgument = (verb) => required({
1332
+ message: `Can't ${verb} without a key ID.`,
1333
+ name: "key",
1334
+ reason: "missing_key",
1335
+ summary: "Key ID, such as key_ or mkey_ and a UUID, as sandcovery keys list prints it"
1336
+ });
1337
+ const providerArgument = (verb) => required({
1338
+ message: `Can't ${verb} without a provider.`,
1339
+ name: "provider",
1340
+ reason: "missing_provider",
1341
+ summary: "Provider, such as e2b, as sandcovery providers list prints it"
1342
+ });
1343
+ const pathArgument = (verb) => required({
1344
+ message: `Can't ${verb} without a path in the sandbox.`,
1345
+ name: "path",
1346
+ reason: "missing_path",
1347
+ summary: "Path in the sandbox"
1348
+ });
1349
+ const SANDBOX_RESULT = [
1350
+ {
1351
+ name: "sandbox.id",
1352
+ type: "string"
1353
+ },
1354
+ {
1355
+ name: "sandbox.status",
1356
+ type: "string"
1357
+ },
1358
+ {
1359
+ name: "sandbox.provider",
1360
+ type: NULLABLE_TEXT
1361
+ },
1362
+ {
1363
+ name: "sandbox.expires_at",
1364
+ type: "string"
1365
+ }
1366
+ ];
1367
+ const sandboxLeaf = ({ name, notes, result = SANDBOX_RESULT, summary, verb }) => ({
1368
+ arguments: [sandboxArgument(verb)],
1369
+ examples: [{
1370
+ argv: [
1371
+ "sandboxes",
1372
+ name,
1373
+ SANDBOX
1374
+ ],
1375
+ summary
1376
+ }],
1377
+ kind: "leaf",
1378
+ name,
1379
+ notes,
1380
+ options: [baseUrl, json],
1381
+ result,
1382
+ summary
1383
+ });
1384
+ const keyPolicyOptions = [
1385
+ {
1386
+ hint: "<TIME>",
1387
+ kind: "value",
1388
+ name: "expires-at",
1389
+ summary: "When the key stops working, as a UTC time such as 2026-12-31T00:00:00.000Z"
1390
+ },
1391
+ {
1392
+ hint: "<NUMBER>",
1393
+ kind: "value",
1394
+ name: "max-concurrent",
1395
+ summary: "Most sandboxes the key can run at once"
1396
+ },
1397
+ {
1398
+ hint: "<SECONDS>",
1399
+ kind: "value",
1400
+ name: "max-ttl",
1401
+ summary: "Longest TTL, in seconds, the key can give a sandbox"
1402
+ },
1403
+ provider("Provider the key can create sandboxes on; repeat for each one"),
1404
+ {
1405
+ hint: "<USD>",
1406
+ kind: "value",
1407
+ name: SPEND_LIMIT,
1408
+ summary: "Most the key can spend per --spend-period, in US dollars, such as 25 or 0.50"
1409
+ },
1410
+ {
1411
+ defaultText: "month",
1412
+ hint: "<PERIOD>",
1413
+ kind: "value",
1414
+ name: "spend-period",
1415
+ summary: "Period --spend-limit applies to",
1416
+ values: SpendLimit.fields.period.literals
1417
+ }
1418
+ ];
1419
+ const KEY_RESULT = [
1420
+ {
1421
+ name: "key.id",
1422
+ type: "string"
1423
+ },
1424
+ {
1425
+ name: "key.kind",
1426
+ type: "\"api\" | \"management\""
1427
+ },
1428
+ {
1429
+ name: "key.name",
1430
+ type: "string"
1431
+ },
1432
+ {
1433
+ name: "key.start",
1434
+ type: "string"
1435
+ },
1436
+ {
1437
+ name: "key.revoked_at",
1438
+ type: NULLABLE_TEXT
1439
+ }
1440
+ ];
1441
+ const sandboxSpecOptions = [
1442
+ env,
1443
+ {
1444
+ hint: "<SECONDS>",
1445
+ kind: "value",
1446
+ name: "idle-timeout",
1447
+ summary: "Seconds without a command after which the provider may pause the sandbox"
1448
+ },
1449
+ {
1450
+ hint: "<IMAGE>",
1451
+ kind: "value",
1452
+ name: "image",
1453
+ summary: "Image to start from, on providers that run custom images"
1454
+ },
1455
+ {
1456
+ hint: "<PORT>",
1457
+ kind: "value",
1458
+ name: "port",
1459
+ repeat: "append",
1460
+ summary: "Port to expose for previews; repeat for each one"
1461
+ },
1462
+ provider("Provider to run on; repeat to allow several, tried in the order given"),
1463
+ {
1464
+ defaultText: "the provider's",
1465
+ hint: "<REGION>",
1466
+ kind: "value",
1467
+ name: "region",
1468
+ short: "r",
1469
+ summary: "Region to run in, such as us, eu, or asia"
1470
+ },
1471
+ {
1472
+ defaultText: DEFAULT_SLUG,
1473
+ hint: "<SLUG>",
1474
+ kind: "value",
1475
+ name: "slug",
1476
+ repeat: "append",
1477
+ short: "s",
1478
+ summary: "Provider and size as <provider>/<vcpu>x<memory_gib>, such as sandcovery/2x4, boat/2x4, or sandcovery/nx16:fastest, routed as :cheapest unless it ends in :fastest or :most-reliable; repeat to try each slug in order"
1479
+ },
1480
+ {
1481
+ defaultText: "price",
1482
+ hint: "<SORT>",
1483
+ kind: "value",
1484
+ name: "sort",
1485
+ summary: "How to rank each slug's candidates; a slug's routing suffix must agree with it",
1486
+ values: ProviderSort.literals
1487
+ },
1488
+ {
1489
+ defaultText: "the key's maximum",
1490
+ hint: "<SECONDS>",
1491
+ kind: "value",
1492
+ name: "ttl",
1493
+ summary: "Seconds until Sandcovery destroys the sandbox"
1494
+ }
1495
+ ];
1496
+ const sandboxesList = {
1497
+ arguments: [],
1498
+ examples: [{
1499
+ argv: ["sandboxes", "list"],
1500
+ summary: "List your newest sandboxes"
1501
+ }, {
1502
+ argv: [
1503
+ "sandboxes",
1504
+ "list",
1505
+ "--status",
1506
+ "running",
1507
+ "--json"
1508
+ ],
1509
+ summary: "List running sandboxes in a script"
1510
+ }],
1511
+ kind: "leaf",
1512
+ name: "list",
1513
+ notes: ["Sandboxes list newest first, one page per run. --next continues after the page that printed it."],
1514
+ options: [
1515
+ baseUrl,
1516
+ json,
1517
+ limit("sandboxes"),
1518
+ next,
1519
+ {
1520
+ hint: "<STATUS>",
1521
+ kind: "value",
1522
+ name: "status",
1523
+ summary: "List only sandboxes in this status",
1524
+ values: SandboxStatus.literals
1525
+ }
1526
+ ],
1527
+ result: [
1528
+ {
1529
+ name: "sandboxes",
1530
+ type: "array"
1531
+ },
1532
+ {
1533
+ name: "sandboxes[].id",
1534
+ type: "string"
1535
+ },
1536
+ {
1537
+ name: "sandboxes[].status",
1538
+ type: "string"
1539
+ },
1540
+ {
1541
+ name: "next_cursor",
1542
+ type: NULLABLE_TEXT
1543
+ }
1544
+ ],
1545
+ shortcuts: ["ls"],
1546
+ summary: "List your sandboxes, newest first"
1547
+ };
1548
+ const sandboxesCreate = {
1549
+ arguments: [],
1550
+ examples: [
1551
+ {
1552
+ argv: ["sandboxes", "create"],
1553
+ summary: `Create a ${DEFAULT_SLUG} sandbox on the best provider`
1554
+ },
1555
+ {
1556
+ argv: [
1557
+ "sandboxes",
1558
+ "create",
1559
+ "--slug",
1560
+ "sandcovery/4x8:cheapest",
1561
+ "--ttl",
1562
+ "600",
1563
+ "--json"
1564
+ ],
1565
+ summary: "Create the cheapest 4x8 sandbox for 10 minutes in a script"
1566
+ },
1567
+ {
1568
+ argv: [
1569
+ "sandboxes",
1570
+ "create",
1571
+ "--slug",
1572
+ "boat/2x4",
1573
+ "--slug",
1574
+ "sandcovery/nx4:cheapest"
1575
+ ],
1576
+ summary: "Try boat at 2x4 first, then the cheapest provider with 4 GiB at any vCPU count"
1577
+ },
1578
+ {
1579
+ argv: [
1580
+ "sandboxes",
1581
+ "create",
1582
+ "--provider",
1583
+ "e2b",
1584
+ "--provider",
1585
+ "daytona"
1586
+ ],
1587
+ summary: "Try E2B first, then Daytona"
1588
+ }
1589
+ ],
1590
+ kind: "leaf",
1591
+ name: "create",
1592
+ notes: [
1593
+ "A slug pins a provider, or routes across every candidate provider when it starts with sandcovery/. Each slug falls back across its candidates on capacity, quota, timeout, and server errors, unless --no-fallbacks is given, and then the create moves to the next --slug.",
1594
+ "Each create sends an idempotency key, so the CLI retries a create that got no answer without making a second sandbox.",
1595
+ "When stdout is not a terminal, the command prints the sandbox ID there."
1596
+ ],
1597
+ options: [
1598
+ baseUrl,
1599
+ flag({
1600
+ name: "fallbacks",
1601
+ summary: "Fall back to the next provider when one fails; --no-fallbacks stops at the first failure"
1602
+ }),
1603
+ json,
1604
+ ...sandboxSpecOptions,
1605
+ {
1606
+ hint: "<SNAPSHOT>",
1607
+ kind: "value",
1608
+ name: "snapshot",
1609
+ summary: "Snapshot ID to restore, as sandcovery sandboxes snapshot prints it"
1610
+ }
1611
+ ],
1612
+ result: [...SANDBOX_RESULT, {
1613
+ name: "sandbox.attempts",
1614
+ type: "array"
1615
+ }],
1616
+ summary: "Create a sandbox"
1617
+ };
1618
+ const sandboxesExec = {
1619
+ arguments: [sandboxArgument("run a command"), {
1620
+ missing: {
1621
+ message: "Can't run a command without the command, after --.",
1622
+ reason: "missing_command"
1623
+ },
1624
+ name: "command",
1625
+ summary: "Command to run, after --; like ssh, its words join with spaces and run in the sandbox's shell",
1626
+ variadic: true
1627
+ }],
1628
+ examples: [
1629
+ {
1630
+ argv: [
1631
+ "sandboxes",
1632
+ "exec",
1633
+ SANDBOX,
1634
+ "--",
1635
+ "ls",
1636
+ "-la"
1637
+ ],
1638
+ summary: "List the working directory"
1639
+ },
1640
+ {
1641
+ argv: [
1642
+ "sandboxes",
1643
+ "exec",
1644
+ SANDBOX,
1645
+ "--json",
1646
+ "--",
1647
+ "npm",
1648
+ "test"
1649
+ ],
1650
+ summary: "Run the tests and read their output and exit code in a script"
1651
+ },
1652
+ {
1653
+ argv: [
1654
+ "sandboxes",
1655
+ "exec",
1656
+ SANDBOX,
1657
+ "--detach",
1658
+ "--",
1659
+ "node",
1660
+ "server.js",
1661
+ ">server.log",
1662
+ "2>&1"
1663
+ ],
1664
+ summary: "Start a server that keeps running after the CLI exits"
1665
+ },
1666
+ {
1667
+ argv: [
1668
+ "sandboxes",
1669
+ "exec",
1670
+ SANDBOX,
1671
+ "--interactive",
1672
+ "--tty",
1673
+ "--",
1674
+ "bash"
1675
+ ],
1676
+ summary: "Open a shell in the sandbox"
1677
+ },
1678
+ {
1679
+ argv: [
1680
+ "sandboxes",
1681
+ "exec",
1682
+ SANDBOX,
1683
+ "--interactive",
1684
+ "--",
1685
+ "wc",
1686
+ "-l"
1687
+ ],
1688
+ summary: "Count the lines piped to the CLI"
1689
+ }
1690
+ ],
1691
+ kind: "leaf",
1692
+ name: "exec",
1693
+ notes: [
1694
+ "The command's stdout and stderr stream to this terminal's, and the CLI exits with the command's exit code.",
1695
+ "With --json, the CLI waits for the command and prints its stdout, stderr, exit code, and duration as one document.",
1696
+ "With --detach, the CLI returns once the provider starts the command, which keeps running until it exits or the sandbox ends, and its output is not kept, so redirect it to a file to read it later. A provider with no detached commands answers unsupported.",
1697
+ "With --interactive, the CLI sends its stdin to the command until stdin ends. With --tty, the command's stdout and stderr, and its stdin with --interactive, sit on a terminal of this terminal's size, and the output reaches this terminal unchanged. Either one runs the command as a process with no timeout that survives a dropped connection; Ctrl-C reaches the command, and a second Ctrl-C without --tty leaves it running and exits the CLI.",
1698
+ "The CLI never retries a command, since running it twice may change the sandbox twice."
1699
+ ],
1700
+ options: [
1701
+ baseUrl,
1702
+ {
1703
+ hint: "<DIR>",
1704
+ kind: "value",
1705
+ name: "cwd",
1706
+ summary: "Directory in the sandbox to run the command in"
1707
+ },
1708
+ flag({
1709
+ name: "detach",
1710
+ summary: "Start the command and return at once, leaving it running in the sandbox"
1711
+ }),
1712
+ env,
1713
+ flag({
1714
+ name: "interactive",
1715
+ summary: "Send this CLI's stdin to the command"
1716
+ }),
1717
+ json,
1718
+ {
1719
+ hint: "<SECONDS>",
1720
+ kind: "value",
1721
+ name: "timeout",
1722
+ summary: "Seconds after which the provider stops the command"
1723
+ },
1724
+ flag({
1725
+ name: "tty",
1726
+ summary: "Run the command on a terminal, as ssh -t does"
1727
+ })
1728
+ ],
1729
+ result: [
1730
+ {
1731
+ name: "exec.exit_code",
1732
+ type: "number"
1733
+ },
1734
+ {
1735
+ name: "exec.stdout",
1736
+ type: "string"
1737
+ },
1738
+ {
1739
+ name: "exec.stderr",
1740
+ type: "string"
1741
+ },
1742
+ {
1743
+ name: "exec.duration_ms",
1744
+ type: "number"
1745
+ },
1746
+ {
1747
+ name: "exec.started_at",
1748
+ type: "string"
1749
+ }
1750
+ ],
1751
+ summary: "Run a command in a sandbox"
1752
+ };
1753
+ const sandboxesDestroy = {
1754
+ arguments: [sandboxArgument("destroy a sandbox")],
1755
+ examples: [{
1756
+ argv: [
1757
+ "sandboxes",
1758
+ "destroy",
1759
+ SANDBOX
1760
+ ],
1761
+ summary: "Destroy a sandbox after a prompt"
1762
+ }, {
1763
+ argv: [
1764
+ "sandboxes",
1765
+ "destroy",
1766
+ SANDBOX,
1767
+ "--yes"
1768
+ ],
1769
+ summary: "Destroy it in a script, after a person approved"
1770
+ }],
1771
+ kind: "leaf",
1772
+ name: "destroy",
1773
+ notes: ["Destroying a sandbox deletes its files and stops its commands. It asks first, and needs --yes without a terminal.", "Destroying a sandbox that already ended changes nothing."],
1774
+ options: [
1775
+ baseUrl,
1776
+ json,
1777
+ yes
1778
+ ],
1779
+ result: SANDBOX_RESULT,
1780
+ shortcuts: ["delete", "rm"],
1781
+ summary: "Destroy a sandbox and everything in it"
1782
+ };
1783
+ const sandboxesPortsInspect = {
1784
+ arguments: [sandboxArgument("preview a port"), required({
1785
+ message: "Can't preview a port without its number.",
1786
+ name: "port",
1787
+ reason: "missing_port",
1788
+ summary: "Port the sandbox exposes, as sandcovery sandboxes create --port set it"
1789
+ })],
1790
+ examples: [{
1791
+ argv: [
1792
+ "sandboxes",
1793
+ "ports",
1794
+ "inspect",
1795
+ SANDBOX,
1796
+ "3000"
1797
+ ],
1798
+ summary: "Print a port's preview URL"
1799
+ }],
1800
+ kind: "leaf",
1801
+ name: "inspect",
1802
+ notes: ["Prints the preview URL and any headers a request to it needs. The headers can grant access to the sandbox, so treat them as secrets."],
1803
+ options: [baseUrl, json],
1804
+ result: [
1805
+ {
1806
+ name: "preview.url",
1807
+ type: "string"
1808
+ },
1809
+ {
1810
+ name: "preview.headers",
1811
+ secret: true,
1812
+ type: "object"
1813
+ },
1814
+ {
1815
+ name: "preview.expires_at",
1816
+ type: NULLABLE_TEXT
1817
+ }
1818
+ ],
1819
+ summary: "Print a port's preview URL"
1820
+ };
1821
+ const sandboxesProcessesInspect = {
1822
+ arguments: [sandboxArgument("show a process"), required({
1823
+ message: "Can't show a process without its ID.",
1824
+ name: "process",
1825
+ reason: "missing_process",
1826
+ summary: "Process ID, such as proc_ and a UUID"
1827
+ })],
1828
+ examples: [{
1829
+ argv: [
1830
+ "sandboxes",
1831
+ "processes",
1832
+ "inspect",
1833
+ SANDBOX,
1834
+ "<PROCESS>"
1835
+ ],
1836
+ summary: "Show a process's status and exit code"
1837
+ }],
1838
+ kind: "leaf",
1839
+ name: "inspect",
1840
+ notes: ["A process is running until its command exits, then exited, or lost when the sandbox ended before the process reported an exit."],
1841
+ options: [baseUrl, json],
1842
+ result: [
1843
+ {
1844
+ name: "process.id",
1845
+ type: "string"
1846
+ },
1847
+ {
1848
+ name: "process.status",
1849
+ type: "\"exited\" | \"lost\" | \"running\""
1850
+ },
1851
+ {
1852
+ name: "process.exit_code",
1853
+ type: NULLABLE_NUMBER
1854
+ },
1855
+ {
1856
+ name: "process.signal",
1857
+ type: NULLABLE_TEXT
1858
+ }
1859
+ ],
1860
+ summary: "Show a process"
1861
+ };
1862
+ const filesList = {
1863
+ arguments: [sandboxArgument("list files"), pathArgument("list files")],
1864
+ examples: [{
1865
+ argv: [
1866
+ "sandboxes",
1867
+ "files",
1868
+ "list",
1869
+ SANDBOX,
1870
+ "logs"
1871
+ ],
1872
+ summary: "List a directory"
1873
+ }],
1874
+ kind: "leaf",
1875
+ name: "list",
1876
+ notes: ["Lists the entries of one directory, without descending into subdirectories."],
1877
+ options: [baseUrl, json],
1878
+ result: [{
1879
+ name: "files.path",
1880
+ type: "string"
1881
+ }, {
1882
+ name: "files.entries",
1883
+ type: "array"
1884
+ }],
1885
+ shortcuts: ["ls"],
1886
+ summary: "List a directory in a sandbox"
1887
+ };
1888
+ const filesRead = {
1889
+ arguments: [sandboxArgument("read a file"), pathArgument("read a file")],
1890
+ examples: [{
1891
+ argv: [
1892
+ "sandboxes",
1893
+ "files",
1894
+ "read",
1895
+ SANDBOX,
1896
+ "logs/out.txt"
1897
+ ],
1898
+ summary: "Print a file"
1899
+ }, {
1900
+ argv: [
1901
+ "sandboxes",
1902
+ "files",
1903
+ "read",
1904
+ SANDBOX,
1905
+ "build.tar"
1906
+ ],
1907
+ summary: "Copy a file out, with stdout redirected to a local file"
1908
+ }],
1909
+ kind: "leaf",
1910
+ name: "read",
1911
+ notes: ["Writes the file's bytes to stdout unchanged when stdout is not a terminal."],
1912
+ options: [baseUrl],
1913
+ result: [],
1914
+ shortcuts: ["cat"],
1915
+ summary: "Print a file from a sandbox"
1916
+ };
1917
+ const filesWrite = {
1918
+ arguments: [sandboxArgument("write a file"), pathArgument("write a file")],
1919
+ examples: [{
1920
+ argv: [
1921
+ "sandboxes",
1922
+ "files",
1923
+ "write",
1924
+ SANDBOX,
1925
+ "in.txt",
1926
+ "--from",
1927
+ "in.txt"
1928
+ ],
1929
+ summary: "Copy a local file into a sandbox"
1930
+ }, {
1931
+ argv: [
1932
+ "sandboxes",
1933
+ "files",
1934
+ "write",
1935
+ SANDBOX,
1936
+ "in.txt",
1937
+ "--from",
1938
+ "-"
1939
+ ],
1940
+ summary: "Write stdin to a file"
1941
+ }],
1942
+ kind: "leaf",
1943
+ name: "write",
1944
+ notes: ["Replaces the file at the path when one exists."],
1945
+ options: [
1946
+ baseUrl,
1947
+ {
1948
+ hint: "<FILE|->",
1949
+ kind: "value",
1950
+ name: "from",
1951
+ required: true,
1952
+ stdin: true,
1953
+ summary: "Local file to upload, or - for stdin"
1954
+ },
1955
+ json
1956
+ ],
1957
+ result: [{
1958
+ name: "file.path",
1959
+ type: "string"
1960
+ }, {
1961
+ name: "file.size_bytes",
1962
+ type: NULLABLE_NUMBER
1963
+ }],
1964
+ summary: "Write a file into a sandbox"
1965
+ };
1966
+ const docker = {
1967
+ arguments: [{
1968
+ name: "args",
1969
+ optional: true,
1970
+ summary: "Arguments for docker, every word passed on unchanged, so sandcovery options such as --base-url go before docker",
1971
+ variadic: true
1972
+ }],
1973
+ examples: [
1974
+ {
1975
+ argv: [
1976
+ "docker",
1977
+ "build",
1978
+ "--tag",
1979
+ "app",
1980
+ "."
1981
+ ],
1982
+ summary: "Build an image from the working directory in a sandbox"
1983
+ },
1984
+ {
1985
+ argv: [
1986
+ "docker",
1987
+ "run",
1988
+ "--rm",
1989
+ "app"
1990
+ ],
1991
+ summary: "Run a container from it in the same sandbox"
1992
+ },
1993
+ {
1994
+ argv: [
1995
+ "docker",
1996
+ "compose",
1997
+ "up",
1998
+ "--build",
1999
+ "--detach"
2000
+ ],
2001
+ summary: "Start the Compose project in the working directory"
2002
+ }
2003
+ ],
2004
+ kind: "leaf",
2005
+ name: "docker",
2006
+ notes: [
2007
+ "Runs the Docker CLI in a sandbox with every word after docker, streams its stdout and stderr to this terminal's, and exits with its exit code.",
2008
+ "The first command starts a sandbox on a provider that runs Docker, as Sandcovery CI runners do, and later commands reuse it until it ends at its TTL, so images, containers, and volumes carry over between commands. sandcovery sandboxes destroy ends it sooner.",
2009
+ "Before docker runs, the command copies the local files it reads into the sandbox at the same absolute paths, up to 100 MiB packed, and runs docker in the same working directory there, so relative and absolute paths resolve as they do here. Those files are the build context of build and bake without what .dockerignore leaves out, the files of a build's -f, --build-context, and --secret, the bind mount sources and env files of run and create, and the file that cp, load -i, or import reads.",
2010
+ "compose copies its Compose files and env files and, for commands that build or start containers, each build context and each bind-mounted file or directory. ps, logs, down, and other commands that only read the project copy only the Compose files and env files. Variables in Compose files come only from .env and --env-file, and ~ in a Compose file names the home folder of the sandbox.",
2011
+ "Only paths under your home folder or the working directory are copied, a symlink arrives as the link itself, and a path through a symlinked folder fails. What containers wrote stays in the sandbox and never comes back here, and a file deleted here since the last copy is deleted there.",
2012
+ "When stdin is not a terminal and docker reads it, as with -i on run or exec without -d, start -i, login --password-stdin, load, import -, build -, or cp -, the command streams stdin to docker as it reads it.",
2013
+ "When stdout is not a terminal and docker writes an archive there, as with save or export without -o, cp to -, or build -o -, the archive arrives byte for byte. save and export without -o refuse a terminal, as docker does.",
2014
+ "A TCP port a container publishes answers on the same address and port here, through a process the command starts in the background, until the sandbox ends. A port another program here listens on, or one only an administrator may listen on, stays in the sandbox, and the command warns once.",
2015
+ "docker gets a terminal in the sandbox wherever this command's stdin, stdout, or stderr is one, so docker run -it, docker exec -it, and docker attach work. A command runs until it exits, and the sandbox stays up past its TTL while it runs.",
2016
+ "sandcovery-docker takes docker arguments alone, runs them in the same sandbox, and adds nothing to docker output, so alias docker=sandcovery-docker runs docker here."
2017
+ ],
2018
+ options: [baseUrl],
2019
+ passthrough: true,
2020
+ result: [],
2021
+ summary: "Run a docker command in a sandbox"
2022
+ };
2023
+ const kubectl = {
2024
+ arguments: [{
2025
+ name: "args",
2026
+ optional: true,
2027
+ summary: "Arguments for kubectl, every word passed on unchanged, so sandcovery options such as --base-url go before kubectl",
2028
+ variadic: true
2029
+ }],
2030
+ examples: [
2031
+ {
2032
+ argv: [
2033
+ "kubectl",
2034
+ "apply",
2035
+ "--filename",
2036
+ "deployment.yaml"
2037
+ ],
2038
+ summary: "Apply a local manifest to a cluster in a sandbox"
2039
+ },
2040
+ {
2041
+ argv: [
2042
+ "kubectl",
2043
+ "get",
2044
+ "pods"
2045
+ ],
2046
+ summary: "List the pods of that cluster"
2047
+ },
2048
+ {
2049
+ argv: [
2050
+ "kubectl",
2051
+ "port-forward",
2052
+ "deployment/app",
2053
+ "8080:80"
2054
+ ],
2055
+ summary: "Reach a pod on port 8080 of this computer"
2056
+ }
2057
+ ],
2058
+ kind: "leaf",
2059
+ name: "kubectl",
2060
+ notes: [
2061
+ "Runs your own kubectl with every word after kubectl against a one-node Kubernetes cluster in a sandbox, so the output and exit code are kubectl's, local files reach apply -f, and port-forward, exec -it, and logs -f work as they do with a local cluster. kubectl must be on PATH.",
2062
+ "The first command that reaches the cluster starts a 2x4 sandbox on Freestyle, or a 2x8 sandbox on boxd when Freestyle cannot create it, and waits a few minutes for the cluster. Later commands reuse it, so what you applied carries over between commands. It stops 15 minutes after the last command that reached it ends, or at its TTL, whichever comes first, and a command that keeps running, such as port-forward or logs -f, keeps it running. sandcovery sandboxes destroy ends it sooner.",
2063
+ "kubectl reads a kubeconfig the CLI keeps beside its settings, through KUBECONFIG, so --kubeconfig names your own clusters instead. completion, config, help, kustomize, options, plugin, version --client, and --help start no cluster.",
2064
+ "sandcovery-kubectl takes kubectl arguments alone and adds nothing to kubectl output, so alias kubectl=sandcovery-kubectl runs kubectl here."
2065
+ ],
2066
+ options: [baseUrl],
2067
+ passthrough: true,
2068
+ result: [],
2069
+ summary: "Run a kubectl command against a cluster in a sandbox"
2070
+ };
2071
+ const setup = {
2072
+ arguments: [],
2073
+ examples: [{
2074
+ argv: ["setup"],
2075
+ summary: "Run docker, kubectl, and the other drop-ins on sandboxes"
2076
+ }, {
2077
+ argv: ["setup", "--undo"],
2078
+ summary: "Remove every shim and every line setup added"
2079
+ }],
2080
+ kind: "leaf",
2081
+ name: "setup",
2082
+ notes: [
2083
+ "Writes a shim for each Sandcovery drop-in on PATH, such as docker for sandcovery-docker and kubectl for sandcovery-kubectl, into the bin folder beside the CLI settings, and adds a line that puts that folder first on PATH to the startup files of bash, zsh, and fish.",
2084
+ "Lists every change and asks first, and without a terminal it needs --yes. Run it again after installing a new drop-in; with nothing to change, it changes nothing.",
2085
+ `Each shim and line it adds is marked "${SETUP_MARK}", and --undo removes only those. Your own docker or kubectl stays where it is and runs by its full path.`
2086
+ ],
2087
+ options: [
2088
+ json,
2089
+ flag({
2090
+ name: "undo",
2091
+ summary: "Remove every shim and every line setup added"
2092
+ }),
2093
+ yes
2094
+ ],
2095
+ result: [
2096
+ {
2097
+ name: "changes[].action",
2098
+ type: "\"append\" | \"delete\" | \"remove\" | \"write\""
2099
+ },
2100
+ {
2101
+ name: "changes[].file",
2102
+ type: "string"
2103
+ },
2104
+ {
2105
+ name: "changes[].line",
2106
+ type: NULLABLE_NUMBER
2107
+ },
2108
+ {
2109
+ name: "changes[].text",
2110
+ type: NULLABLE_TEXT
2111
+ },
2112
+ {
2113
+ name: "drop_ins[].binary",
2114
+ type: "string"
2115
+ },
2116
+ {
2117
+ name: "drop_ins[].installed",
2118
+ type: "boolean"
2119
+ },
2120
+ {
2121
+ name: "drop_ins[].real_path",
2122
+ type: NULLABLE_TEXT
2123
+ },
2124
+ {
2125
+ name: "drop_ins[].tool",
2126
+ type: "string"
2127
+ }
2128
+ ],
2129
+ summary: "Run docker, kubectl, and other drop-ins on sandboxes"
2130
+ };
2131
+ const login = {
2132
+ arguments: [],
2133
+ examples: [{
2134
+ argv: ["login"],
2135
+ summary: "Log in with a browser"
2136
+ }, {
2137
+ argv: ["login", "--no-open"],
2138
+ summary: "Print the login URL instead of opening a browser"
2139
+ }],
2140
+ kind: "leaf",
2141
+ name: "login",
2142
+ notes: ["Shows a login URL and a code, then waits while a person signed in to Sandcovery approves that code in a browser. The login is saved, readable only by you, beside the CLI settings, and renews itself until you log out.", "Commands send --token or SANDCOVERY_API_KEY when either is set, and the saved login otherwise. Without a terminal, set SANDCOVERY_API_KEY instead."],
2143
+ options: [
2144
+ baseUrl,
2145
+ flag({
2146
+ name: "open",
2147
+ summary: "Open the login URL in a browser; the default where one can open, and --no-open only prints it"
2148
+ }),
2149
+ json
2150
+ ],
2151
+ result: [],
2152
+ summary: "Log in with a browser, so commands need no key"
2153
+ };
2154
+ const logout = {
2155
+ arguments: [],
2156
+ examples: [{
2157
+ argv: ["logout"],
2158
+ summary: "Log out on this computer"
2159
+ }],
2160
+ kind: "leaf",
2161
+ name: "logout",
2162
+ notes: ["Revokes the saved login at Sandcovery and deletes it. Keys in --token or SANDCOVERY_API_KEY stay as they are."],
2163
+ options: [json],
2164
+ result: [{
2165
+ name: "logout.origin",
2166
+ type: NULLABLE_TEXT
2167
+ }, {
2168
+ name: "logout.revoked",
2169
+ type: "boolean"
2170
+ }],
2171
+ summary: "Log out and delete the saved login"
2172
+ };
2173
+ const sandboxes = {
2174
+ children: [
2175
+ sandboxesList,
2176
+ sandboxesCreate,
2177
+ sandboxLeaf({
2178
+ name: "inspect",
2179
+ notes: ["Prints the sandbox, its cost so far, and every create attempt."],
2180
+ result: [...SANDBOX_RESULT, {
2181
+ name: "sandbox.cost",
2182
+ type: "object"
2183
+ }],
2184
+ summary: "Show one sandbox",
2185
+ verb: "show a sandbox"
2186
+ }),
2187
+ sandboxesExec,
2188
+ sandboxesDestroy,
2189
+ sandboxLeaf({
2190
+ name: "pause",
2191
+ notes: ["Pausing keeps the memory and files where the provider can. The TTL keeps counting."],
2192
+ summary: "Pause a sandbox",
2193
+ verb: "pause a sandbox"
2194
+ }),
2195
+ sandboxLeaf({
2196
+ name: "resume",
2197
+ notes: ["Resumes a paused sandbox with its files as they were."],
2198
+ summary: "Resume a paused sandbox",
2199
+ verb: "resume a sandbox"
2200
+ }),
2201
+ sandboxLeaf({
2202
+ name: "snapshot",
2203
+ notes: ["Saves the sandbox as a snapshot that sandcovery sandboxes create --snapshot restores."],
2204
+ result: [{
2205
+ name: "snapshot.id",
2206
+ type: "string"
2207
+ }, {
2208
+ name: "snapshot.provider",
2209
+ type: "string"
2210
+ }],
2211
+ summary: "Snapshot a sandbox",
2212
+ verb: "snapshot a sandbox"
2213
+ }),
2214
+ {
2215
+ children: [
2216
+ filesList,
2217
+ filesRead,
2218
+ filesWrite
2219
+ ],
2220
+ kind: "group",
2221
+ name: "files",
2222
+ shortcuts: ["file"],
2223
+ summary: "List, read, and write files in a sandbox"
2224
+ },
2225
+ {
2226
+ children: [sandboxesPortsInspect],
2227
+ defaultChild: "inspect",
2228
+ kind: "group",
2229
+ name: "ports",
2230
+ shortcuts: ["port"],
2231
+ summary: "Preview a sandbox's ports"
2232
+ },
2233
+ {
2234
+ children: [sandboxesProcessesInspect],
2235
+ defaultChild: "inspect",
2236
+ kind: "group",
2237
+ name: "processes",
2238
+ shortcuts: ["process"],
2239
+ summary: "Show the processes of a sandbox"
2240
+ }
2241
+ ],
2242
+ kind: "group",
2243
+ name: "sandboxes",
2244
+ shortcuts: ["sandbox", "sbx"],
2245
+ summary: "Create, run, and destroy sandboxes"
2246
+ };
2247
+ const keysCreate = {
2248
+ arguments: [],
2249
+ examples: [{
2250
+ argv: [
2251
+ "keys",
2252
+ "create",
2253
+ "--name",
2254
+ "ci"
2255
+ ],
2256
+ summary: "Create an API key for CI"
2257
+ }, {
2258
+ argv: [
2259
+ "keys",
2260
+ "create",
2261
+ "--name",
2262
+ "ci",
2263
+ "--max-ttl",
2264
+ "3600",
2265
+ "--spend-limit",
2266
+ "50",
2267
+ "--json"
2268
+ ],
2269
+ summary: "Create a capped API key in a script"
2270
+ }],
2271
+ kind: "leaf",
2272
+ name: "create",
2273
+ notes: ["Prints the secret once. Sandcovery keeps only its first 12 characters, so store it before you close the terminal.", NEEDS_MANAGEMENT],
2274
+ options: [
2275
+ baseUrl,
2276
+ json,
2277
+ ...keyPolicyOptions,
2278
+ {
2279
+ defaultText: "api",
2280
+ hint: "<KIND>",
2281
+ kind: "value",
2282
+ name: "kind",
2283
+ summary: "api for sandboxes, or management for keys, usage, and credentials",
2284
+ values: KeyKind.literals
2285
+ },
2286
+ {
2287
+ hint: "<NAME>",
2288
+ kind: "value",
2289
+ name: "name",
2290
+ required: true,
2291
+ summary: "Name to recognize the key by, up to 100 characters"
2292
+ }
2293
+ ],
2294
+ result: [...KEY_RESULT, {
2295
+ name: "secret",
2296
+ secret: true,
2297
+ type: "string"
2298
+ }],
2299
+ summary: "Create an API key or management key"
2300
+ };
2301
+ const keysUpdate = {
2302
+ arguments: [keyArgument("update a key")],
2303
+ examples: [{
2304
+ argv: [
2305
+ "keys",
2306
+ "update",
2307
+ "<KEY>",
2308
+ "--max-ttl",
2309
+ "7200"
2310
+ ],
2311
+ summary: "Raise a key's longest TTL"
2312
+ }, {
2313
+ argv: [
2314
+ "keys",
2315
+ "update",
2316
+ "<KEY>",
2317
+ "--clear",
2318
+ SPEND_LIMIT
2319
+ ],
2320
+ summary: "Remove a key's spend limit"
2321
+ }],
2322
+ kind: "leaf",
2323
+ name: "update",
2324
+ notes: ["Changes only the fields you pass. --clear removes a limit or expiry, so the key has none.", NEEDS_MANAGEMENT],
2325
+ options: [
2326
+ baseUrl,
2327
+ {
2328
+ hint: "<FIELD>",
2329
+ kind: "value",
2330
+ name: "clear",
2331
+ repeat: "append",
2332
+ summary: "Field to remove; repeat for each one",
2333
+ values: Object.keys(CLEARABLE)
2334
+ },
2335
+ json,
2336
+ ...keyPolicyOptions,
2337
+ {
2338
+ hint: "<NAME>",
2339
+ kind: "value",
2340
+ name: "name",
2341
+ summary: "New name for the key"
2342
+ }
2343
+ ],
2344
+ result: KEY_RESULT,
2345
+ summary: "Change a key's name, expiry, or limits"
2346
+ };
2347
+ const keys = {
2348
+ children: [
2349
+ {
2350
+ arguments: [],
2351
+ examples: [{
2352
+ argv: ["keys", "list"],
2353
+ summary: "List your keys"
2354
+ }],
2355
+ kind: "leaf",
2356
+ name: "list",
2357
+ notes: ["Lists every key, revoked ones included, with the first 12 characters of each secret. Needs a management key."],
2358
+ options: [baseUrl, json],
2359
+ result: [
2360
+ {
2361
+ name: "keys",
2362
+ type: "array"
2363
+ },
2364
+ {
2365
+ name: "keys[].id",
2366
+ type: "string"
2367
+ },
2368
+ {
2369
+ name: "keys[].kind",
2370
+ type: "\"api\" | \"management\""
2371
+ },
2372
+ {
2373
+ name: "keys[].name",
2374
+ type: "string"
2375
+ },
2376
+ {
2377
+ name: "keys[].start",
2378
+ type: "string"
2379
+ }
2380
+ ],
2381
+ shortcuts: ["ls"],
2382
+ summary: "List your keys"
2383
+ },
2384
+ keysCreate,
2385
+ {
2386
+ arguments: [keyArgument("show a key")],
2387
+ examples: [{
2388
+ argv: [
2389
+ "keys",
2390
+ "inspect",
2391
+ "<KEY>"
2392
+ ],
2393
+ summary: "Show a key and its spend"
2394
+ }],
2395
+ kind: "leaf",
2396
+ name: "inspect",
2397
+ notes: [NEEDS_MANAGEMENT],
2398
+ options: [baseUrl, json],
2399
+ result: KEY_RESULT,
2400
+ summary: "Show one key"
2401
+ },
2402
+ keysUpdate,
2403
+ {
2404
+ arguments: [keyArgument("revoke a key")],
2405
+ examples: [{
2406
+ argv: [
2407
+ "keys",
2408
+ "revoke",
2409
+ "<KEY>"
2410
+ ],
2411
+ summary: "Revoke a key after a prompt"
2412
+ }, {
2413
+ argv: [
2414
+ "keys",
2415
+ "revoke",
2416
+ "<KEY>",
2417
+ "--yes"
2418
+ ],
2419
+ summary: "Revoke it in a script, after a person approved"
2420
+ }],
2421
+ kind: "leaf",
2422
+ name: "revoke",
2423
+ notes: ["A revoked key stops working at once and cannot be restored. Its sandboxes keep running until their TTL.", "It asks first, and needs --yes without a terminal. Needs a management key."],
2424
+ options: [
2425
+ baseUrl,
2426
+ json,
2427
+ yes
2428
+ ],
2429
+ result: KEY_RESULT,
2430
+ shortcuts: ["delete", "rm"],
2431
+ summary: "Revoke a key"
2432
+ }
2433
+ ],
2434
+ defaultChild: "list",
2435
+ kind: "group",
2436
+ name: "keys",
2437
+ shortcuts: ["key"],
2438
+ summary: "Manage API keys and management keys"
2439
+ };
2440
+ const credentialField = {
2441
+ hint: "<NAME=VALUE>",
2442
+ kind: "value",
2443
+ name: "field",
2444
+ repeat: "append",
2445
+ summary: "Credential field to set; repeat for each one"
2446
+ };
2447
+ const credentialSource = {
2448
+ hint: "<FILE|->",
2449
+ kind: "value",
2450
+ name: "from",
2451
+ stdin: true,
2452
+ summary: "JSON object of the fields, from a file or - for stdin"
2453
+ };
2454
+ const storedCredential = [
2455
+ {
2456
+ name: "credential.id",
2457
+ type: "string"
2458
+ },
2459
+ {
2460
+ name: "credential.provider",
2461
+ type: "string"
2462
+ },
2463
+ {
2464
+ name: "credential.hint",
2465
+ type: "string"
2466
+ },
2467
+ {
2468
+ name: "credential.paused",
2469
+ type: "boolean"
2470
+ }
2471
+ ];
2472
+ const credentials = {
2473
+ children: [
2474
+ {
2475
+ arguments: [],
2476
+ examples: [{
2477
+ argv: ["credentials", "list"],
2478
+ summary: "List your provider credentials"
2479
+ }],
2480
+ kind: "leaf",
2481
+ name: "list",
2482
+ notes: ["Shows a hint of each credential, never the credential. Needs a management key.", "A provider's credentials are listed in the order a create tries them. A Free organization routes only its oldest credential, and Paused marks each other one."],
2483
+ options: [baseUrl, json],
2484
+ result: [
2485
+ {
2486
+ name: "credentials",
2487
+ type: "array"
2488
+ },
2489
+ {
2490
+ name: "credentials[].id",
2491
+ type: "string"
2492
+ },
2493
+ {
2494
+ name: "credentials[].provider",
2495
+ type: "string"
2496
+ },
2497
+ {
2498
+ name: "credentials[].hint",
2499
+ type: "string"
2500
+ },
2501
+ {
2502
+ name: "credentials[].paused",
2503
+ type: "boolean"
2504
+ }
2505
+ ],
2506
+ shortcuts: ["ls"],
2507
+ summary: "List your provider credentials"
2508
+ },
2509
+ {
2510
+ arguments: [providerArgument("set a credential")],
2511
+ examples: [{
2512
+ argv: [
2513
+ "credentials",
2514
+ "set",
2515
+ "e2b",
2516
+ "--from",
2517
+ "-"
2518
+ ],
2519
+ summary: "Set the E2B credential from a JSON object on stdin"
2520
+ }, {
2521
+ argv: [
2522
+ "credentials",
2523
+ "set",
2524
+ "e2b",
2525
+ "--field",
2526
+ "api_key=<KEY>"
2527
+ ],
2528
+ summary: "Set it from an option"
2529
+ }],
2530
+ kind: "leaf",
2531
+ name: "set",
2532
+ notes: [
2533
+ "Each provider names its fields in sandcovery providers inspect. Sandboxes on that provider then run on your account.",
2534
+ "It replaces the credential when you hold exactly one for the provider, and fails when you hold more; then add the new one and delete the old one.",
2535
+ "Prefer --from -, since options show in process lists. Sandcovery seals the values and never returns them. Needs a management key."
2536
+ ],
2537
+ options: [
2538
+ baseUrl,
2539
+ credentialField,
2540
+ credentialSource,
2541
+ json
2542
+ ],
2543
+ result: storedCredential,
2544
+ summary: "Set or replace a provider credential"
2545
+ },
2546
+ {
2547
+ arguments: [providerArgument("add a credential")],
2548
+ examples: [{
2549
+ argv: [
2550
+ "credentials",
2551
+ "add",
2552
+ "e2b",
2553
+ "--from",
2554
+ "-"
2555
+ ],
2556
+ summary: "Add another E2B credential from a JSON object on stdin"
2557
+ }, {
2558
+ argv: [
2559
+ "credentials",
2560
+ "add",
2561
+ "e2b",
2562
+ "--field",
2563
+ "api_key=<KEY>"
2564
+ ],
2565
+ summary: "Add it from an option"
2566
+ }],
2567
+ kind: "leaf",
2568
+ name: "add",
2569
+ notes: ["A create tries your credentials for a provider in the order you added them, and falls back to the next one on capacity, quota, a provider error, or a timeout.", "A Free organization routes only its oldest credential, so another stays paused until it has Pro. Prefer --from -, since options show in process lists. Needs a management key."],
2570
+ options: [
2571
+ baseUrl,
2572
+ credentialField,
2573
+ credentialSource,
2574
+ json
2575
+ ],
2576
+ result: storedCredential,
2577
+ summary: "Add another provider credential"
2578
+ },
2579
+ {
2580
+ arguments: [providerArgument("delete a credential")],
2581
+ examples: [{
2582
+ argv: [
2583
+ "credentials",
2584
+ "delete",
2585
+ "e2b"
2586
+ ],
2587
+ summary: "Delete every E2B credential after a prompt"
2588
+ }, {
2589
+ argv: [
2590
+ "credentials",
2591
+ "delete",
2592
+ "e2b",
2593
+ "--id",
2594
+ "<CREDENTIAL>"
2595
+ ],
2596
+ summary: "Delete one E2B credential by its ID"
2597
+ }],
2598
+ kind: "leaf",
2599
+ name: "delete",
2600
+ notes: ["Without --id, it deletes every credential of the provider, and new sandboxes on that provider then run on Sandcovery's account. A credential that live sandboxes use cannot be deleted.", "It asks first, and needs --yes without a terminal. Needs a management key."],
2601
+ options: [
2602
+ baseUrl,
2603
+ {
2604
+ hint: "<CREDENTIAL>",
2605
+ kind: "value",
2606
+ name: "id",
2607
+ summary: "Delete only the credential with this ID"
2608
+ },
2609
+ json,
2610
+ yes
2611
+ ],
2612
+ result: [{
2613
+ name: "credential.provider",
2614
+ type: "string"
2615
+ }, {
2616
+ name: "outcome",
2617
+ type: "\"deleted\""
2618
+ }],
2619
+ shortcuts: ["rm"],
2620
+ summary: "Delete provider credentials"
2621
+ },
2622
+ {
2623
+ arguments: [],
2624
+ examples: [{
2625
+ argv: ["credentials", "offer"],
2626
+ summary: "Show the free vCPU-hours your keys have earned"
2627
+ }],
2628
+ kind: "leaf",
2629
+ name: "offer",
2630
+ notes: ["Shows the provider Sandcovery pays for, the keys counted toward the free vCPU-hours, and the vCPU-hours left. It fails as not found while no offer runs. Needs a management key."],
2631
+ options: [baseUrl, json],
2632
+ result: [
2633
+ {
2634
+ name: "offer.provider",
2635
+ type: "string"
2636
+ },
2637
+ {
2638
+ name: "offer.keys_counted",
2639
+ type: "number"
2640
+ },
2641
+ {
2642
+ name: "offer.remaining_vcpu_seconds",
2643
+ type: "number"
2644
+ },
2645
+ {
2646
+ name: "offer.x_post_counted",
2647
+ type: "boolean"
2648
+ }
2649
+ ],
2650
+ summary: "Show the free vCPU-hours offer"
2651
+ },
2652
+ {
2653
+ arguments: [required({
2654
+ message: "Can't count an X post without its URL.",
2655
+ name: "url",
2656
+ reason: "missing_url",
2657
+ summary: "The post's URL on x.com or twitter.com, such as https://x.com/<handle>/status/<id>"
2658
+ })],
2659
+ examples: [{
2660
+ argv: [
2661
+ "credentials",
2662
+ "count-x-post",
2663
+ "https://x.com/you/status/1234567890123456789"
2664
+ ],
2665
+ summary: `Count your post on X that tags @${SANDCOVERY_X_HANDLE} as one key`
2666
+ }],
2667
+ kind: "leaf",
2668
+ name: "count-x-post",
2669
+ notes: [`A post on X that tags @${SANDCOVERY_X_HANDLE} counts as one key toward the free vCPU-hours when the X account linked to your organization's owner wrote it. A repost counts nothing.`, "One post counts per account, and one X account counts for one Sandcovery account only. Needs a management key."],
2670
+ options: [baseUrl, json],
2671
+ result: [
2672
+ {
2673
+ name: "offer.keys_counted",
2674
+ type: "number"
2675
+ },
2676
+ {
2677
+ name: "offer.remaining_vcpu_seconds",
2678
+ type: "number"
2679
+ },
2680
+ {
2681
+ name: "offer.x_post_counted",
2682
+ type: "boolean"
2683
+ }
2684
+ ],
2685
+ summary: "Count an X post toward the free vCPU-hours"
2686
+ }
2687
+ ],
2688
+ defaultChild: "list",
2689
+ kind: "group",
2690
+ name: "credentials",
2691
+ shortcuts: ["credential"],
2692
+ summary: "Run sandboxes on your own provider accounts"
2693
+ };
2694
+ const providers = {
2695
+ children: [{
2696
+ arguments: [],
2697
+ examples: [{
2698
+ argv: ["providers", "list"],
2699
+ summary: "Compare the providers' prices and status"
2700
+ }, {
2701
+ argv: [
2702
+ "providers",
2703
+ "list",
2704
+ "--routed"
2705
+ ],
2706
+ summary: "List only the providers Sandcovery routes sandboxes to"
2707
+ }],
2708
+ kind: "leaf",
2709
+ name: "list",
2710
+ notes: [
2711
+ "Lists each provider with its status, 2x4 price per hour, and median create latency.",
2712
+ "A provider Sandcovery does not route to yet shows as Coming Soon.",
2713
+ "Coming Soon also marks each figure or fact Sandcovery does not publish, and --json adds every fact with the page it was read from.",
2714
+ "With --routed, it lists only the providers on the provider board, and --json prints their board entries."
2715
+ ],
2716
+ options: [
2717
+ baseUrl,
2718
+ json,
2719
+ flag({
2720
+ name: "routed",
2721
+ summary: "List only the providers Sandcovery routes to"
2722
+ })
2723
+ ],
2724
+ result: [
2725
+ {
2726
+ name: "providers",
2727
+ type: "array"
2728
+ },
2729
+ {
2730
+ name: "providers[].provider",
2731
+ type: "string"
2732
+ },
2733
+ {
2734
+ name: "providers[].routed",
2735
+ type: "boolean"
2736
+ },
2737
+ {
2738
+ name: "providers[].status",
2739
+ type: "string"
2740
+ }
2741
+ ],
2742
+ shortcuts: ["ls"],
2743
+ summary: "List the providers"
2744
+ }, {
2745
+ arguments: [providerArgument("show a provider")],
2746
+ examples: [{
2747
+ argv: [
2748
+ "providers",
2749
+ "inspect",
2750
+ "e2b"
2751
+ ],
2752
+ summary: "Show E2B's prices, limits, and credential fields"
2753
+ }],
2754
+ kind: "leaf",
2755
+ name: "inspect",
2756
+ notes: ["Shows the prices of each size, the features and limits, and the fields sandcovery credentials set takes."],
2757
+ options: [baseUrl, json],
2758
+ result: [
2759
+ {
2760
+ name: "provider.provider",
2761
+ type: "string"
2762
+ },
2763
+ {
2764
+ name: "provider.features",
2765
+ type: "object"
2766
+ },
2767
+ {
2768
+ name: "provider.credential_fields",
2769
+ type: "array"
2770
+ }
2771
+ ],
2772
+ summary: "Show one provider"
2773
+ }],
2774
+ defaultChild: "list",
2775
+ kind: "group",
2776
+ name: "providers",
2777
+ shortcuts: ["provider"],
2778
+ summary: "Compare the sandbox providers"
2779
+ };
2780
+ const usage = {
2781
+ children: [
2782
+ {
2783
+ arguments: [],
2784
+ examples: [{
2785
+ argv: ["usage", "inspect"],
2786
+ summary: "Show this month's usage"
2787
+ }, {
2788
+ argv: [
2789
+ "usage",
2790
+ "inspect",
2791
+ "--from",
2792
+ "2026-10-01",
2793
+ "--to",
2794
+ "2026-10-31",
2795
+ "--json"
2796
+ ],
2797
+ summary: "Read October's usage in a script"
2798
+ }],
2799
+ kind: "leaf",
2800
+ name: "inspect",
2801
+ notes: ["Shows sandboxes, sandbox time, vCPU and memory time, and estimated cost per UTC day, key, and provider, at most 92 days at once, plus GPU time once any sandbox ran a GPU. Needs a management key."],
2802
+ options: [
2803
+ baseUrl,
2804
+ {
2805
+ defaultText: "the first day of this UTC month",
2806
+ hint: "<DAY>",
2807
+ kind: "value",
2808
+ name: "from",
2809
+ summary: "First UTC day, such as 2026-11-01"
2810
+ },
2811
+ json,
2812
+ usageKey,
2813
+ {
2814
+ defaultText: "today, in UTC",
2815
+ hint: "<DAY>",
2816
+ kind: "value",
2817
+ name: "to",
2818
+ summary: "Last UTC day, such as 2026-11-30"
2819
+ }
2820
+ ],
2821
+ result: [
2822
+ {
2823
+ name: "usage",
2824
+ type: "array"
2825
+ },
2826
+ {
2827
+ name: "usage[].date",
2828
+ type: "string"
2829
+ },
2830
+ {
2831
+ name: "usage[].estimated_micro_usd",
2832
+ type: "number"
2833
+ }
2834
+ ],
2835
+ summary: "Show usage and cost per day"
2836
+ },
2837
+ {
2838
+ arguments: [],
2839
+ examples: [{
2840
+ argv: ["usage", "live"],
2841
+ summary: "Show the sandboxes live now and their cost per hour"
2842
+ }],
2843
+ kind: "leaf",
2844
+ name: "live",
2845
+ notes: ["Shows the sandboxes live at this moment per key, provider, and status, with their vCPUs, memory, GPUs, cost per hour, and cost so far. Needs a management key."],
2846
+ options: [
2847
+ baseUrl,
2848
+ json,
2849
+ usageKey
2850
+ ],
2851
+ result: [
2852
+ {
2853
+ name: "at",
2854
+ type: "string"
2855
+ },
2856
+ {
2857
+ name: "live",
2858
+ type: "array"
2859
+ },
2860
+ {
2861
+ name: "live[].hourly_micro_usd",
2862
+ type: "number"
2863
+ },
2864
+ {
2865
+ name: "live[].sandbox_count",
2866
+ type: "number"
2867
+ }
2868
+ ],
2869
+ summary: "Show the sandboxes live now"
2870
+ },
2871
+ {
2872
+ arguments: [],
2873
+ examples: [{
2874
+ argv: ["usage", "totals"],
2875
+ summary: "Show today's, this week's, this month's, and all usage"
2876
+ }],
2877
+ kind: "leaf",
2878
+ name: "totals",
2879
+ notes: ["Shows sandboxes, sandbox time, vCPU and memory time, and estimated cost from the start of the UTC day, ISO week, and UTC month to now, and in total, plus GPU time once any sandbox ran a GPU. Needs a management key."],
2880
+ options: [
2881
+ baseUrl,
2882
+ json,
2883
+ usageKey
2884
+ ],
2885
+ result: [
2886
+ {
2887
+ name: "at",
2888
+ type: "string"
2889
+ },
2890
+ {
2891
+ name: "totals",
2892
+ type: "array"
2893
+ },
2894
+ {
2895
+ name: "totals[].period",
2896
+ type: "string"
2897
+ },
2898
+ {
2899
+ name: "totals[].estimated_micro_usd",
2900
+ type: "number"
2901
+ }
2902
+ ],
2903
+ summary: "Show usage totals by day, week, month, and in total"
2904
+ },
2905
+ {
2906
+ children: [
2907
+ {
2908
+ arguments: [],
2909
+ examples: [{
2910
+ argv: [
2911
+ "usage",
2912
+ "shares",
2913
+ "list"
2914
+ ],
2915
+ summary: "List the live usage shares"
2916
+ }],
2917
+ kind: "leaf",
2918
+ name: "list",
2919
+ notes: [NEEDS_MANAGEMENT],
2920
+ options: [baseUrl, json],
2921
+ result: [
2922
+ {
2923
+ name: "shares",
2924
+ type: "array"
2925
+ },
2926
+ {
2927
+ name: "shares[].id",
2928
+ type: "string"
2929
+ },
2930
+ {
2931
+ name: "shares[].url",
2932
+ type: "string"
2933
+ }
2934
+ ],
2935
+ shortcuts: ["ls"],
2936
+ summary: "List usage shares"
2937
+ },
2938
+ {
2939
+ arguments: [],
2940
+ examples: [{
2941
+ argv: [
2942
+ "usage",
2943
+ "shares",
2944
+ "create"
2945
+ ],
2946
+ summary: "Share this month's usage without its cost"
2947
+ }, {
2948
+ argv: [
2949
+ "usage",
2950
+ "shares",
2951
+ "create",
2952
+ "--period",
2953
+ "total",
2954
+ "--figure",
2955
+ "sandbox_count",
2956
+ "--figure",
2957
+ "vcpu_seconds"
2958
+ ],
2959
+ summary: "Share only the sandboxes and vCPU-hours of all time"
2960
+ }],
2961
+ kind: "leaf",
2962
+ name: "create",
2963
+ notes: [
2964
+ "Reads the usage total of the window now and shares the chosen figures at a new public URL. Anyone with the URL sees them and your Sandcovery username, and nothing else of the organization, until you revoke the share.",
2965
+ "With no --figure, it shares every figure but the estimated cost.",
2966
+ "Needs the saved login of an owner or admin who picked a username in the share dialog on the usage page, since a key names no person."
2967
+ ],
2968
+ options: [
2969
+ baseUrl,
2970
+ {
2971
+ hint: "<FIGURE>",
2972
+ kind: "value",
2973
+ name: "figure",
2974
+ repeat: "append",
2975
+ summary: "Figure to share, such as sandbox_count or vcpu_seconds; repeat for each one"
2976
+ },
2977
+ json,
2978
+ {
2979
+ defaultText: "month",
2980
+ hint: "<PERIOD>",
2981
+ kind: "value",
2982
+ name: "period",
2983
+ summary: "Window to share: day, week, month, or total"
2984
+ }
2985
+ ],
2986
+ result: [
2987
+ {
2988
+ name: "share.id",
2989
+ type: "string"
2990
+ },
2991
+ {
2992
+ name: "share.url",
2993
+ type: "string"
2994
+ },
2995
+ {
2996
+ name: "share.image_url",
2997
+ type: "string"
2998
+ }
2999
+ ],
3000
+ summary: "Share usage at a public URL"
3001
+ },
3002
+ {
3003
+ arguments: [required({
3004
+ message: "Can't revoke a usage share without its ID.",
3005
+ name: "share",
3006
+ reason: "missing_value",
3007
+ summary: "Share ID, such as ush_ and a UUID, as sandcovery usage shares list prints it"
3008
+ })],
3009
+ examples: [{
3010
+ argv: [
3011
+ "usage",
3012
+ "shares",
3013
+ "revoke",
3014
+ "<SHARE>"
3015
+ ],
3016
+ summary: "Revoke a share after a prompt"
3017
+ }, {
3018
+ argv: [
3019
+ "usage",
3020
+ "shares",
3021
+ "revoke",
3022
+ "<SHARE>",
3023
+ "--yes"
3024
+ ],
3025
+ summary: "Revoke it in a script, after a person approved"
3026
+ }],
3027
+ kind: "leaf",
3028
+ name: "revoke",
3029
+ notes: ["Its URL answers 404 at once for everyone who has it.", `It asks first, and needs --yes without a terminal. ${NEEDS_MANAGEMENT}`],
3030
+ options: [
3031
+ baseUrl,
3032
+ json,
3033
+ yes
3034
+ ],
3035
+ result: [{
3036
+ name: "share.id",
3037
+ type: "string"
3038
+ }, {
3039
+ name: "outcome",
3040
+ type: "\"revoked\""
3041
+ }],
3042
+ shortcuts: ["delete", "rm"],
3043
+ summary: "Revoke a usage share"
3044
+ },
3045
+ {
3046
+ arguments: [required({
3047
+ message: "Can't show shared usage without its token.",
3048
+ name: "token",
3049
+ reason: "missing_value",
3050
+ summary: "Token, the 43 characters after /share/ in a share URL"
3051
+ })],
3052
+ examples: [{
3053
+ argv: [
3054
+ "usage",
3055
+ "shares",
3056
+ "inspect",
3057
+ "<TOKEN>"
3058
+ ],
3059
+ summary: "Show what a share URL shows"
3060
+ }],
3061
+ kind: "leaf",
3062
+ name: "inspect",
3063
+ notes: ["Shows the figures a share URL shows to anyone. Needs no key."],
3064
+ options: [baseUrl, json],
3065
+ result: [{
3066
+ name: "usage.period",
3067
+ type: "string"
3068
+ }, {
3069
+ name: "usage.figures",
3070
+ type: "array"
3071
+ }],
3072
+ summary: "Show the usage a share URL shows"
3073
+ }
3074
+ ],
3075
+ defaultChild: "list",
3076
+ kind: "group",
3077
+ name: "shares",
3078
+ shortcuts: ["share"],
3079
+ summary: "Share usage at public URLs"
3080
+ },
3081
+ {
3082
+ arguments: [],
3083
+ examples: [{
3084
+ argv: [
3085
+ "usage",
3086
+ "estimate",
3087
+ "--slug",
3088
+ "sandcovery/4x8",
3089
+ "--ttl",
3090
+ "3600"
3091
+ ],
3092
+ summary: "Price a 4x8 sandbox for an hour"
3093
+ }],
3094
+ kind: "leaf",
3095
+ name: "estimate",
3096
+ notes: ["Prices the spec on each provider that can run it, in routing order, at the size each slug runs there, without creating anything.", NO_MARKUP_TERMS],
3097
+ options: [
3098
+ baseUrl,
3099
+ json,
3100
+ ...sandboxSpecOptions
3101
+ ],
3102
+ result: [
3103
+ {
3104
+ name: "estimates",
3105
+ type: "array"
3106
+ },
3107
+ {
3108
+ name: "estimates[].provider",
3109
+ type: "string"
3110
+ },
3111
+ {
3112
+ name: "estimates[].slug",
3113
+ type: "string"
3114
+ },
3115
+ {
3116
+ name: "estimates[].ttl_micro_usd",
3117
+ type: "number"
3118
+ }
3119
+ ],
3120
+ summary: "Price a sandbox before creating it"
3121
+ }
3122
+ ],
3123
+ defaultChild: "inspect",
3124
+ kind: "group",
3125
+ name: "usage",
3126
+ summary: "Show usage and price sandboxes"
3127
+ };
3128
+ const stats = {
3129
+ children: [{
3130
+ arguments: [],
3131
+ examples: [{
3132
+ argv: ["stats", "inspect"],
3133
+ summary: "Show your organization's level, streak, and badges"
3134
+ }, {
3135
+ argv: [
3136
+ "stats",
3137
+ "inspect",
3138
+ "--json"
3139
+ ],
3140
+ summary: "Read the badges in a script"
3141
+ }],
3142
+ kind: "leaf",
3143
+ name: "inspect",
3144
+ notes: ["Reads every sandbox the organization started. Level 1 starts at 1 vCPU-hour, and each level after it takes ten times as many. Takes an API key or a management key."],
3145
+ options: [baseUrl, json],
3146
+ result: [
3147
+ {
3148
+ name: "stats",
3149
+ type: "object"
3150
+ },
3151
+ {
3152
+ name: "stats.level",
3153
+ type: "number"
3154
+ },
3155
+ {
3156
+ name: "stats.badges",
3157
+ type: "array"
3158
+ }
3159
+ ],
3160
+ summary: "Show level, streak, records, and badges"
3161
+ }],
3162
+ defaultChild: "inspect",
3163
+ kind: "group",
3164
+ name: "stats",
3165
+ summary: "Show your organization's level, streak, and badges"
3166
+ };
3167
+ const activity = {
3168
+ children: [{
3169
+ arguments: [],
3170
+ examples: [{
3171
+ argv: ["activity", "list"],
3172
+ summary: "List the newest sandbox events"
3173
+ }],
3174
+ kind: "leaf",
3175
+ name: "list",
3176
+ notes: ["Lists creates, create attempts, pauses, snapshots, and ends, newest first, one page per run."],
3177
+ options: [
3178
+ baseUrl,
3179
+ json,
3180
+ limit("events"),
3181
+ next
3182
+ ],
3183
+ result: [
3184
+ {
3185
+ name: "activity",
3186
+ type: "array"
3187
+ },
3188
+ {
3189
+ name: "activity[].action",
3190
+ type: "string"
3191
+ },
3192
+ {
3193
+ name: "next_cursor",
3194
+ type: NULLABLE_TEXT
3195
+ }
3196
+ ],
3197
+ shortcuts: ["ls"],
3198
+ summary: "List sandbox events, newest first"
3199
+ }],
3200
+ defaultChild: "list",
3201
+ kind: "group",
3202
+ name: "activity",
3203
+ summary: "Read what happened to your sandboxes"
3204
+ };
3205
+ const billing = {
3206
+ children: [{
3207
+ arguments: [],
3208
+ examples: [{
3209
+ argv: ["billing", "inspect"],
3210
+ summary: "Show the plan and the credit balance"
3211
+ }],
3212
+ kind: "leaf",
3213
+ name: "inspect",
3214
+ notes: [`Shows the plan, the credit balance, and the Pro and Enterprise prices. It fails as not found while billing is not set up. ${NEEDS_MANAGEMENT}`],
3215
+ options: [baseUrl, json],
3216
+ result: [
3217
+ {
3218
+ name: "billing.plan",
3219
+ type: "\"free\" | \"pro\" | \"enterprise\""
3220
+ },
3221
+ {
3222
+ name: "billing.credit_balance_micro_usd",
3223
+ type: "number"
3224
+ },
3225
+ {
3226
+ name: "billing.credits_on_sale",
3227
+ type: "boolean"
3228
+ },
3229
+ {
3230
+ name: "billing.pro_price",
3231
+ type: NULLABLE_OBJECT
3232
+ },
3233
+ {
3234
+ name: "billing.enterprise_price",
3235
+ type: NULLABLE_OBJECT
3236
+ },
3237
+ {
3238
+ name: "billing.github_enterprise",
3239
+ type: "boolean"
3240
+ }
3241
+ ],
3242
+ summary: "Show the plan and credits"
3243
+ }, {
3244
+ arguments: [],
3245
+ examples: [{
3246
+ argv: [
3247
+ "billing",
3248
+ "buy-credits",
3249
+ "--amount",
3250
+ "100"
3251
+ ],
3252
+ summary: "Start a 100 USD credit purchase"
3253
+ }],
3254
+ kind: "leaf",
3255
+ name: "buy-credits",
3256
+ notes: [`Prints the Stripe Checkout page that takes the payment. The credits are the amount less the processing fee of ${CARD_FEE_TERMS}, and arrive once Stripe confirms the payment. ${NEEDS_MANAGEMENT}`],
3257
+ options: [
3258
+ {
3259
+ hint: "<USD>",
3260
+ kind: "value",
3261
+ name: "amount",
3262
+ required: true,
3263
+ summary: `Whole US dollars to pay, from ${String(CREDIT_PURCHASE_MIN_MICRO_USD / MICRO_USD_PER_DOLLAR)} to ${String(CREDIT_PURCHASE_MAX_MICRO_USD / MICRO_USD_PER_DOLLAR)}`
3264
+ },
3265
+ baseUrl,
3266
+ json
3267
+ ],
3268
+ result: [{
3269
+ name: "checkout.url",
3270
+ type: "string"
3271
+ }],
3272
+ summary: "Buy credits through Stripe Checkout"
3273
+ }],
3274
+ defaultChild: "inspect",
3275
+ kind: "group",
3276
+ name: "billing",
3277
+ summary: "Show the plan and buy credits"
3278
+ };
3279
+ const pricing = {
3280
+ children: [{
3281
+ arguments: [],
3282
+ examples: [{
3283
+ argv: ["pricing", "inspect"],
3284
+ summary: "Show the plan prices and the credit terms"
3285
+ }],
3286
+ kind: "leaf",
3287
+ name: "inspect",
3288
+ notes: ["Shows the Pro and Enterprise prices, the smallest and largest credit purchase, and the processing fee that comes out of each purchase. It needs no key, and each price reads Not on sale while its plan is not on sale.", NO_MARKUP_TERMS],
3289
+ options: [baseUrl, json],
3290
+ result: [
3291
+ {
3292
+ name: "pricing.pro_price",
3293
+ type: NULLABLE_OBJECT
3294
+ },
3295
+ {
3296
+ name: "pricing.enterprise_price",
3297
+ type: NULLABLE_OBJECT
3298
+ },
3299
+ {
3300
+ name: "pricing.credits",
3301
+ type: "object"
3302
+ }
3303
+ ],
3304
+ summary: "Show the plan prices and credit terms"
3305
+ }, {
3306
+ arguments: [],
3307
+ examples: [{
3308
+ argv: [
3309
+ "pricing",
3310
+ "monthly",
3311
+ "--size",
3312
+ "4x8",
3313
+ "--hours-per-day",
3314
+ "24"
3315
+ ],
3316
+ summary: "Price a 4x8 sandbox that runs all month on each provider"
3317
+ }],
3318
+ kind: "leaf",
3319
+ name: "monthly",
3320
+ notes: [`Prices one size on each provider Sandcovery routes to, cheapest first, for a sandbox that runs --hours-per-day hours on every day of ${MONTH_TEXT}, and prints the slug that routes a create to the cheapest. It needs no key and creates nothing.`, NO_MARKUP_TERMS],
3321
+ options: [
3322
+ baseUrl,
3323
+ {
3324
+ defaultText: String(8),
3325
+ hint: "<HOURS>",
3326
+ kind: "value",
3327
+ name: "hours-per-day",
3328
+ summary: `Hours a day the sandbox runs, above 0 and at most ${String(24)}, such as 8 or 0.5`
3329
+ },
3330
+ json,
3331
+ {
3332
+ defaultText: "2x4",
3333
+ hint: "<SIZE>",
3334
+ kind: "value",
3335
+ name: "size",
3336
+ summary: "Size as <vcpu>x<memory_gib>, such as 2x4 or 2x0.5"
3337
+ }
3338
+ ],
3339
+ result: [
3340
+ {
3341
+ name: "estimates",
3342
+ type: "array"
3343
+ },
3344
+ {
3345
+ name: "estimates[].provider",
3346
+ type: "string"
3347
+ },
3348
+ {
3349
+ name: "estimates[].slug",
3350
+ type: "string"
3351
+ },
3352
+ {
3353
+ name: "estimates[].monthly_micro_usd",
3354
+ type: "number"
3355
+ },
3356
+ {
3357
+ name: "slug",
3358
+ type: "string"
3359
+ }
3360
+ ],
3361
+ summary: "Price a size for a month on each provider"
3362
+ }],
3363
+ defaultChild: "inspect",
3364
+ kind: "group",
3365
+ name: "pricing",
3366
+ summary: "Show the plan prices, the credit terms, and monthly costs"
3367
+ };
3368
+ const problems = {
3369
+ children: [{
3370
+ arguments: [{
3371
+ missing: {
3372
+ message: "Can't report a problem without a message.",
3373
+ reason: "missing_value"
3374
+ },
3375
+ name: "message",
3376
+ summary: `What went wrong, up to ${formatCount({ count: PROBLEM_REPORT_MAX })} characters; its words join with spaces`,
3377
+ variadic: true
3378
+ }],
3379
+ examples: [{
3380
+ argv: [
3381
+ "problems",
3382
+ "report",
3383
+ "The pricing table is cut off on my phone.",
3384
+ "--page",
3385
+ "/pricing"
3386
+ ],
3387
+ summary: "Report a problem with a page"
3388
+ }],
3389
+ kind: "leaf",
3390
+ name: "report",
3391
+ notes: [`Sends the report to the Sandcovery team, who track it as an issue. It needs no key, and Sandcovery takes ${String(3)} reports a minute from one network address.`],
3392
+ options: [
3393
+ baseUrl,
3394
+ json,
3395
+ {
3396
+ hint: "<PATH>",
3397
+ kind: "value",
3398
+ name: "page",
3399
+ summary: "Path of the Sandcovery page the problem is on"
3400
+ }
3401
+ ],
3402
+ result: [{
3403
+ name: "outcome",
3404
+ type: "\"sent\""
3405
+ }],
3406
+ summary: "Tell the Sandcovery team about a problem"
3407
+ }],
3408
+ kind: "group",
3409
+ name: "problems",
3410
+ shortcuts: ["problem"],
3411
+ summary: "Tell the Sandcovery team about a problem"
3412
+ };
3413
+ const ci = {
3414
+ children: [{
3415
+ children: [{
3416
+ arguments: [],
3417
+ examples: [{
3418
+ argv: [
3419
+ "ci",
3420
+ "jobs",
3421
+ "list"
3422
+ ],
3423
+ summary: "List the newest CI jobs"
3424
+ }],
3425
+ kind: "leaf",
3426
+ name: "list",
3427
+ notes: ["Lists each GitHub Actions job that asked for a Sandcovery runner label, newest first, one page per run."],
3428
+ options: [
3429
+ baseUrl,
3430
+ json,
3431
+ limit("jobs"),
3432
+ next
3433
+ ],
3434
+ result: [
3435
+ {
3436
+ name: "jobs",
3437
+ type: "array"
3438
+ },
3439
+ {
3440
+ name: "jobs[].id",
3441
+ type: "string"
3442
+ },
3443
+ {
3444
+ name: "jobs[].status",
3445
+ type: "\"queued\" | \"in_progress\" | \"completed\""
3446
+ },
3447
+ {
3448
+ name: "jobs[].cost_micro_usd",
3449
+ type: NULLABLE_NUMBER
3450
+ },
3451
+ {
3452
+ name: "next_cursor",
3453
+ type: NULLABLE_TEXT
3454
+ }
3455
+ ],
3456
+ shortcuts: ["ls"],
3457
+ summary: "List CI jobs, newest first"
3458
+ }, {
3459
+ arguments: [required({
3460
+ message: "Can't show a CI job without its ID.",
3461
+ name: "job",
3462
+ reason: "missing_job",
3463
+ summary: "CI job ID, such as cij_ and a UUID, as sandcovery ci jobs list prints it"
3464
+ })],
3465
+ examples: [{
3466
+ argv: [
3467
+ "ci",
3468
+ "jobs",
3469
+ "inspect",
3470
+ "<JOB>"
3471
+ ],
3472
+ summary: "Show a job's provider, wait, and cost"
3473
+ }],
3474
+ kind: "leaf",
3475
+ name: "inspect",
3476
+ notes: ["Shows the provider, wait, duration, and list-price cost of a job, beside what it costs on a GitHub-hosted runner."],
3477
+ options: [baseUrl, json],
3478
+ result: [
3479
+ {
3480
+ name: "job.id",
3481
+ type: "string"
3482
+ },
3483
+ {
3484
+ name: "job.provider",
3485
+ type: NULLABLE_TEXT
3486
+ },
3487
+ {
3488
+ name: "job.github_hosted_cost_micro_usd",
3489
+ type: NULLABLE_NUMBER
3490
+ }
3491
+ ],
3492
+ summary: "Show one CI job"
3493
+ }],
3494
+ defaultChild: "list",
3495
+ kind: "group",
3496
+ name: "jobs",
3497
+ shortcuts: ["job"],
3498
+ summary: "Read GitHub Actions jobs that ran on Sandcovery CI"
3499
+ }, {
3500
+ children: [{
3501
+ arguments: [],
3502
+ examples: [{
3503
+ argv: [
3504
+ "ci",
3505
+ "installations",
3506
+ "list"
3507
+ ],
3508
+ summary: "List the linked GitHub installations"
3509
+ }],
3510
+ kind: "leaf",
3511
+ name: "list",
3512
+ notes: [`Lists each linked installation with the API key that creates its runners. An organization owner or admin links one from the dashboard. ${NEEDS_MANAGEMENT}`],
3513
+ options: [baseUrl, json],
3514
+ result: [
3515
+ {
3516
+ name: "installations",
3517
+ type: "array"
3518
+ },
3519
+ {
3520
+ name: "installations[].installation_id",
3521
+ type: "number"
3522
+ },
3523
+ {
3524
+ name: "installations[].api_key_id",
3525
+ type: "string"
3526
+ }
3527
+ ],
3528
+ shortcuts: ["ls"],
3529
+ summary: "List linked GitHub installations"
3530
+ }, {
3531
+ arguments: [required({
3532
+ message: "Can't unlink an installation without its ID.",
3533
+ name: "installation",
3534
+ reason: "missing_installation",
3535
+ summary: "GitHub installation ID, as sandcovery ci installations list prints it"
3536
+ })],
3537
+ examples: [{
3538
+ argv: [
3539
+ "ci",
3540
+ "installations",
3541
+ "unlink",
3542
+ "<INSTALLATION>"
3543
+ ],
3544
+ summary: "Unlink an installation after a prompt"
3545
+ }, {
3546
+ argv: [
3547
+ "ci",
3548
+ "installations",
3549
+ "unlink",
3550
+ "<INSTALLATION>",
3551
+ "--yes"
3552
+ ],
3553
+ summary: "Unlink it in a script, after a person approved"
3554
+ }],
3555
+ kind: "leaf",
3556
+ name: "unlink",
3557
+ notes: ["Its jobs start no more runners, and a runner already started ends when its job completes or at its TTL. The GitHub App stays installed until you uninstall it on GitHub.", `It asks first, and needs --yes without a terminal. ${NEEDS_MANAGEMENT}`],
3558
+ options: [
3559
+ baseUrl,
3560
+ json,
3561
+ yes
3562
+ ],
3563
+ result: [{
3564
+ name: "installation.installation_id",
3565
+ type: "number"
3566
+ }, {
3567
+ name: "outcome",
3568
+ type: "\"unlinked\""
3569
+ }],
3570
+ shortcuts: ["delete", "rm"],
3571
+ summary: "Unlink a GitHub installation"
3572
+ }],
3573
+ defaultChild: "list",
3574
+ kind: "group",
3575
+ name: "installations",
3576
+ shortcuts: ["installation"],
3577
+ summary: "Manage GitHub installations linked to Sandcovery CI"
3578
+ }],
3579
+ kind: "group",
3580
+ name: "ci",
3581
+ summary: "Run GitHub Actions jobs on sandboxes"
3582
+ };
3583
+ const xAccount = {
3584
+ children: [
3585
+ {
3586
+ arguments: [],
3587
+ examples: [{
3588
+ argv: ["x-account", "inspect"],
3589
+ summary: "Show the X account linked to you"
3590
+ }],
3591
+ kind: "leaf",
3592
+ name: "inspect",
3593
+ notes: [`Shows the handle, X ID, and link time of the X account linked to you, and whether Sandcovery links X accounts now. ${NEEDS_PERSON}`],
3594
+ options: [baseUrl, json],
3595
+ result: [
3596
+ {
3597
+ name: "x_account.linked",
3598
+ type: NULLABLE_OBJECT
3599
+ },
3600
+ {
3601
+ name: "x_account.linked.username",
3602
+ type: "string"
3603
+ },
3604
+ {
3605
+ name: "x_account.linking_open",
3606
+ type: "boolean"
3607
+ }
3608
+ ],
3609
+ summary: "Show the linked X account"
3610
+ },
3611
+ {
3612
+ arguments: [],
3613
+ examples: [{
3614
+ argv: ["x-account", "link"],
3615
+ summary: "Print the page that links an X account"
3616
+ }],
3617
+ kind: "leaf",
3618
+ name: "link",
3619
+ notes: ["Prints the dashboard page where you link an X account, since X confirms the link in the browser. Linking asks X only to read your X profile and posts. It fails as not found while Sandcovery links no X accounts, and as a conflict while one is linked to you.", NEEDS_PERSON],
3620
+ options: [baseUrl, json],
3621
+ result: [{
3622
+ name: "link.url",
3623
+ type: "string"
3624
+ }],
3625
+ summary: "Link an X account in the browser"
3626
+ },
3627
+ {
3628
+ arguments: [],
3629
+ examples: [{
3630
+ argv: ["x-account", "unlink"],
3631
+ summary: "Unlink the X account after a prompt"
3632
+ }, {
3633
+ argv: [
3634
+ "x-account",
3635
+ "unlink",
3636
+ "--yes"
3637
+ ],
3638
+ summary: "Unlink it in a script, after a person approved"
3639
+ }],
3640
+ kind: "leaf",
3641
+ name: "unlink",
3642
+ notes: ["Deletes the ID, handle, and X token of the X account linked to you. It fails as not found while none is linked.", `It asks first, and needs --yes without a terminal. ${NEEDS_PERSON}`],
3643
+ options: [
3644
+ baseUrl,
3645
+ json,
3646
+ yes
3647
+ ],
3648
+ result: [{
3649
+ name: "outcome",
3650
+ type: "\"unlinked\""
3651
+ }],
3652
+ shortcuts: ["delete", "rm"],
3653
+ summary: "Unlink the X account"
3654
+ }
3655
+ ],
3656
+ defaultChild: "inspect",
3657
+ kind: "group",
3658
+ name: "x-account",
3659
+ shortcuts: ["x"],
3660
+ summary: "Link or unlink your X account"
3661
+ };
3662
+ const telemetryLeaf = ({ name, summary }) => ({
3663
+ arguments: [],
3664
+ examples: [{
3665
+ argv: [
3666
+ "cli",
3667
+ "telemetry",
3668
+ name
3669
+ ],
3670
+ summary
3671
+ }],
3672
+ kind: "leaf",
3673
+ name,
3674
+ notes: ["Telemetry records command paths, option names, failure reasons, and exit codes, never values, paths, or remote data. SANDCOVERY_TELEMETRY_DISABLED=1 turns it off and wins over this setting."],
3675
+ options: [json],
3676
+ result: [{
3677
+ name: "telemetry.enabled",
3678
+ type: "boolean"
3679
+ }, {
3680
+ name: "telemetry.source",
3681
+ type: "\"default\" | \"environment\" | \"settings\""
3682
+ }],
3683
+ summary
3684
+ });
3685
+ const help = {
3686
+ children: [{
3687
+ arguments: [{
3688
+ missing: {
3689
+ message: "Can't search commands without a query.",
3690
+ reason: "missing_query"
3691
+ },
3692
+ name: "query",
3693
+ summary: "Words to look for",
3694
+ variadic: true
3695
+ }],
3696
+ examples: [{
3697
+ argv: [
3698
+ "help",
3699
+ "search",
3700
+ "destroy"
3701
+ ],
3702
+ summary: "Find the command for a task"
3703
+ }],
3704
+ kind: "leaf",
3705
+ name: "search",
3706
+ notes: ["Matches summaries, command names, and examples, works offline, and prints up to 10 commands."],
3707
+ options: [json],
3708
+ result: [{
3709
+ name: "commands[].path",
3710
+ type: "string"
3711
+ }, {
3712
+ name: "commands[].summary",
3713
+ type: "string"
3714
+ }],
3715
+ summary: "Find commands by task"
3716
+ }],
3717
+ kind: "group",
3718
+ name: "help",
3719
+ options: [flag({
3720
+ name: "all",
3721
+ summary: "List every command"
3722
+ })],
3723
+ summary: "Show help for a command"
3724
+ };
3725
+ const CLI = {
3726
+ bin: BIN,
3727
+ globals: [
3728
+ flag({
3729
+ name: "debug",
3730
+ short: "d",
3731
+ summary: "Print diagnostic detail on stderr, with secrets left out"
3732
+ }),
3733
+ {
3734
+ defaultText: "~/.config/sandcovery",
3735
+ hint: "<DIR>",
3736
+ kind: "value",
3737
+ name: "global-config",
3738
+ short: "Q",
3739
+ summary: "Directory that holds the CLI settings"
3740
+ },
3741
+ flag({
3742
+ name: "help",
3743
+ short: "h",
3744
+ summary: "Show help for the command and do nothing else"
3745
+ }),
3746
+ flag({
3747
+ name: "no-color",
3748
+ summary: "Turn off color"
3749
+ }),
3750
+ flag({
3751
+ name: "non-interactive",
3752
+ summary: "Never prompt; fail and name the missing input instead"
3753
+ }),
3754
+ {
3755
+ hint: "<KEY>",
3756
+ kind: "value",
3757
+ name: "token",
3758
+ short: "t",
3759
+ summary: "API key or management key to authenticate with; prefer SANDCOVERY_API_KEY, since options show in process lists"
3760
+ },
3761
+ flag({
3762
+ name: "version",
3763
+ short: "v",
3764
+ summary: "Print the CLI version"
3765
+ })
3766
+ ],
3767
+ learnMore: "https://www.sandcovery.com/docs",
3768
+ root: {
3769
+ children: [
3770
+ sandboxes,
3771
+ docker,
3772
+ kubectl,
3773
+ setup,
3774
+ keys,
3775
+ credentials,
3776
+ providers,
3777
+ usage,
3778
+ stats,
3779
+ activity,
3780
+ billing,
3781
+ pricing,
3782
+ ci,
3783
+ xAccount,
3784
+ problems,
3785
+ login,
3786
+ logout,
3787
+ help,
3788
+ {
3789
+ children: [{
3790
+ children: [
3791
+ telemetryLeaf({
3792
+ name: "status",
3793
+ summary: "Show whether telemetry is on"
3794
+ }),
3795
+ telemetryLeaf({
3796
+ name: "enable",
3797
+ summary: "Turn telemetry on"
3798
+ }),
3799
+ telemetryLeaf({
3800
+ name: "disable",
3801
+ summary: "Turn telemetry off"
3802
+ })
3803
+ ],
3804
+ kind: "group",
3805
+ name: "telemetry",
3806
+ summary: "Turn usage data on or off, or show its status"
3807
+ }],
3808
+ kind: "group",
3809
+ name: "cli",
3810
+ summary: "Change settings of this CLI"
3811
+ }
3812
+ ],
3813
+ kind: "group",
3814
+ name: BIN,
3815
+ notes: [
3816
+ "SANDCOVERY_API_KEY holds an API key or management key from the dashboard; --token wins over it, an empty value counts as unset, and the CLI never saves it. With neither set, commands send the login that sandcovery login saved.",
3817
+ "SANDCOVERY_BASE_URL sets the origin; --base-url wins over it. SANDCOVERY_TELEMETRY_DISABLED=1 turns telemetry off. SANDCOVERY_GUIDANCE_DISABLED=1 hides optional next steps. SANDCOVERY_ACCESSIBLE=1 prints words instead of status glyphs.",
3818
+ "NO_COLOR or --no-color turns color off, FORCE_COLOR turns it on, and CI makes every command non-interactive."
3819
+ ],
3820
+ summary: "Create, run, and destroy sandboxes on any provider with one key"
3821
+ },
3822
+ tasks: [
3823
+ {
3824
+ paths: [
3825
+ ["sandboxes", "create"],
3826
+ ["sandboxes", "exec"],
3827
+ ["sandboxes", "list"],
3828
+ ["sandboxes", "destroy"],
3829
+ ["sandboxes", "files"],
3830
+ ["docker"],
3831
+ ["kubectl"],
3832
+ ["setup"]
3833
+ ],
3834
+ title: "Sandboxes"
3835
+ },
3836
+ {
3837
+ paths: [
3838
+ ["providers", "list"],
3839
+ ["pricing", "inspect"],
3840
+ ["pricing", "monthly"],
3841
+ ["usage", "estimate"],
3842
+ ["usage", "inspect"],
3843
+ ["usage", "live"],
3844
+ ["usage", "totals"],
3845
+ ["usage", "shares"],
3846
+ ["stats", "inspect"]
3847
+ ],
3848
+ title: "Providers and Cost"
3849
+ },
3850
+ {
3851
+ paths: [
3852
+ ["login"],
3853
+ ["logout"],
3854
+ ["keys"],
3855
+ ["credentials"],
3856
+ ["activity", "list"],
3857
+ ["billing"],
3858
+ ["x-account"]
3859
+ ],
3860
+ title: "Account"
3861
+ },
3862
+ {
3863
+ paths: [
3864
+ ["help"],
3865
+ ["help", "search"],
3866
+ ["problems", "report"],
3867
+ ["cli", "telemetry"]
3868
+ ],
3869
+ title: "Help and Settings"
3870
+ }
3871
+ ]
3872
+ };
3873
+ // src/cli/commands/setup.ts
3874
+ const DROP_INS = [{
3875
+ binary: "sandcovery-docker",
3876
+ tool: "docker"
3877
+ }, {
3878
+ binary: "sandcovery-kubectl",
3879
+ tool: "kubectl"
3880
+ }];
3881
+ const LINE_MARK = ` ${SETUP_MARK}`;
3882
+ const SHIM_HEAD = `#!/bin/sh\n${SETUP_MARK}\n`;
3883
+ const BASH_LOGIN = [
3884
+ ".bash_profile",
3885
+ ".bash_login",
3886
+ ".profile"
3887
+ ];
3888
+ const ZSH_FILES = [".zshenv", ".zshrc"];
3889
+ const FILE_TYPE_UNIT = 4096;
3890
+ const UNREACHABLE = /* @__PURE__ */ new Set([
3891
+ "EACCES",
3892
+ "EEXIST",
3893
+ "EISDIR",
3894
+ "ENOTDIR",
3895
+ "EPERM",
3896
+ "EROFS"
3897
+ ]);
3898
+ const EMPTY = {
3899
+ changes: [],
3900
+ edits: []
3901
+ };
3902
+ const joined = (plans) => ({
3903
+ changes: plans.flatMap(({ changes }) => changes),
3904
+ edits: plans.flatMap(({ edits }) => edits)
3905
+ });
3906
+ const touched = ({ file, verb, work }) => {
3907
+ const done = try_(work);
3908
+ if (isSuccess(done)) return done.success;
3909
+ const { failure } = done;
3910
+ const code = hasProperty(failure, "code") && isString(failure.code) ? failure.code : "";
3911
+ if (!UNREACHABLE.has(code)) throw failure;
3912
+ throw new CliFailure({
3913
+ message: verb === "read" ? `Can't read ${file} (${code}). Nothing was changed.` : `Can't write ${file} (${code}). Run the command again once it is writable, and it lists what is left.`,
3914
+ reason: "permission_denied"
3915
+ });
3916
+ };
3917
+ const statOf = (file) => touched({
3918
+ file,
3919
+ verb: "read",
3920
+ work: () => fs.lstatSync(file, { throwIfNoEntry: false })
3921
+ });
3922
+ const textOf = (file) => fs.existsSync(file) ? touched({
3923
+ file,
3924
+ verb: "read",
3925
+ work: () => fs.readFileSync(file, "utf-8")
3926
+ }) : void 0;
3927
+ const envValue = (name) => {
3928
+ const value = process.env[name];
3929
+ return value === void 0 || value === "" ? void 0 : value;
3930
+ };
3931
+ const fishQuoted = (text) => text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("$", "\\$");
3932
+ const posixQuoted = (text) => fishQuoted(text).replaceAll("`", "\\`");
3933
+ const posixLine = (shims) => `export PATH="${posixQuoted(shims)}:$PATH"${LINE_MARK}`;
3934
+ const fishLine = (shims) => `set -gx PATH "${fishQuoted(shims)}" $PATH${LINE_MARK}`;
3935
+ const shimText = (binary) => `${SHIM_HEAD}exec ${binary} "$@"\n`;
3936
+ const executable = (file) => {
3937
+ const found = try_(() => {
3938
+ fs.accessSync(file, fs.constants.X_OK);
3939
+ return fs.statSync(file).isFile();
3940
+ });
3941
+ return isSuccess(found) && found.success;
3942
+ };
3943
+ const onPath = ({ name, shims }) => (process.env.PATH ?? "").split(path.delimiter).flatMap((folder) => path.isAbsolute(folder) && path.resolve(folder) !== shims ? [path.join(folder, name)] : []).find(executable) ?? null;
3944
+ const zshFolder = (home) => envValue("ZDOTDIR") ?? home;
3945
+ const fishConfig = (configHome) => path.join(configHome, "fish", "config.fish");
3946
+ const defaultConfigHome = (home) => path.join(home, ".config");
3947
+ const shellsOf = (home) => {
3948
+ const bashLogin = BASH_LOGIN.map((name) => path.join(home, name)).find((file) => fs.existsSync(file)) ?? path.join(home, ".profile");
3949
+ return [
3950
+ {
3951
+ files: [path.join(home, ".bashrc"), bashLogin],
3952
+ line: posixLine,
3953
+ name: "bash"
3954
+ },
3955
+ {
3956
+ files: ZSH_FILES.map((name) => path.join(zshFolder(home), name)),
3957
+ line: posixLine,
3958
+ name: "zsh"
3959
+ },
3960
+ {
3961
+ files: [fishConfig(envValue("XDG_CONFIG_HOME") ?? defaultConfigHome(home))],
3962
+ line: fishLine,
3963
+ name: "fish"
3964
+ }
3965
+ ];
3966
+ };
3967
+ const everyStartupFile = (home) => [.../* @__PURE__ */ new Set([
3968
+ ...[".bashrc", ...BASH_LOGIN].map((name) => path.join(home, name)),
3969
+ ...[zshFolder(home), home].flatMap((folder) => ZSH_FILES.map((name) => path.join(folder, name))),
3970
+ ...[envValue("XDG_CONFIG_HOME") ?? defaultConfigHome(home), defaultConfigHome(home)].map(fishConfig)
3971
+ ])];
3972
+ const appended = (line) => (text) => {
3973
+ if (text.split("\n").includes(line)) return text;
3974
+ return `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}${line}\n`;
3975
+ };
3976
+ const withoutMarked = (text) => text.split("\n").filter((line) => !line.endsWith(LINE_MARK)).join("\n");
3977
+ const folderEntries = (folder) => statOf(folder)?.isDirectory() === true ? touched({
3978
+ file: folder,
3979
+ verb: "read",
3980
+ work: () => fs.readdirSync(folder)
3981
+ }).map((name) => path.join(folder, name)).toSorted() : [];
3982
+ const isOwnShim = (file) => statOf(file)?.isFile() === true && (textOf(file) ?? "").startsWith(SHIM_HEAD);
3983
+ const shimDeletion = (file) => ({
3984
+ changes: [{
3985
+ action: "delete",
3986
+ file,
3987
+ line: null,
3988
+ summary: "Delete this shim",
3989
+ text: null
3990
+ }],
3991
+ edits: [{
3992
+ file,
3993
+ kind: "delete"
3994
+ }]
3995
+ });
3996
+ const shimWrite = ({ binary, shims, tool }) => {
3997
+ const file = path.join(shims, tool);
3998
+ const text = shimText(binary);
3999
+ const stat = statOf(file);
4000
+ if (stat !== void 0) {
4001
+ const current = stat.isFile() ? textOf(file) : void 0;
4002
+ if (current === text) return EMPTY;
4003
+ if (current === void 0 || !current.startsWith(SHIM_HEAD)) throw new CliFailure({
4004
+ message: `Can't write the ${tool} shim. ${file} is not a file sandcovery setup wrote, so it stays as it is.`,
4005
+ reason: "conflict",
4006
+ recovery: [{ instruction: `Move ${file} out of ${shims}, then run sandcovery setup again` }]
4007
+ });
4008
+ }
4009
+ return {
4010
+ changes: [{
4011
+ action: "write",
4012
+ file,
4013
+ line: null,
4014
+ summary: `Write a shim that runs ${binary}`,
4015
+ text
4016
+ }],
4017
+ edits: [{
4018
+ file,
4019
+ kind: "shim",
4020
+ text
4021
+ }]
4022
+ };
4023
+ };
4024
+ const shimPlan = ({ dropIns, shims }) => {
4025
+ const wanted = dropIns.filter(({ installed }) => installed);
4026
+ const tools = new Set(wanted.map(({ tool }) => tool));
4027
+ return joined([...wanted.map(({ binary, tool }) => shimWrite({
4028
+ binary,
4029
+ shims,
4030
+ tool
4031
+ })), ...folderEntries(shims).flatMap((file) => tools.has(path.basename(file)) || !isOwnShim(file) ? [] : [shimDeletion(file)])]);
4032
+ };
4033
+ const lineAddition = ({ file, text }) => {
4034
+ const current = textOf(file) ?? "";
4035
+ return appended(text)(current) === current ? EMPTY : {
4036
+ changes: [{
4037
+ action: "append",
4038
+ file,
4039
+ line: null,
4040
+ summary: `Add: ${text}`,
4041
+ text
4042
+ }],
4043
+ edits: [{
4044
+ change: appended(text),
4045
+ file,
4046
+ kind: "startup"
4047
+ }]
4048
+ };
4049
+ };
4050
+ const linePlan = ({ home, shims }) => {
4051
+ const login = path.basename(envValue("SHELL") ?? "");
4052
+ return joined(shellsOf(home).flatMap(({ files, line, name }) => name === login || files.some((file) => fs.existsSync(file)) ? files.map((file) => lineAddition({
4053
+ file,
4054
+ text: line(shims)
4055
+ })) : []));
4056
+ };
4057
+ const lineRemovals = (file) => {
4058
+ const text = textOf(file);
4059
+ if (text === void 0) return EMPTY;
4060
+ const marked = text.split("\n").flatMap((line, index) => line.endsWith(LINE_MARK) ? [{
4061
+ line: index + 1,
4062
+ text: line
4063
+ }] : []);
4064
+ if (marked.length === 0) return EMPTY;
4065
+ const deletion = withoutMarked(text) === "" && statOf(file)?.isFile() === true ? [{
4066
+ action: "delete",
4067
+ file,
4068
+ line: null,
4069
+ summary: "Delete this file, which holds nothing else",
4070
+ text: null
4071
+ }] : [];
4072
+ return {
4073
+ changes: [...marked.map(({ line, text: content }) => ({
4074
+ action: "remove",
4075
+ file,
4076
+ line,
4077
+ summary: `Remove line ${String(line)}: ${content}`,
4078
+ text: content
4079
+ })), ...deletion],
4080
+ edits: [{
4081
+ change: withoutMarked,
4082
+ file,
4083
+ kind: "startup"
4084
+ }]
4085
+ };
4086
+ };
4087
+ const undoPlan = ({ home, shims }) => {
4088
+ const entries = folderEntries(shims);
4089
+ const own = entries.filter(isOwnShim);
4090
+ const folderGoes = statOf(shims)?.isDirectory() === true && own.length === entries.length;
4091
+ return joined([
4092
+ ...everyStartupFile(home).map(lineRemovals),
4093
+ ...own.map(shimDeletion),
4094
+ folderGoes ? {
4095
+ changes: [{
4096
+ action: "delete",
4097
+ file: shims,
4098
+ line: null,
4099
+ summary: "Delete this empty folder",
4100
+ text: null
4101
+ }],
4102
+ edits: [{
4103
+ file: shims,
4104
+ kind: "folder"
4105
+ }]
4106
+ } : EMPTY
4107
+ ]);
4108
+ };
4109
+ const replaceText = ({ file, mode, text }) => {
4110
+ const folder = path.dirname(file);
4111
+ fs.mkdirSync(folder, { recursive: true });
4112
+ const pending = path.join(folder, `.${path.basename(file)}.${crypto$1.randomBytes(8).toString("hex")}.tmp`);
4113
+ fs.writeFileSync(pending, text, { flag: "wx" });
4114
+ if (mode !== void 0) fs.chmodSync(pending, mode);
4115
+ fs.renameSync(pending, file);
4116
+ };
4117
+ const rewrite = ({ change, file }) => {
4118
+ const target = fs.existsSync(file) ? fs.realpathSync(file) : file;
4119
+ const before = textOf(target) ?? "";
4120
+ const after = change(before);
4121
+ if (after === before) return;
4122
+ if (after === "" && statOf(file)?.isFile() === true) {
4123
+ fs.rmSync(file);
4124
+ return;
4125
+ }
4126
+ const stat = statOf(target);
4127
+ replaceText({
4128
+ file: target,
4129
+ mode: stat === void 0 ? void 0 : stat.mode % FILE_TYPE_UNIT,
4130
+ text: after
4131
+ });
4132
+ };
4133
+ const apply = (edit) => {
4134
+ touched({
4135
+ file: edit.file,
4136
+ verb: "write",
4137
+ work: () => {
4138
+ if (edit.kind === "startup") rewrite(edit);
4139
+ else if (edit.kind === "shim") {
4140
+ fs.mkdirSync(path.dirname(edit.file), {
4141
+ mode: 448,
4142
+ recursive: true
4143
+ });
4144
+ replaceText({
4145
+ file: edit.file,
4146
+ mode: 493,
4147
+ text: edit.text
4148
+ });
4149
+ } else if (edit.kind === "delete") fs.rmSync(edit.file, { force: true });
4150
+ else if (fs.readdirSync(edit.file).length === 0) fs.rmdirSync(edit.file);
4151
+ }
4152
+ });
4153
+ };
4154
+ const resultOf = ({ changes, dropIns }) => ({
4155
+ changes: changes.map(({ action, file, line, text }) => ({
4156
+ action,
4157
+ file,
4158
+ line,
4159
+ text
4160
+ })),
4161
+ drop_ins: dropIns
4162
+ });
4163
+ const toolNotes = (dropIns) => dropIns.map(({ binary, installed, real_path: realPath, tool }) => {
4164
+ if (!installed) return `${tool} stays as it is, since ${binary} isn't installed.`;
4165
+ return realPath === null ? `${tool} runs ${binary} in each new terminal.` : `${tool} runs ${binary} in each new terminal. Your own ${tool} stays at ${realPath} and runs by that full path.`;
4166
+ });
4167
+ const confirmed = async ({ changes, context, dropIns, notes, undo }) => {
4168
+ context.io.context(changes.map(({ file, summary }) => ({
4169
+ label: file,
4170
+ value: summary
4171
+ })));
4172
+ context.io.note(notes);
4173
+ if (flagOf(context.options, "yes") === true) return;
4174
+ if (!context.mode.interactive || context.prompter === void 0) throw new CliFailure({
4175
+ data: resultOf({
4176
+ changes,
4177
+ dropIns
4178
+ }),
4179
+ message: `Can't ${undo ? "undo sandcovery setup" : "set up drop-ins"} without --yes in non-interactive mode.`,
4180
+ reason: "confirmation_required",
4181
+ recovery: [{
4182
+ instruction: "After a person approves the changes listed, run",
4183
+ next: {
4184
+ argv: [...context.rerun, "--yes"],
4185
+ when: "Only after a human approves the listed changes"
4186
+ }
4187
+ }],
4188
+ userActionRequired: true
4189
+ });
4190
+ if (!await context.prompter.confirm("Make these changes?")) throw new Canceled({
4191
+ remote: "none",
4192
+ signal: "SIGINT"
4193
+ });
4194
+ };
4195
+ const shimsOf = (context) => path.join(path.dirname(context.settingsFile), "bin");
4196
+ const shimFolder = (context) => {
4197
+ const shims = shimsOf(context);
4198
+ const characters = new Set(shims);
4199
+ if (characters.has(path.delimiter) || characters.has("\n")) throw new CliFailure({
4200
+ message: `Can't put ${shims} on PATH, since PATH can't hold a folder whose name has a colon or a line break.`,
4201
+ reason: "invalid_arguments",
4202
+ recovery: [{ instruction: "Choose another settings folder with --global-config" }]
4203
+ });
4204
+ return shims;
4205
+ };
4206
+ const setupDropIns = async (context) => {
4207
+ if (process.platform === "win32") throw new CliFailure({
4208
+ message: "Can't set up drop-ins on Windows. sandcovery setup changes the startup files of bash, zsh, and fish.",
4209
+ reason: "unsupported"
4210
+ });
4211
+ const undo = flagOf(context.options, "undo") === true;
4212
+ const home = os.homedir();
4213
+ const shims = shimFolder(context);
4214
+ const dropIns = DROP_INS.map(({ binary, tool }) => ({
4215
+ binary,
4216
+ installed: onPath({
4217
+ name: binary,
4218
+ shims
4219
+ }) !== null,
4220
+ real_path: onPath({
4221
+ name: tool,
4222
+ shims
4223
+ }),
4224
+ tool
4225
+ }));
4226
+ if (!undo && dropIns.every(({ installed }) => !installed)) throw new CliFailure({
4227
+ message: `Can't set up drop-ins. None of ${DROP_INS.map(({ binary }) => binary).join(", ")} is on PATH.`,
4228
+ notes: ["They come with the sandcovery npm package: npm install --global sandcovery."],
4229
+ reason: "not_found"
4230
+ });
4231
+ const plan = undo ? undoPlan({
4232
+ home,
4233
+ shims
4234
+ }) : joined([shimPlan({
4235
+ dropIns,
4236
+ shims
4237
+ }), linePlan({
4238
+ home,
4239
+ shims
4240
+ })]);
4241
+ const notes = undo ? [] : toolNotes(dropIns);
4242
+ if (plan.changes.length === 0) {
4243
+ context.io.note([undo ? "Nothing to undo." : "Nothing to change.", ...notes]);
4244
+ return { document: resultOf({
4245
+ changes: [],
4246
+ dropIns
4247
+ }) };
4248
+ }
4249
+ await confirmed({
4250
+ changes: plan.changes,
4251
+ context,
4252
+ dropIns,
4253
+ notes,
4254
+ undo
4255
+ });
4256
+ for (const edit of plan.edits) apply(edit);
4257
+ context.io.receipt({
4258
+ outcome: undo ? "Undone" : "Set up",
4259
+ target: shims
4260
+ });
4261
+ if (!undo) context.io.note(["Open a new terminal, so the shims come first on PATH there."]);
4262
+ return { document: resultOf({
4263
+ changes: plan.changes,
4264
+ dropIns
4265
+ }) };
4266
+ };
4267
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/stringify.js
4268
+ const byteToHex = [];
4269
+ for (let i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).slice(1));
4270
+ function unsafeStringify(arr, offset = 0) {
4271
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
4272
+ }
4273
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/rng.js
4274
+ const rnds8 = /* @__PURE__ */ new Uint8Array(16);
4275
+ function rng() {
4276
+ return crypto.getRandomValues(rnds8);
4277
+ }
4278
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/v7.js
4279
+ const _state = {};
4280
+ function v7(options, buf, offset) {
4281
+ let bytes;
4282
+ if (options) bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset);
4283
+ else {
4284
+ const now = Date.now();
4285
+ const rnds = rng();
4286
+ updateV7State(_state, now, rnds);
4287
+ bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
4288
+ }
4289
+ return buf ?? unsafeStringify(bytes);
4290
+ }
4291
+ function updateV7State(state, now, rnds) {
4292
+ state.msecs ??= -Infinity;
4293
+ state.seq ??= 0;
4294
+ if (now > state.msecs) {
4295
+ state.seq = v7Sequence(rnds);
4296
+ state.msecs = now;
4297
+ } else {
4298
+ state.seq = state.seq + 1 | 0;
4299
+ if (state.seq === 0) state.msecs++;
4300
+ }
4301
+ return state;
4302
+ }
4303
+ function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
4304
+ if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
4305
+ if (!buf) {
4306
+ buf = /* @__PURE__ */ new Uint8Array(16);
4307
+ offset = 0;
4308
+ } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
4309
+ msecs ??= Date.now();
4310
+ seq ??= v7Sequence(rnds);
4311
+ buf[offset++] = msecs / 1099511627776 & 255;
4312
+ buf[offset++] = msecs / 4294967296 & 255;
4313
+ buf[offset++] = msecs / 16777216 & 255;
4314
+ buf[offset++] = msecs / 65536 & 255;
4315
+ buf[offset++] = msecs / 256 & 255;
4316
+ buf[offset++] = msecs & 255;
4317
+ buf[offset++] = 112 | seq >>> 28 & 15;
4318
+ buf[offset++] = seq >>> 20 & 255;
4319
+ buf[offset++] = 128 | seq >>> 14 & 63;
4320
+ buf[offset++] = seq >>> 6 & 255;
4321
+ buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
4322
+ buf[offset++] = rnds[11];
4323
+ buf[offset++] = rnds[12];
4324
+ buf[offset++] = rnds[13];
4325
+ buf[offset++] = rnds[14];
4326
+ buf[offset++] = rnds[15];
4327
+ return buf;
4328
+ }
4329
+ function v7Sequence(rnds) {
4330
+ return (rnds[6] & 127) << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
4331
+ }
4332
+ // src/cli/relay.ts
4333
+ const RELAY_PORT = 9951;
4334
+ const RELAY_TOKEN_HEADER = "x-sandcovery-relay-token";
4335
+ const RELAY_SOURCE = String.raw`import base64
4336
+ import hashlib
4337
+ import hmac
4338
+ import json
4339
+ import os
4340
+ import socket
4341
+ import subprocess
4342
+ import sys
4343
+ import threading
4344
+
4345
+ GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
4346
+ HEADER_LIMIT = 16384
4347
+ CHUNK = 65536
4348
+ KEEPALIVE_SECONDS = 30
4349
+ TEXT, BINARY, CLOSE, PING, PONG = 1, 2, 8, 9, 10
4350
+ EVENTS = [
4351
+ "docker", "events", "--format", "{{.Actor.ID}}",
4352
+ "--filter", "type=container",
4353
+ "--filter", "event=start",
4354
+ "--filter", "event=die",
4355
+ ]
4356
+
4357
+
4358
+ def shut(sock, how=socket.SHUT_RDWR):
4359
+ try:
4360
+ sock.shutdown(how)
4361
+ except OSError:
4362
+ pass
4363
+
4364
+
4365
+ class Peer:
4366
+ def __init__(self, conn):
4367
+ self.conn = conn
4368
+ self.buffer = b""
4369
+ self.lock = threading.Lock()
4370
+ self.done = threading.Event()
4371
+
4372
+ def fill(self):
4373
+ chunk = self.conn.recv(CHUNK)
4374
+ if not chunk:
4375
+ raise EOFError
4376
+ self.buffer += chunk
4377
+
4378
+ def take(self, size):
4379
+ while len(self.buffer) < size:
4380
+ self.fill()
4381
+ data, self.buffer = self.buffer[:size], self.buffer[size:]
4382
+ return data
4383
+
4384
+ def head(self):
4385
+ while b"\r\n\r\n" not in self.buffer:
4386
+ if len(self.buffer) > HEADER_LIMIT:
4387
+ raise EOFError
4388
+ self.fill()
4389
+ head, self.buffer = self.buffer.split(b"\r\n\r\n", 1)
4390
+ return head.decode("latin-1").split("\r\n")
4391
+
4392
+ def send(self, opcode, payload=b""):
4393
+ size = len(payload)
4394
+ if size < 126:
4395
+ head = bytes([0x80 | opcode, size])
4396
+ elif size < 65536:
4397
+ head = bytes([0x80 | opcode, 126]) + size.to_bytes(2, "big")
4398
+ else:
4399
+ head = bytes([0x80 | opcode, 127]) + size.to_bytes(8, "big")
4400
+ with self.lock:
4401
+ self.conn.sendall(head + payload)
4402
+
4403
+ def frame(self):
4404
+ first, second = self.take(2)
4405
+ size = second & 0x7F
4406
+ if size == 126:
4407
+ size = int.from_bytes(self.take(2), "big")
4408
+ elif size == 127:
4409
+ size = int.from_bytes(self.take(8), "big")
4410
+ mask = self.take(4) if second & 0x80 else b""
4411
+ payload = self.take(size)
4412
+ if mask and size:
4413
+ key = (mask * (size // 4 + 1))[:size]
4414
+ mixed = int.from_bytes(payload, "little") ^ int.from_bytes(key, "little")
4415
+ payload = mixed.to_bytes(size, "little")
4416
+ return first & 0x80, first & 0x0F, payload
4417
+
4418
+ def message(self):
4419
+ kind, parts = 0, []
4420
+ while True:
4421
+ final, opcode, payload = self.frame()
4422
+ if opcode == PING:
4423
+ self.send(PONG, payload)
4424
+ elif opcode == CLOSE:
4425
+ return CLOSE, b""
4426
+ elif opcode != PONG:
4427
+ kind = kind or opcode
4428
+ parts.append(payload)
4429
+ if final:
4430
+ return kind, b"".join(parts)
4431
+
4432
+
4433
+ def refuse(peer, status):
4434
+ peer.conn.sendall(
4435
+ ("HTTP/1.1 " + status + "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").encode()
4436
+ )
4437
+
4438
+
4439
+ def keepalive(peer):
4440
+ while not peer.done.wait(KEEPALIVE_SECONDS):
4441
+ try:
4442
+ peer.send(PING)
4443
+ except OSError:
4444
+ return
4445
+
4446
+
4447
+ def accept(peer, key):
4448
+ digest = base64.b64encode(hashlib.sha1(key.encode() + GUID).digest()).decode()
4449
+ peer.conn.sendall(
4450
+ (
4451
+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
4452
+ "Connection: Upgrade\r\nSec-WebSocket-Accept: " + digest + "\r\n\r\n"
4453
+ ).encode()
4454
+ )
4455
+ threading.Thread(target=keepalive, args=(peer,), daemon=True).start()
4456
+
4457
+
4458
+ def send_down(peer, upstream):
4459
+ try:
4460
+ while True:
4461
+ data = upstream.recv(CHUNK)
4462
+ peer.send(BINARY, data)
4463
+ if not data:
4464
+ return
4465
+ except OSError:
4466
+ shut(peer.conn)
4467
+
4468
+
4469
+ def pipe(peer, upstream):
4470
+ with upstream:
4471
+ threading.Thread(target=send_down, args=(peer, upstream), daemon=True).start()
4472
+ try:
4473
+ while True:
4474
+ opcode, payload = peer.message()
4475
+ if opcode == CLOSE:
4476
+ return
4477
+ if payload:
4478
+ upstream.sendall(payload)
4479
+ else:
4480
+ shut(upstream, socket.SHUT_WR)
4481
+ finally:
4482
+ shut(upstream)
4483
+ try:
4484
+ peer.send(CLOSE)
4485
+ except OSError:
4486
+ pass
4487
+
4488
+
4489
+ def ports_snapshot():
4490
+ ids = subprocess.run(
4491
+ ["docker", "ps", "--quiet", "--no-trunc"], capture_output=True, text=True
4492
+ ).stdout.split()
4493
+ if not ids:
4494
+ return "[]"
4495
+ shown = subprocess.run(
4496
+ ["docker", "inspect", "--format", "{{json .NetworkSettings.Ports}}", *ids],
4497
+ capture_output=True,
4498
+ text=True,
4499
+ ).stdout
4500
+ return "[" + ",".join(line for line in shown.splitlines() if line) + "]"
4501
+
4502
+
4503
+ def events(peer, key):
4504
+ accept(peer, key)
4505
+ lock = threading.Lock()
4506
+ watcher = subprocess.Popen(EVENTS, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
4507
+
4508
+ def snapshot(tag=None):
4509
+ with lock:
4510
+ shown = '{"ports":' + ports_snapshot() + ',"tag":' + json.dumps(tag) + "}"
4511
+ peer.send(TEXT, shown.encode())
4512
+
4513
+ def watch():
4514
+ try:
4515
+ for _ in watcher.stdout:
4516
+ snapshot()
4517
+ except OSError:
4518
+ pass
4519
+ shut(peer.conn)
4520
+
4521
+ try:
4522
+ threading.Thread(target=watch, daemon=True).start()
4523
+ snapshot()
4524
+ while True:
4525
+ opcode, payload = peer.message()
4526
+ if opcode == CLOSE:
4527
+ return
4528
+ snapshot(payload.decode("utf-8", "replace"))
4529
+ finally:
4530
+ watcher.kill()
4531
+ watcher.wait()
4532
+
4533
+
4534
+ def handle(conn, token):
4535
+ with conn:
4536
+ peer = Peer(conn)
4537
+ try:
4538
+ lines = peer.head()
4539
+ request = lines[0].split(" ")
4540
+ fields = {}
4541
+ for line in lines[1:]:
4542
+ name, _, value = line.partition(":")
4543
+ fields[name.strip().lower()] = value.strip()
4544
+ offered = fields.get("${RELAY_TOKEN_HEADER}", "").encode()
4545
+ key = fields.get("sec-websocket-key", "")
4546
+ if not hmac.compare_digest(offered, token):
4547
+ return refuse(peer, "401 Unauthorized")
4548
+ if len(request) != 3 or not key or fields.get("upgrade", "").lower() != "websocket":
4549
+ return refuse(peer, "400 Bad Request")
4550
+ target = request[1].split("?")[0]
4551
+ if target.endswith("/events"):
4552
+ return events(peer, key)
4553
+ _, found, digits = target.rpartition("/tcp/")
4554
+ number = int(digits) if found and digits.isascii() and digits.isdigit() else 0
4555
+ if not 0 < number < 65536:
4556
+ return refuse(peer, "404 Not Found")
4557
+ try:
4558
+ upstream = socket.create_connection(("127.0.0.1", number))
4559
+ except OSError:
4560
+ return refuse(peer, "502 Bad Gateway")
4561
+ accept(peer, key)
4562
+ pipe(peer, upstream)
4563
+ except (EOFError, OSError, ValueError):
4564
+ pass
4565
+ finally:
4566
+ peer.done.set()
4567
+
4568
+
4569
+ def main():
4570
+ port, token_file = int(sys.argv[1]), sys.argv[2]
4571
+ with open(token_file, "rb") as file:
4572
+ token = file.read().strip()
4573
+ os.remove(token_file)
4574
+ if not token:
4575
+ raise SystemExit("the relay token file is empty")
4576
+ try:
4577
+ server = socket.create_server(("", port), family=socket.AF_INET6, dualstack_ipv6=True)
4578
+ except (OSError, ValueError):
4579
+ server = socket.create_server(("", port))
4580
+ child = os.fork()
4581
+ if child:
4582
+ print(server.getsockname()[1], child, flush=True)
4583
+ os._exit(0)
4584
+ os.setsid()
4585
+ devnull = os.open(os.devnull, os.O_RDWR)
4586
+ for descriptor in (0, 1, 2):
4587
+ os.dup2(devnull, descriptor)
4588
+ while True:
4589
+ conn, _ = server.accept()
4590
+ threading.Thread(target=handle, args=(conn, token), daemon=True).start()
4591
+
4592
+
4593
+ main()
4594
+ `;
4595
+ // src/cli/port-forwarder.ts
4596
+ const FORWARDER_ENV = "__SANDCOVERY_PORT_FORWARDER";
4597
+ const BUFFERED_LIMIT = 4194304;
4598
+ const DRAIN_POLL_MS = 10;
4599
+ const SYNC_MS = 15e3;
4600
+ const UNATTACHED_MS = 6e4;
4601
+ const PREVIEW_MARGIN_MS = 6e4;
4602
+ const LONGEST_TIMER_MS = 2147483647;
4603
+ const RETRY_MS = [
4604
+ 1e3,
4605
+ 2e3,
4606
+ 5e3,
4607
+ 1e4,
4608
+ 3e4
4609
+ ];
4610
+ const ANY_IPV4 = "0.0.0.0";
4611
+ const HIGHEST_PORT = 65535;
4612
+ const UnforwardedSchema = Struct({
4613
+ host: String$1,
4614
+ port: Number$1,
4615
+ reason: Literals(["busy", "denied"])
4616
+ });
4617
+ const decodeRequest = decodeUnknownOption(fromJsonString(Struct({
4618
+ attachment: Struct({
4619
+ expires_at: String$1,
4620
+ key: String$1,
4621
+ origin: String$1,
4622
+ sandbox: String$1,
4623
+ token: String$1
4624
+ }),
4625
+ sync: Boolean
4626
+ })));
4627
+ const decodeReply = decodeUnknownOption(fromJsonString(Struct({ unforwarded: ArraySchema(UnforwardedSchema) })));
4628
+ const SnapshotSchema = Struct({
4629
+ ports: ArraySchema(NullOr(Record(String$1, NullOr(ArraySchema(Struct({
4630
+ HostIp: String$1,
4631
+ HostPort: String$1
4632
+ })))))),
4633
+ tag: NullOr(String$1)
4634
+ });
4635
+ const decodeSnapshot = decodeUnknownOption(fromJsonString(SnapshotSchema));
4636
+ const keyOf = ({ host, port }) => `${host} ${String(port)}`;
4637
+ const isPort = (port) => Number.isInteger(port) && port > 0 && port <= HIGHEST_PORT;
4638
+ const publishedIn = (ports) => ports.flatMap((container) => Object.entries(container ?? {}).flatMap(([target, bindings]) => target.endsWith("/tcp") ? (bindings ?? []).flatMap(({ HostIp, HostPort }) => {
4639
+ const port = Number(HostPort);
4640
+ return isPort(port) ? [{
4641
+ host: HostIp === "" ? ANY_IPV4 : HostIp,
4642
+ port
4643
+ }] : [];
4644
+ }) : []));
4645
+ const errorCode = (error) => error.code ?? "";
4646
+ const cancel = (timer) => {
4647
+ if (timer !== null) clearTimeout(timer);
4648
+ return null;
4649
+ };
4650
+ const heldUntil = async (attachment) => {
4651
+ const [read] = await Promise.allSettled([new Sandcovery({
4652
+ apiKey: attachment.key,
4653
+ baseUrl: attachment.origin
4654
+ }).sandboxes.get(attachment.sandbox)]);
4655
+ return read.status === "fulfilled" && read.value.status === "running" ? Date.parse(read.value.expires_at) : Number.NEGATIVE_INFINITY;
4656
+ };
4657
+ const resumedWhenDrained = (remote, local) => {
4658
+ const timer = setInterval(() => {
4659
+ if (remote.bufferedAmount <= BUFFERED_LIMIT || remote.readyState !== WebSocket.OPEN) {
4660
+ clearInterval(timer);
4661
+ local.resume();
4662
+ }
4663
+ }, DRAIN_POLL_MS);
4664
+ };
4665
+ const carry = (local, remote) => {
4666
+ const ended = {
4667
+ local: false,
4668
+ remote: false
4669
+ };
4670
+ const finish = () => {
4671
+ if (ended.local && ended.remote) remote.close();
4672
+ };
4673
+ remote.addEventListener("open", () => {
4674
+ local.resume();
4675
+ });
4676
+ remote.addEventListener("message", ({ data }) => {
4677
+ if (!(data instanceof ArrayBuffer)) return;
4678
+ if (data.byteLength === 0) {
4679
+ ended.remote = true;
4680
+ local.end();
4681
+ finish();
4682
+ } else local.write(new Uint8Array(data));
4683
+ });
4684
+ remote.addEventListener("close", () => {
4685
+ if (!ended.local || !ended.remote) local.destroy();
4686
+ });
4687
+ local.on("data", (chunk) => {
4688
+ remote.send(chunk);
4689
+ if (remote.bufferedAmount > BUFFERED_LIMIT) {
4690
+ local.pause();
4691
+ resumedWhenDrained(remote, local);
4692
+ }
4693
+ });
4694
+ local.once("end", () => {
4695
+ ended.local = true;
4696
+ remote.send(/* @__PURE__ */ new Uint8Array());
4697
+ finish();
4698
+ });
4699
+ local.once("error", () => {
4700
+ remote.close();
4701
+ });
4702
+ };
4703
+ const forwarderSocket = (settingsFile) => socketOf({
4704
+ name: "docker-ports",
4705
+ settingsFile
4706
+ });
4707
+ const requested = async (connection) => {
4708
+ const chunks = [];
4709
+ const { promise, resolve } = Promise.withResolvers();
4710
+ connection.on("data", (chunk) => {
4711
+ chunks.push(chunk);
4712
+ });
4713
+ connection.once("end", () => {
4714
+ resolve(Buffer.concat(chunks).toString("utf-8"));
4715
+ });
4716
+ connection.once("close", () => {
4717
+ resolve("");
4718
+ });
4719
+ return await promise;
4720
+ };
4721
+ const forwardPorts = async (socketPath) => {
4722
+ const state = {
4723
+ applying: false,
4724
+ attachment: null,
4725
+ bound: /* @__PURE__ */ new Map(),
4726
+ connecting: false,
4727
+ control: null,
4728
+ expiry: null,
4729
+ failures: 0,
4730
+ latest: null,
4731
+ notices: /* @__PURE__ */ new Map(),
4732
+ relay: null,
4733
+ retry: null,
4734
+ syncs: /* @__PURE__ */ new Map()
4735
+ };
4736
+ const listener = net.createServer({ allowHalfOpen: true });
4737
+ const release = () => {
4738
+ for (const server of state.bound.values()) server.close();
4739
+ state.bound.clear();
4740
+ state.notices.clear();
4741
+ state.latest = null;
4742
+ state.relay = null;
4743
+ state.failures = 0;
4744
+ state.retry = cancel(state.retry);
4745
+ const { control } = state;
4746
+ state.control = null;
4747
+ control?.close();
4748
+ };
4749
+ const wakeSyncs = () => {
4750
+ for (const wake of state.syncs.values()) wake();
4751
+ };
4752
+ const stop = () => {
4753
+ release();
4754
+ state.attachment = null;
4755
+ state.expiry = cancel(state.expiry);
4756
+ listener.close();
4757
+ wakeSyncs();
4758
+ };
4759
+ const expireAt = (deadline) => {
4760
+ const settle = async () => {
4761
+ const { attachment } = state;
4762
+ const later = Date.now() < deadline || attachment === null ? deadline : await heldUntil(attachment);
4763
+ if (state.attachment !== attachment) return;
4764
+ if (later > Date.now()) expireAt(later);
4765
+ else stop();
4766
+ };
4767
+ cancel(state.expiry);
4768
+ state.expiry = setTimeout(() => {
4769
+ settle();
4770
+ }, clamp(deadline - Date.now(), 0, LONGEST_TIMER_MS));
4771
+ };
4772
+ const relay = async (attachment) => {
4773
+ if (state.relay !== null && state.relay.expiresAt - Date.now() > PREVIEW_MARGIN_MS) return state.relay;
4774
+ const preview = await new Sandcovery({
4775
+ apiKey: attachment.key,
4776
+ baseUrl: attachment.origin
4777
+ }).sandboxes.portPreview(attachment.sandbox, RELAY_PORT);
4778
+ state.relay = {
4779
+ expiresAt: preview.expires_at === null ? Number.POSITIVE_INFINITY : Date.parse(preview.expires_at),
4780
+ headers: preview.headers,
4781
+ url: preview.url
4782
+ };
4783
+ return state.relay;
4784
+ };
4785
+ const attempted = async (attachment, target, listen) => {
4786
+ try {
4787
+ const current = await relay(attachment);
4788
+ const url = new URL(current.url);
4789
+ url.pathname = `${url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname}${target}`;
4790
+ const socket = new WebSocket(url, { headers: {
4791
+ ...current.headers,
4792
+ [RELAY_TOKEN_HEADER]: attachment.token
4793
+ } });
4794
+ socket.binaryType = "arraybuffer";
4795
+ listen(socket);
4796
+ return socket;
4797
+ } catch (error) {
4798
+ if (error instanceof Error) return error;
4799
+ throw error;
4800
+ }
4801
+ };
4802
+ const tunnel = async (local, port) => {
4803
+ local.on("error", noop);
4804
+ const { attachment } = state;
4805
+ const outcome = attachment === null ? null : await attempted(attachment, `/tcp/${String(port)}`, (remote) => {
4806
+ carry(local, remote);
4807
+ });
4808
+ if (outcome === null || outcome instanceof Error) local.destroy();
4809
+ };
4810
+ const bind = async (published) => {
4811
+ const { host, port } = published;
4812
+ const server = net.createServer({
4813
+ allowHalfOpen: true,
4814
+ pauseOnConnect: true
4815
+ }, (local) => {
4816
+ tunnel(local, port);
4817
+ });
4818
+ const { promise, resolve } = Promise.withResolvers();
4819
+ server.once("error", (error) => {
4820
+ const code = errorCode(error);
4821
+ if (code === "EADDRINUSE") resolve({
4822
+ host,
4823
+ port,
4824
+ reason: "busy"
4825
+ });
4826
+ else if (code === "EACCES") resolve({
4827
+ host,
4828
+ port,
4829
+ reason: "denied"
4830
+ });
4831
+ else resolve(null);
4832
+ });
4833
+ server.listen({
4834
+ host,
4835
+ ipv6Only: host.includes(":"),
4836
+ port
4837
+ }, () => {
4838
+ server.on("error", noop);
4839
+ state.bound.set(keyOf(published), server);
4840
+ resolve(null);
4841
+ });
4842
+ return await promise;
4843
+ };
4844
+ const apply = async (published) => {
4845
+ const wanted = new Map(published.map((entry) => [keyOf(entry), entry]));
4846
+ for (const [key, server] of state.bound) if (!wanted.has(key)) {
4847
+ server.close();
4848
+ state.bound.delete(key);
4849
+ }
4850
+ for (const key of state.notices.keys()) if (!wanted.has(key)) state.notices.delete(key);
4851
+ const refused = await Promise.all([...wanted.values()].flatMap((entry) => state.bound.has(keyOf(entry)) ? [] : [bind(entry)]));
4852
+ for (const key of state.bound.keys()) state.notices.delete(key);
4853
+ for (const entry of refused) if (entry !== null && !state.notices.has(keyOf(entry))) state.notices.set(keyOf(entry), {
4854
+ entry,
4855
+ reported: false
4856
+ });
4857
+ };
4858
+ const applyLatest = async () => {
4859
+ const next = state.latest;
4860
+ if (next === null || state.applying) return;
4861
+ state.latest = null;
4862
+ state.applying = true;
4863
+ try {
4864
+ await apply(next.published);
4865
+ } finally {
4866
+ state.applying = false;
4867
+ }
4868
+ for (const tag of next.tags) state.syncs.get(tag)?.();
4869
+ await applyLatest();
4870
+ };
4871
+ const received = ({ ports, tag }) => {
4872
+ state.latest = {
4873
+ published: publishedIn(ports),
4874
+ tags: [...state.latest?.tags ?? [], ...tag === null ? [] : [tag]]
4875
+ };
4876
+ applyLatest();
4877
+ };
4878
+ const requestSync = (tag) => {
4879
+ if (state.control?.readyState === WebSocket.OPEN) state.control.send(tag);
4880
+ };
4881
+ const watch = (control) => {
4882
+ state.control = control;
4883
+ control.addEventListener("open", () => {
4884
+ state.failures = 0;
4885
+ for (const tag of state.syncs.keys()) requestSync(tag);
4886
+ });
4887
+ control.addEventListener("message", ({ data }) => {
4888
+ const snapshot = decodeSnapshot(data);
4889
+ if (isSome(snapshot)) received(snapshot.value);
4890
+ });
4891
+ };
4892
+ const connect = async () => {
4893
+ const { attachment } = state;
4894
+ if (attachment === null || state.control !== null || state.connecting) return;
4895
+ state.connecting = true;
4896
+ const { promise: ended, resolve: end } = Promise.withResolvers();
4897
+ const outcome = await attempted(attachment, "/events", (control) => {
4898
+ control.addEventListener("close", () => {
4899
+ end(null);
4900
+ });
4901
+ if (state.attachment?.sandbox === attachment.sandbox) watch(control);
4902
+ else control.close();
4903
+ });
4904
+ state.connecting = false;
4905
+ if (outcome instanceof Error) {
4906
+ state.relay = null;
4907
+ if (isTerminal(outcome)) stop();
4908
+ wakeSyncs();
4909
+ } else if (state.control === outcome) {
4910
+ await ended;
4911
+ if (state.control !== outcome) return;
4912
+ state.control = null;
4913
+ state.relay = null;
4914
+ wakeSyncs();
4915
+ }
4916
+ if (state.attachment === null || state.retry !== null) return;
4917
+ const delay = RETRY_MS[Math.min(state.failures, RETRY_MS.length - 1)];
4918
+ state.failures += 1;
4919
+ state.retry = setTimeout(() => {
4920
+ state.retry = null;
4921
+ connect();
4922
+ }, delay);
4923
+ };
4924
+ const attach = (attachment) => {
4925
+ if (state.attachment?.sandbox !== attachment.sandbox) release();
4926
+ state.attachment = attachment;
4927
+ expireAt(Date.parse(attachment.expires_at));
4928
+ connect();
4929
+ };
4930
+ const synced = async () => {
4931
+ const tag = v7();
4932
+ const { promise, resolve } = Promise.withResolvers();
4933
+ const wake = () => {
4934
+ resolve(null);
4935
+ };
4936
+ const timer = setTimeout(wake, SYNC_MS);
4937
+ state.syncs.set(tag, wake);
4938
+ requestSync(tag);
4939
+ await promise;
4940
+ clearTimeout(timer);
4941
+ state.syncs.delete(tag);
4942
+ };
4943
+ const notices = () => [...state.notices.values()].flatMap((notice) => {
4944
+ if (notice.reported) return [];
4945
+ notice.reported = true;
4946
+ return [notice.entry];
4947
+ });
4948
+ const answer = async (connection) => {
4949
+ connection.on("error", noop);
4950
+ const request = decodeRequest(await requested(connection));
4951
+ if (isNone(request)) {
4952
+ connection.destroy();
4953
+ return;
4954
+ }
4955
+ attach(request.value.attachment);
4956
+ if (request.value.sync) await synced();
4957
+ connection.end(`${JSON.stringify({ unforwarded: notices() })}\n`);
4958
+ };
4959
+ listener.on("connection", (connection) => {
4960
+ answer(connection);
4961
+ });
4962
+ const serving = await servedAt(listener, socketPath);
4963
+ process.stdout.write(READY);
4964
+ if (serving) expireAt(Date.now() + UNATTACHED_MS);
4965
+ };
4966
+ const asked = async ({ line, socketPath }) => {
4967
+ const socket = net.connect(socketPath);
4968
+ const reply = text(socket);
4969
+ socket.end(line);
4970
+ return await reply;
4971
+ };
4972
+ const attachForwarder = async ({ attachment, entry, socketPath, sync }) => {
4973
+ const line = `${JSON.stringify({
4974
+ attachment,
4975
+ sync
4976
+ })}\n`;
4977
+ const reply = await servedOrSpawned({
4978
+ attempt: async () => await asked({
4979
+ line,
4980
+ socketPath
4981
+ }),
4982
+ entry,
4983
+ env: { [FORWARDER_ENV]: socketPath }
4984
+ });
4985
+ return getOrThrowWith(decodeReply(reply), () => /* @__PURE__ */ new Error("The port forwarder stopped before it answered.")).unforwarded;
4986
+ };
4987
+ export { exitCodeOf as $, isOptionValue as A, plainPrefix as B, enabledVariable as C, closest as D, productVariable as E, rerunArgv as F, remoteLine as G, theme as H, valuesOf as I, isDigit as J, remoteText as K, clearLine as L, parseFailure as M, parseLeaf as N, flagOf as O, readOptionToken as P, CliFailure as Q, ellipsis as R, writePrivateFile as S, modeOf as T, escapeUnprintable as U, spinnerFrame as V, remoteCell as W, isUpper as X, isDigits as Y, isWordCharacter as Z, formatMoney as _, RELAY_PORT as a, holdCluster as at, configDirectory as b, onPath as c, Clock as ct, BIN as d, statusOf as et, CLEARABLE as f, formatCount as g, counted as h, forwarderSocket as i, IDLE_WATCHER_ENV as it, lastValue as j, isOptionToken as k, setupDropIns as l, PROBLEM_REPORT_MAX as m, attachForwarder as n, Canceled as nt, RELAY_SOURCE as o, watchIdle as ot, CLI as p, consistsOf as q, forwardPorts as r, IDLE_MS as rt, v7 as s, noop as st, FORWARDER_ENV as t, usageFailure as tt, shimsOf as u, formatPercent as v, guidanceOn as w, withFileLock as x, version as y, glyph as z };