@langchain/daytona 0.1.1 → 0.2.0-alpha.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/README.md CHANGED
@@ -130,6 +130,18 @@ interface DaytonaSandboxOptions {
130
130
  */
131
131
  autoStopInterval?: number;
132
132
 
133
+ /**
134
+ * Auto-archive interval in minutes.
135
+ * The sandbox archives after being stopped for this duration.
136
+ */
137
+ autoArchiveInterval?: number;
138
+
139
+ /**
140
+ * Auto-delete interval in minutes.
141
+ * The sandbox deletes after being stopped for this duration.
142
+ */
143
+ autoDeleteInterval?: number;
144
+
133
145
  /**
134
146
  * Default timeout for command execution in seconds.
135
147
  * @default 300
@@ -269,6 +281,26 @@ await reconnected.start(); // Restart the sandbox
269
281
  const result = await reconnected.execute("ls -la");
270
282
  ```
271
283
 
284
+ ## Auto-Archive and Auto-Delete
285
+
286
+ Configure post-stop lifecycle behavior directly at creation time:
287
+
288
+ ```typescript
289
+ const sandbox = await DaytonaSandbox.create({
290
+ snapshot: "my-snapshot-name",
291
+ // Auto-archive after a sandbox has been stopped for 1 hour
292
+ autoArchiveInterval: 60,
293
+ });
294
+ ```
295
+
296
+ ```typescript
297
+ const sandbox = await DaytonaSandbox.create({
298
+ snapshot: "my-snapshot-name",
299
+ // Auto-delete after a sandbox has been stopped for 1 hour
300
+ autoDeleteInterval: 60,
301
+ });
302
+ ```
303
+
272
304
  ## Sandbox Lifecycle
273
305
 
274
306
  ```typescript
package/dist/index.cjs CHANGED
@@ -1,7 +1,6 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _daytonaio_sdk = require("@daytonaio/sdk");
3
3
  let deepagents = require("deepagents");
4
-
5
4
  //#region src/auth.ts
6
5
  /** Default Daytona API URL */
7
6
  const DEFAULT_API_URL = "https://app.daytona.io/api";
@@ -82,7 +81,6 @@ function getAuthCredentials(options, target) {
82
81
  target: target ?? process.env.DAYTONA_TARGET
83
82
  };
84
83
  }
85
-
86
84
  //#endregion
87
85
  //#region src/types.ts
88
86
  /**
@@ -148,7 +146,6 @@ var DaytonaSandboxError = class DaytonaSandboxError extends deepagents.SandboxEr
148
146
  return typeof error === "object" && error !== null && error[DAYTONA_SANDBOX_ERROR_SYMBOL] === true;
149
147
  }
150
148
  };
151
-
152
149
  //#endregion
153
150
  //#region src/sandbox.ts
154
151
  /**
@@ -324,6 +321,8 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
324
321
  };
325
322
  if (this.#options.envVars) createOptions.envVars = this.#options.envVars;
326
323
  if (this.#options.autoStopInterval !== void 0) createOptions.autoStopInterval = this.#options.autoStopInterval;
324
+ if (this.#options.autoArchiveInterval !== void 0) createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;
325
+ if (this.#options.autoDeleteInterval !== void 0) createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;
327
326
  if (this.#options.labels) createOptions.labels = this.#options.labels;
328
327
  if (this.#options.resources) createOptions.resources = this.#options.resources;
329
328
  this.#sandbox = await this.#daytona.create(createOptions);
@@ -332,6 +331,8 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
332
331
  if (this.#options.snapshot) createOptions.snapshot = this.#options.snapshot;
333
332
  if (this.#options.envVars) createOptions.envVars = this.#options.envVars;
334
333
  if (this.#options.autoStopInterval !== void 0) createOptions.autoStopInterval = this.#options.autoStopInterval;
334
+ if (this.#options.autoArchiveInterval !== void 0) createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;
335
+ if (this.#options.autoDeleteInterval !== void 0) createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;
335
336
  if (this.#options.labels) createOptions.labels = this.#options.labels;
336
337
  this.#sandbox = await this.#daytona.create(createOptions);
337
338
  }
@@ -762,7 +763,6 @@ function createDaytonaSandboxFactory(options) {
762
763
  function createDaytonaSandboxFactoryFromSandbox(sandbox) {
763
764
  return () => sandbox;
764
765
  }
765
-
766
766
  //#endregion
767
767
  exports.DaytonaSandbox = DaytonaSandbox;
768
768
  exports.DaytonaSandboxError = DaytonaSandboxError;
@@ -771,4 +771,5 @@ exports.createDaytonaSandboxFactoryFromSandbox = createDaytonaSandboxFactoryFrom
771
771
  exports.getAuthApiKey = getAuthApiKey;
772
772
  exports.getAuthApiUrl = getAuthApiUrl;
773
773
  exports.getAuthCredentials = getAuthCredentials;
774
+
774
775
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["SandboxError","BaseSandbox","#id","#sandbox","#daytona","#options","#timeout","Daytona","#uploadInitialFiles","#mapError","#setFromExisting"],"sources":["../src/auth.ts","../src/types.ts","../src/sandbox.ts"],"sourcesContent":["/**\n * Authentication utilities for Daytona Sandbox.\n *\n * This module provides authentication credential resolution for the Daytona SDK.\n *\n * @packageDocumentation\n */\n\nimport type { DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Authentication credentials for Daytona API.\n */\nexport interface DaytonaCredentials {\n /** Daytona API key */\n apiKey: string;\n\n /** Daytona API URL */\n apiUrl: string;\n\n /** Target region */\n target?: string;\n}\n\n/** Default Daytona API URL */\nconst DEFAULT_API_URL = \"https://app.daytona.io/api\";\n\n/**\n * Get the API key for Daytona API.\n *\n * Authentication is resolved in the following priority order:\n *\n * 1. **Explicit API key**: If `options.apiKey` is provided, it is used directly.\n * 2. **DAYTONA_API_KEY**: Environment variable for Daytona API key.\n *\n * If no API key is found, an error is thrown with setup instructions.\n *\n * ## Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API key string\n * @throws {Error} If no API key is available\n *\n * @example\n * ```typescript\n * // With explicit API key\n * const apiKey = getAuthApiKey({ apiKey: \"my-api-key\" });\n *\n * // Using environment variables (auto-detected)\n * const apiKey = getAuthApiKey();\n *\n * // From DaytonaSandboxOptions\n * const options: DaytonaSandboxOptions = {\n * auth: { apiKey: \"my-api-key\" }\n * };\n * const apiKey = getAuthApiKey(options.auth);\n * ```\n */\nexport function getAuthApiKey(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API key in options\n if (options?.apiKey) {\n return options.apiKey;\n }\n\n // Priority 2: DAYTONA_API_KEY environment variable\n const apiKey = process.env.DAYTONA_API_KEY;\n if (apiKey) {\n return apiKey;\n }\n\n // No API key found - throw descriptive error\n throw new Error(\n \"Daytona authentication required. Provide an API key using one of these methods:\\n\\n\" +\n \"1. Set DAYTONA_API_KEY environment variable:\\n\" +\n \" Get your API key from https://app.daytona.io\\n\" +\n \" Run: export DAYTONA_API_KEY=your_api_key_here\\n\\n\" +\n \"2. Pass API key directly in options:\\n\" +\n \" new DaytonaSandbox({ auth: { apiKey: '...' } })\",\n );\n}\n\n/**\n * Get the API URL for Daytona API.\n *\n * URL is resolved in the following priority order:\n *\n * 1. **Explicit API URL**: If `options.apiUrl` is provided, it is used directly.\n * 2. **DAYTONA_API_URL**: Environment variable for Daytona API URL.\n * 3. **Default**: Uses the default Daytona API URL.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API URL string\n */\nexport function getAuthApiUrl(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API URL in options\n if (options?.apiUrl) {\n return options.apiUrl;\n }\n\n // Priority 2: DAYTONA_API_URL environment variable\n const apiUrl = process.env.DAYTONA_API_URL;\n if (apiUrl) {\n return apiUrl;\n }\n\n // Priority 3: Default URL\n return DEFAULT_API_URL;\n}\n\n/**\n * Get authentication credentials for Daytona API.\n *\n * This function returns the credentials needed for the Daytona SDK.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @param target - Optional target region\n * @returns Complete authentication credentials\n * @throws {Error} If no API key is available\n */\nexport function getAuthCredentials(\n options?: DaytonaSandboxOptions[\"auth\"],\n target?: string,\n): DaytonaCredentials {\n return {\n apiKey: getAuthApiKey(options),\n apiUrl: getAuthApiUrl(options),\n target: target ?? process.env.DAYTONA_TARGET,\n };\n}\n","/**\n * Type definitions for the Daytona Sandbox backend.\n *\n * This module contains all type definitions for the @langchain/daytona package,\n * including options and error types.\n */\n\nimport { type SandboxErrorCode, SandboxError } from \"deepagents\";\n\n/**\n * Supported target regions for Daytona sandboxes.\n *\n * - `us`: United States\n * - `eu`: Europe\n */\nexport type DaytonaSandboxTarget = \"us\" | \"eu\";\n\n/**\n * Configuration options for creating a Daytona Sandbox.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * timeout: 300, // 5 minutes\n * target: \"us\",\n * };\n * ```\n */\nexport interface DaytonaSandboxOptions {\n /**\n * Primary language for code execution in the sandbox.\n *\n * Determines the runtime environment and code execution tooling.\n *\n * @default \"typescript\"\n */\n language?: \"typescript\" | \"python\" | \"javascript\";\n\n /**\n * Custom environment variables to set in the sandbox.\n *\n * These variables will be available to all commands and code executed\n * in the sandbox.\n *\n * @example\n * ```typescript\n * envVars: {\n * NODE_ENV: \"development\",\n * API_KEY: \"secret\"\n * }\n * ```\n */\n envVars?: Record<string, string>;\n\n /**\n * Resource allocation for the sandbox.\n *\n * When specifying resources, you must also specify an `image`.\n * Resources cannot be customized when using the default snapshot-based sandbox.\n *\n * @example\n * ```typescript\n * resources: { cpu: 2, memory: 4, disk: 20 }\n * ```\n */\n resources?: {\n /** Number of CPUs to allocate */\n cpu?: number;\n /** Amount of memory in GiB */\n memory?: number;\n /** Amount of disk space in GiB */\n disk?: number;\n };\n\n /**\n * Custom Docker image to use for the sandbox.\n *\n * When specified, creates a sandbox from this image instead of the default snapshot.\n * This is required when you want to customize resources.\n *\n * @example \"node:20\" or \"python:3.12\"\n */\n image?: string;\n\n /**\n * Snapshot name to use for the sandbox.\n *\n * When specified, creates a sandbox from this snapshot.\n * Cannot be used together with `image`.\n */\n snapshot?: string;\n\n /**\n * Target region where the sandbox will be created.\n *\n * @default \"us\"\n */\n target?: DaytonaSandboxTarget;\n\n /**\n * Auto-stop interval in minutes.\n *\n * The sandbox will automatically stop after being idle for this duration.\n * Set to 0 to disable auto-stop.\n *\n * @default 15\n */\n autoStopInterval?: number;\n\n /**\n * Default timeout for command execution in seconds.\n *\n * @default 300 (5 minutes)\n */\n timeout?: number;\n\n /**\n * Custom labels to attach to the sandbox.\n *\n * Labels can be used for organizing and filtering sandboxes.\n */\n labels?: Record<string, string>;\n\n /**\n * Initial files to create in the sandbox after initialization.\n *\n * A map of file paths to their contents. Files will be created\n * in the sandbox filesystem before any commands are executed.\n * Parent directories are created automatically.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * initialFiles: {\n * \"/app/index.js\": \"console.log('Hello')\",\n * \"/app/package.json\": '{\"name\": \"test\"}',\n * },\n * };\n * ```\n */\n initialFiles?: Record<string, string>;\n\n /**\n * Authentication configuration for Daytona API.\n *\n * ### Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * Or pass the API key directly in this auth configuration.\n */\n auth?: {\n /**\n * Daytona API key.\n * If not provided, reads from `DAYTONA_API_KEY` environment variable.\n */\n apiKey?: string;\n\n /**\n * Daytona API URL.\n * If not provided, reads from `DAYTONA_API_URL` environment variable\n * or uses the default Daytona API URL.\n *\n * @default \"https://app.daytona.io/api\"\n */\n apiUrl?: string;\n };\n}\n\n/**\n * Error codes for Daytona Sandbox operations.\n *\n * Used to identify specific error conditions and handle them appropriately.\n */\nexport type DaytonaSandboxErrorCode =\n | SandboxErrorCode\n /** Authentication failed - check API key configuration */\n | \"AUTHENTICATION_FAILED\"\n /** Failed to create sandbox - check options and quotas */\n | \"SANDBOX_CREATION_FAILED\"\n /** Sandbox not found - may have been deleted or expired */\n | \"SANDBOX_NOT_FOUND\"\n /** Sandbox is not in started state */\n | \"SANDBOX_NOT_STARTED\"\n /** Resource limits exceeded (CPU, memory, storage) */\n | \"RESOURCE_LIMIT_EXCEEDED\";\n\nconst DAYTONA_SANDBOX_ERROR_SYMBOL = Symbol.for(\"daytona.sandbox.error\");\n\n/**\n * Custom error class for Daytona Sandbox operations.\n *\n * Provides structured error information including:\n * - Human-readable message\n * - Error code for programmatic handling\n * - Original cause for debugging\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"some command\");\n * } catch (error) {\n * if (error instanceof DaytonaSandboxError) {\n * switch (error.code) {\n * case \"NOT_INITIALIZED\":\n * await sandbox.initialize();\n * break;\n * case \"COMMAND_TIMEOUT\":\n * console.error(\"Command took too long\");\n * break;\n * default:\n * throw error;\n * }\n * }\n * }\n * ```\n */\nexport class DaytonaSandboxError extends SandboxError {\n /** Symbol for identifying sandbox error instances */\n [DAYTONA_SANDBOX_ERROR_SYMBOL] = true as const;\n\n /** Error name for instanceof checks and logging */\n override readonly name = \"DaytonaSandboxError\";\n\n /**\n * Creates a new DaytonaSandboxError.\n *\n * @param message - Human-readable error description\n * @param code - Structured error code for programmatic handling\n * @param cause - Original error that caused this error (for debugging)\n */\n constructor(\n message: string,\n public readonly code: DaytonaSandboxErrorCode,\n public override readonly cause?: Error,\n ) {\n super(message, code as SandboxErrorCode, cause);\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, DaytonaSandboxError.prototype);\n }\n\n /**\n * Checks if the error is an instance of DaytonaSandboxError.\n *\n * @param error - The error to check\n * @returns True if the error is an instance of DaytonaSandboxError, false otherwise\n */\n static isInstance(error: unknown): error is DaytonaSandboxError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as Record<symbol, unknown>)[DAYTONA_SANDBOX_ERROR_SYMBOL] === true\n );\n }\n}\n","/* eslint-disable no-instanceof/no-instanceof */\n/**\n * Daytona Sandbox implementation of the SandboxBackendProtocol.\n *\n * This module provides a Daytona Sandbox backend for deepagents, enabling agents\n * to execute commands, read/write files, and manage isolated sandbox environments\n * using Daytona's infrastructure.\n *\n * @packageDocumentation\n */\n\nimport { Daytona, type Sandbox } from \"@daytonaio/sdk\";\nimport {\n BaseSandbox,\n type ExecuteResponse,\n type FileDownloadResponse,\n type FileOperationError,\n type FileUploadResponse,\n type BackendFactory,\n} from \"deepagents\";\n\nimport { getAuthCredentials } from \"./auth.js\";\nimport { DaytonaSandboxError, type DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Daytona Sandbox backend for deepagents.\n *\n * Extends `BaseSandbox` to provide command execution, file operations, and\n * sandbox lifecycle management using Daytona's SDK.\n *\n * ## Basic Usage\n *\n * ```typescript\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * timeout: 300,\n * });\n *\n * try {\n * // Execute commands\n * const result = await sandbox.execute(\"node --version\");\n * console.log(result.output);\n * } finally {\n * // Always cleanup\n * await sandbox.close();\n * }\n * ```\n *\n * ## Using with DeepAgent\n *\n * ```typescript\n * import { createDeepAgent } from \"deepagents\";\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * const sandbox = await DaytonaSandbox.create();\n *\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant with sandbox access.\",\n * backend: sandbox,\n * });\n * ```\n */\nexport class DaytonaSandbox extends BaseSandbox {\n /** Private reference to the Daytona client */\n #daytona: Daytona | null = null;\n\n /** Private reference to the underlying Daytona Sandbox instance */\n #sandbox: Sandbox | null = null;\n\n /** Configuration options for this sandbox */\n #options: DaytonaSandboxOptions;\n\n /** Unique identifier for this sandbox instance */\n #id: string;\n\n /** Default timeout for command execution in seconds */\n #timeout: number;\n\n /**\n * Get the unique identifier for this sandbox.\n *\n * Before initialization, returns a temporary ID.\n * After initialization, returns the actual Daytona sandbox ID.\n */\n get id(): string {\n return this.#id;\n }\n\n /**\n * Get the underlying Daytona Sandbox instance.\n *\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaSdk = sandbox.sandbox; // Access the raw SDK\n * ```\n */\n get instance(): Sandbox {\n if (!this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#sandbox;\n }\n\n /**\n * Get the underlying Daytona client instance.\n *\n * @throws {DaytonaSandboxError} If the client is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaClient = sandbox.client; // Access the raw Daytona client\n * ```\n */\n get client(): Daytona {\n if (!this.#daytona) {\n throw new DaytonaSandboxError(\n \"Daytona client not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#daytona;\n }\n\n /**\n * Check if the sandbox is initialized and running.\n */\n get isRunning(): boolean {\n return this.#sandbox !== null;\n }\n\n /**\n * Create a new DaytonaSandbox instance.\n *\n * Note: This only creates the instance. Call `initialize()` to actually\n * create the Daytona Sandbox, or use the static `DaytonaSandbox.create()` method.\n *\n * @param options - Configuration options for the sandbox\n *\n * @example\n * ```typescript\n * // Two-step initialization\n * const sandbox = new DaytonaSandbox({ language: \"typescript\" });\n * await sandbox.initialize();\n *\n * // Or use the factory method\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n * ```\n */\n constructor(options: DaytonaSandboxOptions = {}) {\n super();\n\n // Set defaults\n this.#options = {\n language: \"typescript\",\n timeout: 300,\n ...options,\n };\n\n this.#timeout = this.#options.timeout ?? 300;\n\n // Generate temporary ID until initialized\n this.#id = `daytona-sandbox-${Date.now()}`;\n }\n\n /**\n * Initialize the sandbox by creating a new Daytona Sandbox instance.\n *\n * This method authenticates with Daytona and provisions a new sandbox.\n * After initialization, the `id` property will reflect the actual sandbox ID.\n *\n * @throws {DaytonaSandboxError} If already initialized (`ALREADY_INITIALIZED`)\n * @throws {DaytonaSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)\n * @throws {DaytonaSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)\n *\n * @example\n * ```typescript\n * const sandbox = new DaytonaSandbox();\n * await sandbox.initialize();\n * console.log(`Sandbox ID: ${sandbox.id}`);\n * ```\n */\n async initialize(): Promise<void> {\n // Prevent double initialization\n if (this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox is already initialized. Each DaytonaSandbox instance can only be initialized once.\",\n \"ALREADY_INITIALIZED\",\n );\n }\n\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(\n this.#options.auth,\n this.#options.target,\n );\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n // Create Daytona client\n this.#daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n // Determine if we're creating from image or snapshot\n if (this.#options.image) {\n // Create from image (allows custom resources)\n const createOptions: {\n image: string;\n language?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n labels?: Record<string, string>;\n resources?: { cpu?: number; memory?: number; disk?: number };\n } = {\n image: this.#options.image,\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n if (this.#options.resources) {\n createOptions.resources = this.#options.resources;\n }\n\n // Create the sandbox from image\n this.#sandbox = await this.#daytona.create(createOptions);\n } else {\n // Create from snapshot (default, simpler approach)\n const createOptions: {\n language?: string;\n snapshot?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n labels?: Record<string, string>;\n } = {\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.snapshot) {\n createOptions.snapshot = this.#options.snapshot;\n }\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n // Create the sandbox from snapshot\n this.#sandbox = await this.#daytona.create(createOptions);\n }\n\n // Update ID to the actual sandbox ID\n this.#id = this.#sandbox.id;\n\n // Upload initial files if provided\n if (this.#options.initialFiles) {\n await this.#uploadInitialFiles(this.#options.initialFiles);\n }\n } catch (error) {\n throw new DaytonaSandboxError(\n `Failed to create Daytona Sandbox: ${error instanceof Error ? error.message : String(error)}`,\n \"SANDBOX_CREATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload initial files to the sandbox.\n *\n * @param files - A map of file paths to their string contents\n */\n async #uploadInitialFiles(files: Record<string, string>): Promise<void> {\n const encoder = new TextEncoder();\n const fileEntries: Array<[string, Uint8Array]> = Object.entries(files).map(\n ([path, content]) => [path, encoder.encode(content)],\n );\n\n const results = await this.uploadFiles(fileEntries);\n\n // Check for any errors during upload\n const errors = results.filter((r) => r.error !== null);\n if (errors.length > 0) {\n const errorPaths = errors.map((e) => `${e.path}: ${e.error}`).join(\", \");\n throw new DaytonaSandboxError(\n `Failed to upload initial files: ${errorPaths}`,\n \"FILE_OPERATION_FAILED\",\n );\n }\n }\n\n /**\n * Execute a command in the sandbox.\n *\n * Commands are run using the sandbox's shell.\n *\n * @param command - The shell command to execute\n * @returns Execution result with output, exit code, and truncation flag\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const result = await sandbox.execute(\"echo 'Hello World'\");\n * console.log(result.output); // \"Hello World\\n\"\n * console.log(result.exitCode); // 0\n * ```\n */\n async execute(command: string): Promise<ExecuteResponse> {\n const sandbox = this.instance; // Throws if not initialized\n\n try {\n const response = await sandbox.process.executeCommand(\n command,\n undefined,\n undefined,\n this.#timeout,\n );\n\n return {\n output: response.result ?? \"\",\n exitCode: response.exitCode ?? 0,\n truncated: false,\n };\n } catch (error) {\n // Check for timeout\n if (error instanceof Error && error.message.includes(\"timeout\")) {\n throw new DaytonaSandboxError(\n `Command timed out: ${command}`,\n \"COMMAND_TIMEOUT\",\n error,\n );\n }\n\n throw new DaytonaSandboxError(\n `Command execution failed: ${error instanceof Error ? error.message : String(error)}`,\n \"COMMAND_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload files to the sandbox.\n *\n * Files are written to the sandbox filesystem. Parent directories are\n * created automatically if they don't exist.\n *\n * @param files - Array of [path, content] tuples to upload\n * @returns Upload result for each file, with success or error status\n *\n * @example\n * ```typescript\n * const encoder = new TextEncoder();\n * const results = await sandbox.uploadFiles([\n * [\"src/index.js\", encoder.encode(\"console.log('Hello')\")],\n * [\"package.json\", encoder.encode('{\"name\": \"test\"}')],\n * ]);\n * ```\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileUploadResponse[] = [];\n\n for (const [path, content] of files) {\n try {\n // Ensure parent directory exists\n const parentDir = path.substring(0, path.lastIndexOf(\"/\"));\n if (parentDir) {\n await sandbox.fs.createFolder(parentDir, \"755\");\n }\n\n // Upload the file content\n const buffer = Buffer.from(content);\n await sandbox.fs.uploadFile(buffer, path);\n results.push({ path, error: null });\n } catch (error) {\n results.push({ path, error: this.#mapError(error) });\n }\n }\n\n return results;\n }\n\n /**\n * Download files from the sandbox.\n *\n * Each file is read individually, allowing partial success when some\n * files exist and others don't.\n *\n * @param paths - Array of file paths to download\n * @returns Download result for each file, with content or error\n *\n * @example\n * ```typescript\n * const results = await sandbox.downloadFiles([\"src/index.js\", \"missing.txt\"]);\n * for (const result of results) {\n * if (result.content) {\n * console.log(new TextDecoder().decode(result.content));\n * } else {\n * console.error(`Error: ${result.error}`);\n * }\n * }\n * ```\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n try {\n const buffer = await sandbox.fs.downloadFile(path);\n results.push({\n path,\n content: new Uint8Array(buffer),\n error: null,\n });\n } catch (error) {\n results.push({\n path,\n content: null,\n error: this.#mapError(error),\n });\n }\n }\n\n return results;\n }\n\n /**\n * Close the sandbox and release all resources.\n *\n * After closing, the sandbox cannot be used again. The sandbox is deleted\n * from Daytona's infrastructure.\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"npm run build\");\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\n async close(): Promise<void> {\n if (this.#sandbox) {\n try {\n await this.#sandbox.delete();\n } finally {\n this.#sandbox = null;\n this.#daytona = null;\n }\n }\n }\n\n /**\n * Stop the sandbox without deleting it.\n *\n * The sandbox can be restarted later using `start()`.\n *\n * @example\n * ```typescript\n * await sandbox.stop();\n * // Later...\n * await sandbox.start();\n * ```\n */\n async stop(): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.stop();\n }\n }\n\n /**\n * Start a stopped sandbox.\n *\n * @param timeout - Maximum time to wait in seconds (default: 60)\n *\n * @example\n * ```typescript\n * await sandbox.start();\n * console.log(\"Sandbox is now running\");\n * ```\n */\n async start(timeout: number = 60): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.start(timeout);\n }\n }\n\n /**\n * Forcefully terminate and delete the sandbox.\n *\n * Use this when you need to immediately stop the sandbox.\n *\n * @example\n * ```typescript\n * await sandbox.kill();\n * ```\n */\n async kill(): Promise<void> {\n await this.close();\n }\n\n /**\n * Get the working directory path inside the sandbox.\n *\n * @returns The absolute path to the sandbox working directory\n *\n * @example\n * ```typescript\n * const workDir = await sandbox.getWorkDir();\n * console.log(`Working directory: ${workDir}`);\n * ```\n */\n async getWorkDir(): Promise<string> {\n const sandbox = this.instance;\n const workDir = await sandbox.getWorkDir();\n return workDir ?? \"/home/daytona\";\n }\n\n /**\n * Get the user's home directory path inside the sandbox.\n *\n * @returns The absolute path to the user's home directory\n *\n * @example\n * ```typescript\n * const homeDir = await sandbox.getUserHomeDir();\n * console.log(`Home directory: ${homeDir}`);\n * ```\n */\n async getUserHomeDir(): Promise<string> {\n const sandbox = this.instance;\n const homeDir = await sandbox.getUserHomeDir();\n return homeDir ?? \"/home/daytona\";\n }\n\n /**\n * Set the sandbox from an existing Daytona Sandbox instance.\n * Used internally by the static `connect()` method.\n */\n #setFromExisting(\n daytona: Daytona,\n existingSandbox: Sandbox,\n sandboxId: string,\n ): void {\n this.#daytona = daytona;\n this.#sandbox = existingSandbox;\n this.#id = sandboxId;\n }\n\n /**\n * Map Daytona SDK errors to standardized FileOperationError codes.\n *\n * @param error - The error from the Daytona SDK\n * @returns A standardized error code\n */\n #mapError(error: unknown): FileOperationError {\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n\n if (msg.includes(\"not found\") || msg.includes(\"enoent\")) {\n return \"file_not_found\";\n }\n if (msg.includes(\"permission\") || msg.includes(\"eacces\")) {\n return \"permission_denied\";\n }\n if (msg.includes(\"directory\") || msg.includes(\"eisdir\")) {\n return \"is_directory\";\n }\n }\n\n return \"invalid_path\";\n }\n\n /**\n * Create and initialize a new DaytonaSandbox in one step.\n *\n * This is the recommended way to create a sandbox. It combines\n * construction and initialization into a single async operation.\n *\n * @param options - Configuration options for the sandbox\n * @returns An initialized and ready-to-use sandbox\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * cpu: 2,\n * memory: 4,\n * });\n * ```\n */\n static async create(\n options?: DaytonaSandboxOptions,\n ): Promise<DaytonaSandbox> {\n const sandbox = new DaytonaSandbox(options);\n await sandbox.initialize();\n return sandbox;\n }\n\n /**\n * Delete all sandboxes matching the given labels.\n *\n * This is useful for cleaning up stale sandboxes from previous test runs\n * or CI pipelines that may not have shut down cleanly.\n *\n * @param labels - Label key-value pairs to filter sandboxes\n * @param options - Optional auth configuration\n * @returns The number of sandboxes that were deleted\n *\n * @example\n * ```typescript\n * // Clean up all integration-test sandboxes\n * const deleted = await DaytonaSandbox.deleteAll({\n * purpose: \"integration-test\",\n * package: \"@langchain/daytona\",\n * });\n * console.log(`Deleted ${deleted} stale sandboxes`);\n * ```\n */\n static async deleteAll(\n labels: Record<string, string>,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\">,\n ): Promise<number> {\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const { items } = await daytona.list(labels);\n\n const results = await Promise.all(\n items.map((sandbox) =>\n daytona\n .delete(sandbox)\n .then(() => true)\n .catch(() => false),\n ),\n );\n\n return results.filter(Boolean).length;\n }\n\n /**\n * Connect to an existing sandbox by ID.\n *\n * This allows you to resume working with a sandbox that was created\n * earlier or that is still running.\n *\n * @param sandboxId - The ID of the sandbox to connect to\n * @param options - Optional auth configuration (for API key)\n * @returns A connected sandbox instance\n *\n * @example\n * ```typescript\n * // Resume a sandbox from a stored ID\n * const sandbox = await DaytonaSandbox.connect(\"sandbox-abc123\");\n * const result = await sandbox.execute(\"ls -la\");\n * ```\n */\n static async fromId(\n id: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\" | \"timeout\">,\n ): Promise<DaytonaSandbox> {\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const existingSandbox = await daytona.get(id);\n\n const daytonaSandbox = new DaytonaSandbox(options);\n // Set the existing sandbox directly (bypass initialize)\n daytonaSandbox.#setFromExisting(daytona, existingSandbox, id);\n\n return daytonaSandbox;\n } catch (error) {\n throw new DaytonaSandboxError(\n `Sandbox not found: ${id}`,\n \"SANDBOX_NOT_FOUND\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Get a running sandbox by name from a deployed app.\n *\n * @param name - The name of the sandbox\n * @param options - Optional auth configuration\n * @returns A connected sandbox instance\n */\n static async fromName(\n name: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\">,\n ): Promise<DaytonaSandbox> {\n return DaytonaSandbox.fromId(name, options);\n }\n}\n\n/**\n * Async factory function type for creating Daytona Sandbox instances.\n *\n * This is similar to BackendFactory but supports async creation,\n * which is required for Daytona Sandbox since initialization is async.\n */\nexport type AsyncDaytonaSandboxFactory = () => Promise<DaytonaSandbox>;\n\n/**\n * Create an async factory function that creates a new Daytona Sandbox per invocation.\n *\n * Each call to the factory will create and initialize a new sandbox.\n * This is useful when you want fresh, isolated environments for each\n * agent invocation.\n *\n * **Important**: This returns an async factory. For use with middleware that\n * requires synchronous BackendFactory, use `createDaytonaSandboxFactoryFromSandbox()`\n * with a pre-created sandbox instead.\n *\n * @param options - Optional configuration for sandbox creation\n * @returns An async factory function that creates new sandboxes\n *\n * @example\n * ```typescript\n * import { DaytonaSandbox, createDaytonaSandboxFactory } from \"@langchain/daytona\";\n *\n * // Create a factory for new sandboxes\n * const factory = createDaytonaSandboxFactory({ language: \"typescript\" });\n *\n * // Each call creates a new sandbox\n * const sandbox1 = await factory();\n * const sandbox2 = await factory();\n *\n * try {\n * // Use sandboxes...\n * } finally {\n * await sandbox1.close();\n * await sandbox2.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactory(\n options?: DaytonaSandboxOptions,\n): AsyncDaytonaSandboxFactory {\n return async () => {\n return await DaytonaSandbox.create(options);\n };\n}\n\n/**\n * Create a backend factory that reuses an existing Daytona Sandbox.\n *\n * This allows multiple agent invocations to share the same sandbox,\n * avoiding the startup overhead of creating new sandboxes.\n *\n * Important: You are responsible for managing the sandbox lifecycle\n * (calling `close()` when done).\n *\n * @param sandbox - An existing DaytonaSandbox instance (must be initialized)\n * @returns A BackendFactory that returns the provided sandbox\n *\n * @example\n * ```typescript\n * import { createDeepAgent, createFilesystemMiddleware } from \"deepagents\";\n * import { DaytonaSandbox, createDaytonaSandboxFactoryFromSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n *\n * try {\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant.\",\n * middlewares: [\n * createFilesystemMiddleware({\n * backend: createDaytonaSandboxFactoryFromSandbox(sandbox),\n * }),\n * ],\n * });\n *\n * await agent.invoke({ messages: [...] });\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactoryFromSandbox(\n sandbox: DaytonaSandbox,\n): BackendFactory {\n return () => sandbox;\n}\n"],"mappings":";;;;;;AAyBA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCxB,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,OAAM,IAAI,MACR,iUAMD;;;;;;;;;;;;;;AAeH,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,QAAO;;;;;;;;;;;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;IACpB,QAAQ,YAAY;IACrB,CAAC;GAEF,MAAM,kBAAkB,MAAM,QAAQ,IAAI,GAAG;GAE7C,MAAM,iBAAiB,IAAI,eAAe,QAAQ;AAElD,mBAAeG,gBAAiB,SAAS,iBAAiB,GAAG;AAE7D,UAAO;WACA,OAAO;AACd,SAAM,IAAI,oBACR,sBAAsB,MACtB,qBACA,iBAAiB,QAAQ,QAAQ,OAClC;;;;;;;;;;CAWL,aAAa,SACX,MACA,SACyB;AACzB,SAAO,eAAe,OAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C/C,SAAgB,4BACd,SAC4B;AAC5B,QAAO,YAAY;AACjB,SAAO,MAAM,eAAe,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyC/C,SAAgB,uCACd,SACgB;AAChB,cAAa"}
1
+ {"version":3,"file":"index.cjs","names":["SandboxError","BaseSandbox","#id","#sandbox","#daytona","#options","#timeout","Daytona","#uploadInitialFiles","#mapError","#setFromExisting"],"sources":["../src/auth.ts","../src/types.ts","../src/sandbox.ts"],"sourcesContent":["/**\n * Authentication utilities for Daytona Sandbox.\n *\n * This module provides authentication credential resolution for the Daytona SDK.\n *\n * @packageDocumentation\n */\n\nimport type { DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Authentication credentials for Daytona API.\n */\nexport interface DaytonaCredentials {\n /** Daytona API key */\n apiKey: string;\n\n /** Daytona API URL */\n apiUrl: string;\n\n /** Target region */\n target?: string;\n}\n\n/** Default Daytona API URL */\nconst DEFAULT_API_URL = \"https://app.daytona.io/api\";\n\n/**\n * Get the API key for Daytona API.\n *\n * Authentication is resolved in the following priority order:\n *\n * 1. **Explicit API key**: If `options.apiKey` is provided, it is used directly.\n * 2. **DAYTONA_API_KEY**: Environment variable for Daytona API key.\n *\n * If no API key is found, an error is thrown with setup instructions.\n *\n * ## Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API key string\n * @throws {Error} If no API key is available\n *\n * @example\n * ```typescript\n * // With explicit API key\n * const apiKey = getAuthApiKey({ apiKey: \"my-api-key\" });\n *\n * // Using environment variables (auto-detected)\n * const apiKey = getAuthApiKey();\n *\n * // From DaytonaSandboxOptions\n * const options: DaytonaSandboxOptions = {\n * auth: { apiKey: \"my-api-key\" }\n * };\n * const apiKey = getAuthApiKey(options.auth);\n * ```\n */\nexport function getAuthApiKey(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API key in options\n if (options?.apiKey) {\n return options.apiKey;\n }\n\n // Priority 2: DAYTONA_API_KEY environment variable\n const apiKey = process.env.DAYTONA_API_KEY;\n if (apiKey) {\n return apiKey;\n }\n\n // No API key found - throw descriptive error\n throw new Error(\n \"Daytona authentication required. Provide an API key using one of these methods:\\n\\n\" +\n \"1. Set DAYTONA_API_KEY environment variable:\\n\" +\n \" Get your API key from https://app.daytona.io\\n\" +\n \" Run: export DAYTONA_API_KEY=your_api_key_here\\n\\n\" +\n \"2. Pass API key directly in options:\\n\" +\n \" new DaytonaSandbox({ auth: { apiKey: '...' } })\",\n );\n}\n\n/**\n * Get the API URL for Daytona API.\n *\n * URL is resolved in the following priority order:\n *\n * 1. **Explicit API URL**: If `options.apiUrl` is provided, it is used directly.\n * 2. **DAYTONA_API_URL**: Environment variable for Daytona API URL.\n * 3. **Default**: Uses the default Daytona API URL.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API URL string\n */\nexport function getAuthApiUrl(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API URL in options\n if (options?.apiUrl) {\n return options.apiUrl;\n }\n\n // Priority 2: DAYTONA_API_URL environment variable\n const apiUrl = process.env.DAYTONA_API_URL;\n if (apiUrl) {\n return apiUrl;\n }\n\n // Priority 3: Default URL\n return DEFAULT_API_URL;\n}\n\n/**\n * Get authentication credentials for Daytona API.\n *\n * This function returns the credentials needed for the Daytona SDK.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @param target - Optional target region\n * @returns Complete authentication credentials\n * @throws {Error} If no API key is available\n */\nexport function getAuthCredentials(\n options?: DaytonaSandboxOptions[\"auth\"],\n target?: string,\n): DaytonaCredentials {\n return {\n apiKey: getAuthApiKey(options),\n apiUrl: getAuthApiUrl(options),\n target: target ?? process.env.DAYTONA_TARGET,\n };\n}\n","/**\n * Type definitions for the Daytona Sandbox backend.\n *\n * This module contains all type definitions for the @langchain/daytona package,\n * including options and error types.\n */\n\nimport { type SandboxErrorCode, SandboxError } from \"deepagents\";\n\n/**\n * Supported target regions for Daytona sandboxes.\n *\n * - `us`: United States\n * - `eu`: Europe\n */\nexport type DaytonaSandboxTarget = \"us\" | \"eu\";\n\n/**\n * Configuration options for creating a Daytona Sandbox.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * timeout: 300, // 5 minutes\n * target: \"us\",\n * };\n * ```\n */\nexport interface DaytonaSandboxOptions {\n /**\n * Primary language for code execution in the sandbox.\n *\n * Determines the runtime environment and code execution tooling.\n *\n * @default \"typescript\"\n */\n language?: \"typescript\" | \"python\" | \"javascript\";\n\n /**\n * Custom environment variables to set in the sandbox.\n *\n * These variables will be available to all commands and code executed\n * in the sandbox.\n *\n * @example\n * ```typescript\n * envVars: {\n * NODE_ENV: \"development\",\n * API_KEY: \"secret\"\n * }\n * ```\n */\n envVars?: Record<string, string>;\n\n /**\n * Resource allocation for the sandbox.\n *\n * When specifying resources, you must also specify an `image`.\n * Resources cannot be customized when using the default snapshot-based sandbox.\n *\n * @example\n * ```typescript\n * resources: { cpu: 2, memory: 4, disk: 20 }\n * ```\n */\n resources?: {\n /** Number of CPUs to allocate */\n cpu?: number;\n /** Amount of memory in GiB */\n memory?: number;\n /** Amount of disk space in GiB */\n disk?: number;\n };\n\n /**\n * Custom Docker image to use for the sandbox.\n *\n * When specified, creates a sandbox from this image instead of the default snapshot.\n * This is required when you want to customize resources.\n *\n * @example \"node:20\" or \"python:3.12\"\n */\n image?: string;\n\n /**\n * Snapshot name to use for the sandbox.\n *\n * When specified, creates a sandbox from this snapshot.\n * Cannot be used together with `image`.\n */\n snapshot?: string;\n\n /**\n * Target region where the sandbox will be created.\n *\n * @default \"us\"\n */\n target?: DaytonaSandboxTarget;\n\n /**\n * Auto-stop interval in minutes.\n *\n * The sandbox will automatically stop after being idle for this duration.\n * Set to 0 to disable auto-stop.\n *\n * @default 15\n */\n autoStopInterval?: number;\n\n /**\n * Auto-archive interval in minutes.\n *\n * The sandbox will automatically archive after being stopped for this duration.\n */\n autoArchiveInterval?: number;\n\n /**\n * Auto-delete interval in minutes.\n *\n * The sandbox will automatically delete after being stopped for this duration.\n */\n autoDeleteInterval?: number;\n\n /**\n * Default timeout for command execution in seconds.\n *\n * @default 300 (5 minutes)\n */\n timeout?: number;\n\n /**\n * Custom labels to attach to the sandbox.\n *\n * Labels can be used for organizing and filtering sandboxes.\n */\n labels?: Record<string, string>;\n\n /**\n * Initial files to create in the sandbox after initialization.\n *\n * A map of file paths to their contents. Files will be created\n * in the sandbox filesystem before any commands are executed.\n * Parent directories are created automatically.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * initialFiles: {\n * \"/app/index.js\": \"console.log('Hello')\",\n * \"/app/package.json\": '{\"name\": \"test\"}',\n * },\n * };\n * ```\n */\n initialFiles?: Record<string, string>;\n\n /**\n * Authentication configuration for Daytona API.\n *\n * ### Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * Or pass the API key directly in this auth configuration.\n */\n auth?: {\n /**\n * Daytona API key.\n * If not provided, reads from `DAYTONA_API_KEY` environment variable.\n */\n apiKey?: string;\n\n /**\n * Daytona API URL.\n * If not provided, reads from `DAYTONA_API_URL` environment variable\n * or uses the default Daytona API URL.\n *\n * @default \"https://app.daytona.io/api\"\n */\n apiUrl?: string;\n };\n}\n\n/**\n * Error codes for Daytona Sandbox operations.\n *\n * Used to identify specific error conditions and handle them appropriately.\n */\nexport type DaytonaSandboxErrorCode =\n | SandboxErrorCode\n /** Authentication failed - check API key configuration */\n | \"AUTHENTICATION_FAILED\"\n /** Failed to create sandbox - check options and quotas */\n | \"SANDBOX_CREATION_FAILED\"\n /** Sandbox not found - may have been deleted or expired */\n | \"SANDBOX_NOT_FOUND\"\n /** Sandbox is not in started state */\n | \"SANDBOX_NOT_STARTED\"\n /** Resource limits exceeded (CPU, memory, storage) */\n | \"RESOURCE_LIMIT_EXCEEDED\";\n\nconst DAYTONA_SANDBOX_ERROR_SYMBOL = Symbol.for(\"daytona.sandbox.error\");\n\n/**\n * Custom error class for Daytona Sandbox operations.\n *\n * Provides structured error information including:\n * - Human-readable message\n * - Error code for programmatic handling\n * - Original cause for debugging\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"some command\");\n * } catch (error) {\n * if (error instanceof DaytonaSandboxError) {\n * switch (error.code) {\n * case \"NOT_INITIALIZED\":\n * await sandbox.initialize();\n * break;\n * case \"COMMAND_TIMEOUT\":\n * console.error(\"Command took too long\");\n * break;\n * default:\n * throw error;\n * }\n * }\n * }\n * ```\n */\nexport class DaytonaSandboxError extends SandboxError {\n /** Symbol for identifying sandbox error instances */\n [DAYTONA_SANDBOX_ERROR_SYMBOL] = true as const;\n\n /** Error name for instanceof checks and logging */\n override readonly name = \"DaytonaSandboxError\";\n\n /**\n * Creates a new DaytonaSandboxError.\n *\n * @param message - Human-readable error description\n * @param code - Structured error code for programmatic handling\n * @param cause - Original error that caused this error (for debugging)\n */\n constructor(\n message: string,\n public readonly code: DaytonaSandboxErrorCode,\n public override readonly cause?: Error,\n ) {\n super(message, code as SandboxErrorCode, cause);\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, DaytonaSandboxError.prototype);\n }\n\n /**\n * Checks if the error is an instance of DaytonaSandboxError.\n *\n * @param error - The error to check\n * @returns True if the error is an instance of DaytonaSandboxError, false otherwise\n */\n static isInstance(error: unknown): error is DaytonaSandboxError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as Record<symbol, unknown>)[DAYTONA_SANDBOX_ERROR_SYMBOL] === true\n );\n }\n}\n","/* oxlint-disable no-instanceof/no-instanceof */\n/**\n * Daytona Sandbox implementation of the SandboxBackendProtocol.\n *\n * This module provides a Daytona Sandbox backend for deepagents, enabling agents\n * to execute commands, read/write files, and manage isolated sandbox environments\n * using Daytona's infrastructure.\n *\n * @packageDocumentation\n */\n\nimport { Daytona, type Sandbox } from \"@daytonaio/sdk\";\nimport {\n BaseSandbox,\n type ExecuteResponse,\n type FileDownloadResponse,\n type FileOperationError,\n type FileUploadResponse,\n type BackendFactory,\n} from \"deepagents\";\n\nimport { getAuthCredentials } from \"./auth.js\";\nimport { DaytonaSandboxError, type DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Daytona Sandbox backend for deepagents.\n *\n * Extends `BaseSandbox` to provide command execution, file operations, and\n * sandbox lifecycle management using Daytona's SDK.\n *\n * ## Basic Usage\n *\n * ```typescript\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * timeout: 300,\n * });\n *\n * try {\n * // Execute commands\n * const result = await sandbox.execute(\"node --version\");\n * console.log(result.output);\n * } finally {\n * // Always cleanup\n * await sandbox.close();\n * }\n * ```\n *\n * ## Using with DeepAgent\n *\n * ```typescript\n * import { createDeepAgent } from \"deepagents\";\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * const sandbox = await DaytonaSandbox.create();\n *\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant with sandbox access.\",\n * backend: sandbox,\n * });\n * ```\n */\nexport class DaytonaSandbox extends BaseSandbox {\n /** Private reference to the Daytona client */\n #daytona: Daytona | null = null;\n\n /** Private reference to the underlying Daytona Sandbox instance */\n #sandbox: Sandbox | null = null;\n\n /** Configuration options for this sandbox */\n #options: DaytonaSandboxOptions;\n\n /** Unique identifier for this sandbox instance */\n #id: string;\n\n /** Default timeout for command execution in seconds */\n #timeout: number;\n\n /**\n * Get the unique identifier for this sandbox.\n *\n * Before initialization, returns a temporary ID.\n * After initialization, returns the actual Daytona sandbox ID.\n */\n get id(): string {\n return this.#id;\n }\n\n /**\n * Get the underlying Daytona Sandbox instance.\n *\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaSdk = sandbox.sandbox; // Access the raw SDK\n * ```\n */\n get instance(): Sandbox {\n if (!this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#sandbox;\n }\n\n /**\n * Get the underlying Daytona client instance.\n *\n * @throws {DaytonaSandboxError} If the client is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaClient = sandbox.client; // Access the raw Daytona client\n * ```\n */\n get client(): Daytona {\n if (!this.#daytona) {\n throw new DaytonaSandboxError(\n \"Daytona client not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#daytona;\n }\n\n /**\n * Check if the sandbox is initialized and running.\n */\n get isRunning(): boolean {\n return this.#sandbox !== null;\n }\n\n /**\n * Create a new DaytonaSandbox instance.\n *\n * Note: This only creates the instance. Call `initialize()` to actually\n * create the Daytona Sandbox, or use the static `DaytonaSandbox.create()` method.\n *\n * @param options - Configuration options for the sandbox\n *\n * @example\n * ```typescript\n * // Two-step initialization\n * const sandbox = new DaytonaSandbox({ language: \"typescript\" });\n * await sandbox.initialize();\n *\n * // Or use the factory method\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n * ```\n */\n constructor(options: DaytonaSandboxOptions = {}) {\n super();\n\n // Set defaults\n this.#options = {\n language: \"typescript\",\n timeout: 300,\n ...options,\n };\n\n this.#timeout = this.#options.timeout ?? 300;\n\n // Generate temporary ID until initialized\n this.#id = `daytona-sandbox-${Date.now()}`;\n }\n\n /**\n * Initialize the sandbox by creating a new Daytona Sandbox instance.\n *\n * This method authenticates with Daytona and provisions a new sandbox.\n * After initialization, the `id` property will reflect the actual sandbox ID.\n *\n * @throws {DaytonaSandboxError} If already initialized (`ALREADY_INITIALIZED`)\n * @throws {DaytonaSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)\n * @throws {DaytonaSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)\n *\n * @example\n * ```typescript\n * const sandbox = new DaytonaSandbox();\n * await sandbox.initialize();\n * console.log(`Sandbox ID: ${sandbox.id}`);\n * ```\n */\n async initialize(): Promise<void> {\n // Prevent double initialization\n if (this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox is already initialized. Each DaytonaSandbox instance can only be initialized once.\",\n \"ALREADY_INITIALIZED\",\n );\n }\n\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(\n this.#options.auth,\n this.#options.target,\n );\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n // Create Daytona client\n this.#daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n // Determine if we're creating from image or snapshot\n if (this.#options.image) {\n // Create from image (allows custom resources)\n const createOptions: {\n image: string;\n language?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n autoArchiveInterval?: number;\n autoDeleteInterval?: number;\n labels?: Record<string, string>;\n resources?: { cpu?: number; memory?: number; disk?: number };\n } = {\n image: this.#options.image,\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.autoArchiveInterval !== undefined) {\n createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;\n }\n\n if (this.#options.autoDeleteInterval !== undefined) {\n createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n if (this.#options.resources) {\n createOptions.resources = this.#options.resources;\n }\n\n // Create the sandbox from image\n this.#sandbox = await this.#daytona.create(createOptions);\n } else {\n // Create from snapshot (default, simpler approach)\n const createOptions: {\n language?: string;\n snapshot?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n autoArchiveInterval?: number;\n autoDeleteInterval?: number;\n labels?: Record<string, string>;\n } = {\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.snapshot) {\n createOptions.snapshot = this.#options.snapshot;\n }\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.autoArchiveInterval !== undefined) {\n createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;\n }\n\n if (this.#options.autoDeleteInterval !== undefined) {\n createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n // Create the sandbox from snapshot\n this.#sandbox = await this.#daytona.create(createOptions);\n }\n\n // Update ID to the actual sandbox ID\n this.#id = this.#sandbox.id;\n\n // Upload initial files if provided\n if (this.#options.initialFiles) {\n await this.#uploadInitialFiles(this.#options.initialFiles);\n }\n } catch (error) {\n throw new DaytonaSandboxError(\n `Failed to create Daytona Sandbox: ${error instanceof Error ? error.message : String(error)}`,\n \"SANDBOX_CREATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload initial files to the sandbox.\n *\n * @param files - A map of file paths to their string contents\n */\n async #uploadInitialFiles(files: Record<string, string>): Promise<void> {\n const encoder = new TextEncoder();\n const fileEntries: Array<[string, Uint8Array]> = Object.entries(files).map(\n ([path, content]) => [path, encoder.encode(content)],\n );\n\n const results = await this.uploadFiles(fileEntries);\n\n // Check for any errors during upload\n const errors = results.filter((r) => r.error !== null);\n if (errors.length > 0) {\n const errorPaths = errors.map((e) => `${e.path}: ${e.error}`).join(\", \");\n throw new DaytonaSandboxError(\n `Failed to upload initial files: ${errorPaths}`,\n \"FILE_OPERATION_FAILED\",\n );\n }\n }\n\n /**\n * Execute a command in the sandbox.\n *\n * Commands are run using the sandbox's shell.\n *\n * @param command - The shell command to execute\n * @returns Execution result with output, exit code, and truncation flag\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const result = await sandbox.execute(\"echo 'Hello World'\");\n * console.log(result.output); // \"Hello World\\n\"\n * console.log(result.exitCode); // 0\n * ```\n */\n async execute(command: string): Promise<ExecuteResponse> {\n const sandbox = this.instance; // Throws if not initialized\n\n try {\n const response = await sandbox.process.executeCommand(\n command,\n undefined,\n undefined,\n this.#timeout,\n );\n\n return {\n output: response.result ?? \"\",\n exitCode: response.exitCode ?? 0,\n truncated: false,\n };\n } catch (error) {\n // Check for timeout\n if (error instanceof Error && error.message.includes(\"timeout\")) {\n throw new DaytonaSandboxError(\n `Command timed out: ${command}`,\n \"COMMAND_TIMEOUT\",\n error,\n );\n }\n\n throw new DaytonaSandboxError(\n `Command execution failed: ${error instanceof Error ? error.message : String(error)}`,\n \"COMMAND_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload files to the sandbox.\n *\n * Files are written to the sandbox filesystem. Parent directories are\n * created automatically if they don't exist.\n *\n * @param files - Array of [path, content] tuples to upload\n * @returns Upload result for each file, with success or error status\n *\n * @example\n * ```typescript\n * const encoder = new TextEncoder();\n * const results = await sandbox.uploadFiles([\n * [\"src/index.js\", encoder.encode(\"console.log('Hello')\")],\n * [\"package.json\", encoder.encode('{\"name\": \"test\"}')],\n * ]);\n * ```\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileUploadResponse[] = [];\n\n for (const [path, content] of files) {\n try {\n // Ensure parent directory exists\n const parentDir = path.substring(0, path.lastIndexOf(\"/\"));\n if (parentDir) {\n await sandbox.fs.createFolder(parentDir, \"755\");\n }\n\n // Upload the file content\n const buffer = Buffer.from(content);\n await sandbox.fs.uploadFile(buffer, path);\n results.push({ path, error: null });\n } catch (error) {\n results.push({ path, error: this.#mapError(error) });\n }\n }\n\n return results;\n }\n\n /**\n * Download files from the sandbox.\n *\n * Each file is read individually, allowing partial success when some\n * files exist and others don't.\n *\n * @param paths - Array of file paths to download\n * @returns Download result for each file, with content or error\n *\n * @example\n * ```typescript\n * const results = await sandbox.downloadFiles([\"src/index.js\", \"missing.txt\"]);\n * for (const result of results) {\n * if (result.content) {\n * console.log(new TextDecoder().decode(result.content));\n * } else {\n * console.error(`Error: ${result.error}`);\n * }\n * }\n * ```\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n try {\n const buffer = await sandbox.fs.downloadFile(path);\n results.push({\n path,\n content: new Uint8Array(buffer),\n error: null,\n });\n } catch (error) {\n results.push({\n path,\n content: null,\n error: this.#mapError(error),\n });\n }\n }\n\n return results;\n }\n\n /**\n * Close the sandbox and release all resources.\n *\n * After closing, the sandbox cannot be used again. The sandbox is deleted\n * from Daytona's infrastructure.\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"npm run build\");\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\n async close(): Promise<void> {\n if (this.#sandbox) {\n try {\n await this.#sandbox.delete();\n } finally {\n this.#sandbox = null;\n this.#daytona = null;\n }\n }\n }\n\n /**\n * Stop the sandbox without deleting it.\n *\n * The sandbox can be restarted later using `start()`.\n *\n * @example\n * ```typescript\n * await sandbox.stop();\n * // Later...\n * await sandbox.start();\n * ```\n */\n async stop(): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.stop();\n }\n }\n\n /**\n * Start a stopped sandbox.\n *\n * @param timeout - Maximum time to wait in seconds (default: 60)\n *\n * @example\n * ```typescript\n * await sandbox.start();\n * console.log(\"Sandbox is now running\");\n * ```\n */\n async start(timeout: number = 60): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.start(timeout);\n }\n }\n\n /**\n * Forcefully terminate and delete the sandbox.\n *\n * Use this when you need to immediately stop the sandbox.\n *\n * @example\n * ```typescript\n * await sandbox.kill();\n * ```\n */\n async kill(): Promise<void> {\n await this.close();\n }\n\n /**\n * Get the working directory path inside the sandbox.\n *\n * @returns The absolute path to the sandbox working directory\n *\n * @example\n * ```typescript\n * const workDir = await sandbox.getWorkDir();\n * console.log(`Working directory: ${workDir}`);\n * ```\n */\n async getWorkDir(): Promise<string> {\n const sandbox = this.instance;\n const workDir = await sandbox.getWorkDir();\n return workDir ?? \"/home/daytona\";\n }\n\n /**\n * Get the user's home directory path inside the sandbox.\n *\n * @returns The absolute path to the user's home directory\n *\n * @example\n * ```typescript\n * const homeDir = await sandbox.getUserHomeDir();\n * console.log(`Home directory: ${homeDir}`);\n * ```\n */\n async getUserHomeDir(): Promise<string> {\n const sandbox = this.instance;\n const homeDir = await sandbox.getUserHomeDir();\n return homeDir ?? \"/home/daytona\";\n }\n\n /**\n * Set the sandbox from an existing Daytona Sandbox instance.\n * Used internally by the static `connect()` method.\n */\n #setFromExisting(\n daytona: Daytona,\n existingSandbox: Sandbox,\n sandboxId: string,\n ): void {\n this.#daytona = daytona;\n this.#sandbox = existingSandbox;\n this.#id = sandboxId;\n }\n\n /**\n * Map Daytona SDK errors to standardized FileOperationError codes.\n *\n * @param error - The error from the Daytona SDK\n * @returns A standardized error code\n */\n #mapError(error: unknown): FileOperationError {\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n\n if (msg.includes(\"not found\") || msg.includes(\"enoent\")) {\n return \"file_not_found\";\n }\n if (msg.includes(\"permission\") || msg.includes(\"eacces\")) {\n return \"permission_denied\";\n }\n if (msg.includes(\"directory\") || msg.includes(\"eisdir\")) {\n return \"is_directory\";\n }\n }\n\n return \"invalid_path\";\n }\n\n /**\n * Create and initialize a new DaytonaSandbox in one step.\n *\n * This is the recommended way to create a sandbox. It combines\n * construction and initialization into a single async operation.\n *\n * @param options - Configuration options for the sandbox\n * @returns An initialized and ready-to-use sandbox\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * cpu: 2,\n * memory: 4,\n * });\n * ```\n */\n static async create(\n options?: DaytonaSandboxOptions,\n ): Promise<DaytonaSandbox> {\n const sandbox = new DaytonaSandbox(options);\n await sandbox.initialize();\n return sandbox;\n }\n\n /**\n * Delete all sandboxes matching the given labels.\n *\n * This is useful for cleaning up stale sandboxes from previous test runs\n * or CI pipelines that may not have shut down cleanly.\n *\n * @param labels - Label key-value pairs to filter sandboxes\n * @param options - Optional auth configuration\n * @returns The number of sandboxes that were deleted\n *\n * @example\n * ```typescript\n * // Clean up all integration-test sandboxes\n * const deleted = await DaytonaSandbox.deleteAll({\n * purpose: \"integration-test\",\n * package: \"@langchain/daytona\",\n * });\n * console.log(`Deleted ${deleted} stale sandboxes`);\n * ```\n */\n static async deleteAll(\n labels: Record<string, string>,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\">,\n ): Promise<number> {\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const { items } = await daytona.list(labels);\n\n const results = await Promise.all(\n items.map((sandbox) =>\n daytona\n .delete(sandbox)\n .then(() => true)\n .catch(() => false),\n ),\n );\n\n return results.filter(Boolean).length;\n }\n\n /**\n * Connect to an existing sandbox by ID.\n *\n * This allows you to resume working with a sandbox that was created\n * earlier or that is still running.\n *\n * @param sandboxId - The ID of the sandbox to connect to\n * @param options - Optional auth configuration (for API key)\n * @returns A connected sandbox instance\n *\n * @example\n * ```typescript\n * // Resume a sandbox from a stored ID\n * const sandbox = await DaytonaSandbox.connect(\"sandbox-abc123\");\n * const result = await sandbox.execute(\"ls -la\");\n * ```\n */\n static async fromId(\n id: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\" | \"timeout\">,\n ): Promise<DaytonaSandbox> {\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const existingSandbox = await daytona.get(id);\n\n const daytonaSandbox = new DaytonaSandbox(options);\n // Set the existing sandbox directly (bypass initialize)\n daytonaSandbox.#setFromExisting(daytona, existingSandbox, id);\n\n return daytonaSandbox;\n } catch (error) {\n throw new DaytonaSandboxError(\n `Sandbox not found: ${id}`,\n \"SANDBOX_NOT_FOUND\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Get a running sandbox by name from a deployed app.\n *\n * @param name - The name of the sandbox\n * @param options - Optional auth configuration\n * @returns A connected sandbox instance\n */\n static async fromName(\n name: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\">,\n ): Promise<DaytonaSandbox> {\n return DaytonaSandbox.fromId(name, options);\n }\n}\n\n/**\n * Async factory function type for creating Daytona Sandbox instances.\n *\n * This is similar to BackendFactory but supports async creation,\n * which is required for Daytona Sandbox since initialization is async.\n */\nexport type AsyncDaytonaSandboxFactory = () => Promise<DaytonaSandbox>;\n\n/**\n * Create an async factory function that creates a new Daytona Sandbox per invocation.\n *\n * Each call to the factory will create and initialize a new sandbox.\n * This is useful when you want fresh, isolated environments for each\n * agent invocation.\n *\n * **Important**: This returns an async factory. For use with middleware that\n * requires synchronous BackendFactory, use `createDaytonaSandboxFactoryFromSandbox()`\n * with a pre-created sandbox instead.\n *\n * @param options - Optional configuration for sandbox creation\n * @returns An async factory function that creates new sandboxes\n *\n * @example\n * ```typescript\n * import { DaytonaSandbox, createDaytonaSandboxFactory } from \"@langchain/daytona\";\n *\n * // Create a factory for new sandboxes\n * const factory = createDaytonaSandboxFactory({ language: \"typescript\" });\n *\n * // Each call creates a new sandbox\n * const sandbox1 = await factory();\n * const sandbox2 = await factory();\n *\n * try {\n * // Use sandboxes...\n * } finally {\n * await sandbox1.close();\n * await sandbox2.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactory(\n options?: DaytonaSandboxOptions,\n): AsyncDaytonaSandboxFactory {\n return async () => {\n return await DaytonaSandbox.create(options);\n };\n}\n\n/**\n * Create a backend factory that reuses an existing Daytona Sandbox.\n *\n * This allows multiple agent invocations to share the same sandbox,\n * avoiding the startup overhead of creating new sandboxes.\n *\n * Important: You are responsible for managing the sandbox lifecycle\n * (calling `close()` when done).\n *\n * @param sandbox - An existing DaytonaSandbox instance (must be initialized)\n * @returns A BackendFactory that returns the provided sandbox\n *\n * @example\n * ```typescript\n * import { createDeepAgent, createFilesystemMiddleware } from \"deepagents\";\n * import { DaytonaSandbox, createDaytonaSandboxFactoryFromSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n *\n * try {\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant.\",\n * middlewares: [\n * createFilesystemMiddleware({\n * backend: createDaytonaSandboxFactoryFromSandbox(sandbox),\n * }),\n * ],\n * });\n *\n * await agent.invoke({ messages: [...] });\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactoryFromSandbox(\n sandbox: DaytonaSandbox,\n): BackendFactory {\n return () => sandbox;\n}\n"],"mappings":";;;;;AAyBA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCxB,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,OAAM,IAAI,MACR,iUAMD;;;;;;;;;;;;;;AAeH,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,QAAO;;;;;;;;;;;;AAaT,SAAgB,mBACd,SACA,QACoB;AACpB,QAAO;EACL,QAAQ,cAAc,QAAQ;EAC9B,QAAQ,cAAc,QAAQ;EAC9B,QAAQ,UAAU,QAAQ,IAAI;EAC/B;;;;;;;;;;AC0EH,MAAM,+BAA+B,OAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BxE,IAAa,sBAAb,MAAa,4BAA4BA,WAAAA,aAAa;;CAEpD,CAAC,gCAAgC;;CAGjC,OAAyB;;;;;;;;CASzB,YACE,SACA,MACA,OACA;AACA,QAAM,SAAS,MAA0B,MAAM;AAH/B,OAAA,OAAA;AACS,OAAA,QAAA;AAIzB,SAAO,eAAe,MAAM,oBAAoB,UAAU;;;;;;;;CAS5D,OAAO,WAA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7D,UAAO;WACA,OAAO;AACd,SAAM,IAAI,oBACR,sBAAsB,MACtB,qBACA,iBAAiB,QAAQ,QAAQ,KAAA,EAClC;;;;;;;;;;CAWL,aAAa,SACX,MACA,SACyB;AACzB,SAAO,eAAe,OAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C/C,SAAgB,4BACd,SAC4B;AAC5B,QAAO,YAAY;AACjB,SAAO,MAAM,eAAe,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyC/C,SAAgB,uCACd,SACgB;AAChB,cAAa"}
package/dist/index.d.cts CHANGED
@@ -92,6 +92,18 @@ interface DaytonaSandboxOptions {
92
92
  * @default 15
93
93
  */
94
94
  autoStopInterval?: number;
95
+ /**
96
+ * Auto-archive interval in minutes.
97
+ *
98
+ * The sandbox will automatically archive after being stopped for this duration.
99
+ */
100
+ autoArchiveInterval?: number;
101
+ /**
102
+ * Auto-delete interval in minutes.
103
+ *
104
+ * The sandbox will automatically delete after being stopped for this duration.
105
+ */
106
+ autoDeleteInterval?: number;
95
107
  /**
96
108
  * Default timeout for command execution in seconds.
97
109
  *
package/dist/index.d.ts CHANGED
@@ -92,6 +92,18 @@ interface DaytonaSandboxOptions {
92
92
  * @default 15
93
93
  */
94
94
  autoStopInterval?: number;
95
+ /**
96
+ * Auto-archive interval in minutes.
97
+ *
98
+ * The sandbox will automatically archive after being stopped for this duration.
99
+ */
100
+ autoArchiveInterval?: number;
101
+ /**
102
+ * Auto-delete interval in minutes.
103
+ *
104
+ * The sandbox will automatically delete after being stopped for this duration.
105
+ */
106
+ autoDeleteInterval?: number;
95
107
  /**
96
108
  * Default timeout for command execution in seconds.
97
109
  *
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Daytona } from "@daytonaio/sdk";
2
2
  import { BaseSandbox, SandboxError } from "deepagents";
3
-
4
3
  //#region src/auth.ts
5
4
  /** Default Daytona API URL */
6
5
  const DEFAULT_API_URL = "https://app.daytona.io/api";
@@ -81,7 +80,6 @@ function getAuthCredentials(options, target) {
81
80
  target: target ?? process.env.DAYTONA_TARGET
82
81
  };
83
82
  }
84
-
85
83
  //#endregion
86
84
  //#region src/types.ts
87
85
  /**
@@ -147,7 +145,6 @@ var DaytonaSandboxError = class DaytonaSandboxError extends SandboxError {
147
145
  return typeof error === "object" && error !== null && error[DAYTONA_SANDBOX_ERROR_SYMBOL] === true;
148
146
  }
149
147
  };
150
-
151
148
  //#endregion
152
149
  //#region src/sandbox.ts
153
150
  /**
@@ -323,6 +320,8 @@ var DaytonaSandbox = class DaytonaSandbox extends BaseSandbox {
323
320
  };
324
321
  if (this.#options.envVars) createOptions.envVars = this.#options.envVars;
325
322
  if (this.#options.autoStopInterval !== void 0) createOptions.autoStopInterval = this.#options.autoStopInterval;
323
+ if (this.#options.autoArchiveInterval !== void 0) createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;
324
+ if (this.#options.autoDeleteInterval !== void 0) createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;
326
325
  if (this.#options.labels) createOptions.labels = this.#options.labels;
327
326
  if (this.#options.resources) createOptions.resources = this.#options.resources;
328
327
  this.#sandbox = await this.#daytona.create(createOptions);
@@ -331,6 +330,8 @@ var DaytonaSandbox = class DaytonaSandbox extends BaseSandbox {
331
330
  if (this.#options.snapshot) createOptions.snapshot = this.#options.snapshot;
332
331
  if (this.#options.envVars) createOptions.envVars = this.#options.envVars;
333
332
  if (this.#options.autoStopInterval !== void 0) createOptions.autoStopInterval = this.#options.autoStopInterval;
333
+ if (this.#options.autoArchiveInterval !== void 0) createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;
334
+ if (this.#options.autoDeleteInterval !== void 0) createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;
334
335
  if (this.#options.labels) createOptions.labels = this.#options.labels;
335
336
  this.#sandbox = await this.#daytona.create(createOptions);
336
337
  }
@@ -761,7 +762,7 @@ function createDaytonaSandboxFactory(options) {
761
762
  function createDaytonaSandboxFactoryFromSandbox(sandbox) {
762
763
  return () => sandbox;
763
764
  }
764
-
765
765
  //#endregion
766
766
  export { DaytonaSandbox, DaytonaSandboxError, createDaytonaSandboxFactory, createDaytonaSandboxFactoryFromSandbox, getAuthApiKey, getAuthApiUrl, getAuthCredentials };
767
+
767
768
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#id","#sandbox","#daytona","#options","#timeout","#uploadInitialFiles","#mapError","#setFromExisting"],"sources":["../src/auth.ts","../src/types.ts","../src/sandbox.ts"],"sourcesContent":["/**\n * Authentication utilities for Daytona Sandbox.\n *\n * This module provides authentication credential resolution for the Daytona SDK.\n *\n * @packageDocumentation\n */\n\nimport type { DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Authentication credentials for Daytona API.\n */\nexport interface DaytonaCredentials {\n /** Daytona API key */\n apiKey: string;\n\n /** Daytona API URL */\n apiUrl: string;\n\n /** Target region */\n target?: string;\n}\n\n/** Default Daytona API URL */\nconst DEFAULT_API_URL = \"https://app.daytona.io/api\";\n\n/**\n * Get the API key for Daytona API.\n *\n * Authentication is resolved in the following priority order:\n *\n * 1. **Explicit API key**: If `options.apiKey` is provided, it is used directly.\n * 2. **DAYTONA_API_KEY**: Environment variable for Daytona API key.\n *\n * If no API key is found, an error is thrown with setup instructions.\n *\n * ## Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API key string\n * @throws {Error} If no API key is available\n *\n * @example\n * ```typescript\n * // With explicit API key\n * const apiKey = getAuthApiKey({ apiKey: \"my-api-key\" });\n *\n * // Using environment variables (auto-detected)\n * const apiKey = getAuthApiKey();\n *\n * // From DaytonaSandboxOptions\n * const options: DaytonaSandboxOptions = {\n * auth: { apiKey: \"my-api-key\" }\n * };\n * const apiKey = getAuthApiKey(options.auth);\n * ```\n */\nexport function getAuthApiKey(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API key in options\n if (options?.apiKey) {\n return options.apiKey;\n }\n\n // Priority 2: DAYTONA_API_KEY environment variable\n const apiKey = process.env.DAYTONA_API_KEY;\n if (apiKey) {\n return apiKey;\n }\n\n // No API key found - throw descriptive error\n throw new Error(\n \"Daytona authentication required. Provide an API key using one of these methods:\\n\\n\" +\n \"1. Set DAYTONA_API_KEY environment variable:\\n\" +\n \" Get your API key from https://app.daytona.io\\n\" +\n \" Run: export DAYTONA_API_KEY=your_api_key_here\\n\\n\" +\n \"2. Pass API key directly in options:\\n\" +\n \" new DaytonaSandbox({ auth: { apiKey: '...' } })\",\n );\n}\n\n/**\n * Get the API URL for Daytona API.\n *\n * URL is resolved in the following priority order:\n *\n * 1. **Explicit API URL**: If `options.apiUrl` is provided, it is used directly.\n * 2. **DAYTONA_API_URL**: Environment variable for Daytona API URL.\n * 3. **Default**: Uses the default Daytona API URL.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API URL string\n */\nexport function getAuthApiUrl(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API URL in options\n if (options?.apiUrl) {\n return options.apiUrl;\n }\n\n // Priority 2: DAYTONA_API_URL environment variable\n const apiUrl = process.env.DAYTONA_API_URL;\n if (apiUrl) {\n return apiUrl;\n }\n\n // Priority 3: Default URL\n return DEFAULT_API_URL;\n}\n\n/**\n * Get authentication credentials for Daytona API.\n *\n * This function returns the credentials needed for the Daytona SDK.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @param target - Optional target region\n * @returns Complete authentication credentials\n * @throws {Error} If no API key is available\n */\nexport function getAuthCredentials(\n options?: DaytonaSandboxOptions[\"auth\"],\n target?: string,\n): DaytonaCredentials {\n return {\n apiKey: getAuthApiKey(options),\n apiUrl: getAuthApiUrl(options),\n target: target ?? process.env.DAYTONA_TARGET,\n };\n}\n","/**\n * Type definitions for the Daytona Sandbox backend.\n *\n * This module contains all type definitions for the @langchain/daytona package,\n * including options and error types.\n */\n\nimport { type SandboxErrorCode, SandboxError } from \"deepagents\";\n\n/**\n * Supported target regions for Daytona sandboxes.\n *\n * - `us`: United States\n * - `eu`: Europe\n */\nexport type DaytonaSandboxTarget = \"us\" | \"eu\";\n\n/**\n * Configuration options for creating a Daytona Sandbox.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * timeout: 300, // 5 minutes\n * target: \"us\",\n * };\n * ```\n */\nexport interface DaytonaSandboxOptions {\n /**\n * Primary language for code execution in the sandbox.\n *\n * Determines the runtime environment and code execution tooling.\n *\n * @default \"typescript\"\n */\n language?: \"typescript\" | \"python\" | \"javascript\";\n\n /**\n * Custom environment variables to set in the sandbox.\n *\n * These variables will be available to all commands and code executed\n * in the sandbox.\n *\n * @example\n * ```typescript\n * envVars: {\n * NODE_ENV: \"development\",\n * API_KEY: \"secret\"\n * }\n * ```\n */\n envVars?: Record<string, string>;\n\n /**\n * Resource allocation for the sandbox.\n *\n * When specifying resources, you must also specify an `image`.\n * Resources cannot be customized when using the default snapshot-based sandbox.\n *\n * @example\n * ```typescript\n * resources: { cpu: 2, memory: 4, disk: 20 }\n * ```\n */\n resources?: {\n /** Number of CPUs to allocate */\n cpu?: number;\n /** Amount of memory in GiB */\n memory?: number;\n /** Amount of disk space in GiB */\n disk?: number;\n };\n\n /**\n * Custom Docker image to use for the sandbox.\n *\n * When specified, creates a sandbox from this image instead of the default snapshot.\n * This is required when you want to customize resources.\n *\n * @example \"node:20\" or \"python:3.12\"\n */\n image?: string;\n\n /**\n * Snapshot name to use for the sandbox.\n *\n * When specified, creates a sandbox from this snapshot.\n * Cannot be used together with `image`.\n */\n snapshot?: string;\n\n /**\n * Target region where the sandbox will be created.\n *\n * @default \"us\"\n */\n target?: DaytonaSandboxTarget;\n\n /**\n * Auto-stop interval in minutes.\n *\n * The sandbox will automatically stop after being idle for this duration.\n * Set to 0 to disable auto-stop.\n *\n * @default 15\n */\n autoStopInterval?: number;\n\n /**\n * Default timeout for command execution in seconds.\n *\n * @default 300 (5 minutes)\n */\n timeout?: number;\n\n /**\n * Custom labels to attach to the sandbox.\n *\n * Labels can be used for organizing and filtering sandboxes.\n */\n labels?: Record<string, string>;\n\n /**\n * Initial files to create in the sandbox after initialization.\n *\n * A map of file paths to their contents. Files will be created\n * in the sandbox filesystem before any commands are executed.\n * Parent directories are created automatically.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * initialFiles: {\n * \"/app/index.js\": \"console.log('Hello')\",\n * \"/app/package.json\": '{\"name\": \"test\"}',\n * },\n * };\n * ```\n */\n initialFiles?: Record<string, string>;\n\n /**\n * Authentication configuration for Daytona API.\n *\n * ### Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * Or pass the API key directly in this auth configuration.\n */\n auth?: {\n /**\n * Daytona API key.\n * If not provided, reads from `DAYTONA_API_KEY` environment variable.\n */\n apiKey?: string;\n\n /**\n * Daytona API URL.\n * If not provided, reads from `DAYTONA_API_URL` environment variable\n * or uses the default Daytona API URL.\n *\n * @default \"https://app.daytona.io/api\"\n */\n apiUrl?: string;\n };\n}\n\n/**\n * Error codes for Daytona Sandbox operations.\n *\n * Used to identify specific error conditions and handle them appropriately.\n */\nexport type DaytonaSandboxErrorCode =\n | SandboxErrorCode\n /** Authentication failed - check API key configuration */\n | \"AUTHENTICATION_FAILED\"\n /** Failed to create sandbox - check options and quotas */\n | \"SANDBOX_CREATION_FAILED\"\n /** Sandbox not found - may have been deleted or expired */\n | \"SANDBOX_NOT_FOUND\"\n /** Sandbox is not in started state */\n | \"SANDBOX_NOT_STARTED\"\n /** Resource limits exceeded (CPU, memory, storage) */\n | \"RESOURCE_LIMIT_EXCEEDED\";\n\nconst DAYTONA_SANDBOX_ERROR_SYMBOL = Symbol.for(\"daytona.sandbox.error\");\n\n/**\n * Custom error class for Daytona Sandbox operations.\n *\n * Provides structured error information including:\n * - Human-readable message\n * - Error code for programmatic handling\n * - Original cause for debugging\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"some command\");\n * } catch (error) {\n * if (error instanceof DaytonaSandboxError) {\n * switch (error.code) {\n * case \"NOT_INITIALIZED\":\n * await sandbox.initialize();\n * break;\n * case \"COMMAND_TIMEOUT\":\n * console.error(\"Command took too long\");\n * break;\n * default:\n * throw error;\n * }\n * }\n * }\n * ```\n */\nexport class DaytonaSandboxError extends SandboxError {\n /** Symbol for identifying sandbox error instances */\n [DAYTONA_SANDBOX_ERROR_SYMBOL] = true as const;\n\n /** Error name for instanceof checks and logging */\n override readonly name = \"DaytonaSandboxError\";\n\n /**\n * Creates a new DaytonaSandboxError.\n *\n * @param message - Human-readable error description\n * @param code - Structured error code for programmatic handling\n * @param cause - Original error that caused this error (for debugging)\n */\n constructor(\n message: string,\n public readonly code: DaytonaSandboxErrorCode,\n public override readonly cause?: Error,\n ) {\n super(message, code as SandboxErrorCode, cause);\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, DaytonaSandboxError.prototype);\n }\n\n /**\n * Checks if the error is an instance of DaytonaSandboxError.\n *\n * @param error - The error to check\n * @returns True if the error is an instance of DaytonaSandboxError, false otherwise\n */\n static isInstance(error: unknown): error is DaytonaSandboxError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as Record<symbol, unknown>)[DAYTONA_SANDBOX_ERROR_SYMBOL] === true\n );\n }\n}\n","/* eslint-disable no-instanceof/no-instanceof */\n/**\n * Daytona Sandbox implementation of the SandboxBackendProtocol.\n *\n * This module provides a Daytona Sandbox backend for deepagents, enabling agents\n * to execute commands, read/write files, and manage isolated sandbox environments\n * using Daytona's infrastructure.\n *\n * @packageDocumentation\n */\n\nimport { Daytona, type Sandbox } from \"@daytonaio/sdk\";\nimport {\n BaseSandbox,\n type ExecuteResponse,\n type FileDownloadResponse,\n type FileOperationError,\n type FileUploadResponse,\n type BackendFactory,\n} from \"deepagents\";\n\nimport { getAuthCredentials } from \"./auth.js\";\nimport { DaytonaSandboxError, type DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Daytona Sandbox backend for deepagents.\n *\n * Extends `BaseSandbox` to provide command execution, file operations, and\n * sandbox lifecycle management using Daytona's SDK.\n *\n * ## Basic Usage\n *\n * ```typescript\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * timeout: 300,\n * });\n *\n * try {\n * // Execute commands\n * const result = await sandbox.execute(\"node --version\");\n * console.log(result.output);\n * } finally {\n * // Always cleanup\n * await sandbox.close();\n * }\n * ```\n *\n * ## Using with DeepAgent\n *\n * ```typescript\n * import { createDeepAgent } from \"deepagents\";\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * const sandbox = await DaytonaSandbox.create();\n *\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant with sandbox access.\",\n * backend: sandbox,\n * });\n * ```\n */\nexport class DaytonaSandbox extends BaseSandbox {\n /** Private reference to the Daytona client */\n #daytona: Daytona | null = null;\n\n /** Private reference to the underlying Daytona Sandbox instance */\n #sandbox: Sandbox | null = null;\n\n /** Configuration options for this sandbox */\n #options: DaytonaSandboxOptions;\n\n /** Unique identifier for this sandbox instance */\n #id: string;\n\n /** Default timeout for command execution in seconds */\n #timeout: number;\n\n /**\n * Get the unique identifier for this sandbox.\n *\n * Before initialization, returns a temporary ID.\n * After initialization, returns the actual Daytona sandbox ID.\n */\n get id(): string {\n return this.#id;\n }\n\n /**\n * Get the underlying Daytona Sandbox instance.\n *\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaSdk = sandbox.sandbox; // Access the raw SDK\n * ```\n */\n get instance(): Sandbox {\n if (!this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#sandbox;\n }\n\n /**\n * Get the underlying Daytona client instance.\n *\n * @throws {DaytonaSandboxError} If the client is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaClient = sandbox.client; // Access the raw Daytona client\n * ```\n */\n get client(): Daytona {\n if (!this.#daytona) {\n throw new DaytonaSandboxError(\n \"Daytona client not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#daytona;\n }\n\n /**\n * Check if the sandbox is initialized and running.\n */\n get isRunning(): boolean {\n return this.#sandbox !== null;\n }\n\n /**\n * Create a new DaytonaSandbox instance.\n *\n * Note: This only creates the instance. Call `initialize()` to actually\n * create the Daytona Sandbox, or use the static `DaytonaSandbox.create()` method.\n *\n * @param options - Configuration options for the sandbox\n *\n * @example\n * ```typescript\n * // Two-step initialization\n * const sandbox = new DaytonaSandbox({ language: \"typescript\" });\n * await sandbox.initialize();\n *\n * // Or use the factory method\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n * ```\n */\n constructor(options: DaytonaSandboxOptions = {}) {\n super();\n\n // Set defaults\n this.#options = {\n language: \"typescript\",\n timeout: 300,\n ...options,\n };\n\n this.#timeout = this.#options.timeout ?? 300;\n\n // Generate temporary ID until initialized\n this.#id = `daytona-sandbox-${Date.now()}`;\n }\n\n /**\n * Initialize the sandbox by creating a new Daytona Sandbox instance.\n *\n * This method authenticates with Daytona and provisions a new sandbox.\n * After initialization, the `id` property will reflect the actual sandbox ID.\n *\n * @throws {DaytonaSandboxError} If already initialized (`ALREADY_INITIALIZED`)\n * @throws {DaytonaSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)\n * @throws {DaytonaSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)\n *\n * @example\n * ```typescript\n * const sandbox = new DaytonaSandbox();\n * await sandbox.initialize();\n * console.log(`Sandbox ID: ${sandbox.id}`);\n * ```\n */\n async initialize(): Promise<void> {\n // Prevent double initialization\n if (this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox is already initialized. Each DaytonaSandbox instance can only be initialized once.\",\n \"ALREADY_INITIALIZED\",\n );\n }\n\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(\n this.#options.auth,\n this.#options.target,\n );\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n // Create Daytona client\n this.#daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n // Determine if we're creating from image or snapshot\n if (this.#options.image) {\n // Create from image (allows custom resources)\n const createOptions: {\n image: string;\n language?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n labels?: Record<string, string>;\n resources?: { cpu?: number; memory?: number; disk?: number };\n } = {\n image: this.#options.image,\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n if (this.#options.resources) {\n createOptions.resources = this.#options.resources;\n }\n\n // Create the sandbox from image\n this.#sandbox = await this.#daytona.create(createOptions);\n } else {\n // Create from snapshot (default, simpler approach)\n const createOptions: {\n language?: string;\n snapshot?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n labels?: Record<string, string>;\n } = {\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.snapshot) {\n createOptions.snapshot = this.#options.snapshot;\n }\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n // Create the sandbox from snapshot\n this.#sandbox = await this.#daytona.create(createOptions);\n }\n\n // Update ID to the actual sandbox ID\n this.#id = this.#sandbox.id;\n\n // Upload initial files if provided\n if (this.#options.initialFiles) {\n await this.#uploadInitialFiles(this.#options.initialFiles);\n }\n } catch (error) {\n throw new DaytonaSandboxError(\n `Failed to create Daytona Sandbox: ${error instanceof Error ? error.message : String(error)}`,\n \"SANDBOX_CREATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload initial files to the sandbox.\n *\n * @param files - A map of file paths to their string contents\n */\n async #uploadInitialFiles(files: Record<string, string>): Promise<void> {\n const encoder = new TextEncoder();\n const fileEntries: Array<[string, Uint8Array]> = Object.entries(files).map(\n ([path, content]) => [path, encoder.encode(content)],\n );\n\n const results = await this.uploadFiles(fileEntries);\n\n // Check for any errors during upload\n const errors = results.filter((r) => r.error !== null);\n if (errors.length > 0) {\n const errorPaths = errors.map((e) => `${e.path}: ${e.error}`).join(\", \");\n throw new DaytonaSandboxError(\n `Failed to upload initial files: ${errorPaths}`,\n \"FILE_OPERATION_FAILED\",\n );\n }\n }\n\n /**\n * Execute a command in the sandbox.\n *\n * Commands are run using the sandbox's shell.\n *\n * @param command - The shell command to execute\n * @returns Execution result with output, exit code, and truncation flag\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const result = await sandbox.execute(\"echo 'Hello World'\");\n * console.log(result.output); // \"Hello World\\n\"\n * console.log(result.exitCode); // 0\n * ```\n */\n async execute(command: string): Promise<ExecuteResponse> {\n const sandbox = this.instance; // Throws if not initialized\n\n try {\n const response = await sandbox.process.executeCommand(\n command,\n undefined,\n undefined,\n this.#timeout,\n );\n\n return {\n output: response.result ?? \"\",\n exitCode: response.exitCode ?? 0,\n truncated: false,\n };\n } catch (error) {\n // Check for timeout\n if (error instanceof Error && error.message.includes(\"timeout\")) {\n throw new DaytonaSandboxError(\n `Command timed out: ${command}`,\n \"COMMAND_TIMEOUT\",\n error,\n );\n }\n\n throw new DaytonaSandboxError(\n `Command execution failed: ${error instanceof Error ? error.message : String(error)}`,\n \"COMMAND_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload files to the sandbox.\n *\n * Files are written to the sandbox filesystem. Parent directories are\n * created automatically if they don't exist.\n *\n * @param files - Array of [path, content] tuples to upload\n * @returns Upload result for each file, with success or error status\n *\n * @example\n * ```typescript\n * const encoder = new TextEncoder();\n * const results = await sandbox.uploadFiles([\n * [\"src/index.js\", encoder.encode(\"console.log('Hello')\")],\n * [\"package.json\", encoder.encode('{\"name\": \"test\"}')],\n * ]);\n * ```\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileUploadResponse[] = [];\n\n for (const [path, content] of files) {\n try {\n // Ensure parent directory exists\n const parentDir = path.substring(0, path.lastIndexOf(\"/\"));\n if (parentDir) {\n await sandbox.fs.createFolder(parentDir, \"755\");\n }\n\n // Upload the file content\n const buffer = Buffer.from(content);\n await sandbox.fs.uploadFile(buffer, path);\n results.push({ path, error: null });\n } catch (error) {\n results.push({ path, error: this.#mapError(error) });\n }\n }\n\n return results;\n }\n\n /**\n * Download files from the sandbox.\n *\n * Each file is read individually, allowing partial success when some\n * files exist and others don't.\n *\n * @param paths - Array of file paths to download\n * @returns Download result for each file, with content or error\n *\n * @example\n * ```typescript\n * const results = await sandbox.downloadFiles([\"src/index.js\", \"missing.txt\"]);\n * for (const result of results) {\n * if (result.content) {\n * console.log(new TextDecoder().decode(result.content));\n * } else {\n * console.error(`Error: ${result.error}`);\n * }\n * }\n * ```\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n try {\n const buffer = await sandbox.fs.downloadFile(path);\n results.push({\n path,\n content: new Uint8Array(buffer),\n error: null,\n });\n } catch (error) {\n results.push({\n path,\n content: null,\n error: this.#mapError(error),\n });\n }\n }\n\n return results;\n }\n\n /**\n * Close the sandbox and release all resources.\n *\n * After closing, the sandbox cannot be used again. The sandbox is deleted\n * from Daytona's infrastructure.\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"npm run build\");\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\n async close(): Promise<void> {\n if (this.#sandbox) {\n try {\n await this.#sandbox.delete();\n } finally {\n this.#sandbox = null;\n this.#daytona = null;\n }\n }\n }\n\n /**\n * Stop the sandbox without deleting it.\n *\n * The sandbox can be restarted later using `start()`.\n *\n * @example\n * ```typescript\n * await sandbox.stop();\n * // Later...\n * await sandbox.start();\n * ```\n */\n async stop(): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.stop();\n }\n }\n\n /**\n * Start a stopped sandbox.\n *\n * @param timeout - Maximum time to wait in seconds (default: 60)\n *\n * @example\n * ```typescript\n * await sandbox.start();\n * console.log(\"Sandbox is now running\");\n * ```\n */\n async start(timeout: number = 60): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.start(timeout);\n }\n }\n\n /**\n * Forcefully terminate and delete the sandbox.\n *\n * Use this when you need to immediately stop the sandbox.\n *\n * @example\n * ```typescript\n * await sandbox.kill();\n * ```\n */\n async kill(): Promise<void> {\n await this.close();\n }\n\n /**\n * Get the working directory path inside the sandbox.\n *\n * @returns The absolute path to the sandbox working directory\n *\n * @example\n * ```typescript\n * const workDir = await sandbox.getWorkDir();\n * console.log(`Working directory: ${workDir}`);\n * ```\n */\n async getWorkDir(): Promise<string> {\n const sandbox = this.instance;\n const workDir = await sandbox.getWorkDir();\n return workDir ?? \"/home/daytona\";\n }\n\n /**\n * Get the user's home directory path inside the sandbox.\n *\n * @returns The absolute path to the user's home directory\n *\n * @example\n * ```typescript\n * const homeDir = await sandbox.getUserHomeDir();\n * console.log(`Home directory: ${homeDir}`);\n * ```\n */\n async getUserHomeDir(): Promise<string> {\n const sandbox = this.instance;\n const homeDir = await sandbox.getUserHomeDir();\n return homeDir ?? \"/home/daytona\";\n }\n\n /**\n * Set the sandbox from an existing Daytona Sandbox instance.\n * Used internally by the static `connect()` method.\n */\n #setFromExisting(\n daytona: Daytona,\n existingSandbox: Sandbox,\n sandboxId: string,\n ): void {\n this.#daytona = daytona;\n this.#sandbox = existingSandbox;\n this.#id = sandboxId;\n }\n\n /**\n * Map Daytona SDK errors to standardized FileOperationError codes.\n *\n * @param error - The error from the Daytona SDK\n * @returns A standardized error code\n */\n #mapError(error: unknown): FileOperationError {\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n\n if (msg.includes(\"not found\") || msg.includes(\"enoent\")) {\n return \"file_not_found\";\n }\n if (msg.includes(\"permission\") || msg.includes(\"eacces\")) {\n return \"permission_denied\";\n }\n if (msg.includes(\"directory\") || msg.includes(\"eisdir\")) {\n return \"is_directory\";\n }\n }\n\n return \"invalid_path\";\n }\n\n /**\n * Create and initialize a new DaytonaSandbox in one step.\n *\n * This is the recommended way to create a sandbox. It combines\n * construction and initialization into a single async operation.\n *\n * @param options - Configuration options for the sandbox\n * @returns An initialized and ready-to-use sandbox\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * cpu: 2,\n * memory: 4,\n * });\n * ```\n */\n static async create(\n options?: DaytonaSandboxOptions,\n ): Promise<DaytonaSandbox> {\n const sandbox = new DaytonaSandbox(options);\n await sandbox.initialize();\n return sandbox;\n }\n\n /**\n * Delete all sandboxes matching the given labels.\n *\n * This is useful for cleaning up stale sandboxes from previous test runs\n * or CI pipelines that may not have shut down cleanly.\n *\n * @param labels - Label key-value pairs to filter sandboxes\n * @param options - Optional auth configuration\n * @returns The number of sandboxes that were deleted\n *\n * @example\n * ```typescript\n * // Clean up all integration-test sandboxes\n * const deleted = await DaytonaSandbox.deleteAll({\n * purpose: \"integration-test\",\n * package: \"@langchain/daytona\",\n * });\n * console.log(`Deleted ${deleted} stale sandboxes`);\n * ```\n */\n static async deleteAll(\n labels: Record<string, string>,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\">,\n ): Promise<number> {\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const { items } = await daytona.list(labels);\n\n const results = await Promise.all(\n items.map((sandbox) =>\n daytona\n .delete(sandbox)\n .then(() => true)\n .catch(() => false),\n ),\n );\n\n return results.filter(Boolean).length;\n }\n\n /**\n * Connect to an existing sandbox by ID.\n *\n * This allows you to resume working with a sandbox that was created\n * earlier or that is still running.\n *\n * @param sandboxId - The ID of the sandbox to connect to\n * @param options - Optional auth configuration (for API key)\n * @returns A connected sandbox instance\n *\n * @example\n * ```typescript\n * // Resume a sandbox from a stored ID\n * const sandbox = await DaytonaSandbox.connect(\"sandbox-abc123\");\n * const result = await sandbox.execute(\"ls -la\");\n * ```\n */\n static async fromId(\n id: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\" | \"timeout\">,\n ): Promise<DaytonaSandbox> {\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const existingSandbox = await daytona.get(id);\n\n const daytonaSandbox = new DaytonaSandbox(options);\n // Set the existing sandbox directly (bypass initialize)\n daytonaSandbox.#setFromExisting(daytona, existingSandbox, id);\n\n return daytonaSandbox;\n } catch (error) {\n throw new DaytonaSandboxError(\n `Sandbox not found: ${id}`,\n \"SANDBOX_NOT_FOUND\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Get a running sandbox by name from a deployed app.\n *\n * @param name - The name of the sandbox\n * @param options - Optional auth configuration\n * @returns A connected sandbox instance\n */\n static async fromName(\n name: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\">,\n ): Promise<DaytonaSandbox> {\n return DaytonaSandbox.fromId(name, options);\n }\n}\n\n/**\n * Async factory function type for creating Daytona Sandbox instances.\n *\n * This is similar to BackendFactory but supports async creation,\n * which is required for Daytona Sandbox since initialization is async.\n */\nexport type AsyncDaytonaSandboxFactory = () => Promise<DaytonaSandbox>;\n\n/**\n * Create an async factory function that creates a new Daytona Sandbox per invocation.\n *\n * Each call to the factory will create and initialize a new sandbox.\n * This is useful when you want fresh, isolated environments for each\n * agent invocation.\n *\n * **Important**: This returns an async factory. For use with middleware that\n * requires synchronous BackendFactory, use `createDaytonaSandboxFactoryFromSandbox()`\n * with a pre-created sandbox instead.\n *\n * @param options - Optional configuration for sandbox creation\n * @returns An async factory function that creates new sandboxes\n *\n * @example\n * ```typescript\n * import { DaytonaSandbox, createDaytonaSandboxFactory } from \"@langchain/daytona\";\n *\n * // Create a factory for new sandboxes\n * const factory = createDaytonaSandboxFactory({ language: \"typescript\" });\n *\n * // Each call creates a new sandbox\n * const sandbox1 = await factory();\n * const sandbox2 = await factory();\n *\n * try {\n * // Use sandboxes...\n * } finally {\n * await sandbox1.close();\n * await sandbox2.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactory(\n options?: DaytonaSandboxOptions,\n): AsyncDaytonaSandboxFactory {\n return async () => {\n return await DaytonaSandbox.create(options);\n };\n}\n\n/**\n * Create a backend factory that reuses an existing Daytona Sandbox.\n *\n * This allows multiple agent invocations to share the same sandbox,\n * avoiding the startup overhead of creating new sandboxes.\n *\n * Important: You are responsible for managing the sandbox lifecycle\n * (calling `close()` when done).\n *\n * @param sandbox - An existing DaytonaSandbox instance (must be initialized)\n * @returns A BackendFactory that returns the provided sandbox\n *\n * @example\n * ```typescript\n * import { createDeepAgent, createFilesystemMiddleware } from \"deepagents\";\n * import { DaytonaSandbox, createDaytonaSandboxFactoryFromSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n *\n * try {\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant.\",\n * middlewares: [\n * createFilesystemMiddleware({\n * backend: createDaytonaSandboxFactoryFromSandbox(sandbox),\n * }),\n * ],\n * });\n *\n * await agent.invoke({ messages: [...] });\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactoryFromSandbox(\n sandbox: DaytonaSandbox,\n): BackendFactory {\n return () => sandbox;\n}\n"],"mappings":";;;;;AAyBA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCxB,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,OAAM,IAAI,MACR,iUAMD;;;;;;;;;;;;;;AAeH,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,QAAO;;;;;;;;;;;;AAaT,SAAgB,mBACd,SACA,QACoB;AACpB,QAAO;EACL,QAAQ,cAAc,QAAQ;EAC9B,QAAQ,cA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,IAAI,eAAe,QAAQ;AAElD,mBAAeO,gBAAiB,SAAS,iBAAiB,GAAG;AAE7D,UAAO;WACA,OAAO;AACd,SAAM,IAAI,oBACR,sBAAsB,MACtB,qBACA,iBAAiB,QAAQ,QAAQ,OAClC;;;;;;;;;;CAWL,aAAa,SACX,MACA,SACyB;AACzB,SAAO,eAAe,OAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C/C,SAAgB,4BACd,SAC4B;AAC5B,QAAO,YAAY;AACjB,SAAO,MAAM,eAAe,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyC/C,SAAgB,uCACd,SACgB;AAChB,cAAa"}
1
+ {"version":3,"file":"index.js","names":["#id","#sandbox","#daytona","#options","#timeout","#uploadInitialFiles","#mapError","#setFromExisting"],"sources":["../src/auth.ts","../src/types.ts","../src/sandbox.ts"],"sourcesContent":["/**\n * Authentication utilities for Daytona Sandbox.\n *\n * This module provides authentication credential resolution for the Daytona SDK.\n *\n * @packageDocumentation\n */\n\nimport type { DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Authentication credentials for Daytona API.\n */\nexport interface DaytonaCredentials {\n /** Daytona API key */\n apiKey: string;\n\n /** Daytona API URL */\n apiUrl: string;\n\n /** Target region */\n target?: string;\n}\n\n/** Default Daytona API URL */\nconst DEFAULT_API_URL = \"https://app.daytona.io/api\";\n\n/**\n * Get the API key for Daytona API.\n *\n * Authentication is resolved in the following priority order:\n *\n * 1. **Explicit API key**: If `options.apiKey` is provided, it is used directly.\n * 2. **DAYTONA_API_KEY**: Environment variable for Daytona API key.\n *\n * If no API key is found, an error is thrown with setup instructions.\n *\n * ## Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API key string\n * @throws {Error} If no API key is available\n *\n * @example\n * ```typescript\n * // With explicit API key\n * const apiKey = getAuthApiKey({ apiKey: \"my-api-key\" });\n *\n * // Using environment variables (auto-detected)\n * const apiKey = getAuthApiKey();\n *\n * // From DaytonaSandboxOptions\n * const options: DaytonaSandboxOptions = {\n * auth: { apiKey: \"my-api-key\" }\n * };\n * const apiKey = getAuthApiKey(options.auth);\n * ```\n */\nexport function getAuthApiKey(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API key in options\n if (options?.apiKey) {\n return options.apiKey;\n }\n\n // Priority 2: DAYTONA_API_KEY environment variable\n const apiKey = process.env.DAYTONA_API_KEY;\n if (apiKey) {\n return apiKey;\n }\n\n // No API key found - throw descriptive error\n throw new Error(\n \"Daytona authentication required. Provide an API key using one of these methods:\\n\\n\" +\n \"1. Set DAYTONA_API_KEY environment variable:\\n\" +\n \" Get your API key from https://app.daytona.io\\n\" +\n \" Run: export DAYTONA_API_KEY=your_api_key_here\\n\\n\" +\n \"2. Pass API key directly in options:\\n\" +\n \" new DaytonaSandbox({ auth: { apiKey: '...' } })\",\n );\n}\n\n/**\n * Get the API URL for Daytona API.\n *\n * URL is resolved in the following priority order:\n *\n * 1. **Explicit API URL**: If `options.apiUrl` is provided, it is used directly.\n * 2. **DAYTONA_API_URL**: Environment variable for Daytona API URL.\n * 3. **Default**: Uses the default Daytona API URL.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @returns The API URL string\n */\nexport function getAuthApiUrl(options?: DaytonaSandboxOptions[\"auth\"]): string {\n // Priority 1: Explicit API URL in options\n if (options?.apiUrl) {\n return options.apiUrl;\n }\n\n // Priority 2: DAYTONA_API_URL environment variable\n const apiUrl = process.env.DAYTONA_API_URL;\n if (apiUrl) {\n return apiUrl;\n }\n\n // Priority 3: Default URL\n return DEFAULT_API_URL;\n}\n\n/**\n * Get authentication credentials for Daytona API.\n *\n * This function returns the credentials needed for the Daytona SDK.\n *\n * @param options - Optional authentication configuration from DaytonaSandboxOptions\n * @param target - Optional target region\n * @returns Complete authentication credentials\n * @throws {Error} If no API key is available\n */\nexport function getAuthCredentials(\n options?: DaytonaSandboxOptions[\"auth\"],\n target?: string,\n): DaytonaCredentials {\n return {\n apiKey: getAuthApiKey(options),\n apiUrl: getAuthApiUrl(options),\n target: target ?? process.env.DAYTONA_TARGET,\n };\n}\n","/**\n * Type definitions for the Daytona Sandbox backend.\n *\n * This module contains all type definitions for the @langchain/daytona package,\n * including options and error types.\n */\n\nimport { type SandboxErrorCode, SandboxError } from \"deepagents\";\n\n/**\n * Supported target regions for Daytona sandboxes.\n *\n * - `us`: United States\n * - `eu`: Europe\n */\nexport type DaytonaSandboxTarget = \"us\" | \"eu\";\n\n/**\n * Configuration options for creating a Daytona Sandbox.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * timeout: 300, // 5 minutes\n * target: \"us\",\n * };\n * ```\n */\nexport interface DaytonaSandboxOptions {\n /**\n * Primary language for code execution in the sandbox.\n *\n * Determines the runtime environment and code execution tooling.\n *\n * @default \"typescript\"\n */\n language?: \"typescript\" | \"python\" | \"javascript\";\n\n /**\n * Custom environment variables to set in the sandbox.\n *\n * These variables will be available to all commands and code executed\n * in the sandbox.\n *\n * @example\n * ```typescript\n * envVars: {\n * NODE_ENV: \"development\",\n * API_KEY: \"secret\"\n * }\n * ```\n */\n envVars?: Record<string, string>;\n\n /**\n * Resource allocation for the sandbox.\n *\n * When specifying resources, you must also specify an `image`.\n * Resources cannot be customized when using the default snapshot-based sandbox.\n *\n * @example\n * ```typescript\n * resources: { cpu: 2, memory: 4, disk: 20 }\n * ```\n */\n resources?: {\n /** Number of CPUs to allocate */\n cpu?: number;\n /** Amount of memory in GiB */\n memory?: number;\n /** Amount of disk space in GiB */\n disk?: number;\n };\n\n /**\n * Custom Docker image to use for the sandbox.\n *\n * When specified, creates a sandbox from this image instead of the default snapshot.\n * This is required when you want to customize resources.\n *\n * @example \"node:20\" or \"python:3.12\"\n */\n image?: string;\n\n /**\n * Snapshot name to use for the sandbox.\n *\n * When specified, creates a sandbox from this snapshot.\n * Cannot be used together with `image`.\n */\n snapshot?: string;\n\n /**\n * Target region where the sandbox will be created.\n *\n * @default \"us\"\n */\n target?: DaytonaSandboxTarget;\n\n /**\n * Auto-stop interval in minutes.\n *\n * The sandbox will automatically stop after being idle for this duration.\n * Set to 0 to disable auto-stop.\n *\n * @default 15\n */\n autoStopInterval?: number;\n\n /**\n * Auto-archive interval in minutes.\n *\n * The sandbox will automatically archive after being stopped for this duration.\n */\n autoArchiveInterval?: number;\n\n /**\n * Auto-delete interval in minutes.\n *\n * The sandbox will automatically delete after being stopped for this duration.\n */\n autoDeleteInterval?: number;\n\n /**\n * Default timeout for command execution in seconds.\n *\n * @default 300 (5 minutes)\n */\n timeout?: number;\n\n /**\n * Custom labels to attach to the sandbox.\n *\n * Labels can be used for organizing and filtering sandboxes.\n */\n labels?: Record<string, string>;\n\n /**\n * Initial files to create in the sandbox after initialization.\n *\n * A map of file paths to their contents. Files will be created\n * in the sandbox filesystem before any commands are executed.\n * Parent directories are created automatically.\n *\n * @example\n * ```typescript\n * const options: DaytonaSandboxOptions = {\n * language: \"typescript\",\n * initialFiles: {\n * \"/app/index.js\": \"console.log('Hello')\",\n * \"/app/package.json\": '{\"name\": \"test\"}',\n * },\n * };\n * ```\n */\n initialFiles?: Record<string, string>;\n\n /**\n * Authentication configuration for Daytona API.\n *\n * ### Environment Variable Setup\n *\n * ```bash\n * # Get your API key from https://app.daytona.io\n * export DAYTONA_API_KEY=your_api_key_here\n * ```\n *\n * Or pass the API key directly in this auth configuration.\n */\n auth?: {\n /**\n * Daytona API key.\n * If not provided, reads from `DAYTONA_API_KEY` environment variable.\n */\n apiKey?: string;\n\n /**\n * Daytona API URL.\n * If not provided, reads from `DAYTONA_API_URL` environment variable\n * or uses the default Daytona API URL.\n *\n * @default \"https://app.daytona.io/api\"\n */\n apiUrl?: string;\n };\n}\n\n/**\n * Error codes for Daytona Sandbox operations.\n *\n * Used to identify specific error conditions and handle them appropriately.\n */\nexport type DaytonaSandboxErrorCode =\n | SandboxErrorCode\n /** Authentication failed - check API key configuration */\n | \"AUTHENTICATION_FAILED\"\n /** Failed to create sandbox - check options and quotas */\n | \"SANDBOX_CREATION_FAILED\"\n /** Sandbox not found - may have been deleted or expired */\n | \"SANDBOX_NOT_FOUND\"\n /** Sandbox is not in started state */\n | \"SANDBOX_NOT_STARTED\"\n /** Resource limits exceeded (CPU, memory, storage) */\n | \"RESOURCE_LIMIT_EXCEEDED\";\n\nconst DAYTONA_SANDBOX_ERROR_SYMBOL = Symbol.for(\"daytona.sandbox.error\");\n\n/**\n * Custom error class for Daytona Sandbox operations.\n *\n * Provides structured error information including:\n * - Human-readable message\n * - Error code for programmatic handling\n * - Original cause for debugging\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"some command\");\n * } catch (error) {\n * if (error instanceof DaytonaSandboxError) {\n * switch (error.code) {\n * case \"NOT_INITIALIZED\":\n * await sandbox.initialize();\n * break;\n * case \"COMMAND_TIMEOUT\":\n * console.error(\"Command took too long\");\n * break;\n * default:\n * throw error;\n * }\n * }\n * }\n * ```\n */\nexport class DaytonaSandboxError extends SandboxError {\n /** Symbol for identifying sandbox error instances */\n [DAYTONA_SANDBOX_ERROR_SYMBOL] = true as const;\n\n /** Error name for instanceof checks and logging */\n override readonly name = \"DaytonaSandboxError\";\n\n /**\n * Creates a new DaytonaSandboxError.\n *\n * @param message - Human-readable error description\n * @param code - Structured error code for programmatic handling\n * @param cause - Original error that caused this error (for debugging)\n */\n constructor(\n message: string,\n public readonly code: DaytonaSandboxErrorCode,\n public override readonly cause?: Error,\n ) {\n super(message, code as SandboxErrorCode, cause);\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, DaytonaSandboxError.prototype);\n }\n\n /**\n * Checks if the error is an instance of DaytonaSandboxError.\n *\n * @param error - The error to check\n * @returns True if the error is an instance of DaytonaSandboxError, false otherwise\n */\n static isInstance(error: unknown): error is DaytonaSandboxError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as Record<symbol, unknown>)[DAYTONA_SANDBOX_ERROR_SYMBOL] === true\n );\n }\n}\n","/* oxlint-disable no-instanceof/no-instanceof */\n/**\n * Daytona Sandbox implementation of the SandboxBackendProtocol.\n *\n * This module provides a Daytona Sandbox backend for deepagents, enabling agents\n * to execute commands, read/write files, and manage isolated sandbox environments\n * using Daytona's infrastructure.\n *\n * @packageDocumentation\n */\n\nimport { Daytona, type Sandbox } from \"@daytonaio/sdk\";\nimport {\n BaseSandbox,\n type ExecuteResponse,\n type FileDownloadResponse,\n type FileOperationError,\n type FileUploadResponse,\n type BackendFactory,\n} from \"deepagents\";\n\nimport { getAuthCredentials } from \"./auth.js\";\nimport { DaytonaSandboxError, type DaytonaSandboxOptions } from \"./types.js\";\n\n/**\n * Daytona Sandbox backend for deepagents.\n *\n * Extends `BaseSandbox` to provide command execution, file operations, and\n * sandbox lifecycle management using Daytona's SDK.\n *\n * ## Basic Usage\n *\n * ```typescript\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * timeout: 300,\n * });\n *\n * try {\n * // Execute commands\n * const result = await sandbox.execute(\"node --version\");\n * console.log(result.output);\n * } finally {\n * // Always cleanup\n * await sandbox.close();\n * }\n * ```\n *\n * ## Using with DeepAgent\n *\n * ```typescript\n * import { createDeepAgent } from \"deepagents\";\n * import { DaytonaSandbox } from \"@langchain/daytona\";\n *\n * const sandbox = await DaytonaSandbox.create();\n *\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant with sandbox access.\",\n * backend: sandbox,\n * });\n * ```\n */\nexport class DaytonaSandbox extends BaseSandbox {\n /** Private reference to the Daytona client */\n #daytona: Daytona | null = null;\n\n /** Private reference to the underlying Daytona Sandbox instance */\n #sandbox: Sandbox | null = null;\n\n /** Configuration options for this sandbox */\n #options: DaytonaSandboxOptions;\n\n /** Unique identifier for this sandbox instance */\n #id: string;\n\n /** Default timeout for command execution in seconds */\n #timeout: number;\n\n /**\n * Get the unique identifier for this sandbox.\n *\n * Before initialization, returns a temporary ID.\n * After initialization, returns the actual Daytona sandbox ID.\n */\n get id(): string {\n return this.#id;\n }\n\n /**\n * Get the underlying Daytona Sandbox instance.\n *\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaSdk = sandbox.sandbox; // Access the raw SDK\n * ```\n */\n get instance(): Sandbox {\n if (!this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#sandbox;\n }\n\n /**\n * Get the underlying Daytona client instance.\n *\n * @throws {DaytonaSandboxError} If the client is not initialized\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create();\n * const daytonaClient = sandbox.client; // Access the raw Daytona client\n * ```\n */\n get client(): Daytona {\n if (!this.#daytona) {\n throw new DaytonaSandboxError(\n \"Daytona client not initialized. Call initialize() or use DaytonaSandbox.create()\",\n \"NOT_INITIALIZED\",\n );\n }\n return this.#daytona;\n }\n\n /**\n * Check if the sandbox is initialized and running.\n */\n get isRunning(): boolean {\n return this.#sandbox !== null;\n }\n\n /**\n * Create a new DaytonaSandbox instance.\n *\n * Note: This only creates the instance. Call `initialize()` to actually\n * create the Daytona Sandbox, or use the static `DaytonaSandbox.create()` method.\n *\n * @param options - Configuration options for the sandbox\n *\n * @example\n * ```typescript\n * // Two-step initialization\n * const sandbox = new DaytonaSandbox({ language: \"typescript\" });\n * await sandbox.initialize();\n *\n * // Or use the factory method\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n * ```\n */\n constructor(options: DaytonaSandboxOptions = {}) {\n super();\n\n // Set defaults\n this.#options = {\n language: \"typescript\",\n timeout: 300,\n ...options,\n };\n\n this.#timeout = this.#options.timeout ?? 300;\n\n // Generate temporary ID until initialized\n this.#id = `daytona-sandbox-${Date.now()}`;\n }\n\n /**\n * Initialize the sandbox by creating a new Daytona Sandbox instance.\n *\n * This method authenticates with Daytona and provisions a new sandbox.\n * After initialization, the `id` property will reflect the actual sandbox ID.\n *\n * @throws {DaytonaSandboxError} If already initialized (`ALREADY_INITIALIZED`)\n * @throws {DaytonaSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)\n * @throws {DaytonaSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)\n *\n * @example\n * ```typescript\n * const sandbox = new DaytonaSandbox();\n * await sandbox.initialize();\n * console.log(`Sandbox ID: ${sandbox.id}`);\n * ```\n */\n async initialize(): Promise<void> {\n // Prevent double initialization\n if (this.#sandbox) {\n throw new DaytonaSandboxError(\n \"Sandbox is already initialized. Each DaytonaSandbox instance can only be initialized once.\",\n \"ALREADY_INITIALIZED\",\n );\n }\n\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(\n this.#options.auth,\n this.#options.target,\n );\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n // Create Daytona client\n this.#daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n // Determine if we're creating from image or snapshot\n if (this.#options.image) {\n // Create from image (allows custom resources)\n const createOptions: {\n image: string;\n language?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n autoArchiveInterval?: number;\n autoDeleteInterval?: number;\n labels?: Record<string, string>;\n resources?: { cpu?: number; memory?: number; disk?: number };\n } = {\n image: this.#options.image,\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.autoArchiveInterval !== undefined) {\n createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;\n }\n\n if (this.#options.autoDeleteInterval !== undefined) {\n createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n if (this.#options.resources) {\n createOptions.resources = this.#options.resources;\n }\n\n // Create the sandbox from image\n this.#sandbox = await this.#daytona.create(createOptions);\n } else {\n // Create from snapshot (default, simpler approach)\n const createOptions: {\n language?: string;\n snapshot?: string;\n envVars?: Record<string, string>;\n autoStopInterval?: number;\n autoArchiveInterval?: number;\n autoDeleteInterval?: number;\n labels?: Record<string, string>;\n } = {\n language: this.#options.language ?? \"typescript\",\n };\n\n if (this.#options.snapshot) {\n createOptions.snapshot = this.#options.snapshot;\n }\n\n if (this.#options.envVars) {\n createOptions.envVars = this.#options.envVars;\n }\n\n if (this.#options.autoStopInterval !== undefined) {\n createOptions.autoStopInterval = this.#options.autoStopInterval;\n }\n\n if (this.#options.autoArchiveInterval !== undefined) {\n createOptions.autoArchiveInterval = this.#options.autoArchiveInterval;\n }\n\n if (this.#options.autoDeleteInterval !== undefined) {\n createOptions.autoDeleteInterval = this.#options.autoDeleteInterval;\n }\n\n if (this.#options.labels) {\n createOptions.labels = this.#options.labels;\n }\n\n // Create the sandbox from snapshot\n this.#sandbox = await this.#daytona.create(createOptions);\n }\n\n // Update ID to the actual sandbox ID\n this.#id = this.#sandbox.id;\n\n // Upload initial files if provided\n if (this.#options.initialFiles) {\n await this.#uploadInitialFiles(this.#options.initialFiles);\n }\n } catch (error) {\n throw new DaytonaSandboxError(\n `Failed to create Daytona Sandbox: ${error instanceof Error ? error.message : String(error)}`,\n \"SANDBOX_CREATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload initial files to the sandbox.\n *\n * @param files - A map of file paths to their string contents\n */\n async #uploadInitialFiles(files: Record<string, string>): Promise<void> {\n const encoder = new TextEncoder();\n const fileEntries: Array<[string, Uint8Array]> = Object.entries(files).map(\n ([path, content]) => [path, encoder.encode(content)],\n );\n\n const results = await this.uploadFiles(fileEntries);\n\n // Check for any errors during upload\n const errors = results.filter((r) => r.error !== null);\n if (errors.length > 0) {\n const errorPaths = errors.map((e) => `${e.path}: ${e.error}`).join(\", \");\n throw new DaytonaSandboxError(\n `Failed to upload initial files: ${errorPaths}`,\n \"FILE_OPERATION_FAILED\",\n );\n }\n }\n\n /**\n * Execute a command in the sandbox.\n *\n * Commands are run using the sandbox's shell.\n *\n * @param command - The shell command to execute\n * @returns Execution result with output, exit code, and truncation flag\n * @throws {DaytonaSandboxError} If the sandbox is not initialized\n *\n * @example\n * ```typescript\n * const result = await sandbox.execute(\"echo 'Hello World'\");\n * console.log(result.output); // \"Hello World\\n\"\n * console.log(result.exitCode); // 0\n * ```\n */\n async execute(command: string): Promise<ExecuteResponse> {\n const sandbox = this.instance; // Throws if not initialized\n\n try {\n const response = await sandbox.process.executeCommand(\n command,\n undefined,\n undefined,\n this.#timeout,\n );\n\n return {\n output: response.result ?? \"\",\n exitCode: response.exitCode ?? 0,\n truncated: false,\n };\n } catch (error) {\n // Check for timeout\n if (error instanceof Error && error.message.includes(\"timeout\")) {\n throw new DaytonaSandboxError(\n `Command timed out: ${command}`,\n \"COMMAND_TIMEOUT\",\n error,\n );\n }\n\n throw new DaytonaSandboxError(\n `Command execution failed: ${error instanceof Error ? error.message : String(error)}`,\n \"COMMAND_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Upload files to the sandbox.\n *\n * Files are written to the sandbox filesystem. Parent directories are\n * created automatically if they don't exist.\n *\n * @param files - Array of [path, content] tuples to upload\n * @returns Upload result for each file, with success or error status\n *\n * @example\n * ```typescript\n * const encoder = new TextEncoder();\n * const results = await sandbox.uploadFiles([\n * [\"src/index.js\", encoder.encode(\"console.log('Hello')\")],\n * [\"package.json\", encoder.encode('{\"name\": \"test\"}')],\n * ]);\n * ```\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileUploadResponse[] = [];\n\n for (const [path, content] of files) {\n try {\n // Ensure parent directory exists\n const parentDir = path.substring(0, path.lastIndexOf(\"/\"));\n if (parentDir) {\n await sandbox.fs.createFolder(parentDir, \"755\");\n }\n\n // Upload the file content\n const buffer = Buffer.from(content);\n await sandbox.fs.uploadFile(buffer, path);\n results.push({ path, error: null });\n } catch (error) {\n results.push({ path, error: this.#mapError(error) });\n }\n }\n\n return results;\n }\n\n /**\n * Download files from the sandbox.\n *\n * Each file is read individually, allowing partial success when some\n * files exist and others don't.\n *\n * @param paths - Array of file paths to download\n * @returns Download result for each file, with content or error\n *\n * @example\n * ```typescript\n * const results = await sandbox.downloadFiles([\"src/index.js\", \"missing.txt\"]);\n * for (const result of results) {\n * if (result.content) {\n * console.log(new TextDecoder().decode(result.content));\n * } else {\n * console.error(`Error: ${result.error}`);\n * }\n * }\n * ```\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const sandbox = this.instance; // Throws if not initialized\n const results: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n try {\n const buffer = await sandbox.fs.downloadFile(path);\n results.push({\n path,\n content: new Uint8Array(buffer),\n error: null,\n });\n } catch (error) {\n results.push({\n path,\n content: null,\n error: this.#mapError(error),\n });\n }\n }\n\n return results;\n }\n\n /**\n * Close the sandbox and release all resources.\n *\n * After closing, the sandbox cannot be used again. The sandbox is deleted\n * from Daytona's infrastructure.\n *\n * @example\n * ```typescript\n * try {\n * await sandbox.execute(\"npm run build\");\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\n async close(): Promise<void> {\n if (this.#sandbox) {\n try {\n await this.#sandbox.delete();\n } finally {\n this.#sandbox = null;\n this.#daytona = null;\n }\n }\n }\n\n /**\n * Stop the sandbox without deleting it.\n *\n * The sandbox can be restarted later using `start()`.\n *\n * @example\n * ```typescript\n * await sandbox.stop();\n * // Later...\n * await sandbox.start();\n * ```\n */\n async stop(): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.stop();\n }\n }\n\n /**\n * Start a stopped sandbox.\n *\n * @param timeout - Maximum time to wait in seconds (default: 60)\n *\n * @example\n * ```typescript\n * await sandbox.start();\n * console.log(\"Sandbox is now running\");\n * ```\n */\n async start(timeout: number = 60): Promise<void> {\n if (this.#sandbox) {\n await this.#sandbox.start(timeout);\n }\n }\n\n /**\n * Forcefully terminate and delete the sandbox.\n *\n * Use this when you need to immediately stop the sandbox.\n *\n * @example\n * ```typescript\n * await sandbox.kill();\n * ```\n */\n async kill(): Promise<void> {\n await this.close();\n }\n\n /**\n * Get the working directory path inside the sandbox.\n *\n * @returns The absolute path to the sandbox working directory\n *\n * @example\n * ```typescript\n * const workDir = await sandbox.getWorkDir();\n * console.log(`Working directory: ${workDir}`);\n * ```\n */\n async getWorkDir(): Promise<string> {\n const sandbox = this.instance;\n const workDir = await sandbox.getWorkDir();\n return workDir ?? \"/home/daytona\";\n }\n\n /**\n * Get the user's home directory path inside the sandbox.\n *\n * @returns The absolute path to the user's home directory\n *\n * @example\n * ```typescript\n * const homeDir = await sandbox.getUserHomeDir();\n * console.log(`Home directory: ${homeDir}`);\n * ```\n */\n async getUserHomeDir(): Promise<string> {\n const sandbox = this.instance;\n const homeDir = await sandbox.getUserHomeDir();\n return homeDir ?? \"/home/daytona\";\n }\n\n /**\n * Set the sandbox from an existing Daytona Sandbox instance.\n * Used internally by the static `connect()` method.\n */\n #setFromExisting(\n daytona: Daytona,\n existingSandbox: Sandbox,\n sandboxId: string,\n ): void {\n this.#daytona = daytona;\n this.#sandbox = existingSandbox;\n this.#id = sandboxId;\n }\n\n /**\n * Map Daytona SDK errors to standardized FileOperationError codes.\n *\n * @param error - The error from the Daytona SDK\n * @returns A standardized error code\n */\n #mapError(error: unknown): FileOperationError {\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n\n if (msg.includes(\"not found\") || msg.includes(\"enoent\")) {\n return \"file_not_found\";\n }\n if (msg.includes(\"permission\") || msg.includes(\"eacces\")) {\n return \"permission_denied\";\n }\n if (msg.includes(\"directory\") || msg.includes(\"eisdir\")) {\n return \"is_directory\";\n }\n }\n\n return \"invalid_path\";\n }\n\n /**\n * Create and initialize a new DaytonaSandbox in one step.\n *\n * This is the recommended way to create a sandbox. It combines\n * construction and initialization into a single async operation.\n *\n * @param options - Configuration options for the sandbox\n * @returns An initialized and ready-to-use sandbox\n *\n * @example\n * ```typescript\n * const sandbox = await DaytonaSandbox.create({\n * language: \"typescript\",\n * cpu: 2,\n * memory: 4,\n * });\n * ```\n */\n static async create(\n options?: DaytonaSandboxOptions,\n ): Promise<DaytonaSandbox> {\n const sandbox = new DaytonaSandbox(options);\n await sandbox.initialize();\n return sandbox;\n }\n\n /**\n * Delete all sandboxes matching the given labels.\n *\n * This is useful for cleaning up stale sandboxes from previous test runs\n * or CI pipelines that may not have shut down cleanly.\n *\n * @param labels - Label key-value pairs to filter sandboxes\n * @param options - Optional auth configuration\n * @returns The number of sandboxes that were deleted\n *\n * @example\n * ```typescript\n * // Clean up all integration-test sandboxes\n * const deleted = await DaytonaSandbox.deleteAll({\n * purpose: \"integration-test\",\n * package: \"@langchain/daytona\",\n * });\n * console.log(`Deleted ${deleted} stale sandboxes`);\n * ```\n */\n static async deleteAll(\n labels: Record<string, string>,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\">,\n ): Promise<number> {\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const { items } = await daytona.list(labels);\n\n const results = await Promise.all(\n items.map((sandbox) =>\n daytona\n .delete(sandbox)\n .then(() => true)\n .catch(() => false),\n ),\n );\n\n return results.filter(Boolean).length;\n }\n\n /**\n * Connect to an existing sandbox by ID.\n *\n * This allows you to resume working with a sandbox that was created\n * earlier or that is still running.\n *\n * @param sandboxId - The ID of the sandbox to connect to\n * @param options - Optional auth configuration (for API key)\n * @returns A connected sandbox instance\n *\n * @example\n * ```typescript\n * // Resume a sandbox from a stored ID\n * const sandbox = await DaytonaSandbox.connect(\"sandbox-abc123\");\n * const result = await sandbox.execute(\"ls -la\");\n * ```\n */\n static async fromId(\n id: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\" | \"target\" | \"timeout\">,\n ): Promise<DaytonaSandbox> {\n // Get authentication credentials\n let credentials: { apiKey: string; apiUrl: string; target?: string };\n try {\n credentials = getAuthCredentials(options?.auth, options?.target);\n } catch (error) {\n throw new DaytonaSandboxError(\n \"Failed to authenticate with Daytona. Check your API key configuration.\",\n \"AUTHENTICATION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n\n try {\n const daytona = new Daytona({\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n target: credentials.target,\n });\n\n const existingSandbox = await daytona.get(id);\n\n const daytonaSandbox = new DaytonaSandbox(options);\n // Set the existing sandbox directly (bypass initialize)\n daytonaSandbox.#setFromExisting(daytona, existingSandbox, id);\n\n return daytonaSandbox;\n } catch (error) {\n throw new DaytonaSandboxError(\n `Sandbox not found: ${id}`,\n \"SANDBOX_NOT_FOUND\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Get a running sandbox by name from a deployed app.\n *\n * @param name - The name of the sandbox\n * @param options - Optional auth configuration\n * @returns A connected sandbox instance\n */\n static async fromName(\n name: string,\n options?: Pick<DaytonaSandboxOptions, \"auth\">,\n ): Promise<DaytonaSandbox> {\n return DaytonaSandbox.fromId(name, options);\n }\n}\n\n/**\n * Async factory function type for creating Daytona Sandbox instances.\n *\n * This is similar to BackendFactory but supports async creation,\n * which is required for Daytona Sandbox since initialization is async.\n */\nexport type AsyncDaytonaSandboxFactory = () => Promise<DaytonaSandbox>;\n\n/**\n * Create an async factory function that creates a new Daytona Sandbox per invocation.\n *\n * Each call to the factory will create and initialize a new sandbox.\n * This is useful when you want fresh, isolated environments for each\n * agent invocation.\n *\n * **Important**: This returns an async factory. For use with middleware that\n * requires synchronous BackendFactory, use `createDaytonaSandboxFactoryFromSandbox()`\n * with a pre-created sandbox instead.\n *\n * @param options - Optional configuration for sandbox creation\n * @returns An async factory function that creates new sandboxes\n *\n * @example\n * ```typescript\n * import { DaytonaSandbox, createDaytonaSandboxFactory } from \"@langchain/daytona\";\n *\n * // Create a factory for new sandboxes\n * const factory = createDaytonaSandboxFactory({ language: \"typescript\" });\n *\n * // Each call creates a new sandbox\n * const sandbox1 = await factory();\n * const sandbox2 = await factory();\n *\n * try {\n * // Use sandboxes...\n * } finally {\n * await sandbox1.close();\n * await sandbox2.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactory(\n options?: DaytonaSandboxOptions,\n): AsyncDaytonaSandboxFactory {\n return async () => {\n return await DaytonaSandbox.create(options);\n };\n}\n\n/**\n * Create a backend factory that reuses an existing Daytona Sandbox.\n *\n * This allows multiple agent invocations to share the same sandbox,\n * avoiding the startup overhead of creating new sandboxes.\n *\n * Important: You are responsible for managing the sandbox lifecycle\n * (calling `close()` when done).\n *\n * @param sandbox - An existing DaytonaSandbox instance (must be initialized)\n * @returns A BackendFactory that returns the provided sandbox\n *\n * @example\n * ```typescript\n * import { createDeepAgent, createFilesystemMiddleware } from \"deepagents\";\n * import { DaytonaSandbox, createDaytonaSandboxFactoryFromSandbox } from \"@langchain/daytona\";\n *\n * // Create and initialize a sandbox\n * const sandbox = await DaytonaSandbox.create({ language: \"typescript\" });\n *\n * try {\n * const agent = createDeepAgent({\n * model: new ChatAnthropic({ model: \"claude-sonnet-4-20250514\" }),\n * systemPrompt: \"You are a coding assistant.\",\n * middlewares: [\n * createFilesystemMiddleware({\n * backend: createDaytonaSandboxFactoryFromSandbox(sandbox),\n * }),\n * ],\n * });\n *\n * await agent.invoke({ messages: [...] });\n * } finally {\n * await sandbox.close();\n * }\n * ```\n */\nexport function createDaytonaSandboxFactoryFromSandbox(\n sandbox: DaytonaSandbox,\n): BackendFactory {\n return () => sandbox;\n}\n"],"mappings":";;;;AAyBA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCxB,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,OAAM,IAAI,MACR,iUAMD;;;;;;;;;;;;;;AAeH,SAAgB,cAAc,SAAiD;AAE7E,KAAI,SAAS,OACX,QAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;AAC3B,KAAI,OACF,QAAO;AAIT,QAAO;;;;;;;;;;;;AAaT,SAAgB,mBACd,SACA,QACoB;AACpB,QAAO;EACL,QAAQ,cAAc,QAAQ;EAC9B,QAAQ,cAAc,QAAQ;EAC9B,QAAQ,UAAU,QAAQ,IAAI;EAC/B;;;;;;;;;;AC0EH,MAAM,+BAA+B,OAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BxE,IAAa,sBAAb,MAAa,4BAA4B,aAAa;;CAEpD,CAAC,gCAAgC;;CAGjC,OAAyB;;;;;;;;CASzB,YACE,SACA,MACA,OACA;AACA,QAAM,SAAS,MAA0B,MAAM;AAH/B,OAAA,OAAA;AACS,OAAA,QAAA;AAIzB,SAAO,eAAe,MAAM,oBAAoB,UAAU;;;;;;;;CAS5D,OAAO,WAAW,OAA8C;AAC9D,SACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A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QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C/C,SAAgB,4BACd,SAC4B;AAC5B,QAAO,YAAY;AACjB,SAAO,MAAM,eAAe,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyC/C,SAAgB,uCACd,SACgB;AAChB,cAAa"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/daytona",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-alpha.0",
4
4
  "description": "Daytona Sandbox backend for deepagents",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -27,22 +27,22 @@
27
27
  },
28
28
  "homepage": "https://github.com/langchain-ai/deepagentsjs#readme",
29
29
  "dependencies": {
30
- "@daytonaio/sdk": "^0.135.0"
30
+ "@daytonaio/sdk": "^0.155.0"
31
31
  },
32
32
  "peerDependencies": {
33
- "deepagents": ">=1.6.0"
33
+ "deepagents": ">=1.9.0-alpha.0"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@tsconfig/recommended": "^1.0.13",
37
37
  "@types/node": "^25.1.0",
38
38
  "@vitest/coverage-v8": "^4.0.18",
39
39
  "dotenv": "^17.2.3",
40
- "tsdown": "^0.20.1",
40
+ "tsdown": "^0.21.4",
41
41
  "tsx": "^4.21.0",
42
- "typescript": "^5.9.3",
42
+ "typescript": "^6.0.2",
43
43
  "vitest": "^4.0.18",
44
- "deepagents": "1.7.1",
45
- "@langchain/standard-tests": "0.0.1"
44
+ "deepagents": "1.9.0-alpha.1",
45
+ "@langchain/sandbox-standard-tests": "1.0.0-alpha.0"
46
46
  },
47
47
  "exports": {
48
48
  ".": {