@finalai/sandbox-router-final 0.0.0-stage → 0.2.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.
Files changed (67) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +38 -2
  4. package/dist/modules/frames.d.mts +18 -0
  5. package/dist/modules/frames.mjs +98 -0
  6. package/dist/modules/frames.mjs.map +7 -0
  7. package/dist/modules/images.d.mts +15 -0
  8. package/dist/modules/images.mjs +116 -0
  9. package/dist/modules/images.mjs.map +7 -0
  10. package/dist/modules/index.d.mts +4 -0
  11. package/dist/modules/index.mjs +16 -0
  12. package/dist/modules/index.mjs.map +7 -0
  13. package/dist/modules/limits.d.mts +6 -0
  14. package/dist/modules/limits.mjs +37 -0
  15. package/dist/modules/limits.mjs.map +7 -0
  16. package/dist/modules/options.d.mts +24 -0
  17. package/dist/modules/options.mjs +19 -0
  18. package/dist/modules/options.mjs.map +7 -0
  19. package/dist/modules/provider.d.mts +5 -0
  20. package/dist/modules/provider.mjs +647 -0
  21. package/dist/modules/provider.mjs.map +7 -0
  22. package/dist/modules/vm/api.d.mts +28 -0
  23. package/dist/modules/vm/api.mjs +94 -0
  24. package/dist/modules/vm/api.mjs.map +7 -0
  25. package/dist/modules/vm/client.d.mts +104 -0
  26. package/dist/modules/vm/client.mjs +186 -0
  27. package/dist/modules/vm/client.mjs.map +7 -0
  28. package/dist/modules/vm/clock.d.mts +5 -0
  29. package/dist/modules/vm/clock.mjs +11 -0
  30. package/dist/modules/vm/clock.mjs.map +7 -0
  31. package/dist/modules/vm/errors.d.mts +23 -0
  32. package/dist/modules/vm/errors.mjs +30 -0
  33. package/dist/modules/vm/errors.mjs.map +7 -0
  34. package/dist/modules/vm/exec.d.mts +47 -0
  35. package/dist/modules/vm/exec.mjs +292 -0
  36. package/dist/modules/vm/exec.mjs.map +7 -0
  37. package/dist/modules/vm/files.d.mts +18 -0
  38. package/dist/modules/vm/files.mjs +160 -0
  39. package/dist/modules/vm/files.mjs.map +7 -0
  40. package/dist/modules/vm/grants.d.mts +35 -0
  41. package/dist/modules/vm/grants.mjs +106 -0
  42. package/dist/modules/vm/grants.mjs.map +7 -0
  43. package/dist/modules/vm/ids.d.mts +3 -0
  44. package/dist/modules/vm/ids.mjs +35 -0
  45. package/dist/modules/vm/ids.mjs.map +7 -0
  46. package/dist/modules/vm/ingress.d.mts +99 -0
  47. package/dist/modules/vm/ingress.mjs +263 -0
  48. package/dist/modules/vm/ingress.mjs.map +7 -0
  49. package/dist/modules/vm/machines.d.mts +79 -0
  50. package/dist/modules/vm/machines.mjs +60 -0
  51. package/dist/modules/vm/machines.mjs.map +7 -0
  52. package/dist/modules/vm/network.d.mts +17 -0
  53. package/dist/modules/vm/network.mjs +44 -0
  54. package/dist/modules/vm/network.mjs.map +7 -0
  55. package/dist/modules/vm/sandbox.d.mts +75 -0
  56. package/dist/modules/vm/sandbox.mjs +175 -0
  57. package/dist/modules/vm/sandbox.mjs.map +7 -0
  58. package/dist/modules/vm/schemas.d.mts +1209 -0
  59. package/dist/modules/vm/schemas.mjs +289 -0
  60. package/dist/modules/vm/schemas.mjs.map +7 -0
  61. package/dist/modules/vm/wire.d.mts +3 -0
  62. package/dist/modules/vm/wire.mjs +9 -0
  63. package/dist/modules/vm/wire.mjs.map +7 -0
  64. package/dist/modules/vm/workload.d.mts +14 -0
  65. package/dist/modules/vm/workload.mjs +11 -0
  66. package/dist/modules/vm/workload.mjs.map +7 -0
  67. package/package.json +38 -4
@@ -0,0 +1,647 @@
1
+ import {
2
+ AtEnd,
3
+ attempt,
4
+ defineProvider,
5
+ EgressMode,
6
+ ExitReason,
7
+ fail,
8
+ failFromStatus,
9
+ FileKind,
10
+ fitWithinLimits,
11
+ canonicalJson,
12
+ formatUsd,
13
+ sha256Hex,
14
+ HardwareConfidence,
15
+ isEgressAllowList,
16
+ ok,
17
+ PauseKeep,
18
+ PortAuth,
19
+ ProcessFrameKind,
20
+ ProcessSignal,
21
+ BillingModel,
22
+ SandboxRouterErrorCode,
23
+ SandboxState,
24
+ shellQuote,
25
+ SPECIFICATION_VERSION,
26
+ toNanos,
27
+ unsupported
28
+ } from "@finalai/sandbox-router/provider";
29
+ import { capabilities, DEFAULT_DISK_GIB, limits, PROVIDER, regions } from "./limits.mjs";
30
+ import { createSeqFrames } from "./frames.mjs";
31
+ import { baseReference, buildImage, ensureImage, imageStrategy } from "./images.mjs";
32
+ import {
33
+ finalOptionsSchema
34
+ } from "./options.mjs";
35
+ import {
36
+ createVmClient,
37
+ SourceKind
38
+ } from "./vm/client.mjs";
39
+ import { systemClock } from "./vm/clock.mjs";
40
+ import { isVmError } from "./vm/errors.mjs";
41
+ import { SandboxState as VmState } from "./vm/schemas.mjs";
42
+ import { PREVIEW_TOKEN_HEADER, PREVIEW_TOKEN_QUERY } from "./vm/wire.mjs";
43
+ const REGION = regions[0] ?? "us-west";
44
+ const SETTLE_TIMEOUT_MS = 5 * 6e4;
45
+ const SETTLE_POLL_MS = 500;
46
+ const LIST_PAGE = 200;
47
+ const PREVIEW_TOKEN_TTL_S = 86400;
48
+ const MAX_CACHED_HANDLES = 1e3;
49
+ const HOURS_PER_MONTH = 730;
50
+ const STATES = {
51
+ [VmState.Creating]: SandboxState.Creating,
52
+ [VmState.Running]: SandboxState.Running,
53
+ [VmState.Starting]: SandboxState.Creating,
54
+ [VmState.Resuming]: SandboxState.Creating,
55
+ [VmState.Pausing]: SandboxState.Paused,
56
+ [VmState.Paused]: SandboxState.Paused,
57
+ [VmState.Stopping]: SandboxState.Stopped,
58
+ [VmState.Stopped]: SandboxState.Stopped,
59
+ [VmState.Deleting]: SandboxState.Deleted,
60
+ [VmState.Deleted]: SandboxState.Deleted,
61
+ [VmState.Failed]: SandboxState.Failed
62
+ };
63
+ const sandboxStateOf = (native) => STATES[native] ?? SandboxState.Unknown;
64
+ const GONE = /* @__PURE__ */ new Set([VmState.Deleting, VmState.Deleted]);
65
+ const toVendor = (info) => ({
66
+ providerSandboxId: info.id,
67
+ region: REGION,
68
+ state: sandboxStateOf(info.state),
69
+ nativeState: info.state,
70
+ nativeError: info.state === VmState.Failed ? info.interruption?.reason ?? info.recovery?.reason ?? null : null,
71
+ labels: info.labels,
72
+ createdAt: info.createdAt.toISOString(),
73
+ granted: {
74
+ cpu: info.cpu?.request ?? info.vcpu,
75
+ memoryMib: info.memory?.request ?? info.memoryMb,
76
+ diskGib: info.diskGb
77
+ }
78
+ });
79
+ const SIGNALS = {
80
+ [ProcessSignal.Hup]: 1,
81
+ [ProcessSignal.Int]: 2,
82
+ [ProcessSignal.Kill]: 9,
83
+ [ProcessSignal.Term]: 15
84
+ };
85
+ const signalName = (signal) => {
86
+ if (signal == null) return null;
87
+ const known = Object.entries(SIGNALS).find(([, number]) => number === signal);
88
+ return known?.[0] ?? `SIG${signal}`;
89
+ };
90
+ const fileKind = (kind) => kind === "file" ? FileKind.File : kind === "directory" ? FileKind.Directory : kind === "symlink" ? FileKind.Symlink : FileKind.Other;
91
+ const fileEntry = (stat) => ({
92
+ name: stat.path.split("/").filter((part) => part !== "").at(-1) ?? "/",
93
+ path: stat.path,
94
+ kind: fileKind(stat.kind),
95
+ size: stat.size,
96
+ modifiedAt: Number.isNaN(stat.modifiedAt.getTime()) ? null : stat.modifiedAt.toISOString(),
97
+ mode: stat.mode & 4095
98
+ });
99
+ const classify = (cause) => {
100
+ if (!isVmError(cause)) return null;
101
+ const nativeError = `${cause.code}: ${cause.message}`;
102
+ if (cause.status == null) {
103
+ if (cause.code === "timeout")
104
+ return fail(SandboxRouterErrorCode.Timeout, cause.message, { retryable: true, nativeError });
105
+ if (cause.code === "request_failed" || cause.code === "connect_failed")
106
+ return fail(SandboxRouterErrorCode.NetworkError, cause.message, {
107
+ retryable: true,
108
+ nativeError
109
+ });
110
+ return fail(SandboxRouterErrorCode.ProviderError, cause.message, { nativeError });
111
+ }
112
+ if (cause.status === 410)
113
+ return fail(SandboxRouterErrorCode.NotFound, "final has no such resource", {
114
+ status: 410,
115
+ nativeError
116
+ });
117
+ return failFromStatus(PROVIDER, cause.status, nativeError);
118
+ };
119
+ const isMissing = (cause) => isVmError(cause) && (cause.status === 404 || cause.status === 410 || cause.code === "invalid_id");
120
+ const call = (run) => attempt(PROVIDER, run, classify);
121
+ const failure = (cause) => classify(cause) ?? fail(SandboxRouterErrorCode.ProviderError, `${PROVIDER} failed`, {
122
+ nativeError: cause instanceof Error ? cause.message : String(cause)
123
+ });
124
+ const classifyCreate = (cause) => {
125
+ const lost = isVmError(cause) && (cause.status == null && cause.code === "request_failed" || cause.code === "pending") || cause instanceof Error && (cause.name === "TimeoutError" || cause.name === "AbortError");
126
+ if (lost)
127
+ return fail(SandboxRouterErrorCode.Timeout, "final did not answer the create", {
128
+ retryable: true,
129
+ nativeError: cause instanceof Error ? cause.message : String(cause)
130
+ });
131
+ return classify(cause);
132
+ };
133
+ const networkFields = (network) => {
134
+ if (network.egress === EgressMode.AllowAll)
135
+ return { allowInternet: true, allowDomains: [], allowCidrs: [] };
136
+ if (network.egress === EgressMode.DenyAll)
137
+ return { allowInternet: false, allowDomains: [], allowCidrs: [] };
138
+ return isEgressAllowList(network.egress) ? {
139
+ allowInternet: false,
140
+ allowDomains: network.egress.allowDomains ?? [],
141
+ allowCidrs: network.egress.allowCidrs ?? []
142
+ } : { allowInternet: false, allowDomains: [], allowCidrs: [] };
143
+ };
144
+ const timerFields = (spec) => spec.atEnd === AtEnd.Pause ? { idleTimeoutS: spec.timeouts.idleS, wallClockLimitS: spec.timeouts.maxS } : {
145
+ idleTimeoutS: spec.timeouts.idleS,
146
+ ephemeral: spec.timeouts.idleS == null ? void 0 : true,
147
+ ttlS: spec.timeouts.maxS
148
+ };
149
+ const sourceOf = (artifact) => artifact.kind === "template" ? { kind: SourceKind.Template, templateId: artifact.id } : artifact.kind === "snapshot" ? { kind: SourceKind.Snapshot, snapshotId: artifact.id } : { kind: SourceKind.Image, imageId: artifact.id };
150
+ const IDLE_WORKLOAD = {
151
+ entrypoint: ["/bin/sh", "-c"],
152
+ cmd: ["exec sleep infinity"],
153
+ restart: false
154
+ };
155
+ const sameSize = (source, size) => source.cpu?.request === size.cpu[0] && source.cpu.limit === size.cpu[1] && source.memory?.request === size.memory[0] && source.memory.limit === size.memory[1];
156
+ const final = (credentials, options = {}) => {
157
+ const clock = systemClock;
158
+ const client = createVmClient({
159
+ apiKey: credentials.apiKey,
160
+ apiUrl: credentials.apiUrl,
161
+ previewDomain: options.previewDomain,
162
+ fetch: options.fetch
163
+ });
164
+ const handles = /* @__PURE__ */ new Map();
165
+ const remember = (handle) => {
166
+ if (handles.size >= MAX_CACHED_HANDLES) {
167
+ const oldest = handles.keys().next().value;
168
+ if (oldest != null) handles.delete(oldest);
169
+ }
170
+ handles.set(handle.id, handle);
171
+ return handle;
172
+ };
173
+ const handleOf = async (id) => handles.get(id) ?? remember(await client.sandboxes.get(id));
174
+ const withHandle = (id, run) => call(async () => run(await handleOf(id)));
175
+ const settle = async (handle, want, signal) => {
176
+ const deadline = clock.now() + SETTLE_TIMEOUT_MS;
177
+ let info = handle.info();
178
+ for (; ; ) {
179
+ if (want.some((state) => state === info.state)) return info;
180
+ if (info.state === VmState.Failed || GONE.has(info.state))
181
+ throw new Error(`sandbox ${handle.id} is ${info.state}`);
182
+ if (clock.now() >= deadline)
183
+ throw Object.assign(new Error(`sandbox ${handle.id} is still ${info.state}`), {
184
+ name: "TimeoutError"
185
+ });
186
+ await clock.sleep(SETTLE_POLL_MS, signal);
187
+ info = await handle.refresh();
188
+ }
189
+ };
190
+ const ready = async (handle, signal) => toVendor(await settle(handle, [VmState.Running], signal));
191
+ const startTemplateService = async (handle, templateId, env) => {
192
+ const template = await client.templates.get(templateId);
193
+ if (template.startCmd == null) return;
194
+ const result = await handle.run(
195
+ `nohup sh -c ${shellQuote(template.startCmd)} >/tmp/sandbox-start.log 2>&1 </dev/null &`,
196
+ { env }
197
+ );
198
+ if (result.exitCode !== 0) throw new Error(`the start command failed: ${result.stderr}`);
199
+ };
200
+ const resolveSource = async (args) => {
201
+ const { spec, size, artifact } = args;
202
+ const plain = (source) => ({
203
+ source,
204
+ sized: true,
205
+ workload: void 0,
206
+ startTemplate: null
207
+ });
208
+ if (args.snapshotId != null)
209
+ return ok({
210
+ source: { kind: SourceKind.Snapshot, snapshotId: args.snapshotId },
211
+ sized: false,
212
+ workload: void 0,
213
+ startTemplate: null
214
+ });
215
+ if (artifact?.kind === "template") {
216
+ const template = await client.templates.get(artifact.id);
217
+ const restorable = Object.keys(spec.env).length === 0 && sameSize(template, size);
218
+ return ok(
219
+ restorable ? { source: sourceOf(artifact), sized: false, workload: void 0, startTemplate: null } : {
220
+ ...plain({ kind: SourceKind.Image, imageId: template.imageId }),
221
+ startTemplate: artifact.id
222
+ }
223
+ );
224
+ }
225
+ if (artifact?.kind === "snapshot") {
226
+ const snapshot = await client.snapshots.get(artifact.id);
227
+ return ok(
228
+ sameSize(snapshot, size) ? { source: sourceOf(artifact), sized: false, workload: void 0, startTemplate: null } : { ...plain(sourceOf(artifact)), workload: IDLE_WORKLOAD }
229
+ );
230
+ }
231
+ if (artifact != null) return ok(plain(sourceOf(artifact)));
232
+ if (spec.image == null) return ok(plain());
233
+ const reference = baseReference(spec.image.base);
234
+ if (reference == null) return ok(plain());
235
+ const image = await ensureImage({ client, clock, signal: args.signal }, reference);
236
+ return image.ok ? ok(plain({ kind: SourceKind.Image, imageId: image.value })) : image;
237
+ };
238
+ const stream = async (args) => {
239
+ const stdout = args.pty ? ProcessFrameKind.Data : ProcessFrameKind.Stdout;
240
+ const stderr = args.pty ? ProcessFrameKind.Data : ProcessFrameKind.Stderr;
241
+ let process = null;
242
+ let killed = false;
243
+ let detached = false;
244
+ const sendKill = (signal) => {
245
+ try {
246
+ process?.kill(signal);
247
+ } catch {
248
+ }
249
+ };
250
+ const frames = createSeqFrames({
251
+ afterSeq: args.afterSeq,
252
+ awaitStarted: args.afterSeq < 0,
253
+ maxOutputBytes: limits.maxOutputBytes,
254
+ onOutputCap: () => sendKill(SIGNALS[ProcessSignal.Kill])
255
+ });
256
+ const opened = await call(
257
+ () => args.open({
258
+ onStdout: (bytes, seq) => frames.output(stdout, seq, bytes),
259
+ onStderr: (bytes, seq) => frames.output(stderr, seq, bytes)
260
+ })
261
+ );
262
+ if (!opened.ok) return opened;
263
+ const current = opened.value;
264
+ process = current;
265
+ if (args.afterSeq < 0) frames.started(current.processId, current.pid);
266
+ if (!args.keepStdin)
267
+ try {
268
+ current.closeStdin();
269
+ } catch {
270
+ }
271
+ current.wait().then(
272
+ (result) => frames.exit(
273
+ result.exitCode,
274
+ result.timedOut ? ExitReason.Timeout : killed || result.signal != null ? ExitReason.Killed : ExitReason.Exited,
275
+ signalName(result.signal)
276
+ ),
277
+ (cause) => {
278
+ if (detached) return;
279
+ if (isVmError(cause) && (cause.code === "exec_unreachable" || cause.code === "exec_lost"))
280
+ frames.exit(null, ExitReason.ProviderLost, null);
281
+ else
282
+ frames.error(
283
+ SandboxRouterErrorCode.ProviderError,
284
+ cause instanceof Error ? cause.message : String(cause)
285
+ );
286
+ }
287
+ );
288
+ args.signal?.addEventListener("abort", () => sendKill(SIGNALS[ProcessSignal.Kill]), {
289
+ once: true
290
+ });
291
+ const input = (send) => call(async () => {
292
+ send();
293
+ });
294
+ return ok({
295
+ processId: current.processId,
296
+ frames: frames.frames,
297
+ write: (data) => input(() => current.write(data)),
298
+ closeStdin: () => input(() => current.closeStdin()),
299
+ kill: async (signal) => {
300
+ if (!frames.ended()) {
301
+ killed = true;
302
+ sendKill(SIGNALS[signal ?? ProcessSignal.Term]);
303
+ }
304
+ return ok(void 0);
305
+ },
306
+ detach: () => {
307
+ detached = true;
308
+ current.detach();
309
+ frames.stop();
310
+ },
311
+ resize: (size) => input(() => current.resize(size))
312
+ });
313
+ };
314
+ const fit = (spec) => {
315
+ const diskGib = spec.diskGib ?? DEFAULT_DISK_GIB;
316
+ const fitted = fitWithinLimits({ limits, spec: { ...spec, diskGib } });
317
+ if (spec.gpu != null) fitted.rejected.push({ field: "gpu", reason: "no GPUs" });
318
+ if (spec.region != null && !regions.includes(spec.region))
319
+ fitted.rejected.push({ field: "region", reason: `only ${regions.join(", ")}` });
320
+ return {
321
+ ...fitted,
322
+ applied: spec.diskGib == null ? fitted.applied.filter((field) => field !== "diskGib") : fitted.applied
323
+ };
324
+ };
325
+ const prices = async (spec, context) => {
326
+ const parsed = finalOptionsSchema.safeParse(context.providerOptions ?? {});
327
+ if (!parsed.success) return fail(SandboxRouterErrorCode.InvalidRequest, parsed.error.message);
328
+ const { cpuLimit, memoryLimitMib, machine } = parsed.data;
329
+ const diskGib = spec.diskGib ?? DEFAULT_DISK_GIB;
330
+ const listed = await call(
331
+ () => client.machineTypes.list({
332
+ cpu: [spec.cpu, cpuLimit ?? spec.cpu],
333
+ memory: [spec.memoryMib, memoryLimitMib ?? spec.memoryMib],
334
+ diskGb: diskGib
335
+ })
336
+ );
337
+ if (!listed.ok) return listed;
338
+ const cheapest = listed.value.find(
339
+ (entry) => entry.price.hourly != null && entry.price.currency.toUpperCase() === "USD" && (machine?.types == null || machine.types.includes(entry.machineType)) && (machine?.cpuFamilies == null || machine.cpuFamilies.includes(entry.hardware.cpuFamily))
340
+ );
341
+ if (cheapest?.price.hourly == null)
342
+ return fail(SandboxRouterErrorCode.ProviderError, "no priced machine type fits the spec");
343
+ const diskGibMonth = cheapest.price.diskGibMonth;
344
+ return ok({
345
+ hourlyRunning: cheapest.price.hourly.baseline,
346
+ hourlyPaused: diskGibMonth == null ? null : formatUsd(diskGib * toNanos(diskGibMonth) / HOURS_PER_MONTH),
347
+ perCreate: "0",
348
+ // Names the exact prices (not where they run), so a price change is a new version.
349
+ priceVersion: `${PROVIDER}@${(await sha256Hex(canonicalJson(cheapest.price))).slice(0, 12)}`,
350
+ billingModel: BillingModel.MaxOfRequestAndUse,
351
+ hardware: {
352
+ chips: [cheapest.hardware.cpuModel],
353
+ host: null,
354
+ confidence: HardwareConfidence.Documented,
355
+ sourceUrl: null
356
+ },
357
+ sourceUrl: null
358
+ });
359
+ };
360
+ return defineProvider({
361
+ specificationVersion: SPECIFICATION_VERSION,
362
+ name: PROVIDER,
363
+ regions,
364
+ capabilities,
365
+ limits,
366
+ providerOptions: finalOptionsSchema,
367
+ fit,
368
+ prices,
369
+ create: async (spec, context) => {
370
+ const providerOptions = finalOptionsSchema.parse(context.providerOptions ?? {});
371
+ const size = {
372
+ cpu: [spec.cpu, providerOptions.cpuLimit ?? spec.cpu],
373
+ memory: [spec.memoryMib, providerOptions.memoryLimitMib ?? spec.memoryMib]
374
+ };
375
+ const resolved = await call(
376
+ () => resolveSource({
377
+ spec,
378
+ size,
379
+ artifact: context.artifact,
380
+ snapshotId: context.snapshotId,
381
+ signal: context.signal
382
+ })
383
+ );
384
+ if (!resolved.ok) return resolved;
385
+ if (!resolved.value.ok) return resolved.value;
386
+ const plan = resolved.value.value;
387
+ const request = {
388
+ projectId: providerOptions.projectId,
389
+ source: plan.source,
390
+ workload: plan.workload,
391
+ cpu: plan.sized ? size.cpu : void 0,
392
+ memory: plan.sized ? size.memory : void 0,
393
+ diskGb: spec.diskGib,
394
+ machine: providerOptions.machine,
395
+ env: Object.keys(spec.env).length === 0 ? void 0 : spec.env,
396
+ ports: spec.ports,
397
+ publicPorts: providerOptions.publicPorts,
398
+ tools: providerOptions.tools,
399
+ ...networkFields(spec.network),
400
+ ...timerFields(spec),
401
+ labels: { name: context.name, ...context.labels },
402
+ signal: context.signal
403
+ };
404
+ const created = await attempt(
405
+ PROVIDER,
406
+ async () => remember(await client.sandboxes.create(request)),
407
+ classifyCreate
408
+ );
409
+ if (!created.ok) return created;
410
+ const handle = created.value;
411
+ const started = await call(async () => {
412
+ const sandbox = await ready(handle, context.signal);
413
+ if (plan.startTemplate != null)
414
+ await startTemplateService(handle, plan.startTemplate, spec.env);
415
+ return sandbox;
416
+ });
417
+ if (!started.ok) await handle.delete().catch(() => void 0);
418
+ return started;
419
+ },
420
+ get: async (id) => {
421
+ try {
422
+ const cached = handles.get(id);
423
+ const info = cached == null ? remember(await client.sandboxes.get(id)).info() : await cached.refresh();
424
+ return ok(toVendor(info));
425
+ } catch (cause) {
426
+ if (isMissing(cause)) return ok(null);
427
+ return failure(cause);
428
+ }
429
+ },
430
+ list: ({ labels }) => call(async () => {
431
+ const found = [];
432
+ let after;
433
+ for (; ; ) {
434
+ const page = await client.sandboxes.list({ labels, after, limit: LIST_PAGE });
435
+ for (const info of page) if (!GONE.has(info.state)) found.push(toVendor(info));
436
+ if (page.length < LIST_PAGE) return found;
437
+ after = page.at(-1)?.id;
438
+ }
439
+ }),
440
+ delete: async (id) => {
441
+ try {
442
+ const handle = await handleOf(id);
443
+ if (!GONE.has(handle.info().state)) await handle.delete();
444
+ handles.delete(id);
445
+ return ok(void 0);
446
+ } catch (cause) {
447
+ handles.delete(id);
448
+ if (isMissing(cause)) return ok(void 0);
449
+ return failure(cause);
450
+ }
451
+ },
452
+ pause: (id) => withHandle(id, async (handle) => {
453
+ await handle.pause();
454
+ await settle(handle, [VmState.Paused]);
455
+ return { kept: PauseKeep.Memory };
456
+ }),
457
+ resume: (id) => withHandle(id, async (handle) => {
458
+ const result = await handle.resume();
459
+ await settle(handle, [VmState.Running]);
460
+ return { coldRestart: result.resumed?.mode === "cold" };
461
+ }),
462
+ stop: (id) => withHandle(id, async (handle) => {
463
+ await handle.stop();
464
+ await settle(handle, [VmState.Stopped]);
465
+ }),
466
+ start: (id) => withHandle(id, async (handle) => {
467
+ await handle.start();
468
+ await settle(handle, [VmState.Running]);
469
+ }),
470
+ // The wall-clock limit, counted from now; Final VMs pause the sandbox when it runs out. The
471
+ // idle timeout is set at create only.
472
+ setTimeout: async (id, timeouts) => {
473
+ if (timeouts.idleS != null) return unsupported(PROVIDER, "changing the idle timeout");
474
+ const maxS = timeouts.maxS;
475
+ if (maxS == null) return ok(void 0);
476
+ return withHandle(id, async (handle) => {
477
+ await handle.setTimeout(maxS);
478
+ });
479
+ },
480
+ setNetwork: (id, network) => withHandle(id, async (handle) => {
481
+ const fields = networkFields(network);
482
+ let status = await handle.network.set({ ...fields, denyCidrs: [] });
483
+ const deadline = clock.now() + SETTLE_TIMEOUT_MS;
484
+ while (!status.applied && clock.now() < deadline) {
485
+ await clock.sleep(SETTLE_POLL_MS);
486
+ status = await handle.network.get();
487
+ }
488
+ if (!status.applied) throw new Error("the network policy was not applied in time");
489
+ }),
490
+ exec: (id, command, execOptions) => withHandle(
491
+ id,
492
+ (handle) => stream({
493
+ open: (handlers) => handle.exec({
494
+ cmd: command,
495
+ env: execOptions.env,
496
+ cwd: execOptions.cwd,
497
+ user: execOptions.user,
498
+ timeoutMs: execOptions.timeoutMs,
499
+ ...handlers
500
+ }),
501
+ afterSeq: -1,
502
+ pty: false,
503
+ keepStdin: execOptions.stdin === true,
504
+ signal: execOptions.signal
505
+ })
506
+ ).then((result) => result.ok ? result.value : result),
507
+ attach: (id, processId, { afterSeq }) => withHandle(
508
+ id,
509
+ (handle) => stream({
510
+ open: (handlers) => handle.attach({ processId, afterSeq: Math.max(afterSeq, 0), ...handlers }),
511
+ afterSeq: Math.max(afterSeq, 0),
512
+ pty: false,
513
+ keepStdin: true
514
+ })
515
+ ).then((result) => result.ok ? result.value : result),
516
+ pty: (id, ptyOptions) => withHandle(
517
+ id,
518
+ (handle) => stream({
519
+ open: (handlers) => handle.exec({
520
+ cmd: ptyOptions.command ?? 'exec "${SHELL:-/bin/bash}" -l',
521
+ env: ptyOptions.env,
522
+ cwd: ptyOptions.cwd,
523
+ pty: { cols: ptyOptions.cols, rows: ptyOptions.rows },
524
+ ...handlers
525
+ }),
526
+ afterSeq: -1,
527
+ pty: true,
528
+ keepStdin: true
529
+ })
530
+ ).then((result) => result.ok ? result.value : result),
531
+ files: {
532
+ read: (id, path, range) => withHandle(
533
+ id,
534
+ (handle) => handle.files.read(path, { offset: range?.offset, length: range?.length })
535
+ ),
536
+ write: (id, path, bytes, writeOptions) => withHandle(id, async (handle) => {
537
+ await handle.files.write(path, bytes, { mode: writeOptions?.mode });
538
+ }),
539
+ list: (id, path) => withHandle(id, async (handle) => (await handle.files.list(path)).entries.map(fileEntry)),
540
+ mkdir: (id, path, mkdirOptions) => withHandle(
541
+ id,
542
+ (handle) => handle.files.mkdir(path, { parents: mkdirOptions?.recursive ?? true })
543
+ ),
544
+ remove: (id, path, removeOptions) => withHandle(id, async (handle) => {
545
+ try {
546
+ await handle.files.remove(path, { recursive: removeOptions?.recursive });
547
+ } catch (cause) {
548
+ if (!(isVmError(cause) && cause.status === 404)) throw cause;
549
+ }
550
+ }),
551
+ stat: (id, path) => withHandle(id, async (handle) => {
552
+ const stat = await handle.files.stat(path);
553
+ return stat == null ? null : fileEntry(stat);
554
+ })
555
+ },
556
+ ports: {
557
+ // A published port is public; any other answers to a preview token, sent in a header by
558
+ // programs (a browser opening the URL exchanges it for a session cookie).
559
+ url: (id, port) => withHandle(id, async (handle) => {
560
+ const [published, base] = await Promise.all([
561
+ handle.listPorts(),
562
+ handle.previewUrl(port)
563
+ ]);
564
+ if (published.some((entry) => entry.port === port && entry.public))
565
+ return { url: base, auth: PortAuth.Public, token: null, expiresAt: null };
566
+ const token = await handle.createPreviewToken(port, { ttlS: PREVIEW_TOKEN_TTL_S });
567
+ const url = new URL(base);
568
+ url.searchParams.set(PREVIEW_TOKEN_QUERY, token.token);
569
+ return {
570
+ url: url.toString(),
571
+ auth: PortAuth.Header,
572
+ token: token.token,
573
+ header: PREVIEW_TOKEN_HEADER,
574
+ expiresAt: token.expiresAt.toISOString()
575
+ };
576
+ })
577
+ },
578
+ snapshot: (id, { name }) => withHandle(id, async (handle) => {
579
+ try {
580
+ return await handle.checkpoint({ name });
581
+ } catch (cause) {
582
+ if (!(isVmError(cause) && cause.code === "name_taken")) throw cause;
583
+ const earlier = (await client.snapshots.list()).find(
584
+ (snapshot) => snapshot.name === name && snapshot.sandboxId === id
585
+ );
586
+ if (earlier != null) return { snapshotId: earlier.id };
587
+ return handle.checkpoint({ name: `${name}-${crypto.randomUUID().slice(0, 8)}` });
588
+ }
589
+ }),
590
+ deleteSnapshot: async (snapshotId) => {
591
+ try {
592
+ await client.snapshots.delete(snapshotId);
593
+ return ok(void 0);
594
+ } catch (cause) {
595
+ if (isMissing(cause)) return ok(void 0);
596
+ return failure(cause);
597
+ }
598
+ },
599
+ fork: (id, { count, labels, name }) => withHandle(id, async (handle) => {
600
+ const { children } = await handle.fork(count);
601
+ return Promise.all(
602
+ children.map(async (child, index) => {
603
+ remember(child);
604
+ await child.updateLabels({ name: `${name}-${index}`, ...labels });
605
+ return ready(child);
606
+ })
607
+ );
608
+ }),
609
+ image: {
610
+ strategy: imageStrategy,
611
+ build: (spec, buildContext) => call(
612
+ () => buildImage(
613
+ { client, clock, signal: buildContext.signal, onLog: buildContext.onLog },
614
+ spec
615
+ )
616
+ ).then((result) => result.ok ? result.value : result),
617
+ remove: async (artifact) => {
618
+ try {
619
+ if (artifact.kind === "template") await client.templates.delete(artifact.id);
620
+ else if (artifact.kind === "snapshot") await client.snapshots.delete(artifact.id);
621
+ else await client.images.delete(artifact.id);
622
+ return ok(void 0);
623
+ } catch (cause) {
624
+ if (isMissing(cause)) return ok(void 0);
625
+ return failure(cause);
626
+ }
627
+ }
628
+ },
629
+ connect: (id) => withHandle(id, async (handle) => {
630
+ const grant = await handle.connect();
631
+ return {
632
+ provider: PROVIDER,
633
+ providerSandboxId: id,
634
+ kind: "grant",
635
+ token: grant.token,
636
+ url: grant.endpoint.includes("://") ? grant.endpoint : `https://${grant.endpoint}`,
637
+ expiresAt: new Date(grant.expiresAt).toISOString(),
638
+ details: { generation: String(grant.generation) }
639
+ };
640
+ })
641
+ });
642
+ };
643
+ export {
644
+ final,
645
+ sandboxStateOf
646
+ };
647
+ //# sourceMappingURL=provider.mjs.map