sandcovery 0.10.0 → 0.12.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,9 +1,11 @@
1
1
  #!/usr/bin/env node
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
- import http from "node:http";
2
+ import { $ as toTransform, $a as add, $i as fail$5, $n as take, $o as assignProperty, $r as provideContext, $t as is, A as empty$4, Aa as isReadonlyArrayNonEmpty, Ai as provide$1, An as CurrentRedactedNames$1, Ar as forEach$1, B as mkString, Ba as map$9, Bi as doneUnsafe, Bn as make$18, Bo as NodeInspectSymbol, Br as logError, Bt as TrueLiterals, C as AgentId, Ca as empty$5, Ci as withParentSpan, Cn as empty$2, Co as liftThrowable, Cr as fail, Ct as NonEmptyString, D as catchReason$1, Di as round, Dn as toString, Do as orElse, Dr as flatMapEager, Dt as OptionFromOptional, E as callback$1, Ea as findLast, Ei as isDoneCause, En as setAll$1, Eo as none, Er as flatMap$1, F as fromReadableStream, Fa as reduce, Fi as addFinalizerExit, Fn as merge$2, Fo as withFiber$1, Fr as gen, Ft as String$7, G as splitLines, Gi as fail$3, Gn as fromInputUnsafe$1, Go as isNotNull, Gr as matchCauseEffect, Gt as declare, H as run$3, Ha as fail$1, Hi as isDone, Hn as stringOrRedacted, Ho as redact, Hr as mapEager, Ht as URL$2, I as interruptWhen, Ia as sort, Ii as close, In as remove$1, Io as getStackTraceLimit, Ir as ignore, It as Struct, J as toReadableStreamEffect, Ji as succeed$3, Jn as make$20, Jo as isNullish, Jr as onError, Jt as decodeUnknownEffect$1, K as suspend$1, Ka as isSuccess$1, Ki as isFailure, Kn as endUnsafe, Kr as matchEffect, Kt as decodeEffect, L as isStream, La as fromIterableWith, Li as makeUnsafe$1, Ln as set, Lo as setStackTraceLimit, Lr as ignoreCause, Lt as TaggedError$1, M as fail$2, Ma as match$1, Mi as succeed$4, Mn as fromInput$1, Mo as mapInput, Mr as forkChild, Mt as Record, N as fromChannel$1, Ni as Scope, Nn as fromRecordUnsafe, No as Prototype, Nr as forkScoped, Nt as RedactedFromValue, O as decodeText, Oa as head, Oi as effect, On as fromBody, Oo as some, Or as fn, Ot as OptionFromOptionalKey, P as fromPull, Pa as of, Pi as addFinalizer, Pn as isRedactedName, Po as PipeInspectableProto, Pr as fromResult, Pt as SchemaError, Q as mapDone, Qa as Service, Qi as done, Qn as sliding, Qo as isUndefined, Qr as provide$2, Qt as fromJsonString, R as merge$1, Ra as get$4, Ri as provide, Rn as setAll, Ro as BaseProto, Rr as interrupt$1, Rt as TaggedUnion, Sa as toMillis, Si as withFiber, Sn as CurrentRedactedNames, So as liftPredicate, Sr as ensuring, St as NonEmptyArray, Ta as findFirstIndex, Ti as catchDone, Tn as redactUrl, To as match, Tr as failSync, Tt as Number$2, U as runCollect, Ua as getOrThrow, Ui as isDoneUnsafe, Un as fromSetCookie, Uo as hasProperty, Ur as mapError, Ut as Union, V as mkUint8Array, Va as all$2, Vi as fail$4, Vn as value, Vo as format, Vr as map$5, Vt as Tuple, W as runDrain, Wa as isFailure$1, Wi as makeUnsafe, Wn as bytes, Wo as isFunction, Wr as match$2, Wt as Unknown, X as unwrap$4, Xa as try_$1, Xi as Done, Xn as offerUnsafe, Xo as isString, Xr as onInterrupt, Xt as decodeUnknownSync, Y as transduce, Ya as succeed$1, Yi as void_, Yn as offer, Yo as isObjectKeyword, Yr as onExit, Yt as decodeUnknownOption, Z as fromTransform$1, Za as Reference, Zi as UnknownError, Zn as poll, Zo as isTagged, Zr as orDie, Zt as encodeSync, _ as fromApi, _a as Error$1, _i as uninterruptible, _n as Transformation, _o as getOrNull, _r as catchTags, _t as Finite, a as SandcoveryApi, aa as makeDieReason, ai as runSync, an as optional$3, ao as merge, ar as addFinalizer$1, as as dual, ba as fromInputUnsafe, bi as useSpan, bn as InvalidValue$1, bo as isNone, br as contextWith, bt as Literal, ca as squash, ci as serviceOption, cn as toCodecJson, co as exists, cr as as, cs as memoize, da as LogToStderr$1, di as suspend, dn as decodeUnknownEffect, do as flatMap$2, dr as catchCause, dt as ArraySchema, ea as fromReasons, ei as provideService, en as isGreaterThan, eo as empty$6, er as getCurrent, es as ownEnumerableKeys, et as unwrap$3, fa as sync$1, fi as sync, fn as applyToSelfOrLastLinkEncoding, fo as flatten, fr as catchEager, ft as Boolean$3, ga as DisablePropagation, gi as try_, gn as unknown, go as getOrElse, gr as catchTag, gt as FalseLiterals, ha as TracerTimingEnabled$1, hi as tryPromise, hn as toEncoded, ho as fromUndefinedOr, hr as catchReason, ht as Error$2, ia as isFailReason, in as makeFilter, io as make$21, ir as acquireRelease, is as constant, j as ensuring$1, ja as map$8, ji as provideMerge, jn as empty$3, jo as String$6, jr as forever, k as drainFork, ka as isCanonicalArrayIndex, ki as mergeAll, kn as unwrap$5, ko as toArray, kr as fnUntraced, kt as OptionFromOptionalNullOr, la as ClockRef, li as sleep, ln as toCodecStringTree, lo as filter, lr as cached, ls as pipe, m as SANDCOVERY_ORIGIN, ma as TracerEnabled$1, mi as tapCause, mn as getIndexSignatureKeys, mo as fromNullishOr, mr as catchIf, mt as Defect, na as hasInterruptsOnly, ni as runFork, nn as isStartingWith, no as getOrUndefined, nr as join$2, ns as constTrue, nt as get$5, oa as makeFailReason, oi as scope, on as optionalKey, or as all$1, os as flow, ot as make$19, p as API_PREFIX, pa as MinimumLogLevel$1, pi as tap, pn as decodeTo, po as fromNullOr, pr as catchFilter, pt as BooleanLiterals, q as tapError, qa as map$6, qi as isSuccess, qn as failCauseUnsafe, qo as isNotUndefined, qr as never, qt as decodeTo$1, r as read, ra as isDieReason, ri as runForkWith, rn as make$17, ro as getUnsafe, rr as runIn, rs as constVoid, sa as reasonAnnotations, si as scoped, sn as tag, so as contains, sr as andThen, ss as identity, st as set$1, ta as hasInterrupts, ti as raceFirst, tn as isNonEmpty, to as get$3, tr as interrupt, ts as constFalse, ua as ConsoleRef, ui as succeed$2, ur as callback, us as pipeArguments, ut as makeUnsafe$2, v as allShort, va as TaggedError, vi as uninterruptibleMask, vn as passthrough, vo as getOrThrowWith, vr as catch_, vt as Int$1, wa as findFirst, wi as zipWith, wn as fromInput, wo as map$7, wr as failCause, wt as NullOr, x as Process, xa as isFinite, xi as void_$1, xn as Pointer, xo as isSome, xr as effectify, xt as Literals$2, y as isHttpMethod, ya as taggedEnum, yi as updateContext, yn as transformEffect, yo as getOrUndefined$1, yr as context, yt as Json, z as mkArrayBuffer, za as getSomes, zi as _await, zn as isRedacted, zo as Class, zr as isEffect, zt as Trim } from "../src-qykrguUO.mjs";
3
+ import { a as value$1, i as tag$1, n as orElse$1, o as when, r as string, t as exhaustive } from "../Match-B1Ad5u7a.mjs";
4
+ import { r as onPath } from "../kubectl-CDaJnlvo.mjs";
5
+ import { a as follow, t as quoted } from "../sync-D1IG3FDD.mjs";
6
+ import { i as chunk, n as logoutRun, r as signIn, t as loginRun } from "../sign-in-Cxjwe2Xs.mjs";
7
+ import { E as noop, T as clamp, _ as stopSignalOf, b as v7, g as startTool, h as credentialsFileOf, v as storedKey } from "../saved-sandboxes-D_mgmx4a.mjs";
8
+ import http, { WebSocket } from "node:http";
7
9
  import * as OS from "node:os";
8
10
  import os, { constants } from "node:os";
9
11
  import * as NodeChildProcess from "node:child_process";
@@ -13,8 +15,10 @@ import "node:string_decoder";
13
15
  import * as Crypto from "node:crypto";
14
16
  import fs, * as NFS from "node:fs";
15
17
  import path, * as Path from "node:path";
18
+ import { buffer } from "node:stream/consumers";
16
19
  import * as NodeUrl from "node:url";
17
20
  import * as readline$1 from "node:readline";
21
+ import { once } from "node:events";
18
22
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
23
  import { parseArgs } from "node:util";
20
24
  // ../../node_modules/.pnpm/effect@4.1.5/node_modules/effect/dist/References.js
@@ -3187,6 +3191,28 @@ const make$8 = (impl) => Terminal.of({
3187
3191
  ...impl,
3188
3192
  [TypeId$11]: TypeId$11
3189
3193
  });
3194
+ // ../../node_modules/.pnpm/es-toolkit@1.53.2/node_modules/es-toolkit/dist/math/sumBy.mjs
3195
+ /**
3196
+ * Calculates the sum of an array of numbers when applying
3197
+ * the `getValue` function to each element.
3198
+ *
3199
+ * If the array is empty, this function returns `0`.
3200
+ *
3201
+ * @template T - The type of elements in the array.
3202
+ * @param items - An array to calculate the sum.
3203
+ * @param getValue - A function that selects a numeric value from each element.
3204
+ * It receives the element and its zero‑based index in the array.
3205
+ * @returns The sum of all the numbers as determined by the `getValue` function.
3206
+ *
3207
+ * @example
3208
+ * sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8
3209
+ * sumBy([], () => 1); // Returns: 0
3210
+ */
3211
+ function sumBy(items, getValue) {
3212
+ let result = 0;
3213
+ for (let i = 0; i < items.length; i++) result += getValue(items[i], i);
3214
+ return result;
3215
+ }
3190
3216
  // ../../node_modules/.pnpm/effect@4.1.5/node_modules/effect/dist/http/HttpBody.js
3191
3217
  const TypeId$10 = "~effect/http/HttpBody";
3192
3218
  var Proto$6 = class {
@@ -3280,8 +3306,8 @@ var Uint8Array$1 = class extends Proto$6 {
3280
3306
  */
3281
3307
  const uint8Array = (body, contentType) => new Uint8Array$1(body, contentType ?? "application/octet-stream", body.length);
3282
3308
  const encoder$1 = /*#__PURE__*/ new TextEncoder();
3283
- const buffer = globalThis.Buffer;
3284
- const encodeText = buffer !== void 0 ? (body) => buffer.from(body, "utf8") : (body) => encoder$1.encode(body);
3309
+ const buffer$1 = globalThis.Buffer;
3310
+ const encodeText = buffer$1 !== void 0 ? (body) => buffer$1.from(body, "utf8") : (body) => encoder$1.encode(body);
3285
3311
  /**
3286
3312
  * Creates a UTF-8 encoded text HTTP body.
3287
3313
  *
@@ -3293,9 +3319,9 @@ const encodeText = buffer !== void 0 ? (body) => buffer.from(body, "utf8") : (bo
3293
3319
  * @category constructors
3294
3320
  * @since 4.0.0
3295
3321
  */
3296
- const text = (body, contentType) => {
3322
+ const text$1 = (body, contentType) => {
3297
3323
  if (typeof body !== "string") body = body === void 0 ? "" : String(body);
3298
- if (buffer !== void 0) return new Uint8Array$1(void 0, contentType ?? "text/plain", buffer.byteLength(body, "utf8"), body);
3324
+ if (buffer$1 !== void 0) return new Uint8Array$1(void 0, contentType ?? "text/plain", buffer$1.byteLength(body, "utf8"), body);
3299
3325
  const bytes = encoder$1.encode(body);
3300
3326
  return new Uint8Array$1(bytes, contentType ?? "text/plain", bytes.length, body);
3301
3327
  };
@@ -3310,7 +3336,7 @@ const text = (body, contentType) => {
3310
3336
  * @category constructors
3311
3337
  * @since 4.0.0
3312
3338
  */
3313
- const jsonUnsafe = (body, contentType) => text(JSON.stringify(body), contentType ?? "application/json");
3339
+ const jsonUnsafe = (body, contentType) => text$1(JSON.stringify(body), contentType ?? "application/json");
3314
3340
  /**
3315
3341
  * Creates an `application/x-www-form-urlencoded` HTTP body from `UrlParams`.
3316
3342
  *
@@ -3318,7 +3344,7 @@ const jsonUnsafe = (body, contentType) => text(JSON.stringify(body), contentType
3318
3344
  * @category constructors
3319
3345
  * @since 4.0.0
3320
3346
  */
3321
- const urlParams = (urlParams, contentType) => text(toString(fromInput(urlParams)), contentType ?? "application/x-www-form-urlencoded");
3347
+ const urlParams = (urlParams, contentType) => text$1(toString(fromInput(urlParams)), contentType ?? "application/x-www-form-urlencoded");
3322
3348
  // ../../node_modules/.pnpm/effect@4.1.5/node_modules/effect/dist/http/HttpClientError.js
3323
3349
  /**
3324
3350
  * Typed failure model for Effect HTTP client operations.
@@ -8567,7 +8593,7 @@ const regExpGroups = {
8567
8593
  5: (opts) => new Meridiem(opts),
8568
8594
  6: (opts) => new Hours(opts),
8569
8595
  7: (opts) => new Minutes(opts),
8570
- 8: (opts) => new Seconds(opts),
8596
+ 8: (opts) => new Seconds$1(opts),
8571
8597
  9: (opts) => new Milliseconds(opts)
8572
8598
  };
8573
8599
  const makeDateParts = (dateMask, date, locales) => {
@@ -8663,7 +8689,7 @@ var Milliseconds = class extends DatePart {
8663
8689
  return `${this.date.getMilliseconds()}`.padStart(4, "0").substring(0, this.token.length);
8664
8690
  }
8665
8691
  };
8666
- var Seconds = class extends DatePart {
8692
+ var Seconds$1 = class extends DatePart {
8667
8693
  increment() {
8668
8694
  this.date.setSeconds(this.date.getSeconds() + 1);
8669
8695
  }
@@ -14125,6 +14151,7 @@ const runWith = (command, config) => {
14125
14151
  }, ({ error, userMessage }) => andThen(showUserError(error, userMessage), fail(error))), catchFilter((e) => isQuitError(e) ? succeed$1(e) : fail$1(e), (_) => interrupt$1));
14126
14152
  };
14127
14153
  // ../cli-core/src/api-command.ts
14154
+ const OPERATION_ID_SEGMENTS = 2;
14128
14155
  var ApiAnswered = class extends TaggedError("ApiAnswered") {
14129
14156
  [errorReported] = false;
14130
14157
  };
@@ -14132,18 +14159,18 @@ const ApiOperation = Service("@coveries/cli-core/ApiOperation");
14132
14159
  const FIELD_BODIES = /* @__PURE__ */ new Map([["application/json", "Json"], ["application/x-www-form-urlencoded", "FormUrlEncoded"]]);
14133
14160
  const JsonNode = Struct({
14134
14161
  $ref: OptionFromOptionalKey(String$7),
14135
- additionalProperties: optionalKey(Json),
14162
+ additionalProperties: OptionFromOptionalKey(Json),
14136
14163
  anyOf: OptionFromOptionalKey(ArraySchema(Json)),
14137
14164
  const: OptionFromOptionalKey(Json),
14138
- description: optionalKey(String$7),
14165
+ description: OptionFromOptionalKey(String$7),
14139
14166
  enum: OptionFromOptionalKey(ArraySchema(Json)),
14140
- patternProperties: optionalKey(Record(String$7, Json)),
14141
- properties: optionalKey(Record(String$7, Json)),
14142
- required: optionalKey(ArraySchema(String$7)),
14143
- type: optionalKey(Json)
14167
+ patternProperties: OptionFromOptionalKey(Record(String$7, Json)),
14168
+ properties: OptionFromOptionalKey(Record(String$7, Json)),
14169
+ required: OptionFromOptionalKey(ArraySchema(String$7)),
14170
+ type: OptionFromOptionalKey(Json)
14144
14171
  });
14145
14172
  const Parameter = Struct({
14146
- description: optional$3(String$7),
14173
+ description: OptionFromOptional(String$7),
14147
14174
  in: Literals$2([
14148
14175
  "cookie",
14149
14176
  "header",
@@ -14151,23 +14178,23 @@ const Parameter = Struct({
14151
14178
  "query"
14152
14179
  ]),
14153
14180
  name: String$7,
14154
- required: optional$3(Boolean$3),
14155
- schema: optional$3(Json)
14181
+ required: OptionFromOptional(Boolean$3),
14182
+ schema: OptionFromOptionalNullOr(Json)
14156
14183
  });
14157
14184
  const OperationSchema = Struct({
14158
- description: optional$3(String$7),
14185
+ description: OptionFromOptional(String$7),
14159
14186
  operationId: String$7,
14160
- parameters: optional$3(ArraySchema(Parameter)),
14161
- requestBody: optional$3(Struct({ content: Record(String$7, Struct({ schema: optional$3(Json) })) })),
14162
- summary: optional$3(String$7),
14163
- tags: optional$3(ArraySchema(String$7))
14187
+ parameters: OptionFromOptional(ArraySchema(Parameter)),
14188
+ requestBody: OptionFromOptional(Struct({ content: Record(String$7, Struct({ schema: OptionFromOptionalNullOr(Json) })) })),
14189
+ summary: OptionFromOptional(String$7),
14190
+ tags: OptionFromOptional(ArraySchema(String$7))
14164
14191
  });
14165
14192
  const ApiDocumentSchema = Struct({
14166
- components: optional$3(Struct({ schemas: optional$3(Record(String$7, Json)) })),
14167
- info: optional$3(Struct({ description: optional$3(String$7) })),
14193
+ components: OptionFromOptional(Struct({ schemas: OptionFromOptional(Record(String$7, Json)) })),
14194
+ info: OptionFromOptional(Struct({ description: OptionFromOptional(String$7) })),
14168
14195
  paths: Record(String$7, Record(String$7, Unknown)),
14169
- tags: optional$3(ArraySchema(Struct({
14170
- description: optional$3(String$7),
14196
+ tags: OptionFromOptional(ArraySchema(Struct({
14197
+ description: OptionFromOptional(String$7),
14171
14198
  name: String$7
14172
14199
  })))
14173
14200
  });
@@ -14187,20 +14214,20 @@ const nodeOf = (document, schema) => {
14187
14214
  const node = decodeUnknownSync(JsonNode)(schema);
14188
14215
  return match(node.$ref, {
14189
14216
  onNone: () => node,
14190
- onSome: (ref) => nodeOf(document, getOrThrowWith(get$4(document.components?.schemas ?? {}, ref.replace("#/components/schemas/", "")), () => /* @__PURE__ */ new TypeError(`${ref} names no schema`)))
14217
+ onSome: (ref) => nodeOf(document, getOrThrowWith(get$4(document.components.pipe(flatMap$2(({ schemas }) => schemas), getOrElse(() => ({}))), ref.replace("#/components/schemas/", "")), () => /* @__PURE__ */ new TypeError(`${ref} names no schema`)))
14191
14218
  });
14192
14219
  };
14193
- const hasFixedKeys = (node) => node.type === "object" && node.additionalProperties === false && Object.values(node.patternProperties ?? {}).every((value) => value === false);
14220
+ const hasFixedKeys = (node) => contains(node.type, "object") && contains(node.additionalProperties, false) && Object.values(getOrElse(node.patternProperties, () => ({}))).every((value) => value === false);
14194
14221
  const isText = (document, schema) => {
14195
14222
  const node = nodeOf(document, schema);
14196
- return node.anyOf.pipe(map$7((members) => members.filter((member) => nodeOf(document, member).type !== "null").every((member) => isText(document, member))), orElse(() => node.enum.pipe(map$7((values) => values.every(isString)))), orElse(() => node.const.pipe(map$7(isString))), getOrElse(() => node.type === "string"));
14223
+ return node.anyOf.pipe(map$7((members) => members.filter((member) => !contains(nodeOf(document, member).type, "null")).every((member) => isText(document, member))), orElse(() => node.enum.pipe(map$7((values) => values.every(isString)))), orElse(() => node.const.pipe(map$7(isString))), getOrElse(() => contains(node.type, "string")));
14197
14224
  };
14198
14225
  const bodyOf = (document, operation) => {
14199
- const content = Object.entries(operation.requestBody?.content ?? {}).filter(([, { schema }]) => nodeOf(document, schema ?? {}).type !== "null");
14226
+ const content = Object.entries(operation.requestBody.pipe(map$7((body) => body.content), getOrElse(() => ({})))).filter(([, { schema }]) => !contains(nodeOf(document, getOrElse(schema, () => ({}))).type, "null"));
14200
14227
  const contentTypes = content.map(([contentType]) => contentType);
14201
14228
  if (contentTypes.some((type) => type.startsWith("multipart/"))) throw new TypeError(`${operation.operationId} takes a multipart body`);
14202
14229
  const fieldBody = findFirst(content, ([contentType, { schema }]) => fromNullishOr(FIELD_BODIES.get(contentType)).pipe(map$7((tag) => ({
14203
- node: nodeOf(document, schema ?? {}),
14230
+ node: nodeOf(document, getOrElse(schema, () => ({}))),
14204
14231
  tag
14205
14232
  })), filter(({ node }) => hasFixedKeys(node))));
14206
14233
  return match(fieldBody, {
@@ -14209,11 +14236,11 @@ const bodyOf = (document, operation) => {
14209
14236
  contentTypes
14210
14237
  },
14211
14238
  onSome: ({ node, tag }) => {
14212
- const required = new Set(node.required);
14239
+ const required = new Set(getOrElse(node.required, () => []));
14213
14240
  return {
14214
14241
  _tag: tag,
14215
- fields: Object.entries(node.properties ?? {}).map(([name, property]) => ({
14216
- description: nodeOf(document, property).description ?? "",
14242
+ fields: Object.entries(getOrElse(node.properties, () => ({}))).map(([name, property]) => ({
14243
+ description: nodeOf(document, property).description.pipe(getOrElse(() => "")),
14217
14244
  optional: !required.has(name),
14218
14245
  text: isText(document, property),
14219
14246
  name
@@ -14233,13 +14260,13 @@ const endpointsOf = (document) => Object.entries(document.paths).flatMap(([path,
14233
14260
  })));
14234
14261
  const segmentsOf = ({ operationId }) => {
14235
14262
  const segments = operationId.split(".");
14236
- if (segments.length > 2) throw new TypeError(`${operationId} has more than one dot`);
14263
+ if (segments.length > OPERATION_ID_SEGMENTS) throw new TypeError(`${operationId} has more than one dot`);
14237
14264
  return segments;
14238
14265
  };
14239
- const parameterFields = (document, operation, part) => (operation.parameters ?? []).flatMap((parameter) => parameter.in === part ? [{
14240
- description: parameter.description ?? nodeOf(document, parameter.schema ?? {}).description ?? "",
14266
+ const parameterFields = (document, operation, part) => getOrElse(operation.parameters, () => []).flatMap((parameter) => parameter.in === part ? [{
14267
+ description: parameter.description.pipe(orElse(() => nodeOf(document, getOrElse(parameter.schema, () => ({}))).description), getOrElse(() => "")),
14241
14268
  name: parameter.name,
14242
- optional: parameter.required !== true,
14269
+ optional: !contains(parameter.required, true),
14243
14270
  text: true
14244
14271
  }] : []);
14245
14272
  const FETCH_LIMIT_SECONDS = 300;
@@ -14289,7 +14316,7 @@ const CONTENT_TYPE = {
14289
14316
  const endpointCommand = (document, { body, method, operation, path }, { argument, listings, name, parents }) => {
14290
14317
  const contentTypes = body._tag === "Stdin" ? body.contentTypes : [];
14291
14318
  const media = contentTypes.length > 1 ? [CONTENT_TYPE] : [];
14292
- if ((operation.parameters ?? []).some(({ in: part }) => part === "cookie")) throw new TypeError(`${operation.operationId} takes a cookie parameter`);
14319
+ if (getOrElse(operation.parameters, () => []).some(({ in: part }) => part === "cookie")) throw new TypeError(`${operation.operationId} takes a cookie parameter`);
14293
14320
  const queryFields = parameterFields(document, operation, "query");
14294
14321
  const positional = queryFields.filter((field) => contains(argument, field.name));
14295
14322
  if (isSome(argument) && positional.length === 0) throw new TypeError(`${operation.operationId} has no query field ${argument.value}`);
@@ -14363,7 +14390,7 @@ const endpointCommand = (document, { body, method, operation, path }, { argument
14363
14390
  "2xx": ({ stream }) => stream.pipe(catchReason$1("HttpClientError", "EmptyBodyError", () => empty$4), run$3(stdio.stdout())),
14364
14391
  orElse: answeredOnStderr
14365
14392
  });
14366
- })).pipe(withDescription(operation.summary ?? operation.description ?? ""));
14393
+ })).pipe(withDescription(operation.summary.pipe(orElse(() => operation.description), getOrElse(() => ""))));
14367
14394
  };
14368
14395
  const apiCommand = (name, document, { pickers, verbs }) => {
14369
14396
  const endpoints = endpointsOf(document);
@@ -14386,10 +14413,10 @@ const apiCommand = (name, document, { pickers, verbs }) => {
14386
14413
  parents: [name],
14387
14414
  listings
14388
14415
  })] : []);
14389
- const groups = Map.groupBy(named.filter(({ segments }) => segments.length === 2), ({ segments }) => segments[0]);
14390
- return make(name).pipe(withDescription(document.info?.description ?? ""), withSubcommands([...topLevel, ...Array.from(groups, ([group, members]) => {
14391
- const tag = members[0].endpoint.operation.tags?.at(0);
14392
- const description = document.tags?.find((entry) => entry.name === tag)?.description ?? "";
14416
+ const groups = Map.groupBy(named.filter(({ segments }) => segments.length === OPERATION_ID_SEGMENTS), ({ segments }) => segments[0]);
14417
+ return make(name).pipe(withDescription(document.info.pipe(flatMap$2(({ description }) => description), getOrElse(() => ""))), withSubcommands([...topLevel, ...Array.from(groups, ([group, members]) => {
14418
+ const tag = members[0].endpoint.operation.tags.pipe(flatMap$2(head));
14419
+ const description = document.tags.pipe(flatMap$2(findFirst((entry) => contains(tag, entry.name))), flatMap$2((entry) => entry.description), getOrElse(() => ""));
14393
14420
  const subcommands = members.map(({ argument, endpoint, plain, segments }) => match(flatten(plain), {
14394
14421
  onNone: () => endpointCommand(document, endpoint, {
14395
14422
  argument: none(),
@@ -14416,13 +14443,14 @@ const apiCommand = (name, document, { pickers, verbs }) => {
14416
14443
  })]));
14417
14444
  };
14418
14445
  // ../cli-core/src/answer-wait.ts
14446
+ const UNDICI_DISPATCHER_2_MAJOR = 8;
14447
+ const SECOND_MS = 1e3;
14419
14448
  const UNDICI_NO_LIMIT_MS = 0;
14420
- const [FETCH_UNDICI_MAJOR] = (process.versions.undici ?? "").split(".");
14421
- const GLOBAL_DISPATCHER = Symbol.for(`undici.globalDispatcher.${Number(FETCH_UNDICI_MAJOR) >= 8 ? "2" : "1"}`);
14422
- const decodeGlobalDispatcher = decodeUnknownSync(Struct({ [GLOBAL_DISPATCHER]: declare((input) => hasProperty(input, "dispatch") && isFunction(input.dispatch)) }));
14449
+ const [FETCH_UNDICI_MAJOR] = getOrElse(fromNullishOr(process.versions.undici), () => "").split(".");
14450
+ const GLOBAL_DISPATCHER = Symbol.for(`undici.globalDispatcher.${Number(FETCH_UNDICI_MAJOR) >= UNDICI_DISPATCHER_2_MAJOR ? "2" : "1"}`);
14423
14451
  const answeredWithin = (seconds) => {
14424
- const limit = Number.isFinite(seconds) ? answerWaitSeconds(seconds) * 1e3 : UNDICI_NO_LIMIT_MS;
14425
- const dispatcher = { dispatch: (options, handler) => decodeGlobalDispatcher(globalThis)[GLOBAL_DISPATCHER].dispatch({
14452
+ const limit = Number.isFinite(seconds) ? answerWaitSeconds(seconds) * SECOND_MS : UNDICI_NO_LIMIT_MS;
14453
+ const dispatcher = { dispatch: (options, handler) => decodeUnknownSync(Struct({ [GLOBAL_DISPATCHER]: declare((input) => hasProperty(input, "dispatch") && isFunction(input.dispatch)) }))(globalThis)[GLOBAL_DISPATCHER].dispatch({
14426
14454
  ...options,
14427
14455
  bodyTimeout: limit,
14428
14456
  headersTimeout: limit
@@ -14445,6 +14473,10 @@ const toApiAt = (origin, bearer) => flow(mapRequest(prependUrl(origin)), mapRequ
14445
14473
  onSome: (value) => bearerToken(request, value)
14446
14474
  })));
14447
14475
  // ../cli-core/src/run-api-cli.ts
14476
+ const SPACE_BYTE = 32;
14477
+ const DELETE_BYTE = 127;
14478
+ const SIGNAL_EXIT_BASE = 128;
14479
+ const ARGV_ARGUMENTS_START = 2;
14448
14480
  const invalidToStderr = layerPresenter({ present: (event) => event._tag === "InvalidInvocation" ? gen(function* () {
14449
14481
  const { canColor } = yield* TerminalCapabilities;
14450
14482
  const formatter = defaultFormatter({ colors: canColor });
@@ -14456,7 +14488,7 @@ const documentOf = (spec) => gen(function* () {
14456
14488
  return yield* get(spec).pipe(flatMap$1(filterStatusOk), flatMap$1(schemaBodyJson(ApiDocumentSchema)));
14457
14489
  });
14458
14490
  const encoder = new TextEncoder();
14459
- const Token = RedactedFromValue(Trim.check(isNonEmpty(), makeFilter((value) => encoder.encode(value).every((byte) => byte > 32 && byte < 127), { expected: "a token of visible ASCII characters" })));
14491
+ const Token = RedactedFromValue(Trim.check(isNonEmpty(), makeFilter((value) => encoder.encode(value).every((byte) => byte > SPACE_BYTE && byte < DELETE_BYTE), { expected: "a token of visible ASCII characters" })));
14460
14492
  const flushed = async (stream) => {
14461
14493
  if (stream.destroyed) return;
14462
14494
  const { promise, resolve } = Promise.withResolvers();
@@ -14484,10 +14516,10 @@ const runApiCli = ({ answerSeconds, name, origin, spec, storedToken, token, vers
14484
14516
  return (yield* HttpClient).pipe(toApiAt(base.origin, orElse(key, () => flatMap$2(fromNullOr(storedToken), decodeUnknownOption(Token)))), mapRequest(setHeader("user-agent", `${name}/${version}`)), waitingForAnswers(answerSeconds));
14485
14517
  })).pipe(provide$1(layer$7));
14486
14518
  process.once("SIGTERM", () => {
14487
- process.exit(128 + constants.signals.SIGTERM);
14519
+ process.exit(SIGNAL_EXIT_BASE + constants.signals.SIGTERM);
14488
14520
  });
14489
14521
  runMain(gen(function* () {
14490
- const [flag, ...rest] = process.argv.slice(2);
14522
+ const [flag, ...rest] = process.argv.slice(ARGV_ARGUMENTS_START);
14491
14523
  if (rest.length === 0 && (flag === "--version" || flag === "-v")) return yield* run(make(name), { version });
14492
14524
  const document = yield* documentOf(spec);
14493
14525
  return yield* run(apiCommand(name, document, words), { version });
@@ -14502,149 +14534,9 @@ const runApiCli = ({ answerSeconds, name, origin, spec, storedToken, token, vers
14502
14534
  });
14503
14535
  };
14504
14536
  // package.json
14505
- var version = "0.10.0";
14506
- // src/cli/commands/sign-in.ts
14507
- const LOGIN_USAGE = `Usage: sandcovery login
14508
-
14509
- Signs this computer in to Sandcovery as you. It opens a page in your browser, where you approve the sign-in, and keeps a key for this computer in $XDG_CONFIG_HOME/sandcovery/credentials.json, or ~/.config/sandcovery/credentials.json. Every sandcovery command on this computer then uses that key, unless SANDCOVERY_API_KEY is set.
14510
-
14511
- -h, --help Print this help.
14512
-
14513
- It reads the API origin from SANDCOVERY_BASE_URL.
14514
- `;
14515
- const LOGOUT_USAGE = `Usage: sandcovery logout
14516
-
14517
- Signs this computer out of Sandcovery: it revokes the key sandcovery login keeps for this computer, and deletes it.
14518
-
14519
- -h, --help Print this help.
14520
- `;
14521
- const DENIED = "The sign-in was denied, so this computer isn't signed in. To try again, run sandcovery login.";
14522
- const ENDED = "The sign-in ended before anyone approved it. To try again, run sandcovery login.";
14523
- const NOT_REVOKED = "revoke it in API Keys in the Sandcovery dashboard. Sandcovery couldn't revoke it:";
14524
- const MS_PER_SECOND = 1e3;
14525
- const UNNAMED_COMPUTER = "Computer";
14526
- const NO_HEADERS$1 = {};
14527
- const NO_PARAMS = {};
14528
- const NO_QUERY$1 = {};
14529
- const OPENERS = /* @__PURE__ */ new Map([["darwin", ["open"]], ["win32", [
14530
- "cmd",
14531
- "/c",
14532
- "start",
14533
- "\"\""
14534
- ]]]);
14535
- const LINUX_OPENER = ["xdg-open"];
14536
- const DISPLAYS = ["DISPLAY", "WAYLAND_DISPLAY"];
14537
- const requestOf = (tool, json) => ({
14538
- answerSeconds: 0,
14539
- body: none(),
14540
- headers: NO_HEADERS$1,
14541
- params: NO_PARAMS,
14542
- query: NO_QUERY$1,
14543
- signal: some(tool.signal),
14544
- json
14545
- });
14546
- const settled = async (input) => {
14547
- await setTimeout$1(input.intervalSeconds * MS_PER_SECOND, null, { signal: input.tool.signal });
14548
- const token = await read(input.config, CliSignInToken, SandcoveryApi.groups.cliSignIns.endpoints.collectCliSignIn, requestOf(input.tool, some({ device_code: input.deviceCode })));
14549
- return token.status === "pending" ? await settled(input) : token;
14550
- };
14551
- const signIn = async (tool) => {
14552
- const config = make$19({
14553
- apiKey: none(),
14554
- baseUrl: tool.origin,
14555
- send: none()
14556
- });
14557
- const started = await read(config, CliSignInStart, SandcoveryApi.groups.cliSignIns.endpoints.startCliSignIn, requestOf(tool, some({ name: liftPredicate(os.hostname().slice(0, 64), (name) => name !== "").pipe(getOrElse(() => UNNAMED_COMPUTER)) })));
14558
- tool.io.stderr.write(`To sign in this computer, approve the code ${started.user_code} at\n${started.verification_url}\n`);
14559
- if (process.platform !== "linux" || DISPLAYS.some((name) => (process.env[name] ?? "") !== "")) {
14560
- const [command, ...rest] = getOrElse(fromUndefinedOr(OPENERS.get(process.platform)), () => LINUX_OPENER);
14561
- const opener = spawn(command, [...rest, started.verification_url], {
14562
- detached: true,
14563
- stdio: "ignore"
14564
- });
14565
- opener.on("error", noop);
14566
- opener.unref();
14567
- }
14568
- const token = await settled({
14569
- config,
14570
- tool,
14571
- deviceCode: started.device_code,
14572
- intervalSeconds: started.interval_seconds
14573
- });
14574
- const apiKey = fromNullOr(token.api_key);
14575
- if (isNone(apiKey)) throw new Error(token.status === "denied" ? DENIED : ENDED);
14576
- writePrivateFile({
14577
- file: tool.credentials,
14578
- text: encodeSync(Credentials)({ api_key: apiKey.value })
14579
- });
14580
- tool.io.stderr.write("This computer is signed in to Sandcovery as you.\n");
14581
- return apiKey.value;
14582
- };
14583
- const loginRun = async (tool) => {
14584
- const { values } = parseArgs({
14585
- args: [...tool.args],
14586
- options: { help: {
14587
- short: "h",
14588
- type: "boolean"
14589
- } },
14590
- strict: true
14591
- });
14592
- if (values.help === true) {
14593
- tool.io.stdout.write(LOGIN_USAGE);
14594
- return 0;
14595
- }
14596
- const before = storedKey(tool.credentials);
14597
- const signedIn = await signIn(tool);
14598
- if ((process.env.SANDCOVERY_API_KEY ?? "") !== "") tool.io.stderr.write("SANDCOVERY_API_KEY is set, so sandcovery commands use it instead until you unset it.\n");
14599
- const replaced = before.pipe(filter((key) => key !== signedIn));
14600
- if (isNone(replaced)) return 0;
14601
- try {
14602
- await call(make$19({
14603
- apiKey: replaced,
14604
- baseUrl: tool.origin,
14605
- send: none()
14606
- }), SandcoveryApi.groups.cliSignIns.endpoints.signOutCli, requestOf(tool, none()));
14607
- } catch (error) {
14608
- tool.io.stderr.write(`This computer held an earlier key, so ${NOT_REVOKED} ${error instanceof Error ? error.message : String(error)}\n`);
14609
- return 1;
14610
- }
14611
- return 0;
14612
- };
14613
- const logoutRun = async (tool) => {
14614
- const { values } = parseArgs({
14615
- args: [...tool.args],
14616
- options: { help: {
14617
- short: "h",
14618
- type: "boolean"
14619
- } },
14620
- strict: true
14621
- });
14622
- if (values.help === true) {
14623
- tool.io.stdout.write(LOGOUT_USAGE);
14624
- return 0;
14625
- }
14626
- const key = storedKey(tool.credentials);
14627
- if (isNone(key)) {
14628
- tool.io.stderr.write("This computer isn't signed in to Sandcovery.\n");
14629
- return 0;
14630
- }
14631
- try {
14632
- await call(make$19({
14633
- apiKey: key,
14634
- baseUrl: tool.origin,
14635
- send: none()
14636
- }), SandcoveryApi.groups.cliSignIns.endpoints.signOutCli, requestOf(tool, none()));
14637
- } catch (error) {
14638
- fs.rmSync(tool.credentials, { force: true });
14639
- tool.io.stderr.write(`This computer is signed out, but its key is still live, so ${NOT_REVOKED} ${error instanceof Error ? error.message : String(error)}\n`);
14640
- return 1;
14641
- }
14642
- fs.rmSync(tool.credentials, { force: true });
14643
- tool.io.stderr.write("This computer is signed out of Sandcovery.\n");
14644
- return 0;
14645
- };
14537
+ var version = "0.12.0";
14646
14538
  // src/cli/commands/agents-ssh.ts
14647
- const USAGE = `Usage: sandcovery agents ssh <agent_id> [-- <ssh arguments>...]
14539
+ const USAGE$1 = `Usage: sandcovery agents ssh <agent_id> [-- <ssh arguments>...]
14648
14540
 
14649
14541
  Opens SSH to an always-on agent. A shell joins the agent's session. After --, ssh options such as -L forward the agent's ports, and a command runs on its own instead of the shell. It signs in with a key it makes for this connection and deletes when ssh exits, and exits with ssh's exit code.
14650
14542
 
@@ -14671,7 +14563,7 @@ const agentsSshRun = async (tool) => {
14671
14563
  tokens: true
14672
14564
  });
14673
14565
  if (values.help === true) {
14674
- tool.io.stdout.write(USAGE);
14566
+ tool.io.stdout.write(USAGE$1);
14675
14567
  return 0;
14676
14568
  }
14677
14569
  const end = fromUndefinedOr(tokens.find((token) => token.kind === "option-terminator")).pipe(map$7(({ index }) => index), getOrElse(() => tool.args.length));
@@ -14789,6 +14681,805 @@ const agentsSshRun = async (tool) => {
14789
14681
  }
14790
14682
  });
14791
14683
  };
14684
+ // ../sandcovery-contract/src/engine.ts
14685
+ const ENGINE_CONNECT_PATH = `${API_PREFIX}/engine/connect`;
14686
+ const ENGINE_ORIGIN = "https://engine.invalid";
14687
+ const ENGINE_PING = "ping";
14688
+ const HeaderList = ArraySchema(Tuple([String$7, String$7]));
14689
+ const toEngineFrame = Union([
14690
+ Struct({
14691
+ body: Boolean$3,
14692
+ headers: HeaderList,
14693
+ id: String$7,
14694
+ method: String$7,
14695
+ path: String$7,
14696
+ type: Literal("request")
14697
+ }),
14698
+ Struct({
14699
+ id: String$7,
14700
+ type: Literal("cancel")
14701
+ }),
14702
+ Struct({
14703
+ id: String$7,
14704
+ type: Literal("end")
14705
+ })
14706
+ ]);
14707
+ const fromEngineFrame = Union([
14708
+ Struct({
14709
+ headers: HeaderList,
14710
+ id: String$7,
14711
+ status: Int$1,
14712
+ type: Literal("head")
14713
+ }),
14714
+ Struct({
14715
+ id: String$7,
14716
+ type: Literal("end")
14717
+ }),
14718
+ Struct({
14719
+ id: String$7,
14720
+ message: String$7,
14721
+ type: Literal("fail")
14722
+ })
14723
+ ]);
14724
+ `${String(8080)}`;
14725
+ const Positive = Number$2.check(isGreaterThan(0));
14726
+ const Seconds = Int$1.check(isGreaterThan(0));
14727
+ const createSchema = Struct({
14728
+ cpu: Positive,
14729
+ egress: Union([Struct({ mode: Literals$2(["allow_all", "deny_all"]) }), Struct({
14730
+ cidrs: ArraySchema(NonEmptyString),
14731
+ domains: ArraySchema(NonEmptyString),
14732
+ mode: Literal("allowlist")
14733
+ })]),
14734
+ env: Record(String$7, String$7),
14735
+ gpu: OptionFromOptionalKey(NonEmptyString),
14736
+ idle_timeout_seconds: OptionFromOptionalKey(Seconds),
14737
+ image: Union([Struct({ registry: NonEmptyString }), Struct({ snapshot: NonEmptyString })]),
14738
+ memory_mib: Int$1.check(isGreaterThan(0)),
14739
+ name: NonEmptyString,
14740
+ timeout_seconds: Seconds
14741
+ });
14742
+ Struct({ sandbox_id: NonEmptyString });
14743
+ const execSchema = Struct({
14744
+ argv: NonEmptyArray(String$7),
14745
+ timeout_seconds: Seconds
14746
+ });
14747
+ const errorSchema = Struct({
14748
+ code: String$7,
14749
+ message: String$7,
14750
+ status: Int$1
14751
+ });
14752
+ Union([
14753
+ Struct({
14754
+ data: String$7,
14755
+ stream: Literals$2(["stderr", "stdout"])
14756
+ }),
14757
+ Struct({ exit_code: Int$1 }),
14758
+ Struct({ error: errorSchema })
14759
+ ]);
14760
+ Struct({ running: Boolean$3 });
14761
+ Struct({ sandbox_ids: ArraySchema(NonEmptyString) });
14762
+ Struct({ entries: ArraySchema(Struct({
14763
+ modified_seconds: NullOr(Number$2),
14764
+ name: String$7,
14765
+ path: String$7,
14766
+ size_bytes: NullOr(Int$1),
14767
+ type: Literals$2([
14768
+ "directory",
14769
+ "file",
14770
+ "other",
14771
+ "symlink"
14772
+ ])
14773
+ })) });
14774
+ Struct({ image_id: NonEmptyString });
14775
+ Struct({
14776
+ token: NonEmptyString,
14777
+ url: NonEmptyString
14778
+ });
14779
+ // ../sandcovery-core/src/units.ts
14780
+ const MS_PER_SECOND = 1e3;
14781
+ const MIB_PER_GIB = 1024;
14782
+ Int$1.check(isGreaterThan(0));
14783
+ String$7.check(isStartingWith("https://"));
14784
+ // src/cli/commands/engine.ts
14785
+ const USAGE = `Usage: sandcovery engine [--cpus <count>] [--memory <GiB>]
14786
+
14787
+ Runs Sandcovery sandboxes on this computer as Docker containers, shown in Sandcovery as Your machine. It signs this computer in to Sandcovery if it isn't signed in yet, connects to Sandcovery, and stays connected until you stop it.
14788
+
14789
+ --cpus <count> The CPUs all sandboxes may reserve together. Defaults to half of this computer's CPUs.
14790
+ --memory <GiB> The memory all sandboxes may reserve together, in GiB. Defaults to half of this computer's memory.
14791
+ -h, --help Print this help.
14792
+
14793
+ It reads the API origin from SANDCOVERY_BASE_URL.
14794
+ `;
14795
+ const DOCKER = `docker${process.platform === "win32" ? ".exe" : ""}`;
14796
+ const PING_MS = 3e4;
14797
+ const QUIET_LIMIT_MS = 3 * PING_MS;
14798
+ const FIRST_RETRY_MS = 1e3;
14799
+ const LAST_RETRY_MS = 6e4;
14800
+ const BYTES_PER_MIB = 1048576;
14801
+ const ENGINE_LABEL = "sandcovery.engine";
14802
+ const NAME_LABEL = "sandcovery.name";
14803
+ const CPU_LABEL = "sandcovery.cpu";
14804
+ const MEMORY_LABEL = "sandcovery.memory_mib";
14805
+ const SNAPSHOT_LABEL = "sandcovery.snapshot";
14806
+ const SANDBOXES_PATH = "/v1/sandboxes";
14807
+ const SANDBOXES_PREFIX = `${SANDBOXES_PATH}/`;
14808
+ const SNAPSHOTS_PREFIX = "/v1/snapshots/";
14809
+ const PIDS_LIMIT = 4096;
14810
+ const EXEC_MARK = "SANDCOVERY_EXEC";
14811
+ const MISSING_EXIT = 2;
14812
+ const WRONG_KIND_EXIT = 3;
14813
+ const READ_SCRIPT = `[ -e "$1" ] || exit ${String(MISSING_EXIT)}
14814
+ [ -d "$1" ] && exit ${String(WRONG_KIND_EXIT)}
14815
+ exec cat -- "$1"`;
14816
+ const WRITE_SCRIPT = `[ -d "$1" ] && exit ${String(WRONG_KIND_EXIT)}
14817
+ mkdir -p "$(dirname "$1")" && exec cat > "$1"`;
14818
+ const LIST_SCRIPT = `[ -e "$1" ] || exit ${String(MISSING_EXIT)}
14819
+ [ -d "$1" ] || exit ${String(WRONG_KIND_EXIT)}
14820
+ for entry in "$1"/* "$1"/.[!.]* "$1"/..?*; do
14821
+ if [ -e "$entry" ] || [ -L "$entry" ]; then
14822
+ printf '%s\\0%s\\0' "$(stat -c '%F|%s|%Y' -- "$entry")" "$entry"
14823
+ fi
14824
+ done`;
14825
+ const KILL_SCRIPT = `for entry in /proc/[0-9]*; do
14826
+ tr '\\0' '\\n' < "$entry/environ" 2>/dev/null | grep -qx -- "$1" && kill -KILL "\${entry#/proc/}" 2>/dev/null
14827
+ done
14828
+ exit 0`;
14829
+ const ENTRY_TYPES = /* @__PURE__ */ new Map([
14830
+ ["directory", "directory"],
14831
+ ["regular empty file", "file"],
14832
+ ["regular file", "file"],
14833
+ ["symbolic link", "symlink"]
14834
+ ]);
14835
+ const decodeCreate = decodeUnknownOption(fromJsonString(createSchema));
14836
+ const decodeExec = decodeUnknownOption(fromJsonString(execSchema));
14837
+ const decodeFrame = decodeUnknownOption(fromJsonString(toEngineFrame));
14838
+ const encodeFrame = encodeSync(fromJsonString(fromEngineFrame));
14839
+ var EngineRefusal = class extends TaggedError("EngineRefusal") {};
14840
+ const GONE = new EngineRefusal({
14841
+ code: "not_found",
14842
+ message: "Your machine has no such sandbox.",
14843
+ status: 404
14844
+ });
14845
+ const STOPPED = new EngineRefusal({
14846
+ code: "not_running",
14847
+ message: "The sandbox has stopped.",
14848
+ status: 409
14849
+ });
14850
+ const UNROUTED = new EngineRefusal({
14851
+ code: "no_route",
14852
+ message: "Your machine has no such route.",
14853
+ status: 404
14854
+ });
14855
+ const PAST_TIMEOUT = { error: {
14856
+ code: "DEADLINE_EXCEEDED",
14857
+ message: "The command ran past its timeout.",
14858
+ status: 504
14859
+ } };
14860
+ const framed = (frame) => `data: ${JSON.stringify(frame)}\n\n`;
14861
+ const docker = async (binary, args, input) => {
14862
+ const child = spawn(binary, args, { stdio: [
14863
+ "pipe",
14864
+ "pipe",
14865
+ "pipe"
14866
+ ] });
14867
+ child.stdin.on("error", noop);
14868
+ match(input, {
14869
+ onNone: () => child.stdin.end(),
14870
+ onSome: (bytes) => child.stdin.end(bytes)
14871
+ });
14872
+ const [stdout, stderr] = await Promise.all([
14873
+ buffer(child.stdout),
14874
+ buffer(child.stderr),
14875
+ once(child, "close")
14876
+ ]);
14877
+ return {
14878
+ code: child.exitCode ?? -1,
14879
+ stderr: stderr.toString().trim(),
14880
+ stdout
14881
+ };
14882
+ };
14883
+ const dockerOut = async (binary, args, input) => {
14884
+ const ran = await docker(binary, args, input);
14885
+ if (ran.code !== 0) throw new EngineRefusal({
14886
+ code: "docker_error",
14887
+ message: ran.stderr,
14888
+ status: 502
14889
+ });
14890
+ return ran.stdout.toString().trim();
14891
+ };
14892
+ const inSandbox = async (input) => {
14893
+ const { binary, content, sandboxId, script, target, wrongKind } = input;
14894
+ const ran = await docker(binary, [
14895
+ "exec",
14896
+ ...match(content, {
14897
+ onNone: () => [],
14898
+ onSome: () => ["--interactive"]
14899
+ }),
14900
+ "--",
14901
+ sandboxId,
14902
+ "sh",
14903
+ "-c",
14904
+ script,
14905
+ "sh",
14906
+ target
14907
+ ], content);
14908
+ if (ran.code === MISSING_EXIT) throw new EngineRefusal({
14909
+ code: "not_found",
14910
+ message: `${target} doesn't exist in the sandbox.`,
14911
+ status: 404
14912
+ });
14913
+ if (ran.code === WRONG_KIND_EXIT) throw new EngineRefusal({
14914
+ code: "invalid_request",
14915
+ message: `${target} is ${wrongKind}.`,
14916
+ status: 400
14917
+ });
14918
+ if (ran.code !== 0) throw new EngineRefusal({
14919
+ code: "sandbox_error",
14920
+ message: ran.stderr,
14921
+ status: 400
14922
+ });
14923
+ return ran.stdout;
14924
+ };
14925
+ const runningOf = async (binary, sandboxId) => {
14926
+ const ran = await docker(binary, [
14927
+ "inspect",
14928
+ "--type",
14929
+ "container",
14930
+ "--format",
14931
+ `{{index .Config.Labels "${ENGINE_LABEL}"}} {{.State.Running}}`,
14932
+ "--",
14933
+ sandboxId
14934
+ ], none());
14935
+ const [engine, running] = ran.stdout.toString().trim().split(" ");
14936
+ if (ran.code !== 0 || engine !== "true") throw GONE;
14937
+ return running === "true";
14938
+ };
14939
+ const pathOf = (url) => {
14940
+ const target = url.searchParams.get("path") ?? "";
14941
+ if (target === "") throw new EngineRefusal({
14942
+ code: "invalid_request",
14943
+ message: "The path query is required.",
14944
+ status: 400
14945
+ });
14946
+ return target;
14947
+ };
14948
+ const execResponse = (input) => {
14949
+ const { argv, binary, sandboxId, signal, timeoutSeconds } = input;
14950
+ const deadline = Date.now() + timeoutSeconds * MS_PER_SECOND;
14951
+ const exited = Promise.withResolvers();
14952
+ const mark = `${EXEC_MARK}=${v7()}`;
14953
+ const stop = AbortSignal.any([signal, AbortSignal.timeout(timeoutSeconds * MS_PER_SECOND)]);
14954
+ const kill = () => {
14955
+ docker(binary, [
14956
+ "exec",
14957
+ "--",
14958
+ sandboxId,
14959
+ "sh",
14960
+ "-c",
14961
+ KILL_SCRIPT,
14962
+ "sh",
14963
+ mark
14964
+ ], none());
14965
+ };
14966
+ stop.addEventListener("abort", kill, { once: true });
14967
+ const child = spawn(binary, [
14968
+ "exec",
14969
+ "--env",
14970
+ mark,
14971
+ "--",
14972
+ sandboxId,
14973
+ ...argv
14974
+ ], {
14975
+ signal: stop,
14976
+ stdio: [
14977
+ "ignore",
14978
+ "pipe",
14979
+ "pipe"
14980
+ ]
14981
+ });
14982
+ child.on("error", noop);
14983
+ child.on("close", (code) => {
14984
+ stop.removeEventListener("abort", kill);
14985
+ exited.resolve(code);
14986
+ });
14987
+ const events = new ReadableStream({ start: async (controller) => {
14988
+ const pump = async (stream) => {
14989
+ const output = child[stream];
14990
+ output.setEncoding("utf-8");
14991
+ for await (const data of output) controller.enqueue(framed({
14992
+ data: String(data),
14993
+ stream
14994
+ }));
14995
+ };
14996
+ await Promise.all([pump("stdout"), pump("stderr")]);
14997
+ const code = await exited.promise;
14998
+ if (signal.aborted) {
14999
+ controller.close();
15000
+ return;
15001
+ }
15002
+ controller.enqueue(framed(Date.now() >= deadline || code === null ? PAST_TIMEOUT : { exit_code: code }));
15003
+ controller.close();
15004
+ } });
15005
+ return new Response(events.pipeThrough(new TextEncoderStream()), { headers: {
15006
+ "cache-control": "no-store",
15007
+ "content-type": "text/event-stream"
15008
+ } });
15009
+ };
15010
+ const sandboxResponse = async (input) => {
15011
+ const { binary, body, method, remove, rest, sandboxId, signal, url } = input;
15012
+ const route = `${method} ${rest}`;
15013
+ const running = await runningOf(binary, sandboxId);
15014
+ if (route === "GET ") return Response.json({ running });
15015
+ if (route === "DELETE ") {
15016
+ await remove(sandboxId);
15017
+ return Response.json({});
15018
+ }
15019
+ if (route === "POST /snapshot") {
15020
+ const imageId = await dockerOut(binary, [
15021
+ "commit",
15022
+ "--change",
15023
+ `LABEL ${SNAPSHOT_LABEL}=true`,
15024
+ "--",
15025
+ sandboxId
15026
+ ], none());
15027
+ return Response.json({ image_id: imageId });
15028
+ }
15029
+ if (!running) throw STOPPED;
15030
+ if (route === "POST /exec") {
15031
+ const exec = decodeExec(new TextDecoder().decode(body));
15032
+ if (isNone(exec)) throw new EngineRefusal({
15033
+ code: "invalid_request",
15034
+ message: "The body is a JSON object with argv, a non-empty array of strings, and timeout_seconds, a whole number of seconds.",
15035
+ status: 400
15036
+ });
15037
+ return execResponse({
15038
+ binary,
15039
+ sandboxId,
15040
+ signal,
15041
+ argv: exec.value.argv,
15042
+ timeoutSeconds: exec.value.timeout_seconds
15043
+ });
15044
+ }
15045
+ if (route === "GET /file") {
15046
+ const bytes = await inSandbox({
15047
+ binary,
15048
+ sandboxId,
15049
+ content: none(),
15050
+ script: READ_SCRIPT,
15051
+ target: pathOf(url),
15052
+ wrongKind: "a directory"
15053
+ });
15054
+ return new Response(bytes, { headers: { "content-type": "application/octet-stream" } });
15055
+ }
15056
+ if (route === "PUT /file") {
15057
+ await inSandbox({
15058
+ binary,
15059
+ sandboxId,
15060
+ content: some(body),
15061
+ script: WRITE_SCRIPT,
15062
+ target: pathOf(url),
15063
+ wrongKind: "a directory"
15064
+ });
15065
+ return Response.json({});
15066
+ }
15067
+ if (route === "GET /directory") {
15068
+ const directory = pathOf(url);
15069
+ const output = await inSandbox({
15070
+ binary,
15071
+ sandboxId,
15072
+ content: none(),
15073
+ script: LIST_SCRIPT,
15074
+ target: directory,
15075
+ wrongKind: "not a directory"
15076
+ });
15077
+ const listing = { entries: chunk(output.toString().split("\0").slice(0, -1), 2).map(([meta = "", entry = ""]) => {
15078
+ const [kind = "", size = "", modified = ""] = meta.split("|");
15079
+ const name = path.posix.basename(entry);
15080
+ return {
15081
+ name,
15082
+ modified_seconds: Number.isFinite(Number(modified)) ? Number(modified) : null,
15083
+ path: path.posix.join(directory, name),
15084
+ size_bytes: Number.isSafeInteger(Number(size)) ? Number(size) : null,
15085
+ type: ENTRY_TYPES.get(kind) ?? "other"
15086
+ };
15087
+ }) };
15088
+ return Response.json(listing);
15089
+ }
15090
+ throw UNROUTED;
15091
+ };
15092
+ const engineResponse = async (input) => {
15093
+ const { binary, body, capacity, method, remove, reservations, signal, target, watch } = input;
15094
+ const url = new URL(target, ENGINE_ORIGIN);
15095
+ const route = `${method} ${url.pathname}`;
15096
+ if (route === "GET /v1/health") {
15097
+ await dockerOut(binary, [
15098
+ "version",
15099
+ "--format",
15100
+ "{{.Server.Version}}"
15101
+ ], none());
15102
+ return Response.json({});
15103
+ }
15104
+ if (route === `POST ${SANDBOXES_PATH}`) {
15105
+ const create = decodeCreate(new TextDecoder().decode(body));
15106
+ if (isNone(create)) throw new EngineRefusal({
15107
+ code: "invalid_request",
15108
+ message: "The body is not a sandbox Your machine can create.",
15109
+ status: 400
15110
+ });
15111
+ const { cpu, egress, env, image, memory_mib, name, timeout_seconds } = create.value;
15112
+ if (egress.mode === "allowlist") throw new EngineRefusal({
15113
+ code: "unsupported",
15114
+ message: "Your machine cannot limit a sandbox to chosen destinations.",
15115
+ status: 400
15116
+ });
15117
+ const reserved = [...reservations.values()];
15118
+ if (sumBy(reserved, (reservation) => reservation.cpu) + cpu > capacity.cpus || sumBy(reserved, (reservation) => reservation.memoryMib) + memory_mib > capacity.memoryMib) throw new EngineRefusal({
15119
+ code: "capacity",
15120
+ message: "Your machine has no room left for this sandbox.",
15121
+ status: 503
15122
+ });
15123
+ const imageRef = await value$1(image).pipe(when({ registry: string }, async ({ registry }) => await Promise.resolve(registry)), orElse$1(async ({ snapshot }) => {
15124
+ const labeled = await docker(binary, [
15125
+ "image",
15126
+ "inspect",
15127
+ "--format",
15128
+ `{{index .Config.Labels "${SNAPSHOT_LABEL}"}}`,
15129
+ "--",
15130
+ snapshot
15131
+ ], none());
15132
+ if (labeled.code !== 0 || labeled.stdout.toString().trim() !== "true") throw new EngineRefusal({
15133
+ code: "not_found",
15134
+ message: "Your machine has no such snapshot.",
15135
+ status: 404
15136
+ });
15137
+ return snapshot;
15138
+ }));
15139
+ const reservation = {
15140
+ cpu,
15141
+ memoryMib: memory_mib
15142
+ };
15143
+ const pending = v7();
15144
+ reservations.set(pending, reservation);
15145
+ try {
15146
+ const sandboxId = await dockerOut(binary, [
15147
+ "run",
15148
+ "--detach",
15149
+ "--rm",
15150
+ "--init",
15151
+ "--security-opt",
15152
+ "no-new-privileges",
15153
+ "--pids-limit",
15154
+ String(PIDS_LIMIT),
15155
+ "--cpus",
15156
+ String(cpu),
15157
+ "--memory",
15158
+ `${String(memory_mib)}m`,
15159
+ "--label",
15160
+ `${ENGINE_LABEL}=true`,
15161
+ "--label",
15162
+ `${NAME_LABEL}=${name}`,
15163
+ "--label",
15164
+ `${CPU_LABEL}=${String(cpu)}`,
15165
+ "--label",
15166
+ `${MEMORY_LABEL}=${String(memory_mib)}`,
15167
+ ...egress.mode === "deny_all" ? ["--network", "none"] : [],
15168
+ ...Object.entries(env).flatMap(([variable, value]) => ["--env", `${variable}=${value}`]),
15169
+ "--entrypoint",
15170
+ "sleep",
15171
+ "--",
15172
+ imageRef,
15173
+ String(timeout_seconds)
15174
+ ], none());
15175
+ reservations.set(sandboxId, reservation);
15176
+ watch(sandboxId);
15177
+ return Response.json({ sandbox_id: sandboxId }, { status: 201 });
15178
+ } finally {
15179
+ reservations.delete(pending);
15180
+ }
15181
+ }
15182
+ if (route === `DELETE ${SANDBOXES_PATH}`) {
15183
+ const name = url.searchParams.get("name") ?? "";
15184
+ if (name === "") throw new EngineRefusal({
15185
+ code: "invalid_request",
15186
+ message: "The name query is required.",
15187
+ status: 400
15188
+ });
15189
+ const sandboxIds = (await dockerOut(binary, [
15190
+ "ps",
15191
+ "--all",
15192
+ "--quiet",
15193
+ "--no-trunc",
15194
+ "--filter",
15195
+ `label=${ENGINE_LABEL}=true`,
15196
+ "--filter",
15197
+ `label=${NAME_LABEL}=${name}`
15198
+ ], none())).split("\n").filter((sandboxId) => sandboxId !== "");
15199
+ await Promise.all(sandboxIds.map(remove));
15200
+ return Response.json({ sandbox_ids: sandboxIds });
15201
+ }
15202
+ if (method === "DELETE" && url.pathname.startsWith(SNAPSHOTS_PREFIX)) {
15203
+ const imageId = decodeURIComponent(url.pathname.slice(14));
15204
+ const ran = await docker(binary, [
15205
+ "image",
15206
+ "inspect",
15207
+ "--format",
15208
+ `{{index .Config.Labels "${SNAPSHOT_LABEL}"}}`,
15209
+ "--",
15210
+ imageId
15211
+ ], none());
15212
+ if (ran.code !== 0 || ran.stdout.toString().trim() !== "true") throw new EngineRefusal({
15213
+ code: "not_found",
15214
+ message: "Your machine has no such snapshot.",
15215
+ status: 404
15216
+ });
15217
+ await dockerOut(binary, [
15218
+ "image",
15219
+ "rm",
15220
+ "--",
15221
+ imageId
15222
+ ], none());
15223
+ return Response.json({});
15224
+ }
15225
+ if (!url.pathname.startsWith(SANDBOXES_PREFIX)) throw UNROUTED;
15226
+ const [segment = "", ...rest] = url.pathname.slice(SANDBOXES_PREFIX.length).split("/");
15227
+ if (segment === "") throw UNROUTED;
15228
+ return await sandboxResponse({
15229
+ binary,
15230
+ body,
15231
+ method,
15232
+ remove,
15233
+ signal,
15234
+ url,
15235
+ rest: rest.map((part) => `/${part}`).join(""),
15236
+ sandboxId: decodeURIComponent(segment)
15237
+ });
15238
+ };
15239
+ const session = async (input) => {
15240
+ const { answer, key, signal, stderr, url } = input;
15241
+ const awaiting = /* @__PURE__ */ new Map();
15242
+ const running = /* @__PURE__ */ new Map();
15243
+ const opened = make$19(false);
15244
+ const heard = make$19(Date.now());
15245
+ const closed = Promise.withResolvers();
15246
+ const socket = new WebSocket(url, { headers: { authorization: `Bearer ${key}` } });
15247
+ socket.binaryType = "arraybuffer";
15248
+ const send = (frame) => {
15249
+ socket.send(encodeFrame(frame));
15250
+ };
15251
+ const answered = async (request) => {
15252
+ try {
15253
+ return await answer(request);
15254
+ } catch (error) {
15255
+ if (error instanceof EngineRefusal) return Response.json({
15256
+ code: error.code,
15257
+ message: error.message
15258
+ }, { status: error.status });
15259
+ throw error;
15260
+ }
15261
+ };
15262
+ const served = async (request) => {
15263
+ const { body, id, method, target } = request;
15264
+ const controller = new AbortController();
15265
+ const prefix = new TextEncoder().encode(id);
15266
+ running.set(id, controller);
15267
+ try {
15268
+ const response = await answered({
15269
+ body,
15270
+ method,
15271
+ target,
15272
+ signal: controller.signal
15273
+ });
15274
+ if (controller.signal.aborted) return;
15275
+ send({
15276
+ id,
15277
+ headers: [...response.headers],
15278
+ status: response.status,
15279
+ type: "head"
15280
+ });
15281
+ if (response.body !== null) for await (const part of response.body) {
15282
+ if (controller.signal.aborted) return;
15283
+ socket.send(Buffer.concat([prefix, part]));
15284
+ }
15285
+ send({
15286
+ id,
15287
+ type: "end"
15288
+ });
15289
+ } catch (error) {
15290
+ send({
15291
+ id,
15292
+ message: error instanceof Error ? error.message : String(error),
15293
+ type: "fail"
15294
+ });
15295
+ } finally {
15296
+ running.delete(id);
15297
+ }
15298
+ };
15299
+ const pinger = setInterval(() => {
15300
+ if (Date.now() - get$5(heard) > QUIET_LIMIT_MS) {
15301
+ socket.close();
15302
+ return;
15303
+ }
15304
+ socket.send(ENGINE_PING);
15305
+ }, PING_MS);
15306
+ const stop = () => {
15307
+ socket.close(1e3);
15308
+ };
15309
+ signal.addEventListener("abort", stop, { once: true });
15310
+ socket.addEventListener("open", () => {
15311
+ set$1(opened, true);
15312
+ set$1(heard, Date.now());
15313
+ stderr.write("Your machine is connected to Sandcovery.\n");
15314
+ });
15315
+ socket.addEventListener("message", ({ data }) => {
15316
+ set$1(heard, Date.now());
15317
+ if (data instanceof ArrayBuffer) {
15318
+ const id = new TextDecoder().decode(data.slice(0, 36));
15319
+ const waiting = fromUndefinedOr(awaiting.get(id));
15320
+ if (isSome(waiting)) awaiting.set(id, {
15321
+ ...waiting.value,
15322
+ parts: [...waiting.value.parts, new Uint8Array(data, 36)]
15323
+ });
15324
+ return;
15325
+ }
15326
+ if (data === "pong") return;
15327
+ const frame = decodeFrame(String(data));
15328
+ if (isNone(frame)) return;
15329
+ const { id } = frame.value;
15330
+ if (frame.value.type === "cancel") {
15331
+ awaiting.delete(id);
15332
+ running.get(id)?.abort();
15333
+ return;
15334
+ }
15335
+ if (frame.value.type === "end") {
15336
+ const waiting = fromUndefinedOr(awaiting.get(id));
15337
+ awaiting.delete(id);
15338
+ if (isSome(waiting)) {
15339
+ const { method, parts, target } = waiting.value;
15340
+ served({
15341
+ id,
15342
+ method,
15343
+ target,
15344
+ body: Buffer.concat(parts)
15345
+ });
15346
+ }
15347
+ return;
15348
+ }
15349
+ const request = {
15350
+ method: frame.value.method,
15351
+ target: frame.value.path
15352
+ };
15353
+ if (frame.value.body) {
15354
+ awaiting.set(id, {
15355
+ ...request,
15356
+ parts: []
15357
+ });
15358
+ return;
15359
+ }
15360
+ served({
15361
+ ...request,
15362
+ id,
15363
+ body: /* @__PURE__ */ new Uint8Array()
15364
+ });
15365
+ });
15366
+ socket.addEventListener("close", () => {
15367
+ clearInterval(pinger);
15368
+ signal.removeEventListener("abort", stop);
15369
+ for (const controller of running.values()) controller.abort();
15370
+ closed.resolve(get$5(opened));
15371
+ });
15372
+ return await closed.promise;
15373
+ };
15374
+ const engineRun = async (tool) => {
15375
+ const { values } = parseArgs({
15376
+ args: [...tool.args],
15377
+ options: {
15378
+ cpus: { type: "string" },
15379
+ help: {
15380
+ short: "h",
15381
+ type: "boolean"
15382
+ },
15383
+ memory: { type: "string" }
15384
+ },
15385
+ strict: true
15386
+ });
15387
+ if (values.help === true) {
15388
+ tool.io.stdout.write(USAGE);
15389
+ return 0;
15390
+ }
15391
+ const cpus = fromUndefinedOr(values.cpus).pipe(map$7(Number), getOrElse(() => os.availableParallelism() / 2));
15392
+ const memoryMib = fromUndefinedOr(values.memory).pipe(map$7((gib) => Number(gib) * MIB_PER_GIB), getOrElse(() => Math.floor(os.totalmem() / BYTES_PER_MIB / 2)));
15393
+ if (!(cpus > 0 && Number.isFinite(cpus))) {
15394
+ tool.io.stderr.write("--cpus takes a number of CPUs above 0.\n");
15395
+ return 2;
15396
+ }
15397
+ if (!(memoryMib > 0 && Number.isFinite(memoryMib))) {
15398
+ tool.io.stderr.write("--memory takes a number of GiB above 0.\n");
15399
+ return 2;
15400
+ }
15401
+ const found = onPath(DOCKER);
15402
+ if (isNone(found)) {
15403
+ tool.io.stderr.write("sandcovery engine runs sandboxes in Docker, and Docker isn't on PATH. Install Docker, then run sandcovery engine again.\n");
15404
+ return 1;
15405
+ }
15406
+ const binary = found.value;
15407
+ const version = await docker(binary, [
15408
+ "version",
15409
+ "--format",
15410
+ "{{.Server.Version}}"
15411
+ ], none());
15412
+ if (version.code !== 0) {
15413
+ tool.io.stderr.write(`sandcovery engine runs sandboxes in Docker, and Docker isn't answering on this computer: ${version.stderr}\n`);
15414
+ return 1;
15415
+ }
15416
+ const reservations = /* @__PURE__ */ new Map();
15417
+ const watch = (sandboxId) => {
15418
+ const waiter = spawn(binary, [
15419
+ "wait",
15420
+ "--",
15421
+ sandboxId
15422
+ ], { stdio: "ignore" });
15423
+ waiter.on("error", noop);
15424
+ waiter.on("close", () => {
15425
+ reservations.delete(sandboxId);
15426
+ });
15427
+ waiter.unref();
15428
+ };
15429
+ const remove = async (sandboxId) => {
15430
+ await dockerOut(binary, [
15431
+ "rm",
15432
+ "--force",
15433
+ "--",
15434
+ sandboxId
15435
+ ], none());
15436
+ reservations.delete(sandboxId);
15437
+ };
15438
+ const held = await dockerOut(binary, [
15439
+ "ps",
15440
+ "--no-trunc",
15441
+ "--filter",
15442
+ `label=${ENGINE_LABEL}=true`,
15443
+ "--format",
15444
+ `{{.ID}} {{.Label "${CPU_LABEL}"}} {{.Label "${MEMORY_LABEL}"}}`
15445
+ ], none());
15446
+ for (const line of held.split("\n").filter((row) => row !== "")) {
15447
+ const [sandboxId = "", cpu = "", memory = ""] = line.split(" ");
15448
+ reservations.set(sandboxId, {
15449
+ cpu: Number(cpu),
15450
+ memoryMib: Number(memory)
15451
+ });
15452
+ watch(sandboxId);
15453
+ }
15454
+ const key = await getOrElse(tool.key, async () => await signIn(tool));
15455
+ tool.io.stderr.write(`Your machine offers Sandcovery sandboxes ${String(cpus)} CPUs and ${String(Math.round(memoryMib / MIB_PER_GIB * 10) / 10)} GiB of memory in total. Press Ctrl-C to stop.\n`);
15456
+ const connected = async (attempt) => {
15457
+ const opened = await session({
15458
+ key,
15459
+ signal: tool.signal,
15460
+ stderr: tool.io.stderr,
15461
+ url: new URL(ENGINE_CONNECT_PATH, tool.origin),
15462
+ answer: async (request) => await engineResponse({
15463
+ ...request,
15464
+ binary,
15465
+ capacity: {
15466
+ cpus,
15467
+ memoryMib
15468
+ },
15469
+ remove,
15470
+ reservations,
15471
+ watch
15472
+ })
15473
+ });
15474
+ if (tool.signal.aborted) return 0;
15475
+ const next = opened ? 0 : attempt + 1;
15476
+ const delayMs = clamp(FIRST_RETRY_MS * 2 ** next, FIRST_RETRY_MS, LAST_RETRY_MS);
15477
+ tool.io.stderr.write(`${opened ? "Your machine lost its connection to Sandcovery" : "Your machine couldn't connect to Sandcovery"}. Trying again in ${String(delayMs / MS_PER_SECOND)} seconds.\n`);
15478
+ await setTimeout$1(delayMs, null, { signal: tool.signal });
15479
+ return await connected(next);
15480
+ };
15481
+ return await connected(0);
15482
+ };
14792
15483
  // src/cli/index.ts
14793
15484
  const PROVIDER_PACED_SECONDS = Number.POSITIVE_INFINITY;
14794
15485
  const Waits = Struct({
@@ -14802,6 +15493,10 @@ const LOCAL_COMMANDS = [
14802
15493
  run: agentsSshRun,
14803
15494
  words: ["agents", "ssh"]
14804
15495
  },
15496
+ {
15497
+ run: engineRun,
15498
+ words: ["engine"]
15499
+ },
14805
15500
  {
14806
15501
  run: loginRun,
14807
15502
  words: ["login"]
@@ -14838,8 +15533,10 @@ if (isSome(local)) {
14838
15533
  ["agents.stopAgent", PROVIDER_PACED_SECONDS],
14839
15534
  ["sandboxes.createSandbox", (ttl_seconds ?? 3600) + 60],
14840
15535
  ["sandboxes.destroySandbox", PROVIDER_PACED_SECONDS],
15536
+ ["sandboxes.detachExecSandbox", PROVIDER_PACED_SECONDS],
14841
15537
  ["sandboxes.downloadFile", PROVIDER_PACED_SECONDS],
14842
15538
  ["sandboxes.execSandbox", exec],
15539
+ ["sandboxes.getPortPreview", PROVIDER_PACED_SECONDS],
14843
15540
  ["sandboxes.listFiles", PROVIDER_PACED_SECONDS],
14844
15541
  ["sandboxes.pauseSandbox", PROVIDER_PACED_SECONDS],
14845
15542
  ["sandboxes.resumeSandbox", PROVIDER_PACED_SECONDS],