sandcovery 0.1.0 → 0.3.0

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,2459 @@
1
+ import { G as none, H as getOrUndefined, L as getSuccess, M as makeFormatterStandardSchemaV1, R as isFailure, U as isNone, W as map, _ as decodeUnknownOption, b as fromJsonString, c as Literals, h as Struct, m as String$1, q as isPropertyKey, v as decodeUnknownResult, x as is } from "./Schema-DiSfJzMf.mjs";
2
+ import { a as CredentialFields, i as ApiError, n as CalendarDay, r as EstimateRequest, t as Sandcovery } from "./src-YrynO3hz.mjs";
3
+ import { A as KeyId, D as MICRO_USD_PER_DOLLAR, F as SandboxId, N as Provider, O as ApiKeyId, _ as SandboxStatus, b as ProviderSort, c as SpendLimit, d as CreateSandboxRequest, f as Port, j as KeySecret, l as UpdateKeyRequest, n as SANDCOVERY_ORIGIN, o as KeyKind, r as CreateKeyRequest } from "./origin-CIA-1Jia.mjs";
4
+ import { A as CliFailure, D as isDigits, N as usageFailure, P as Canceled, T as consistsOf, g as ellipsis, i as version, k as isWordCharacter, l as lastValue, m as valuesOf, n as CLEARABLE, o as flagOf, x as escapeUnprintable } from "./spec-DfgmzDj-.mjs";
5
+ import path from "node:path";
6
+ import { setTimeout } from "node:timers/promises";
7
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/math/sumBy.mjs
8
+ /**
9
+ * Calculates the sum of an array of numbers when applying
10
+ * the `getValue` function to each element.
11
+ *
12
+ * If the array is empty, this function returns `0`.
13
+ *
14
+ * @template T - The type of elements in the array.
15
+ * @param items - An array to calculate the sum.
16
+ * @param getValue - A function that selects a numeric value from each element.
17
+ * It receives the element and its zero‑based index in the array.
18
+ * @returns The sum of all the numbers as determined by the `getValue` function.
19
+ *
20
+ * @example
21
+ * sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8
22
+ * sumBy([], () => 1); // Returns: 0
23
+ */
24
+ function sumBy(items, getValue) {
25
+ let result = 0;
26
+ for (let i = 0; i < items.length; i++) result += getValue(items[i], i);
27
+ return result;
28
+ }
29
+ // ../cli-core/src/credential.ts
30
+ const present = (value) => {
31
+ const trimmed = value?.trim();
32
+ return trimmed === "" ? void 0 : trimmed;
33
+ };
34
+ // src/cli/access.ts
35
+ const keysPage = () => `${SANDCOVERY_ORIGIN}/app/keys`;
36
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
37
+ "127.0.0.1",
38
+ "[::1]",
39
+ "localhost"
40
+ ]);
41
+ const isKeySecret = is(KeySecret);
42
+ const isSecureOrigin = (url) => url.protocol === "https:" || url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname);
43
+ const isBareOrigin = (url) => url.username === "" && url.password === "" && url.pathname === "/" && `${url.search}${url.hash}` === "";
44
+ const originFrom = (value) => {
45
+ const url = URL.parse(value);
46
+ return url !== null && isSecureOrigin(url) && isBareOrigin(url) ? url.origin : void 0;
47
+ };
48
+ const originOf = (context) => {
49
+ const option = present(lastValue(context.options, "base-url"));
50
+ const variable = present(process.env.SANDCOVERY_BASE_URL);
51
+ const chosen = option ?? variable;
52
+ if (chosen === void 0) return SANDCOVERY_ORIGIN;
53
+ const origin = originFrom(chosen);
54
+ if (origin !== void 0) return origin;
55
+ const field = option === void 0 ? "SANDCOVERY_BASE_URL" : "--base-url";
56
+ const message = `Can't use ${field}. It must be an https origin, such as ${SANDCOVERY_ORIGIN}, with no path, query, or login.`;
57
+ throw usageFailure({
58
+ help: context.path,
59
+ issues: [{
60
+ field,
61
+ message
62
+ }],
63
+ message
64
+ });
65
+ };
66
+ const chosenKey = (context) => {
67
+ const option = present(context.token);
68
+ const secret = option ?? present(process.env.SANDCOVERY_API_KEY);
69
+ const source = option === void 0 ? "SANDCOVERY_API_KEY" : "--token";
70
+ if (secret !== void 0 && !isKeySecret(secret)) {
71
+ const message = `Can't use the key in ${source}. A Sandcovery key starts with sand_ or sandm_ and has 43 more characters.`;
72
+ throw usageFailure({
73
+ help: context.path,
74
+ issues: [{
75
+ field: source,
76
+ message
77
+ }],
78
+ message
79
+ });
80
+ }
81
+ return secret === void 0 ? secret : {
82
+ secret,
83
+ source
84
+ };
85
+ };
86
+ const requiredKey = ({ action, context }) => {
87
+ const key = chosenKey(context);
88
+ if (key !== void 0) return key;
89
+ throw new CliFailure({
90
+ message: `Can't ${action} without a Sandcovery key. Set SANDCOVERY_API_KEY to an API key or management key.`,
91
+ reason: "login_required",
92
+ recovery: [{
93
+ instruction: "Create a key in the dashboard",
94
+ url: keysPage()
95
+ }],
96
+ userActionRequired: true
97
+ });
98
+ };
99
+ // ../format/src/display.ts
100
+ const LOCALE = "en-US";
101
+ const UTC = "UTC";
102
+ new Intl.DateTimeFormat(LOCALE, {
103
+ day: "numeric",
104
+ month: "short",
105
+ timeZone: UTC,
106
+ year: "numeric"
107
+ });
108
+ new Intl.DateTimeFormat(LOCALE, {
109
+ hour: "numeric",
110
+ minute: "2-digit",
111
+ timeZone: UTC,
112
+ timeZoneName: "short"
113
+ });
114
+ new Intl.DateTimeFormat(LOCALE, {
115
+ month: "long",
116
+ timeZone: UTC,
117
+ year: "numeric"
118
+ });
119
+ new Intl.DateTimeFormat(LOCALE, {
120
+ day: "numeric",
121
+ month: "short",
122
+ timeZone: UTC
123
+ });
124
+ const monthName = new Intl.DateTimeFormat(LOCALE, {
125
+ month: "long",
126
+ timeZone: UTC
127
+ });
128
+ Array.from({ length: 12 }, (_, month) => monthName.format(Date.UTC(2e3, month)));
129
+ new Intl.DateTimeFormat(LOCALE, {
130
+ day: "numeric",
131
+ hour: "numeric",
132
+ minute: "2-digit",
133
+ month: "short",
134
+ timeZone: "America/New_York",
135
+ timeZoneName: "short",
136
+ year: "numeric"
137
+ });
138
+ new Intl.DateTimeFormat(LOCALE, {
139
+ day: "2-digit",
140
+ hour: "2-digit",
141
+ hourCycle: "h23",
142
+ minute: "2-digit",
143
+ month: "2-digit",
144
+ timeZoneName: "short",
145
+ year: "numeric"
146
+ });
147
+ const moneyFormats = {
148
+ exact: new Intl.NumberFormat(LOCALE, {
149
+ currency: "USD",
150
+ maximumFractionDigits: 2,
151
+ minimumFractionDigits: 2,
152
+ style: "currency"
153
+ }),
154
+ signed: new Intl.NumberFormat(LOCALE, {
155
+ currency: "USD",
156
+ maximumFractionDigits: 2,
157
+ minimumFractionDigits: 2,
158
+ signDisplay: "exceptZero",
159
+ style: "currency"
160
+ }),
161
+ subcent: new Intl.NumberFormat(LOCALE, {
162
+ currency: "USD",
163
+ maximumSignificantDigits: 3,
164
+ style: "currency"
165
+ }),
166
+ trimmed: new Intl.NumberFormat(LOCALE, {
167
+ currency: "USD",
168
+ style: "currency",
169
+ trailingZeroDisplay: "stripIfInteger"
170
+ }),
171
+ whole: new Intl.NumberFormat(LOCALE, {
172
+ currency: "USD",
173
+ maximumFractionDigits: 0,
174
+ style: "currency"
175
+ })
176
+ };
177
+ const formatMoney = ({ cents, style }) => moneyFormats[style].format(cents / 100);
178
+ new Intl.NumberFormat(LOCALE, {
179
+ maximumFractionDigits: 1,
180
+ notation: "compact"
181
+ }), new Intl.NumberFormat(LOCALE, { maximumFractionDigits: 0 });
182
+ new Intl.PluralRules(LOCALE);
183
+ const unitFormat = ({ unit }) => new Intl.NumberFormat(LOCALE, {
184
+ style: "unit",
185
+ unit,
186
+ unitDisplay: "long"
187
+ });
188
+ unitFormat({ unit: "hour" }), unitFormat({ unit: "minute" }), unitFormat({ unit: "month" }), unitFormat({ unit: "second" });
189
+ const percentFormats = {
190
+ rate: new Intl.NumberFormat(LOCALE, {
191
+ maximumFractionDigits: 2,
192
+ minimumFractionDigits: 2,
193
+ style: "percent"
194
+ }),
195
+ whole: new Intl.NumberFormat(LOCALE, {
196
+ maximumFractionDigits: 0,
197
+ style: "percent"
198
+ })
199
+ };
200
+ const formatPercent = ({ rate, style }) => percentFormats[style].format(rate);
201
+ // src/cli/format.ts
202
+ const MICROS_PER_CENT = 1e4;
203
+ const SECONDS_PER_MINUTE = 60;
204
+ const SECONDS_PER_HOUR$1 = 3600;
205
+ const moneyText = (micros) => formatMoney({
206
+ cents: micros / MICROS_PER_CENT,
207
+ style: "exact"
208
+ });
209
+ const rateText = (micros) => formatMoney({
210
+ cents: micros / MICROS_PER_CENT,
211
+ style: "subcent"
212
+ });
213
+ const shareText = (share) => share === null ? "-" : formatPercent({
214
+ rate: share,
215
+ style: "rate"
216
+ });
217
+ const timeText = (iso) => iso === null ? "-" : `${iso.slice(0, 16).replace("T", " ")} UTC`;
218
+ const durationText = (seconds) => {
219
+ if (seconds < 120) return `${String(seconds)}s`;
220
+ if (seconds < SECONDS_PER_HOUR$1 * 2) return `${String(Math.round(seconds / SECONDS_PER_MINUTE))}m`;
221
+ return `${String(Math.round(seconds / SECONDS_PER_HOUR$1 * 10) / 10)}h`;
222
+ };
223
+ const orDash = (value) => value ?? "-";
224
+ const countOrDash = (value) => value === null ? "-" : String(value);
225
+ const put = (target, key, value) => {
226
+ if (value !== void 0) target[key] = value;
227
+ };
228
+ // src/cli/failures.ts
229
+ const isApiError = is(ApiError);
230
+ const UNSENT_CODES = /* @__PURE__ */ new Set([
231
+ "CERT_HAS_EXPIRED",
232
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
233
+ "EAI_AGAIN",
234
+ "ECONNREFUSED",
235
+ "EHOSTUNREACH",
236
+ "ENETUNREACH",
237
+ "ENOTFOUND",
238
+ "ERR_TLS_CERT_ALTNAME_INVALID",
239
+ "SELF_SIGNED_CERT_IN_CHAIN",
240
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
241
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
242
+ ]);
243
+ const UPDATE_RECOVERY = { instruction: "Update the CLI with npm install --global sandcovery@latest, then run the command again" };
244
+ const HTTP_REDIRECT_MIN = 300;
245
+ const HTTP_CLIENT_ERROR_MIN = 400;
246
+ const HTTP_TOO_MANY_REQUESTS = 429;
247
+ const HTTP_SERVER_ERROR_MIN = 500;
248
+ const remoteRow = (label, value) => ({
249
+ label,
250
+ value
251
+ });
252
+ const decodeTransportError = decodeUnknownOption(Struct({ cause: Struct({ code: String$1 }) }));
253
+ const decodeEnvelope = decodeUnknownOption(Struct({ cause: Struct({ body: fromJsonString(Struct({
254
+ error: String$1,
255
+ message: String$1
256
+ })) }) }));
257
+ const envelopeRows = (envelope) => envelope === void 0 ? [] : [{
258
+ label: "Error Code",
259
+ value: envelope.error
260
+ }, remoteRow("Sandcovery", envelope.message)];
261
+ const envelopeData = (envelope) => envelope === void 0 ? void 0 : { error: envelope.error };
262
+ const answeredText = ({ envelope, status }) => {
263
+ if (envelope === void 0) return `Sandcovery answered ${String(status)}.`;
264
+ return consistsOf(envelope.error, isWordCharacter) ? `Sandcovery answered ${String(status)} with error ${envelope.error}.` : `Sandcovery answered ${String(status)} with an error code this CLI doesn't know.`;
265
+ };
266
+ const inspectRecovery = (operation) => operation.inspect === void 0 ? [] : [{
267
+ instruction: "Check what happened",
268
+ next: { argv: operation.inspect }
269
+ }];
270
+ const unknownOutcome = ({ cause, envelope, operation }) => new CliFailure({
271
+ data: envelopeData(envelope),
272
+ detail: envelopeRows(envelope),
273
+ message: `Can't confirm whether the request to ${operation.action} finished. ${cause}`,
274
+ notes: ["Sandcovery may have applied it, so check before running the command again."],
275
+ reason: "unknown_outcome",
276
+ recovery: inspectRecovery(operation),
277
+ remoteMessage: envelope?.message
278
+ });
279
+ const retriesRow = (attempts) => attempts > 1 ? [{
280
+ label: "Retries",
281
+ value: String(attempts - 1)
282
+ }] : [];
283
+ const apiFailure = ({ error, key, operation }) => {
284
+ const { action } = operation;
285
+ const remote = [remoteRow("Sandcovery", error.message)];
286
+ switch (error.error) {
287
+ case "unauthorized": return new CliFailure({
288
+ detail: remote,
289
+ message: key === void 0 ? `Can't ${action} without a Sandcovery key. Set SANDCOVERY_API_KEY to an API key or management key.` : `Sandcovery refused the key in ${key.source}. It may be revoked, expired, or mistyped.`,
290
+ reason: "login_required",
291
+ recovery: [{
292
+ instruction: "Create a key in the dashboard",
293
+ url: keysPage()
294
+ }],
295
+ remoteMessage: error.message,
296
+ userActionRequired: true
297
+ });
298
+ case "forbidden": return new CliFailure({
299
+ detail: remote,
300
+ message: operation.management === true ? `Only a management key can ${action}. This key is an API key.` : `This key can't ${action}. Use an API key, since a management key can't reach sandboxes.`,
301
+ reason: "permission_denied",
302
+ recovery: [{
303
+ instruction: "Create the right kind of key in the dashboard",
304
+ url: keysPage()
305
+ }],
306
+ remoteMessage: error.message
307
+ });
308
+ case "not_found": return new CliFailure({
309
+ detail: remote,
310
+ message: `Couldn't find ${operation.target ?? "it"}.`,
311
+ reason: "not_found",
312
+ remoteMessage: error.message
313
+ });
314
+ case "invalid_request": return new CliFailure({
315
+ detail: remote,
316
+ message: `Sandcovery refused the request to ${action} as invalid.`,
317
+ reason: "invalid_arguments",
318
+ remoteMessage: error.message
319
+ });
320
+ case "conflict": return new CliFailure({
321
+ detail: remote,
322
+ message: `Can't ${action}. It conflicts with the current state.`,
323
+ reason: "conflict",
324
+ remoteMessage: error.message
325
+ });
326
+ case "concurrency_limit_reached": return new CliFailure({
327
+ data: { concurrency_cap: error.concurrency_cap },
328
+ detail: remote,
329
+ message: `Can't ${action}. This key already runs its limit of ${String(error.concurrency_cap)} sandboxes at once.`,
330
+ reason: "concurrency_limit_reached",
331
+ recovery: [{
332
+ instruction: "See the running sandboxes",
333
+ next: { argv: [
334
+ "sandboxes",
335
+ "list",
336
+ "--status",
337
+ "running"
338
+ ] }
339
+ }],
340
+ remoteMessage: error.message
341
+ });
342
+ case "spend_limit_reached": return new CliFailure({
343
+ data: {
344
+ limit_micro_usd: error.limit_micro_usd,
345
+ resets_at: error.resets_at,
346
+ spent_micro_usd: error.spent_micro_usd
347
+ },
348
+ detail: [
349
+ {
350
+ label: "Spent",
351
+ value: moneyText(error.spent_micro_usd)
352
+ },
353
+ {
354
+ label: "Resets",
355
+ value: timeText(error.resets_at)
356
+ },
357
+ ...remote
358
+ ],
359
+ message: `Can't ${action}. This key reached its spend limit of ${moneyText(error.limit_micro_usd)}.`,
360
+ reason: "spend_limit_reached",
361
+ remoteMessage: error.message
362
+ });
363
+ case "no_provider_available": return new CliFailure({
364
+ data: { attempts: error.attempts },
365
+ detail: [...remote, ...error.attempts.map((attempt) => remoteRow(attempt.provider, attempt.failure === null ? "no failure given" : `${attempt.failure.reason}: ${attempt.failure.message}`))],
366
+ message: `Couldn't ${action}. Every candidate provider failed.`,
367
+ reason: "no_provider_available",
368
+ remoteMessage: error.message,
369
+ retryable: false
370
+ });
371
+ case "provider_error": return new CliFailure({
372
+ data: { provider: error.provider },
373
+ detail: [{
374
+ label: "Provider",
375
+ value: error.provider
376
+ }, ...remote],
377
+ message: `Failed to ${action}. ${error.provider} answered with an error.`,
378
+ reason: "provider_error",
379
+ remoteMessage: error.message
380
+ });
381
+ case "unsupported": return new CliFailure({
382
+ data: {
383
+ options: error.options,
384
+ provider: error.provider
385
+ },
386
+ detail: error.options.length > 0 ? [{
387
+ label: "Sizes That Would Run",
388
+ value: error.options.join(", ")
389
+ }, ...remote] : remote,
390
+ message: error.options.length > 0 ? `Can't ${action}. No candidate provider runs that size.` : `Can't ${action}. No candidate provider supports the request.`,
391
+ reason: "unsupported",
392
+ remoteMessage: error.message
393
+ });
394
+ default: return new CliFailure({
395
+ detail: remote,
396
+ message: `Failed to ${action}. Sandcovery answered with an error this CLI doesn't know.`,
397
+ reason: "api_error",
398
+ recovery: [UPDATE_RECOVERY]
399
+ });
400
+ }
401
+ };
402
+ const statusFailure = ({ attempts, envelope, host, operation, status }) => {
403
+ const rows = [
404
+ {
405
+ label: "Status",
406
+ value: String(status)
407
+ },
408
+ ...envelopeRows(envelope),
409
+ ...retriesRow(attempts)
410
+ ];
411
+ const remote = {
412
+ data: envelopeData(envelope),
413
+ detail: rows,
414
+ remoteMessage: envelope?.message
415
+ };
416
+ if (status >= HTTP_REDIRECT_MIN && status < HTTP_CLIENT_ERROR_MIN) return {
417
+ failure: new CliFailure({
418
+ ...remote,
419
+ message: `Couldn't ${operation.action}. ${host} answered with a redirect, which the CLI never follows.`,
420
+ notes: ["Check that --base-url or SANDCOVERY_BASE_URL names the Sandcovery origin itself."],
421
+ reason: "redirected"
422
+ }),
423
+ retry: false
424
+ };
425
+ if (status === HTTP_TOO_MANY_REQUESTS) return {
426
+ failure: new CliFailure({
427
+ ...remote,
428
+ message: "Too many requests to the Sandcovery API. Try again in a minute.",
429
+ reason: "rate_limited",
430
+ retryable: true
431
+ }),
432
+ retry: true
433
+ };
434
+ if (status >= HTTP_SERVER_ERROR_MIN && !operation.idempotent) return {
435
+ failure: unknownOutcome({
436
+ cause: answeredText({
437
+ envelope,
438
+ status
439
+ }),
440
+ envelope,
441
+ operation
442
+ }),
443
+ retry: false
444
+ };
445
+ return {
446
+ failure: new CliFailure({
447
+ ...remote,
448
+ message: `Failed to ${operation.action}. ${answeredText({
449
+ envelope,
450
+ status
451
+ })}`,
452
+ reason: "api_error",
453
+ recovery: envelope === void 0 ? void 0 : [UPDATE_RECOVERY],
454
+ retryable: operation.idempotent && status >= HTTP_SERVER_ERROR_MIN
455
+ }),
456
+ retry: status >= HTTP_SERVER_ERROR_MIN
457
+ };
458
+ };
459
+ const transportFailure = ({ attempts, error, host, operation, timedOut, timeoutSeconds }) => {
460
+ const code = getOrUndefined(map(decodeTransportError(error), (found) => found.cause.code));
461
+ const coded = code === void 0 ? "" : ` with ${code}`;
462
+ const unsent = !timedOut && UNSENT_CODES.has(code ?? "");
463
+ if (!operation.idempotent && !unsent) return {
464
+ failure: unknownOutcome({
465
+ cause: timedOut ? `${host} didn't answer within ${String(timeoutSeconds)} seconds.` : `The connection to ${host} failed${coded}.`,
466
+ operation
467
+ }),
468
+ retry: false
469
+ };
470
+ return {
471
+ failure: new CliFailure({
472
+ detail: retriesRow(attempts),
473
+ message: timedOut ? `Couldn't reach ${host}. It didn't answer within ${String(timeoutSeconds)} seconds.` : `Couldn't reach ${host}. The connection failed${coded}.`,
474
+ notes: ["The CLI honors HTTPS_PROXY, NO_PROXY, and NODE_EXTRA_CA_CERTS."],
475
+ reason: "network_error",
476
+ retryable: true
477
+ }),
478
+ retry: operation.idempotent
479
+ };
480
+ };
481
+ const classify = (attempted) => {
482
+ const { error, key, operation, status } = attempted;
483
+ if (isApiError(error)) return {
484
+ failure: apiFailure({
485
+ error,
486
+ key,
487
+ operation
488
+ }),
489
+ retry: false
490
+ };
491
+ if (status !== void 0 && (status < 200 || status >= HTTP_REDIRECT_MIN)) return statusFailure({
492
+ ...attempted,
493
+ envelope: getOrUndefined(map(decodeEnvelope(error), (found) => found.cause.body)),
494
+ status
495
+ });
496
+ if (status === void 0) return transportFailure(attempted);
497
+ return {
498
+ failure: operation.idempotent ? new CliFailure({
499
+ message: `Failed to ${operation.action}. Sandcovery answered in a form this CLI can't read.`,
500
+ reason: "api_error",
501
+ recovery: [UPDATE_RECOVERY]
502
+ }) : unknownOutcome({
503
+ cause: "Sandcovery's answer can't be read by this CLI.",
504
+ operation
505
+ }),
506
+ retry: false
507
+ };
508
+ };
509
+ // src/cli/api.ts
510
+ const ATTEMPTS = 3;
511
+ const REQUEST_TIMEOUT_SECONDS = 60;
512
+ const RETRY_AFTER_CAP_SECONDS = 10;
513
+ const BACKOFF_MS = [500, 1500];
514
+ const MS_PER_SECOND = 1e3;
515
+ const retryAfterOf = (value) => {
516
+ const seconds = value === null ? NaN : Number(value);
517
+ return Number.isFinite(seconds) && seconds >= 0 ? Math.min(seconds, RETRY_AFTER_CAP_SECONDS) : void 0;
518
+ };
519
+ const userAgent = `sandcovery-cli/${version} node/${process.versions.node} ${process.platform}-${process.arch}`;
520
+ const urlOf = (input) => new URL(input instanceof Request ? input.url : input);
521
+ const tracedFetch = ({ answer, context }) => async (input, init) => {
522
+ const headers = new Headers(init?.headers);
523
+ headers.set("user-agent", userAgent);
524
+ context.progress.sent = true;
525
+ context.debug(`${init?.method ?? "GET"} ${urlOf(input).pathname}`);
526
+ const response = await globalThis.fetch(input, {
527
+ ...init,
528
+ headers,
529
+ redirect: "manual"
530
+ });
531
+ answer.status = response.status;
532
+ answer.retryAfter = retryAfterOf(response.headers.get("retry-after"));
533
+ context.debug(`answered ${String(response.status)}`);
534
+ return response;
535
+ };
536
+ const attempt = async ({ call, context, key, number, origin }) => {
537
+ const answer = {};
538
+ const limit = call.timeoutSeconds === void 0 ? REQUEST_TIMEOUT_SECONDS : call.timeoutSeconds;
539
+ const timeout = limit === null ? void 0 : AbortSignal.timeout(limit * MS_PER_SECOND);
540
+ const signal = timeout === void 0 ? context.signal : AbortSignal.any([context.signal, timeout]);
541
+ const client = new Sandcovery({
542
+ apiKey: key?.secret,
543
+ baseUrl: origin,
544
+ fetch: tracedFetch({
545
+ answer,
546
+ context
547
+ })
548
+ });
549
+ try {
550
+ return await call.run(client, signal);
551
+ } catch (error) {
552
+ if (context.signal.aborted) throw error;
553
+ const { failure, retry } = classify({
554
+ attempts: number,
555
+ error,
556
+ host: new URL(origin).host,
557
+ key,
558
+ operation: call,
559
+ status: answer.status,
560
+ timedOut: timeout?.aborted === true,
561
+ timeoutSeconds: limit ?? void 0
562
+ });
563
+ if (!retry || !call.idempotent || number >= ATTEMPTS) throw failure;
564
+ context.debug(`retrying after ${failure.reason}`);
565
+ context.io.note([`Retrying automatically${ellipsis(context.mode.stderr)}`]);
566
+ await setTimeout(answer.retryAfter === void 0 ? BACKOFF_MS[number - 1] ?? 0 : answer.retryAfter * MS_PER_SECOND, void 0, { signal: context.signal });
567
+ return await attempt({
568
+ call,
569
+ context,
570
+ key,
571
+ number: number + 1,
572
+ origin
573
+ });
574
+ }
575
+ };
576
+ const callApi = async ({ call, context }) => {
577
+ const origin = originOf(context);
578
+ const key = call.key === "required" ? requiredKey({
579
+ action: call.action,
580
+ context
581
+ }) : chosenKey(context);
582
+ context.progress.inspect = call.inspect ?? null;
583
+ context.progress.mutation = !call.idempotent || call.inspect !== void 0;
584
+ return await attempt({
585
+ call,
586
+ context,
587
+ key,
588
+ number: 1,
589
+ origin
590
+ });
591
+ };
592
+ // src/cli/inputs.ts
593
+ const formatIssues = makeFormatterStandardSchemaV1();
594
+ const REQUEST_FIELD = "request";
595
+ const segmentOf = (segment) => String(isPropertyKey(segment) ? segment : segment.key);
596
+ const fieldOf = ({ flags, path }) => {
597
+ const keys = (path ?? []).map(segmentOf);
598
+ const [first] = keys;
599
+ if (first === void 0) return REQUEST_FIELD;
600
+ return flags[keys.join(".")] ?? flags[first] ?? first;
601
+ };
602
+ const inputsOf = ({ context, issues }) => {
603
+ const lastOf = (name) => lastValue(context.options, name);
604
+ const decoded = ({ field, message, schema, value }) => {
605
+ const found = value === void 0 ? none() : decodeUnknownOption(schema)(value);
606
+ if (value !== void 0 && isNone(found)) issues.push({
607
+ field,
608
+ message
609
+ });
610
+ return getOrUndefined(found);
611
+ };
612
+ return {
613
+ argument: (name) => context.arguments[name]?.[0] ?? "",
614
+ checked: ({ flags, schema, value }) => {
615
+ const result = decodeUnknownResult(schema, { errors: "all" })(value);
616
+ if (isFailure(result)) {
617
+ const named = /* @__PURE__ */ new Map();
618
+ for (const found of formatIssues(result.failure.issue).issues) {
619
+ const field = fieldOf({
620
+ flags,
621
+ path: found.path
622
+ });
623
+ const label = field === REQUEST_FIELD ? "The request" : field;
624
+ if (!named.has(field)) named.set(field, {
625
+ field,
626
+ message: `${label}: ${found.message}.`
627
+ });
628
+ }
629
+ issues.push(...named.values());
630
+ }
631
+ return getOrUndefined(getSuccess(result));
632
+ },
633
+ decoded,
634
+ flag: (name) => flagOf(context.options, name),
635
+ integer: (name, { maximum, minimum }) => {
636
+ const value = lastOf(name);
637
+ const number = value !== void 0 && isDigits(value) ? Number(value) : NaN;
638
+ const top = maximum ?? Number.MAX_SAFE_INTEGER;
639
+ const fits = Number.isSafeInteger(number) && number >= minimum && number <= top;
640
+ if (value !== void 0 && !fits) issues.push({
641
+ field: `--${name}`,
642
+ message: maximum === void 0 ? `--${name} must be a whole number of at least ${String(minimum)}.` : `--${name} must be a whole number from ${String(minimum)} to ${String(maximum)}.`
643
+ });
644
+ return fits ? number : void 0;
645
+ },
646
+ issue: (issue) => {
647
+ issues.push(issue);
648
+ },
649
+ oneOf: (name, values) => decoded({
650
+ field: `--${name}`,
651
+ message: `--${name} must be one of ${values.join(", ")}.`,
652
+ schema: Literals(values),
653
+ value: lastOf(name)
654
+ }),
655
+ pairs: (name) => {
656
+ const split = valuesOf(context.options, name).map((pair) => ({
657
+ at: pair.indexOf("="),
658
+ pair
659
+ }));
660
+ const malformed = split.some(({ at }) => at <= 0);
661
+ if (malformed) issues.push({
662
+ field: `--${name}`,
663
+ message: `Each --${name} must be NAME=VALUE, with a name before the =.`
664
+ });
665
+ return split.length === 0 || malformed ? void 0 : Object.fromEntries(split.map(({ at, pair }) => [pair.slice(0, at), pair.slice(at + 1)]));
666
+ },
667
+ text: lastOf,
668
+ texts: (name) => valuesOf(context.options, name)
669
+ };
670
+ };
671
+ const readInputs = ({ build, context, verb }) => {
672
+ const issues = [];
673
+ const built = build(inputsOf({
674
+ context,
675
+ issues
676
+ }));
677
+ const [first] = issues;
678
+ if (first === void 0 && built !== void 0) return built;
679
+ throw usageFailure({
680
+ help: context.path,
681
+ issues,
682
+ message: issues.length > 1 ? `Can't ${verb}. ${String(issues.length)} inputs are invalid.` : `Can't ${verb}. ${first?.message ?? "The input is invalid."}`
683
+ });
684
+ };
685
+ // src/cli/commands/shared.ts
686
+ const SPEC_FLAGS = {
687
+ env: "--env",
688
+ idle_timeout_seconds: "--idle-timeout",
689
+ image: "--image",
690
+ ports: "--port",
691
+ provider: "--provider",
692
+ "provider.allow_fallbacks": "--fallbacks",
693
+ "provider.sort": "--sort",
694
+ region: "--region",
695
+ size: "--size",
696
+ snapshot_id: "--snapshot",
697
+ ttl_seconds: "--ttl"
698
+ };
699
+ const wholeNumber = (text) => isDigits(text) ? Number(text) : NaN;
700
+ const numberOf = (text) => text === void 0 ? text : wholeNumber(text);
701
+ const specInput = (inputs) => {
702
+ const providers = inputs.texts("provider");
703
+ const ports = inputs.texts("port");
704
+ const preferences = {};
705
+ const spec = {};
706
+ if (providers.length > 0) {
707
+ preferences.only = providers;
708
+ preferences.order = providers;
709
+ }
710
+ put(preferences, "allow_fallbacks", inputs.flag("fallbacks"));
711
+ put(preferences, "sort", inputs.oneOf("sort", ProviderSort.literals));
712
+ if (Object.keys(preferences).length > 0) spec.provider = preferences;
713
+ if (ports.length > 0) spec.ports = ports.map(wholeNumber);
714
+ put(spec, "env", inputs.pairs("env"));
715
+ put(spec, "idle_timeout_seconds", numberOf(inputs.text("idle-timeout")));
716
+ put(spec, "image", inputs.text("image"));
717
+ put(spec, "region", inputs.text("region"));
718
+ put(spec, "size", inputs.text("size"));
719
+ put(spec, "ttl_seconds", numberOf(inputs.text("ttl")));
720
+ return spec;
721
+ };
722
+ const sandboxIdOf = (inputs) => inputs.decoded({
723
+ field: "<sandbox>",
724
+ message: "The sandbox ID must be sbx_ followed by a UUID, as sandcovery sandboxes list prints it.",
725
+ schema: SandboxId,
726
+ value: inputs.argument("sandbox")
727
+ });
728
+ const providerOf = (inputs) => inputs.decoded({
729
+ field: "<provider>",
730
+ message: "The provider must be a name such as e2b, as sandcovery providers list prints it.",
731
+ schema: Provider,
732
+ value: inputs.argument("provider")
733
+ });
734
+ const sizeText = (sandbox) => sandbox.size ?? `${String(sandbox.vcpu)} vCPU, ${String(sandbox.memory_mib)} MiB`;
735
+ const sandboxRows = (sandbox) => [
736
+ {
737
+ label: "ID",
738
+ value: sandbox.id
739
+ },
740
+ {
741
+ label: "Status",
742
+ value: sandbox.status
743
+ },
744
+ {
745
+ label: "Provider",
746
+ value: orDash(sandbox.provider)
747
+ },
748
+ {
749
+ label: "Size",
750
+ value: sizeText(sandbox)
751
+ },
752
+ {
753
+ label: "Region",
754
+ value: orDash(sandbox.region)
755
+ },
756
+ {
757
+ label: "Expires",
758
+ value: timeText(sandbox.expires_at)
759
+ },
760
+ {
761
+ label: "Cost So Far",
762
+ value: moneyText(sandbox.cost.estimated_micro_usd)
763
+ },
764
+ {
765
+ label: "Hourly",
766
+ value: rateText(sandbox.cost.hourly_micro_usd)
767
+ },
768
+ ...sandbox.ended_at === null ? [] : [{
769
+ label: "Ended",
770
+ value: `${timeText(sandbox.ended_at)}, ${orDash(sandbox.end_reason)}`
771
+ }]
772
+ ];
773
+ const sandboxTableRow = (sandbox) => [
774
+ sandbox.id,
775
+ sandbox.status,
776
+ orDash(sandbox.provider),
777
+ sizeText(sandbox),
778
+ timeText(sandbox.expires_at)
779
+ ];
780
+ const SANDBOX_COLUMNS = [
781
+ { header: "ID" },
782
+ { header: "Status" },
783
+ { header: "Provider" },
784
+ { header: "Size" },
785
+ { header: "Expires" }
786
+ ];
787
+ const attemptRows = (attempts) => attempts.map((attempt) => [
788
+ attempt.provider,
789
+ attempt.failure === null ? "created" : attempt.failure.reason,
790
+ durationText(Math.round(attempt.duration_ms / 1e3))
791
+ ]);
792
+ const ATTEMPT_COLUMNS = [
793
+ { header: "Provider" },
794
+ { header: "Outcome" },
795
+ { header: "Took" }
796
+ ];
797
+ const nextPage = ({ argv, cursor }) => cursor === null ? [] : [{
798
+ argv: [
799
+ ...argv,
800
+ "--next",
801
+ cursor
802
+ ],
803
+ benefit: "List the next page"
804
+ }];
805
+ // src/cli/commands/activity.ts
806
+ const activityList = async (context) => {
807
+ const query = readInputs({
808
+ build: (inputs) => ({
809
+ cursor: inputs.text("next"),
810
+ limit: inputs.integer("limit", {
811
+ maximum: 100,
812
+ minimum: 1
813
+ })
814
+ }),
815
+ context,
816
+ verb: "list activity"
817
+ });
818
+ const page = await callApi({
819
+ call: {
820
+ action: "list activity",
821
+ idempotent: true,
822
+ key: "required",
823
+ run: async (client, signal) => await client.activity.list(query, { signal })
824
+ },
825
+ context
826
+ });
827
+ context.io.table({
828
+ empty: "No activity.",
829
+ table: {
830
+ columns: [
831
+ { header: "At" },
832
+ { header: "Action" },
833
+ { header: "Outcome" },
834
+ { header: "Sandbox" },
835
+ { header: "Provider" }
836
+ ],
837
+ rows: page.data.map((event) => [
838
+ timeText(event.at),
839
+ event.action,
840
+ event.outcome,
841
+ orDash(event.sandbox_id),
842
+ orDash(event.provider)
843
+ ])
844
+ }
845
+ });
846
+ return {
847
+ document: {
848
+ activity: page.data,
849
+ next_cursor: page.next_cursor
850
+ },
851
+ next: nextPage({
852
+ argv: ["activity", "list"],
853
+ cursor: page.next_cursor
854
+ })
855
+ };
856
+ };
857
+ // src/cli/commands/billing.ts
858
+ const BILLING_TARGET = "billing, which opens once Sandcovery sells credits";
859
+ const AMOUNT_FLAG = "--amount";
860
+ const billingInspect = async (context) => {
861
+ const billing = await callApi({
862
+ call: {
863
+ action: "show billing",
864
+ idempotent: true,
865
+ key: "required",
866
+ management: true,
867
+ run: async (client, signal) => await client.billing.get({ signal }),
868
+ target: BILLING_TARGET
869
+ },
870
+ context
871
+ });
872
+ const price = billing.pro_price;
873
+ context.io.details([
874
+ {
875
+ label: "Plan",
876
+ value: billing.plan === "pro" ? "Pro" : "Free"
877
+ },
878
+ {
879
+ label: "Credits",
880
+ value: moneyText(billing.credit_balance_micro_usd)
881
+ },
882
+ {
883
+ label: "Pro Price",
884
+ value: price === null ? "Not on sale" : `${moneyText(price.micro_usd)} a ${price.interval}`
885
+ }
886
+ ]);
887
+ return {
888
+ document: { billing },
889
+ next: [{
890
+ argv: [
891
+ "billing",
892
+ "buy-credits",
893
+ "--amount",
894
+ "<USD>"
895
+ ],
896
+ benefit: "Add credits through Stripe Checkout",
897
+ optional: true
898
+ }]
899
+ };
900
+ };
901
+ const billingBuyCredits = async (context) => {
902
+ const dollars = readInputs({
903
+ build: (inputs) => {
904
+ if (inputs.text("amount") === void 0) inputs.issue({
905
+ field: AMOUNT_FLAG,
906
+ message: `Can't buy credits without ${AMOUNT_FLAG}, in whole US dollars.`
907
+ });
908
+ return inputs.integer("amount", {
909
+ maximum: 1e3,
910
+ minimum: 25
911
+ }) ?? 0;
912
+ },
913
+ context,
914
+ verb: "buy credits"
915
+ });
916
+ const checkout = await callApi({
917
+ call: {
918
+ action: "start a credit purchase",
919
+ idempotent: false,
920
+ key: "required",
921
+ management: true,
922
+ run: async (client, signal) => await client.billing.buyCredits({ amount_micro_usd: dollars * MICRO_USD_PER_DOLLAR }, { signal }),
923
+ target: BILLING_TARGET
924
+ },
925
+ context
926
+ });
927
+ context.io.details([{
928
+ label: "Checkout",
929
+ value: checkout.url
930
+ }]);
931
+ return { document: { checkout } };
932
+ };
933
+ // ../cli-core/src/consent.ts
934
+ const SEVERE_ATTEMPTS = 3;
935
+ const typedName = async ({ attempts, io, prompter, request }) => {
936
+ const name = request.name ?? "";
937
+ if (attempts === 0) throw new Canceled({
938
+ remote: "none",
939
+ signal: "SIGINT"
940
+ });
941
+ if (await prompter.text(`To confirm, type the ${request.noun} name "${name}":`) === name) return;
942
+ io.note([`Type only the ${request.noun} name "${name}".`]);
943
+ await typedName({
944
+ attempts: attempts - 1,
945
+ io,
946
+ prompter,
947
+ request
948
+ });
949
+ };
950
+ const confirmConsent = async ({ action, argv, io, mode, prompter, request, tier, yes }) => {
951
+ if (tier === void 0 || yes) return;
952
+ const closing = request.irreversible ? ["This cannot be undone."] : [];
953
+ if (!mode.interactive || prompter === void 0) throw new CliFailure({
954
+ data: {
955
+ effects: [...request.effects, ...closing],
956
+ target: Object.fromEntries(request.target.map(({ label, value }) => [label, value]))
957
+ },
958
+ message: `Can't ${action} without --yes in non-interactive mode.`,
959
+ reason: "confirmation_required",
960
+ recovery: [{
961
+ instruction: "After a person approves, run",
962
+ next: {
963
+ argv: [...argv, "--yes"],
964
+ when: `Only after a human approves: ${request.consequence}`
965
+ }
966
+ }],
967
+ userActionRequired: true
968
+ });
969
+ io.context(request.target);
970
+ io.note([...request.effects, ...closing]);
971
+ if (tier === "severe") {
972
+ await typedName({
973
+ attempts: SEVERE_ATTEMPTS,
974
+ io,
975
+ prompter,
976
+ request
977
+ });
978
+ return;
979
+ }
980
+ if (!await prompter.confirm(request.question)) throw new Canceled({
981
+ remote: "none",
982
+ signal: "SIGINT"
983
+ });
984
+ };
985
+ // src/cli/commands/credentials.ts
986
+ const DELETE_ACTION = "delete the credential";
987
+ const decodeFields = decodeUnknownOption(fromJsonString(CredentialFields));
988
+ const FROM = "--from";
989
+ const credentialTarget = (provider) => `the ${provider} credential`;
990
+ const SECONDS_PER_HOUR = 3600;
991
+ const vcpuHours = (vcpuSeconds) => `${String(Math.floor(vcpuSeconds / SECONDS_PER_HOUR))} vCPU-hours`;
992
+ const credentialsOffer = async (context) => {
993
+ const offer = await callApi({
994
+ call: {
995
+ action: "show the offer",
996
+ idempotent: true,
997
+ key: "required",
998
+ management: true,
999
+ run: async (client, signal) => await client.credentials.offer({ signal }),
1000
+ target: "a running offer of free vCPU-hours"
1001
+ },
1002
+ context
1003
+ });
1004
+ context.io.details([
1005
+ {
1006
+ label: "Provider",
1007
+ value: offer.provider
1008
+ },
1009
+ {
1010
+ label: "Keys Counted",
1011
+ value: `${String(Math.min(offer.keys_counted, offer.keys_needed))}/${String(offer.keys_needed)}`
1012
+ },
1013
+ {
1014
+ label: "Free Left",
1015
+ value: `${vcpuHours(offer.remaining_vcpu_seconds)} of ${vcpuHours(offer.cap_vcpu_seconds)}`
1016
+ },
1017
+ {
1018
+ label: "Each Key Earns",
1019
+ value: vcpuHours(offer.vcpu_seconds_per_key)
1020
+ },
1021
+ {
1022
+ label: "Month Used Up",
1023
+ value: offer.month_used_up ? "Yes" : "No"
1024
+ }
1025
+ ]);
1026
+ return { document: { offer } };
1027
+ };
1028
+ const credentialsList = async (context) => {
1029
+ const listed = await callApi({
1030
+ call: {
1031
+ action: "list provider credentials",
1032
+ idempotent: true,
1033
+ key: "required",
1034
+ management: true,
1035
+ run: async (client, signal) => await client.credentials.list({ signal })
1036
+ },
1037
+ context
1038
+ });
1039
+ context.io.table({
1040
+ empty: "No provider credentials. Sandboxes run on Sandcovery's provider accounts.",
1041
+ table: {
1042
+ columns: [
1043
+ { header: "Provider" },
1044
+ { header: "Hint" },
1045
+ { header: "Updated" }
1046
+ ],
1047
+ rows: listed.data.map((credential) => [
1048
+ credential.provider,
1049
+ credential.hint,
1050
+ timeText(credential.updated_at)
1051
+ ])
1052
+ }
1053
+ });
1054
+ return { document: { credentials: listed.data } };
1055
+ };
1056
+ const fieldsOf = async ({ context, pairs }) => {
1057
+ const source = lastValue(context.options, "from");
1058
+ if (source !== void 0 && pairs !== void 0) {
1059
+ const message = "Can't use --from with --field. Pass the fields one way.";
1060
+ throw usageFailure({
1061
+ help: context.path,
1062
+ issues: [{
1063
+ field: FROM,
1064
+ message
1065
+ }],
1066
+ message
1067
+ });
1068
+ }
1069
+ if (pairs !== void 0) return pairs;
1070
+ if (source === void 0) {
1071
+ const message = "Can't set a credential without its fields. Pass --from - with a JSON object on stdin, or --field NAME=VALUE.";
1072
+ throw new CliFailure({
1073
+ issues: [{
1074
+ field: FROM,
1075
+ message
1076
+ }],
1077
+ message,
1078
+ reason: "missing_value",
1079
+ recovery: [{
1080
+ instruction: "See the fields the provider takes",
1081
+ next: { argv: [
1082
+ "providers",
1083
+ "inspect",
1084
+ context.arguments.provider?.[0] ?? "<PROVIDER>"
1085
+ ] }
1086
+ }]
1087
+ });
1088
+ }
1089
+ const decoded = decodeFields(new TextDecoder().decode(await context.read(source)));
1090
+ if (isNone(decoded) || Object.keys(decoded.value).length === 0) {
1091
+ const message = `Can't set the credential. ${source === "-" ? "Stdin" : source} must hold a JSON object of string fields, such as {"api_key": "..."}.`;
1092
+ throw usageFailure({
1093
+ help: context.path,
1094
+ issues: [{
1095
+ field: FROM,
1096
+ message
1097
+ }],
1098
+ message
1099
+ });
1100
+ }
1101
+ return decoded.value;
1102
+ };
1103
+ const credentialsSet = async (context) => {
1104
+ const { pairs, provider } = readInputs({
1105
+ build: (inputs) => ({
1106
+ pairs: inputs.pairs("field"),
1107
+ provider: providerOf(inputs) ?? ""
1108
+ }),
1109
+ context,
1110
+ verb: "set the credential"
1111
+ });
1112
+ const fields = await fieldsOf({
1113
+ context,
1114
+ pairs
1115
+ });
1116
+ const credential = await callApi({
1117
+ call: {
1118
+ action: "set the credential",
1119
+ idempotent: true,
1120
+ inspect: ["credentials", "list"],
1121
+ key: "required",
1122
+ management: true,
1123
+ run: async (client, signal) => await client.credentials.set(provider, fields, { signal }),
1124
+ target: provider
1125
+ },
1126
+ context
1127
+ });
1128
+ context.io.receipt({
1129
+ outcome: "Saved",
1130
+ rows: [{
1131
+ label: "Hint",
1132
+ value: credential.hint
1133
+ }],
1134
+ target: credentialTarget(provider)
1135
+ });
1136
+ return { document: { credential } };
1137
+ };
1138
+ const credentialsDelete = async (context) => {
1139
+ const provider = readInputs({
1140
+ build: providerOf,
1141
+ context,
1142
+ verb: DELETE_ACTION
1143
+ });
1144
+ await confirmConsent({
1145
+ action: DELETE_ACTION,
1146
+ argv: context.rerun,
1147
+ io: context.io,
1148
+ mode: context.mode,
1149
+ prompter: context.prompter,
1150
+ request: {
1151
+ consequence: `deletes the ${provider} credential, so new ${provider} sandboxes run on Sandcovery's account`,
1152
+ effects: [`New ${provider} sandboxes run on Sandcovery's account instead of yours.`],
1153
+ irreversible: true,
1154
+ noun: "credential",
1155
+ question: `Delete the ${provider} credential?`,
1156
+ target: [{
1157
+ label: "Provider",
1158
+ value: provider
1159
+ }]
1160
+ },
1161
+ tier: "destructive",
1162
+ yes: flagOf(context.options, "yes") === true
1163
+ });
1164
+ await callApi({
1165
+ call: {
1166
+ action: DELETE_ACTION,
1167
+ idempotent: false,
1168
+ inspect: ["credentials", "list"],
1169
+ key: "required",
1170
+ management: true,
1171
+ run: async (client, signal) => {
1172
+ await client.credentials.delete(provider, { signal });
1173
+ },
1174
+ target: credentialTarget(provider)
1175
+ },
1176
+ context
1177
+ });
1178
+ context.io.receipt({
1179
+ outcome: "Deleted",
1180
+ target: credentialTarget(provider)
1181
+ });
1182
+ return { document: {
1183
+ credential: { provider },
1184
+ outcome: "deleted"
1185
+ } };
1186
+ };
1187
+ // src/cli/commands/files.ts
1188
+ const fileInputs = (context, verb) => readInputs({
1189
+ build: (inputs) => {
1190
+ const file = inputs.argument("path");
1191
+ if (file.trim() === "") inputs.issue({
1192
+ field: "<path>",
1193
+ message: "The path in the sandbox is empty."
1194
+ });
1195
+ return {
1196
+ file,
1197
+ id: sandboxIdOf(inputs) ?? ""
1198
+ };
1199
+ },
1200
+ context,
1201
+ verb
1202
+ });
1203
+ const targetOf = ({ file, id }) => `${file} in sandbox ${id}`;
1204
+ const filesList = async (context) => {
1205
+ const target = fileInputs(context, "list the directory");
1206
+ const listed = await callApi({
1207
+ call: {
1208
+ action: "list the directory",
1209
+ idempotent: true,
1210
+ key: "required",
1211
+ run: async (client, signal) => await client.sandboxes.listFiles(target.id, target.file, { signal }),
1212
+ target: targetOf(target)
1213
+ },
1214
+ context
1215
+ });
1216
+ context.io.table({
1217
+ empty: "The directory is empty.",
1218
+ table: {
1219
+ columns: [
1220
+ { header: "Name" },
1221
+ { header: "Type" },
1222
+ { header: "Bytes" },
1223
+ { header: "Modified" }
1224
+ ],
1225
+ rows: listed.entries.map((entry) => [
1226
+ entry.name,
1227
+ entry.type,
1228
+ countOrDash(entry.size_bytes),
1229
+ timeText(entry.modified_at)
1230
+ ])
1231
+ }
1232
+ });
1233
+ return { document: { files: listed } };
1234
+ };
1235
+ const filesRead = async (context) => {
1236
+ const target = fileInputs(context, "read the file");
1237
+ const bytes = await callApi({
1238
+ call: {
1239
+ action: "read the file",
1240
+ idempotent: true,
1241
+ key: "required",
1242
+ run: async (client, signal) => await client.sandboxes.readFile(target.id, target.file, { signal }),
1243
+ target: targetOf(target)
1244
+ },
1245
+ context
1246
+ });
1247
+ context.streams.stdout.write(context.mode.stdout.tty ? escapeUnprintable(new TextDecoder().decode(bytes)) : bytes);
1248
+ return { document: {} };
1249
+ };
1250
+ const filesWrite = async (context) => {
1251
+ const target = fileInputs(context, "write the file");
1252
+ const content = await context.read(lastValue(context.options, "from") ?? "-");
1253
+ const entry = await callApi({
1254
+ call: {
1255
+ action: "write the file",
1256
+ idempotent: true,
1257
+ inspect: [
1258
+ "sandboxes",
1259
+ "files",
1260
+ "list",
1261
+ target.id,
1262
+ path.posix.dirname(target.file)
1263
+ ],
1264
+ key: "required",
1265
+ run: async (client, signal) => await client.sandboxes.writeFile(target.id, target.file, content, { signal }),
1266
+ target: `sandbox ${target.id}`
1267
+ },
1268
+ context
1269
+ });
1270
+ context.io.receipt({
1271
+ outcome: "Wrote",
1272
+ rows: [{
1273
+ label: "Sandbox",
1274
+ value: target.id
1275
+ }, {
1276
+ label: "Bytes",
1277
+ value: countOrDash(entry.size_bytes)
1278
+ }],
1279
+ target: entry.path
1280
+ });
1281
+ return { document: { file: entry } };
1282
+ };
1283
+ // src/cli/commands/keys.ts
1284
+ const MICRO_PER_DOLLAR = 1e6;
1285
+ const MICRO_PER_CENT = 1e4;
1286
+ const CENTS_DIGITS = 2;
1287
+ const REVOKE_ACTION = "revoke the key";
1288
+ const CLEAR = "--clear";
1289
+ const KEY_FLAGS = {
1290
+ allowed_providers: "--provider",
1291
+ expires_at: "--expires-at",
1292
+ kind: "--kind",
1293
+ max_concurrent_sandboxes: "--max-concurrent",
1294
+ max_ttl_seconds: "--max-ttl",
1295
+ name: "--name",
1296
+ spend_limit: "--spend-limit"
1297
+ };
1298
+ const CLEARED = new Map(Object.entries(CLEARABLE));
1299
+ const microUsdOf = (text) => {
1300
+ const [whole = "", fraction = "", ...rest] = text.split(".");
1301
+ return isDigits(whole) && (fraction === "" || isDigits(fraction)) && rest.length === 0 && fraction.length <= CENTS_DIGITS ? Number(whole) * MICRO_PER_DOLLAR + Number(fraction.padEnd(CENTS_DIGITS, "0")) * MICRO_PER_CENT : NaN;
1302
+ };
1303
+ const policyInput = (inputs) => {
1304
+ const draft = {};
1305
+ const providers = inputs.texts("provider");
1306
+ const limit = inputs.text("spend-limit");
1307
+ const period = inputs.oneOf("spend-period", SpendLimit.fields.period.literals);
1308
+ if (providers.length > 0) draft.allowed_providers = providers;
1309
+ if (limit !== void 0) draft.spend_limit = {
1310
+ limit_micro_usd: microUsdOf(limit),
1311
+ period: period ?? "month"
1312
+ };
1313
+ else if (inputs.text("spend-period") !== void 0) inputs.issue({
1314
+ field: "--spend-period",
1315
+ message: "--spend-period needs --spend-limit."
1316
+ });
1317
+ put(draft, "expires_at", inputs.text("expires-at"));
1318
+ put(draft, "max_concurrent_sandboxes", numberOf(inputs.text("max-concurrent")));
1319
+ put(draft, "max_ttl_seconds", numberOf(inputs.text("max-ttl")));
1320
+ put(draft, "name", inputs.text("name"));
1321
+ return draft;
1322
+ };
1323
+ const keyIdOf = (inputs) => inputs.decoded({
1324
+ field: "<key>",
1325
+ message: "The key ID must be key_ or mkey_ followed by a UUID, as sandcovery keys list prints it.",
1326
+ schema: KeyId,
1327
+ value: inputs.argument("key")
1328
+ }) ?? "";
1329
+ const keyRows = (key) => [
1330
+ {
1331
+ label: "ID",
1332
+ value: key.id
1333
+ },
1334
+ {
1335
+ label: "Kind",
1336
+ value: key.kind
1337
+ },
1338
+ {
1339
+ label: "Start",
1340
+ value: key.start
1341
+ },
1342
+ {
1343
+ label: "Spent",
1344
+ value: moneyText(key.spend.spent_micro_usd)
1345
+ },
1346
+ {
1347
+ label: "Spend Limit",
1348
+ value: key.spend_limit === null ? "-" : `${moneyText(key.spend_limit.limit_micro_usd)} per ${key.spend_limit.period}`
1349
+ },
1350
+ {
1351
+ label: "Max TTL",
1352
+ value: key.max_ttl_seconds === null ? "-" : durationText(key.max_ttl_seconds)
1353
+ },
1354
+ {
1355
+ label: "Max Concurrent",
1356
+ value: countOrDash(key.max_concurrent_sandboxes)
1357
+ },
1358
+ {
1359
+ label: "Providers",
1360
+ value: key.allowed_providers === null ? "any" : key.allowed_providers.join(", ")
1361
+ },
1362
+ {
1363
+ label: "Expires",
1364
+ value: timeText(key.expires_at)
1365
+ },
1366
+ {
1367
+ label: "Last Used",
1368
+ value: timeText(key.last_used_at)
1369
+ },
1370
+ ...key.revoked_at === null ? [] : [{
1371
+ label: "Revoked",
1372
+ value: timeText(key.revoked_at)
1373
+ }]
1374
+ ];
1375
+ const keyTarget = (id) => `key ${id}`;
1376
+ const keysList = async (context) => {
1377
+ const listed = await callApi({
1378
+ call: {
1379
+ action: "list keys",
1380
+ idempotent: true,
1381
+ key: "required",
1382
+ management: true,
1383
+ run: async (client, signal) => await client.keys.list({ signal })
1384
+ },
1385
+ context
1386
+ });
1387
+ context.io.table({
1388
+ empty: "No keys.",
1389
+ table: {
1390
+ columns: [
1391
+ { header: "ID" },
1392
+ { header: "Name" },
1393
+ { header: "Kind" },
1394
+ { header: "Start" },
1395
+ { header: "Last Used" },
1396
+ { header: "Revoked" }
1397
+ ],
1398
+ rows: listed.data.map((key) => [
1399
+ key.id,
1400
+ key.name,
1401
+ key.kind,
1402
+ key.start,
1403
+ timeText(key.last_used_at),
1404
+ timeText(key.revoked_at)
1405
+ ])
1406
+ }
1407
+ });
1408
+ return { document: { keys: listed.data } };
1409
+ };
1410
+ const keysCreate = async (context) => {
1411
+ const request = readInputs({
1412
+ build: (inputs) => {
1413
+ const draft = policyInput(inputs);
1414
+ draft.kind = inputs.oneOf("kind", KeyKind.literals) ?? "api";
1415
+ return inputs.checked({
1416
+ flags: KEY_FLAGS,
1417
+ schema: CreateKeyRequest,
1418
+ value: draft
1419
+ });
1420
+ },
1421
+ context,
1422
+ verb: "create a key"
1423
+ });
1424
+ const created = await callApi({
1425
+ call: {
1426
+ action: "create the key",
1427
+ idempotent: false,
1428
+ inspect: ["keys", "list"],
1429
+ key: "required",
1430
+ management: true,
1431
+ run: async (client, signal) => await client.keys.create(request, { signal })
1432
+ },
1433
+ context
1434
+ });
1435
+ context.io.mask(created.secret);
1436
+ context.io.receipt({
1437
+ outcome: "Created",
1438
+ rows: [{
1439
+ label: "Name",
1440
+ value: created.key.name
1441
+ }, ...keyRows(created.key).slice(1, 3)],
1442
+ target: keyTarget(created.key.id)
1443
+ });
1444
+ context.io.note(["Store the secret now. Sandcovery keeps only its first 12 characters and can't show it again."]);
1445
+ context.io.secret(created.secret);
1446
+ return { document: {
1447
+ key: created.key,
1448
+ secret: created.secret
1449
+ } };
1450
+ };
1451
+ const keysInspect = async (context) => {
1452
+ const id = readInputs({
1453
+ build: keyIdOf,
1454
+ context,
1455
+ verb: "show the key"
1456
+ });
1457
+ const key = await callApi({
1458
+ call: {
1459
+ action: "show the key",
1460
+ idempotent: true,
1461
+ key: "required",
1462
+ management: true,
1463
+ run: async (client, signal) => await client.keys.get(id, { signal }),
1464
+ target: keyTarget(id)
1465
+ },
1466
+ context
1467
+ });
1468
+ context.io.details([{
1469
+ label: "Name",
1470
+ value: key.name
1471
+ }, ...keyRows(key)]);
1472
+ return { document: { key } };
1473
+ };
1474
+ const keysUpdate = async (context) => {
1475
+ const { id, request } = readInputs({
1476
+ build: (inputs) => {
1477
+ const draft = policyInput(inputs);
1478
+ for (const name of inputs.texts("clear")) {
1479
+ const field = CLEARED.get(name);
1480
+ if (field === void 0) inputs.issue({
1481
+ field: CLEAR,
1482
+ message: `--clear must be one of ${[...CLEARED.keys()].join(", ")}.`
1483
+ });
1484
+ else if (draft[field] === void 0 || draft[field] === null) draft[field] = null;
1485
+ else inputs.issue({
1486
+ field: CLEAR,
1487
+ message: `Can't use --clear ${name} with --${name}.`
1488
+ });
1489
+ }
1490
+ return {
1491
+ id: keyIdOf(inputs),
1492
+ request: inputs.checked({
1493
+ flags: KEY_FLAGS,
1494
+ schema: UpdateKeyRequest,
1495
+ value: draft
1496
+ })
1497
+ };
1498
+ },
1499
+ context,
1500
+ verb: "update the key"
1501
+ });
1502
+ if (request === void 0 || Object.keys(request).length === 0) {
1503
+ const message = "Can't update the key without a change. Pass an option such as --name or --clear.";
1504
+ throw usageFailure({
1505
+ help: context.path,
1506
+ issues: [{
1507
+ field: "options",
1508
+ message
1509
+ }],
1510
+ message
1511
+ });
1512
+ }
1513
+ const key = await callApi({
1514
+ call: {
1515
+ action: "update the key",
1516
+ idempotent: true,
1517
+ inspect: [
1518
+ "keys",
1519
+ "inspect",
1520
+ id
1521
+ ],
1522
+ key: "required",
1523
+ management: true,
1524
+ run: async (client, signal) => await client.keys.update(id, request, { signal }),
1525
+ target: keyTarget(id)
1526
+ },
1527
+ context
1528
+ });
1529
+ context.io.receipt({
1530
+ outcome: "Updated",
1531
+ rows: keyRows(key).slice(3),
1532
+ target: keyTarget(key.id)
1533
+ });
1534
+ return { document: { key } };
1535
+ };
1536
+ const keysRevoke = async (context) => {
1537
+ const id = readInputs({
1538
+ build: keyIdOf,
1539
+ context,
1540
+ verb: REVOKE_ACTION
1541
+ });
1542
+ await confirmConsent({
1543
+ action: REVOKE_ACTION,
1544
+ argv: context.rerun,
1545
+ io: context.io,
1546
+ mode: context.mode,
1547
+ prompter: context.prompter,
1548
+ request: {
1549
+ consequence: `revokes key ${id}, so every program that uses it loses access`,
1550
+ effects: ["Every program that uses the key loses access at once. Its sandboxes keep running until their TTL."],
1551
+ irreversible: true,
1552
+ noun: "key",
1553
+ question: `Revoke key ${id}?`,
1554
+ target: [{
1555
+ label: "Key",
1556
+ value: id
1557
+ }]
1558
+ },
1559
+ tier: "destructive",
1560
+ yes: flagOf(context.options, "yes") === true
1561
+ });
1562
+ const key = await callApi({
1563
+ call: {
1564
+ action: REVOKE_ACTION,
1565
+ idempotent: true,
1566
+ inspect: [
1567
+ "keys",
1568
+ "inspect",
1569
+ id
1570
+ ],
1571
+ key: "required",
1572
+ management: true,
1573
+ run: async (client, signal) => await client.keys.revoke(id, { signal }),
1574
+ target: keyTarget(id)
1575
+ },
1576
+ context
1577
+ });
1578
+ context.io.receipt({
1579
+ outcome: "Revoked",
1580
+ rows: [{
1581
+ label: "Revoked",
1582
+ value: timeText(key.revoked_at)
1583
+ }],
1584
+ target: keyTarget(key.id)
1585
+ });
1586
+ return { document: {
1587
+ key,
1588
+ outcome: "revoked"
1589
+ } };
1590
+ };
1591
+ // src/cli/commands/providers.ts
1592
+ const LISTED_SIZE = "2x4";
1593
+ const NO_PROVIDERS = "No providers.";
1594
+ const PROVIDER = "Provider";
1595
+ const CREATE_P50 = "Create p50";
1596
+ const UPTIME_24H = "Uptime 24h";
1597
+ const latencyText = (ms) => ms === null ? "-" : `${String(ms)} ms`;
1598
+ const mibText = (mib) => mib === null ? "-" : `${String(mib)} MiB`;
1599
+ const ISO_DAY_LENGTH = 10;
1600
+ const securityText = (fact) => {
1601
+ if (fact === null) return "unknown";
1602
+ const value = [fact.value].flat().join(", ");
1603
+ const read = `${fact.source_url}, read ${fact.read_at.slice(0, ISO_DAY_LENGTH)}`;
1604
+ return fact.source_changed_at === null ? `${value} (${read})` : `${value} (${read}, page changed ${fact.source_changed_at.slice(0, ISO_DAY_LENGTH)})`;
1605
+ };
1606
+ const COMING_SOON = "coming soon";
1607
+ const NOT_SHARED = "Not shared";
1608
+ const incidentsText = (incidents, statusUrl) => {
1609
+ if (incidents === null) return statusUrl === null ? "no public status page" : "not read yet";
1610
+ const active = incidents.data.filter(({ resolved_at }) => resolved_at === null).length;
1611
+ return active === 0 ? "none active" : `${String(active)} active`;
1612
+ };
1613
+ const listedRow = ({ entry, shared, status, statusUrl }) => {
1614
+ const hourly = entry.prices.find((candidate) => candidate.size === LISTED_SIZE)?.hourly_micro_usd;
1615
+ return [
1616
+ entry.provider,
1617
+ status,
1618
+ hourly === void 0 || hourly === null ? "-" : `${rateText(hourly)}/h`,
1619
+ shared ? latencyText(entry.create_latency_ms.p50) : NOT_SHARED,
1620
+ shared ? shareText(entry.uptime.last_24_hours) : NOT_SHARED,
1621
+ incidentsText(entry.incidents, statusUrl)
1622
+ ];
1623
+ };
1624
+ const listProviders = ({ context, rows }) => {
1625
+ context.io.table({
1626
+ empty: NO_PROVIDERS,
1627
+ table: {
1628
+ columns: [
1629
+ { header: PROVIDER },
1630
+ { header: "Status" },
1631
+ { header: `${LISTED_SIZE} Price` },
1632
+ { header: CREATE_P50 },
1633
+ { header: UPTIME_24H },
1634
+ { header: "Incidents" }
1635
+ ],
1636
+ rows
1637
+ }
1638
+ });
1639
+ };
1640
+ const routedRow = (entry) => listedRow({
1641
+ entry,
1642
+ shared: entry.health_published,
1643
+ status: entry.status,
1644
+ statusUrl: entry.status_url
1645
+ });
1646
+ const catalogRow = (entry) => listedRow({
1647
+ entry,
1648
+ shared: entry.measurement !== "not_published",
1649
+ status: entry.routed ? entry.status : COMING_SOON,
1650
+ statusUrl: entry.links.status_url
1651
+ });
1652
+ const providersList = async (context) => {
1653
+ if (readInputs({
1654
+ build: (inputs) => inputs.flag("routed") === true,
1655
+ context,
1656
+ verb: "list the providers"
1657
+ })) {
1658
+ const board = await callApi({
1659
+ call: {
1660
+ action: "list the routed providers",
1661
+ idempotent: true,
1662
+ key: "optional",
1663
+ run: async (client, signal) => await client.providers.list({ signal })
1664
+ },
1665
+ context
1666
+ });
1667
+ listProviders({
1668
+ context,
1669
+ rows: board.data.map(routedRow)
1670
+ });
1671
+ return { document: { providers: board.data } };
1672
+ }
1673
+ const catalog = await callApi({
1674
+ call: {
1675
+ action: "list the providers",
1676
+ idempotent: true,
1677
+ key: "optional",
1678
+ run: async (client, signal) => await client.providers.catalog({ signal })
1679
+ },
1680
+ context
1681
+ });
1682
+ listProviders({
1683
+ context,
1684
+ rows: catalog.data.map(catalogRow)
1685
+ });
1686
+ return { document: { providers: catalog.data } };
1687
+ };
1688
+ const providersInspect = async (context) => {
1689
+ const provider = readInputs({
1690
+ build: providerOf,
1691
+ context,
1692
+ verb: "show the provider"
1693
+ });
1694
+ const entry = await callApi({
1695
+ call: {
1696
+ action: "show the provider",
1697
+ idempotent: true,
1698
+ key: "optional",
1699
+ run: async (client, signal) => await client.providers.get(provider, { signal }),
1700
+ target: `provider ${provider}`
1701
+ },
1702
+ context
1703
+ });
1704
+ const { features } = entry;
1705
+ context.io.details([
1706
+ {
1707
+ label: PROVIDER,
1708
+ value: entry.provider
1709
+ },
1710
+ {
1711
+ label: "Name",
1712
+ value: entry.name
1713
+ },
1714
+ {
1715
+ label: "Status",
1716
+ value: entry.status
1717
+ },
1718
+ {
1719
+ label: CREATE_P50,
1720
+ value: latencyText(entry.create_latency_ms.p50)
1721
+ },
1722
+ {
1723
+ label: "Create p95",
1724
+ value: latencyText(entry.create_latency_ms.p95)
1725
+ },
1726
+ {
1727
+ label: "Uptime 7d",
1728
+ value: shareText(entry.uptime.last_7_days)
1729
+ },
1730
+ {
1731
+ label: "Incidents",
1732
+ value: incidentsText(entry.incidents, entry.status_url)
1733
+ },
1734
+ {
1735
+ label: "Isolation",
1736
+ value: securityText(entry.security.isolation)
1737
+ },
1738
+ {
1739
+ label: "Compliance",
1740
+ value: securityText(entry.security.compliance)
1741
+ },
1742
+ {
1743
+ label: "Data Location",
1744
+ value: securityText(entry.security.data_location)
1745
+ },
1746
+ {
1747
+ label: "Regions",
1748
+ value: features.regions.join(", ")
1749
+ },
1750
+ {
1751
+ label: "Max TTL",
1752
+ value: durationText(features.max_ttl_seconds)
1753
+ },
1754
+ {
1755
+ label: "Max vCPU",
1756
+ value: String(features.max_vcpu)
1757
+ },
1758
+ {
1759
+ label: "Max Memory",
1760
+ value: mibText(features.max_memory_mib)
1761
+ },
1762
+ {
1763
+ label: "Max Disk",
1764
+ value: mibText(features.max_disk_mib)
1765
+ },
1766
+ {
1767
+ label: "Egress",
1768
+ value: features.egress_modes.join(", ")
1769
+ },
1770
+ {
1771
+ label: "Features",
1772
+ value: [
1773
+ "custom_image",
1774
+ "idle_timeout",
1775
+ "pause",
1776
+ "ports",
1777
+ "snapshot",
1778
+ "streamed_exec"
1779
+ ].filter((name) => features[name]).join(", ")
1780
+ },
1781
+ {
1782
+ label: "Credential Fields",
1783
+ value: orDash(entry.credential_fields.map((field) => field.name).join(", ") || null)
1784
+ },
1785
+ {
1786
+ label: "Rate Card",
1787
+ value: `${entry.rate_card_version}, ${entry.rate_card_source_url}`
1788
+ },
1789
+ {
1790
+ label: "Updated",
1791
+ value: timeText(entry.updated_at)
1792
+ }
1793
+ ]);
1794
+ context.io.table({
1795
+ empty: "No prices.",
1796
+ table: {
1797
+ columns: [{ header: "Size" }, { header: "Hourly" }],
1798
+ rows: entry.prices.map((price) => [price.size, rateText(price.hourly_micro_usd)])
1799
+ }
1800
+ });
1801
+ if (entry.incidents !== null) context.io.table({
1802
+ empty: "No incidents in the last 7 days.",
1803
+ table: {
1804
+ columns: [
1805
+ { header: "Incident" },
1806
+ { header: "Impact" },
1807
+ { header: "Started" },
1808
+ { header: "Resolved" }
1809
+ ],
1810
+ rows: entry.incidents.data.map((incident) => [
1811
+ incident.title,
1812
+ incident.impact,
1813
+ timeText(incident.started_at),
1814
+ incident.resolved_at === null ? "active" : timeText(incident.resolved_at)
1815
+ ])
1816
+ }
1817
+ });
1818
+ return {
1819
+ document: { provider: entry },
1820
+ next: [{
1821
+ argv: [
1822
+ "credentials",
1823
+ "set",
1824
+ entry.provider,
1825
+ "--from",
1826
+ "-"
1827
+ ],
1828
+ benefit: "Run sandboxes on your own account",
1829
+ optional: true
1830
+ }]
1831
+ };
1832
+ };
1833
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/stringify.js
1834
+ const byteToHex = [];
1835
+ for (let i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).slice(1));
1836
+ function unsafeStringify(arr, offset = 0) {
1837
+ 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();
1838
+ }
1839
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/rng.js
1840
+ const rnds8 = /* @__PURE__ */ new Uint8Array(16);
1841
+ function rng() {
1842
+ return crypto.getRandomValues(rnds8);
1843
+ }
1844
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/v7.js
1845
+ const _state = {};
1846
+ function v7(options, buf, offset) {
1847
+ let bytes;
1848
+ if (options) bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset);
1849
+ else {
1850
+ const now = Date.now();
1851
+ const rnds = rng();
1852
+ updateV7State(_state, now, rnds);
1853
+ bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
1854
+ }
1855
+ return buf ?? unsafeStringify(bytes);
1856
+ }
1857
+ function updateV7State(state, now, rnds) {
1858
+ state.msecs ??= -Infinity;
1859
+ state.seq ??= 0;
1860
+ if (now > state.msecs) {
1861
+ state.seq = v7Sequence(rnds);
1862
+ state.msecs = now;
1863
+ } else {
1864
+ state.seq = state.seq + 1 | 0;
1865
+ if (state.seq === 0) state.msecs++;
1866
+ }
1867
+ return state;
1868
+ }
1869
+ function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
1870
+ if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
1871
+ if (!buf) {
1872
+ buf = /* @__PURE__ */ new Uint8Array(16);
1873
+ offset = 0;
1874
+ } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
1875
+ msecs ??= Date.now();
1876
+ seq ??= v7Sequence(rnds);
1877
+ buf[offset++] = msecs / 1099511627776 & 255;
1878
+ buf[offset++] = msecs / 4294967296 & 255;
1879
+ buf[offset++] = msecs / 16777216 & 255;
1880
+ buf[offset++] = msecs / 65536 & 255;
1881
+ buf[offset++] = msecs / 256 & 255;
1882
+ buf[offset++] = msecs & 255;
1883
+ buf[offset++] = 112 | seq >>> 28 & 15;
1884
+ buf[offset++] = seq >>> 20 & 255;
1885
+ buf[offset++] = 128 | seq >>> 14 & 63;
1886
+ buf[offset++] = seq >>> 6 & 255;
1887
+ buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
1888
+ buf[offset++] = rnds[11];
1889
+ buf[offset++] = rnds[12];
1890
+ buf[offset++] = rnds[13];
1891
+ buf[offset++] = rnds[14];
1892
+ buf[offset++] = rnds[15];
1893
+ return buf;
1894
+ }
1895
+ function v7Sequence(rnds) {
1896
+ return (rnds[6] & 127) << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
1897
+ }
1898
+ // src/cli/commands/sandboxes.ts
1899
+ const CREATE_TIMEOUT_SECONDS = 180;
1900
+ const EXEC_MARGIN_SECONDS = 60;
1901
+ const MAX_EXIT_CODE = 255;
1902
+ const RUN_ACTION = "run the command";
1903
+ const START_ACTION = "start the detached command";
1904
+ const DESTROY_ACTION = "destroy the sandbox";
1905
+ const isPort = is(Port);
1906
+ const sandboxTarget = (id) => `sandbox ${id}`;
1907
+ const inspectArgv = (id) => [
1908
+ "sandboxes",
1909
+ "inspect",
1910
+ id
1911
+ ];
1912
+ const sandboxDocument = (sandbox) => ({ sandbox });
1913
+ const sandboxIdFrom = (context, verb) => readInputs({
1914
+ build: (inputs) => sandboxIdOf(inputs) ?? "",
1915
+ context,
1916
+ verb
1917
+ });
1918
+ const sandboxesList = async (context) => {
1919
+ const query = readInputs({
1920
+ build: (inputs) => ({
1921
+ cursor: inputs.text("next"),
1922
+ limit: inputs.integer("limit", {
1923
+ maximum: 100,
1924
+ minimum: 1
1925
+ }),
1926
+ status: inputs.oneOf("status", SandboxStatus.literals)
1927
+ }),
1928
+ context,
1929
+ verb: "list sandboxes"
1930
+ });
1931
+ const page = await callApi({
1932
+ call: {
1933
+ action: "list sandboxes",
1934
+ idempotent: true,
1935
+ key: "required",
1936
+ run: async (client, signal) => await client.sandboxes.list(query, { signal })
1937
+ },
1938
+ context
1939
+ });
1940
+ context.io.table({
1941
+ empty: "No sandboxes.",
1942
+ table: {
1943
+ columns: SANDBOX_COLUMNS,
1944
+ rows: page.data.map(sandboxTableRow)
1945
+ }
1946
+ });
1947
+ return {
1948
+ document: {
1949
+ next_cursor: page.next_cursor,
1950
+ sandboxes: page.data
1951
+ },
1952
+ next: nextPage({
1953
+ argv: [
1954
+ "sandboxes",
1955
+ "list",
1956
+ ...query.status === void 0 ? [] : ["--status", query.status]
1957
+ ],
1958
+ cursor: page.next_cursor
1959
+ })
1960
+ };
1961
+ };
1962
+ const sandboxesCreate = async (context) => {
1963
+ const request = readInputs({
1964
+ build: (inputs) => {
1965
+ const spec = specInput(inputs);
1966
+ put(spec, "snapshot_id", inputs.text("snapshot"));
1967
+ return inputs.checked({
1968
+ flags: SPEC_FLAGS,
1969
+ schema: CreateSandboxRequest,
1970
+ value: spec
1971
+ });
1972
+ },
1973
+ context,
1974
+ verb: "create a sandbox"
1975
+ });
1976
+ const idempotencyKey = v7();
1977
+ const sandbox = await callApi({
1978
+ call: {
1979
+ action: "create the sandbox",
1980
+ idempotent: true,
1981
+ inspect: ["sandboxes", "list"],
1982
+ key: "required",
1983
+ run: async (client, signal) => await client.sandboxes.create(request, {
1984
+ idempotencyKey,
1985
+ signal
1986
+ }),
1987
+ timeoutSeconds: CREATE_TIMEOUT_SECONDS
1988
+ },
1989
+ context
1990
+ });
1991
+ context.io.receipt({
1992
+ outcome: "Created",
1993
+ rows: [...sandboxRows(sandbox).slice(1), {
1994
+ label: "Attempts",
1995
+ value: attemptRows(sandbox.attempts).map((row) => row.join(" ")).join(", ")
1996
+ }],
1997
+ target: sandboxTarget(sandbox.id)
1998
+ });
1999
+ context.io.identifier(sandbox.id);
2000
+ return {
2001
+ document: sandboxDocument(sandbox),
2002
+ next: [{
2003
+ argv: [
2004
+ "sandboxes",
2005
+ "exec",
2006
+ sandbox.id,
2007
+ "--",
2008
+ "uname",
2009
+ "-a"
2010
+ ],
2011
+ benefit: "Run a command in it"
2012
+ }]
2013
+ };
2014
+ };
2015
+ const sandboxesInspect = async (context) => {
2016
+ const id = sandboxIdFrom(context, "show the sandbox");
2017
+ const sandbox = await callApi({
2018
+ call: {
2019
+ action: "show the sandbox",
2020
+ idempotent: true,
2021
+ key: "required",
2022
+ run: async (client, signal) => await client.sandboxes.get(id, { signal }),
2023
+ target: sandboxTarget(id)
2024
+ },
2025
+ context
2026
+ });
2027
+ context.io.details(sandboxRows(sandbox));
2028
+ context.io.table({
2029
+ empty: "No attempts.",
2030
+ table: {
2031
+ columns: ATTEMPT_COLUMNS,
2032
+ rows: attemptRows(sandbox.attempts)
2033
+ }
2034
+ });
2035
+ return { document: sandboxDocument(sandbox) };
2036
+ };
2037
+ const exitCodeOf = (code) => Number.isInteger(code) && code >= 0 && code <= MAX_EXIT_CODE ? code : 1;
2038
+ const streamed = async ({ context, id, request }) => {
2039
+ const terminal = context.mode.stdout.tty;
2040
+ return await callApi({
2041
+ call: {
2042
+ action: RUN_ACTION,
2043
+ idempotent: false,
2044
+ inspect: inspectArgv(id),
2045
+ key: "required",
2046
+ run: async (client, signal) => {
2047
+ for await (const event of client.sandboxes.execStream(id, request, { signal })) switch (event.type) {
2048
+ case "stdout":
2049
+ context.streams.stdout.write(terminal ? escapeUnprintable(event.data) : event.data);
2050
+ break;
2051
+ case "stderr":
2052
+ context.streams.stderr.write(context.mode.stderr.tty ? escapeUnprintable(event.data) : event.data);
2053
+ break;
2054
+ case "exit": return exitCodeOf(event.exit_code);
2055
+ case "error": throw new CliFailure({
2056
+ data: { provider: event.provider },
2057
+ message: `Failed to run the command. ${event.provider} reported an error while it ran.`,
2058
+ notes: ["The command may have run in part, so check the sandbox before running it again."],
2059
+ reason: "provider_error",
2060
+ remoteMessage: event.message
2061
+ });
2062
+ }
2063
+ throw new CliFailure({
2064
+ message: "Can't confirm whether the command finished. The stream ended without its exit code.",
2065
+ reason: "unknown_outcome",
2066
+ recovery: [{
2067
+ instruction: "Check the sandbox",
2068
+ next: { argv: inspectArgv(id) }
2069
+ }]
2070
+ });
2071
+ },
2072
+ target: sandboxTarget(id),
2073
+ timeoutSeconds: null
2074
+ },
2075
+ context
2076
+ });
2077
+ };
2078
+ const sandboxesExec = async (context) => {
2079
+ const { detach, id, request } = readInputs({
2080
+ build: (inputs) => {
2081
+ const draft = { command: (context.arguments.command ?? []).join(" ") };
2082
+ const detached = inputs.flag("detach") === true;
2083
+ put(draft, "cwd", inputs.text("cwd"));
2084
+ put(draft, "env", inputs.pairs("env"));
2085
+ put(draft, "timeout_seconds", inputs.integer("timeout", { minimum: 1 }));
2086
+ if (detached && draft.timeout_seconds !== void 0) inputs.issue({
2087
+ field: "--timeout",
2088
+ message: "Can't use --timeout with --detach, since a detached command runs until it exits or the sandbox ends."
2089
+ });
2090
+ return {
2091
+ detach: detached,
2092
+ id: sandboxIdOf(inputs) ?? "",
2093
+ request: draft
2094
+ };
2095
+ },
2096
+ context,
2097
+ verb: RUN_ACTION
2098
+ });
2099
+ if (detach) {
2100
+ const started = await callApi({
2101
+ call: {
2102
+ action: START_ACTION,
2103
+ idempotent: false,
2104
+ inspect: inspectArgv(id),
2105
+ key: "required",
2106
+ run: async (client, signal) => await client.sandboxes.execDetached(id, request, { signal }),
2107
+ target: sandboxTarget(id)
2108
+ },
2109
+ context
2110
+ });
2111
+ context.io.receipt({
2112
+ outcome: "Started",
2113
+ rows: [{
2114
+ label: "Started at",
2115
+ value: started.started_at
2116
+ }],
2117
+ target: sandboxTarget(id)
2118
+ });
2119
+ return { document: { exec: started } };
2120
+ }
2121
+ if (context.mode.format === "human") return {
2122
+ document: {},
2123
+ exitCode: await streamed({
2124
+ context,
2125
+ id,
2126
+ request
2127
+ })
2128
+ };
2129
+ const result = await callApi({
2130
+ call: {
2131
+ action: RUN_ACTION,
2132
+ idempotent: false,
2133
+ inspect: inspectArgv(id),
2134
+ key: "required",
2135
+ run: async (client, signal) => await client.sandboxes.exec(id, request, { signal }),
2136
+ target: sandboxTarget(id),
2137
+ timeoutSeconds: request.timeout_seconds === void 0 ? null : request.timeout_seconds + EXEC_MARGIN_SECONDS
2138
+ },
2139
+ context
2140
+ });
2141
+ return {
2142
+ document: { exec: result },
2143
+ exitCode: exitCodeOf(result.exit_code)
2144
+ };
2145
+ };
2146
+ const sandboxesDestroy = async (context) => {
2147
+ const id = sandboxIdFrom(context, DESTROY_ACTION);
2148
+ await confirmConsent({
2149
+ action: DESTROY_ACTION,
2150
+ argv: context.rerun,
2151
+ io: context.io,
2152
+ mode: context.mode,
2153
+ prompter: context.prompter,
2154
+ request: {
2155
+ consequence: `destroys sandbox ${id} and deletes its files`,
2156
+ effects: ["Stops every command in the sandbox and deletes its files."],
2157
+ irreversible: true,
2158
+ noun: "sandbox",
2159
+ question: `Destroy sandbox ${id}?`,
2160
+ target: [{
2161
+ label: "Sandbox",
2162
+ value: id
2163
+ }]
2164
+ },
2165
+ tier: "destructive",
2166
+ yes: flagOf(context.options, "yes") === true
2167
+ });
2168
+ const sandbox = await callApi({
2169
+ call: {
2170
+ action: DESTROY_ACTION,
2171
+ idempotent: true,
2172
+ inspect: inspectArgv(id),
2173
+ key: "required",
2174
+ run: async (client, signal) => await client.sandboxes.destroy(id, { signal }),
2175
+ target: sandboxTarget(id)
2176
+ },
2177
+ context
2178
+ });
2179
+ context.io.receipt({
2180
+ outcome: "Destroyed",
2181
+ rows: [{
2182
+ label: "Cost",
2183
+ value: moneyText(sandbox.cost.estimated_micro_usd)
2184
+ }],
2185
+ target: sandboxTarget(id)
2186
+ });
2187
+ return { document: {
2188
+ outcome: "destroyed",
2189
+ ...sandboxDocument(sandbox)
2190
+ } };
2191
+ };
2192
+ const lifecycle = ({ outcome, run, verb }) => async (context) => {
2193
+ const id = sandboxIdFrom(context, `${verb} the sandbox`);
2194
+ const sandbox = await callApi({
2195
+ call: {
2196
+ action: `${verb} the sandbox`,
2197
+ idempotent: false,
2198
+ inspect: inspectArgv(id),
2199
+ key: "required",
2200
+ run: async (client, signal) => await client.sandboxes[run](id, { signal }),
2201
+ target: sandboxTarget(id)
2202
+ },
2203
+ context
2204
+ });
2205
+ context.io.receipt({
2206
+ outcome,
2207
+ rows: [{
2208
+ label: "Status",
2209
+ value: sandbox.status
2210
+ }],
2211
+ target: sandboxTarget(id)
2212
+ });
2213
+ return { document: sandboxDocument(sandbox) };
2214
+ };
2215
+ const sandboxesPause = lifecycle({
2216
+ outcome: "Paused",
2217
+ run: "pause",
2218
+ verb: "pause"
2219
+ });
2220
+ const sandboxesResume = lifecycle({
2221
+ outcome: "Resumed",
2222
+ run: "resume",
2223
+ verb: "resume"
2224
+ });
2225
+ const sandboxesSnapshot = async (context) => {
2226
+ const id = sandboxIdFrom(context, "snapshot the sandbox");
2227
+ const snapshot = await callApi({
2228
+ call: {
2229
+ action: "snapshot the sandbox",
2230
+ idempotent: false,
2231
+ inspect: inspectArgv(id),
2232
+ key: "required",
2233
+ run: async (client, signal) => await client.sandboxes.snapshot(id, { signal }),
2234
+ target: sandboxTarget(id)
2235
+ },
2236
+ context
2237
+ });
2238
+ context.io.receipt({
2239
+ outcome: "Snapshot",
2240
+ rows: [{
2241
+ label: "Snapshot",
2242
+ value: snapshot.id
2243
+ }, {
2244
+ label: "Provider",
2245
+ value: snapshot.provider
2246
+ }],
2247
+ target: sandboxTarget(id)
2248
+ });
2249
+ context.io.identifier(snapshot.id);
2250
+ return {
2251
+ document: { snapshot },
2252
+ next: [{
2253
+ argv: [
2254
+ "sandboxes",
2255
+ "create",
2256
+ "--snapshot",
2257
+ snapshot.id
2258
+ ],
2259
+ benefit: "Start a sandbox from it"
2260
+ }]
2261
+ };
2262
+ };
2263
+ const portsInspect = async (context) => {
2264
+ const { id, port } = readInputs({
2265
+ build: (inputs) => {
2266
+ const number = wholeNumber(inputs.argument("port"));
2267
+ if (!isPort(number)) inputs.issue({
2268
+ field: "<port>",
2269
+ message: "The port must be a whole number from 1 to 65535."
2270
+ });
2271
+ return {
2272
+ id: sandboxIdOf(inputs) ?? "",
2273
+ port: number
2274
+ };
2275
+ },
2276
+ context,
2277
+ verb: "preview the port"
2278
+ });
2279
+ const preview = await callApi({
2280
+ call: {
2281
+ action: "preview the port",
2282
+ idempotent: true,
2283
+ key: "required",
2284
+ run: async (client, signal) => await client.sandboxes.portPreview(id, port, { signal }),
2285
+ target: `port ${String(port)} of ${sandboxTarget(id)}`
2286
+ },
2287
+ context
2288
+ });
2289
+ context.io.values([preview.url]);
2290
+ for (const [name, value] of Object.entries(preview.headers)) {
2291
+ context.io.mask(value);
2292
+ context.io.secret(`${name}: ${value}`);
2293
+ }
2294
+ return { document: { preview } };
2295
+ };
2296
+ // src/cli/commands/usage.ts
2297
+ const MAX_DAYS = 92;
2298
+ const MS_PER_DAY = 864e5;
2299
+ const DAY_LENGTH = 10;
2300
+ const dayIssue = (flag) => `--${flag} must be a UTC day such as 2026-11-08.`;
2301
+ const usageInspect = async (context) => {
2302
+ const today = context.now.toISOString().slice(0, DAY_LENGTH);
2303
+ const query = readInputs({
2304
+ build: (inputs) => {
2305
+ const from = inputs.decoded({
2306
+ field: "--from",
2307
+ message: dayIssue("from"),
2308
+ schema: CalendarDay,
2309
+ value: inputs.text("from")
2310
+ }) ?? `${today.slice(0, 8)}01`;
2311
+ const to = inputs.decoded({
2312
+ field: "--to",
2313
+ message: dayIssue("to"),
2314
+ schema: CalendarDay,
2315
+ value: inputs.text("to")
2316
+ }) ?? today;
2317
+ const span = (Date.parse(to) - Date.parse(from)) / MS_PER_DAY;
2318
+ if (span < 0) inputs.issue({
2319
+ field: "--to",
2320
+ message: "--to must be on or after --from."
2321
+ });
2322
+ else if (span > MAX_DAYS) inputs.issue({
2323
+ field: "--to",
2324
+ message: `--to must be at most ${String(MAX_DAYS)} days after --from.`
2325
+ });
2326
+ const range = {
2327
+ from,
2328
+ to
2329
+ };
2330
+ put(range, "api_key_id", inputs.decoded({
2331
+ field: "--key",
2332
+ message: "--key must be an API key ID, key_ followed by a UUID.",
2333
+ schema: ApiKeyId,
2334
+ value: inputs.text("key")
2335
+ }));
2336
+ return range;
2337
+ },
2338
+ context,
2339
+ verb: "show usage"
2340
+ });
2341
+ const usage = await callApi({
2342
+ call: {
2343
+ action: "show usage",
2344
+ idempotent: true,
2345
+ key: "required",
2346
+ management: true,
2347
+ run: async (client, signal) => await client.usage.get(query, { signal })
2348
+ },
2349
+ context
2350
+ });
2351
+ const total = sumBy(usage.data, (day) => day.estimated_micro_usd);
2352
+ context.io.table({
2353
+ empty: `No usage from ${query.from} to ${query.to}.`,
2354
+ table: {
2355
+ columns: [
2356
+ { header: "Day" },
2357
+ { header: "Key" },
2358
+ { header: "Provider" },
2359
+ { header: "Sandboxes" },
2360
+ { header: "Time" },
2361
+ { header: "Cost" }
2362
+ ],
2363
+ rows: usage.data.map((day) => [
2364
+ day.date,
2365
+ day.api_key_id,
2366
+ day.provider,
2367
+ String(day.sandbox_count),
2368
+ durationText(day.sandbox_seconds),
2369
+ moneyText(day.estimated_micro_usd)
2370
+ ])
2371
+ }
2372
+ });
2373
+ context.io.note([`Estimated total from ${query.from} to ${query.to}: ${moneyText(total)}.`]);
2374
+ return { document: {
2375
+ from: query.from,
2376
+ to: query.to,
2377
+ total_micro_usd: total,
2378
+ usage: usage.data
2379
+ } };
2380
+ };
2381
+ const usageEstimate = async (context) => {
2382
+ const request = readInputs({
2383
+ build: (inputs) => inputs.checked({
2384
+ flags: SPEC_FLAGS,
2385
+ schema: EstimateRequest,
2386
+ value: specInput(inputs)
2387
+ }),
2388
+ context,
2389
+ verb: "price the sandbox"
2390
+ });
2391
+ const estimates = await callApi({
2392
+ call: {
2393
+ action: "price the sandbox",
2394
+ idempotent: true,
2395
+ key: "required",
2396
+ run: async (client, signal) => await client.usage.estimate(request, { signal })
2397
+ },
2398
+ context
2399
+ });
2400
+ context.io.table({
2401
+ empty: "No provider can run this spec.",
2402
+ table: {
2403
+ columns: [
2404
+ { header: "Provider" },
2405
+ { header: "Hourly" },
2406
+ { header: "For the TTL" }
2407
+ ],
2408
+ rows: estimates.data.map((estimate) => [
2409
+ estimate.provider,
2410
+ rateText(estimate.hourly_micro_usd),
2411
+ moneyText(estimate.ttl_micro_usd)
2412
+ ])
2413
+ }
2414
+ });
2415
+ return {
2416
+ document: { estimates: estimates.data },
2417
+ next: [{
2418
+ argv: [
2419
+ "sandboxes",
2420
+ "create",
2421
+ ...context.rerun.slice(2)
2422
+ ],
2423
+ benefit: "Create it",
2424
+ optional: true
2425
+ }]
2426
+ };
2427
+ };
2428
+ // src/cli/handlers.ts
2429
+ const HANDLERS = /* @__PURE__ */ new Map([
2430
+ ["activity list", activityList],
2431
+ ["billing buy-credits", billingBuyCredits],
2432
+ ["billing inspect", billingInspect],
2433
+ ["credentials delete", credentialsDelete],
2434
+ ["credentials list", credentialsList],
2435
+ ["credentials offer", credentialsOffer],
2436
+ ["credentials set", credentialsSet],
2437
+ ["keys create", keysCreate],
2438
+ ["keys inspect", keysInspect],
2439
+ ["keys list", keysList],
2440
+ ["keys revoke", keysRevoke],
2441
+ ["keys update", keysUpdate],
2442
+ ["providers inspect", providersInspect],
2443
+ ["providers list", providersList],
2444
+ ["sandboxes create", sandboxesCreate],
2445
+ ["sandboxes destroy", sandboxesDestroy],
2446
+ ["sandboxes exec", sandboxesExec],
2447
+ ["sandboxes files list", filesList],
2448
+ ["sandboxes files read", filesRead],
2449
+ ["sandboxes files write", filesWrite],
2450
+ ["sandboxes inspect", sandboxesInspect],
2451
+ ["sandboxes list", sandboxesList],
2452
+ ["sandboxes pause", sandboxesPause],
2453
+ ["sandboxes ports inspect", portsInspect],
2454
+ ["sandboxes resume", sandboxesResume],
2455
+ ["sandboxes snapshot", sandboxesSnapshot],
2456
+ ["usage estimate", usageEstimate],
2457
+ ["usage inspect", usageInspect]
2458
+ ]);
2459
+ export { HANDLERS };