@langchain/daytona 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -208,7 +208,7 @@ await sdk.fs.createFolder("src", "755");
208
208
  await sdk.fs.uploadFile(Buffer.from("content"), "src/index.ts");
209
209
  ```
210
210
 
211
- See the [@daytonaio/sdk documentation](https://www.npmjs.com/package/@daytonaio/sdk) for all available SDK methods.
211
+ See the [@daytona/sdk documentation](https://www.npmjs.com/package/@daytona/sdk) for all available SDK methods.
212
212
 
213
213
  ## Factory Functions
214
214
 
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let _daytonaio_sdk = require("@daytonaio/sdk");
2
+ let _daytona_sdk = require("@daytona/sdk");
3
3
  let deepagents = require("deepagents");
4
4
  //#region src/auth.ts
5
5
  /** Default Daytona API URL */
@@ -119,6 +119,8 @@ const DAYTONA_SANDBOX_ERROR_SYMBOL = Symbol.for("daytona.sandbox.error");
119
119
  * ```
120
120
  */
121
121
  var DaytonaSandboxError = class DaytonaSandboxError extends deepagents.SandboxError {
122
+ code;
123
+ cause;
122
124
  /** Symbol for identifying sandbox error instances */
123
125
  [DAYTONA_SANDBOX_ERROR_SYMBOL] = true;
124
126
  /** Error name for instanceof checks and logging */
@@ -157,6 +159,9 @@ var DaytonaSandboxError = class DaytonaSandboxError extends deepagents.SandboxEr
157
159
  *
158
160
  * @packageDocumentation
159
161
  */
162
+ function shellQuote(value) {
163
+ return `'${value.replace(/'/g, "'\\''")}'`;
164
+ }
160
165
  /**
161
166
  * Daytona Sandbox backend for deepagents.
162
167
  *
@@ -309,7 +314,7 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
309
314
  throw new DaytonaSandboxError("Failed to authenticate with Daytona. Check your API key configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
310
315
  }
311
316
  try {
312
- this.#daytona = new _daytonaio_sdk.Daytona({
317
+ this.#daytona = new _daytona_sdk.Daytona({
313
318
  apiKey: credentials.apiKey,
314
319
  apiUrl: credentials.apiUrl,
315
320
  target: credentials.target
@@ -406,7 +411,7 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
406
411
  const results = [];
407
412
  for (const [path, content] of files) try {
408
413
  const parentDir = path.substring(0, path.lastIndexOf("/"));
409
- if (parentDir) await sandbox.fs.createFolder(parentDir, "755");
414
+ if (parentDir) await this.#ensureParentDirectory(parentDir);
410
415
  const buffer = Buffer.from(content);
411
416
  await sandbox.fs.uploadFile(buffer, path);
412
417
  results.push({
@@ -421,6 +426,9 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
421
426
  }
422
427
  return results;
423
428
  }
429
+ async #ensureParentDirectory(parentDir) {
430
+ if ((await this.execute(`mkdir -p ${shellQuote(parentDir)}`)).exitCode !== 0) throw new Error(`Failed to create parent directory: ${parentDir}`);
431
+ }
424
432
  /**
425
433
  * Download files from the sandbox.
426
434
  *
@@ -628,13 +636,14 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
628
636
  } catch (error) {
629
637
  throw new DaytonaSandboxError("Failed to authenticate with Daytona. Check your API key configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
630
638
  }
631
- const daytona = new _daytonaio_sdk.Daytona({
639
+ const daytona = new _daytona_sdk.Daytona({
632
640
  apiKey: credentials.apiKey,
633
641
  apiUrl: credentials.apiUrl,
634
642
  target: credentials.target
635
643
  });
636
- const { items } = await daytona.list(labels);
637
- return (await Promise.all(items.map((sandbox) => daytona.delete(sandbox).then(() => true).catch(() => false)))).filter(Boolean).length;
644
+ const sandboxes = [];
645
+ for await (const sandbox of daytona.list({ labels })) sandboxes.push(sandbox);
646
+ return (await Promise.all(sandboxes.map((sandbox) => daytona.delete(sandbox).then(() => true).catch(() => false)))).filter(Boolean).length;
638
647
  }
639
648
  /**
640
649
  * Connect to an existing sandbox by ID.
@@ -661,7 +670,7 @@ var DaytonaSandbox = class DaytonaSandbox extends deepagents.BaseSandbox {
661
670
  throw new DaytonaSandboxError("Failed to authenticate with Daytona. Check your API key configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
662
671
  }
663
672
  try {
664
- const daytona = new _daytonaio_sdk.Daytona({
673
+ const daytona = new _daytona_sdk.Daytona({
665
674
  apiKey: credentials.apiKey,
666
675
  apiUrl: credentials.apiUrl,
667
676
  target: credentials.target
@@ -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 * 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","/* 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 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,WAAW,OAA8C;AAC9D,SACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5M3E,IAAa,iBAAb,MAAa,uBAAuBC,WAAAA,YAAY;;CAE9C,WAA2B;;CA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;;;;;;;;;;;;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","#ensureParentDirectory","#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 \"@daytona/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\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\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 this.#ensureParentDirectory(parentDir);\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 async #ensureParentDirectory(parentDir: string): Promise<void> {\n const result = await this.execute(`mkdir -p ${shellQuote(parentDir)}`);\n if (result.exitCode !== 0) {\n throw new Error(`Failed to create parent directory: ${parentDir}`);\n }\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 sandboxes: Sandbox[] = [];\n for await (const sandbox of daytona.list({ labels })) {\n sandboxes.push(sandbox);\n }\n\n const results = await Promise.all(\n sandboxes.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;CAE7E,IAAI,SAAS,QACX,OAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;CAC3B,IAAI,QACF,OAAO;CAIT,MAAM,IAAI,MACR,gUAMF;AACF;;;;;;;;;;;;;AAcA,SAAgB,cAAc,SAAiD;CAE7E,IAAI,SAAS,QACX,OAAO,QAAQ;CAIjB,MAAM,SAAS,QAAQ,IAAI;CAC3B,IAAI,QACF,OAAO;CAIT,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,mBACd,SACA,QACoB;CACpB,OAAO;EACL,QAAQ,cAAc,OAAO;EAC7B,QAAQ,cAAc,OAAO;EAC7B,QAAQ,UAAU,QAAQ,IAAI;CAChC;AACF;;;;;;;;;ACyEA,MAAM,+BAA+B,OAAO,IAAI,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BvE,IAAa,sBAAb,MAAa,4BAA4BA,WAAAA,aAAa;CAgBlC;CACS;;CAf3B,CAAC,gCAAgC;;CAGjC,OAAyB;;;;;;;;CASzB,YACE,SACA,MACA,OACA;EACA,MAAM,SAAS,MAA0B,KAAK;EAH9B,KAAA,OAAA;EACS,KAAA,QAAA;EAIzB,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;;;;;;;CAQA,OAAO,WAAW,OAA8C;EAC9D,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,kCAAkC;CAEzE;AAC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,OAAO,CAAC,CAAC;CACjC;;;;;;;;;;;;;;;;;;CAmBA,aAAa,OACX,IACA,SACyB;EAEzB,IAAI;EACJ,IAAI;GACF,cAAc,mBAAmB,SAAS,MAAM,SAAS,MAAM;EACjE,SAAS,OAAO;GACd,MAAM,IAAI,oBACR,0EACA,yBACA,iBAAiB,QAAQ,QAAQ,KAAA,CACnC;EACF;EAEA,IAAI;GACF,MAAM,UAAU,IAAIA,aAAAA,QAAQ;IAC1B,QAAQ,YAAY;IACpB,QAAQ,YAAY;IACpB,QAAQ,YAAY;GACtB,CAAC;GAED,MAAM,kBAAkB,MAAM,QAAQ,IAAI,EAAE;GAE5C,MAAM,iBAAiB,IAAI,eAAe,OAAO;GAEjD,eAAeI,iBAAiB,SAAS,iBAAiB,EAAE;GAE5D,OAAO;EACT,SAAS,OAAO;GACd,MAAM,IAAI,oBACR,sBAAsB,MACtB,qBACA,iBAAiB,QAAQ,QAAQ,KAAA,CACnC;EACF;CACF;;;;;;;;CASA,aAAa,SACX,MACA,SACyB;EACzB,OAAO,eAAe,OAAO,MAAM,OAAO;CAC5C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,4BACd,SAC4B;CAC5B,OAAO,YAAY;EACjB,OAAO,MAAM,eAAe,OAAO,OAAO;CAC5C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,uCACd,SACgB;CAChB,aAAa;AACf"}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,5 @@
1
- import { Daytona, Sandbox } from "@daytonaio/sdk";
1
+ import { Daytona, Sandbox } from "@daytona/sdk";
2
2
  import { BackendFactory, BaseSandbox, ExecuteResponse, FileDownloadResponse, FileUploadResponse, SandboxError, SandboxErrorCode } from "deepagents";
3
-
4
3
  //#region src/types.d.ts
5
4
  /**
6
5
  * Supported target regions for Daytona sandboxes.
@@ -57,8 +56,11 @@ interface DaytonaSandboxOptions {
57
56
  * ```
58
57
  */
59
58
  resources?: {
60
- /** Number of CPUs to allocate */cpu?: number; /** Amount of memory in GiB */
61
- memory?: number; /** Amount of disk space in GiB */
59
+ /** Number of CPUs to allocate */
60
+ cpu?: number;
61
+ /** Amount of memory in GiB */
62
+ memory?: number;
63
+ /** Amount of disk space in GiB */
62
64
  disk?: number;
63
65
  };
64
66
  /**
@@ -168,7 +170,17 @@ interface DaytonaSandboxOptions {
168
170
  *
169
171
  * Used to identify specific error conditions and handle them appropriately.
170
172
  */
171
- type DaytonaSandboxErrorCode = SandboxErrorCode /** Authentication failed - check API key configuration */ | "AUTHENTICATION_FAILED" /** Failed to create sandbox - check options and quotas */ | "SANDBOX_CREATION_FAILED" /** Sandbox not found - may have been deleted or expired */ | "SANDBOX_NOT_FOUND" /** Sandbox is not in started state */ | "SANDBOX_NOT_STARTED" /** Resource limits exceeded (CPU, memory, storage) */ | "RESOURCE_LIMIT_EXCEEDED";
173
+ type DaytonaSandboxErrorCode = SandboxErrorCode |
174
+ /** Authentication failed - check API key configuration */
175
+ "AUTHENTICATION_FAILED" |
176
+ /** Failed to create sandbox - check options and quotas */
177
+ "SANDBOX_CREATION_FAILED" |
178
+ /** Sandbox not found - may have been deleted or expired */
179
+ "SANDBOX_NOT_FOUND" |
180
+ /** Sandbox is not in started state */
181
+ "SANDBOX_NOT_STARTED" |
182
+ /** Resource limits exceeded (CPU, memory, storage) */
183
+ "RESOURCE_LIMIT_EXCEEDED";
172
184
  declare const DAYTONA_SANDBOX_ERROR_SYMBOL: unique symbol;
173
185
  /**
174
186
  * Custom error class for Daytona Sandbox operations.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { Daytona, Sandbox } from "@daytonaio/sdk";
1
+ import { Daytona, Sandbox } from "@daytona/sdk";
2
2
  import { BackendFactory, BaseSandbox, ExecuteResponse, FileDownloadResponse, FileUploadResponse, SandboxError, SandboxErrorCode } from "deepagents";
3
-
4
3
  //#region src/types.d.ts
5
4
  /**
6
5
  * Supported target regions for Daytona sandboxes.
@@ -57,8 +56,11 @@ interface DaytonaSandboxOptions {
57
56
  * ```
58
57
  */
59
58
  resources?: {
60
- /** Number of CPUs to allocate */cpu?: number; /** Amount of memory in GiB */
61
- memory?: number; /** Amount of disk space in GiB */
59
+ /** Number of CPUs to allocate */
60
+ cpu?: number;
61
+ /** Amount of memory in GiB */
62
+ memory?: number;
63
+ /** Amount of disk space in GiB */
62
64
  disk?: number;
63
65
  };
64
66
  /**
@@ -168,7 +170,17 @@ interface DaytonaSandboxOptions {
168
170
  *
169
171
  * Used to identify specific error conditions and handle them appropriately.
170
172
  */
171
- type DaytonaSandboxErrorCode = SandboxErrorCode /** Authentication failed - check API key configuration */ | "AUTHENTICATION_FAILED" /** Failed to create sandbox - check options and quotas */ | "SANDBOX_CREATION_FAILED" /** Sandbox not found - may have been deleted or expired */ | "SANDBOX_NOT_FOUND" /** Sandbox is not in started state */ | "SANDBOX_NOT_STARTED" /** Resource limits exceeded (CPU, memory, storage) */ | "RESOURCE_LIMIT_EXCEEDED";
173
+ type DaytonaSandboxErrorCode = SandboxErrorCode |
174
+ /** Authentication failed - check API key configuration */
175
+ "AUTHENTICATION_FAILED" |
176
+ /** Failed to create sandbox - check options and quotas */
177
+ "SANDBOX_CREATION_FAILED" |
178
+ /** Sandbox not found - may have been deleted or expired */
179
+ "SANDBOX_NOT_FOUND" |
180
+ /** Sandbox is not in started state */
181
+ "SANDBOX_NOT_STARTED" |
182
+ /** Resource limits exceeded (CPU, memory, storage) */
183
+ "RESOURCE_LIMIT_EXCEEDED";
172
184
  declare const DAYTONA_SANDBOX_ERROR_SYMBOL: unique symbol;
173
185
  /**
174
186
  * Custom error class for Daytona Sandbox operations.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Daytona } from "@daytonaio/sdk";
1
+ import { Daytona } from "@daytona/sdk";
2
2
  import { BaseSandbox, SandboxError } from "deepagents";
3
3
  //#region src/auth.ts
4
4
  /** Default Daytona API URL */
@@ -118,6 +118,8 @@ const DAYTONA_SANDBOX_ERROR_SYMBOL = Symbol.for("daytona.sandbox.error");
118
118
  * ```
119
119
  */
120
120
  var DaytonaSandboxError = class DaytonaSandboxError extends SandboxError {
121
+ code;
122
+ cause;
121
123
  /** Symbol for identifying sandbox error instances */
122
124
  [DAYTONA_SANDBOX_ERROR_SYMBOL] = true;
123
125
  /** Error name for instanceof checks and logging */
@@ -156,6 +158,9 @@ var DaytonaSandboxError = class DaytonaSandboxError extends SandboxError {
156
158
  *
157
159
  * @packageDocumentation
158
160
  */
161
+ function shellQuote(value) {
162
+ return `'${value.replace(/'/g, "'\\''")}'`;
163
+ }
159
164
  /**
160
165
  * Daytona Sandbox backend for deepagents.
161
166
  *
@@ -405,7 +410,7 @@ var DaytonaSandbox = class DaytonaSandbox extends BaseSandbox {
405
410
  const results = [];
406
411
  for (const [path, content] of files) try {
407
412
  const parentDir = path.substring(0, path.lastIndexOf("/"));
408
- if (parentDir) await sandbox.fs.createFolder(parentDir, "755");
413
+ if (parentDir) await this.#ensureParentDirectory(parentDir);
409
414
  const buffer = Buffer.from(content);
410
415
  await sandbox.fs.uploadFile(buffer, path);
411
416
  results.push({
@@ -420,6 +425,9 @@ var DaytonaSandbox = class DaytonaSandbox extends BaseSandbox {
420
425
  }
421
426
  return results;
422
427
  }
428
+ async #ensureParentDirectory(parentDir) {
429
+ if ((await this.execute(`mkdir -p ${shellQuote(parentDir)}`)).exitCode !== 0) throw new Error(`Failed to create parent directory: ${parentDir}`);
430
+ }
423
431
  /**
424
432
  * Download files from the sandbox.
425
433
  *
@@ -632,8 +640,9 @@ var DaytonaSandbox = class DaytonaSandbox extends BaseSandbox {
632
640
  apiUrl: credentials.apiUrl,
633
641
  target: credentials.target
634
642
  });
635
- const { items } = await daytona.list(labels);
636
- return (await Promise.all(items.map((sandbox) => daytona.delete(sandbox).then(() => true).catch(() => false)))).filter(Boolean).length;
643
+ const sandboxes = [];
644
+ for await (const sandbox of daytona.list({ labels })) sandboxes.push(sandbox);
645
+ return (await Promise.all(sandboxes.map((sandbox) => daytona.delete(sandbox).then(() => true).catch(() => false)))).filter(Boolean).length;
637
646
  }
638
647
  /**
639
648
  * Connect to an existing sandbox by ID.
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 * 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","/* 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 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;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Error","#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 \"@daytona/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\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\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 this.#ensureParentDirectory(parentDir);\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 async #ensureParentDirectory(parentDir: string): Promise<void> {\n const result = await this.execute(`mkdir -p ${shellQuote(parentDir)}`);\n if (result.exitCode !== 0) {\n throw new Error(`Failed to create parent directory: ${parentDir}`);\n }\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 sandboxes: Sandbox[] = [];\n for await (const sandbox of daytona.list({ labels })) {\n sandboxes.push(sandbox);\n }\n\n const results = await Promise.all(\n sandboxes.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;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AAY;GACtB,CAAC;GAED,MAAM,kBAAkB,MAAM,QAAQ,IAAI,EAAE;GAE5C,MAAM,iBAAiB,IAAI,eAAe,OAAO;GAEjD,eAAeQ,iBAAiB,SAAS,iBAAiB,EAAE;GAE5D,OAAO;EACT,SAAS,OAAO;GACd,MAAM,IAAI,oBACR,sBAAsB,MACtB,qBACA,iBAAiB,QAAQ,QAAQ,KAAA,CACnC;EACF;CACF;;;;;;;;CASA,aAAa,SACX,MACA,SACyB;EACzB,OAAO,eAAe,OAAO,MAAM,OAAO;CAC5C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,4BACd,SAC4B;CAC5B,OAAO,YAAY;EACjB,OAAO,MAAM,eAAe,OAAO,OAAO;CAC5C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,uCACd,SACgB;CAChB,aAAa;AACf"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/daytona",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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.155.0"
30
+ "@daytona/sdk": "^0.200.1"
31
31
  },
32
32
  "peerDependencies": {
33
- "deepagents": ">=1.6.0"
33
+ "deepagents": ">=1.12.0-rc.0"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@tsconfig/recommended": "^1.0.13",
37
- "@types/node": "^25.1.0",
37
+ "@types/node": "^26.1.0",
38
38
  "@vitest/coverage-v8": "^4.0.18",
39
39
  "dotenv": "^17.2.3",
40
- "tsdown": "^0.21.4",
40
+ "tsdown": "^0.22.1",
41
41
  "tsx": "^4.21.0",
42
- "typescript": "^5.9.3",
42
+ "typescript": "^7.0.2",
43
43
  "vitest": "^4.0.18",
44
- "deepagents": "1.8.7",
45
- "@langchain/sandbox-standard-tests": "0.1.0"
44
+ "deepagents": "1.12.2",
45
+ "@langchain/sandbox-standard-tests": "2.0.0"
46
46
  },
47
47
  "exports": {
48
48
  ".": {