sandcovery 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1016 @@
1
+ import { E as isGreaterThanOrEqualTo, G as getOrElse, N as optionalKey, P as tag, S as fromJsonString, T as isBetween, _ as Union, c as Literal, f as NonEmptyString, g as Struct, h as String$1, i as Finite, j as makeFilter, l as Literals, m as Record, n as Boolean, o as Int, p as NullOr, r as Error$1, t as ArraySchema, u as Natural, x as decodeUnknownSync, y as decodeUnknownOption } from "./Schema-CFI3ZMu8.mjs";
2
+ import { A as CreditCheckout, B as Provider, C as RoutingFields, E as Billing, F as CredentialId, H as SandboxId, I as GpuType, L as KeyId, M as Pricing, N as ApiKeyId, P as CiJobId, S as ROUTING_FIELDS_TEXT, T as StandardSize, U as Timestamp, V as Region, 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, z as MicroUsd } from "./origin-BTx2gX8x.mjs";
3
+ // ../../node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/ErrorReporter.js
4
+ /**
5
+ * Defines the runtime property key used to mark an object error as ignored by error
6
+ * reporting.
7
+ *
8
+ * **When to use**
9
+ *
10
+ * Use to suppress reporting for expected object errors, such as HTTP 404
11
+ * responses.
12
+ *
13
+ * **Details**
14
+ *
15
+ * Set `error[ErrorReporter.ignore]` to `true` to prevent the error from being
16
+ * forwarded to reporters. This is useful for expected failures such as HTTP 404
17
+ * responses.
18
+ *
19
+ * **Example** (Marking errors as ignored)
20
+ *
21
+ * ```ts import.meta.vitest
22
+ * import { Data, ErrorReporter } from "effect"
23
+ *
24
+ * class NotFoundError extends Data.TaggedError("NotFoundError")<{}> {
25
+ * readonly [ErrorReporter.ignore] = true
26
+ * }
27
+ *
28
+ * ErrorReporter.isIgnored(new NotFoundError()) // => true
29
+ * ```
30
+ *
31
+ * @see {@link isIgnored} for checking whether a value carries this annotation
32
+ * @see {@link Reportable} for the annotation contract recognized on object
33
+ * errors
34
+ *
35
+ * @stability unstable
36
+ * @category annotations
37
+ * @since 4.0.0
38
+ */
39
+ const ignore = "~effect/ErrorReporter/ignore";
40
+ const ActivityAction = NonEmptyString.annotate({
41
+ 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
+ examples: [
43
+ "sandbox.create",
44
+ "sandbox.create_attempt",
45
+ "sandbox.destroy",
46
+ "sandbox.expire",
47
+ "sandbox.pause",
48
+ "sandbox.resume",
49
+ "sandbox.snapshot"
50
+ ],
51
+ identifier: "ActivityAction"
52
+ });
53
+ const ActivityEvent = Struct({
54
+ action: ActivityAction,
55
+ api_key_id: NullOr(ApiKeyId),
56
+ at: Timestamp,
57
+ error: NullOr(String$1).annotate({ description: "Why the action failed, or null when it succeeded." }),
58
+ id: NonEmptyString,
59
+ outcome: Literals(["failed", "succeeded"]),
60
+ provider: NullOr(Provider),
61
+ sandbox_id: NullOr(SandboxId)
62
+ }).annotate({
63
+ description: "One entry of the activity log, which records every sandbox lifecycle call and create attempt.",
64
+ identifier: "ActivityEvent"
65
+ });
66
+ const ActivityList = Struct({
67
+ data: ArraySchema(ActivityEvent),
68
+ next_cursor: NullOr(String$1)
69
+ }).annotate({ identifier: "ActivityList" });
70
+ // ../sandcovery-contract/src/providers.ts
71
+ const Ratio = Finite.check(isBetween({
72
+ maximum: 1,
73
+ minimum: 0
74
+ })).annotate({ description: "A share from 0 to 1." });
75
+ const EgressMode = NonEmptyString.annotate({
76
+ description: "An egress policy mode the provider can enforce, such as `allow_all`, `allowlist`, or `deny_all`. The API adds modes over time.",
77
+ examples: [
78
+ "allow_all",
79
+ "allowlist",
80
+ "deny_all"
81
+ ],
82
+ identifier: "EgressMode"
83
+ });
84
+ const ProviderFeatures = Struct({
85
+ custom_image: Boolean,
86
+ egress_modes: ArraySchema(EgressMode),
87
+ gpu_types: ArraySchema(GpuType).annotate({ description: "The GPU types a sandbox on this provider can get, up to 8 GPUs of one type. Empty when the provider runs no GPU sandbox." }),
88
+ idle_timeout: Boolean,
89
+ max_disk_mib: NullOr(Natural).annotate({ description: "The largest disk size in MiB the provider takes, or null when it takes no disk size." }),
90
+ max_memory_mib: Natural.annotate({ description: "The most memory in MiB the provider runs. For a provider that states no memory ceiling, such as Depot, it is the memory of the largest standard size the provider runs." }),
91
+ max_ttl_seconds: Natural.annotate({ description: "The longest TTL in seconds. For a provider that states no TTL limit, such as Sprites, it is Sandcovery's own maximum of 86,400, which Sandcovery enforces by destroying the sandbox." }),
92
+ max_vcpu: Natural,
93
+ pause: Boolean,
94
+ ports: Boolean,
95
+ regions: ArraySchema(Region),
96
+ snapshot: Boolean,
97
+ streamed_exec: Boolean
98
+ }).annotate({
99
+ description: "What the provider can enforce. A spec asking for more answers `unsupported` on that provider.",
100
+ identifier: "ProviderFeatures"
101
+ });
102
+ const CredentialField = Struct({
103
+ label: NonEmptyString.annotate({ description: "The field name to show a person, such as \"Team ID\"." }),
104
+ name: NonEmptyString.annotate({ description: "The key of the field in `PUT /api/v1/credentials/{provider}`, such as `team_id`." }),
105
+ secret: Boolean.annotate({ description: "Whether to mask the value while it is typed." })
106
+ }).annotate({
107
+ description: "One field of a provider credential.",
108
+ identifier: "CredentialField"
109
+ });
110
+ const ProviderStatus = Literals([
111
+ "degraded",
112
+ "down",
113
+ "operational",
114
+ "unknown"
115
+ ]).annotate({ identifier: "ProviderStatus" });
116
+ const BrandImage = Struct({
117
+ source_url: String$1.annotate({ description: "The provider's own page or file the image was copied from, such as its brand page or the favicon its home page declares." }),
118
+ tile: Boolean.annotate({ description: "Whether the image stands out on this theme's background only on a tile of the other theme's background, because the provider publishes no variant for this theme." }),
119
+ url: String$1.annotate({ description: "Sandcovery's own copy of the image." })
120
+ }).annotate({ identifier: "BrandImage" });
121
+ const ThemedBrandImage = Struct({
122
+ dark: BrandImage,
123
+ light: BrandImage
124
+ }).annotate({
125
+ description: "The provider's own variants of an image for a light and a dark background. Where the provider publishes one variant, both name the same file.",
126
+ identifier: "ThemedBrandImage"
127
+ });
128
+ const securityFact = (value) => Struct({
129
+ detail: NullOr(String$1).annotate({ description: "A sentence that qualifies the value, or null." }),
130
+ read_at: Timestamp.annotate({ description: "The UTC day Sandcovery read the provider's page." }),
131
+ source_changed_at: NullOr(Timestamp).annotate({ description: "When Sandcovery's daily check first found the visible text of `source_url` changed since its first check after `read_at`, or null while it reads the same, so a non-null value means the fact may be out of date." }),
132
+ source_url: String$1.annotate({ description: "The provider's public page that states the value." }),
133
+ value
134
+ });
135
+ const SecurityText = securityFact(String$1).annotate({
136
+ description: "A security fact a provider states, with the page and the day it was read.",
137
+ identifier: "SecurityText"
138
+ });
139
+ const SecurityList = securityFact(ArraySchema(String$1)).annotate({
140
+ description: "A list of names a provider states, with the page and the day it was read.",
141
+ identifier: "SecurityList"
142
+ });
143
+ const ProviderSecurity = Struct({
144
+ compliance: NullOr(SecurityList).annotate({ description: "The audits and certifications the provider states, or null when its pages state none." }),
145
+ data_location: NullOr(SecurityText).annotate({ description: "Where the provider says customer data sits, or null when its pages do not say." }),
146
+ isolation: NullOr(SecurityText).annotate({ description: "How the provider isolates one sandbox from another, or null when its pages do not say." })
147
+ }).annotate({
148
+ description: "What the provider's own pages state about its security.",
149
+ identifier: "ProviderSecurity"
150
+ });
151
+ const VendorIncident = Struct({
152
+ id: NonEmptyString.annotate({ description: "The incident's ID on the provider's status page." }),
153
+ impact: Literals([
154
+ "none",
155
+ "minor",
156
+ "major",
157
+ "critical",
158
+ "maintenance"
159
+ ]).annotate({
160
+ description: "The impact the provider states, on the Atlassian Statuspage scale: `none`, `minor`, `major`, or `critical`, or `maintenance` for planned work.",
161
+ identifier: "IncidentImpact"
162
+ }),
163
+ resolved_at: NullOr(Timestamp).annotate({ description: "When the provider marked the incident resolved, or null while it is active." }),
164
+ started_at: Timestamp,
165
+ title: NonEmptyString,
166
+ url: NonEmptyString.annotate({ description: "The incident's page on the provider's status page." })
167
+ }).annotate({
168
+ description: "One incident from the provider's own status page.",
169
+ identifier: "VendorIncident"
170
+ });
171
+ const VendorIncidentRead = Struct({
172
+ data: ArraySchema(VendorIncident).annotate({ description: "Active incidents first, then those resolved in the last 7 days, each group newest first." }),
173
+ read_at: Timestamp.annotate({ description: "When Sandcovery last read the feed." }),
174
+ source_url: NonEmptyString.annotate({ description: "The provider's public status feed Sandcovery reads." })
175
+ }).annotate({
176
+ description: "The last read of a provider status feed.",
177
+ identifier: "VendorIncidentRead"
178
+ });
179
+ const VendorIncidents = NullOr(VendorIncidentRead).annotate({ description: "Incidents the provider's own status page reports, read every 5 minutes, or null when Sandcovery reads no status feed of the provider. A provider whose `status_url` is null publishes no status page." });
180
+ const ProviderBoardEntry = Struct({
181
+ create_latency_ms: Struct({
182
+ p50: NullOr(Natural),
183
+ p95: NullOr(Natural)
184
+ }).annotate({ description: "Create latency of the probe sandboxes over the last 24 hours, or null before the first probe or when `health_published` is false." }),
185
+ credential_fields: ArraySchema(CredentialField).annotate({ description: "The fields a credential for this provider takes, in form order, so a client can ask for a provider it does not know." }),
186
+ docs_only_adapter: Boolean.annotate({ description: "True when Sandcovery routes to the provider through an adapter written from the provider's public docs alone. Sandcovery has not run that adapter against the provider's service and runs no probe there, so `status` stays `unknown` and the `uptime` and `create_latency_ms` values stay null." }),
187
+ favicon: NullOr(ThemedBrandImage).annotate({ description: "The provider's favicon for a light and a dark background, or null when Sandcovery shows no mark for the provider." }),
188
+ features: ProviderFeatures,
189
+ gpu_prices: ArraySchema(Struct({
190
+ hourly_micro_usd: MicroUsd,
191
+ type: GpuType
192
+ })).annotate({ description: "List price per hour of one GPU of each type the provider runs, which a GPU sandbox adds to the price of its size. Empty when the provider runs no GPU sandbox." }),
193
+ health_published: Boolean.annotate({ description: "Whether the board publishes the provider's status, uptime, and create latency. False for a provider whose terms do not allow publishing them, whose `status` is then `unknown` and whose `uptime` and `create_latency_ms` values are null." }),
194
+ home_url: String$1.annotate({ description: "The provider's own home page." }),
195
+ incidents: VendorIncidents,
196
+ name: String$1,
197
+ prices: ArraySchema(Struct({
198
+ hourly_micro_usd: MicroUsd,
199
+ size: StandardSize
200
+ })).annotate({ description: "List price per hour of each standard size the provider can run. A provider that runs no standard size lists each size it does run instead, named `<vCPU>x<memory GiB>`, such as `2x0.5`, which a create asks for with `vcpu` and `memory_mib`." }),
201
+ provider: Provider,
202
+ rate_card_source_url: String$1.annotate({ description: "The provider's public pricing page the rate card copies." }),
203
+ rate_card_version: String$1,
204
+ security: ProviderSecurity,
205
+ status: ProviderStatus,
206
+ status_url: NullOr(String$1).annotate({ description: "The provider's own status page, or null when it publishes none." }),
207
+ updated_at: Timestamp,
208
+ uptime: Struct({
209
+ last_15_minutes: NullOr(Ratio),
210
+ last_24_hours: NullOr(Ratio),
211
+ last_7_days: NullOr(Ratio)
212
+ }).annotate({ description: "Share of probe creates that succeeded in each window, or null before the first probe or when `health_published` is false. For a provider probed less often than every 5 minutes, `last_15_minutes` covers its own probe interval instead, so it holds the result of its last probe." })
213
+ }).annotate({
214
+ description: "One provider on the public provider board.",
215
+ identifier: "ProviderBoardEntry"
216
+ });
217
+ const ProviderBoard = Struct({ data: ArraySchema(ProviderBoardEntry) }).annotate({ identifier: "ProviderBoard" });
218
+ // ../sandcovery-contract/src/catalog.ts
219
+ const fact = (value) => Struct({
220
+ detail: NullOr(String$1).annotate({ description: "A sentence that qualifies the value, or null." }),
221
+ source_url: NullOr(String$1).annotate({ description: "The provider's public page that states the value, or null when the value comes from Sandcovery's own adapter for the provider, whose pages are `adapter_source_urls`." }),
222
+ value
223
+ });
224
+ const CatalogFlag = fact(Boolean).annotate({
225
+ description: "A yes or no fact about a provider and where it was read.",
226
+ identifier: "CatalogFlag"
227
+ });
228
+ const CatalogText = fact(String$1).annotate({
229
+ description: "A short fact about a provider and where it was read.",
230
+ identifier: "CatalogText"
231
+ });
232
+ const CatalogList = fact(ArraySchema(String$1)).annotate({
233
+ description: "A list of names about a provider and where it was read.",
234
+ identifier: "CatalogList"
235
+ });
236
+ const CatalogLimit = fact(NullOr(Natural)).annotate({
237
+ description: "A ceiling and where it was read. A null `value` means the provider states that it sets no such ceiling.",
238
+ identifier: "CatalogLimit"
239
+ });
240
+ const CatalogGpus = fact(ArraySchema(Struct({
241
+ hourly_micro_usd: NullOr(MicroUsd).annotate({ description: "List price per hour of one GPU, or null when the provider publishes none." }),
242
+ name: String$1.annotate({ description: "The GPU's name: a `GpuType` for a provider Sandcovery routes to, and the name on the provider's page otherwise." })
243
+ }))).annotate({
244
+ description: "The GPUs a sandbox can get and where the list was read. Empty when Sandcovery starts no GPU sandbox on a provider it routes to.",
245
+ identifier: "CatalogGpus"
246
+ });
247
+ const CATALOG_MEASUREMENTS = [
248
+ "measured",
249
+ "not_measured",
250
+ "not_published"
251
+ ];
252
+ const BENCHMARK_TERMS = [
253
+ "barred",
254
+ "conditional",
255
+ "no_bar_found"
256
+ ];
257
+ const ProviderCatalogEntry = Struct({
258
+ adapter_source_urls: ArraySchema(String$1).annotate({ description: "The provider's public pages that Sandcovery's adapter for it was written from, which every fact with a null `source_url` traces to. Empty for a provider with no adapter." }),
259
+ billing: NullOr(CatalogText).annotate({ description: "The unit the provider bills a sandbox in, such as per second or per session-hour." }),
260
+ brand: Struct({
261
+ favicon: NullOr(ThemedBrandImage),
262
+ logo: NullOr(ThemedBrandImage)
263
+ }).annotate({ description: "The provider's favicon and logo, each for a light and a dark background, and each null when Sandcovery shows no mark for the provider." }),
264
+ capabilities: Struct({
265
+ ci_runner: NullOr(CatalogFlag).annotate({ description: "Whether Sandcovery CI can start a GitHub Actions runner in a sandbox on the provider, with the reason in `detail` when it cannot, or null when Sandcovery has not run a runner there. A runner's just-in-time config reaches a sandbox only through the provider's exec environment or file API, never inside a command." }),
266
+ custom_image: NullOr(CatalogFlag),
267
+ environment: NullOr(CatalogFlag),
268
+ files: NullOr(CatalogFlag),
269
+ idle_timeout: NullOr(CatalogFlag),
270
+ pause: NullOr(CatalogFlag),
271
+ ports: NullOr(CatalogFlag),
272
+ snapshot: NullOr(CatalogFlag),
273
+ streamed_exec: NullOr(CatalogFlag)
274
+ }).annotate({ description: "What a sandbox can do. For a provider Sandcovery routes to, each is what Sandcovery's adapter does there, and otherwise what the provider's pages state." }),
275
+ create_latency_ms: Struct({
276
+ p50: NullOr(Natural),
277
+ p95: NullOr(Natural)
278
+ }).annotate({ description: "Create latency of the probe sandboxes over the last 24 hours, or null unless `measurement` is `measured` and a probe has run." }),
279
+ credential_fields: ArraySchema(CredentialField).annotate({ description: "The fields a credential for this provider takes. Empty for a provider that is coming soon." }),
280
+ docs_only_adapter: Boolean.annotate({ description: "True when Sandcovery routes to the provider through an adapter written from the provider's public docs alone. Sandcovery has not run that adapter against the provider's service and runs no probe there, so `measurement` is `not_measured`." }),
281
+ egress_modes: NullOr(CatalogList).annotate({ description: "The egress policy modes the provider can enforce, such as `allow_all`, `allowlist`, or `deny_all`." }),
282
+ gpus: NullOr(CatalogGpus),
283
+ incidents: VendorIncidents,
284
+ limits: Struct({
285
+ max_disk_mib: NullOr(CatalogLimit),
286
+ max_memory_mib: NullOr(CatalogLimit),
287
+ max_ttl_seconds: NullOr(CatalogLimit),
288
+ max_vcpu: NullOr(CatalogLimit)
289
+ }).annotate({ description: "The most one sandbox can get. For a provider Sandcovery routes to, each is the most Sandcovery starts there, and `max_disk_mib` is null when its adapter takes no disk size." }),
290
+ links: Struct({
291
+ docs_url: String$1,
292
+ home_url: String$1,
293
+ pricing_url: String$1,
294
+ security_url: NullOr(String$1),
295
+ status_url: NullOr(String$1),
296
+ terms_url: String$1
297
+ }).annotate({ description: "The provider's own public pages." }),
298
+ measured_at: NullOr(Timestamp).annotate({ description: "When the published uptime and create latency were last rolled up, or null when none is published." }),
299
+ measurement: Literals(CATALOG_MEASUREMENTS).annotate({
300
+ description: "Whether the figures are measured: `measured` when Sandcovery probes the provider and publishes the result, `not_published` when it probes the provider and the provider's terms do not allow publishing the result, and `not_measured` when it runs no probe there.",
301
+ identifier: "CatalogMeasurement"
302
+ }),
303
+ name: String$1,
304
+ policy: Struct({
305
+ benchmark_terms: fact(Literals(BENCHMARK_TERMS)).annotate({
306
+ description: "What the provider's terms say about publishing benchmarks of its service: `barred` when they forbid it, `conditional` when they allow it under a condition that `detail` states, and `no_bar_found` when a reading of the terms found no such clause.",
307
+ identifier: "CatalogBenchmarkTerms"
308
+ }),
309
+ brand_terms: fact(Literals(BENCHMARK_TERMS)).annotate({
310
+ description: "What the provider's terms or brand page say about showing its logo and favicon: `barred` when they need the provider's permission first, `conditional` when they allow it under a condition that `detail` states, and `no_bar_found` when a reading of the terms found no such clause.",
311
+ identifier: "CatalogBrandTerms"
312
+ }),
313
+ compliance: ProviderSecurity.fields.compliance,
314
+ data_location: ProviderSecurity.fields.data_location,
315
+ free_allowance: NullOr(CatalogText).annotate({ description: "The free usage or credit the provider states." }),
316
+ isolation: ProviderSecurity.fields.isolation,
317
+ payment_required: NullOr(CatalogFlag).annotate({ description: "Whether an account needs a payment method before it starts a sandbox." }),
318
+ plan_required: NullOr(CatalogFlag).annotate({ description: "Whether an account needs a paid plan before it starts a sandbox." }),
319
+ read_at: Timestamp.annotate({ description: "The UTC day the provider's pages were read. Each security fact carries its own `read_at`, which is later for a fact read again since." }),
320
+ sla: NullOr(CatalogText).annotate({ description: "The uptime commitment the provider states." })
321
+ }).annotate({ description: "What the provider's terms and public pages state. A null fact means those pages do not state it." }),
322
+ prices: ArraySchema(Struct({
323
+ hourly_micro_usd: NullOr(MicroUsd),
324
+ offered: NullOr(Boolean).annotate({ description: "Whether the provider runs the size, or null when its pages do not say which sizes a sandbox takes." }),
325
+ size: StandardSize
326
+ })).annotate({ description: "List price per hour of each standard size, then of each other size the provider runs, such as `2x0.5`, from the provider's vCPU and memory rates or its listed plan price. `hourly_micro_usd` is null when the provider does not run the size or its pages give no rate that prices it." }),
327
+ provider: Provider,
328
+ rates: NullOr(Struct({
329
+ as_of: Timestamp.annotate({ description: "When the rates took effect on a provider Sandcovery routes to, and when the pricing page was read otherwise." }),
330
+ detail: NullOr(String$1),
331
+ memory_gib_hour_micro_usd: MicroUsd,
332
+ source_url: String$1,
333
+ vcpu_hour_micro_usd: MicroUsd
334
+ })).annotate({ description: "List price of one vCPU and of one GiB of memory for an hour, or null when the provider prices no such unit." }),
335
+ regions: NullOr(CatalogList).annotate({ description: "Where a sandbox can run: coarse `Region` names for a provider Sandcovery routes to, and the region names on the provider's page otherwise." }),
336
+ routed: Boolean.annotate({ description: "Whether Sandcovery routes sandboxes to the provider. `false` means the provider is coming soon: Sandcovery does not route to it yet." }),
337
+ sizes: NullOr(CatalogText).annotate({ description: "The sizes a sandbox comes in, each named `<vCPU>x<memory GiB>`, or a note that any size within the limits runs." }),
338
+ status: ProviderStatus,
339
+ uptime: Struct({
340
+ last_15_minutes: NullOr(Ratio),
341
+ last_24_hours: NullOr(Ratio),
342
+ last_7_days: NullOr(Ratio)
343
+ }).annotate({ description: "Share of probe creates that succeeded in each window, or null unless `measurement` is `measured` and a probe has run. For a provider probed less often than every 5 minutes, `last_15_minutes` covers its own probe interval instead, so it holds the result of its last probe." })
344
+ }).annotate({
345
+ description: "One sandbox provider in the catalog: what Sandcovery measured, and what the provider's public pages state. A null fact means those pages do not state it.",
346
+ identifier: "ProviderCatalogEntry"
347
+ });
348
+ const ProviderCatalog = Struct({ data: ArraySchema(ProviderCatalogEntry) }).annotate({ identifier: "ProviderCatalog" });
349
+ // ../sandcovery-contract/src/ci.ts
350
+ const GitHubId = Int.check(isGreaterThanOrEqualTo(1));
351
+ const CiJobStatus = Literals([
352
+ "completed",
353
+ "in_progress",
354
+ "queued"
355
+ ]).annotate({
356
+ description: "Where GitHub reports the job: `queued` until a runner takes it, `in_progress` while it runs, and `completed` once it ends.",
357
+ identifier: "CiJobStatus"
358
+ });
359
+ const CiJobConclusion = NonEmptyString.annotate({
360
+ description: "How GitHub concluded the job, such as `success`, `failure`, `cancelled`, `skipped`, or `timed_out`. GitHub adds conclusions over time.",
361
+ examples: [
362
+ "action_required",
363
+ "cancelled",
364
+ "failure",
365
+ "neutral",
366
+ "skipped",
367
+ "success",
368
+ "timed_out"
369
+ ],
370
+ identifier: "CiJobConclusion"
371
+ });
372
+ const CiJob = Struct({
373
+ completed_at: NullOr(Timestamp).annotate({ description: "When GitHub reported the job completed." }),
374
+ conclusion: NullOr(CiJobConclusion),
375
+ cost_micro_usd: NullOr(MicroUsd).annotate({ description: "The list-price cost of the runner sandbox that took the job, from the provider's rate card, so far while it runs and final once it ends. Null until a Sandcovery runner takes the job." }),
376
+ duration_ms: NullOr(Natural).annotate({ description: "Milliseconds from start to completion. Null until the job completes." }),
377
+ github_hosted_cost_micro_usd: NullOr(MicroUsd).annotate({ description: "What the same job costs on a GitHub-hosted x64 Linux runner: its duration rounded up to the whole minute, at GitHub's per-minute price for the smallest runner with at least the runner sandbox's vCPU. Null until the job completes on a Sandcovery runner, or when no GitHub-hosted runner has that many vCPU." }),
378
+ id: CiJobId,
379
+ job_name: String$1,
380
+ provider: NullOr(Provider).annotate({ description: "The provider of the runner sandbox that took the job, or null until a Sandcovery runner takes it." }),
381
+ queued_at: Timestamp,
382
+ repository: NonEmptyString.annotate({ description: "The repository as `<owner>/<name>`." }),
383
+ runner_error: NullOr(String$1).annotate({ description: "Why Sandcovery started no runner for the job, such as a create the API key refused, or null." }),
384
+ runner_label: NonEmptyString.annotate({ description: "The Sandcovery runner label the job asked for, such as `sandcovery/4x16:cheapest`." }),
385
+ sandbox_id: NullOr(SandboxId).annotate({ description: "The runner sandbox that took the job, or null until a Sandcovery runner takes it. A runner takes any queued job with its label, so it can differ from the sandbox started when this job was queued." }),
386
+ started_at: NullOr(Timestamp).annotate({ description: "When GitHub reported a runner started the job." }),
387
+ status: CiJobStatus,
388
+ wait_ms: NullOr(Natural).annotate({ description: "Milliseconds from queued to started. Null until the job starts." }),
389
+ workflow_job_id: GitHubId.annotate({ description: "GitHub's job ID." }),
390
+ workflow_run_id: GitHubId.annotate({ description: "GitHub's workflow run ID." })
391
+ }).annotate({
392
+ description: "A GitHub Actions job that asked for a Sandcovery runner label in a repository of a linked GitHub installation. Money is at list price, and the provider bills your own account.",
393
+ identifier: "CiJob"
394
+ });
395
+ const CiJobList = Struct({
396
+ data: ArraySchema(CiJob),
397
+ next_cursor: NullOr(String$1)
398
+ }).annotate({ identifier: "CiJobList" });
399
+ const CiInstallation = Struct({
400
+ account: NonEmptyString.annotate({ description: "The GitHub organization the installation belongs to." }),
401
+ api_key_id: ApiKeyId.annotate({ description: "The API key that creates the installation's runner sandboxes, whose spend limit, provider allowlist, concurrency cap, and maximum TTL govern them." }),
402
+ installation_id: GitHubId.annotate({ description: "GitHub's ID of the Sandcovery CI GitHub App installation." }),
403
+ linked_at: Timestamp,
404
+ provider_order: ArraySchema(Provider).annotate({ description: "Providers a runner label that pins no provider tries first, in this order, within the API key's allowlist." })
405
+ }).annotate({
406
+ description: "A GitHub installation of the Sandcovery CI GitHub App, linked to this organization.",
407
+ identifier: "CiInstallation"
408
+ });
409
+ const CiInstallationList = Struct({ data: ArraySchema(CiInstallation) }).annotate({ identifier: "CiInstallationList" });
410
+ // ../sandcovery-contract/src/credentials.ts
411
+ const CredentialFields = Record(String$1, NonEmptyString).annotate({
412
+ description: "The provider's credential fields by name, as its `credential_fields` on the provider board lists them, such as `api_key` for `e2b` or `api_key` and `workspace_id` for `render`. A missing or unknown field answers 400 `invalid_request`.",
413
+ identifier: "CredentialFields"
414
+ });
415
+ const ProviderCredential = Struct({
416
+ created_at: Timestamp,
417
+ hint: String$1.annotate({ description: "The last four characters of the first secret field, for display." }),
418
+ id: CredentialId,
419
+ provider: Provider,
420
+ updated_at: Timestamp
421
+ }).annotate({
422
+ description: "A stored provider credential. Sandcovery encrypts it at rest and never returns its fields.",
423
+ identifier: "ProviderCredential"
424
+ });
425
+ const ProviderCredentialList = Struct({ data: ArraySchema(ProviderCredential).annotate({ description: "Every stored credential, by provider and then in the order a create tries them: the order they were added. Without Pro, a create uses only each provider's first credential." }) }).annotate({ identifier: "ProviderCredentialList" });
426
+ // ../sandcovery-contract/src/errors/concurrency-limit-reached.ts
427
+ var ConcurrencyLimitReached = class extends Error$1("ConcurrencyLimitReached")({
428
+ concurrency_cap: Natural,
429
+ error: tag("concurrency_limit_reached"),
430
+ message: String$1
431
+ }, {
432
+ description: "The API key already has `concurrency_cap` live sandboxes, its `max_concurrent_sandboxes`. Destroy one or wait for one to end.",
433
+ httpApiStatus: 429,
434
+ identifier: "ConcurrencyLimitReached"
435
+ }) {
436
+ [ignore] = true;
437
+ };
438
+ // ../sandcovery-contract/src/errors/conflict.ts
439
+ var Conflict = class extends Error$1("Conflict")({
440
+ error: tag("conflict"),
441
+ message: String$1
442
+ }, {
443
+ description: "The request clashes with the current state, such as an `Idempotency-Key` reused with a different body, a call on a sandbox that is not running, or deleting a provider credential that live sandboxes still use.",
444
+ httpApiStatus: 409,
445
+ identifier: "Conflict"
446
+ }) {
447
+ [ignore] = true;
448
+ };
449
+ // ../sandcovery-contract/src/errors/forbidden.ts
450
+ var Forbidden = class extends Error$1("Forbidden")({
451
+ error: tag("forbidden"),
452
+ message: String$1
453
+ }, {
454
+ description: "The credential is valid but may not make this call, such as a management key on a sandbox, an API key on keys, usage, or provider credentials, a member who is not an owner on keys, a member who is not an owner or admin on usage or provider credentials, a signed-in member who is not an owner or admin, or their agent, on sandbox create, a management key whose minting owner is no longer an owner on keys, or a TTL over the API key's `max_ttl_seconds`. `message` names the rule.",
455
+ httpApiStatus: 403,
456
+ identifier: "Forbidden"
457
+ }) {
458
+ [ignore] = true;
459
+ };
460
+ // ../sandcovery-contract/src/errors/invalid-request.ts
461
+ var InvalidRequest = class extends Error$1("InvalidRequest")({
462
+ error: tag("invalid_request"),
463
+ message: String$1
464
+ }, {
465
+ description: "The path, query, headers, or body do not decode against the operation, or contradict each other, and `message` names the failure.",
466
+ httpApiStatus: 400,
467
+ identifier: "InvalidRequest"
468
+ }) {
469
+ [ignore] = true;
470
+ };
471
+ // ../sandcovery-contract/src/errors/no-provider-available.ts
472
+ var NoProviderAvailable = class extends Error$1("NoProviderAvailable")({
473
+ 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." }),
474
+ error: tag("no_provider_available"),
475
+ message: String$1
476
+ }, {
477
+ description: "Every candidate provider failed to create the sandbox, or none was left after filtering.",
478
+ httpApiStatus: 503,
479
+ identifier: "NoProviderAvailable"
480
+ }) {};
481
+ // ../sandcovery-contract/src/errors/not-found.ts
482
+ var NotFound = class extends Error$1("NotFound")({
483
+ error: tag("not_found"),
484
+ message: String$1
485
+ }, {
486
+ description: "The resource the path names does not exist or belongs to another organization or key.",
487
+ httpApiStatus: 404,
488
+ identifier: "NotFound"
489
+ }) {
490
+ [ignore] = true;
491
+ };
492
+ // ../sandcovery-contract/src/errors/provider-error.ts
493
+ var ProviderError = class extends Error$1("ProviderError")({
494
+ error: tag("provider_error"),
495
+ message: String$1,
496
+ provider: Provider
497
+ }, {
498
+ description: "The sandbox's provider failed the call. `message` carries the provider's reason.",
499
+ httpApiStatus: 502,
500
+ identifier: "ProviderError"
501
+ }) {};
502
+ // ../sandcovery-contract/src/errors/spend-limit-reached.ts
503
+ var SpendLimitReached = class extends Error$1("SpendLimitReached")({
504
+ error: tag("spend_limit_reached"),
505
+ limit_micro_usd: MicroUsd,
506
+ message: String$1,
507
+ resets_at: NullOr(Timestamp),
508
+ spent_micro_usd: MicroUsd
509
+ }, {
510
+ description: "The API key's spend limit leaves too little for the sandbox's full TTL at list price. `resets_at` is when the window resets, or null for a `total` limit.",
511
+ httpApiStatus: 402,
512
+ identifier: "SpendLimitReached"
513
+ }) {
514
+ [ignore] = true;
515
+ };
516
+ // ../sandcovery-contract/src/errors/unauthorized.ts
517
+ var Unauthorized = class extends Error$1("Unauthorized")({
518
+ error: tag("unauthorized"),
519
+ message: String$1
520
+ }, {
521
+ description: "The request carries no live key and no signed-in session, or a key that is unknown, revoked, or expired.",
522
+ httpApiStatus: 401,
523
+ identifier: "Unauthorized"
524
+ }) {
525
+ [ignore] = true;
526
+ };
527
+ // ../sandcovery-contract/src/errors/unsupported.ts
528
+ var Unsupported = class extends Error$1("Unsupported")({
529
+ error: tag("unsupported"),
530
+ message: String$1,
531
+ options: ArraySchema(String$1).annotate({ description: "Slugs that would run for this request: each refused slug at the sizes its candidates run, then, for a slug that pins a provider, the `sandcovery/` slug at the size it asked for. Empty when nothing near the refused slugs would run, such as a spec field no candidate provider can enforce or an operation the bound provider lacks, and then `message` names that field or operation." }),
532
+ provider: NullOr(Provider).annotate({ description: "The sandbox's provider for an operation on an existing sandbox, or null for a create." })
533
+ }, {
534
+ description: "A slug, spec option, or operation that no candidate provider can serve. Sandcovery never ignores an option. For a slug, `options` lists slugs that would run; otherwise `options` is empty and `message` names the field or operation.",
535
+ httpApiStatus: 422,
536
+ identifier: "Unsupported"
537
+ }) {
538
+ [ignore] = true;
539
+ };
540
+ // ../sandcovery-contract/src/errors/api-error.ts
541
+ const ApiError = Union([
542
+ ConcurrencyLimitReached,
543
+ Conflict,
544
+ Forbidden,
545
+ InvalidRequest,
546
+ NoProviderAvailable,
547
+ NotFound,
548
+ ProviderError,
549
+ SpendLimitReached,
550
+ Unauthorized,
551
+ Unsupported
552
+ ]);
553
+ // ../sandcovery-contract/src/exec.ts
554
+ const MAX_EXEC_TIMEOUT_SECONDS = 3600;
555
+ const commandFields = {
556
+ command: NonEmptyString.annotate({ description: "A shell command line, run with `sh -c`." }),
557
+ cwd: optionalKey(NonEmptyString.annotate({ description: "Working directory. Defaults to the provider's default directory." })),
558
+ env: optionalKey(Record(NonEmptyString, String$1).annotate({ description: "Environment variables for this command only." }))
559
+ };
560
+ Struct(commandFields).annotate({
561
+ description: "A command to start and leave running. It runs until it exits or the sandbox ends, with no timeout, and its output is not kept.",
562
+ identifier: "DetachedExecRequest"
563
+ });
564
+ const DetachedExec = Struct({ started_at: Timestamp.annotate({ description: "When the provider reported the command started." }) }).annotate({
565
+ description: "A command the provider started and left running.",
566
+ identifier: "DetachedExec"
567
+ });
568
+ Struct({
569
+ ...commandFields,
570
+ timeout_seconds: optionalKey(Int.check(isBetween({
571
+ maximum: MAX_EXEC_TIMEOUT_SECONDS,
572
+ minimum: 1
573
+ })).annotate({ description: "Seconds after which the command is killed. Defaults to 300." }))
574
+ }).annotate({ identifier: "ExecRequest" });
575
+ const ExecResult = Struct({
576
+ duration_ms: Natural,
577
+ exit_code: Int,
578
+ stderr: String$1,
579
+ stdout: String$1
580
+ }).annotate({
581
+ description: "The result of a command that ran to its end.",
582
+ identifier: "ExecResult"
583
+ });
584
+ const ExecEvent = Union([
585
+ Struct({
586
+ data: String$1,
587
+ type: Literal("stdout")
588
+ }),
589
+ Struct({
590
+ data: String$1,
591
+ type: Literal("stderr")
592
+ }),
593
+ Struct({
594
+ duration_ms: Natural,
595
+ exit_code: Int,
596
+ type: Literal("exit")
597
+ }),
598
+ Struct({
599
+ message: String$1,
600
+ provider: Provider,
601
+ type: Literal("error")
602
+ })
603
+ ]).annotate({
604
+ description: "One server-sent event of a streamed command: output chunks as they arrive, then one `exit`, or one `error` when the provider fails mid-stream.",
605
+ identifier: "ExecEvent"
606
+ });
607
+ Struct({ path: NonEmptyString.annotate({ description: "An absolute path inside the sandbox." }) });
608
+ const FileEntry = Struct({
609
+ modified_at: NullOr(Timestamp),
610
+ name: String$1,
611
+ path: String$1,
612
+ size_bytes: NullOr(Natural),
613
+ type: Literals([
614
+ "directory",
615
+ "file",
616
+ "other",
617
+ "symlink"
618
+ ]).annotate({
619
+ description: "`other` is an entry that is neither a file, a directory, nor a symlink, such as a socket or a device.",
620
+ identifier: "FileEntryType"
621
+ })
622
+ }).annotate({ identifier: "FileEntry" });
623
+ const FileList = Struct({
624
+ entries: ArraySchema(FileEntry),
625
+ path: String$1
626
+ }).annotate({ identifier: "FileList" });
627
+ // ../sandcovery-contract/src/offer.ts
628
+ const VcpuSeconds = Natural;
629
+ const Offer = Struct({
630
+ 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." }),
631
+ 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." }),
632
+ keys_needed: Natural.annotate({ description: "Counted keys the account needs before its sandboxes may run on free vCPU-seconds." }),
633
+ 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`." }),
634
+ provider: Provider.annotate({ description: "The provider whose sandboxes run on free vCPU-seconds, on its account that Sandcovery pays for." }),
635
+ remaining_vcpu_seconds: VcpuSeconds.annotate({ description: "`cap_vcpu_seconds` less `used_vcpu_seconds`, never below zero." }),
636
+ 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." }),
637
+ vcpu_seconds_per_key: VcpuSeconds.annotate({ description: "The free vCPU-seconds each counted key earns." })
638
+ }).annotate({
639
+ 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.",
640
+ identifier: "Offer"
641
+ });
642
+ // ../sandcovery-contract/src/usage.ts
643
+ const EstimateRequest = Struct({
644
+ ...SandboxSpec.fields,
645
+ ...RoutingFields,
646
+ provider: optionalKey(ProviderPreferences)
647
+ }).annotate({
648
+ description: `A sandbox spec, the slug or slugs to run it on, and routing preferences, to price without creating anything. ${ROUTING_FIELDS_TEXT}`,
649
+ identifier: "EstimateRequest"
650
+ });
651
+ const Estimate = Struct({
652
+ hourly_micro_usd: MicroUsd,
653
+ provider: Provider,
654
+ rate_card_version: String$1,
655
+ slug: Slug,
656
+ ttl_micro_usd: MicroUsd.annotate({ description: "List-price cost if the sandbox runs for its whole TTL." })
657
+ }).annotate({
658
+ description: "One candidate a create would try: its provider, the slug of the size it would run there, such as `boat/2x4`, and its list price.",
659
+ identifier: "Estimate"
660
+ });
661
+ 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" });
662
+ const isCalendarDay = makeFilter((value) => {
663
+ const at = Date.parse(`${value}T00:00:00.000Z`);
664
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
665
+ }, {
666
+ expected: "a UTC calendar day such as 2026-11-08",
667
+ toJsonSchema: () => ({ format: "date" })
668
+ });
669
+ const CalendarDay = String$1.check(isCalendarDay);
670
+ Struct({
671
+ api_key_id: optionalKey(ApiKeyId),
672
+ from: CalendarDay.annotate({ description: "First UTC day, inclusive." }),
673
+ to: CalendarDay.annotate({ description: "Last UTC day, inclusive. At most 92 days after `from`." })
674
+ });
675
+ const UsageDay = Struct({
676
+ api_key_id: NullOr(ApiKeyId).annotate({ description: "The key that created the sandboxes, or null for sandboxes created on a signed-in session." }),
677
+ date: CalendarDay,
678
+ estimated_micro_usd: MicroUsd,
679
+ gpu_seconds: Natural.annotate({ description: "GPU-seconds: each sandbox GPU count times its seconds run." }),
680
+ memory_gib_seconds: Natural.annotate({ description: "GiB-seconds: each sandbox memory in GiB times its seconds run, rounded to a whole number." }),
681
+ provider: Provider,
682
+ sandbox_count: Natural,
683
+ sandbox_seconds: Natural,
684
+ vcpu_seconds: Natural.annotate({ description: "vCPU-seconds: each sandbox vCPU count times its seconds run." })
685
+ }).annotate({
686
+ description: "Estimated list-price usage and resource time of one key on one provider on one UTC day. Resource time counts the vCPUs, memory, and GPUs of each sandbox spec over the time it ran, the same time its estimated cost counts, and never measured utilization.",
687
+ identifier: "UsageDay"
688
+ });
689
+ const Usage = Struct({ data: ArraySchema(UsageDay) }).annotate({ identifier: "Usage" });
690
+ Struct({ api_key_id: optionalKey(ApiKeyId) });
691
+ const LiveSandboxes = Struct({
692
+ accrued_micro_usd: MicroUsd.annotate({ description: "Estimated list-price cost these sandboxes have run up from their start to now or their TTL." }),
693
+ api_key_id: NullOr(ApiKeyId).annotate({ description: "The key that created the sandboxes, or null for sandboxes created on a signed-in session." }),
694
+ gpus: Natural,
695
+ hourly_micro_usd: MicroUsd.annotate({ description: "List-price cost per hour of these sandboxes while they run, at the rate card each started on. A sandbox still creating or past its TTL adds nothing." }),
696
+ memory_mib: Natural,
697
+ provider: NullOr(Provider).annotate({ description: "The provider running the sandboxes, or null for creates no provider has started yet." }),
698
+ sandbox_count: Natural,
699
+ status: Literals([
700
+ "creating",
701
+ "destroying",
702
+ "paused",
703
+ "running"
704
+ ]).annotate({ identifier: "LiveSandboxStatus" }),
705
+ vcpus: Natural
706
+ }).annotate({
707
+ description: "The live sandboxes of one key on one provider in one status, with the vCPUs, memory, and GPUs their specs hold.",
708
+ identifier: "LiveSandboxes"
709
+ });
710
+ const LiveUsage = Struct({
711
+ at: Timestamp.annotate({ description: "When the API read these figures." }),
712
+ data: ArraySchema(LiveSandboxes)
713
+ }).annotate({ identifier: "LiveUsage" });
714
+ const UsageTotal = Struct({
715
+ estimated_micro_usd: MicroUsd,
716
+ gpu_seconds: Natural,
717
+ memory_gib_seconds: Natural,
718
+ period: Literals([
719
+ "day",
720
+ "month",
721
+ "total",
722
+ "week"
723
+ ]).annotate({
724
+ 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.",
725
+ identifier: "UsagePeriod"
726
+ }),
727
+ sandbox_count: Natural.annotate({ description: "Sandboxes that ran at any time in the window." }),
728
+ sandbox_seconds: Natural,
729
+ since: NullOr(Timestamp).annotate({ description: "The start of the window, or null for `total`." }),
730
+ vcpu_seconds: Natural
731
+ }).annotate({
732
+ description: "Estimated list-price cost and resource time of the sandboxes run from the start of one window to now, counted as usage per day counts them.",
733
+ identifier: "UsageTotal"
734
+ });
735
+ const UsageTotals = Struct({
736
+ at: Timestamp.annotate({ description: "When the API read these figures." }),
737
+ data: ArraySchema(UsageTotal).annotate({ description: "One total for each window: `day`, `week`, `month`, `total`." })
738
+ }).annotate({ identifier: "UsageTotals" });
739
+ // ../sandcovery-contract/src/stats.ts
740
+ const StatsDay = Struct({
741
+ date: CalendarDay,
742
+ sandbox_count: Natural.annotate({ description: "Sandboxes that started on this UTC day." })
743
+ }).annotate({ identifier: "StatsDay" });
744
+ const Badge = Struct({
745
+ earned_at: NullOr(Timestamp).annotate({ description: "When the organization earned the badge, read from the sandbox, attempt, or snapshot that earned it, or null while it is still to earn." }),
746
+ id: NonEmptyString.annotate({ description: "Stable badge name, such as `sandboxes-100` or `streak-7`. The API may add badges, so treat it as an open string." }),
747
+ name: NonEmptyString.annotate({ description: "The badge as a person reads it, such as `100 Sandboxes`." }),
748
+ progress: Natural.annotate({ description: "How far the organization has come toward `target`, at most `target`." }),
749
+ target: Natural.annotate({ description: "What earns the badge, in `unit`." }),
750
+ unit: NonEmptyString.annotate({ description: "The unit of `progress` and `target`: `sandboxes`, `providers`, `days`, `seconds`, or `snapshots`. The API may add units, so treat it as an open string." })
751
+ }).annotate({ identifier: "Badge" });
752
+ const Stats = Struct({
753
+ badges: ArraySchema(Badge),
754
+ busiest_day: NullOr(StatsDay).annotate({ description: "The UTC day the most sandboxes started, the earliest such day on a tie." }),
755
+ days: ArraySchema(StatsDay).annotate({ description: "Each UTC day of the last 365, today included, on which at least one sandbox started, oldest first." }),
756
+ largest_sandbox: NullOr(Struct({
757
+ memory_mib: Natural,
758
+ provider: Provider,
759
+ sandbox_id: SandboxId,
760
+ vcpus: Natural
761
+ })).annotate({ description: "The started sandbox with the most vCPUs, then the most memory, the earliest on a tie." }),
762
+ level: Natural.annotate({ description: "Level 1 starts at 1 vCPU-hour, and each level after it takes ten times the vCPU-hours of the one before." }),
763
+ level_vcpu_seconds: Natural.annotate({ description: "The vCPU-seconds at which the current level started." }),
764
+ longest_run: NullOr(Struct({
765
+ provider: Provider,
766
+ sandbox_id: SandboxId,
767
+ seconds: Natural
768
+ })).annotate({ description: "The sandbox that ran longest, up to its end or its TTL, counting a live one up to now." }),
769
+ next_level_vcpu_seconds: Natural.annotate({ description: "The vCPU-seconds the next level starts at." }),
770
+ sandbox_count: Natural.annotate({ description: "Sandboxes the organization started." }),
771
+ streak: Struct({
772
+ current_days: Natural.annotate({ description: "Consecutive UTC days with a sandbox start, ending today or yesterday, or 0." }),
773
+ longest_days: Natural.annotate({ description: "The longest run of consecutive UTC days with a sandbox start." })
774
+ }),
775
+ vcpu_seconds: Natural.annotate({ description: "vCPU-seconds of every sandbox the organization started, each from its start to its end or TTL, counting live sandboxes up to now." })
776
+ }).annotate({
777
+ description: "The organization's level, streak, records, and badges, each read from the sandboxes, create attempts, and snapshots it stores.",
778
+ identifier: "Stats"
779
+ });
780
+ // src/sse.ts
781
+ const fieldOf = (line) => {
782
+ const colon = line.indexOf(":");
783
+ if (colon === -1) return {
784
+ name: line,
785
+ value: ""
786
+ };
787
+ const value = line.slice(colon + 1);
788
+ return {
789
+ name: line.slice(0, colon),
790
+ value: value.startsWith(" ") ? value.slice(1) : value
791
+ };
792
+ };
793
+ const eventOf = (block) => {
794
+ const fields = block.split("\n").flatMap((line) => {
795
+ if (line.startsWith(":")) return [];
796
+ return [fieldOf(line)];
797
+ });
798
+ const data = fields.flatMap(({ name, value }) => name === "data" ? [value] : []);
799
+ const event = fields.findLast(({ name }) => name === "event")?.value ?? "message";
800
+ return data.length > 0 ? {
801
+ data: data.join("\n"),
802
+ event
803
+ } : void 0;
804
+ };
805
+ const normalized = (text) => text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
806
+ const serverSentEvents = async function* (body) {
807
+ const decoder = new TextDecoder();
808
+ let pending = "";
809
+ for await (const bytes of body) {
810
+ const text = `${pending}${decoder.decode(bytes, { stream: true })}`;
811
+ const cut = text.endsWith("\r") ? text.length - 1 : text.length;
812
+ const blocks = normalized(text.slice(0, cut)).split("\n\n");
813
+ pending = `${blocks.pop() ?? ""}${text.slice(cut)}`;
814
+ for (const block of blocks) {
815
+ const event = eventOf(block);
816
+ if (event !== void 0) yield event;
817
+ }
818
+ }
819
+ };
820
+ // src/index.ts
821
+ const STREAM_FAILURE_EVENT = "effect/http-api/stream/failure";
822
+ const decodeApiError = decodeUnknownOption(fromJsonString(ApiError));
823
+ const failureOf = async (response) => {
824
+ const text = await response.text();
825
+ return getOrElse(decodeApiError(text), () => new Error(`Sandcovery answered ${response.status}`, { cause: {
826
+ body: text,
827
+ status: response.status
828
+ } }));
829
+ };
830
+ const segment = (schema, value) => encodeURIComponent(decodeUnknownSync(schema)(value));
831
+ const sandboxPath = (sandboxId) => `/sandboxes/${segment(SandboxId, sandboxId)}`;
832
+ const keyPath = (keyId) => `/keys/${segment(KeyId, keyId)}`;
833
+ const portSegment = (port) => String(decodeUnknownSync(Port)(port));
834
+ const credentialPath = (provider) => `/credentials/${segment(Provider, provider)}`;
835
+ const ciJobPath = (jobId) => `/ci/jobs/${segment(CiJobId, jobId)}`;
836
+ const ciInstallationPath = (installationId) => `/ci/installations/${String(decodeUnknownSync(GitHubId)(installationId))}`;
837
+ const filePath = (sandboxId) => `${sandboxPath(sandboxId)}/files/content`;
838
+ const decodeExecEvent = decodeUnknownSync(fromJsonString(ExecEvent));
839
+ var Sandcovery = class {
840
+ activity;
841
+ billing;
842
+ ci;
843
+ credentials;
844
+ keys;
845
+ pricing;
846
+ providers;
847
+ sandboxes;
848
+ stats;
849
+ usage;
850
+ constructor(options = {}) {
851
+ const configuredKey = options.apiKey ?? globalThis.process?.env.SANDCOVERY_API_KEY;
852
+ const apiKey = configuredKey === "" ? void 0 : configuredKey;
853
+ const baseUrl = options.baseUrl ?? "https://www.sandcovery.com";
854
+ const send = options.fetch ?? globalThis.fetch;
855
+ const call = async (method, path, { body, headers = {}, json, query = {}, signal } = {}) => {
856
+ const url = new URL(`${API_PREFIX}${path}`, baseUrl);
857
+ for (const [key, value] of Object.entries(query)) if (value !== void 0) url.searchParams.set(key, String(value));
858
+ const sent = new Headers(headers);
859
+ if (apiKey !== void 0) sent.set("authorization", `Bearer ${apiKey}`);
860
+ if (json !== void 0) sent.set("content-type", "application/json");
861
+ const response = await send(url, {
862
+ body: json === void 0 ? body : JSON.stringify(json),
863
+ headers: sent,
864
+ method,
865
+ signal
866
+ });
867
+ if (!response.ok) throw await failureOf(response);
868
+ return response;
869
+ };
870
+ const read = async (schema, method, path, request) => {
871
+ const text = await (await call(method, path, request)).text();
872
+ return decodeUnknownSync(fromJsonString(schema))(text);
873
+ };
874
+ this.sandboxes = {
875
+ create: async (request = {}, { idempotencyKey, signal } = {}) => await read(Sandbox, "POST", "/sandboxes", {
876
+ headers: idempotencyKey === void 0 ? {} : { "idempotency-key": idempotencyKey },
877
+ json: request,
878
+ signal
879
+ }),
880
+ destroy: async (sandboxId, { signal } = {}) => await read(Sandbox, "DELETE", sandboxPath(sandboxId), { signal }),
881
+ downloadFile: async (sandboxId, path, { signal } = {}) => {
882
+ const response = await call("GET", filePath(sandboxId), {
883
+ query: { path },
884
+ signal
885
+ });
886
+ if (response.body === null) throw new Error("Sandcovery answered no file body", { cause: { status: response.status } });
887
+ return response.body;
888
+ },
889
+ exec: async (sandboxId, request, { signal } = {}) => await read(ExecResult, "POST", `${sandboxPath(sandboxId)}/exec`, {
890
+ json: request,
891
+ signal
892
+ }),
893
+ execDetached: async (sandboxId, request, { signal } = {}) => await read(DetachedExec, "POST", `${sandboxPath(sandboxId)}/exec/detached`, {
894
+ json: request,
895
+ signal
896
+ }),
897
+ async *execStream(sandboxId, request, { signal } = {}) {
898
+ const response = await call("POST", `${sandboxPath(sandboxId)}/exec/stream`, {
899
+ headers: { accept: "text/event-stream" },
900
+ json: request,
901
+ signal
902
+ });
903
+ if (response.body === null) return;
904
+ for await (const { data, event } of serverSentEvents(response.body)) {
905
+ if (event === STREAM_FAILURE_EVENT) throw new Error("Sandcovery failed the stream", { cause: { body: data } });
906
+ yield decodeExecEvent(data);
907
+ }
908
+ },
909
+ get: async (sandboxId, { signal } = {}) => await read(Sandbox, "GET", sandboxPath(sandboxId), { signal }),
910
+ list: async (query = {}, { signal } = {}) => await read(SandboxList, "GET", "/sandboxes", {
911
+ query: { ...query },
912
+ signal
913
+ }),
914
+ listFiles: async (sandboxId, path, { signal } = {}) => await read(FileList, "GET", `${sandboxPath(sandboxId)}/files`, {
915
+ query: { path },
916
+ signal
917
+ }),
918
+ pause: async (sandboxId, { signal } = {}) => await read(Sandbox, "POST", `${sandboxPath(sandboxId)}/pause`, { signal }),
919
+ portPreview: async (sandboxId, port, { signal } = {}) => await read(PortPreview, "GET", `${sandboxPath(sandboxId)}/ports/${portSegment(port)}`, { signal }),
920
+ readFile: async (sandboxId, path, { signal } = {}) => {
921
+ const response = await call("GET", filePath(sandboxId), {
922
+ query: { path },
923
+ signal
924
+ });
925
+ return new Uint8Array(await response.arrayBuffer());
926
+ },
927
+ resume: async (sandboxId, { signal } = {}) => await read(Sandbox, "POST", `${sandboxPath(sandboxId)}/resume`, { signal }),
928
+ snapshot: async (sandboxId, { signal } = {}) => await read(Snapshot, "POST", `${sandboxPath(sandboxId)}/snapshot`, { signal }),
929
+ writeFile: async (sandboxId, path, content, { signal } = {}) => await read(FileEntry, "PUT", filePath(sandboxId), {
930
+ body: content instanceof Uint8Array ? new Uint8Array(content) : content,
931
+ headers: { "content-type": "application/octet-stream" },
932
+ query: { path },
933
+ signal
934
+ })
935
+ };
936
+ this.keys = {
937
+ create: async (request, { signal } = {}) => await read(CreatedKey, "POST", "/keys", {
938
+ json: request,
939
+ signal
940
+ }),
941
+ get: async (keyId, { signal } = {}) => await read(Key, "GET", keyPath(keyId), { signal }),
942
+ list: async ({ signal } = {}) => await read(KeyList, "GET", "/keys", { signal }),
943
+ revoke: async (keyId, { signal } = {}) => await read(Key, "DELETE", keyPath(keyId), { signal }),
944
+ update: async (keyId, request, { signal } = {}) => await read(Key, "PATCH", keyPath(keyId), {
945
+ json: request,
946
+ signal
947
+ })
948
+ };
949
+ this.credentials = {
950
+ add: async (provider, fields, { signal } = {}) => await read(ProviderCredential, "POST", credentialPath(provider), {
951
+ json: fields,
952
+ signal
953
+ }),
954
+ delete: async (provider, { signal } = {}) => {
955
+ await call("DELETE", credentialPath(provider), { signal });
956
+ },
957
+ deleteOne: async (provider, credentialId, { signal } = {}) => {
958
+ await call("DELETE", `${credentialPath(provider)}/${segment(CredentialId, credentialId)}`, { signal });
959
+ },
960
+ list: async ({ signal } = {}) => await read(ProviderCredentialList, "GET", "/credentials", { signal }),
961
+ offer: async ({ signal } = {}) => await read(Offer, "GET", "/offer", { signal }),
962
+ set: async (provider, fields, { signal } = {}) => await read(ProviderCredential, "PUT", credentialPath(provider), {
963
+ json: fields,
964
+ signal
965
+ })
966
+ };
967
+ this.activity = { list: async (query = {}, { signal } = {}) => await read(ActivityList, "GET", "/activity", {
968
+ query: { ...query },
969
+ signal
970
+ }) };
971
+ this.billing = {
972
+ buyCredits: async (request, { signal } = {}) => await read(CreditCheckout, "POST", "/billing/credits", {
973
+ json: request,
974
+ signal
975
+ }),
976
+ get: async ({ signal } = {}) => await read(Billing, "GET", "/billing", { signal })
977
+ };
978
+ this.ci = {
979
+ getJob: async (jobId, { signal } = {}) => await read(CiJob, "GET", ciJobPath(jobId), { signal }),
980
+ listInstallations: async ({ signal } = {}) => await read(CiInstallationList, "GET", "/ci/installations", { signal }),
981
+ listJobs: async (query = {}, { signal } = {}) => await read(CiJobList, "GET", "/ci/jobs", {
982
+ query: { ...query },
983
+ signal
984
+ }),
985
+ unlinkInstallation: async (installationId, { signal } = {}) => {
986
+ await call("DELETE", ciInstallationPath(installationId), { signal });
987
+ }
988
+ };
989
+ this.pricing = { get: async ({ signal } = {}) => await read(Pricing, "GET", "/pricing", { signal }) };
990
+ this.providers = {
991
+ catalog: async ({ signal } = {}) => await read(ProviderCatalog, "GET", "/catalog", { signal }),
992
+ get: async (provider, { signal } = {}) => await read(ProviderBoardEntry, "GET", `/providers/${segment(Provider, provider)}`, { signal }),
993
+ list: async ({ signal } = {}) => await read(ProviderBoard, "GET", "/providers", { signal })
994
+ };
995
+ this.stats = { get: async ({ signal } = {}) => await read(Stats, "GET", "/stats", { signal }) };
996
+ this.usage = {
997
+ estimate: async (request, { signal } = {}) => await read(EstimateList, "POST", "/estimates", {
998
+ json: request,
999
+ signal
1000
+ }),
1001
+ get: async (query, { signal } = {}) => await read(Usage, "GET", "/usage", {
1002
+ query: { ...query },
1003
+ signal
1004
+ }),
1005
+ live: async (query = {}, { signal } = {}) => await read(LiveUsage, "GET", "/usage/live", {
1006
+ query: { ...query },
1007
+ signal
1008
+ }),
1009
+ totals: async (query = {}, { signal } = {}) => await read(UsageTotals, "GET", "/usage/totals", {
1010
+ query: { ...query },
1011
+ signal
1012
+ })
1013
+ };
1014
+ }
1015
+ };
1016
+ export { CredentialFields as a, ApiError as i, CalendarDay as n, GitHubId as o, EstimateRequest as r, Sandcovery as t };