sandcovery 0.9.0 → 0.10.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.
package/README.md CHANGED
@@ -79,7 +79,7 @@ sandcovery sandboxes destroySandbox --sandbox_id "$id"
79
79
 
80
80
  - A command prints the API's answer body on stdout. An error answer goes to stderr as the API sent it, and the command exits 1.
81
81
  - It sends `SANDCOVERY_API_KEY` as the key, and calls `SANDCOVERY_BASE_URL` when it is set, or https://www.sandcovery.com.
82
- - A flag for a field that is not text, such as a number, a list, or an object, takes JSON. An operation whose body is a file, such as `sandboxes uploadFile`, reads that body from stdin.
82
+ - A flag for a body field that is not text, such as a number, a list, or an object, takes JSON, either as the flag value or as `@` and a path relative to the current directory to a file inside it, such as `--env @env.json`. Every other flag takes its value as text as written, so `--command @run.sh` sends the text `@run.sh`. An operation whose body is a file, such as `sandboxes uploadFile`, reads that body from stdin.
83
83
  - `--help` works on every command.
84
84
 
85
85
  ## Docker, kubectl, and T3 Code
@@ -100,7 +100,7 @@ Provider, region, and slug names are open strings, so a name the API adds later
100
100
 
101
101
  ## Keys and provider credentials
102
102
 
103
- `keys`, `credentials`, `usage`, and `billing` need a management key, which an organization owner mints in the dashboard. An API key receives 403 there.
103
+ `keys`, `credentials`, `usage`, and `billing` need a management key, which an organization admin mints in the dashboard. An API key receives 403 there.
104
104
 
105
105
  ```ts
106
106
  const admin = new Sandcovery({ apiKey: process.env.SANDCOVERY_MANAGEMENT_KEY })
@@ -110,7 +110,9 @@ await admin.credentials.set('e2b', { api_key: process.env.E2B_API_KEY ?? '' })
110
110
 
111
111
  On Pro or the Enterprise plan, an organization holds as many credentials per provider as it needs: `credentials.add(provider, fields)` adds another, a create tries a provider's credentials in the order they were added, and `credentials.deleteOne(provider, id)` deletes one. A Free organization routes one of its own keys per provider, so adding a second key of the same provider receives 403. When an organization leaves Pro or the Enterprise plan, it keeps every key, routes the oldest key of each provider, and `paused` is `true` on the others until it is on Pro or the Enterprise plan again.
112
112
 
113
- The fields each provider takes are its `credential_fields` on `sandcovery.providers.get(provider)`. `sandcovery.providers.catalog()` lists every provider on the [provider board](https://www.sandcovery.com/providers), where `routed` is `false` for a provider that is coming soon. `credentials.offer()` reads the free vCPUh your keys have earned, `credentials.countXPost()` finds your newest post on X of the last day that tags @Sandcovery and counts it as one key, reading X at most 10 times a UTC day and 30 seconds apart for an organization and otherwise answering `retry_later` with `retry_at`, `billing.get()` reads the plan, the credit balance, and auto top-up, `billing.buyCredits({ amount_micro_usd })` answers the Stripe Checkout page that takes a credit payment, `billing.setAutoTopUp({ amount_micro_usd, threshold_micro_usd })` sets the amount Sandcovery charges the saved card each time the credit balance falls below the threshold and answers the Stripe Checkout page that saves a card when none is saved, and `billing.stopAutoTopUp()` turns auto top-up off.
113
+ The fields each provider takes are its `credential_fields` on `sandcovery.providers.get(provider)`. `sandcovery.providers.catalog()` lists every provider on the [provider board](https://www.sandcovery.com/providers), where `routed` is `false` for a provider that is coming soon. `credentials.offer()` reads the free vCPUh your keys have earned, `credentials.countXPost()` finds your newest post on X of the last day that tags @Sandcovery and counts it as one key, reading X at most 10 times a UTC day and 30 seconds apart for an organization and otherwise answering `retry_later` with `retry_at`.
114
+
115
+ `billing.get()` reads the plan, the credit balance, whether credits are on sale, and auto top-up. `billing.startSubscription({ plan })` answers the Stripe Checkout page that starts a Pro or Enterprise subscription, and `billing.openBillingPortal()` answers the Stripe billing portal page where an admin manages the subscription, payment method, and invoices. `billing.buyCredits({ amount_micro_usd })` answers the Stripe Checkout page that takes a credit payment. `billing.setAutoTopUp({ amount_micro_usd, threshold_micro_usd })` sets the amount Sandcovery charges the saved card each time the credit balance falls below the threshold or a create needs credit that one top-up covers. While auto top-up is on, the change applies at once. While it is off, the answer carries the Stripe Checkout page that saves a card and then turns auto top-up on with these settings. `billing.stopAutoTopUp()` turns auto top-up off. Auto top-up charges the card its own Checkout page saved, not the card the billing portal sets, and removing that card in the portal turns auto top-up off at its next charge. To move it to another card, call `billing.stopAutoTopUp()` and then `billing.setAutoTopUp(...)` again. `billing.openBillingPortal()` throws with the error code `not_found` until the organization has a Stripe customer, which each of these Checkout pages makes.
114
116
 
115
117
  ## X account
116
118
 
@@ -118,7 +120,7 @@ The fields each provider takes are its `credential_fields` on `sandcovery.provid
118
120
 
119
121
  ## Interfaces
120
122
 
121
- This client, the Python client, and the `sandcovery` command cover the product operations they expose. Health, usable keys, credential field choices, CLI sign-in, and agents live on the HTTP API and the CLI.
123
+ This client and the Python client have a method for every operation of the REST API except CLI sign-in, the health check, and the choices for a credential field. The `sandcovery` command reaches every operation.
122
124
 
123
125
  ## Errors
124
126
 
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { $ as toTransform, $a as flatMap$2, $i as ConsoleRef, $n as cached, $o as pipeArguments, $r as succeed$2, $t as tag, A as fail$2, Aa as all$2, Ai as fail$4, An as make$18, Ao as format, Ar as map$5, At as SchemaError, B as mkUint8Array, Ba as Service, Bi as UnknownError, Bn as offerUnsafe, Bo as isTagged, Br as orDie, Bt as declare, Ca as of, Ci as addFinalizer, Cn as fromRecordUnsafe, Co as PipeInspectableProto, Cr as fromResult, D as drainFork, Da as get$4, Di as provide, Dn as set, Do as BaseProto, Dr as interrupt$1, E as decodeText, Ea as fromIterableWith, Ei as makeUnsafe$1, En as remove$1, Eo as setStackTraceLimit, Er as ignoreCause, F as interruptWhen, Fa as isSuccess$1, Fi as isFailure, Fn as fromInputUnsafe$1, Fr as matchEffect, Ft as Trim, G as splitLines, Ga as getUnsafe, Gi as hasInterruptsOnly, Gn as interrupt, Go as constTrue, Gr as runFork, Gt as encodeSync, H as runCollect, Ha as empty$6, Hi as fail$5, Hn as sliding, Ho as assignProperty, Hr as provideContext, Ht as decodeUnknownEffect$1, I as isStream, Ia as map$6, Ii as isSuccess, In as endUnsafe, Io as isNotUndefined, Ir as never, It as TrueLiterals, J as toReadableStreamEffect, Ji as makeDieReason, Jn as acquireRelease, Jo as dual, Jr as runSync, Jt as isNonEmpty, K as suspend$1, Ka as make$21, Ki as isDieReason, Kn as join$2, Ko as constVoid, Kr as runForkWith, Kt as fromJsonString, L as merge$1, La as succeed$1, Li as succeed$3, Ln as failCauseUnsafe, Lo as isNullish, Lr as onError, Lt as URL$2, M as fromChannel$1, Ma as getOrThrow, Mi as isDoneUnsafe, Mn as stringOrRedacted, Mo as hasProperty, Mr as mapError, Mt as Struct, N as fromPull, Na as isFailure$1, Ni as makeUnsafe, Nn as fromSetCookie, No as isFunction, Nr as match$2, Nt as TaggedError$1, O as empty$4, Oa as getSomes, Oi as _await, On as setAll, Oo as Class, Or as isEffect, Ot as Record, P as fromReadableStream, Pi as fail$3, Pn as bytes, Po as isNotNull, Pr as matchCauseEffect, Pt as TaggedUnion, Q as mapDone, Qi as ClockRef, Qn as as, Qo as pipe, Qr as sleep, Qt as optionalKey, R as mkArrayBuffer, Ra as try_$1, Ri as void_, Rn as make$20, Ro as isObjectKeyword, Rr as onExit, Rt as Union, Si as Scope, Sn as fromInput$1, So as Prototype, Sr as forkScoped, St as NullOr, T as catchReason$1, Ta as sort, Ti as close, Tn as merge$2, To as getStackTraceLimit, Tr as ignore, Tt as OptionFromOptionalKey, U as runDrain, Ua as get$3, Ui as fromReasons, Un as take, Uo as ownEnumerableKeys, Ur as provideService, Ut as decodeUnknownOption, V as run$3, Va as add, Vi as done, Vn as poll, Vo as isUndefined, Vr as provide$2, Vt as decodeEffect, Wa as getOrUndefined, Wi as hasInterrupts, Wn as getCurrent, Wo as constFalse, Wr as raceFirst, Wt as decodeUnknownSync, X as unwrap$4, Xa as exists, Xi as reasonAnnotations, Xn as all$1, Xo as identity, Xr as scoped, Xt as makeFilter, Y as transduce, Ya as contains, Yi as makeFailReason, Yn as addFinalizer$1, Yo as flow, Yr as scope, Yt as make$17, Z as fromTransform$1, Za as filter, Zi as squash, Zn as andThen, Zo as memoize, Zr as serviceOption, Zt as optional$3, _i as effect, _n as toString, _o as some, _r as flatMapEager, _t as Finite, a as CliSignInStart, aa as DisablePropagation, ai as try_, an as getIndexSignatureKeys, ao as getOrElse, ar as catchReason, b as isHttpMethod, ba as map$8, bi as provideMerge, bn as CurrentRedactedNames$1, bo as String$6, br as forever, bt as Literals$2, ca as taggedEnum, ci as updateContext, cn as Transformation, co as getOrUndefined$1, cr as catch_, da as toMillis, di as withFiber, dn as Pointer, do as liftPredicate, dr as effectify, dt as ArraySchema, ea as LogToStderr$1, ei as suspend, en as toCodecJson, er as callback, et as unwrap$3, fa as empty$5, fi as withParentSpan, fn as CurrentRedactedNames, fo as liftThrowable, fr as ensuring, ft as Boolean$3, gi as round, gn as setAll$1, go as orElse, gr as flatMap$1, gt as FalseLiterals, h as SANDCOVERY_ORIGIN, ha as findLast, hi as isDoneCause, hn as redactUrl, ho as none, hr as failSync, ht as Error$2, i as SandcoveryApi, ia as TracerTimingEnabled$1, ii as tryPromise, in as decodeTo, io as fromUndefinedOr, ir as catchIf, ja as fail$1, ji as isDone, jn as value, jo as redact, jr as mapEager, jt as String$7, k as ensuring$1, ka as map$9, ki as doneUnsafe, kn as isRedacted, ko as NodeInspectSymbol, kr as logError, kt as RedactedFromValue, la as fromInputUnsafe, li as useSpan, ln as passthrough, lo as isNone, lr as context, ma as findFirstIndex, mi as catchDone, mn as fromInput, mo as match, mr as failCause, mt as Defect, n as call, na as MinimumLogLevel$1, ni as tap, nn as decodeUnknownEffect, no as fromNullOr, nr as catchEager, o as CliSignInToken, oa as Error$1, oi as uninterruptible, on as toEncoded, oo as getOrNull, or as catchTag, ot as make$19, p as Process, pa as findFirst, pi as zipWith, pn as empty$2, po as map$7, pr as fail, pt as BooleanLiterals, q as tapError, qa as merge, qi as isFailReason, qn as runIn, qo as constant, qt as is, r as read, ra as TracerEnabled$1, ri as tapCause, rn as applyToSelfOrLastLinkEncoding, ro as fromNullishOr, rr as catchFilter, sa as TaggedError, si as uninterruptibleMask, sn as unknown, so as getOrThrowWith, sr as catchTags, ta as sync$1, ti as sync, tn as toCodecStringTree, to as flatten, tr as catchCause, ua as isFinite, ui as void_$1, un as transformEffect, uo as isSome, ur as contextWith, ut as makeUnsafe$2, v as fromApi, va as isCanonicalArrayIndex, vi as mergeAll, vn as fromBody, vo as toArray, vr as fnUntraced, vt as Json, w as callback$1, wa as reduce, wi as addFinalizerExit, wn as isRedactedName, wo as withFiber$1, wr as gen, x as AgentId, xa as match$1, xi as succeed$4, xn as empty$3, xo as mapInput, xr as forkChild, y as allShort, ya as isReadonlyArrayNonEmpty, yi as provide$1, yn as unwrap$5, yr as forEach$1, yt as Literal, z as mkString, za as Reference, zi as Done, zn as offer, zo as isString, zr as onInterrupt, zt as Unknown } from "../src-DjOLw-ft.mjs";
3
- import { c as exhaustive, d as value$1, r as follow, t as quoted, u as tag$1 } from "../sync-rEFjHNC4.mjs";
4
- import { r as onPath } from "../kubectl-Ck04daor.mjs";
5
- import { a as Credentials, c as credentialsFileOf, d as storedKey, f as writePrivateFile, l as startTool, u as stopSignalOf, w as noop } from "../saved-sandboxes-BMjkAVGx.mjs";
2
+ import { $ as toTransform, $a as exists, $i as reasonAnnotations, $n as andThen, $o as identity, $r as scoped, $t as optionalKey, A as fail$2, Aa as get$4, Ai as provide, An as setAll, Ao as BaseProto, Ar as interrupt$1, At as SchemaError, B as mkUint8Array, Ba as succeed$1, Bi as succeed$3, Bn as make$20, Bo as isNullish, Br as onError, Bt as declare, Ca as map$8, Ci as provideMerge, Cn as empty$3, Co as String$6, Cr as forever, D as drainFork, Da as reduce, Di as addFinalizerExit, Dn as merge$2, Do as withFiber$1, Dr as gen, E as decodeText, Ea as of, Ei as addFinalizer, En as isRedactedName, Eo as PipeInspectableProto, Er as fromResult, F as interruptWhen, Fa as getOrThrow, Fi as isDoneUnsafe, Fn as fromSetCookie, Fo as hasProperty, Fr as mapError, Ft as Trim, G as splitLines, Ga as empty$6, Gi as fail$5, Gn as take, Go as assignProperty, Gr as provideContext, Gt as decodeUnknownSync, H as runCollect, Ha as Reference, Hi as Done, Hn as offerUnsafe, Ho as isString, Hr as onInterrupt, Ht as decodeTo$1, I as isStream, Ia as isFailure$1, Ii as makeUnsafe, In as bytes, Io as isFunction, Ir as match$2, It as TrueLiterals, J as toReadableStreamEffect, Ja as getUnsafe, Ji as hasInterruptsOnly, Jn as join$2, Jo as constTrue, Jr as runFork, Jt as is, K as suspend$1, Ka as get$3, Ki as fromReasons, Kn as getCurrent, Ko as ownEnumerableKeys, Kr as provideService, Kt as encodeSync, L as merge$1, Li as fail$3, Ln as fromInputUnsafe$1, Lo as isNotNull, Lr as matchCauseEffect, Lt as URL$2, M as fromChannel$1, Ma as map$9, Mi as doneUnsafe, Mn as make$18, Mo as NodeInspectSymbol, Mr as logError, Mt as Struct, N as fromPull, Na as all$2, Ni as fail$4, Nn as value, No as format, Nr as map$5, Nt as TaggedError$1, O as empty$4, Oa as sort, Oi as close, On as remove$1, Oo as getStackTraceLimit, Or as ignore, Ot as Record, P as fromReadableStream, Pa as fail$1, Pi as isDone, Pn as stringOrRedacted, Po as redact, Pr as mapEager, Pt as TaggedUnion, Q as mapDone, Qa as contains, Qi as makeFailReason, Qn as all$1, Qo as flow, Qr as scope, Qt as optional$3, R as mkArrayBuffer, Ra as isSuccess$1, Ri as isFailure, Rn as endUnsafe, Rr as matchEffect, Rt as Union, Sa as isReadonlyArrayNonEmpty, Si as provide$1, Sn as CurrentRedactedNames$1, Sr as forEach$1, St as NullOr, T as catchReason$1, Ti as Scope, Tn as fromRecordUnsafe, To as Prototype, Tr as forkScoped, Tt as OptionFromOptionalKey, U as runDrain, Ua as Service, Ui as UnknownError, Un as poll, Uo as isTagged, Ur as orDie, Ut as decodeUnknownEffect$1, V as run$3, Va as try_$1, Vi as void_, Vn as offer, Vo as isObjectKeyword, Vr as onExit, Vt as decodeEffect, Wa as add, Wi as done, Wn as sliding, Wo as isUndefined, Wr as provide$2, Wt as decodeUnknownOption, X as unwrap$4, Xa as merge, Xi as isFailReason, Xn as acquireRelease, Xo as constant, Xt as make$17, Y as transduce, Ya as make$21, Yi as isDieReason, Yn as runIn, Yo as constVoid, Yr as runForkWith, Yt as isNonEmpty, Z as fromTransform$1, Zi as makeDieReason, Zn as addFinalizer$1, Zo as dual, Zr as runSync, Zt as makeFilter, _ as isHttpMethod, _a as findFirstIndex, _i as catchDone, _n as redactUrl, _o as match, _r as failSync, _t as Finite, a as CliSignInStart, aa as MinimumLogLevel$1, ai as tap, an as decodeTo, ao as fromNullOr, ar as catchFilter, bi as effect, bn as fromBody, bo as some, br as fn, bt as Literals$2, ca as DisablePropagation, ci as try_, cn as unknown, co as getOrElse, cr as catchTag, da as taggedEnum, di as updateContext, dn as transformEffect, do as getOrUndefined$1, dr as context, dt as ArraySchema, ea as squash, ei as serviceOption, en as tag, eo as filter, er as as, es as memoize, et as unwrap$3, f as SANDCOVERY_ORIGIN, fa as fromInputUnsafe, fi as useSpan, fn as InvalidValue$1, fo as isNone, fr as contextWith, ft as Boolean$3, g as allShort, ga as findFirst, gi as zipWith, gn as fromInput, go as map$7, gr as failCause, gt as FalseLiterals, h as fromApi, ha as empty$5, hi as withParentSpan, hn as empty$2, ho as liftThrowable, hr as fail, ht as Error$2, i as SandcoveryApi, ia as sync$1, ii as sync, in as applyToSelfOrLastLinkEncoding, io as flatten, ir as catchEager, ja as getSomes, ji as _await, jn as isRedacted, jo as Class, jr as isEffect, jt as String$7, k as ensuring$1, ka as fromIterableWith, ki as makeUnsafe$1, kn as set, ko as setStackTraceLimit, kr as ignoreCause, kt as RedactedFromValue, la as Error$1, li as uninterruptible, ln as Transformation, lo as getOrNull, lr as catchTags, ma as toMillis, mi as withFiber, mn as CurrentRedactedNames, mo as liftPredicate, mr as ensuring, mt as Defect, n as call, na as ConsoleRef, ni as succeed$2, nn as toCodecStringTree, no as flatMap$2, nr as callback, ns as pipeArguments, o as CliSignInToken, oa as TracerEnabled$1, oi as tapCause, on as getIndexSignatureKeys, oo as fromNullishOr, or as catchIf, ot as make$19, pa as isFinite, pi as void_$1, pn as Pointer, po as isSome, pr as effectify, pt as BooleanLiterals, q as tapError, qa as getOrUndefined, qi as hasInterrupts, qn as interrupt, qo as constFalse, qr as raceFirst, qt as fromJsonString, r as read, ra as LogToStderr$1, ri as suspend, rn as decodeUnknownEffect, rr as catchCause, sa as TracerTimingEnabled$1, si as tryPromise, sn as toEncoded, so as fromUndefinedOr, sr as catchReason, ta as ClockRef, ti as sleep, tn as toCodecJson, tr as cached, ts as pipe, ua as TaggedError, ui as uninterruptibleMask, un as passthrough, uo as getOrThrowWith, ur as catch_, ut as makeUnsafe$2, va as findLast, vi as isDoneCause, vn as setAll$1, vo as none, vr as flatMap$1, vt as Json, w as callback$1, wa as match$1, wi as succeed$4, wn as fromInput$1, wo as mapInput, wr as forkChild, x as AgentId, xa as isCanonicalArrayIndex, xi as mergeAll, xn as unwrap$5, xo as toArray, xr as fnUntraced, y as Process, yi as round, yn as toString, yo as orElse, yr as flatMapEager, yt as Literal, z as mkString, za as map$6, zi as isSuccess, zn as failCauseUnsafe, zo as isNotUndefined, zr as never, zt as Unknown } from "../src-Ce-b80jJ.mjs";
3
+ import { c as exhaustive, d as value$1, r as follow, t as quoted, u as tag$1 } from "../sync-KX0CReEd.mjs";
4
+ import { r as onPath } from "../kubectl-BZIzN5z0.mjs";
5
+ import { a as Credentials, c as credentialsFileOf, d as storedKey, f as writePrivateFile, l as startTool, u as stopSignalOf, w as noop } from "../saved-sandboxes-XNeQ5SEm.mjs";
6
6
  import http from "node:http";
7
7
  import * as OS from "node:os";
8
8
  import os, { constants } from "node:os";
@@ -14242,7 +14242,31 @@ const parameterFields = (document, operation, part) => (operation.parameters ??
14242
14242
  optional: parameter.required !== true,
14243
14243
  text: true
14244
14244
  }] : []);
14245
- const json = fromJsonString(Json);
14245
+ const FETCH_LIMIT_SECONDS = 300;
14246
+ const ANSWER_MARGIN_SECONDS = 60;
14247
+ const answerWaitSeconds = (seconds) => Math.max(FETCH_LIMIT_SECONDS, seconds + ANSWER_MARGIN_SECONDS);
14248
+ const outsideCwd = new InvalidValue$1({ expected: "a JSON value or @path under the current directory" });
14249
+ const unreadableFile = new InvalidValue$1({ expected: "a readable JSON file" });
14250
+ const readJsonFile = fn("readJsonFile")(function* (input) {
14251
+ const path = yield* Path$1;
14252
+ const fileSystem = yield* FileSystem;
14253
+ const root = yield* fileSystem.realPath(".").pipe(mapError(() => unreadableFile));
14254
+ const file = yield* match(path.resolveWithin(root, input), {
14255
+ onNone: () => fail(outsideCwd),
14256
+ onSome: (candidate) => fileSystem.realPath(candidate).pipe(mapError(() => unreadableFile))
14257
+ });
14258
+ return yield* match(path.resolveWithin(root, path.relative(root, file)), {
14259
+ onNone: () => fail(outsideCwd),
14260
+ onSome: (inside) => fileSystem.readFileString(inside).pipe(mapError(() => unreadableFile))
14261
+ });
14262
+ });
14263
+ const json = String$7.pipe(decodeTo$1(fromJsonString(Json), {
14264
+ decode: transformEffect((value) => match(liftPredicate(value, (flag) => flag.startsWith("@")), {
14265
+ onNone: () => succeed$2(value),
14266
+ onSome: (flag) => readJsonFile(flag.slice(1))
14267
+ })),
14268
+ encode: passthrough()
14269
+ }));
14246
14270
  const OTHER_ROUTE_SEGMENTS = /* @__PURE__ */ new Set([
14247
14271
  "",
14248
14272
  ".",
@@ -14276,7 +14300,10 @@ const endpointCommand = (document, { body, method, operation, path }, { argument
14276
14300
  }),
14277
14301
  form: textFlags(body._tag === "FormUrlEncoded" ? body.fields : []),
14278
14302
  headers: flagsOf(parameterFields(document, operation, "header"), (field) => withSchema(String$1(field.name), HeaderValue)),
14279
- json: flagsOf(body._tag === "Json" ? body.fields : [], (field) => field.text ? String$1(field.name) : withSchema(String$1(field.name), json)),
14303
+ json: flagsOf(body._tag === "Json" ? body.fields.map((field) => ({
14304
+ ...field,
14305
+ description: field.text ? field.description : [field.description, "Takes JSON or @path."].filter((part) => part !== "").join(" ")
14306
+ })) : [], (field) => field.text ? String$1(field.name) : withSchema(String$1(field.name), json)),
14280
14307
  media: flagsOf(media, (field) => Literals(field.name, contentTypes)),
14281
14308
  params: flagsOf(parameterFields(document, operation, "path").map((field) => ({
14282
14309
  ...field,
@@ -14389,14 +14416,12 @@ const apiCommand = (name, document, { pickers, verbs }) => {
14389
14416
  })]));
14390
14417
  };
14391
14418
  // ../cli-core/src/answer-wait.ts
14392
- const FETCH_LIMIT_SECONDS = 300;
14393
- const ANSWER_MARGIN_SECONDS = 60;
14394
14419
  const UNDICI_NO_LIMIT_MS = 0;
14395
14420
  const [FETCH_UNDICI_MAJOR] = (process.versions.undici ?? "").split(".");
14396
14421
  const GLOBAL_DISPATCHER = Symbol.for(`undici.globalDispatcher.${Number(FETCH_UNDICI_MAJOR) >= 8 ? "2" : "1"}`);
14397
14422
  const decodeGlobalDispatcher = decodeUnknownSync(Struct({ [GLOBAL_DISPATCHER]: declare((input) => hasProperty(input, "dispatch") && isFunction(input.dispatch)) }));
14398
14423
  const answeredWithin = (seconds) => {
14399
- const limit = Number.isFinite(seconds) ? Math.max(FETCH_LIMIT_SECONDS, seconds + ANSWER_MARGIN_SECONDS) * 1e3 : UNDICI_NO_LIMIT_MS;
14424
+ const limit = Number.isFinite(seconds) ? answerWaitSeconds(seconds) * 1e3 : UNDICI_NO_LIMIT_MS;
14400
14425
  const dispatcher = { dispatch: (options, handler) => decodeGlobalDispatcher(globalThis)[GLOBAL_DISPATCHER].dispatch({
14401
14426
  ...options,
14402
14427
  bodyTimeout: limit,
@@ -14477,7 +14502,7 @@ const runApiCli = ({ answerSeconds, name, origin, spec, storedToken, token, vers
14477
14502
  });
14478
14503
  };
14479
14504
  // package.json
14480
- var version = "0.9.0";
14505
+ var version = "0.10.0";
14481
14506
  // src/cli/commands/sign-in.ts
14482
14507
  const LOGIN_USAGE = `Usage: sandcovery login
14483
14508
 
@@ -14802,6 +14827,15 @@ if (isSome(local)) {
14802
14827
  const { timeout_seconds, ttl_seconds } = getOrElse(decodeWaits(json), () => NO_WAITS);
14803
14828
  const exec = timeout_seconds ?? 300;
14804
14829
  return (/* @__PURE__ */ new Map([
14830
+ ["agents.createAgent", PROVIDER_PACED_SECONDS],
14831
+ ["agents.deleteAgent", PROVIDER_PACED_SECONDS],
14832
+ ["agents.getAgentLogs", PROVIDER_PACED_SECONDS],
14833
+ ["agents.openAgentSession", PROVIDER_PACED_SECONDS],
14834
+ ["agents.openAgentSsh", PROVIDER_PACED_SECONDS],
14835
+ ["agents.openAgentWeb", PROVIDER_PACED_SECONDS],
14836
+ ["agents.restartAgent", PROVIDER_PACED_SECONDS],
14837
+ ["agents.startAgent", PROVIDER_PACED_SECONDS],
14838
+ ["agents.stopAgent", PROVIDER_PACED_SECONDS],
14805
14839
  ["sandboxes.createSandbox", (ttl_seconds ?? 3600) + 60],
14806
14840
  ["sandboxes.destroySandbox", PROVIDER_PACED_SECONDS],
14807
14841
  ["sandboxes.downloadFile", PROVIDER_PACED_SECONDS],
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { C as SandboxId, Ct as Number$1, Dt as ReadonlySet, Et as ReadonlyMap, Ja as all, Kt as fromJsonString, Mt as Struct, Ot as Record, Po as isNotNull, Qa as firstSomeOf, Qt as optionalKey, Rt as Union, Sa as matchLeft, St as NullOr, Ut as decodeUnknownOption, Xa as exists, Za as filter, _a as head, _o as some, ao as getOrElse, bt as Literals, c as ProviderError, ct as update, do as liftPredicate, dt as ArraySchema, eo as flatMapNullishOr, fo as liftThrowable, ft as Boolean$1, ga as get, ho as none, io as fromUndefinedOr, it as getAndSet, jt as String$1, lo as isNone, m as ProcessTerminal, mo as match, no as fromNullOr, nt as get$1, oo as getOrNull, ot as make, pa as findFirst, po as map, qt as is, ro as fromNullishOr, rt as getAndIncrement, so as getOrThrowWith, st as set, t as Sandcovery, u as NoProviderAvailable, uo as isSome, vo as toArray, wa as reduce, wt as Option, yo as zipWith, zo as isString, zt as Unknown } from "../src-DjOLw-ft.mjs";
3
- import { C as clamp, S as RELAY_ENV, _ as servedOrSpawned, f as writePrivateFile, g as servedAt, h as isTerminal, i as launchedRelay, l as startTool, m as READY, n as savedSandboxes, o as DESTROY_TIMEOUT_MS, p as v7, r as RELAY_PORT, s as createdSandbox, t as runningSandbox, v as socketOf, w as noop } from "../saved-sandboxes-BMjkAVGx.mjs";
4
- import { a as terminalOf, d as value, f as when, i as runAttached, l as orElse, m as __require, n as syncCommand, o as uniq, p as __commonJSMin, s as difference, t as quoted } from "../sync-rEFjHNC4.mjs";
2
+ import { $a as exists, $t as optionalKey, C as SandboxId, Ct as Number$1, Da as reduce, Dt as ReadonlySet, Et as ReadonlyMap, Ho as isString, Jt as is, Lo as isNotNull, Mt as Struct, Ot as Record, Rt as Union, So as zipWith, St as NullOr, Ta as matchLeft, Wt as decodeUnknownOption, Za as all, _o as match, ao as fromNullOr, b as ProcessTerminal, ba as head, bo as some, bt as Literals, c as ProviderError, co as getOrElse, ct as update, dt as ArraySchema, eo as filter, fo as isNone, ft as Boolean$1, ga as findFirst, go as map, ho as liftThrowable, it as getAndSet, jt as String$1, lo as getOrNull, mo as liftPredicate, nt as get$1, oo as fromNullishOr, ot as make, po as isSome, qt as fromJsonString, ro as flatMapNullishOr, rt as getAndIncrement, so as fromUndefinedOr, st as set, t as Sandcovery, to as firstSomeOf, u as NoProviderAvailable, uo as getOrThrowWith, vo as none, wt as Option, xo as toArray, ya as get, zt as Unknown } from "../src-Ce-b80jJ.mjs";
3
+ import { C as clamp, S as RELAY_ENV, _ as servedOrSpawned, f as writePrivateFile, g as servedAt, h as isTerminal, i as launchedRelay, l as startTool, m as READY, n as savedSandboxes, o as DESTROY_TIMEOUT_MS, p as v7, r as RELAY_PORT, s as createdSandbox, t as runningSandbox, v as socketOf, w as noop } from "../saved-sandboxes-XNeQ5SEm.mjs";
4
+ import { a as terminalOf, d as value, f as when, i as runAttached, l as orElse, m as __require, n as syncCommand, o as uniq, p as __commonJSMin, s as difference, t as quoted } from "../sync-KX0CReEd.mjs";
5
5
  import { WebSocket } from "node:http";
6
6
  import net from "node:net";
7
7
  import { randomBytes } from "node:crypto";
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { _o as some } from "../src-DjOLw-ft.mjs";
3
- import { a as watchIdle, i as IDLE_WATCHER_ENV, n as kubectlRun } from "../kubectl-Ck04daor.mjs";
4
- import { l as startTool } from "../saved-sandboxes-BMjkAVGx.mjs";
2
+ import { bo as some } from "../src-Ce-b80jJ.mjs";
3
+ import { a as watchIdle, i as IDLE_WATCHER_ENV, n as kubectlRun } from "../kubectl-BZIzN5z0.mjs";
4
+ import { l as startTool } from "../saved-sandboxes-XNeQ5SEm.mjs";
5
5
  // src/cli/sandcovery-kubectl.ts
6
6
  await startTool({
7
7
  run: kubectlRun,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { Kt as fromJsonString, Mt as Struct, Ut as decodeUnknownOption, Xa as exists, Xt as makeFilter, ho as none, io as fromUndefinedOr, lo as isNone, mo as match, oo as getOrNull, po as map, vo as toArray, xt as NonEmptyString } from "../src-DjOLw-ft.mjs";
3
- import { l as startTool, o as DESTROY_TIMEOUT_MS, s as createdSandbox, w as noop } from "../saved-sandboxes-BMjkAVGx.mjs";
4
- import { r as onPath, t as answers } from "../kubectl-Ck04daor.mjs";
2
+ import { $a as exists, Mt as Struct, Wt as decodeUnknownOption, Zt as makeFilter, _o as match, fo as isNone, go as map, lo as getOrNull, qt as fromJsonString, so as fromUndefinedOr, vo as none, xo as toArray, xt as NonEmptyString } from "../src-Ce-b80jJ.mjs";
3
+ import { l as startTool, o as DESTROY_TIMEOUT_MS, s as createdSandbox, w as noop } from "../saved-sandboxes-XNeQ5SEm.mjs";
4
+ import { r as onPath, t as answers } from "../kubectl-BZIzN5z0.mjs";
5
5
  import { spawn } from "node:child_process";
6
6
  import { once } from "node:events";
7
7
  import { parseArgs } from "node:util";
@@ -21,11 +21,19 @@ Creates a sandbox, installs the same version of T3 Code there as your local t3,
21
21
 
22
22
  It reads your key from SANDCOVERY_API_KEY, or from sandcovery login, and the API origin from SANDCOVERY_BASE_URL.
23
23
  `;
24
- const EXEC_TIMEOUT_SECONDS = 600;
24
+ const STEP_SECONDS = 20;
25
+ const POLL_SECONDS = 12;
26
+ const INSTALL_WAIT_MS = 6e5;
27
+ const SERVE_WAIT_MS = 12e4;
25
28
  const ANSWER_WAIT_MS = 12e4;
29
+ const STDERR_CHARACTERS = 2e3;
26
30
  const T3_HOME = "\"$HOME/.t3\"";
27
31
  const ON_PATH = "export PATH=\"$HOME/.local/bin:$PATH\"";
28
- const INSTALL_COMMAND = [
32
+ const INSTALL_STATUS = `${T3_HOME}/install.status`;
33
+ const INSTALL_LOG = `${T3_HOME}/install.log`;
34
+ const INSTALL_PID = `${T3_HOME}/install.pid`;
35
+ const INSTALL_RUNNING = `{ p=$(cat ${INSTALL_PID}) s=; kill -0 "$p" 2>/dev/null && { read -r _ _ s _ 2>/dev/null </proc/"$p"/stat; test "$s" != Z; }; }`;
36
+ const INSTALL_SCRIPT = [
29
37
  "set -e",
30
38
  ON_PATH,
31
39
  "curl -fsSL https://t3.codes/install.sh -o /tmp/t3-install.sh",
@@ -37,12 +45,27 @@ const INSTALL_COMMAND = [
37
45
  `mkdir -p ${T3_HOME}/userdata`,
38
46
  `printf '%s\\n' '{"linkedEnvironmentsEnabled":true}' >${T3_HOME}/userdata/settings.json`
39
47
  ].join("\n");
40
- const SERVE_COMMAND = [ON_PATH, `setsid t3 serve --host 0.0.0.0 --port ${String(T3_PORT)} --base-dir ${T3_HOME} --no-browser </dev/null >>${T3_HOME}/serve.log 2>&1 &`].join("\n");
41
- const PAIR_COMMAND = [
42
- ON_PATH,
43
- `for _ in $(seq 60); do curl -fsS -m 5 -o /dev/null http://127.0.0.1:${String(T3_PORT)}/.well-known/t3/environment && break; sleep 1; done`,
44
- `t3 auth pairing create --base-dir ${T3_HOME} --json --ttl 10m --label sandcovery`
48
+ const INSTALL_COMMAND = [
49
+ `mkdir -p ${T3_HOME}`,
50
+ `rm -f ${INSTALL_STATUS}`,
51
+ `cat >${T3_HOME}/install.sh <<'T3_INSTALL'`,
52
+ INSTALL_SCRIPT,
53
+ "T3_INSTALL",
54
+ `$(command -v setsid) nohup sh -c 'sh ${T3_HOME}/install.sh >${INSTALL_LOG} 2>&1; echo $? >${T3_HOME}/install.code; mv ${T3_HOME}/install.code ${INSTALL_STATUS}' </dev/null >/dev/null 2>&1 &`,
55
+ `echo $! >${INSTALL_PID}`
45
56
  ].join("\n");
57
+ const INSTALL_POLL_COMMAND = [
58
+ `for _ in $(seq ${String(POLL_SECONDS)}); do test -s ${INSTALL_STATUS} && break; ${INSTALL_RUNNING} || break; sleep 1; done`,
59
+ `tail -c ${String(STDERR_CHARACTERS)} ${INSTALL_LOG} >&2`,
60
+ `if test -s ${INSTALL_STATUS}; then cat ${INSTALL_STATUS}; elif ${INSTALL_RUNNING}; then :; elif test -s ${INSTALL_STATUS}; then cat ${INSTALL_STATUS}; else echo stopped; fi`
61
+ ].join("\n");
62
+ const SERVE_COMMAND = [ON_PATH, `$(command -v setsid) nohup t3 serve --host 0.0.0.0 --port ${String(T3_PORT)} --base-dir ${T3_HOME} --no-browser </dev/null >>${T3_HOME}/serve.log 2>&1 &`].join("\n");
63
+ const SERVED_POLL_COMMAND = [
64
+ `end=$(($(date +%s) + ${String(POLL_SECONDS)}))`,
65
+ `until curl -fsS -m 2 -o /dev/null http://127.0.0.1:${String(T3_PORT)}/.well-known/t3/environment; do test "$(date +%s)" -lt "$end" || { tail -c ${String(STDERR_CHARACTERS)} ${T3_HOME}/serve.log >&2; exit 0; }; sleep 1; done`,
66
+ "echo served"
67
+ ].join("\n");
68
+ const PAIR_COMMAND = [ON_PATH, `t3 auth pairing create --base-dir ${T3_HOME} --json --ttl 10m --label sandcovery`].join("\n");
46
69
  const decodePairing = decodeUnknownOption(fromJsonString(Struct({ credential: NonEmptyString.check(makeFilter((credential) => !credential.includes("\n"))) })));
47
70
  const providerOf = (sandbox) => sandbox.provider ?? "its provider";
48
71
  const ranT3 = async ({ args, input, signal, t3 }) => {
@@ -72,10 +95,27 @@ const ranInSandbox = async ({ command, env, sandbox, step, tool }) => {
72
95
  command,
73
96
  env,
74
97
  cwd: null,
75
- timeout_seconds: EXEC_TIMEOUT_SECONDS
98
+ timeout_seconds: STEP_SECONDS
76
99
  }, { signal: tool.signal });
77
100
  if (result.exit_code !== 0) throw new Error(`Can't ${VERB}. Couldn't ${step} in sandbox ${sandbox.id} on ${providerOf(sandbox)}, so Sandcovery destroyed it.`, { cause: result.stderr.slice(-2e3) });
78
- return result.stdout;
101
+ return result;
102
+ };
103
+ const awaited = async ({ command, deadline, sandbox, step, tool }) => {
104
+ const result = await ranInSandbox({
105
+ env: null,
106
+ command,
107
+ sandbox,
108
+ step,
109
+ tool
110
+ });
111
+ if (result.stdout.trim() !== "" || Date.now() > deadline) return result;
112
+ return await awaited({
113
+ command,
114
+ deadline,
115
+ sandbox,
116
+ step,
117
+ tool
118
+ });
79
119
  };
80
120
  const linked = async ({ access, env, sandbox, t3, tool, version }) => {
81
121
  const preview = await tool.client.sandboxes.portPreview(sandbox.id, T3_PORT, { signal: tool.signal });
@@ -86,10 +126,19 @@ const linked = async ({ access, env, sandbox, t3, tool, version }) => {
86
126
  await ranInSandbox({
87
127
  command: INSTALL_COMMAND,
88
128
  env: { T3CODE_VERSION: version },
89
- step: `install T3 Code ${version}`,
129
+ step: `start installing T3 Code ${version}`,
130
+ sandbox,
131
+ tool
132
+ });
133
+ const installed = await awaited({
134
+ command: INSTALL_POLL_COMMAND,
135
+ deadline: Date.now() + INSTALL_WAIT_MS,
136
+ step: `check on the T3 Code ${version} install`,
90
137
  sandbox,
91
138
  tool
92
139
  });
140
+ if (installed.stdout.trim() === "") throw new Error(`Can't ${VERB}. T3 Code ${version} didn't finish installing in sandbox ${sandbox.id} on ${providerOf(sandbox)} within 10 minutes, so Sandcovery destroyed it.`, { cause: installed.stderr });
141
+ if (installed.stdout.trim() !== "0") throw new Error(`Can't ${VERB}. Couldn't install T3 Code ${version} in sandbox ${sandbox.id} on ${providerOf(sandbox)}, so Sandcovery destroyed it.`, { cause: installed.stderr });
93
142
  await ranInSandbox({
94
143
  command: SERVE_COMMAND,
95
144
  step: "start T3 Code",
@@ -97,6 +146,14 @@ const linked = async ({ access, env, sandbox, t3, tool, version }) => {
97
146
  sandbox,
98
147
  tool
99
148
  });
149
+ const served = await awaited({
150
+ command: SERVED_POLL_COMMAND,
151
+ deadline: Date.now() + SERVE_WAIT_MS,
152
+ step: "check that T3 Code serves",
153
+ sandbox,
154
+ tool
155
+ });
156
+ if (served.stdout.trim() === "") throw new Error(`Can't ${VERB}. T3 Code ${version} didn't start serving in sandbox ${sandbox.id} on ${providerOf(sandbox)} within 2 minutes, so Sandcovery destroyed it.`, { cause: served.stderr });
100
157
  const paired = await ranInSandbox({
101
158
  command: PAIR_COMMAND,
102
159
  env: null,
@@ -104,7 +161,7 @@ const linked = async ({ access, env, sandbox, t3, tool, version }) => {
104
161
  sandbox,
105
162
  tool
106
163
  });
107
- const pairing = decodePairing(paired.trim());
164
+ const pairing = decodePairing(paired.stdout.trim());
108
165
  if (isNone(pairing)) throw new Error(`Can't ${VERB}. T3 Code in sandbox ${sandbox.id} on ${providerOf(sandbox)} gave no pairing code, so Sandcovery destroyed it.`);
109
166
  if (!await answers({
110
167
  deadline: Date.now() + ANSWER_WAIT_MS,