@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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,65 @@
1
+ import { type CapsuleHandle, type CapsuleInfo, type CapsuleSpec, type CapsuleState, type Connection, type CreateOptions, type Provider, type ProviderCapabilities } from '@capsulos/sdk';
2
+ export interface DaytonaProviderOptions {
3
+ /** Default: the DAYTONA_API_KEY variable. */
4
+ apiKey?: string;
5
+ /** Daytona's API (default the DAYTONA_API_URL variable, or https://app.daytona.io/api; a self-hosted Daytona has its own). */
6
+ apiUrl?: string;
7
+ /** The region sandboxes are created in (default the DAYTONA_TARGET variable, or the organization's default). */
8
+ target?: string;
9
+ /** Default hard limit per capsule, in seconds (default one hour). */
10
+ maxDurationSeconds?: number;
11
+ fetch?: typeof fetch;
12
+ }
13
+ /** What Daytona gives a capsule (its default sandbox class, a container on Daytona's runners). */
14
+ export declare const DAYTONA_CAPABILITIES: ProviderCapabilities;
15
+ export interface DaytonaSandbox {
16
+ id: string;
17
+ snapshot?: string;
18
+ labels?: Record<string, string>;
19
+ state?: string;
20
+ errorReason?: string;
21
+ createdAt?: string;
22
+ autoDestroyAt?: string;
23
+ toolboxProxyUrl?: string;
24
+ }
25
+ /** The name of the snapshot a template version is built into: `capsulos-<name>:<version>`. */
26
+ export declare const daytonaSnapshot: (template: string, version?: string | null) => string;
27
+ export declare class DaytonaProvider implements Provider {
28
+ private readonly opts;
29
+ readonly name = "daytona";
30
+ readonly capabilities: ProviderCapabilities;
31
+ private readonly apiKey;
32
+ private readonly apiUrl;
33
+ private readonly fetchImpl;
34
+ private readonly previews;
35
+ constructor(opts?: DaytonaProviderOptions);
36
+ /** 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. */
37
+ api<T>(method: string, path: string, body?: unknown, ok?: number[], timeoutMs?: number): Promise<{
38
+ status: number;
39
+ data: T | null;
40
+ }>;
41
+ /** `template` is the name of a Daytona snapshot (`capsulos-<name>` for one built from a capsule.yaml, with the version after a colon). */
42
+ create(spec: CapsuleSpec, opts?: CreateOptions): Promise<CapsuleHandle>;
43
+ /** What is asked of Daytona for a capsule. A subclass may start from something other than a snapshot. */
44
+ protected sandboxBody(spec: CapsuleSpec, common: Record<string, unknown>): Record<string, unknown>;
45
+ /**
46
+ * Start capsulod through the sandbox's toolbox, unless the image's own
47
+ * entrypoint already did. It is started without a token: the boot hook
48
+ * brings it. The session keeps it running after this call returns.
49
+ */
50
+ private startDaemon;
51
+ get(id: string): Promise<CapsuleInfo | null>;
52
+ /** The capsules of the organization, optionally those of one template (its snapshot's name, with or without the version). */
53
+ list(template?: string): Promise<CapsuleInfo[]>;
54
+ terminate(id: string): Promise<void>;
55
+ connect(id: string): Promise<Connection>;
56
+ /** The address of a port of the capsule. It asks for the preview token (`portHeaders`). */
57
+ portUrl(id: string, port: number): Promise<string>;
58
+ portHeaders(id: string, port: number): Promise<Record<string, string>>;
59
+ private preview;
60
+ private portConnection;
61
+ private sandboxes;
62
+ private infoOf;
63
+ }
64
+ export declare function toState(s: string | undefined): CapsuleState;
65
+ export * from './templates.js';
package/dist/index.js ADDED
@@ -0,0 +1,283 @@
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 { CapsuleError, HOOKS_PORT, callHook, deliverBoot, } from '@capsulos/sdk';
17
+ const CAPSULOD_PORT = 8080;
18
+ const PREVIEW_HEADER = 'X-Daytona-Preview-Token';
19
+ /** The label every capsule carries, to tell them from the organization's other sandboxes. */
20
+ const LABEL = 'capsulos';
21
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
22
+ /** What Daytona gives a capsule (its default sandbox class, a container on Daytona's runners). */
23
+ export const DAYTONA_CAPABILITIES = {
24
+ os: ['linux'],
25
+ arch: ['amd64'],
26
+ isolation: 'container',
27
+ maxMemoryMiB: 8192,
28
+ maxCpu: 4,
29
+ gpu: false,
30
+ pause: false,
31
+ snapshot: false,
32
+ mounts: true,
33
+ networkPolicy: true,
34
+ agentHarness: true,
35
+ templateVersions: true,
36
+ typicalStartMs: 5000,
37
+ };
38
+ /** The name of the snapshot a template version is built into: `capsulos-<name>:<version>`. */
39
+ export const daytonaSnapshot = (template, version) => (version ? `${template}:${version}` : template);
40
+ export class DaytonaProvider {
41
+ opts;
42
+ name = 'daytona';
43
+ capabilities = DAYTONA_CAPABILITIES;
44
+ apiKey;
45
+ apiUrl;
46
+ fetchImpl;
47
+ previews = new Map();
48
+ constructor(opts = {}) {
49
+ this.opts = opts;
50
+ const key = opts.apiKey ?? process.env.DAYTONA_API_KEY;
51
+ if (!key)
52
+ throw new CapsuleError('Daytona needs an API key: set DAYTONA_API_KEY (https://app.daytona.io/dashboard/keys)');
53
+ this.apiKey = key;
54
+ this.apiUrl = (opts.apiUrl ?? process.env.DAYTONA_API_URL ?? 'https://app.daytona.io/api').replace(/\/+$/, '');
55
+ this.fetchImpl = opts.fetch ?? fetch;
56
+ }
57
+ /** 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. */
58
+ async api(method, path, body, ok = [], timeoutMs = 60_000) {
59
+ const url = /^https?:\/\//.test(path) ? path : `${this.apiUrl}${path}`;
60
+ const what = `Daytona ${method} ${/^https?:\/\//.test(path) ? new URL(path).pathname : path}`;
61
+ let res;
62
+ try {
63
+ res = await this.fetchImpl(url, {
64
+ method,
65
+ headers: { authorization: `Bearer ${this.apiKey}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
66
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
67
+ signal: AbortSignal.timeout(timeoutMs),
68
+ });
69
+ }
70
+ catch (err) {
71
+ throw new CapsuleError(`${what}: ${err instanceof Error ? err.message : String(err)}`);
72
+ }
73
+ const text = await res.text();
74
+ if (!res.ok && !ok.includes(res.status)) {
75
+ let message = text.slice(0, 300);
76
+ try {
77
+ const parsed = JSON.parse(text);
78
+ if (parsed.message)
79
+ message = Array.isArray(parsed.message) ? parsed.message.join('; ') : parsed.message;
80
+ }
81
+ catch {
82
+ // not JSON: the text is the message
83
+ }
84
+ throw new CapsuleError(`${what}: ${res.status} ${message}`, res.status);
85
+ }
86
+ let data = null;
87
+ try {
88
+ data = text ? JSON.parse(text) : null;
89
+ }
90
+ catch {
91
+ data = null;
92
+ }
93
+ return { status: res.status, data };
94
+ }
95
+ /** `template` is the name of a Daytona snapshot (`capsulos-<name>` for one built from a capsule.yaml, with the version after a colon). */
96
+ async create(spec, opts = {}) {
97
+ if (spec.clientToken) {
98
+ const again = (await this.sandboxes({ [LABEL]: '1', 'capsulos-client-token': spec.clientToken }))[0];
99
+ if (again)
100
+ return { ...this.infoOf(again), connection: await this.connect(again.id) };
101
+ }
102
+ const maxDurationSeconds = spec.maxDurationSeconds ?? this.opts.maxDurationSeconds ?? 3600;
103
+ const deadline = Date.now() + (opts.timeoutMs ?? 120_000);
104
+ const target = this.opts.target ?? process.env.DAYTONA_TARGET;
105
+ const { data } = await this.api('POST', '/sandbox', this.sandboxBody(spec, {
106
+ labels: { [LABEL]: '1', 'capsulos-template': spec.template, ...(spec.clientToken ? { 'capsulos-client-token': spec.clientToken } : {}) },
107
+ // The preview address of a port asks for the sandbox's token.
108
+ public: false,
109
+ // Daytona's idle stop would end every process of the capsule: its life is the time to live and nothing else.
110
+ autoStopInterval: 0,
111
+ ttlMinutes: Math.max(1, Math.ceil(maxDurationSeconds / 60)),
112
+ ...(target ? { target } : {}),
113
+ }));
114
+ if (!data?.id)
115
+ throw new CapsuleError('Daytona created a sandbox without an id');
116
+ const id = data.id;
117
+ try {
118
+ let sandbox = data;
119
+ while (sandbox.state !== 'started') {
120
+ if (sandbox.state === 'error' || sandbox.state === 'build_failed' || sandbox.state === 'destroyed') {
121
+ throw new CapsuleError(`Daytona could not start sandbox ${id}: ${sandbox.state}${sandbox.errorReason ? ` (${sandbox.errorReason})` : ''}`);
122
+ }
123
+ if (opts.signal?.aborted)
124
+ throw new CapsuleError(`creation of sandbox ${id} aborted`);
125
+ if (Date.now() > deadline)
126
+ throw new CapsuleError(`sandbox ${id} was still ${sandbox.state ?? 'not started'} after ${Math.round((opts.timeoutMs ?? 120_000) / 1000)} s`);
127
+ await sleep(500);
128
+ sandbox = (await this.api('GET', `/sandbox/${id}`)).data ?? sandbox;
129
+ }
130
+ await this.startDaemon(sandbox);
131
+ await deliverBoot(await this.portConnection(id, HOOKS_PORT), id, spec, { timeoutMs: Math.max(10_000, deadline - Date.now()), signal: opts.signal, fetch: this.fetchImpl });
132
+ }
133
+ catch (err) {
134
+ await this.terminate(id).catch(() => undefined);
135
+ const e = err instanceof Error ? err : new Error(String(err));
136
+ throw new CapsuleError(`${e.message}; terminated sandbox ${id}`, err instanceof CapsuleError ? err.status : undefined, { capsuleId: id });
137
+ }
138
+ const preview = await this.preview(id, CAPSULOD_PORT);
139
+ return {
140
+ id,
141
+ provider: this.name,
142
+ state: 'running',
143
+ template: spec.template,
144
+ templateVersion: spec.templateVersion ?? null,
145
+ createdAt: data.createdAt ? new Date(data.createdAt) : new Date(),
146
+ endpoint: preview.url,
147
+ maxDurationSeconds,
148
+ connection: await this.portConnection(id, CAPSULOD_PORT),
149
+ };
150
+ }
151
+ /** What is asked of Daytona for a capsule. A subclass may start from something other than a snapshot. */
152
+ sandboxBody(spec, common) {
153
+ return { snapshot: daytonaSnapshot(spec.template, spec.templateVersion), ...common };
154
+ }
155
+ /**
156
+ * Start capsulod through the sandbox's toolbox, unless the image's own
157
+ * entrypoint already did. It is started without a token: the boot hook
158
+ * brings it. The session keeps it running after this call returns.
159
+ */
160
+ async startDaemon(sandbox) {
161
+ const toolbox = `${(sandbox.toolboxProxyUrl ?? 'https://proxy.app.daytona.io/toolbox').replace(/\/+$/, '')}/${sandbox.id}`;
162
+ const sessionId = 'capsulod';
163
+ // 409: the session exists (a create() repeated on the same sandbox).
164
+ await this.api('POST', `${toolbox}/process/session`, { sessionId }, [409]);
165
+ await this.api('POST', `${toolbox}/process/session/${sessionId}/exec`, {
166
+ command: 'pgrep -x capsulod >/dev/null || (mkdir -p /workspace && cd /workspace && exec capsulod >>/var/log/capsulod.log 2>&1)',
167
+ runAsync: true,
168
+ });
169
+ }
170
+ async get(id) {
171
+ const { status, data } = await this.api('GET', `/sandbox/${encodeURIComponent(id)}`, undefined, [404]);
172
+ if (status === 404 || !data)
173
+ return null;
174
+ return this.infoOf(data);
175
+ }
176
+ /** The capsules of the organization, optionally those of one template (its snapshot's name, with or without the version). */
177
+ async list(template) {
178
+ const all = await this.sandboxes({ [LABEL]: '1' });
179
+ if (!template)
180
+ return all.map((s) => this.infoOf(s));
181
+ return all.filter((s) => s.labels?.['capsulos-template'] === template || s.snapshot === template).map((s) => this.infoOf(s));
182
+ }
183
+ async terminate(id) {
184
+ // Best effort: a service that asked for the notice gets it before the machine goes.
185
+ if (this.previews.has(`${id}:${HOOKS_PORT}`)) {
186
+ await callHook(await this.portConnection(id, HOOKS_PORT), 'terminate', {}, { timeoutMs: 0, requestTimeoutMs: 4_000, fetch: this.fetchImpl }).catch(() => undefined);
187
+ }
188
+ await this.api('DELETE', `/sandbox/${encodeURIComponent(id)}`, undefined, [404]);
189
+ for (const key of [...this.previews.keys()])
190
+ if (key.startsWith(`${id}:`))
191
+ this.previews.delete(key);
192
+ }
193
+ async connect(id) {
194
+ return this.portConnection(id, CAPSULOD_PORT);
195
+ }
196
+ /** The address of a port of the capsule. It asks for the preview token (`portHeaders`). */
197
+ async portUrl(id, port) {
198
+ return (await this.preview(id, port)).url;
199
+ }
200
+ async portHeaders(id, port) {
201
+ const preview = await this.preview(id, port);
202
+ // Without the second header Daytona answers a browser warning page instead of the port.
203
+ return { ...(preview.token ? { [PREVIEW_HEADER]: preview.token } : {}), 'X-Daytona-Skip-Preview-Warning': 'true' };
204
+ }
205
+ async preview(id, port, fresh = false) {
206
+ const key = `${id}:${port}`;
207
+ const cached = this.previews.get(key);
208
+ if (cached && !fresh)
209
+ return cached;
210
+ const { status, data } = await this.api('GET', `/sandbox/${encodeURIComponent(id)}/ports/${port}/preview-url`, undefined, [404]);
211
+ if (status === 404 || !data?.url)
212
+ throw new CapsuleError(`Daytona has no sandbox ${id} (it ended, or it never existed)`, 404, { capsuleId: id });
213
+ const preview = { url: data.url.replace(/\/+$/, ''), ...(data.token ? { token: data.token } : {}) };
214
+ this.previews.set(key, preview);
215
+ return preview;
216
+ }
217
+ async portConnection(id, port) {
218
+ const preview = await this.preview(id, port);
219
+ return {
220
+ baseUrl: preview.url,
221
+ headers: async (opts) => {
222
+ if (opts?.fresh)
223
+ await this.preview(id, port, true);
224
+ return this.portHeaders(id, port);
225
+ },
226
+ };
227
+ }
228
+ async sandboxes(labels) {
229
+ const { data } = await this.api('GET', `/sandbox?labels=${encodeURIComponent(JSON.stringify(labels))}`);
230
+ return Array.isArray(data) ? data : (data?.items ?? []);
231
+ }
232
+ infoOf(s) {
233
+ const created = s.createdAt ? new Date(s.createdAt) : null;
234
+ const end = s.autoDestroyAt ? new Date(s.autoDestroyAt) : null;
235
+ const [template, version] = splitSnapshot(s.snapshot ?? s.labels?.['capsulos-template']);
236
+ return {
237
+ id: s.id,
238
+ provider: this.name,
239
+ state: toState(s.state),
240
+ template,
241
+ templateVersion: version,
242
+ createdAt: created,
243
+ stateReason: s.errorReason ?? null,
244
+ endpoint: this.previews.get(`${s.id}:${CAPSULOD_PORT}`)?.url ?? null,
245
+ maxDurationSeconds: created && end ? Math.round((end.getTime() - created.getTime()) / 1000) : null,
246
+ };
247
+ }
248
+ }
249
+ function splitSnapshot(snapshot) {
250
+ if (!snapshot)
251
+ return [null, null];
252
+ const at = snapshot.lastIndexOf(':');
253
+ return at > 0 ? [snapshot.slice(0, at), snapshot.slice(at + 1)] : [snapshot, null];
254
+ }
255
+ export function toState(s) {
256
+ switch (s) {
257
+ case 'started':
258
+ return 'running';
259
+ case 'creating':
260
+ case 'starting':
261
+ case 'restoring':
262
+ case 'pending_build':
263
+ case 'building_snapshot':
264
+ case 'pulling_snapshot':
265
+ return 'pending';
266
+ case 'paused':
267
+ case 'pausing':
268
+ return 'suspended';
269
+ case 'stopped':
270
+ case 'stopping':
271
+ case 'destroyed':
272
+ case 'destroying':
273
+ case 'archived':
274
+ case 'archiving':
275
+ case 'error':
276
+ case 'build_failed':
277
+ return 'terminated';
278
+ default:
279
+ return 'unknown';
280
+ }
281
+ }
282
+ export * from './templates.js';
283
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,uEAAuE;AACvE,wEAAwE;AACxE,uEAAuE;AACvE,qEAAqE;AACrE,EAAE;AACF,2DAA2D;AAC3D,uEAAuE;AACvE,0EAA0E;AAC1E,6EAA6E;AAC7E,6EAA6E;AAC7E,oDAAoD;AACpD,6EAA6E;AAC7E,wDAAwD;AACxD,aAAa;AACb,OAAO,EACL,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,WAAW,GASZ,MAAM,eAAe,CAAC;AAcvB,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,cAAc,GAAG,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;AAED,SAAS,aAAa,CAAC,QAA4B;IACjD,IAAI,CAAC,QAAQ;QAAE,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACnC,MAAM,EAAE,GAAG,QAAQ,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACrC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AACrF,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,CAAqB;IAC3C,QAAQ,CAAC,EAAE,CAAC;QACV,KAAK,SAAS;YACZ,OAAO,SAAS,CAAC;QACnB,KAAK,UAAU,CAAC;QAChB,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW,CAAC;QACjB,KAAK,eAAe,CAAC;QACrB,KAAK,mBAAmB,CAAC;QACzB,KAAK,kBAAkB;YACrB,OAAO,SAAS,CAAC;QACnB,KAAK,QAAQ,CAAC;QACd,KAAK,SAAS;YACZ,OAAO,WAAW,CAAC;QACrB,KAAK,SAAS,CAAC;QACf,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY,CAAC;QAClB,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW,CAAC;QACjB,KAAK,OAAO,CAAC;QACb,KAAK,cAAc;YACjB,OAAO,YAAY,CAAC;QACtB;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC;AACD,cAAc,gBAAgB,CAAC"}
@@ -0,0 +1,83 @@
1
+ import { type DaytonaProvider } from './index.js';
2
+ export declare const daytonaTemplateName: (name: string) => string;
3
+ /** The line a snapshot's Dockerfile ends with: which template version it is. */
4
+ export declare const daytonaIdentity: (m: {
5
+ name: string;
6
+ version: string;
7
+ digest: string;
8
+ }) => string;
9
+ export declare function parseDaytonaIdentity(dockerfile: string | undefined): {
10
+ name: string;
11
+ version: string;
12
+ digest: string;
13
+ } | null;
14
+ export interface DaytonaSnapshotInfo {
15
+ id: string;
16
+ name: string;
17
+ state: string;
18
+ errorReason?: string | null;
19
+ createdAt?: string;
20
+ buildInfo?: {
21
+ dockerfileContent?: string;
22
+ };
23
+ }
24
+ export interface DaytonaVersion {
25
+ version: string;
26
+ digest: string;
27
+ /** The snapshot's name: `capsulos-<name>:<version>`. */
28
+ snapshot: string;
29
+ snapshotId: string;
30
+ createdAt?: string;
31
+ }
32
+ /** The versions a list of snapshots describes: the active ones whose Dockerfile says they are this template. */
33
+ export declare function daytonaVersions(name: string, snapshots: DaytonaSnapshotInfo[]): DaytonaVersion[];
34
+ /** The snapshots of a template, whatever their state. Daytona's `name` filter matches part of a name: the prefix is checked here. */
35
+ export declare function daytonaSnapshots(provider: DaytonaProvider, name: string): Promise<DaytonaSnapshotInfo[]>;
36
+ /** What Daytona lends to upload a build context with (GET /object-storage/push-access). */
37
+ export interface DaytonaPushAccess {
38
+ accessKey: string;
39
+ secret: string;
40
+ sessionToken: string;
41
+ storageUrl: string;
42
+ organizationId: string;
43
+ bucket: string;
44
+ region?: string;
45
+ }
46
+ /** The name Daytona gives a context: the md5 of its tar. */
47
+ export declare const daytonaContextHash: (tar: Uint8Array) => string;
48
+ /** Where a context goes in the object storage Daytona lends. */
49
+ export declare const daytonaContextKey: (organizationId: string, hash: string) => string;
50
+ export interface DaytonaBuildOptions {
51
+ /** The capsulos template's name. */
52
+ name: string;
53
+ version: string;
54
+ digest: string;
55
+ memoryMiB: number;
56
+ /** The Dockerfile as the template compiles it; the identity line is added here. */
57
+ dockerfile: string;
58
+ /** The context without its Dockerfile, as one tar (packDirectory with the Dockerfile left out). */
59
+ contextTar: Uint8Array;
60
+ /** Puts the tar where Daytona builds from (daytonaContextKey); the CLI with push-access, cloud from its vault. */
61
+ upload(tar: Uint8Array, hash: string): Promise<void>;
62
+ log?: (msg: string) => void;
63
+ signal?: AbortSignal;
64
+ /** The longest a build may take (default 30 minutes). */
65
+ timeoutMs?: number;
66
+ /** How often to ask how the build goes (default 3 s). */
67
+ pollMs?: number;
68
+ }
69
+ export declare class DaytonaBuildError extends Error {
70
+ readonly snapshotId?: string | undefined;
71
+ constructor(message: string, snapshotId?: string | undefined);
72
+ }
73
+ /**
74
+ * Builds a version of a template as a Daytona snapshot. A snapshot of the same name (a version built again,
75
+ * or one whose build failed) is removed first; a snapshot whose build fails is removed.
76
+ */
77
+ export declare function buildDaytonaSnapshot(provider: DaytonaProvider, opts: DaytonaBuildOptions): Promise<{
78
+ snapshotId: string;
79
+ snapshot: string;
80
+ durationMs: number;
81
+ }>;
82
+ /** Takes a version back: its snapshot. */
83
+ export declare function removeDaytonaVersion(provider: DaytonaProvider, name: string, version: string): Promise<void>;