@langchain/daytona 0.0.1

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/dist/index.js ADDED
@@ -0,0 +1,689 @@
1
+ import { Daytona } from "@daytonaio/sdk";
2
+ import { BaseSandbox } from "deepagents";
3
+
4
+ //#region src/auth.ts
5
+ /** Default Daytona API URL */
6
+ const DEFAULT_API_URL = "https://app.daytona.io/api";
7
+ /**
8
+ * Get the API key for Daytona API.
9
+ *
10
+ * Authentication is resolved in the following priority order:
11
+ *
12
+ * 1. **Explicit API key**: If `options.apiKey` is provided, it is used directly.
13
+ * 2. **DAYTONA_API_KEY**: Environment variable for Daytona API key.
14
+ *
15
+ * If no API key is found, an error is thrown with setup instructions.
16
+ *
17
+ * ## Environment Variable Setup
18
+ *
19
+ * ```bash
20
+ * # Get your API key from https://app.daytona.io
21
+ * export DAYTONA_API_KEY=your_api_key_here
22
+ * ```
23
+ *
24
+ * @param options - Optional authentication configuration from DaytonaSandboxOptions
25
+ * @returns The API key string
26
+ * @throws {Error} If no API key is available
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * // With explicit API key
31
+ * const apiKey = getAuthApiKey({ apiKey: "my-api-key" });
32
+ *
33
+ * // Using environment variables (auto-detected)
34
+ * const apiKey = getAuthApiKey();
35
+ *
36
+ * // From DaytonaSandboxOptions
37
+ * const options: DaytonaSandboxOptions = {
38
+ * auth: { apiKey: "my-api-key" }
39
+ * };
40
+ * const apiKey = getAuthApiKey(options.auth);
41
+ * ```
42
+ */
43
+ function getAuthApiKey(options) {
44
+ if (options?.apiKey) return options.apiKey;
45
+ const apiKey = process.env.DAYTONA_API_KEY;
46
+ if (apiKey) return apiKey;
47
+ throw new Error("Daytona authentication required. Provide an API key using one of these methods:\n\n1. Set DAYTONA_API_KEY environment variable:\n Get your API key from https://app.daytona.io\n Run: export DAYTONA_API_KEY=your_api_key_here\n\n2. Pass API key directly in options:\n new DaytonaSandbox({ auth: { apiKey: '...' } })");
48
+ }
49
+ /**
50
+ * Get the API URL for Daytona API.
51
+ *
52
+ * URL is resolved in the following priority order:
53
+ *
54
+ * 1. **Explicit API URL**: If `options.apiUrl` is provided, it is used directly.
55
+ * 2. **DAYTONA_API_URL**: Environment variable for Daytona API URL.
56
+ * 3. **Default**: Uses the default Daytona API URL.
57
+ *
58
+ * @param options - Optional authentication configuration from DaytonaSandboxOptions
59
+ * @returns The API URL string
60
+ */
61
+ function getAuthApiUrl(options) {
62
+ if (options?.apiUrl) return options.apiUrl;
63
+ const apiUrl = process.env.DAYTONA_API_URL;
64
+ if (apiUrl) return apiUrl;
65
+ return DEFAULT_API_URL;
66
+ }
67
+ /**
68
+ * Get authentication credentials for Daytona API.
69
+ *
70
+ * This function returns the credentials needed for the Daytona SDK.
71
+ *
72
+ * @param options - Optional authentication configuration from DaytonaSandboxOptions
73
+ * @param target - Optional target region
74
+ * @returns Complete authentication credentials
75
+ * @throws {Error} If no API key is available
76
+ */
77
+ function getAuthCredentials(options, target) {
78
+ return {
79
+ apiKey: getAuthApiKey(options),
80
+ apiUrl: getAuthApiUrl(options),
81
+ target: target ?? process.env.DAYTONA_TARGET
82
+ };
83
+ }
84
+
85
+ //#endregion
86
+ //#region src/types.ts
87
+ /**
88
+ * Custom error class for Daytona Sandbox operations.
89
+ *
90
+ * Provides structured error information including:
91
+ * - Human-readable message
92
+ * - Error code for programmatic handling
93
+ * - Original cause for debugging
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * try {
98
+ * await sandbox.execute("some command");
99
+ * } catch (error) {
100
+ * if (error instanceof DaytonaSandboxError) {
101
+ * switch (error.code) {
102
+ * case "NOT_INITIALIZED":
103
+ * await sandbox.initialize();
104
+ * break;
105
+ * case "COMMAND_TIMEOUT":
106
+ * console.error("Command took too long");
107
+ * break;
108
+ * default:
109
+ * throw error;
110
+ * }
111
+ * }
112
+ * }
113
+ * ```
114
+ */
115
+ var DaytonaSandboxError = class DaytonaSandboxError extends Error {
116
+ /** Error name for instanceof checks and logging */
117
+ name = "DaytonaSandboxError";
118
+ /**
119
+ * Creates a new DaytonaSandboxError.
120
+ *
121
+ * @param message - Human-readable error description
122
+ * @param code - Structured error code for programmatic handling
123
+ * @param cause - Original error that caused this error (for debugging)
124
+ */
125
+ constructor(message, code, cause) {
126
+ super(message);
127
+ this.code = code;
128
+ this.cause = cause;
129
+ Object.setPrototypeOf(this, DaytonaSandboxError.prototype);
130
+ }
131
+ };
132
+
133
+ //#endregion
134
+ //#region src/sandbox.ts
135
+ /**
136
+ * Daytona Sandbox implementation of the SandboxBackendProtocol.
137
+ *
138
+ * This module provides a Daytona Sandbox backend for deepagents, enabling agents
139
+ * to execute commands, read/write files, and manage isolated sandbox environments
140
+ * using Daytona's infrastructure.
141
+ *
142
+ * @packageDocumentation
143
+ */
144
+ /**
145
+ * Daytona Sandbox backend for deepagents.
146
+ *
147
+ * Extends `BaseSandbox` to provide command execution, file operations, and
148
+ * sandbox lifecycle management using Daytona's SDK.
149
+ *
150
+ * ## Basic Usage
151
+ *
152
+ * ```typescript
153
+ * import { DaytonaSandbox } from "@langchain/daytona";
154
+ *
155
+ * // Create and initialize a sandbox
156
+ * const sandbox = await DaytonaSandbox.create({
157
+ * language: "typescript",
158
+ * timeout: 300,
159
+ * });
160
+ *
161
+ * try {
162
+ * // Execute commands
163
+ * const result = await sandbox.execute("node --version");
164
+ * console.log(result.output);
165
+ * } finally {
166
+ * // Always cleanup
167
+ * await sandbox.close();
168
+ * }
169
+ * ```
170
+ *
171
+ * ## Using with DeepAgent
172
+ *
173
+ * ```typescript
174
+ * import { createDeepAgent } from "deepagents";
175
+ * import { DaytonaSandbox } from "@langchain/daytona";
176
+ *
177
+ * const sandbox = await DaytonaSandbox.create();
178
+ *
179
+ * const agent = createDeepAgent({
180
+ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
181
+ * systemPrompt: "You are a coding assistant with sandbox access.",
182
+ * backend: sandbox,
183
+ * });
184
+ * ```
185
+ */
186
+ var DaytonaSandbox = class DaytonaSandbox extends BaseSandbox {
187
+ /** Private reference to the Daytona client */
188
+ #daytona = null;
189
+ /** Private reference to the underlying Daytona Sandbox instance */
190
+ #sandbox = null;
191
+ /** Configuration options for this sandbox */
192
+ #options;
193
+ /** Unique identifier for this sandbox instance */
194
+ #id;
195
+ /** Default timeout for command execution in seconds */
196
+ #timeout;
197
+ /**
198
+ * Get the unique identifier for this sandbox.
199
+ *
200
+ * Before initialization, returns a temporary ID.
201
+ * After initialization, returns the actual Daytona sandbox ID.
202
+ */
203
+ get id() {
204
+ return this.#id;
205
+ }
206
+ /**
207
+ * Get the underlying Daytona Sandbox instance.
208
+ *
209
+ * @throws {DaytonaSandboxError} If the sandbox is not initialized
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * const sandbox = await DaytonaSandbox.create();
214
+ * const daytonaSdk = sandbox.sandbox; // Access the raw SDK
215
+ * ```
216
+ */
217
+ get sandbox() {
218
+ if (!this.#sandbox) throw new DaytonaSandboxError("Sandbox not initialized. Call initialize() or use DaytonaSandbox.create()", "NOT_INITIALIZED");
219
+ return this.#sandbox;
220
+ }
221
+ /**
222
+ * Check if the sandbox is initialized and running.
223
+ */
224
+ get isRunning() {
225
+ return this.#sandbox !== null;
226
+ }
227
+ /**
228
+ * Create a new DaytonaSandbox instance.
229
+ *
230
+ * Note: This only creates the instance. Call `initialize()` to actually
231
+ * create the Daytona Sandbox, or use the static `DaytonaSandbox.create()` method.
232
+ *
233
+ * @param options - Configuration options for the sandbox
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * // Two-step initialization
238
+ * const sandbox = new DaytonaSandbox({ language: "typescript" });
239
+ * await sandbox.initialize();
240
+ *
241
+ * // Or use the factory method
242
+ * const sandbox = await DaytonaSandbox.create({ language: "typescript" });
243
+ * ```
244
+ */
245
+ constructor(options = {}) {
246
+ super();
247
+ this.#options = {
248
+ language: "typescript",
249
+ timeout: 300,
250
+ ...options
251
+ };
252
+ this.#timeout = this.#options.timeout ?? 300;
253
+ this.#id = `daytona-sandbox-${Date.now()}`;
254
+ }
255
+ /**
256
+ * Initialize the sandbox by creating a new Daytona Sandbox instance.
257
+ *
258
+ * This method authenticates with Daytona and provisions a new sandbox.
259
+ * After initialization, the `id` property will reflect the actual sandbox ID.
260
+ *
261
+ * @throws {DaytonaSandboxError} If already initialized (`ALREADY_INITIALIZED`)
262
+ * @throws {DaytonaSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)
263
+ * @throws {DaytonaSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * const sandbox = new DaytonaSandbox();
268
+ * await sandbox.initialize();
269
+ * console.log(`Sandbox ID: ${sandbox.id}`);
270
+ * ```
271
+ */
272
+ async initialize() {
273
+ if (this.#sandbox) throw new DaytonaSandboxError("Sandbox is already initialized. Each DaytonaSandbox instance can only be initialized once.", "ALREADY_INITIALIZED");
274
+ let credentials;
275
+ try {
276
+ credentials = getAuthCredentials(this.#options.auth, this.#options.target);
277
+ } catch (error) {
278
+ throw new DaytonaSandboxError("Failed to authenticate with Daytona. Check your API key configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
279
+ }
280
+ try {
281
+ this.#daytona = new Daytona({
282
+ apiKey: credentials.apiKey,
283
+ apiUrl: credentials.apiUrl,
284
+ target: credentials.target
285
+ });
286
+ if (this.#options.image) {
287
+ const createOptions = {
288
+ image: this.#options.image,
289
+ language: this.#options.language ?? "typescript"
290
+ };
291
+ if (this.#options.envVars) createOptions.envVars = this.#options.envVars;
292
+ if (this.#options.autoStopInterval !== void 0) createOptions.autoStopInterval = this.#options.autoStopInterval;
293
+ if (this.#options.labels) createOptions.labels = this.#options.labels;
294
+ if (this.#options.resources) createOptions.resources = this.#options.resources;
295
+ this.#sandbox = await this.#daytona.create(createOptions);
296
+ } else {
297
+ const createOptions = { language: this.#options.language ?? "typescript" };
298
+ if (this.#options.snapshot) createOptions.snapshot = this.#options.snapshot;
299
+ if (this.#options.envVars) createOptions.envVars = this.#options.envVars;
300
+ if (this.#options.autoStopInterval !== void 0) createOptions.autoStopInterval = this.#options.autoStopInterval;
301
+ if (this.#options.labels) createOptions.labels = this.#options.labels;
302
+ this.#sandbox = await this.#daytona.create(createOptions);
303
+ }
304
+ this.#id = this.#sandbox.id;
305
+ if (this.#options.initialFiles) await this.#uploadInitialFiles(this.#options.initialFiles);
306
+ } catch (error) {
307
+ throw new DaytonaSandboxError(`Failed to create Daytona Sandbox: ${error instanceof Error ? error.message : String(error)}`, "SANDBOX_CREATION_FAILED", error instanceof Error ? error : void 0);
308
+ }
309
+ }
310
+ /**
311
+ * Upload initial files to the sandbox.
312
+ *
313
+ * @param files - A map of file paths to their string contents
314
+ */
315
+ async #uploadInitialFiles(files) {
316
+ const encoder = new TextEncoder();
317
+ const fileEntries = Object.entries(files).map(([path, content]) => [path, encoder.encode(content)]);
318
+ const errors = (await this.uploadFiles(fileEntries)).filter((r) => r.error !== null);
319
+ if (errors.length > 0) throw new DaytonaSandboxError(`Failed to upload initial files: ${errors.map((e) => `${e.path}: ${e.error}`).join(", ")}`, "FILE_OPERATION_FAILED");
320
+ }
321
+ /**
322
+ * Execute a command in the sandbox.
323
+ *
324
+ * Commands are run using the sandbox's shell.
325
+ *
326
+ * @param command - The shell command to execute
327
+ * @returns Execution result with output, exit code, and truncation flag
328
+ * @throws {DaytonaSandboxError} If the sandbox is not initialized
329
+ *
330
+ * @example
331
+ * ```typescript
332
+ * const result = await sandbox.execute("echo 'Hello World'");
333
+ * console.log(result.output); // "Hello World\n"
334
+ * console.log(result.exitCode); // 0
335
+ * ```
336
+ */
337
+ async execute(command) {
338
+ const sandbox = this.sandbox;
339
+ try {
340
+ const response = await sandbox.process.executeCommand(command, void 0, void 0, this.#timeout);
341
+ return {
342
+ output: response.result ?? "",
343
+ exitCode: response.exitCode ?? 0,
344
+ truncated: false
345
+ };
346
+ } catch (error) {
347
+ if (error instanceof Error && error.message.includes("timeout")) throw new DaytonaSandboxError(`Command timed out: ${command}`, "COMMAND_TIMEOUT", error);
348
+ throw new DaytonaSandboxError(`Command execution failed: ${error instanceof Error ? error.message : String(error)}`, "COMMAND_FAILED", error instanceof Error ? error : void 0);
349
+ }
350
+ }
351
+ /**
352
+ * Upload files to the sandbox.
353
+ *
354
+ * Files are written to the sandbox filesystem. Parent directories are
355
+ * created automatically if they don't exist.
356
+ *
357
+ * @param files - Array of [path, content] tuples to upload
358
+ * @returns Upload result for each file, with success or error status
359
+ *
360
+ * @example
361
+ * ```typescript
362
+ * const encoder = new TextEncoder();
363
+ * const results = await sandbox.uploadFiles([
364
+ * ["src/index.js", encoder.encode("console.log('Hello')")],
365
+ * ["package.json", encoder.encode('{"name": "test"}')],
366
+ * ]);
367
+ * ```
368
+ */
369
+ async uploadFiles(files) {
370
+ const sandbox = this.sandbox;
371
+ const results = [];
372
+ for (const [path, content] of files) try {
373
+ const parentDir = path.substring(0, path.lastIndexOf("/"));
374
+ if (parentDir) await sandbox.fs.createFolder(parentDir, "755");
375
+ const buffer = Buffer.from(content);
376
+ await sandbox.fs.uploadFile(buffer, path);
377
+ results.push({
378
+ path,
379
+ error: null
380
+ });
381
+ } catch (error) {
382
+ results.push({
383
+ path,
384
+ error: this.#mapError(error)
385
+ });
386
+ }
387
+ return results;
388
+ }
389
+ /**
390
+ * Download files from the sandbox.
391
+ *
392
+ * Each file is read individually, allowing partial success when some
393
+ * files exist and others don't.
394
+ *
395
+ * @param paths - Array of file paths to download
396
+ * @returns Download result for each file, with content or error
397
+ *
398
+ * @example
399
+ * ```typescript
400
+ * const results = await sandbox.downloadFiles(["src/index.js", "missing.txt"]);
401
+ * for (const result of results) {
402
+ * if (result.content) {
403
+ * console.log(new TextDecoder().decode(result.content));
404
+ * } else {
405
+ * console.error(`Error: ${result.error}`);
406
+ * }
407
+ * }
408
+ * ```
409
+ */
410
+ async downloadFiles(paths) {
411
+ const sandbox = this.sandbox;
412
+ const results = [];
413
+ for (const path of paths) try {
414
+ const buffer = await sandbox.fs.downloadFile(path);
415
+ results.push({
416
+ path,
417
+ content: new Uint8Array(buffer),
418
+ error: null
419
+ });
420
+ } catch (error) {
421
+ results.push({
422
+ path,
423
+ content: null,
424
+ error: this.#mapError(error)
425
+ });
426
+ }
427
+ return results;
428
+ }
429
+ /**
430
+ * Close the sandbox and release all resources.
431
+ *
432
+ * After closing, the sandbox cannot be used again. The sandbox is deleted
433
+ * from Daytona's infrastructure.
434
+ *
435
+ * @example
436
+ * ```typescript
437
+ * try {
438
+ * await sandbox.execute("npm run build");
439
+ * } finally {
440
+ * await sandbox.close();
441
+ * }
442
+ * ```
443
+ */
444
+ async close() {
445
+ if (this.#sandbox) try {
446
+ await this.#sandbox.delete();
447
+ } finally {
448
+ this.#sandbox = null;
449
+ this.#daytona = null;
450
+ }
451
+ }
452
+ /**
453
+ * Stop the sandbox without deleting it.
454
+ *
455
+ * The sandbox can be restarted later using `start()`.
456
+ *
457
+ * @example
458
+ * ```typescript
459
+ * await sandbox.stop();
460
+ * // Later...
461
+ * await sandbox.start();
462
+ * ```
463
+ */
464
+ async stop() {
465
+ if (this.#sandbox) await this.#sandbox.stop();
466
+ }
467
+ /**
468
+ * Start a stopped sandbox.
469
+ *
470
+ * @param timeout - Maximum time to wait in seconds (default: 60)
471
+ *
472
+ * @example
473
+ * ```typescript
474
+ * await sandbox.start();
475
+ * console.log("Sandbox is now running");
476
+ * ```
477
+ */
478
+ async start(timeout = 60) {
479
+ if (this.#sandbox) await this.#sandbox.start(timeout);
480
+ }
481
+ /**
482
+ * Forcefully terminate and delete the sandbox.
483
+ *
484
+ * Use this when you need to immediately stop the sandbox.
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * await sandbox.kill();
489
+ * ```
490
+ */
491
+ async kill() {
492
+ await this.close();
493
+ }
494
+ /**
495
+ * Get the working directory path inside the sandbox.
496
+ *
497
+ * @returns The absolute path to the sandbox working directory
498
+ *
499
+ * @example
500
+ * ```typescript
501
+ * const workDir = await sandbox.getWorkDir();
502
+ * console.log(`Working directory: ${workDir}`);
503
+ * ```
504
+ */
505
+ async getWorkDir() {
506
+ return await this.sandbox.getWorkDir() ?? "/home/daytona";
507
+ }
508
+ /**
509
+ * Get the user's home directory path inside the sandbox.
510
+ *
511
+ * @returns The absolute path to the user's home directory
512
+ *
513
+ * @example
514
+ * ```typescript
515
+ * const homeDir = await sandbox.getUserHomeDir();
516
+ * console.log(`Home directory: ${homeDir}`);
517
+ * ```
518
+ */
519
+ async getUserHomeDir() {
520
+ return await this.sandbox.getUserHomeDir() ?? "/home/daytona";
521
+ }
522
+ /**
523
+ * Set the sandbox from an existing Daytona Sandbox instance.
524
+ * Used internally by the static `connect()` method.
525
+ */
526
+ #setFromExisting(daytona, existingSandbox, sandboxId) {
527
+ this.#daytona = daytona;
528
+ this.#sandbox = existingSandbox;
529
+ this.#id = sandboxId;
530
+ }
531
+ /**
532
+ * Map Daytona SDK errors to standardized FileOperationError codes.
533
+ *
534
+ * @param error - The error from the Daytona SDK
535
+ * @returns A standardized error code
536
+ */
537
+ #mapError(error) {
538
+ if (error instanceof Error) {
539
+ const msg = error.message.toLowerCase();
540
+ if (msg.includes("not found") || msg.includes("enoent")) return "file_not_found";
541
+ if (msg.includes("permission") || msg.includes("eacces")) return "permission_denied";
542
+ if (msg.includes("directory") || msg.includes("eisdir")) return "is_directory";
543
+ }
544
+ return "invalid_path";
545
+ }
546
+ /**
547
+ * Create and initialize a new DaytonaSandbox in one step.
548
+ *
549
+ * This is the recommended way to create a sandbox. It combines
550
+ * construction and initialization into a single async operation.
551
+ *
552
+ * @param options - Configuration options for the sandbox
553
+ * @returns An initialized and ready-to-use sandbox
554
+ *
555
+ * @example
556
+ * ```typescript
557
+ * const sandbox = await DaytonaSandbox.create({
558
+ * language: "typescript",
559
+ * cpu: 2,
560
+ * memory: 4,
561
+ * });
562
+ * ```
563
+ */
564
+ static async create(options) {
565
+ const sandbox = new DaytonaSandbox(options);
566
+ await sandbox.initialize();
567
+ return sandbox;
568
+ }
569
+ /**
570
+ * Connect to an existing sandbox by ID.
571
+ *
572
+ * This allows you to resume working with a sandbox that was created
573
+ * earlier or that is still running.
574
+ *
575
+ * @param sandboxId - The ID of the sandbox to connect to
576
+ * @param options - Optional auth configuration (for API key)
577
+ * @returns A connected sandbox instance
578
+ *
579
+ * @example
580
+ * ```typescript
581
+ * // Resume a sandbox from a stored ID
582
+ * const sandbox = await DaytonaSandbox.connect("sandbox-abc123");
583
+ * const result = await sandbox.execute("ls -la");
584
+ * ```
585
+ */
586
+ static async connect(sandboxId, options) {
587
+ let credentials;
588
+ try {
589
+ credentials = getAuthCredentials(options?.auth, options?.target);
590
+ } catch (error) {
591
+ throw new DaytonaSandboxError("Failed to authenticate with Daytona. Check your API key configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
592
+ }
593
+ try {
594
+ const daytona = new Daytona({
595
+ apiKey: credentials.apiKey,
596
+ apiUrl: credentials.apiUrl,
597
+ target: credentials.target
598
+ });
599
+ const existingSandbox = await daytona.get(sandboxId);
600
+ const daytonaSandbox = new DaytonaSandbox(options);
601
+ daytonaSandbox.#setFromExisting(daytona, existingSandbox, sandboxId);
602
+ return daytonaSandbox;
603
+ } catch (error) {
604
+ throw new DaytonaSandboxError(`Sandbox not found: ${sandboxId}`, "SANDBOX_NOT_FOUND", error instanceof Error ? error : void 0);
605
+ }
606
+ }
607
+ };
608
+ /**
609
+ * Create an async factory function that creates a new Daytona Sandbox per invocation.
610
+ *
611
+ * Each call to the factory will create and initialize a new sandbox.
612
+ * This is useful when you want fresh, isolated environments for each
613
+ * agent invocation.
614
+ *
615
+ * **Important**: This returns an async factory. For use with middleware that
616
+ * requires synchronous BackendFactory, use `createDaytonaSandboxFactoryFromSandbox()`
617
+ * with a pre-created sandbox instead.
618
+ *
619
+ * @param options - Optional configuration for sandbox creation
620
+ * @returns An async factory function that creates new sandboxes
621
+ *
622
+ * @example
623
+ * ```typescript
624
+ * import { DaytonaSandbox, createDaytonaSandboxFactory } from "@langchain/daytona";
625
+ *
626
+ * // Create a factory for new sandboxes
627
+ * const factory = createDaytonaSandboxFactory({ language: "typescript" });
628
+ *
629
+ * // Each call creates a new sandbox
630
+ * const sandbox1 = await factory();
631
+ * const sandbox2 = await factory();
632
+ *
633
+ * try {
634
+ * // Use sandboxes...
635
+ * } finally {
636
+ * await sandbox1.close();
637
+ * await sandbox2.close();
638
+ * }
639
+ * ```
640
+ */
641
+ function createDaytonaSandboxFactory(options) {
642
+ return async () => {
643
+ return await DaytonaSandbox.create(options);
644
+ };
645
+ }
646
+ /**
647
+ * Create a backend factory that reuses an existing Daytona Sandbox.
648
+ *
649
+ * This allows multiple agent invocations to share the same sandbox,
650
+ * avoiding the startup overhead of creating new sandboxes.
651
+ *
652
+ * Important: You are responsible for managing the sandbox lifecycle
653
+ * (calling `close()` when done).
654
+ *
655
+ * @param sandbox - An existing DaytonaSandbox instance (must be initialized)
656
+ * @returns A BackendFactory that returns the provided sandbox
657
+ *
658
+ * @example
659
+ * ```typescript
660
+ * import { createDeepAgent, createFilesystemMiddleware } from "deepagents";
661
+ * import { DaytonaSandbox, createDaytonaSandboxFactoryFromSandbox } from "@langchain/daytona";
662
+ *
663
+ * // Create and initialize a sandbox
664
+ * const sandbox = await DaytonaSandbox.create({ language: "typescript" });
665
+ *
666
+ * try {
667
+ * const agent = createDeepAgent({
668
+ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
669
+ * systemPrompt: "You are a coding assistant.",
670
+ * middlewares: [
671
+ * createFilesystemMiddleware({
672
+ * backend: createDaytonaSandboxFactoryFromSandbox(sandbox),
673
+ * }),
674
+ * ],
675
+ * });
676
+ *
677
+ * await agent.invoke({ messages: [...] });
678
+ * } finally {
679
+ * await sandbox.close();
680
+ * }
681
+ * ```
682
+ */
683
+ function createDaytonaSandboxFactoryFromSandbox(sandbox) {
684
+ return () => sandbox;
685
+ }
686
+
687
+ //#endregion
688
+ export { DaytonaSandbox, DaytonaSandboxError, createDaytonaSandboxFactory, createDaytonaSandboxFactoryFromSandbox, getAuthApiKey, getAuthApiUrl, getAuthCredentials };
689
+ //# sourceMappingURL=index.js.map