@finalai/sandbox-router-daytona 0.2.1 → 0.2.2

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,11 +1,13 @@
1
1
  import {
2
- AtEnd,
3
2
  defineProvider,
3
+ DesktopState,
4
4
  EgressMode,
5
5
  ExitReason,
6
6
  fail,
7
7
  FileKind,
8
8
  fitWithinLimits,
9
+ IdleAction,
10
+ MaxAction,
9
11
  ImageStepKind,
10
12
  ImageStrategy,
11
13
  ok,
@@ -16,7 +18,8 @@ import {
16
18
  SandboxState,
17
19
  sha256Hex,
18
20
  shellQuote,
19
- SPECIFICATION_VERSION
21
+ SPECIFICATION_VERSION,
22
+ VolumeState
20
23
  } from "@finalai/sandbox-router/provider";
21
24
  import * as z from "zod";
22
25
  import { DAYTONA_CAPABILITIES, DAYTONA_REGIONS, daytonaLimits } from "./limits.mjs";
@@ -25,8 +28,10 @@ import {
25
28
  DaytonaErrorCode,
26
29
  DaytonaSandboxState,
27
30
  DaytonaSnapshotState,
31
+ DaytonaVolumeState,
28
32
  failureMessage
29
33
  } from "./client/index.mjs";
34
+ import { asUser } from "./client/processes.mjs";
30
35
  import { baseDockerfile, DEFAULT_DAYTONA_IMAGE, specDockerfile } from "./dockerfile.mjs";
31
36
  import {
32
37
  createProcessRegistry,
@@ -44,10 +49,16 @@ const POLL_MS = 500;
44
49
  const DEFAULT_OPERATION_TIMEOUT_MS = 10 * 6e4;
45
50
  const CIDR = /^\d{1,3}(?:\.\d{1,3}){3}\/\d{1,2}$/;
46
51
  const ARTIFACT_PREFIX = "dockerfile-sha256:";
52
+ const CAPACITY_REFUSAL = /no available runners?|no capacity|insufficient capacity|quota exceeded/i;
47
53
  const errorOf = (result2) => {
48
54
  const message = failureMessage(result2);
49
55
  const status = result2.statusCode ?? null;
50
56
  const options = { status, nativeError: message };
57
+ if (CAPACITY_REFUSAL.test(message))
58
+ return fail(SandboxRouterErrorCode.NoCapacity, `${PROVIDER} has no capacity for the sandbox`, {
59
+ ...options,
60
+ retryable: true
61
+ });
51
62
  switch (result2.error) {
52
63
  case DaytonaErrorCode.Unauthorized:
53
64
  case DaytonaErrorCode.Forbidden:
@@ -133,7 +144,66 @@ const sandboxOf = (sandbox) => ({
133
144
  nativeError: sandbox.errorReason,
134
145
  labels: sandbox.labels,
135
146
  createdAt: sandbox.createdAt,
136
- granted: sandbox.cpu == null || sandbox.memory == null ? null : { cpu: sandbox.cpu, memoryMib: sandbox.memory * 1024, diskGib: sandbox.disk }
147
+ granted: sandbox.cpu == null || sandbox.memory == null ? null : { cpu: sandbox.cpu, memoryMib: sandbox.memory * 1024, diskGib: sandbox.disk },
148
+ lifecycle: lifecycleOfSandbox(sandbox)
149
+ });
150
+ const lifecycleOfSandbox = (sandbox) => {
151
+ if (sandbox.autoStopInterval == null || sandbox.autoDeleteInterval == null) return null;
152
+ const destroyAt = sandbox.autoDestroyAt == null ? null : Date.parse(sandbox.autoDestroyAt);
153
+ const createdAt = sandbox.createdAt == null ? null : Date.parse(sandbox.createdAt);
154
+ return {
155
+ idle: sandbox.autoStopInterval > 0 ? {
156
+ afterS: sandbox.autoStopInterval * 60,
157
+ action: sandbox.autoDeleteInterval >= 0 ? IdleAction.Delete : IdleAction.Stop
158
+ } : null,
159
+ max: destroyAt == null || createdAt == null || !(destroyAt > createdAt) ? null : { afterS: Math.round((destroyAt - createdAt) / 1e3), action: MaxAction.Delete },
160
+ autoResume: false
161
+ };
162
+ };
163
+ const ENDING_SIGNALS = /* @__PURE__ */ new Set([
164
+ ProcessSignal.Term,
165
+ ProcessSignal.Kill,
166
+ ProcessSignal.Int,
167
+ ProcessSignal.Hup,
168
+ ProcessSignal.Quit
169
+ ]);
170
+ const signalRefusal = (signal) => signal == null || ENDING_SIGNALS.has(signal) ? null : fail(
171
+ SandboxRouterErrorCode.UnsupportedByProvider,
172
+ `Daytona can end a process but not send it ${signal}`
173
+ );
174
+ const volumeStateOf = (state) => {
175
+ switch (state) {
176
+ case DaytonaVolumeState.PendingCreate:
177
+ case DaytonaVolumeState.Creating:
178
+ return VolumeState.Creating;
179
+ case DaytonaVolumeState.Ready:
180
+ return VolumeState.Ready;
181
+ case DaytonaVolumeState.PendingDelete:
182
+ case DaytonaVolumeState.Deleting:
183
+ case DaytonaVolumeState.Deleted:
184
+ return VolumeState.Deleted;
185
+ case DaytonaVolumeState.Error:
186
+ case DaytonaVolumeState.Other:
187
+ return VolumeState.Unknown;
188
+ }
189
+ };
190
+ const volumeOf = (volume) => ({
191
+ volumeId: volume.id,
192
+ name: volume.name,
193
+ region: "",
194
+ sizeGib: null,
195
+ state: volumeStateOf(volume.state),
196
+ labels: {}
197
+ });
198
+ const snapshotOf = (snapshot) => ({
199
+ snapshotId: snapshot.name,
200
+ name: snapshot.name,
201
+ state: snapshot.state === DaytonaSnapshotState.Active || snapshot.state === DaytonaSnapshotState.Inactive ? "ready" : snapshot.state === DaytonaSnapshotState.Error || snapshot.state === DaytonaSnapshotState.BuildFailed ? "failed" : "pending",
202
+ memory: false,
203
+ sizeBytes: snapshot.sizeGb == null ? null : Math.round(snapshot.sizeGb * 1024 ** 3),
204
+ labels: {},
205
+ createdAt: snapshot.createdAt,
206
+ expiresAt: null
137
207
  });
138
208
  const entryOf = (entry, directory) => ({
139
209
  name: entry.name,
@@ -166,6 +236,98 @@ const networkOf = (network) => {
166
236
  });
167
237
  };
168
238
  const minutes = (seconds) => Math.max(1, Math.ceil(seconds / 60));
239
+ const lifecycleSettings = (lifecycle, args) => {
240
+ const { idle, max } = lifecycle;
241
+ return {
242
+ autoStopInterval: idle === void 0 ? args.defaultAutoStopMinutes : idle === null ? 0 : minutes(idle.afterS),
243
+ autoDeleteInterval: idle?.action === IdleAction.Delete ? 1 : -1,
244
+ // Daytona's time to live always deletes.
245
+ ttlMinutes: max == null ? args.replace ? 0 : void 0 : minutes(max.afterS)
246
+ };
247
+ };
248
+ const lifecycleRefusal = (lifecycle) => {
249
+ if (lifecycle.autoResume === true)
250
+ return "Daytona does not start a stopped sandbox when it is used";
251
+ if (lifecycle.max?.action === MaxAction.Stop)
252
+ return "Daytona deletes a sandbox at its time to live; it cannot stop it instead";
253
+ return null;
254
+ };
255
+ const policyOf = (sandbox) => {
256
+ const cidrs = (sandbox.networkAllowList ?? "").split(",").filter((entry) => entry !== "");
257
+ const domains = (sandbox.domainAllowList ?? "").split(",").filter((entry) => entry !== "");
258
+ if (sandbox.networkBlockAll === true) return { egress: EgressMode.DenyAll };
259
+ if (cidrs.length === 0 && domains.length === 0) return { egress: EgressMode.AllowAll };
260
+ return {
261
+ egress: {
262
+ ...domains.length > 0 ? { allowDomains: domains } : {},
263
+ ...cidrs.length > 0 ? { allowCidrs: cidrs } : {}
264
+ }
265
+ };
266
+ };
267
+ const ACTION_STATES = {
268
+ create: SandboxState.Running,
269
+ start: SandboxState.Running,
270
+ stop: SandboxState.Stopped,
271
+ archive: SandboxState.Stopped,
272
+ pause: SandboxState.Paused,
273
+ delete: SandboxState.Deleted
274
+ };
275
+ const desktopStateOf = (status) => {
276
+ if (status === "active") return DesktopState.Running;
277
+ if (status === "partial") return DesktopState.Starting;
278
+ return DesktopState.Stopped;
279
+ };
280
+ const scrolls = (dx, dy) => [
281
+ ...dy === 0 ? [] : [{ direction: dy > 0 ? "down" : "up", amount: Math.max(1, Math.round(Math.abs(dy))) }],
282
+ ...dx === 0 ? [] : [{ direction: dx > 0 ? "right" : "left", amount: Math.max(1, Math.round(Math.abs(dx))) }]
283
+ ];
284
+ const portsPublic = (ports) => {
285
+ if (ports.every((port) => port.public)) return ports.length > 0;
286
+ return ports.some((port) => port.public) ? null : false;
287
+ };
288
+ const DEFAULT_CONNECT_TTL_S = 3600;
289
+ const LABEL_INDEX_WAIT_MS = 6e4;
290
+ const NOVNC_PORT = 6080;
291
+ const actionCalls = (action) => {
292
+ switch (action.type) {
293
+ case "click":
294
+ return [
295
+ [
296
+ "mouse/click",
297
+ {
298
+ x: action.x,
299
+ y: action.y,
300
+ button: action.button ?? "left",
301
+ double: action.double === true
302
+ }
303
+ ]
304
+ ];
305
+ case "move":
306
+ return [["mouse/move", { x: action.x, y: action.y }]];
307
+ case "drag": {
308
+ const first = action.path[0];
309
+ const last = action.path.at(-1);
310
+ if (first == null || last == null) return [];
311
+ return [
312
+ ["mouse/move", first],
313
+ ["mouse/down", { ...first, button: "left" }],
314
+ ...action.path.slice(1).map((point) => ["mouse/move", point]),
315
+ ["mouse/up", { ...last, button: "left" }]
316
+ ];
317
+ }
318
+ case "type":
319
+ return [["keyboard/type", { text: action.text }]];
320
+ case "key": {
321
+ const key = action.keys.at(-1);
322
+ return key == null ? [] : [["keyboard/key", { key, modifiers: action.keys.slice(0, -1) }]];
323
+ }
324
+ case "scroll":
325
+ return scrolls(action.dx, action.dy).map((step) => [
326
+ "mouse/scroll",
327
+ { x: action.x, y: action.y, ...step }
328
+ ]);
329
+ }
330
+ };
169
331
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
170
332
  const snapshotName = (value) => value.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 100);
171
333
  const daytona = (credentials, options = {}) => {
@@ -178,6 +340,7 @@ const daytona = (credentials, options = {}) => {
178
340
  });
179
341
  const defaultImage = options.defaultImage ?? DEFAULT_DAYTONA_IMAGE;
180
342
  const operationTimeoutMs = options.operationTimeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
343
+ const defaultAutoStopMinutes = Math.max(0, Math.round(options.defaultAutoStopMinutes ?? 0));
181
344
  const limits = daytonaLimits;
182
345
  const processes = createProcessRegistry();
183
346
  const processControls = /* @__PURE__ */ new Map();
@@ -214,6 +377,12 @@ const daytona = (credentials, options = {}) => {
214
377
  if (sandbox == null || GONE.has(sandbox.state))
215
378
  return fail(SandboxRouterErrorCode.NotFound, `the ${PROVIDER} sandbox is gone`);
216
379
  if (done(sandbox)) return ok(sandbox);
380
+ if (sandbox.queueTimedOutAt != null)
381
+ return fail(
382
+ SandboxRouterErrorCode.NoCapacity,
383
+ `no ${PROVIDER} runner took the sandbox in time`,
384
+ { retryable: true, nativeError: sandbox.errorReason ?? sandbox.nativeState }
385
+ );
217
386
  if (FAILED.has(sandbox.state))
218
387
  return fail(
219
388
  SandboxRouterErrorCode.ProviderError,
@@ -244,9 +413,10 @@ const daytona = (credentials, options = {}) => {
244
413
  SandboxRouterErrorCode.UnsupportedByProvider,
245
414
  "private registry bases need their credential resolved first"
246
415
  );
247
- if (!built) return ok(baseDockerfile(image.base, defaultImage));
248
416
  try {
249
- return ok(specDockerfile(image, defaultImage));
417
+ return ok(
418
+ built ? specDockerfile(image, defaultImage) : baseDockerfile(image.base, defaultImage)
419
+ );
250
420
  } catch (cause) {
251
421
  return fail(
252
422
  SandboxRouterErrorCode.InvalidRequest,
@@ -278,11 +448,30 @@ const daytona = (credentials, options = {}) => {
278
448
  const base = fitWithinLimits({ limits, spec });
279
449
  if (spec.gpu != null)
280
450
  base.rejected.push({ field: "gpu", reason: "GPU sandboxes are not offered here" });
281
- if (spec.atEnd === AtEnd.Pause && spec.timeouts.maxS != null)
451
+ if (spec.lifecycle.autoResume)
452
+ base.rejected.push({
453
+ field: "lifecycle.autoResume",
454
+ reason: "Daytona does not start a stopped sandbox when it is used"
455
+ });
456
+ if (spec.lifecycle.max?.action === MaxAction.Stop)
282
457
  base.rejected.push({
283
- field: "timeouts.maxS",
458
+ field: "lifecycle.max",
284
459
  reason: "Daytona deletes a sandbox at its time to live; it cannot stop it instead"
285
460
  });
461
+ if (spec.volumes.some((mount) => mount.readOnly))
462
+ base.rejected.push({ field: "volumes", reason: "Daytona mounts volumes read-write" });
463
+ if (spec.cpuLimit != null && spec.cpuLimit > spec.cpu)
464
+ base.rejected.push({ field: "cpuLimit", reason: "Daytona sandboxes have a fixed size" });
465
+ if (spec.memoryLimitMib != null && spec.memoryLimitMib > spec.memoryMib)
466
+ base.rejected.push({
467
+ field: "memoryLimitMib",
468
+ reason: "Daytona sandboxes have a fixed size"
469
+ });
470
+ if (portsPublic(spec.ports) == null)
471
+ base.rejected.push({
472
+ field: "ports",
473
+ reason: "Daytona makes every port public or none"
474
+ });
286
475
  const network = networkOf(spec.network);
287
476
  if (!network.ok) base.rejected.push({ field: "network", reason: network.error.message });
288
477
  return base;
@@ -318,13 +507,27 @@ const daytona = (credentials, options = {}) => {
318
507
  return {
319
508
  write: async (data) => args.stdinOpen ? result(await process.write(data)) : fail(SandboxRouterErrorCode.InvalidRequest, "the process was started without stdin"),
320
509
  closeStdin: async () => result(await process.closeStdin()),
321
- // Daytona ends a process by deleting its session, whatever the signal.
322
- kill: async () => {
510
+ kill: async (signal) => {
511
+ const refusal = signalRefusal(signal);
512
+ if (refusal != null) return refusal;
323
513
  killed = true;
324
514
  return result(await process.kill());
325
515
  }
326
516
  };
327
517
  };
518
+ const desktopStatus = async (toolbox) => {
519
+ const status = await toolbox.computerUseStatus();
520
+ if (!status.ok) return errorOf(status);
521
+ const state = desktopStateOf(status.data);
522
+ const size = state === DesktopState.Running ? await toolbox.displaySize() : null;
523
+ return ok({
524
+ state,
525
+ width: size?.ok === true ? size.data?.width ?? null : null,
526
+ height: size?.ok === true ? size.data?.height ?? null : null,
527
+ error: null,
528
+ version: null
529
+ });
530
+ };
328
531
  return defineProvider({
329
532
  specificationVersion: SPECIFICATION_VERSION,
330
533
  name: PROVIDER,
@@ -338,24 +541,62 @@ const daytona = (credentials, options = {}) => {
338
541
  if (!parsed.success) return fail(SandboxRouterErrorCode.InvalidRequest, parsed.error.message);
339
542
  const network = networkOf(spec.network);
340
543
  if (!network.ok) return network;
544
+ const refusal = lifecycleRefusal(spec.lifecycle);
545
+ if (refusal != null) return fail(SandboxRouterErrorCode.UnsupportedByProvider, refusal);
546
+ if (spec.volumes.some((mount) => mount.readOnly))
547
+ return fail(
548
+ SandboxRouterErrorCode.UnsupportedByProvider,
549
+ "Daytona mounts volumes read-write"
550
+ );
551
+ const isPublic = portsPublic(spec.ports);
552
+ if (isPublic == null)
553
+ return fail(
554
+ SandboxRouterErrorCode.UnsupportedByProvider,
555
+ "Daytona makes every port public or none"
556
+ );
341
557
  const granted = fit(spec).granted;
558
+ const settings = lifecycleSettings(spec.lifecycle, {
559
+ defaultAutoStopMinutes,
560
+ replace: false
561
+ });
342
562
  const body = {
343
563
  name: context.name,
344
564
  labels: context.labels,
345
565
  env: { ...spec.image?.env, ...spec.env },
346
566
  target: spec.region ?? context.region ?? options.target,
347
567
  user: spec.image?.user,
568
+ public: isPublic,
569
+ volumes: spec.volumes.map((mount) => ({ volumeId: mount.volumeId, mountPath: mount.path })),
348
570
  ...network.value,
349
571
  autoArchiveInterval: parsed.data.autoArchiveMinutes
350
572
  };
351
- if (spec.timeouts.idleS != null) {
352
- body.autoStopInterval = minutes(spec.timeouts.idleS);
353
- if (spec.atEnd === AtEnd.Delete) body.autoDeleteInterval = 0;
354
- }
355
- if (spec.timeouts.maxS != null) body.ttlMinutes = minutes(spec.timeouts.maxS);
573
+ body.autoStopInterval = settings.autoStopInterval;
574
+ body.autoDeleteInterval = settings.autoDeleteInterval;
575
+ if (settings.ttlMinutes != null) body.ttlMinutes = settings.ttlMinutes;
356
576
  const snapshot = context.snapshotId ?? (context.artifact?.kind === "snapshot" ? context.artifact.id : null) ?? parsed.data.snapshot;
357
- if (snapshot != null) body.snapshot = snapshot;
358
- else {
577
+ if (snapshot != null) {
578
+ const found = await client.getSnapshot(snapshot);
579
+ if (found.ok && found.data?.state === DaytonaSnapshotState.Inactive) {
580
+ const activated = await client.activateSnapshot(found.data.id);
581
+ if (!activated.ok) return errorOf(activated);
582
+ const deadline = Date.now() + operationTimeoutMs;
583
+ for (; ; ) {
584
+ const again = await client.getSnapshot(snapshot);
585
+ if (!again.ok) return errorOf(again);
586
+ if (again.data == null || again.data.state === DaytonaSnapshotState.Active) break;
587
+ if (Date.now() > deadline)
588
+ return fail(
589
+ SandboxRouterErrorCode.Timeout,
590
+ `the ${PROVIDER} snapshot did not activate`,
591
+ {
592
+ retryable: true
593
+ }
594
+ );
595
+ await sleep(POLL_MS);
596
+ }
597
+ }
598
+ body.snapshot = snapshot;
599
+ } else {
359
600
  const dockerfile = dockerfileFor(spec, context.artifact != null);
360
601
  if (!dockerfile.ok) return dockerfile;
361
602
  if (context.artifact != null && context.artifact.id !== `${ARTIFACT_PREFIX}${await sha256Hex(dockerfile.value)}`)
@@ -450,22 +691,96 @@ const daytona = (credentials, options = {}) => {
450
691
  const waited = await waitFor(id, started, "start");
451
692
  return waited.ok ? ok(void 0) : waited;
452
693
  },
453
- setTimeout: async (id, timeouts) => {
454
- if (timeouts.idleS != null) {
455
- const set = await client.setAutoStop(id, minutes(timeouts.idleS));
456
- if (!set.ok) return errorOf(set);
457
- }
458
- if (timeouts.maxS != null) {
459
- const set = await client.setTtl(id, minutes(timeouts.maxS));
460
- if (!set.ok) return errorOf(set);
461
- }
462
- return ok(void 0);
694
+ setLifecycle: async (id, lifecycle) => {
695
+ const refusal = lifecycleRefusal(lifecycle);
696
+ if (refusal != null) return fail(SandboxRouterErrorCode.UnsupportedByProvider, refusal);
697
+ const settings = lifecycleSettings(lifecycle, { defaultAutoStopMinutes, replace: true });
698
+ const stop = await client.setAutoStop(id, settings.autoStopInterval);
699
+ if (!stop.ok) return errorOf(stop);
700
+ const remove = await client.setAutoDelete(id, settings.autoDeleteInterval);
701
+ if (!remove.ok) return errorOf(remove);
702
+ if (lifecycle.max == null) return result(await client.setTtl(id, 0));
703
+ const found = await client.getSandbox(id);
704
+ if (!found.ok) return errorOf(found);
705
+ const createdAt = found.data?.createdAt == null ? null : Date.parse(found.data.createdAt);
706
+ const ageS = createdAt == null ? 0 : Math.max(0, (Date.now() - createdAt) / 1e3);
707
+ return result(await client.setTtl(id, minutes(lifecycle.max.afterS - ageS)));
463
708
  },
464
- setNetwork: async (id, network) => {
709
+ // Daytona does not version network policies, so a revision cannot be checked.
710
+ setNetwork: async (id, network, networkOptions = {}) => {
711
+ if (networkOptions.expectedRevision != null)
712
+ return fail(
713
+ SandboxRouterErrorCode.UnsupportedByProvider,
714
+ "Daytona does not version network policies"
715
+ );
465
716
  const settings = networkOf(network);
466
717
  if (!settings.ok) return settings;
467
718
  return result(await client.updateNetworkSettings(id, settings.value));
468
719
  },
720
+ getNetwork: async (id) => {
721
+ const found = await client.getSandbox(id);
722
+ if (!found.ok) return errorOf(found);
723
+ if (found.data == null || GONE.has(found.data.state))
724
+ return fail(SandboxRouterErrorCode.NotFound, `${PROVIDER} has no sandbox ${id}`);
725
+ return ok({ network: policyOf(found.data), revision: null });
726
+ },
727
+ // Daytona's label index catches up after a change, query by query; this resolves once
728
+ // listing by each new label finds the sandbox (or after LABEL_INDEX_WAIT_MS, the labels being
729
+ // set either way).
730
+ setLabels: async (id, labels) => {
731
+ const replaced = await client.replaceLabels(id, labels);
732
+ if (!replaced.ok) return errorOf(replaced);
733
+ const sandboxId = replaced.data;
734
+ const deadline = Date.now() + LABEL_INDEX_WAIT_MS;
735
+ let pending = Object.entries(labels);
736
+ while (pending.length > 0 && Date.now() < deadline) {
737
+ const found = await Promise.all(
738
+ pending.map(async ([key, value]) => {
739
+ const listed = await client.listSandboxes({ [key]: value });
740
+ return listed.ok && listed.data.some((sandbox) => sandbox.id === sandboxId);
741
+ })
742
+ );
743
+ pending = pending.filter((_, index) => !found[index]);
744
+ if (pending.length > 0) await sleep(POLL_MS * 2);
745
+ }
746
+ return ok(void 0);
747
+ },
748
+ // The API actions taken on the sandbox, from the organization's audit log; Daytona's own
749
+ // transitions (an idle stop, say) are not in it.
750
+ events: {
751
+ list: async (id, { before, limit = 50 }) => {
752
+ const found = await client.getSandbox(id);
753
+ if (!found.ok) return errorOf(found);
754
+ const organizationId = found.data?.organizationId;
755
+ if (found.data == null || organizationId == null)
756
+ return fail(SandboxRouterErrorCode.NotFound, `${PROVIDER} has no sandbox ${id}`);
757
+ const listed = await client.auditEvents({
758
+ organizationId,
759
+ sandboxId: found.data.id,
760
+ before,
761
+ limit
762
+ });
763
+ if (!listed.ok) return errorOf(listed);
764
+ const events = listed.data.map(
765
+ (event) => ({
766
+ id: event.id,
767
+ type: event.action,
768
+ state: event.statusCode != null && event.statusCode < 300 ? ACTION_STATES[event.action] ?? null : null,
769
+ generation: null,
770
+ at: event.createdAt,
771
+ details: {
772
+ ...event.statusCode == null ? {} : { statusCode: String(event.statusCode) },
773
+ ...event.errorMessage == null ? {} : { error: event.errorMessage }
774
+ }
775
+ })
776
+ );
777
+ return ok({
778
+ events,
779
+ nextBefore: events.length < limit ? null : events.at(-1)?.at ?? null
780
+ });
781
+ }
782
+ },
783
+ // Daytona never starts a stopped sandbox for a command, so `autoResume: false` always holds.
469
784
  exec: async (id, command, execOptions) => {
470
785
  const toolbox = await toolboxFor(id);
471
786
  if (!toolbox.ok) return toolbox;
@@ -475,7 +790,7 @@ const daytona = (credentials, options = {}) => {
475
790
  if (!dir.ok) return dir;
476
791
  cwd = dir.value;
477
792
  }
478
- const line = execOptions.user == null ? command : `sudo -E -H -u ${shellQuote(execOptions.user)} -- bash -lc ${shellQuote(command)}`;
793
+ const line = execOptions.user == null ? command : asUser(execOptions.user, command);
479
794
  const stdinOpen = execOptions.stdin === true;
480
795
  const spawned = await toolbox.value.spawn({
481
796
  command: line,
@@ -554,7 +869,9 @@ const daytona = (credentials, options = {}) => {
554
869
  return ok(void 0);
555
870
  },
556
871
  closeStdin: async () => ok(void 0),
557
- kill: async () => {
872
+ kill: async (signal) => {
873
+ const refusal = signalRefusal(signal);
874
+ if (refusal != null) return refusal;
558
875
  killed = true;
559
876
  const deleted = await toolbox.value.deletePty(ptyId);
560
877
  terminal.close();
@@ -614,8 +931,29 @@ const daytona = (credentials, options = {}) => {
614
931
  const made = await toolbox.value.createFolder({ path: parent });
615
932
  if (!made.ok) return errorOf(made);
616
933
  }
617
- const uploaded = await toolbox.value.upload({ path, content: bytes });
618
- if (!uploaded.ok) return errorOf(uploaded);
934
+ if (writeOptions.append === true) {
935
+ const appended = await toolbox.value.spawn({
936
+ command: `cat >> ${shellQuote(path)}`,
937
+ args: [],
938
+ shell: true,
939
+ cwd: "/",
940
+ env: {},
941
+ stdin: true
942
+ });
943
+ if (!appended.ok) return errorOf(appended);
944
+ const written = await appended.data.write(bytes);
945
+ const closed = written.ok ? await appended.data.closeStdin() : written;
946
+ const exit = await appended.data.wait();
947
+ if (!closed.ok) return errorOf(closed);
948
+ if (!exit.ok) return errorOf(exit);
949
+ if (exit.data.exitCode !== 0)
950
+ return fail(SandboxRouterErrorCode.ProviderError, `appending to ${path} failed`, {
951
+ nativeError: `exit ${exit.data.exitCode}`
952
+ });
953
+ } else {
954
+ const uploaded = await toolbox.value.upload({ path, content: bytes });
955
+ if (!uploaded.ok) return errorOf(uploaded);
956
+ }
619
957
  if (writeOptions.mode == null) return ok(void 0);
620
958
  return result(await toolbox.value.setMode({ path, mode: writeOptions.mode }));
621
959
  },
@@ -651,15 +989,169 @@ const daytona = (credentials, options = {}) => {
651
989
  }
652
990
  },
653
991
  ports: {
654
- url: async (id, port) => {
655
- const ttlS = options.portUrlTtlS ?? 3600;
992
+ // Ports something listens on; Daytona previews any of them, all public or all private.
993
+ list: async (id) => {
994
+ const found = await client.getSandbox(id);
995
+ if (!found.ok) return errorOf(found);
996
+ if (found.data == null || GONE.has(found.data.state))
997
+ return fail(SandboxRouterErrorCode.NotFound, `${PROVIDER} has no sandbox ${id}`);
998
+ const isPublic = found.data.public;
999
+ const toolbox = await toolboxFor(id);
1000
+ if (!toolbox.ok) return toolbox;
1001
+ const open = await toolbox.value.openPorts();
1002
+ if (!open.ok) return errorOf(open);
1003
+ return ok(open.data.map((port) => ({ port, public: isPublic })));
1004
+ },
1005
+ url: async (id, port, urlOptions = {}) => {
1006
+ const found = await client.getSandbox(id);
1007
+ if (!found.ok) return errorOf(found);
1008
+ if (found.data == null || GONE.has(found.data.state))
1009
+ return fail(SandboxRouterErrorCode.NotFound, `${PROVIDER} has no sandbox ${id}`);
1010
+ if (found.data.public) {
1011
+ const preview = await client.previewUrl(id, port);
1012
+ if (!preview.ok) return errorOf(preview);
1013
+ return ok({ url: preview.data.url, auth: PortAuth.Public, token: null, expiresAt: null });
1014
+ }
1015
+ const ttlS = urlOptions.ttlS ?? options.portUrlTtlS ?? 3600;
656
1016
  const expiresAt = new Date(Date.now() + ttlS * 1e3).toISOString();
657
1017
  const signed = await client.signedPreviewUrl(id, port, ttlS);
658
1018
  if (!signed.ok) return errorOf(signed);
659
- return ok({ url: signed.data, auth: PortAuth.Url, token: null, expiresAt });
1019
+ return ok({ url: signed.data.url, auth: PortAuth.Url, token: null, expiresAt });
660
1020
  }
661
1021
  },
662
- snapshot: async (id, { name }) => {
1022
+ desktop: {
1023
+ start: async (id) => {
1024
+ const toolbox = await toolboxFor(id);
1025
+ if (!toolbox.ok) return toolbox;
1026
+ const startedNow = await toolbox.value.computerUse("start");
1027
+ if (!startedNow.ok) return errorOf(startedNow);
1028
+ const deadline = Date.now() + 6e4;
1029
+ for (; ; ) {
1030
+ const status = await desktopStatus(toolbox.value);
1031
+ if (!status.ok || status.value.state === DesktopState.Running) return status;
1032
+ if (Date.now() > deadline)
1033
+ return fail(SandboxRouterErrorCode.Timeout, "the desktop did not start in time", {
1034
+ retryable: true
1035
+ });
1036
+ await sleep(POLL_MS);
1037
+ }
1038
+ },
1039
+ stop: async (id) => {
1040
+ const toolbox = await toolboxFor(id);
1041
+ if (!toolbox.ok) return toolbox;
1042
+ return result(await toolbox.value.computerUse("stop"));
1043
+ },
1044
+ status: async (id) => {
1045
+ const toolbox = await toolboxFor(id);
1046
+ if (!toolbox.ok) return toolbox;
1047
+ return desktopStatus(toolbox.value);
1048
+ },
1049
+ // noVNC in the browser, behind a signed preview URL. Its view-only switch is a client
1050
+ // setting the URL's holder could drop, so view-only sessions are not offered.
1051
+ screen: async (id, screenOptions = {}) => {
1052
+ if (screenOptions.viewOnly === true)
1053
+ return fail(
1054
+ SandboxRouterErrorCode.UnsupportedByProvider,
1055
+ "Daytona cannot limit a screen session to viewing"
1056
+ );
1057
+ const ttlS = options.portUrlTtlS ?? 3600;
1058
+ const signed = await client.signedPreviewUrl(id, NOVNC_PORT, ttlS);
1059
+ if (!signed.ok) return errorOf(signed);
1060
+ return ok({
1061
+ protocol: "url",
1062
+ url: `${signed.data.url.replace(/\/+$/, "")}/vnc.html?autoconnect=true&resize=scale`,
1063
+ token: null,
1064
+ expiresAt: new Date(Date.now() + ttlS * 1e3).toISOString(),
1065
+ details: {}
1066
+ });
1067
+ }
1068
+ },
1069
+ computerUse: {
1070
+ screenshot: async (id) => {
1071
+ const toolbox = await toolboxFor(id);
1072
+ if (!toolbox.ok) return toolbox;
1073
+ return result(await toolbox.value.screenshot());
1074
+ },
1075
+ act: async (id, action) => {
1076
+ const toolbox = await toolboxFor(id);
1077
+ if (!toolbox.ok) return toolbox;
1078
+ for (const [path, body] of actionCalls(action)) {
1079
+ const done = await toolbox.value.computerUse(path, body);
1080
+ if (!done.ok) return errorOf(done);
1081
+ }
1082
+ return ok(void 0);
1083
+ }
1084
+ },
1085
+ // Daytona never starts a stopped sandbox to list its processes.
1086
+ processes: {
1087
+ list: async (id) => {
1088
+ const toolbox = await toolboxFor(id);
1089
+ if (!toolbox.ok) return toolbox;
1090
+ const listed = await toolbox.value.listProcesses();
1091
+ if (!listed.ok) return errorOf(listed);
1092
+ return ok(
1093
+ listed.data.map((process) => ({
1094
+ processId: process.ref,
1095
+ command: process.command,
1096
+ args: null,
1097
+ cwd: process.cwd,
1098
+ user: process.user,
1099
+ pid: null,
1100
+ running: process.running,
1101
+ exitCode: process.exitCode,
1102
+ startedAt: process.startedAt,
1103
+ endedAt: null
1104
+ }))
1105
+ );
1106
+ }
1107
+ },
1108
+ // An SSH login (which reaches commands, files and ports) for `exec`; a signed preview URL
1109
+ // for one port alone. File-only scopes have no narrower Daytona credential.
1110
+ connect: async (id, connectOptions = {}) => {
1111
+ const ttlS = connectOptions.ttlS ?? options.connectTtlS ?? DEFAULT_CONNECT_TTL_S;
1112
+ const scopes = connectOptions.scopes;
1113
+ const portScopes = (scopes ?? []).flatMap(
1114
+ (scope) => scope.startsWith("ports:") ? [Number(scope.slice("ports:".length))] : []
1115
+ );
1116
+ if (scopes != null && !scopes.includes("exec")) {
1117
+ const port = portScopes[0];
1118
+ if (port == null || scopes.length !== 1)
1119
+ return fail(
1120
+ SandboxRouterErrorCode.UnsupportedByProvider,
1121
+ `Daytona has no credential limited to ${scopes.join(", ")}`
1122
+ );
1123
+ const signed = await client.signedPreviewUrl(id, port, ttlS);
1124
+ if (!signed.ok) return errorOf(signed);
1125
+ return ok({
1126
+ provider: PROVIDER,
1127
+ providerSandboxId: id,
1128
+ kind: "signed_preview_url",
1129
+ token: signed.data.token,
1130
+ url: signed.data.url,
1131
+ expiresAt: new Date(Date.now() + ttlS * 1e3).toISOString(),
1132
+ details: { port: String(port) }
1133
+ });
1134
+ }
1135
+ const access = await client.createSshAccess(id, ttlS / 60);
1136
+ if (!access.ok) return errorOf(access);
1137
+ return ok({
1138
+ provider: PROVIDER,
1139
+ providerSandboxId: id,
1140
+ kind: "ssh_access",
1141
+ token: access.data.token,
1142
+ url: null,
1143
+ expiresAt: access.data.expiresAt,
1144
+ details: { sshCommand: access.data.sshCommand }
1145
+ });
1146
+ },
1147
+ // Daytona keeps a snapshot until it is deleted, so every snapshot is retained; one left
1148
+ // unused is deactivated and create activates it again.
1149
+ snapshot: async (id, { name, labels }) => {
1150
+ if (labels != null && Object.keys(labels).length > 0)
1151
+ return fail(
1152
+ SandboxRouterErrorCode.UnsupportedByProvider,
1153
+ "Daytona snapshots carry no labels"
1154
+ );
663
1155
  const snapshotId = snapshotName(`${name}-${crypto.randomUUID().slice(0, 8)}`);
664
1156
  const taken = await client.snapshotSandbox(id, snapshotId);
665
1157
  if (!taken.ok) return errorOf(taken);
@@ -680,6 +1172,83 @@ const daytona = (credentials, options = {}) => {
680
1172
  await sleep(POLL_MS);
681
1173
  }
682
1174
  },
1175
+ // Daytona snapshots carry no labels: listing takes none and returns every snapshot taken
1176
+ // from a sandbox.
1177
+ snapshots: {
1178
+ get: async (snapshotId) => {
1179
+ const found = await client.getSnapshot(snapshotId);
1180
+ if (!found.ok) return errorOf(found);
1181
+ return ok(found.data == null ? null : snapshotOf(found.data));
1182
+ },
1183
+ list: async ({ labels }) => {
1184
+ if (Object.keys(labels).length > 0)
1185
+ return fail(
1186
+ SandboxRouterErrorCode.UnsupportedByProvider,
1187
+ "Daytona snapshots carry no labels"
1188
+ );
1189
+ const listed = await client.listSnapshots();
1190
+ if (!listed.ok) return errorOf(listed);
1191
+ return ok(
1192
+ listed.data.filter((snapshot) => snapshot.sourceSandboxId != null).map(snapshotOf)
1193
+ );
1194
+ }
1195
+ },
1196
+ // Volumes keep no labels, size or expiry here; writes reach the volume as they happen.
1197
+ volumes: {
1198
+ create: async ({ name }) => {
1199
+ const made = await client.createVolume(name);
1200
+ if (!made.ok) return errorOf(made);
1201
+ const deadline = Date.now() + operationTimeoutMs;
1202
+ for (; ; ) {
1203
+ const found = await client.getVolume(made.data.id);
1204
+ if (!found.ok) return errorOf(found);
1205
+ if (found.data == null)
1206
+ return fail(SandboxRouterErrorCode.NotFound, "the Daytona volume is gone");
1207
+ if (found.data.state === DaytonaVolumeState.Ready) return ok(volumeOf(found.data));
1208
+ if (found.data.state === DaytonaVolumeState.Error)
1209
+ return fail(SandboxRouterErrorCode.ProviderError, "the Daytona volume failed", {
1210
+ nativeError: found.data.errorReason ?? found.data.nativeState
1211
+ });
1212
+ if (Date.now() > deadline)
1213
+ return fail(SandboxRouterErrorCode.Timeout, "the Daytona volume took too long", {
1214
+ retryable: true
1215
+ });
1216
+ await sleep(POLL_MS);
1217
+ }
1218
+ },
1219
+ get: async (volumeId) => {
1220
+ const found = await client.getVolume(volumeId);
1221
+ if (!found.ok) return errorOf(found);
1222
+ return ok(found.data == null ? null : volumeOf(found.data));
1223
+ },
1224
+ list: async ({ labels, name }) => {
1225
+ if (Object.keys(labels).length > 0)
1226
+ return fail(
1227
+ SandboxRouterErrorCode.UnsupportedByProvider,
1228
+ "Daytona volumes carry no labels"
1229
+ );
1230
+ if (name != null) {
1231
+ const found = await client.getVolumeByName(name);
1232
+ if (!found.ok) return errorOf(found);
1233
+ return ok(found.data == null ? [] : [volumeOf(found.data)]);
1234
+ }
1235
+ const listed = await client.listVolumes();
1236
+ if (!listed.ok) return errorOf(listed);
1237
+ return ok(listed.data.map(volumeOf));
1238
+ },
1239
+ // Daytona refuses to delete a volume a sandbox still mounts, even one being deleted: wait
1240
+ // for the sandbox to go.
1241
+ delete: async (volumeId) => {
1242
+ const deadline = Date.now() + operationTimeoutMs;
1243
+ for (; ; ) {
1244
+ const deleted = await client.deleteVolume(volumeId);
1245
+ if (deleted.ok) return ok(void 0);
1246
+ if (deleted.error !== DaytonaErrorCode.Conflict && deleted.error !== DaytonaErrorCode.BadRequest || Date.now() > deadline)
1247
+ return errorOf(deleted);
1248
+ await sleep(POLL_MS * 4);
1249
+ }
1250
+ }
1251
+ },
683
1252
  deleteSnapshot: async (snapshotId) => {
684
1253
  const snapshot = await client.getSnapshot(snapshotId);
685
1254
  if (!snapshot.ok) return errorOf(snapshot);
@@ -727,8 +1296,9 @@ const BUILD_SPEC = {
727
1296
  env: {},
728
1297
  ports: [],
729
1298
  network: { egress: EgressMode.AllowAll },
730
- timeouts: {},
731
- atEnd: AtEnd.Delete,
1299
+ lifecycle: { autoResume: false },
1300
+ volumes: [],
1301
+ telemetry: {},
732
1302
  labels: {}
733
1303
  };
734
1304
  export {