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