@capsulos/provider-daytona 0.0.0-stage → 0.9.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,141 @@
1
+ // Templates on Daytona: one snapshot per template version, named `capsulos-<name>:<version>`.
2
+ //
3
+ // The snapshot keeps the Dockerfile it was built from, and the last line of that Dockerfile says which
4
+ // declaration it is (name, version and the lock's digest). Daytona builds from a Dockerfile and a context
5
+ // that travels as one tar to the object storage Daytona lends for that (its key is the tar's hash, so the
6
+ // same context is uploaded once).
7
+ //
8
+ // The upload is the caller's: the CLI does it with the short-lived credentials Daytona lends
9
+ // (GET /object-storage/push-access), capsulos cloud does it inside its vault, so the credentials never
10
+ // leave it. Everything else goes through the provider's fetch.
11
+ import { createHash } from 'node:crypto';
12
+ import { daytonaSnapshot } from './index.js';
13
+ export const daytonaTemplateName = (name) => `capsulos-${name}`;
14
+ const IDENTITY = /capsulos (\S+)@(\d+\.\d+\.\d+) (sha256:[0-9a-f]{64})/;
15
+ /** The line a snapshot's Dockerfile ends with: which template version it is. */
16
+ export const daytonaIdentity = (m) => `LABEL dev.capsulos.identity="capsulos ${m.name}@${m.version} ${m.digest}"`;
17
+ export function parseDaytonaIdentity(dockerfile) {
18
+ const m = IDENTITY.exec((dockerfile ?? '')
19
+ .split('\n')
20
+ .filter((l) => l.startsWith('LABEL dev.capsulos.identity='))
21
+ .at(-1) ?? '');
22
+ return m ? { name: m[1], version: m[2], digest: m[3] } : null;
23
+ }
24
+ /** The versions a list of snapshots describes: the active ones whose Dockerfile says they are this template. */
25
+ export function daytonaVersions(name, snapshots) {
26
+ const out = [];
27
+ for (const s of snapshots) {
28
+ const id = parseDaytonaIdentity(s.buildInfo?.dockerfileContent);
29
+ if (!id || id.name !== name || s.state !== 'active' || s.name !== daytonaSnapshot(daytonaTemplateName(name), id.version))
30
+ continue;
31
+ out.push({
32
+ version: id.version,
33
+ digest: id.digest,
34
+ snapshot: s.name,
35
+ snapshotId: s.id,
36
+ ...(s.createdAt ? { createdAt: s.createdAt } : {}),
37
+ });
38
+ }
39
+ return out;
40
+ }
41
+ /** The snapshots of a template, whatever their state. Daytona's `name` filter matches part of a name: the prefix is checked here. */
42
+ export async function daytonaSnapshots(provider, name) {
43
+ const prefix = `${daytonaTemplateName(name)}:`;
44
+ const out = [];
45
+ for (let page = 1;; page++) {
46
+ const { data } = await provider.api('GET', `/snapshots?name=${encodeURIComponent(daytonaTemplateName(name))}&limit=100&page=${page}`);
47
+ for (const s of data?.items ?? []) {
48
+ if (!s.name.startsWith(prefix))
49
+ continue;
50
+ // A listing may leave the Dockerfile out: the snapshot itself has it.
51
+ out.push(s.buildInfo?.dockerfileContent ? s : ((await provider.api('GET', `/snapshots/${s.id}`, undefined, [404])).data ?? s));
52
+ }
53
+ if (!data?.items?.length || page >= (data.totalPages ?? 1))
54
+ break;
55
+ }
56
+ return out;
57
+ }
58
+ /** The name Daytona gives a context: the md5 of its tar. */
59
+ export const daytonaContextHash = (tar) => createHash('md5').update(tar).digest('hex');
60
+ /** Where a context goes in the object storage Daytona lends. */
61
+ export const daytonaContextKey = (organizationId, hash) => `${organizationId}/${hash}/context.tar`;
62
+ export class DaytonaBuildError extends Error {
63
+ snapshotId;
64
+ constructor(message, snapshotId) {
65
+ super(message);
66
+ this.snapshotId = snapshotId;
67
+ this.name = 'DaytonaBuildError';
68
+ }
69
+ }
70
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
71
+ const t = setTimeout(resolve, ms);
72
+ signal?.addEventListener('abort', () => {
73
+ clearTimeout(t);
74
+ reject(signal.reason ?? new Error('aborted'));
75
+ });
76
+ });
77
+ /**
78
+ * Builds a version of a template as a Daytona snapshot. A snapshot of the same name (a version built again,
79
+ * or one whose build failed) is removed first; a snapshot whose build fails is removed.
80
+ */
81
+ export async function buildDaytonaSnapshot(provider, opts) {
82
+ const log = opts.log ?? (() => undefined);
83
+ const t0 = Date.now();
84
+ const hash = daytonaContextHash(opts.contextTar);
85
+ await opts.upload(opts.contextTar, hash);
86
+ log(`uploaded the build context to Daytona (${opts.contextTar.length} bytes)`);
87
+ const name = daytonaSnapshot(daytonaTemplateName(opts.name), opts.version);
88
+ for (const old of (await daytonaSnapshots(provider, opts.name)).filter((s) => s.name === name)) {
89
+ await provider.api('DELETE', `/snapshots/${old.id}`, undefined, [404]);
90
+ for (let i = 0; i < 60 && (await provider.api('GET', `/snapshots/${old.id}`, undefined, [404])).status !== 404; i++)
91
+ await sleep(opts.pollMs ?? 1_000, opts.signal);
92
+ }
93
+ const dockerfile = `${opts.dockerfile.trimEnd()}\n${daytonaIdentity(opts)}\n`;
94
+ const { data: created } = await provider
95
+ .api('POST', '/snapshots', {
96
+ name,
97
+ cpu: 2,
98
+ memory: Math.max(1, Math.ceil(opts.memoryMiB / 1024)),
99
+ disk: 5,
100
+ buildInfo: { dockerfileContent: dockerfile, contextHashes: [hash] },
101
+ })
102
+ .catch((err) => {
103
+ // A key that only runs sandboxes: say what is missing instead of a bare 403.
104
+ if (err.status !== 403)
105
+ throw err;
106
+ throw new DaytonaBuildError(`${err.message}. Building a template needs an API key with write:snapshots and delete:snapshots (https://app.daytona.io/dashboard/keys)`);
107
+ });
108
+ if (!created?.id)
109
+ throw new DaytonaBuildError(`Daytona took the snapshot ${name} without giving it an id`);
110
+ log(`Daytona builds ${name} (${opts.memoryMiB} MiB)`);
111
+ const fail = async (message) => {
112
+ await provider.api('DELETE', `/snapshots/${created.id}`, undefined, [404]).catch(() => undefined);
113
+ throw new DaytonaBuildError(message, created.id);
114
+ };
115
+ let last = '';
116
+ for (;;) {
117
+ await sleep(opts.pollMs ?? 3_000, opts.signal);
118
+ const snap = (await provider.api('GET', `/snapshots/${created.id}`)).data;
119
+ if (snap && snap.state !== last)
120
+ log(`state=${snap.state} (t+${((Date.now() - t0) / 1000).toFixed(0)}s)`);
121
+ last = snap?.state ?? last;
122
+ if (snap?.state === 'active')
123
+ break;
124
+ if (snap?.state === 'error' || snap?.state === 'build_failed')
125
+ return await fail(`the build of ${opts.name}@${opts.version} failed on Daytona (${snap.state})${snap.errorReason ? `: ${snap.errorReason}` : ''}`);
126
+ if (Date.now() - t0 > (opts.timeoutMs ?? 30 * 60_000))
127
+ return await fail(`the build of ${opts.name}@${opts.version} is still ${last} after ${Math.round((Date.now() - t0) / 60_000)} minutes`);
128
+ }
129
+ return {
130
+ snapshotId: created.id,
131
+ snapshot: name,
132
+ durationMs: Date.now() - t0,
133
+ };
134
+ }
135
+ /** Takes a version back: its snapshot. */
136
+ export async function removeDaytonaVersion(provider, name, version) {
137
+ const snapshot = daytonaSnapshot(daytonaTemplateName(name), version);
138
+ for (const s of (await daytonaSnapshots(provider, name)).filter((x) => x.name === snapshot))
139
+ await provider.api('DELETE', `/snapshots/${s.id}`, undefined, [404]);
140
+ }
141
+ //# sourceMappingURL=templates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,EAAE;AACF,uGAAuG;AACvG,0GAA0G;AAC1G,0GAA0G;AAC1G,kCAAkC;AAClC,EAAE;AACF,6FAA6F;AAC7F,uGAAuG;AACvG,+DAA+D;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAwB,MAAM,YAAY,CAAC;AAEnE,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,YAAY,IAAI,EAAE,CAAC;AACxE,MAAM,QAAQ,GAAG,sDAAsD,CAAC;AACxE,gFAAgF;AAChF,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAoD,EAAE,EAAE,CAAC,yCAAyC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC;AACrK,MAAM,UAAU,oBAAoB,CAAC,UAA8B;IACjE,MAAM,CAAC,GAAG,QAAQ,CAAC,IA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AC;QAAE,MAAM,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;AACpK,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@capsulos/provider-daytona",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.9.0",
4
+ "description": "capsulos provider for Daytona: capsules as Daytona sandboxes, built from the same capsule.yaml.",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "sandbox",
8
+ "ai-agents",
9
+ "aws",
10
+ "lambda",
11
+ "microvm",
12
+ "firecracker",
13
+ "e2b",
14
+ "daytona"
15
+ ],
16
+ "homepage": "https://github.com/tornoai/capsulos#readme",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/tornoai/capsulos.git",
20
+ "directory": "packages/provider-daytona"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/tornoai/capsulos/issues"
24
+ },
25
+ "engines": {
26
+ "node": ">=22"
27
+ },
28
+ "type": "module",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "main": "./dist/index.js",
36
+ "types": "./dist/index.d.ts",
37
+ "sideEffects": false,
38
+ "files": [
39
+ "dist",
40
+ "src"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@capsulos/sdk": "0.9.0"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.20.1",
50
+ "typescript": "^5.9.0",
51
+ "vitest": "^4.1.10"
52
+ },
53
+ "scripts": {
54
+ "typecheck": "tsc --noEmit",
55
+ "build": "tsc -p tsconfig.build.json",
56
+ "test": "vitest run --passWithNoTests"
57
+ }
6
58
  }
@@ -0,0 +1,102 @@
1
+ // The Daytona provider against a stubbed fetch: Daytona does not run the
2
+ // image's command, so the provider starts capsulod through the toolbox and
3
+ // then delivers the boot hook. The service itself is exercised by the
4
+ // conformance suite.
5
+ import { describe, expect, it } from 'vitest';
6
+ import { CapsuleError } from '@capsulos/sdk';
7
+ import { DaytonaProvider, daytonaSnapshot, toState } from './index.js';
8
+
9
+ interface Call {
10
+ method: string;
11
+ url: string;
12
+ headers: Record<string, string>;
13
+ body: unknown;
14
+ }
15
+
16
+ function stub(answer: (call: Call) => { status?: number; body?: unknown } | undefined) {
17
+ const calls: Call[] = [];
18
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
19
+ const call: Call = {
20
+ method: init?.method ?? 'GET',
21
+ url: String(input),
22
+ headers: Object.fromEntries(Object.entries((init?.headers ?? {}) as Record<string, string>).map(([k, v]) => [k.toLowerCase(), v])),
23
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
24
+ };
25
+ calls.push(call);
26
+ const res = answer(call) ?? { status: 404, body: { message: 'not stubbed' } };
27
+ return new Response(res.body === undefined ? null : JSON.stringify(res.body), { status: res.status ?? 200 });
28
+ }) as typeof fetch;
29
+ return { calls, provider: new DaytonaProvider({ apiKey: 'dtn_key', fetch: fetchImpl }) };
30
+ }
31
+
32
+ const API = 'https://app.daytona.io/api';
33
+ const TOOLBOX = 'https://proxy.app.daytona.io/toolbox';
34
+ const preview = (port: number) => ({ url: `https://${port}-sb1.daytonaproxy01.net`, token: `preview-${port}` });
35
+
36
+ function happy(c: Call, states = ['creating', 'started']): { status?: number; body?: unknown } | undefined {
37
+ if (c.method === 'POST' && c.url === `${API}/sandbox`) return { body: { id: 'sb1', state: states[0], toolboxProxyUrl: TOOLBOX } };
38
+ if (c.method === 'GET' && c.url === `${API}/sandbox/sb1`) return { body: { id: 'sb1', state: states.at(-1), toolboxProxyUrl: TOOLBOX } };
39
+ if (c.url === `${TOOLBOX}/sb1/process/session`) return { body: {} };
40
+ if (c.url === `${TOOLBOX}/sb1/process/session/capsulod/exec`) return { body: { cmdId: 'c1' } };
41
+ const m = /\/sandbox\/sb1\/ports\/(\d+)\/preview-url$/.exec(c.url);
42
+ if (m) return { body: preview(Number(m[1])) };
43
+ if (c.url.startsWith('https://9000-sb1.daytonaproxy01.net/')) return { body: { ok: true } };
44
+ if (c.method === 'DELETE') return { status: 200, body: {} };
45
+ return undefined;
46
+ }
47
+
48
+ describe('DaytonaProvider.create', () => {
49
+ it('starts capsulod through the toolbox and delivers the token in the boot hook', async () => {
50
+ const { calls, provider } = stub((c) => happy(c));
51
+ const handle = await provider.create({ template: 'capsulos-base', templateVersion: '2.0.0', token: 'capsule-token-0123456789', maxDurationSeconds: 90 });
52
+ expect(handle).toMatchObject({ id: 'sb1', provider: 'daytona', state: 'running', endpoint: 'https://8080-sb1.daytonaproxy01.net', maxDurationSeconds: 90 });
53
+
54
+ const create = calls[0]!;
55
+ expect(create.headers.authorization).toBe('Bearer dtn_key');
56
+ expect(create.body).toMatchObject({ snapshot: 'capsulos-base:2.0.0', public: false, autoStopInterval: 0, ttlMinutes: 2, labels: { capsulos: '1', 'capsulos-template': 'capsulos-base' } });
57
+
58
+ const exec = calls.find((c) => c.url.endsWith('/process/session/capsulod/exec'))!;
59
+ expect(exec.body).toMatchObject({ runAsync: true });
60
+ // The token never travels in a command line or in what Daytona stores of the sandbox.
61
+ expect(JSON.stringify([create.body, exec.body])).not.toContain('capsule-token');
62
+
63
+ const hook = calls.find((c) => c.url.endsWith('/run'))!;
64
+ expect(hook.headers['x-daytona-preview-token']).toBe('preview-9000');
65
+ expect(JSON.parse((hook.body as { runHookPayload: string }).runHookPayload).token).toBe('capsule-token-0123456789');
66
+ expect(calls.indexOf(exec)).toBeLessThan(calls.indexOf(hook));
67
+ expect(await handle.connection.headers()).toEqual({ 'X-Daytona-Preview-Token': 'preview-8080', 'X-Daytona-Skip-Preview-Warning': 'true' });
68
+ });
69
+
70
+ it('deletes a sandbox that Daytona could not start, and names it', async () => {
71
+ const { calls, provider } = stub((c) => happy(c, ['creating', 'error']));
72
+ const err = await provider.create({ template: 't', token: 'capsule-token-0123456789' }).catch((e: unknown) => e);
73
+ expect(err).toBeInstanceOf(CapsuleError);
74
+ expect((err as CapsuleError).capsuleId).toBe('sb1');
75
+ expect(calls.some((c) => c.method === 'DELETE' && c.url === `${API}/sandbox/sb1`)).toBe(true);
76
+ expect(calls.some((c) => c.url.includes('/process/'))).toBe(false);
77
+ });
78
+
79
+ it('returns the sandbox an earlier call with the same clientToken created', async () => {
80
+ const { calls, provider } = stub((c) => {
81
+ if (c.url.startsWith(`${API}/sandbox?labels=`)) return { body: [{ id: 'sb1', state: 'started', snapshot: 'capsulos-base:2.0.0' }] };
82
+ return happy(c);
83
+ });
84
+ const handle = await provider.create({ template: 'capsulos-base', clientToken: 'row-1', token: 'capsule-token-0123456789' });
85
+ expect(handle).toMatchObject({ id: 'sb1', template: 'capsulos-base', templateVersion: '2.0.0' });
86
+ expect(calls.some((c) => c.method === 'POST')).toBe(false);
87
+ expect(JSON.parse(decodeURIComponent(calls[0]!.url.split('labels=')[1]!))).toEqual({ capsulos: '1', 'capsulos-client-token': 'row-1' });
88
+ });
89
+ });
90
+
91
+ describe('names and states', () => {
92
+ it('a version is part of the snapshot name', () => {
93
+ expect(daytonaSnapshot('capsulos-base', '2.0.0')).toBe('capsulos-base:2.0.0');
94
+ expect(daytonaSnapshot('my-snapshot')).toBe('my-snapshot');
95
+ });
96
+ it('maps Daytona states', () => {
97
+ expect(toState('started')).toBe('running');
98
+ expect(toState('pulling_snapshot')).toBe('pending');
99
+ expect(toState('stopped')).toBe('terminated');
100
+ expect(toState('whatever')).toBe('unknown');
101
+ });
102
+ });
package/src/index.ts ADDED
@@ -0,0 +1,324 @@
1
+ // Provider for Daytona. One capsule = one Daytona sandbox, created from a
2
+ // snapshot (the image a capsule.yaml was built into). The SDK talks to
3
+ // Daytona's API with your API key and to capsulod through the sandbox's
4
+ // preview address for a port (https://8080-<id>.<proxy domain>), which
5
+ // Daytona only opens to whoever carries the sandbox's preview token.
6
+ //
7
+ // Verified on the service (2026-11-17, docs/providers.md):
8
+ // - Daytona does not run the image's command: the first process of a
9
+ // sandbox is Daytona's own daemon (the toolbox). This provider starts
10
+ // capsulod through it, as root, and then delivers the boot hook (/run on
11
+ // port 9000) the way Lambda MicroVMs does by itself. The capsule's token
12
+ // travels in that hook, never in a command line
13
+ // - a sandbox of the `container` class cannot be paused (stopping it keeps
14
+ // the disk and ends every process): no pause() here
15
+ // - x86_64
16
+ import {
17
+ CapsuleError,
18
+ HOOKS_PORT,
19
+ callHook,
20
+ deliverBoot,
21
+ type CapsuleHandle,
22
+ type CapsuleInfo,
23
+ type CapsuleSpec,
24
+ type CapsuleState,
25
+ type Connection,
26
+ type CreateOptions,
27
+ type Provider,
28
+ type ProviderCapabilities,
29
+ } from '@capsulos/sdk';
30
+
31
+ export interface DaytonaProviderOptions {
32
+ /** Default: the DAYTONA_API_KEY variable. */
33
+ apiKey?: string;
34
+ /** Daytona's API (default the DAYTONA_API_URL variable, or https://app.daytona.io/api; a self-hosted Daytona has its own). */
35
+ apiUrl?: string;
36
+ /** The region sandboxes are created in (default the DAYTONA_TARGET variable, or the organization's default). */
37
+ target?: string;
38
+ /** Default hard limit per capsule, in seconds (default one hour). */
39
+ maxDurationSeconds?: number;
40
+ fetch?: typeof fetch;
41
+ }
42
+
43
+ const CAPSULOD_PORT = 8080;
44
+ const PREVIEW_HEADER = 'X-Daytona-Preview-Token';
45
+ /** The label every capsule carries, to tell them from the organization's other sandboxes. */
46
+ const LABEL = 'capsulos';
47
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
48
+
49
+ /** What Daytona gives a capsule (its default sandbox class, a container on Daytona's runners). */
50
+ export const DAYTONA_CAPABILITIES: ProviderCapabilities = {
51
+ os: ['linux'],
52
+ arch: ['amd64'],
53
+ isolation: 'container',
54
+ maxMemoryMiB: 8192,
55
+ maxCpu: 4,
56
+ gpu: false,
57
+ pause: false,
58
+ snapshot: false,
59
+ mounts: true,
60
+ networkPolicy: true,
61
+ agentHarness: true,
62
+ templateVersions: true,
63
+ typicalStartMs: 5000,
64
+ };
65
+
66
+ export interface DaytonaSandbox {
67
+ id: string;
68
+ snapshot?: string;
69
+ labels?: Record<string, string>;
70
+ state?: string;
71
+ errorReason?: string;
72
+ createdAt?: string;
73
+ autoDestroyAt?: string;
74
+ toolboxProxyUrl?: string;
75
+ }
76
+
77
+ interface Preview {
78
+ url: string;
79
+ token?: string;
80
+ }
81
+
82
+ /** The name of the snapshot a template version is built into: `capsulos-<name>:<version>`. */
83
+ export const daytonaSnapshot = (template: string, version?: string | null) => (version ? `${template}:${version}` : template);
84
+
85
+ export class DaytonaProvider implements Provider {
86
+ readonly name = 'daytona';
87
+ readonly capabilities = DAYTONA_CAPABILITIES;
88
+ private readonly apiKey: string;
89
+ private readonly apiUrl: string;
90
+ private readonly fetchImpl: typeof fetch;
91
+ private readonly previews = new Map<string, Preview>();
92
+
93
+ constructor(private readonly opts: DaytonaProviderOptions = {}) {
94
+ const key = opts.apiKey ?? process.env.DAYTONA_API_KEY;
95
+ if (!key) throw new CapsuleError('Daytona needs an API key: set DAYTONA_API_KEY (https://app.daytona.io/dashboard/keys)');
96
+ this.apiKey = key;
97
+ this.apiUrl = (opts.apiUrl ?? process.env.DAYTONA_API_URL ?? 'https://app.daytona.io/api').replace(/\/+$/, '');
98
+ this.fetchImpl = opts.fetch ?? fetch;
99
+ }
100
+
101
+ /** A call to Daytona's API (or, with a full URL, to a sandbox's toolbox). `ok` lists the statuses that are not errors besides 2xx. */
102
+ async api<T>(method: string, path: string, body?: unknown, ok: number[] = [], timeoutMs = 60_000): Promise<{ status: number; data: T | null }> {
103
+ const url = /^https?:\/\//.test(path) ? path : `${this.apiUrl}${path}`;
104
+ const what = `Daytona ${method} ${/^https?:\/\//.test(path) ? new URL(path).pathname : path}`;
105
+ let res: Response;
106
+ try {
107
+ res = await this.fetchImpl(url, {
108
+ method,
109
+ headers: { authorization: `Bearer ${this.apiKey}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
110
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
111
+ signal: AbortSignal.timeout(timeoutMs),
112
+ });
113
+ } catch (err) {
114
+ throw new CapsuleError(`${what}: ${err instanceof Error ? err.message : String(err)}`);
115
+ }
116
+ const text = await res.text();
117
+ if (!res.ok && !ok.includes(res.status)) {
118
+ let message = text.slice(0, 300);
119
+ try {
120
+ const parsed = JSON.parse(text) as { message?: string | string[] };
121
+ if (parsed.message) message = Array.isArray(parsed.message) ? parsed.message.join('; ') : parsed.message;
122
+ } catch {
123
+ // not JSON: the text is the message
124
+ }
125
+ throw new CapsuleError(`${what}: ${res.status} ${message}`, res.status);
126
+ }
127
+ let data: T | null = null;
128
+ try {
129
+ data = text ? (JSON.parse(text) as T) : null;
130
+ } catch {
131
+ data = null;
132
+ }
133
+ return { status: res.status, data };
134
+ }
135
+
136
+ /** `template` is the name of a Daytona snapshot (`capsulos-<name>` for one built from a capsule.yaml, with the version after a colon). */
137
+ async create(spec: CapsuleSpec, opts: CreateOptions = {}): Promise<CapsuleHandle> {
138
+ if (spec.clientToken) {
139
+ const again = (await this.sandboxes({ [LABEL]: '1', 'capsulos-client-token': spec.clientToken }))[0];
140
+ if (again) return { ...this.infoOf(again), connection: await this.connect(again.id) };
141
+ }
142
+ const maxDurationSeconds = spec.maxDurationSeconds ?? this.opts.maxDurationSeconds ?? 3600;
143
+ const deadline = Date.now() + (opts.timeoutMs ?? 120_000);
144
+ const target = this.opts.target ?? process.env.DAYTONA_TARGET;
145
+ const { data } = await this.api<DaytonaSandbox>('POST', '/sandbox', this.sandboxBody(spec, {
146
+ labels: { [LABEL]: '1', 'capsulos-template': spec.template, ...(spec.clientToken ? { 'capsulos-client-token': spec.clientToken } : {}) },
147
+ // The preview address of a port asks for the sandbox's token.
148
+ public: false,
149
+ // Daytona's idle stop would end every process of the capsule: its life is the time to live and nothing else.
150
+ autoStopInterval: 0,
151
+ ttlMinutes: Math.max(1, Math.ceil(maxDurationSeconds / 60)),
152
+ ...(target ? { target } : {}),
153
+ }));
154
+ if (!data?.id) throw new CapsuleError('Daytona created a sandbox without an id');
155
+ const id = data.id;
156
+ try {
157
+ let sandbox = data;
158
+ while (sandbox.state !== 'started') {
159
+ if (sandbox.state === 'error' || sandbox.state === 'build_failed' || sandbox.state === 'destroyed') {
160
+ throw new CapsuleError(`Daytona could not start sandbox ${id}: ${sandbox.state}${sandbox.errorReason ? ` (${sandbox.errorReason})` : ''}`);
161
+ }
162
+ if (opts.signal?.aborted) throw new CapsuleError(`creation of sandbox ${id} aborted`);
163
+ if (Date.now() > deadline) throw new CapsuleError(`sandbox ${id} was still ${sandbox.state ?? 'not started'} after ${Math.round((opts.timeoutMs ?? 120_000) / 1000)} s`);
164
+ await sleep(500);
165
+ sandbox = (await this.api<DaytonaSandbox>('GET', `/sandbox/${id}`)).data ?? sandbox;
166
+ }
167
+ await this.startDaemon(sandbox);
168
+ await deliverBoot(await this.portConnection(id, HOOKS_PORT), id, spec, { timeoutMs: Math.max(10_000, deadline - Date.now()), signal: opts.signal, fetch: this.fetchImpl });
169
+ } catch (err) {
170
+ await this.terminate(id).catch(() => undefined);
171
+ const e = err instanceof Error ? err : new Error(String(err));
172
+ throw new CapsuleError(`${e.message}; terminated sandbox ${id}`, err instanceof CapsuleError ? err.status : undefined, { capsuleId: id });
173
+ }
174
+ const preview = await this.preview(id, CAPSULOD_PORT);
175
+ return {
176
+ id,
177
+ provider: this.name,
178
+ state: 'running',
179
+ template: spec.template,
180
+ templateVersion: spec.templateVersion ?? null,
181
+ createdAt: data.createdAt ? new Date(data.createdAt) : new Date(),
182
+ endpoint: preview.url,
183
+ maxDurationSeconds,
184
+ connection: await this.portConnection(id, CAPSULOD_PORT),
185
+ };
186
+ }
187
+
188
+ /** What is asked of Daytona for a capsule. A subclass may start from something other than a snapshot. */
189
+ protected sandboxBody(spec: CapsuleSpec, common: Record<string, unknown>): Record<string, unknown> {
190
+ return { snapshot: daytonaSnapshot(spec.template, spec.templateVersion), ...common };
191
+ }
192
+
193
+ /**
194
+ * Start capsulod through the sandbox's toolbox, unless the image's own
195
+ * entrypoint already did. It is started without a token: the boot hook
196
+ * brings it. The session keeps it running after this call returns.
197
+ */
198
+ private async startDaemon(sandbox: DaytonaSandbox): Promise<void> {
199
+ const toolbox = `${(sandbox.toolboxProxyUrl ?? 'https://proxy.app.daytona.io/toolbox').replace(/\/+$/, '')}/${sandbox.id}`;
200
+ const sessionId = 'capsulod';
201
+ // 409: the session exists (a create() repeated on the same sandbox).
202
+ await this.api('POST', `${toolbox}/process/session`, { sessionId }, [409]);
203
+ await this.api('POST', `${toolbox}/process/session/${sessionId}/exec`, {
204
+ command: 'pgrep -x capsulod >/dev/null || (mkdir -p /workspace && cd /workspace && exec capsulod >>/var/log/capsulod.log 2>&1)',
205
+ runAsync: true,
206
+ });
207
+ }
208
+
209
+ async get(id: string): Promise<CapsuleInfo | null> {
210
+ const { status, data } = await this.api<DaytonaSandbox>('GET', `/sandbox/${encodeURIComponent(id)}`, undefined, [404]);
211
+ if (status === 404 || !data) return null;
212
+ return this.infoOf(data);
213
+ }
214
+
215
+ /** The capsules of the organization, optionally those of one template (its snapshot's name, with or without the version). */
216
+ async list(template?: string): Promise<CapsuleInfo[]> {
217
+ const all = await this.sandboxes({ [LABEL]: '1' });
218
+ if (!template) return all.map((s) => this.infoOf(s));
219
+ return all.filter((s) => s.labels?.['capsulos-template'] === template || s.snapshot === template).map((s) => this.infoOf(s));
220
+ }
221
+
222
+ async terminate(id: string): Promise<void> {
223
+ // Best effort: a service that asked for the notice gets it before the machine goes.
224
+ if (this.previews.has(`${id}:${HOOKS_PORT}`)) {
225
+ await callHook(await this.portConnection(id, HOOKS_PORT), 'terminate', {}, { timeoutMs: 0, requestTimeoutMs: 4_000, fetch: this.fetchImpl }).catch(() => undefined);
226
+ }
227
+ await this.api('DELETE', `/sandbox/${encodeURIComponent(id)}`, undefined, [404]);
228
+ for (const key of [...this.previews.keys()]) if (key.startsWith(`${id}:`)) this.previews.delete(key);
229
+ }
230
+
231
+ async connect(id: string): Promise<Connection> {
232
+ return this.portConnection(id, CAPSULOD_PORT);
233
+ }
234
+
235
+ /** The address of a port of the capsule. It asks for the preview token (`portHeaders`). */
236
+ async portUrl(id: string, port: number): Promise<string> {
237
+ return (await this.preview(id, port)).url;
238
+ }
239
+
240
+ async portHeaders(id: string, port: number): Promise<Record<string, string>> {
241
+ const preview = await this.preview(id, port);
242
+ // Without the second header Daytona answers a browser warning page instead of the port.
243
+ return { ...(preview.token ? { [PREVIEW_HEADER]: preview.token } : {}), 'X-Daytona-Skip-Preview-Warning': 'true' };
244
+ }
245
+
246
+ private async preview(id: string, port: number, fresh = false): Promise<Preview> {
247
+ const key = `${id}:${port}`;
248
+ const cached = this.previews.get(key);
249
+ if (cached && !fresh) return cached;
250
+ const { status, data } = await this.api<Preview>('GET', `/sandbox/${encodeURIComponent(id)}/ports/${port}/preview-url`, undefined, [404]);
251
+ if (status === 404 || !data?.url) throw new CapsuleError(`Daytona has no sandbox ${id} (it ended, or it never existed)`, 404, { capsuleId: id });
252
+ const preview = { url: data.url.replace(/\/+$/, ''), ...(data.token ? { token: data.token } : {}) };
253
+ this.previews.set(key, preview);
254
+ return preview;
255
+ }
256
+
257
+ private async portConnection(id: string, port: number): Promise<Connection> {
258
+ const preview = await this.preview(id, port);
259
+ return {
260
+ baseUrl: preview.url,
261
+ headers: async (opts) => {
262
+ if (opts?.fresh) await this.preview(id, port, true);
263
+ return this.portHeaders(id, port);
264
+ },
265
+ };
266
+ }
267
+
268
+ private async sandboxes(labels: Record<string, string>): Promise<DaytonaSandbox[]> {
269
+ const { data } = await this.api<DaytonaSandbox[] | { items?: DaytonaSandbox[] }>('GET', `/sandbox?labels=${encodeURIComponent(JSON.stringify(labels))}`);
270
+ return Array.isArray(data) ? data : (data?.items ?? []);
271
+ }
272
+
273
+ private infoOf(s: DaytonaSandbox): CapsuleInfo {
274
+ const created = s.createdAt ? new Date(s.createdAt) : null;
275
+ const end = s.autoDestroyAt ? new Date(s.autoDestroyAt) : null;
276
+ const [template, version] = splitSnapshot(s.snapshot ?? s.labels?.['capsulos-template']);
277
+ return {
278
+ id: s.id,
279
+ provider: this.name,
280
+ state: toState(s.state),
281
+ template,
282
+ templateVersion: version,
283
+ createdAt: created,
284
+ stateReason: s.errorReason ?? null,
285
+ endpoint: this.previews.get(`${s.id}:${CAPSULOD_PORT}`)?.url ?? null,
286
+ maxDurationSeconds: created && end ? Math.round((end.getTime() - created.getTime()) / 1000) : null,
287
+ };
288
+ }
289
+ }
290
+
291
+ function splitSnapshot(snapshot: string | undefined): [string | null, string | null] {
292
+ if (!snapshot) return [null, null];
293
+ const at = snapshot.lastIndexOf(':');
294
+ return at > 0 ? [snapshot.slice(0, at), snapshot.slice(at + 1)] : [snapshot, null];
295
+ }
296
+
297
+ export function toState(s: string | undefined): CapsuleState {
298
+ switch (s) {
299
+ case 'started':
300
+ return 'running';
301
+ case 'creating':
302
+ case 'starting':
303
+ case 'restoring':
304
+ case 'pending_build':
305
+ case 'building_snapshot':
306
+ case 'pulling_snapshot':
307
+ return 'pending';
308
+ case 'paused':
309
+ case 'pausing':
310
+ return 'suspended';
311
+ case 'stopped':
312
+ case 'stopping':
313
+ case 'destroyed':
314
+ case 'destroying':
315
+ case 'archived':
316
+ case 'archiving':
317
+ case 'error':
318
+ case 'build_failed':
319
+ return 'terminated';
320
+ default:
321
+ return 'unknown';
322
+ }
323
+ }
324
+ export * from './templates.js';