sandcovery 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
- import { B as tag, E as fromJsonString, L as makeFilter, S as decodeUnknownOption, _ as Struct, a as Finite, d as Natural, er as getOrElse, g as String$1, h as Record, i as Error$1, j as isGreaterThanOrEqualTo, k as isBetween, l as Literal, m as NullOr, n as Boolean, p as NonEmptyString, s as Int, t as ArraySchema, u as Literals, v as Union, w as decodeUnknownSync, z as optionalKey } from "./Schema-fLas6rbA.mjs";
2
- import { A as CreditCheckout, B as MicroUsd, C as RoutingFields, E as Billing, F as CiJobId, H as Region, I as CredentialId, L as GpuType, N as Pricing, P as ApiKeyId, R as KeyId, S as ROUTING_FIELDS_TEXT, T as StandardSize, U as SandboxId, V as Provider, W as Timestamp, a as Key, b as ProviderPreferences, f as Port, g as SandboxSpec, h as SandboxList, i as CreatedKey, m as Sandbox, p as PortPreview, s as KeyList, t as API_PREFIX, u as CreateAttempt, v as Snapshot, w as Slug } from "./origin-5maEGWRg.mjs";
1
+ import { A as isBase64Url$1, B as makeFilter, E as decodeUnknownSync, F as isMaxLength, H as optionalKey, I as isMinLength, L as isMultipleOf, M as isGreaterThan, N as isGreaterThanOrEqualTo, O as fromJsonString, U as tag, _ as String$1, a as Finite, cr as isSome, d as Natural, f as NonEmptyArray, g as Record, h as Number$1, i as Error$1, j as isBetween, k as is, l as Literal, m as NullOr, n as Boolean, o as FiniteFromString, p as NonEmptyString, rr as getOrElse, s as Int, t as ArraySchema, u as Literals, v as Struct, w as decodeUnknownOption, x as annotateEncoded, y as Union, z as isUUID } from "./Schema-CoX0a2_o.mjs";
3
2
  // ../../node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/ErrorReporter.js
4
3
  /**
5
4
  * Defines the runtime property key used to mark an object error as ignored by error
@@ -37,6 +36,84 @@ import { A as CreditCheckout, B as MicroUsd, C as RoutingFields, E as Billing, F
37
36
  * @since 4.0.0
38
37
  */
39
38
  const ignore = "~effect/ErrorReporter/ignore";
39
+ // ../sandcovery-contract/src/primitives.ts
40
+ const PROVIDERS = [
41
+ "daytona",
42
+ "depot",
43
+ "e2b",
44
+ "upstash"
45
+ ];
46
+ const PROVIDER_EXAMPLES = new Intl.ListFormat("en", { type: "disjunction" }).format(PROVIDERS.map((provider) => `\`${provider}\``));
47
+ const SLUG_CHARACTERS = /* @__PURE__ */ new Set("abcdefghijklmnopqrstuvwxyz0123456789-");
48
+ const isProviderName = (value) => value !== "" && value.split("").every((character) => SLUG_CHARACTERS.has(character));
49
+ const Provider = String$1.check(makeFilter(isProviderName, {
50
+ expected: "a provider name of lowercase letters, digits, and hyphens",
51
+ toJsonSchema: () => ({ minLength: 1 })
52
+ })).annotate({
53
+ description: `A provider name of lowercase letters, digits, and hyphens, such as ${PROVIDER_EXAMPLES}. The API adds providers over time, so a client accepts any such name and the API refuses one it does not serve.`,
54
+ examples: PROVIDERS,
55
+ identifier: "Provider"
56
+ });
57
+ const Region = NonEmptyString.annotate({
58
+ description: "A coarse region, such as `asia`, `eu`, or `us`. A sandbox runs in a data center of the routed provider inside that region. The API adds regions over time.",
59
+ examples: [
60
+ "asia",
61
+ "eu",
62
+ "us"
63
+ ],
64
+ identifier: "Region"
65
+ });
66
+ const GpuType = NonEmptyString.annotate({
67
+ description: "A GPU model, such as `h100`, `b200`, `rtx-pro-6000`, or `mi355x`. The API adds types over time.",
68
+ examples: [
69
+ "b200",
70
+ "b300",
71
+ "h100",
72
+ "h200",
73
+ "mi355x",
74
+ "rtx-4090",
75
+ "rtx-5090",
76
+ "rtx-pro-6000"
77
+ ],
78
+ identifier: "GpuType"
79
+ });
80
+ const isUtcTimestamp = makeFilter((value) => {
81
+ const at = Date.parse(value);
82
+ return Number.isFinite(at) && new Date(at).toISOString() === value;
83
+ }, {
84
+ expected: "a UTC timestamp such as 2026-11-08T11:20:00.000Z",
85
+ toJsonSchema: () => ({ format: "date-time" })
86
+ });
87
+ const Timestamp = String$1.check(isUtcTimestamp).annotate({ description: "A UTC instant with milliseconds and a `Z` suffix, such as `2026-11-08T11:20:00.000Z`." });
88
+ const MicroUsd = Natural.annotate({ description: "An amount in integer micro-dollars: 1,000,000 is 1 USD." });
89
+ const isUuidV7 = is(String$1.check(isUUID(7)));
90
+ const hasPrefixedUuid = (value, prefix) => value.startsWith(prefix) && isUuidV7(value.slice(prefix.length));
91
+ const prefixedId = (prefix, noun) => String$1.check(makeFilter((value) => hasPrefixedUuid(value, prefix), {
92
+ expected: `${prefix} followed by a UUID v7`,
93
+ toJsonSchema: () => ({})
94
+ })).annotate({ description: `${noun} ID: \`${prefix}\` followed by a UUID v7.` });
95
+ const SandboxId = prefixedId("sbx_", "Sandbox");
96
+ const SnapshotId = prefixedId("snap_", "Snapshot");
97
+ const CiJobId = prefixedId("cij_", "CI job");
98
+ const CredentialId = prefixedId("cred_", "Provider credential");
99
+ const ProcessId = prefixedId("proc_", "Process");
100
+ const UsageShareId = prefixedId("ush_", "Usage share");
101
+ const API_KEY_ID_PREFIX = "key_";
102
+ const MANAGEMENT_KEY_ID_PREFIX = "mkey_";
103
+ const ApiKeyId = prefixedId(API_KEY_ID_PREFIX, "API key");
104
+ const KeyId = String$1.check(makeFilter((value) => hasPrefixedUuid(value, API_KEY_ID_PREFIX) || hasPrefixedUuid(value, MANAGEMENT_KEY_ID_PREFIX), {
105
+ expected: `${API_KEY_ID_PREFIX} or ${MANAGEMENT_KEY_ID_PREFIX} followed by a UUID v7`,
106
+ toJsonSchema: () => ({})
107
+ })).annotate({ description: `Key ID: \`${API_KEY_ID_PREFIX}\` for an API key or \`${MANAGEMENT_KEY_ID_PREFIX}\` for a management key, followed by a UUID v7.` });
108
+ const SECRET_TEXT_LENGTH = 43;
109
+ const isBase64Url = is(String$1.check(isBase64Url$1()));
110
+ const API_KEY_SECRET_PREFIX = "sand_";
111
+ const MANAGEMENT_KEY_SECRET_PREFIX = "sandm_";
112
+ const hasPrefixedSecret = (value, prefix) => value.startsWith(prefix) && value.length === prefix.length + SECRET_TEXT_LENGTH && isBase64Url(value.slice(prefix.length));
113
+ const KeySecret = String$1.check(makeFilter((value) => hasPrefixedSecret(value, API_KEY_SECRET_PREFIX) || hasPrefixedSecret(value, MANAGEMENT_KEY_SECRET_PREFIX), {
114
+ expected: `${API_KEY_SECRET_PREFIX} or ${MANAGEMENT_KEY_SECRET_PREFIX} followed by 43 base64url characters`,
115
+ toJsonSchema: () => ({})
116
+ })).annotate({ description: `The key secret, returned once at creation: \`${API_KEY_SECRET_PREFIX}\` for an API key or \`${MANAGEMENT_KEY_SECRET_PREFIX}\` for a management key, followed by 32 random bytes as 43 unpadded base64url characters.` });
40
117
  const ActivityAction = NonEmptyString.annotate({
41
118
  description: "What happened, such as `sandbox.create`, `sandbox.create_attempt` for each provider tried, `sandbox.destroy`, or `sandbox.expire` at the TTL. The API adds actions over time.",
42
119
  examples: [
@@ -67,6 +144,176 @@ const ActivityList = Struct({
67
144
  data: ArraySchema(ActivityEvent),
68
145
  next_cursor: NullOr(String$1)
69
146
  }).annotate({ identifier: "ActivityList" });
147
+ // ../sandcovery-contract/src/billing.ts
148
+ const FREE_PLAN = "free";
149
+ const ENTERPRISE_PLAN = "enterprise";
150
+ const MICRO_USD_PER_DOLLAR = 1e6;
151
+ const CREDIT_PURCHASE_MIN_MICRO_USD = 25 * MICRO_USD_PER_DOLLAR;
152
+ const CREDIT_PURCHASE_MAX_MICRO_USD = 1e3 * MICRO_USD_PER_DOLLAR;
153
+ const CARD_FEE_TERMS = "2.9% plus 30 cents";
154
+ const NO_MARKUP_TERMS = [
155
+ "Sandbox usage carries no markup.",
156
+ "On your own provider keys, each provider bills you at its own prices, and Sandcovery charges nothing for that usage.",
157
+ `Credits pay each provider's list price for a sandbox's size, from its start until it ends, and a card processing fee of ${CARD_FEE_TERMS} comes out of each credit purchase.`,
158
+ "Beyond list prices and that fee, Sandcovery charges only for its Pro and Enterprise plans, each a fixed fee for each organization."
159
+ ].join(" ");
160
+ const Plan = Literals([
161
+ FREE_PLAN,
162
+ "pro",
163
+ ENTERPRISE_PLAN
164
+ ]).annotate({
165
+ description: "The organization plan: `pro` or `enterprise` while that subscription is active, trialing, or past due, otherwise `free`. `enterprise` is Pro for an organization that connects a GitHub account a GitHub Enterprise owns.",
166
+ identifier: "Plan"
167
+ });
168
+ const ProInterval = Literals([
169
+ "day",
170
+ "month",
171
+ "week",
172
+ "year"
173
+ ]).annotate({
174
+ description: "How often the plan fee is charged.",
175
+ identifier: "ProInterval"
176
+ });
177
+ const ProPrice = Struct({
178
+ interval: ProInterval,
179
+ micro_usd: MicroUsd
180
+ }).annotate({
181
+ description: "The fixed fee of a plan for each billing interval.",
182
+ identifier: "ProPrice"
183
+ });
184
+ const EnterprisePrice = NullOr(ProPrice).annotate({ description: "The Enterprise price, or null while the Enterprise plan is not on sale." });
185
+ const Billing = Struct({
186
+ credit_balance_micro_usd: Int.annotate({ description: "Credits bought, less refunds and open disputes. A refund after use can take it below zero." }),
187
+ credits_on_sale: Boolean.annotate({ description: "Whether a credit purchase is open." }),
188
+ enterprise_price: EnterprisePrice,
189
+ github_enterprise: Boolean.annotate({ description: "Whether a GitHub Enterprise owns a GitHub account this organization connected to Sandcovery CI, so that its jobs run only on the Enterprise plan." }),
190
+ plan: Plan,
191
+ pro_price: NullOr(ProPrice).annotate({ description: "The Pro price, or null while Pro is not on sale." })
192
+ }).annotate({ identifier: "Billing" });
193
+ const CreditTerms = Struct({
194
+ fee_fixed_micro_usd: MicroUsd.annotate({ description: "The fixed part of the processing fee that comes out of each credit purchase." }),
195
+ fee_rate_basis_points: Natural.annotate({ description: "The part of the processing fee that grows with the payment, in basis points of it, rounded to the cent: 290 is 2.9%." }),
196
+ max_micro_usd: MicroUsd.annotate({ description: "The largest credit purchase, in whole US dollars." }),
197
+ min_micro_usd: MicroUsd.annotate({ description: "The smallest credit purchase, in whole US dollars." })
198
+ }).annotate({
199
+ description: "How credits are bought: a payment in whole US dollars between the two bounds adds credit equal to the payment less the processing fee, spent at each provider list price.",
200
+ identifier: "CreditTerms"
201
+ });
202
+ const Pricing = Struct({
203
+ credits: CreditTerms,
204
+ enterprise_price: EnterprisePrice,
205
+ pro_price: NullOr(ProPrice).annotate({ description: "The Pro price, or null while Pro is not on sale." })
206
+ }).annotate({
207
+ description: "The public prices: the Pro and Enterprise prices for one organization and the terms of a credit purchase.",
208
+ identifier: "Pricing"
209
+ });
210
+ Struct({ amount_micro_usd: MicroUsd.check(isMultipleOf(MICRO_USD_PER_DOLLAR), isBetween({
211
+ maximum: CREDIT_PURCHASE_MAX_MICRO_USD,
212
+ minimum: CREDIT_PURCHASE_MIN_MICRO_USD
213
+ })).annotate({ description: `Whole US dollars charged to the card, from 25 to 1,000 USD. The credits granted are this amount less the processing fee of ${CARD_FEE_TERMS}, rounded to the cent.` }) }).annotate({ identifier: "CreditPurchaseRequest" });
214
+ const CreditCheckout = Struct({ url: String$1.annotate({ description: "The Stripe Checkout page that takes the payment. The credits arrive once Stripe confirms it." }) }).annotate({ identifier: "CreditCheckout" });
215
+ const StandardSize = NonEmptyString.annotate({
216
+ description: "A standard size named `<vCPU>x<memory GiB>`, such as `1x2`, `2x4`, `4x8`, or `8x16`. The API adds sizes over time.",
217
+ examples: [
218
+ {
219
+ memory_mib: 2048,
220
+ name: "1x2",
221
+ vcpu: 1
222
+ },
223
+ {
224
+ memory_mib: 4096,
225
+ name: "2x4",
226
+ vcpu: 2
227
+ },
228
+ {
229
+ memory_mib: 8192,
230
+ name: "4x8",
231
+ vcpu: 4
232
+ },
233
+ {
234
+ memory_mib: 16384,
235
+ name: "8x16",
236
+ vcpu: 8
237
+ }
238
+ ].map(({ name }) => name),
239
+ identifier: "StandardSize"
240
+ });
241
+ const ProviderSort = Literals([
242
+ "latency",
243
+ "price",
244
+ "uptime"
245
+ ]).annotate({
246
+ description: "Candidate order: `price` by list price, `latency` by measured create latency, and `uptime` by uptime over the last 15 minutes, or over a provider's own probe interval where it is probed less often.",
247
+ identifier: "ProviderSort"
248
+ });
249
+ const ROUTER = "sandcovery";
250
+ const DEFAULT_SLUG = `${ROUTER}/2x4`;
251
+ const MIB_PER_GIB = 1024;
252
+ const ANY = "n";
253
+ const vcpusOf = (text) => {
254
+ if (text === ANY) return null;
255
+ const value = Number(text);
256
+ return Number.isSafeInteger(value) && value > 0 && String(value) === text ? value : void 0;
257
+ };
258
+ const memoryGibOf = (text) => {
259
+ if (text === ANY) return null;
260
+ const value = Number(text);
261
+ return String(value) === text && value > 0 && Number.isSafeInteger(value * MIB_PER_GIB) ? value : void 0;
262
+ };
263
+ const parseSlug = (text) => {
264
+ const [provider = "", size = "", ...extraPaths] = text.split("/");
265
+ const [dimensions = "", suffix, ...extraSuffixes] = size.split(":");
266
+ const [vcpuText = "", memoryText = "", ...extraParts] = dimensions.split("x");
267
+ if (extraPaths.length + extraSuffixes.length + extraParts.length > 0 || suffix === "" || !isProviderName(provider)) return;
268
+ const vcpus = vcpusOf(vcpuText);
269
+ const memoryGib = memoryGibOf(memoryText);
270
+ return vcpus === void 0 || memoryGib === void 0 ? void 0 : {
271
+ memoryGib,
272
+ provider,
273
+ suffix: suffix ?? null,
274
+ vcpus
275
+ };
276
+ };
277
+ const isSizeName = (text) => {
278
+ const parsed = parseSlug(`${ROUTER}/${text}`);
279
+ return parsed !== void 0 && parsed.suffix === null && parsed.vcpus !== null && parsed.memoryGib !== null;
280
+ };
281
+ const SizeName = String$1.check(makeFilter(isSizeName, {
282
+ expected: "<vcpu>x<memory_gib>, such as 2x4 or 2x0.5",
283
+ toJsonSchema: () => ({ minLength: 1 })
284
+ }));
285
+ const SLUG_EXAMPLES = [
286
+ `${ROUTER}/2x4`,
287
+ `${ROUTER}/2x4:cheapest`,
288
+ `${ROUTER}/nx16:cheapest`,
289
+ `${ROUTER}/2xn:fastest`,
290
+ `${ROUTER}/nxn:most-reliable`,
291
+ "boat/2x4",
292
+ "e2b/2x0.5"
293
+ ];
294
+ const Slug = String$1.check(makeFilter((text) => parseSlug(text) !== void 0, {
295
+ expected: "<provider>/<vcpu>x<memory_gib>, optionally followed by a routing suffix",
296
+ toJsonSchema: () => ({ minLength: 1 })
297
+ })).annotate({
298
+ description: `A provider and size, written \`<provider>/<vcpu>x<memory_gib>\` and optionally followed by a routing suffix, in the shape of OpenRouter model slugs. A provider name such as \`boat\` or \`e2b\` pins that provider, and \`${ROUTER}\` routes across every candidate provider. \`2x4\` is 2 vCPU and 4 GiB, and memory may be any whole number of MiB written in GiB, such as \`2x0.5\` or \`2x1.5\`. Either number may be \`n\`, meaning any value: \`nx16\` is any vCPU count with 16 GiB, \`2xn\` is 2 vCPU with any memory, and \`nxn\` is any size, and each provider then runs its cheapest size that matches. \`:cheapest\` sorts candidates by list price, \`:fastest\` by measured create latency, and \`:most-reliable\` by uptime over the last 15 minutes, or over a provider's own probe interval where it is probed less often. A slug with no suffix routes as \`:cheapest\`. A malformed slug or an unknown suffix answers 400 \`invalid_request\`, and a slug that no candidate provider can run answers 422 \`unsupported\`, listing slugs that would run as \`options\`.`,
299
+ examples: SLUG_EXAMPLES,
300
+ identifier: "Slug"
301
+ });
302
+ const ROUTING_FIELDS_TEXT = `\`slug\` is the provider and size to run, as OpenRouter takes \`model\`, and \`slugs\` lists slugs to try in order, as OpenRouter takes \`models\`. With both, \`slug\` is tried first. With neither, the slug is \`${DEFAULT_SLUG}\`.`;
303
+ const RoutingFields = {
304
+ slug: optionalKey(Slug),
305
+ slugs: optionalKey(ArraySchema(Slug).check(isMinLength(1), isMaxLength(8)).annotate({ description: `Slugs to try in order, from 1 to ${String(8)}, as OpenRouter takes \`models\`. Within a \`${ROUTER}/\` slug, a failed create (capacity, quota, a provider 5xx, or a timeout) first falls back across that slug's candidates, then the create moves to the next slug. A provider is tried at most once a create, at the size of the first slug that reaches it.` }))
306
+ };
307
+ const ProviderPreferences = Struct({
308
+ allow_fallbacks: optionalKey(Boolean.annotate({ description: "Whether a failed create (capacity, quota, a provider 5xx, or a timeout) moves to the next candidate of the same slug. Defaults to true. With false, each slug tries only its first candidate, and the create still moves on to the next slug." })),
309
+ ignore: optionalKey(ArraySchema(Provider).annotate({ description: "Providers never to route to." })),
310
+ only: optionalKey(ArraySchema(Provider).annotate({ description: "The only providers to route to." })),
311
+ order: optionalKey(ArraySchema(Provider).annotate({ description: `Providers a \`${ROUTER}/\` slug tries first, in this order, before its remaining candidates in sorted order.` })),
312
+ sort: optionalKey(ProviderSort)
313
+ }).annotate({
314
+ description: `Routing preferences in the shape of OpenRouter provider preferences, applied to every slug: \`only\`, \`ignore\`, and the API key's provider allowlist filter each slug's candidates. A slug's suffix sets \`sort\` for that slug, and a slug whose suffix disagrees with \`sort\` answers 400 \`invalid_request\`.`,
315
+ identifier: "ProviderPreferences"
316
+ });
70
317
  // ../sandcovery-contract/src/providers.ts
71
318
  const Ratio = Finite.check(isBetween({
72
319
  maximum: 1,
@@ -469,6 +716,148 @@ var InvalidRequest = class extends Error$1("InvalidRequest")({
469
716
  }) {
470
717
  [ignore] = true;
471
718
  };
719
+ // ../sandcovery-contract/src/sandbox.ts
720
+ const MAX_TTL_SECONDS = 86400;
721
+ const MAX_PORT = 65535;
722
+ const MAX_PORTS = 8;
723
+ const MAX_GPUS = 8;
724
+ const between = (minimum, maximum) => Int.check(isBetween({
725
+ maximum,
726
+ minimum
727
+ }));
728
+ const Port = between(1, MAX_PORT);
729
+ const Gpu = Struct({
730
+ count: between(1, MAX_GPUS).annotate({ description: "How many GPUs of `type` the sandbox gets, from 1 to 8." }),
731
+ type: GpuType
732
+ }).annotate({
733
+ description: "GPUs for the sandbox. It runs only on a provider that runs `count` GPUs of `type`, which picks the sandbox's region itself, so a GPU sandbox takes no `region`. Its list price adds each GPU's hourly price to the price of its size.",
734
+ identifier: "Gpu"
735
+ });
736
+ const EnvironmentVariables = Record(NonEmptyString, String$1).annotate({ description: "Environment variables by name. Sandcovery passes them to the provider and never returns them." });
737
+ const EgressPolicy = Union([
738
+ Struct({ mode: Literal("allow_all") }),
739
+ Struct({ mode: Literal("deny_all") }),
740
+ Struct({
741
+ destinations: NonEmptyArray(NonEmptyString).annotate({ description: "Host names or CIDR blocks the sandbox may reach." }),
742
+ mode: Literal("allowlist")
743
+ })
744
+ ]).annotate({
745
+ description: "Outbound network access: `allow_all`, `deny_all`, or `allowlist` with the destinations the sandbox may reach.",
746
+ identifier: "EgressPolicy"
747
+ });
748
+ const SandboxSpec = Struct({
749
+ disk_mib: optionalKey(Int.check(isGreaterThanOrEqualTo(1024)).annotate({ description: "Disk size in MiB. Defaults to the provider default." })),
750
+ egress: optionalKey(EgressPolicy),
751
+ env: optionalKey(EnvironmentVariables),
752
+ gpu: optionalKey(Gpu),
753
+ idle_timeout_seconds: optionalKey(Int.check(isGreaterThanOrEqualTo(60)).annotate({ description: "Seconds without a running command after which the provider pauses the sandbox. Unset means no idle timeout." })),
754
+ image: optionalKey(NonEmptyString.annotate({ description: "An OCI image reference. Unset means the provider's default Linux image." })),
755
+ ports: optionalKey(ArraySchema(Port).check(isMaxLength(MAX_PORTS)).annotate({ description: "Ports to expose for preview URLs. Some providers expose only ports declared at create." })),
756
+ region: optionalKey(Region),
757
+ ttl_seconds: optionalKey(between(60, MAX_TTL_SECONDS).annotate({ description: "Seconds from creation after which Sandcovery destroys the sandbox, even when the client is gone. Defaults to 3600, and the API key may cap it lower." }))
758
+ });
759
+ const CreateSandboxRequest = Struct({
760
+ ...SandboxSpec.fields,
761
+ ...RoutingFields,
762
+ provider: optionalKey(ProviderPreferences),
763
+ snapshot_id: optionalKey(SnapshotId.annotate({ description: "A snapshot to start from. The sandbox runs on the snapshot's provider." }))
764
+ }).annotate({
765
+ description: `A sandbox spec, the slug or slugs to run it on, and routing preferences. ${ROUTING_FIELDS_TEXT} A spec option that no candidate provider can enforce answers 422 \`unsupported\` and is never ignored.`,
766
+ identifier: "CreateSandboxRequest"
767
+ });
768
+ const CreateAttempt = Struct({
769
+ duration_ms: Natural,
770
+ failure: NullOr(Struct({
771
+ message: String$1,
772
+ reason: Literals([
773
+ "capacity",
774
+ "quota",
775
+ "rejected",
776
+ "server_error",
777
+ "timeout"
778
+ ]).annotate({ identifier: "CreateFailureReason" })
779
+ }).annotate({ description: "Why the attempt failed: `capacity`, `quota`, `server_error` (a provider 5xx), and `timeout` fall back to the next candidate when `allow_fallbacks` is not false, while `rejected` (any other provider refusal, such as an invalid credential) stops the create, which answers 502 `provider_error` naming that provider." })),
780
+ provider: Provider,
781
+ started_at: Timestamp
782
+ }).annotate({
783
+ description: "One provider create call made while routing a sandbox. `failure` is null on the attempt that created it.",
784
+ identifier: "CreateAttempt"
785
+ });
786
+ const SandboxStatus = Literals([
787
+ "creating",
788
+ "destroyed",
789
+ "destroying",
790
+ "failed",
791
+ "paused",
792
+ "running"
793
+ ]).annotate({ identifier: "SandboxStatus" });
794
+ const SandboxEndReason = Literals([
795
+ "create_failed",
796
+ "destroyed",
797
+ "expired",
798
+ "gone"
799
+ ]).annotate({
800
+ description: "Why the sandbox ended: `create_failed` when no create attempt succeeded, `destroyed` by a destroy call, `expired` at its TTL, or `gone` when the provider no longer had it.",
801
+ identifier: "SandboxEndReason"
802
+ });
803
+ const SandboxCost = Struct({
804
+ estimated_micro_usd: MicroUsd.annotate({ description: "Estimated list-price cost so far, from the rate card, until the sandbox is destroyed." }),
805
+ hourly_micro_usd: MicroUsd,
806
+ rate_card_version: String$1
807
+ }).annotate({
808
+ description: "Estimated cost at the provider's list price from a versioned rate card. The provider bills your own account.",
809
+ identifier: "SandboxCost"
810
+ });
811
+ const Sandbox = Struct({
812
+ api_key_id: NullOr(ApiKeyId).annotate({ description: "The API key that created the sandbox, or null when an organization owner or admin created it while signed in, or their agent did on their session." }),
813
+ attempts: ArraySchema(CreateAttempt),
814
+ cost: SandboxCost,
815
+ created_at: Timestamp,
816
+ disk_mib: NullOr(Natural),
817
+ egress: EgressPolicy,
818
+ end_reason: NullOr(SandboxEndReason),
819
+ ended_at: NullOr(Timestamp),
820
+ expires_at: Timestamp,
821
+ gpu: NullOr(Gpu),
822
+ id: SandboxId,
823
+ idle_timeout_seconds: NullOr(Natural),
824
+ image: NullOr(String$1),
825
+ memory_mib: Natural.annotate({ description: "Memory of the bound size, or of the first candidate's size while the sandbox is creating or after every create attempt failed." }),
826
+ ports: ArraySchema(Port),
827
+ provider: NullOr(Provider).annotate({ description: "The provider the sandbox is bound to, or null while it is creating or when every create attempt failed." }),
828
+ provider_sandbox_id: NullOr(String$1),
829
+ region: NullOr(Region),
830
+ slug: NullOr(Slug).annotate({ description: "The provider and size the sandbox runs on, such as `boat/2x4`, as OpenRouter answers the `model` it used, or null while it is creating or when every create attempt failed." }),
831
+ started_at: NullOr(Timestamp).annotate({ description: "When the provider reported the sandbox running." }),
832
+ status: SandboxStatus,
833
+ ttl_seconds: Natural,
834
+ vcpu: Natural.annotate({ description: "vCPU count of the bound size, or of the first candidate's size while the sandbox is creating or after every create attempt failed." })
835
+ }).annotate({
836
+ description: "A sandbox, bound to the provider that created it. `expires_at` is when Sandcovery destroys it, and pausing does not move it. `ended_at` and `end_reason` are set once it ends.",
837
+ identifier: "Sandbox"
838
+ });
839
+ const SandboxList = Struct({
840
+ data: ArraySchema(Sandbox),
841
+ next_cursor: NullOr(String$1)
842
+ }).annotate({ identifier: "SandboxList" });
843
+ const Snapshot = Struct({
844
+ created_at: Timestamp,
845
+ id: SnapshotId,
846
+ provider: Provider,
847
+ sandbox_id: SandboxId
848
+ }).annotate({
849
+ description: "A snapshot of a sandbox filesystem. A sandbox created from it runs on the same provider.",
850
+ identifier: "Snapshot"
851
+ });
852
+ const PortPreview = Struct({
853
+ expires_at: NullOr(Timestamp),
854
+ headers: Record(String$1, String$1).annotate({ description: "Headers a request to `url` must carry, such as a provider preview token. Often empty." }),
855
+ port: Port,
856
+ url: String$1
857
+ }).annotate({
858
+ description: "A provider URL that reaches a port inside the sandbox.",
859
+ identifier: "PortPreview"
860
+ });
472
861
  // ../sandcovery-contract/src/errors/no-provider-available.ts
473
862
  var NoProviderAvailable = class extends Error$1("NoProviderAvailable")({
474
863
  attempts: ArraySchema(CreateAttempt).annotate({ description: "Every create attempt, in order. Empty when no provider was a candidate, such as when none has a stored credential." }),
@@ -500,6 +889,17 @@ var ProviderError = class extends Error$1("ProviderError")({
500
889
  httpApiStatus: 502,
501
890
  identifier: "ProviderError"
502
891
  }) {};
892
+ // ../sandcovery-contract/src/errors/rate-limited.ts
893
+ var RateLimited = class extends Error$1("RateLimited")({
894
+ error: tag("rate_limited"),
895
+ message: String$1
896
+ }, {
897
+ description: "The caller sent this operation more requests than its limit allows, such as more than 3 problem reports a minute. Wait a minute and try again.",
898
+ httpApiStatus: 429,
899
+ identifier: "RateLimited"
900
+ }) {
901
+ [ignore] = true;
902
+ };
503
903
  // ../sandcovery-contract/src/errors/spend-limit-reached.ts
504
904
  var SpendLimitReached = class extends Error$1("SpendLimitReached")({
505
905
  error: tag("spend_limit_reached"),
@@ -547,6 +947,7 @@ const ApiError = Union([
547
947
  NoProviderAvailable,
548
948
  NotFound,
549
949
  ProviderError,
950
+ RateLimited,
550
951
  SpendLimitReached,
551
952
  Unauthorized,
552
953
  Unsupported
@@ -625,21 +1026,147 @@ const FileList = Struct({
625
1026
  entries: ArraySchema(FileEntry),
626
1027
  path: String$1
627
1028
  }).annotate({ identifier: "FileList" });
1029
+ const KeyName = NonEmptyString.check(isMaxLength(64));
1030
+ const PositiveInt = Int.check(isGreaterThanOrEqualTo(1));
1031
+ const KeyKind = Literals(["api", "management"]).annotate({
1032
+ description: "An `api` key creates and drives sandboxes. A `management` key mints, changes, and revokes keys, sets provider credentials, and reads usage, and reaches no sandbox.",
1033
+ identifier: "KeyKind"
1034
+ });
1035
+ const SpendLimit = Struct({
1036
+ limit_micro_usd: MicroUsd,
1037
+ period: Literals([
1038
+ "day",
1039
+ "month",
1040
+ "total",
1041
+ "week"
1042
+ ]).annotate({
1043
+ description: "The window the limit counts: a UTC `day`, an ISO `week` from Monday 00:00 UTC, a UTC calendar `month`, or the key `total`.",
1044
+ identifier: "SpendLimitPeriod"
1045
+ })
1046
+ }).annotate({
1047
+ description: "A cap on the list-price cost of sandboxes the key creates, counting usage billed to your own provider accounts.",
1048
+ identifier: "SpendLimit"
1049
+ });
1050
+ const keyPolicyFields = {
1051
+ allowed_providers: NullOr(ArraySchema(Provider)).annotate({ description: "The only providers the key may route to. Null allows all." }),
1052
+ max_concurrent_sandboxes: NullOr(PositiveInt),
1053
+ max_ttl_seconds: NullOr(PositiveInt),
1054
+ spend_limit: NullOr(SpendLimit)
1055
+ };
1056
+ const Key = Struct({
1057
+ ...keyPolicyFields,
1058
+ created_at: Timestamp,
1059
+ expires_at: NullOr(Timestamp),
1060
+ id: KeyId,
1061
+ kind: KeyKind,
1062
+ last_used_at: NullOr(Timestamp),
1063
+ name: String$1,
1064
+ revoked_at: NullOr(Timestamp),
1065
+ spend: Struct({
1066
+ resets_at: NullOr(Timestamp),
1067
+ spent_micro_usd: MicroUsd
1068
+ }).annotate({ description: "List-price cost counted against `spend_limit` in its current window, or in total when the key has no limit. Always 0 for a management key." }),
1069
+ start: String$1.annotate({ description: "The first 12 characters of the secret, for display." })
1070
+ }).annotate({
1071
+ description: "An API key or a management key. Its secret is never returned after creation, and the limits are null on a management key.",
1072
+ identifier: "Key"
1073
+ });
1074
+ const KeyList = Struct({ data: ArraySchema(Key) }).annotate({ identifier: "KeyList" });
1075
+ const CreateKeyRequest = Struct({
1076
+ allowed_providers: optionalKey(keyPolicyFields.allowed_providers),
1077
+ expires_at: optionalKey(NullOr(Timestamp)),
1078
+ kind: optionalKey(KeyKind).annotate({ description: "Defaults to `api`. Only a signed-in owner mints a `management` key, and a management key takes no limits." }),
1079
+ max_concurrent_sandboxes: optionalKey(keyPolicyFields.max_concurrent_sandboxes),
1080
+ max_ttl_seconds: optionalKey(keyPolicyFields.max_ttl_seconds),
1081
+ name: KeyName,
1082
+ spend_limit: optionalKey(keyPolicyFields.spend_limit)
1083
+ }).annotate({ identifier: "CreateKeyRequest" });
1084
+ const UpdateKeyRequest = Struct({
1085
+ allowed_providers: optionalKey(keyPolicyFields.allowed_providers),
1086
+ expires_at: optionalKey(NullOr(Timestamp)),
1087
+ max_concurrent_sandboxes: optionalKey(keyPolicyFields.max_concurrent_sandboxes),
1088
+ max_ttl_seconds: optionalKey(keyPolicyFields.max_ttl_seconds),
1089
+ name: optionalKey(KeyName),
1090
+ spend_limit: optionalKey(keyPolicyFields.spend_limit)
1091
+ }).annotate({
1092
+ description: "Fields to change. An absent field keeps its value, and null clears a limit. A limit on a management key answers 400 `invalid_request`.",
1093
+ identifier: "UpdateKeyRequest"
1094
+ });
1095
+ const CreatedKey = Struct({
1096
+ key: Key,
1097
+ secret: KeySecret
1098
+ }).annotate({ identifier: "CreatedKey" });
628
1099
  // ../sandcovery-contract/src/offer.ts
629
1100
  const VcpuSeconds = Natural;
1101
+ const POST_URL_MAX = 2048;
1102
+ const SANDCOVERY_X_HANDLE = "Sandcovery";
630
1103
  const Offer = Struct({
631
1104
  cap_vcpu_seconds: VcpuSeconds.annotate({ description: "The free vCPU-seconds the account has earned in total, with no reset: `vcpu_seconds_per_key` for each counted key once `keys_counted` reaches `keys_needed`, and 0 before." }),
632
- keys_counted: Natural.annotate({ description: "Providers the account has earned free vCPU-seconds for, counted once each for good: each is a provider that accepted a credential an organization the account owns stored, when it was stored for a provider that names the account a key belongs to and otherwise when a sandbox first ran on it. A key, or a provider account a provider names, that already earned for any account counts nothing, and removing a credential and storing it again counts nothing more." }),
1105
+ keys_counted: Natural.annotate({ description: "Providers the account has earned free vCPU-seconds for, counted once each for good, plus one for a counted post on X: each provider accepted a credential an organization the account owns stored, when it was stored for a provider that names the account a key belongs to and otherwise when a sandbox first ran on it. A key, or a provider account a provider names, that already earned for any account counts nothing, and removing a credential and storing it again counts nothing more." }),
633
1106
  keys_needed: Natural.annotate({ description: "Counted keys the account needs before its sandboxes may run on free vCPU-seconds." }),
634
1107
  month_used_up: Boolean.annotate({ description: "Whether the free vCPU-seconds on `provider` that all accounts share this month are used up, so no free sandbox fits until use more than 31 days old stops counting. The account's own `remaining_vcpu_seconds` stays as it is, and a create that would go past the month's share routes to a provider whose credential the organization stored, or fails with `no_provider_available`." }),
635
1108
  provider: Provider.annotate({ description: "The provider whose sandboxes run on free vCPU-seconds, on its account that Sandcovery pays for." }),
636
1109
  remaining_vcpu_seconds: VcpuSeconds.annotate({ description: "`cap_vcpu_seconds` less `used_vcpu_seconds`, never below zero." }),
637
1110
  used_vcpu_seconds: VcpuSeconds.annotate({ description: "vCPU-seconds of the account's ended free sandboxes as they ran, plus each live one's vCPUs over its full TTL." }),
638
- vcpu_seconds_per_key: VcpuSeconds.annotate({ description: "The free vCPU-seconds each counted key earns." })
1111
+ vcpu_seconds_per_key: VcpuSeconds.annotate({ description: "The free vCPU-seconds each counted key earns." }),
1112
+ x_post_counted: Boolean.annotate({ description: `Whether a post on X that tags @${SANDCOVERY_X_HANDLE} counted as one of the account's keys. One post counts per account, for good.` })
639
1113
  }).annotate({
640
1114
  description: "Free vCPU-seconds on `provider`, which an organization with no credential of its own for `provider` may route to. They belong to the account that owns the organization, the organization's earliest owner, and every organization that account owns draws on them.",
641
1115
  identifier: "Offer"
642
1116
  });
1117
+ Struct({ url: NonEmptyString.check(isMaxLength(POST_URL_MAX)).annotate({ description: "The post's address on x.com or twitter.com, such as `https://x.com/<handle>/status/<id>`." }) }).annotate({
1118
+ description: `A post on X that tags @${SANDCOVERY_X_HANDLE}, to count as one key of the free vCPU-seconds.`,
1119
+ identifier: "XPostRequest"
1120
+ });
1121
+ // ../sandcovery-contract/src/origin.ts
1122
+ const SANDCOVERY_ORIGIN = "https://www.sandcovery.com";
1123
+ const isLocalPath = (path) => path.startsWith("/") && !path.startsWith("//") && !path.startsWith("/\\");
1124
+ const LocalPath = String$1.check(makeFilter(isLocalPath, { expected: "a path on this site" }));
1125
+ const API_PREFIX = "/api/v1";
1126
+ // ../sandcovery-contract/src/process.ts
1127
+ const TerminalCells = Int.check(isBetween({
1128
+ maximum: 65535,
1129
+ minimum: 1
1130
+ }));
1131
+ const ProcessTerminal = Struct({
1132
+ cols: TerminalCells.annotate({ description: "Columns of the terminal." }),
1133
+ rows: TerminalCells.annotate({ description: "Rows of the terminal." }),
1134
+ stderr: Boolean.annotate({ description: "Whether stderr is the terminal." }),
1135
+ stdin: Boolean.annotate({ description: "Whether stdin is the terminal." }),
1136
+ stdout: Boolean.annotate({ description: "Whether stdout is the terminal." })
1137
+ }).annotate({
1138
+ description: "A pseudo-terminal of the given size, and which of stdin, stdout, and stderr sit on it. At least one does; the rest are pipes.",
1139
+ identifier: "ProcessTerminal"
1140
+ });
1141
+ Struct({
1142
+ ...commandFields,
1143
+ terminal: optionalKey(ProcessTerminal)
1144
+ }).annotate({
1145
+ description: "A command to run as a process, with no timeout, on a terminal or on pipes.",
1146
+ identifier: "ProcessRequest"
1147
+ });
1148
+ const ProcessStatus = Literals([
1149
+ "exited",
1150
+ "lost",
1151
+ "running"
1152
+ ]).annotate({
1153
+ description: "`running` until the command exits, then `exited`, or `lost` when the sandbox ended before the process reported an exit.",
1154
+ identifier: "ProcessStatus"
1155
+ });
1156
+ const Process = Struct({
1157
+ command: String$1,
1158
+ created_at: Timestamp,
1159
+ exit_code: NullOr(Int).annotate({ description: "The exit code, 128 plus the signal number after a signal, or null until the command exits." }),
1160
+ exited_at: NullOr(Timestamp),
1161
+ id: ProcessId,
1162
+ sandbox_id: SandboxId,
1163
+ signal: NullOr(String$1).annotate({ description: "The signal that ended the command, such as `SIGKILL`." }),
1164
+ status: ProcessStatus,
1165
+ terminal: NullOr(ProcessTerminal)
1166
+ }).annotate({
1167
+ description: "A command a sandbox runs on a terminal or pipes. A client attaches to its stdin, stdout, stderr, resizes, and signals over a WebSocket at `/api/v1/sandboxes/{sandbox_id}/processes/{process_id}/attach`.",
1168
+ identifier: "Process"
1169
+ });
643
1170
  // ../sandcovery-contract/src/usage.ts
644
1171
  const EstimateRequest = Struct({
645
1172
  ...SandboxSpec.fields,
@@ -660,6 +1187,32 @@ const Estimate = Struct({
660
1187
  identifier: "Estimate"
661
1188
  });
662
1189
  const EstimateList = Struct({ data: ArraySchema(Estimate).annotate({ description: "One estimate per candidate provider that can run the spec, in routing order, each at the size of the first slug that reaches it." }) }).annotate({ identifier: "EstimateList" });
1190
+ const MONTH_TEXT = "an average month of 365/12 days";
1191
+ const MonthlyCostQuery = Struct({
1192
+ hours_per_day: FiniteFromString.check(isGreaterThan(0), isBetween({
1193
+ maximum: 24,
1194
+ minimum: 0
1195
+ })).pipe(annotateEncoded({ description: `Hours a day the sandbox runs, above 0 and at most ${String(24)}, such as 8 or 0.5.` })),
1196
+ size: SizeName.annotate({ description: "The size to price, `<vcpu>x<memory_gib>` as in a slug, such as `2x4` or `2x0.5`." })
1197
+ });
1198
+ const MonthlyCost = Struct({
1199
+ hourly_micro_usd: MicroUsd,
1200
+ monthly_micro_usd: MicroUsd.annotate({ description: `List-price cost of the size running \`hours_per_day\` hours on every day of ${MONTH_TEXT}.` }),
1201
+ provider: Provider,
1202
+ rate_card_source_url: String$1.annotate({ description: "The provider's public pricing page the rate card copies." }),
1203
+ rate_card_version: String$1,
1204
+ slug: Slug
1205
+ }).annotate({
1206
+ description: "The list price of one size on one provider, by the hour and for a month, with the slug that pins it there, such as `e2b/2x4`.",
1207
+ identifier: "MonthlyCost"
1208
+ });
1209
+ const MonthlyCostList = Struct({
1210
+ data: ArraySchema(MonthlyCost).annotate({ description: "Each provider Sandcovery routes to that runs the size, cheapest first, and none when no provider runs it." }),
1211
+ slug: Slug
1212
+ }).annotate({
1213
+ description: "The monthly list price of one size on every provider Sandcovery routes to, and `slug`, such as `sandcovery/2x4:cheapest`, which routes a create of that size to the cheapest of them that holds your credential.",
1214
+ identifier: "MonthlyCostList"
1215
+ });
663
1216
  const isCalendarDay = makeFilter((value) => {
664
1217
  const at = Date.parse(`${value}T00:00:00.000Z`);
665
1218
  return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
@@ -712,19 +1265,20 @@ const LiveUsage = Struct({
712
1265
  at: Timestamp.annotate({ description: "When the API read these figures." }),
713
1266
  data: ArraySchema(LiveSandboxes)
714
1267
  }).annotate({ identifier: "LiveUsage" });
1268
+ const UsagePeriod = Literals([
1269
+ "day",
1270
+ "month",
1271
+ "total",
1272
+ "week"
1273
+ ]).annotate({
1274
+ description: "The window: the current UTC `day`, the ISO `week` from Monday 00:00 UTC, the UTC calendar `month`, or the `total` of every sandbox run.",
1275
+ identifier: "UsagePeriod"
1276
+ });
715
1277
  const UsageTotal = Struct({
716
1278
  estimated_micro_usd: MicroUsd,
717
1279
  gpu_seconds: Natural,
718
1280
  memory_gib_seconds: Natural,
719
- period: Literals([
720
- "day",
721
- "month",
722
- "total",
723
- "week"
724
- ]).annotate({
725
- description: "The window: the current UTC `day`, the ISO `week` from Monday 00:00 UTC, the UTC calendar `month`, or the `total` of every sandbox run.",
726
- identifier: "UsagePeriod"
727
- }),
1281
+ period: UsagePeriod,
728
1282
  sandbox_count: Natural.annotate({ description: "Sandboxes that ran at any time in the window." }),
729
1283
  sandbox_seconds: Natural,
730
1284
  since: NullOr(Timestamp).annotate({ description: "The start of the window, or null for `total`." }),
@@ -778,6 +1332,389 @@ const Stats = Struct({
778
1332
  description: "The organization's level, streak, records, and badges, each read from the sandboxes, create attempts, and snapshots it stores.",
779
1333
  identifier: "Stats"
780
1334
  });
1335
+ // ../sandcovery-contract/src/usage-shares.ts
1336
+ const USAGE_SHARE_FIGURES = [
1337
+ "sandbox_count",
1338
+ "sandbox_seconds",
1339
+ "vcpu_seconds",
1340
+ "memory_gib_seconds",
1341
+ "gpu_seconds",
1342
+ "estimated_micro_usd"
1343
+ ];
1344
+ const UsageShareFigure = Literals(USAGE_SHARE_FIGURES).annotate({
1345
+ description: "A figure of a usage total, named as its `UsageTotal` field.",
1346
+ identifier: "UsageShareFigure"
1347
+ });
1348
+ const DEFAULT_SHARED_FIGURES = USAGE_SHARE_FIGURES.filter((figure) => figure !== "estimated_micro_usd");
1349
+ const SHARE_TOKEN_LENGTH = 43;
1350
+ const BASE64URL = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
1351
+ const isShareToken = (value) => value.length === SHARE_TOKEN_LENGTH && value.split("").every((character) => BASE64URL.has(character));
1352
+ const ShareToken = String$1.check(makeFilter(isShareToken, {
1353
+ expected: "a share token of 43 base64url characters",
1354
+ toJsonSchema: () => ({})
1355
+ })).annotate({ description: "A share token: 32 random bytes as 43 unpadded base64url characters. Anyone holding it can read the figures it shares." });
1356
+ const CreateUsageShareRequest = Struct({
1357
+ figures: ArraySchema(UsageShareFigure).check(isMinLength(1), isMaxLength(USAGE_SHARE_FIGURES.length)).annotate({ description: "The figures of the window to share, at least one. The share shows each once, in the order `UsageShareFigure` lists them." }),
1358
+ period: UsagePeriod
1359
+ }).annotate({
1360
+ description: "The window whose usage total to share and the figures of it to show. Nothing else of the organization becomes public.",
1361
+ identifier: "CreateUsageShareRequest"
1362
+ });
1363
+ const SharedUsageFigure = Struct({
1364
+ figure: UsageShareFigure,
1365
+ value: Natural.annotate({ description: "The value, in the unit of its `UsageTotal` field." })
1366
+ }).annotate({ identifier: "SharedUsageFigure" });
1367
+ const SharedUsage = Struct({
1368
+ at: Timestamp.annotate({ description: "When the API read the figures. They never change after." }),
1369
+ figures: ArraySchema(SharedUsageFigure).annotate({ description: "The shared figures, in the order `UsageShareFigure` lists them." }),
1370
+ period: UsagePeriod,
1371
+ shared_by: String$1.annotate({ description: "The Sandcovery username of the person who shared, as it reads now, so a rename shows on every link they shared." }),
1372
+ since: NullOr(Timestamp).annotate({ description: "The start of the window, or null for `total`." })
1373
+ }).annotate({
1374
+ description: "A usage total an organization shared by link: only the window and the figures it chose, read once when it shared them, and the username of the person who shared, with no organization, email, name, key, or billing detail.",
1375
+ identifier: "SharedUsage"
1376
+ });
1377
+ const UsageShare = Struct({
1378
+ id: UsageShareId,
1379
+ image_url: String$1.annotate({ description: "The PNG card of the share, which its page names as its social image and anyone can download without signing in." }),
1380
+ token: ShareToken,
1381
+ url: String$1.annotate({ description: "The public page of the share, which anyone can open without signing in." }),
1382
+ usage: SharedUsage
1383
+ }).annotate({
1384
+ description: "A public link to one usage total of the organization. It lives until revoked.",
1385
+ identifier: "UsageShare"
1386
+ });
1387
+ const UsageShareList = Struct({ data: ArraySchema(UsageShare).annotate({ description: "Every live usage share of the organization, newest first." }) }).annotate({ identifier: "UsageShareList" });
1388
+ // ../sandcovery-contract/src/x-account.ts
1389
+ const XAccount = Struct({
1390
+ id: String$1.annotate({ description: "X's ID of the account." }),
1391
+ linked_at: Timestamp,
1392
+ username: String$1.annotate({ description: "The X handle, without the leading @." })
1393
+ }).annotate({
1394
+ description: "The X account linked to you.",
1395
+ identifier: "XAccount"
1396
+ });
1397
+ const XAccountStatus = Struct({
1398
+ linked: NullOr(XAccount).annotate({ description: "The X account linked to you, or null while none is." }),
1399
+ linking_open: Boolean.annotate({ description: "Whether Sandcovery links X accounts now." })
1400
+ }).annotate({
1401
+ description: "The X account linked to you, and whether linking is open.",
1402
+ identifier: "XAccountStatus"
1403
+ });
1404
+ const XAccountLink = Struct({ url: String$1.annotate({ description: "The dashboard page where you confirm the link on X, signed in to www.sandcovery.com as yourself." }) }).annotate({
1405
+ description: "Where to finish linking an X account, since X confirms it in the browser.",
1406
+ identifier: "XAccountLink"
1407
+ });
1408
+ // src/attach.ts
1409
+ const ATTACH_PROTOCOL = "sandcovery-attach-v1";
1410
+ const STDIN = 0;
1411
+ const STDOUT = 1;
1412
+ const STDERR = 2;
1413
+ const HEADER_BYTES = 9;
1414
+ const CHUNK_BYTES = 65536;
1415
+ const UNACKNOWLEDGED_LIMIT_BYTES = 8388608;
1416
+ const NORMAL_CLOSURE = 1e3;
1417
+ const REPLACED = 4e3;
1418
+ const RETRY_MS = [
1419
+ 250,
1420
+ 1e3,
1421
+ 2e3,
1422
+ 5e3
1423
+ ];
1424
+ const CHECK_MS = 15e3;
1425
+ const LOST = "The sandbox ended before the process reported an exit, so its exit is unknown.";
1426
+ const REPLACED_MESSAGE = "Another client attached to the process, which detached this one.";
1427
+ const ABORTED = "The attach was aborted.";
1428
+ const OUTPUT_NAMES = /* @__PURE__ */ new Map([[STDOUT, "stdout"], [STDERR, "stderr"]]);
1429
+ const RelayMessageSchema = Union([
1430
+ Struct({ type: Literals(["ready", "waiting"]) }),
1431
+ Struct({
1432
+ offset: Number$1,
1433
+ stream: Literal("stdin"),
1434
+ type: Literal("ack")
1435
+ }),
1436
+ Struct({
1437
+ code: Int,
1438
+ signal: NullOr(String$1),
1439
+ type: Literal("exit")
1440
+ })
1441
+ ]);
1442
+ const decodeRelayMessage = decodeUnknownOption(fromJsonString(RelayMessageSchema));
1443
+ const isApiError = is(ApiError);
1444
+ const frame = (stream, offset, data) => {
1445
+ const bytes = new Uint8Array(HEADER_BYTES + data.length);
1446
+ bytes[0] = stream;
1447
+ new DataView(bytes.buffer).setBigUint64(1, BigInt(offset));
1448
+ bytes.set(data, HEADER_BYTES);
1449
+ return bytes;
1450
+ };
1451
+ const control = (message) => JSON.stringify(message);
1452
+ const abortError = (signal) => {
1453
+ const reason = signal?.reason;
1454
+ return reason instanceof Error ? reason : new Error(ABORTED, { cause: reason });
1455
+ };
1456
+ var Attachment = class {
1457
+ #done = Promise.withResolvers();
1458
+ #received = /* @__PURE__ */ new Map();
1459
+ #sinks;
1460
+ #target;
1461
+ #drained = [];
1462
+ #ended = false;
1463
+ #finished = false;
1464
+ #ready = false;
1465
+ #retries = 0;
1466
+ #signals = [];
1467
+ #size;
1468
+ #socket = null;
1469
+ #stdinAcked = 0;
1470
+ #stdinEnd = 0;
1471
+ #synced = false;
1472
+ #timer;
1473
+ #unacknowledged = [];
1474
+ #aborted = () => {
1475
+ this.#fail(abortError(this.#target.options.signal));
1476
+ };
1477
+ constructor(target) {
1478
+ this.#target = target;
1479
+ this.#sinks = /* @__PURE__ */ new Map([[STDOUT, target.options.stdout], [STDERR, target.options.stderr]]);
1480
+ const { signal } = target.options;
1481
+ if (signal?.aborted === true) this.#fail(abortError(signal));
1482
+ else {
1483
+ signal?.addEventListener("abort", this.#aborted, { once: true });
1484
+ this.#connect();
1485
+ }
1486
+ }
1487
+ get exit() {
1488
+ return this.#done.promise;
1489
+ }
1490
+ async write(data) {
1491
+ if (this.#ended || this.#finished) return;
1492
+ for (let start = 0; start < data.length; start += CHUNK_BYTES) {
1493
+ const chunk = data.slice(start, start + CHUNK_BYTES);
1494
+ const offset = this.#stdinEnd;
1495
+ this.#unacknowledged.push({
1496
+ data: chunk,
1497
+ offset
1498
+ });
1499
+ this.#stdinEnd += chunk.length;
1500
+ if (this.#live()) this.#socket?.send(frame(STDIN, offset, chunk));
1501
+ }
1502
+ if (this.#stdinEnd - this.#stdinAcked > UNACKNOWLEDGED_LIMIT_BYTES) {
1503
+ const drained = Promise.withResolvers();
1504
+ this.#drained.push(drained);
1505
+ await drained.promise;
1506
+ }
1507
+ }
1508
+ endStdin() {
1509
+ if (this.#ended || this.#finished) return;
1510
+ this.#ended = true;
1511
+ if (this.#live()) this.#socket?.send(this.#eof());
1512
+ }
1513
+ resize(cols, rows) {
1514
+ this.#size = {
1515
+ cols,
1516
+ rows
1517
+ };
1518
+ if (this.#live()) this.#socket?.send(control({
1519
+ cols,
1520
+ rows,
1521
+ type: "resize"
1522
+ }));
1523
+ }
1524
+ sendSignal(name) {
1525
+ if (this.#finished) return;
1526
+ if (this.#live()) this.#socket?.send(control({
1527
+ name,
1528
+ type: "signal"
1529
+ }));
1530
+ else this.#signals.push(name);
1531
+ }
1532
+ #live() {
1533
+ return this.#ready && this.#synced;
1534
+ }
1535
+ #eof() {
1536
+ return control({
1537
+ offset: this.#stdinEnd,
1538
+ stream: "stdin",
1539
+ type: "eof"
1540
+ });
1541
+ }
1542
+ #connect() {
1543
+ const { credential, url } = this.#target;
1544
+ const socket = new WebSocket(url, credential === void 0 ? [ATTACH_PROTOCOL] : [ATTACH_PROTOCOL, credential]);
1545
+ socket.binaryType = "arraybuffer";
1546
+ socket.addEventListener("message", (event) => {
1547
+ this.#message(event);
1548
+ });
1549
+ socket.addEventListener("close", (event) => {
1550
+ this.#closed(socket, event.code);
1551
+ });
1552
+ this.#socket = socket;
1553
+ this.#watch();
1554
+ }
1555
+ #closed(socket, code) {
1556
+ if (socket !== this.#socket || this.#finished) return;
1557
+ this.#socket = null;
1558
+ this.#ready = false;
1559
+ if (code === REPLACED) {
1560
+ this.#fail(/* @__PURE__ */ new Error(REPLACED_MESSAGE));
1561
+ return;
1562
+ }
1563
+ const delay = RETRY_MS[Math.min(this.#retries, RETRY_MS.length - 1)];
1564
+ this.#retries += 1;
1565
+ clearTimeout(this.#timer);
1566
+ this.#timer = setTimeout(() => {
1567
+ this.#reconnect();
1568
+ }, delay);
1569
+ }
1570
+ async #reconnect() {
1571
+ if (await this.#alive() && this.#socket === null) this.#connect();
1572
+ }
1573
+ #watch() {
1574
+ clearTimeout(this.#timer);
1575
+ this.#timer = setTimeout(() => {
1576
+ this.#keepWatching();
1577
+ }, CHECK_MS);
1578
+ }
1579
+ async #keepWatching() {
1580
+ if (await this.#alive() && !this.#ready && this.#socket !== null) this.#watch();
1581
+ }
1582
+ async #alive() {
1583
+ const [checked] = await Promise.allSettled([this.#target.check()]);
1584
+ if (checked.status === "fulfilled" && checked.value.status === "lost") this.#fail(/* @__PURE__ */ new Error(LOST));
1585
+ if (checked.status === "rejected") {
1586
+ const reason = checked.reason;
1587
+ if (isApiError(reason)) this.#fail(reason);
1588
+ }
1589
+ return !this.#finished;
1590
+ }
1591
+ #message(event) {
1592
+ const data = event.data;
1593
+ if (data instanceof ArrayBuffer) {
1594
+ this.#output(new Uint8Array(data));
1595
+ return;
1596
+ }
1597
+ const decoded = decodeRelayMessage(data);
1598
+ if (isSome(decoded)) this.#control(decoded.value);
1599
+ }
1600
+ #control(message) {
1601
+ switch (message.type) {
1602
+ case "ready":
1603
+ this.#ready = true;
1604
+ this.#retries = 0;
1605
+ clearTimeout(this.#timer);
1606
+ if (this.#synced) this.#resend();
1607
+ break;
1608
+ case "waiting":
1609
+ this.#ready = false;
1610
+ this.#watch();
1611
+ break;
1612
+ case "ack":
1613
+ this.#acknowledgeStdin(message.offset);
1614
+ break;
1615
+ case "exit": this.#finish({
1616
+ code: message.code,
1617
+ signal: message.signal
1618
+ });
1619
+ }
1620
+ }
1621
+ #resend() {
1622
+ for (const { data, offset } of this.#unacknowledged) this.#socket?.send(frame(STDIN, offset, data));
1623
+ if (this.#ended) this.#socket?.send(this.#eof());
1624
+ if (this.#size !== void 0) this.#socket?.send(control({
1625
+ ...this.#size,
1626
+ type: "resize"
1627
+ }));
1628
+ for (const name of this.#signals) this.#socket?.send(control({
1629
+ name,
1630
+ type: "signal"
1631
+ }));
1632
+ this.#signals = [];
1633
+ }
1634
+ #rebase(base) {
1635
+ this.#synced = true;
1636
+ this.#stdinAcked = base;
1637
+ this.#stdinEnd += base;
1638
+ this.#unacknowledged = this.#unacknowledged.map(({ data, offset }) => ({
1639
+ data,
1640
+ offset: offset + base
1641
+ }));
1642
+ if (this.#ready) this.#resend();
1643
+ }
1644
+ #acknowledgeStdin(offset) {
1645
+ if (!this.#synced) {
1646
+ this.#rebase(offset);
1647
+ return;
1648
+ }
1649
+ this.#stdinAcked = Math.max(this.#stdinAcked, offset);
1650
+ this.#unacknowledged = this.#unacknowledged.filter((chunk) => chunk.offset + chunk.data.length > this.#stdinAcked);
1651
+ if (this.#stdinEnd - this.#stdinAcked <= UNACKNOWLEDGED_LIMIT_BYTES) this.#release();
1652
+ }
1653
+ #output(bytes) {
1654
+ const stream = bytes[0] ?? STDIN;
1655
+ const name = OUTPUT_NAMES.get(stream);
1656
+ if (bytes.length < HEADER_BYTES || name === void 0) return;
1657
+ const offset = Number(new DataView(bytes.buffer, bytes.byteOffset).getBigUint64(1));
1658
+ const known = this.#received.get(stream) ?? offset;
1659
+ const data = bytes.subarray(HEADER_BYTES);
1660
+ if (offset > known) return;
1661
+ const fresh = data.subarray(known - offset);
1662
+ const received = known + fresh.length;
1663
+ if (fresh.length > 0) {
1664
+ this.#received.set(stream, received);
1665
+ this.#sinks.get(stream)?.(fresh);
1666
+ }
1667
+ this.#socket?.send(control({
1668
+ offset: received,
1669
+ stream: name,
1670
+ type: "ack"
1671
+ }));
1672
+ }
1673
+ #release() {
1674
+ const waiting = this.#drained;
1675
+ this.#drained = [];
1676
+ for (const drained of waiting) drained.resolve(void 0);
1677
+ }
1678
+ #stop() {
1679
+ this.#finished = true;
1680
+ this.#ready = false;
1681
+ clearTimeout(this.#timer);
1682
+ this.#target.options.signal?.removeEventListener("abort", this.#aborted);
1683
+ this.#socket?.close(NORMAL_CLOSURE);
1684
+ this.#socket = null;
1685
+ this.#release();
1686
+ }
1687
+ #finish(exit) {
1688
+ if (!this.#finished) {
1689
+ this.#stop();
1690
+ this.#done.resolve(exit);
1691
+ }
1692
+ }
1693
+ #fail(error) {
1694
+ if (!this.#finished) {
1695
+ this.#stop();
1696
+ this.#done.reject(error);
1697
+ }
1698
+ }
1699
+ };
1700
+ const attach = (target) => {
1701
+ const attachment = new Attachment(target);
1702
+ return {
1703
+ endStdin: () => {
1704
+ attachment.endStdin();
1705
+ },
1706
+ exit: attachment.exit,
1707
+ resize: (cols, rows) => {
1708
+ attachment.resize(cols, rows);
1709
+ },
1710
+ sendSignal: (name) => {
1711
+ attachment.sendSignal(name);
1712
+ },
1713
+ write: async (data) => {
1714
+ await attachment.write(data);
1715
+ }
1716
+ };
1717
+ };
781
1718
  // src/sse.ts
782
1719
  const fieldOf = (line) => {
783
1720
  const colon = line.indexOf(":");
@@ -820,6 +1757,7 @@ const serverSentEvents = async function* (body) {
820
1757
  };
821
1758
  // src/index.ts
822
1759
  const STREAM_FAILURE_EVENT = "effect/http-api/stream/failure";
1760
+ const X_ACCOUNT_PATH = "/x-account";
823
1761
  const decodeApiError = decodeUnknownOption(fromJsonString(ApiError));
824
1762
  const failureOf = async (response) => {
825
1763
  const text = await response.text();
@@ -830,12 +1768,14 @@ const failureOf = async (response) => {
830
1768
  };
831
1769
  const segment = (schema, value) => encodeURIComponent(decodeUnknownSync(schema)(value));
832
1770
  const sandboxPath = (sandboxId) => `/sandboxes/${segment(SandboxId, sandboxId)}`;
1771
+ const processPath = (sandboxId, processId) => `${sandboxPath(sandboxId)}/processes/${segment(ProcessId, processId)}`;
833
1772
  const keyPath = (keyId) => `/keys/${segment(KeyId, keyId)}`;
834
1773
  const portSegment = (port) => String(decodeUnknownSync(Port)(port));
835
1774
  const credentialPath = (provider) => `/credentials/${segment(Provider, provider)}`;
836
1775
  const ciJobPath = (jobId) => `/ci/jobs/${segment(CiJobId, jobId)}`;
837
1776
  const ciInstallationPath = (installationId) => `/ci/installations/${String(decodeUnknownSync(GitHubId)(installationId))}`;
838
1777
  const filePath = (sandboxId) => `${sandboxPath(sandboxId)}/files/content`;
1778
+ const USAGE_SHARES_PATH = "/usage/shares";
839
1779
  const decodeExecEvent = decodeUnknownSync(fromJsonString(ExecEvent));
840
1780
  var Sandcovery = class {
841
1781
  activity;
@@ -844,10 +1784,12 @@ var Sandcovery = class {
844
1784
  credentials;
845
1785
  keys;
846
1786
  pricing;
1787
+ problems;
847
1788
  providers;
848
1789
  sandboxes;
849
1790
  stats;
850
1791
  usage;
1792
+ xAccount;
851
1793
  constructor(options = {}) {
852
1794
  const configuredKey = options.apiKey ?? globalThis.process?.env.SANDCOVERY_API_KEY;
853
1795
  const apiKey = configuredKey === "" ? void 0 : configuredKey;
@@ -873,6 +1815,17 @@ var Sandcovery = class {
873
1815
  return decodeUnknownSync(fromJsonString(schema))(text);
874
1816
  };
875
1817
  this.sandboxes = {
1818
+ attachProcess: (sandboxId, processId, attachOptions = {}) => {
1819
+ const path = processPath(sandboxId, processId);
1820
+ const url = new URL(`${API_PREFIX}${path}/attach`, baseUrl);
1821
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
1822
+ return attach({
1823
+ check: async () => await read(Process, "GET", path, { signal: attachOptions.signal }),
1824
+ credential: apiKey,
1825
+ options: attachOptions,
1826
+ url
1827
+ });
1828
+ },
876
1829
  create: async (request = {}, { idempotencyKey, signal } = {}) => await read(Sandbox, "POST", "/sandboxes", {
877
1830
  headers: idempotencyKey === void 0 ? {} : { "idempotency-key": idempotencyKey },
878
1831
  json: request,
@@ -908,6 +1861,7 @@ var Sandcovery = class {
908
1861
  }
909
1862
  },
910
1863
  get: async (sandboxId, { signal } = {}) => await read(Sandbox, "GET", sandboxPath(sandboxId), { signal }),
1864
+ getProcess: async (sandboxId, processId, { signal } = {}) => await read(Process, "GET", processPath(sandboxId, processId), { signal }),
911
1865
  list: async (query = {}, { signal } = {}) => await read(SandboxList, "GET", "/sandboxes", {
912
1866
  query: { ...query },
913
1867
  signal
@@ -927,6 +1881,10 @@ var Sandcovery = class {
927
1881
  },
928
1882
  resume: async (sandboxId, { signal } = {}) => await read(Sandbox, "POST", `${sandboxPath(sandboxId)}/resume`, { signal }),
929
1883
  snapshot: async (sandboxId, { signal } = {}) => await read(Snapshot, "POST", `${sandboxPath(sandboxId)}/snapshot`, { signal }),
1884
+ startProcess: async (sandboxId, request, { signal } = {}) => await read(Process, "POST", `${sandboxPath(sandboxId)}/processes`, {
1885
+ json: request,
1886
+ signal
1887
+ }),
930
1888
  writeFile: async (sandboxId, path, content, { signal } = {}) => await read(FileEntry, "PUT", filePath(sandboxId), {
931
1889
  body: content instanceof Uint8Array ? new Uint8Array(content) : content,
932
1890
  headers: { "content-type": "application/octet-stream" },
@@ -952,6 +1910,10 @@ var Sandcovery = class {
952
1910
  json: fields,
953
1911
  signal
954
1912
  }),
1913
+ countXPost: async (request, { signal } = {}) => await read(Offer, "POST", "/offer/x-post", {
1914
+ json: request,
1915
+ signal
1916
+ }),
955
1917
  delete: async (provider, { signal } = {}) => {
956
1918
  await call("DELETE", credentialPath(provider), { signal });
957
1919
  },
@@ -987,7 +1949,19 @@ var Sandcovery = class {
987
1949
  await call("DELETE", ciInstallationPath(installationId), { signal });
988
1950
  }
989
1951
  };
990
- this.pricing = { get: async ({ signal } = {}) => await read(Pricing, "GET", "/pricing", { signal }) };
1952
+ this.pricing = {
1953
+ get: async ({ signal } = {}) => await read(Pricing, "GET", "/pricing", { signal }),
1954
+ monthly: async (query, { signal } = {}) => await read(MonthlyCostList, "GET", "/pricing/monthly", {
1955
+ query: { ...query },
1956
+ signal
1957
+ })
1958
+ };
1959
+ this.problems = { report: async (request, { signal } = {}) => {
1960
+ await call("POST", "/problem-reports", {
1961
+ json: request,
1962
+ signal
1963
+ });
1964
+ } };
991
1965
  this.providers = {
992
1966
  catalog: async ({ signal } = {}) => await read(ProviderCatalog, "GET", "/catalog", { signal }),
993
1967
  get: async (provider, { signal } = {}) => await read(ProviderBoardEntry, "GET", `/providers/${segment(Provider, provider)}`, { signal }),
@@ -1003,15 +1977,31 @@ var Sandcovery = class {
1003
1977
  query: { ...query },
1004
1978
  signal
1005
1979
  }),
1980
+ getShared: async (token, { signal } = {}) => await read(SharedUsage, "GET", `/shared-usage/${segment(ShareToken, token)}`, { signal }),
1981
+ listShares: async ({ signal } = {}) => await read(UsageShareList, "GET", USAGE_SHARES_PATH, { signal }),
1006
1982
  live: async (query = {}, { signal } = {}) => await read(LiveUsage, "GET", "/usage/live", {
1007
1983
  query: { ...query },
1008
1984
  signal
1009
1985
  }),
1986
+ revokeShare: async (shareId, { signal } = {}) => {
1987
+ await call("DELETE", `${USAGE_SHARES_PATH}/${segment(UsageShareId, shareId)}`, { signal });
1988
+ },
1989
+ share: async (request, { signal } = {}) => await read(UsageShare, "POST", USAGE_SHARES_PATH, {
1990
+ json: request,
1991
+ signal
1992
+ }),
1010
1993
  totals: async (query = {}, { signal } = {}) => await read(UsageTotals, "GET", "/usage/totals", {
1011
1994
  query: { ...query },
1012
1995
  signal
1013
1996
  })
1014
1997
  };
1998
+ this.xAccount = {
1999
+ get: async ({ signal } = {}) => await read(XAccountStatus, "GET", X_ACCOUNT_PATH, { signal }),
2000
+ link: async ({ signal } = {}) => await read(XAccountLink, "POST", X_ACCOUNT_PATH, { signal }),
2001
+ unlink: async ({ signal } = {}) => {
2002
+ await call("DELETE", X_ACCOUNT_PATH, { signal });
2003
+ }
2004
+ };
1015
2005
  }
1016
2006
  };
1017
- export { CredentialFields as a, ApiError as i, CalendarDay as n, GitHubId as o, EstimateRequest as r, Sandcovery as t };
2007
+ export { GitHubId as A, ApiKeyId as B, NotFound as C, Forbidden as D, SandboxStatus as E, CREDIT_PURCHASE_MIN_MICRO_USD as F, ProcessId as G, CredentialId as H, ENTERPRISE_PLAN as I, UsageShareId as J, Provider as K, FREE_PLAN as L, ProviderSort as M, CARD_FEE_TERMS as N, Conflict as O, CREDIT_PURCHASE_MAX_MICRO_USD as P, MICRO_USD_PER_DOLLAR as R, Unauthorized as S, Port as T, KeyId as U, CiJobId as V, KeySecret as W, KeyKind as _, USAGE_SHARE_FIGURES as a, ApiError as b, EstimateRequest as c, UsagePeriod as d, API_PREFIX as f, CreateKeyRequest as g, SANDCOVERY_X_HANDLE as h, ShareToken as i, DEFAULT_SLUG as j, CredentialFields as k, MONTH_TEXT as l, SANDCOVERY_ORIGIN as m, CreateUsageShareRequest as n, UsageShareFigure as o, LocalPath as p, SandboxId as q, DEFAULT_SHARED_FIGURES as r, CalendarDay as s, Sandcovery as t, MonthlyCostQuery as u, SpendLimit as v, CreateSandboxRequest as w, Unsupported as x, UpdateKeyRequest as y, NO_MARKUP_TERMS as z };