import { Daytona, Sandbox } from "@daytona/sdk"; import { BackendFactory, BaseSandbox, ExecuteResponse, FileDownloadResponse, FileUploadResponse, SandboxError, SandboxErrorCode } from "deepagents"; //#region src/types.d.ts /** * Supported target regions for Daytona sandboxes. * * - `us`: United States * - `eu`: Europe */ type DaytonaSandboxTarget = "us" | "eu"; /** * Configuration options for creating a Daytona Sandbox. * * @example * ```typescript * const options: DaytonaSandboxOptions = { * language: "typescript", * timeout: 300, // 5 minutes * target: "us", * }; * ``` */ interface DaytonaSandboxOptions { /** * Primary language for code execution in the sandbox. * * Determines the runtime environment and code execution tooling. * * @default "typescript" */ language?: "typescript" | "python" | "javascript"; /** * Custom environment variables to set in the sandbox. * * These variables will be available to all commands and code executed * in the sandbox. * * @example * ```typescript * envVars: { * NODE_ENV: "development", * API_KEY: "secret" * } * ``` */ envVars?: Record; /** * Resource allocation for the sandbox. * * When specifying resources, you must also specify an `image`. * Resources cannot be customized when using the default snapshot-based sandbox. * * @example * ```typescript * resources: { cpu: 2, memory: 4, disk: 20 } * ``` */ resources?: { /** Number of CPUs to allocate */ cpu?: number; /** Amount of memory in GiB */ memory?: number; /** Amount of disk space in GiB */ disk?: number; }; /** * Custom Docker image to use for the sandbox. * * When specified, creates a sandbox from this image instead of the default snapshot. * This is required when you want to customize resources. * * @example "node:20" or "python:3.12" */ image?: string; /** * Snapshot name to use for the sandbox. * * When specified, creates a sandbox from this snapshot. * Cannot be used together with `image`. */ snapshot?: string; /** * Target region where the sandbox will be created. * * @default "us" */ target?: DaytonaSandboxTarget; /** * Auto-stop interval in minutes. * * The sandbox will automatically stop after being idle for this duration. * Set to 0 to disable auto-stop. * * @default 15 */ autoStopInterval?: number; /** * Auto-archive interval in minutes. * * The sandbox will automatically archive after being stopped for this duration. */ autoArchiveInterval?: number; /** * Auto-delete interval in minutes. * * The sandbox will automatically delete after being stopped for this duration. */ autoDeleteInterval?: number; /** * Default timeout for command execution in seconds. * * @default 300 (5 minutes) */ timeout?: number; /** * Custom labels to attach to the sandbox. * * Labels can be used for organizing and filtering sandboxes. */ labels?: Record; /** * Initial files to create in the sandbox after initialization. * * A map of file paths to their contents. Files will be created * in the sandbox filesystem before any commands are executed. * Parent directories are created automatically. * * @example * ```typescript * const options: DaytonaSandboxOptions = { * language: "typescript", * initialFiles: { * "/app/index.js": "console.log('Hello')", * "/app/package.json": '{"name": "test"}', * }, * }; * ``` */ initialFiles?: Record; /** * Authentication configuration for Daytona API. * * ### Environment Variable Setup * * ```bash * # Get your API key from https://app.daytona.io * export DAYTONA_API_KEY=your_api_key_here * ``` * * Or pass the API key directly in this auth configuration. */ auth?: { /** * Daytona API key. * If not provided, reads from `DAYTONA_API_KEY` environment variable. */ apiKey?: string; /** * Daytona API URL. * If not provided, reads from `DAYTONA_API_URL` environment variable * or uses the default Daytona API URL. * * @default "https://app.daytona.io/api" */ apiUrl?: string; }; } /** * Error codes for Daytona Sandbox operations. * * Used to identify specific error conditions and handle them appropriately. */ 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"; declare const DAYTONA_SANDBOX_ERROR_SYMBOL: unique symbol; /** * Custom error class for Daytona Sandbox operations. * * Provides structured error information including: * - Human-readable message * - Error code for programmatic handling * - Original cause for debugging * * @example * ```typescript * try { * await sandbox.execute("some command"); * } catch (error) { * if (error instanceof DaytonaSandboxError) { * switch (error.code) { * case "NOT_INITIALIZED": * await sandbox.initialize(); * break; * case "COMMAND_TIMEOUT": * console.error("Command took too long"); * break; * default: * throw error; * } * } * } * ``` */ declare class DaytonaSandboxError extends SandboxError { readonly code: DaytonaSandboxErrorCode; readonly cause?: Error | undefined; /** Symbol for identifying sandbox error instances */ [DAYTONA_SANDBOX_ERROR_SYMBOL]: true; /** Error name for instanceof checks and logging */ readonly name = "DaytonaSandboxError"; /** * Creates a new DaytonaSandboxError. * * @param message - Human-readable error description * @param code - Structured error code for programmatic handling * @param cause - Original error that caused this error (for debugging) */ constructor(message: string, code: DaytonaSandboxErrorCode, cause?: Error | undefined); /** * Checks if the error is an instance of DaytonaSandboxError. * * @param error - The error to check * @returns True if the error is an instance of DaytonaSandboxError, false otherwise */ static isInstance(error: unknown): error is DaytonaSandboxError; } //#endregion //#region src/sandbox.d.ts /** * Daytona Sandbox backend for deepagents. * * Extends `BaseSandbox` to provide command execution, file operations, and * sandbox lifecycle management using Daytona's SDK. * * ## Basic Usage * * ```typescript * import { DaytonaSandbox } from "@langchain/daytona"; * * // Create and initialize a sandbox * const sandbox = await DaytonaSandbox.create({ * language: "typescript", * timeout: 300, * }); * * try { * // Execute commands * const result = await sandbox.execute("node --version"); * console.log(result.output); * } finally { * // Always cleanup * await sandbox.close(); * } * ``` * * ## Using with DeepAgent * * ```typescript * import { createDeepAgent } from "deepagents"; * import { DaytonaSandbox } from "@langchain/daytona"; * * const sandbox = await DaytonaSandbox.create(); * * const agent = createDeepAgent({ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }), * systemPrompt: "You are a coding assistant with sandbox access.", * backend: sandbox, * }); * ``` */ declare class DaytonaSandbox extends BaseSandbox { #private; /** * Get the unique identifier for this sandbox. * * Before initialization, returns a temporary ID. * After initialization, returns the actual Daytona sandbox ID. */ get id(): string; /** * Get the underlying Daytona Sandbox instance. * * @throws {DaytonaSandboxError} If the sandbox is not initialized * * @example * ```typescript * const sandbox = await DaytonaSandbox.create(); * const daytonaSdk = sandbox.sandbox; // Access the raw SDK * ``` */ get instance(): Sandbox; /** * Get the underlying Daytona client instance. * * @throws {DaytonaSandboxError} If the client is not initialized * * @example * ```typescript * const sandbox = await DaytonaSandbox.create(); * const daytonaClient = sandbox.client; // Access the raw Daytona client * ``` */ get client(): Daytona; /** * Check if the sandbox is initialized and running. */ get isRunning(): boolean; /** * Create a new DaytonaSandbox instance. * * Note: This only creates the instance. Call `initialize()` to actually * create the Daytona Sandbox, or use the static `DaytonaSandbox.create()` method. * * @param options - Configuration options for the sandbox * * @example * ```typescript * // Two-step initialization * const sandbox = new DaytonaSandbox({ language: "typescript" }); * await sandbox.initialize(); * * // Or use the factory method * const sandbox = await DaytonaSandbox.create({ language: "typescript" }); * ``` */ constructor(options?: DaytonaSandboxOptions); /** * Initialize the sandbox by creating a new Daytona Sandbox instance. * * This method authenticates with Daytona and provisions a new sandbox. * After initialization, the `id` property will reflect the actual sandbox ID. * * @throws {DaytonaSandboxError} If already initialized (`ALREADY_INITIALIZED`) * @throws {DaytonaSandboxError} If authentication fails (`AUTHENTICATION_FAILED`) * @throws {DaytonaSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`) * * @example * ```typescript * const sandbox = new DaytonaSandbox(); * await sandbox.initialize(); * console.log(`Sandbox ID: ${sandbox.id}`); * ``` */ initialize(): Promise; /** * Execute a command in the sandbox. * * Commands are run using the sandbox's shell. * * @param command - The shell command to execute * @returns Execution result with output, exit code, and truncation flag * @throws {DaytonaSandboxError} If the sandbox is not initialized * * @example * ```typescript * const result = await sandbox.execute("echo 'Hello World'"); * console.log(result.output); // "Hello World\n" * console.log(result.exitCode); // 0 * ``` */ execute(command: string): Promise; /** * Upload files to the sandbox. * * Files are written to the sandbox filesystem. Parent directories are * created automatically if they don't exist. * * @param files - Array of [path, content] tuples to upload * @returns Upload result for each file, with success or error status * * @example * ```typescript * const encoder = new TextEncoder(); * const results = await sandbox.uploadFiles([ * ["src/index.js", encoder.encode("console.log('Hello')")], * ["package.json", encoder.encode('{"name": "test"}')], * ]); * ``` */ uploadFiles(files: Array<[string, Uint8Array]>): Promise; /** * Download files from the sandbox. * * Each file is read individually, allowing partial success when some * files exist and others don't. * * @param paths - Array of file paths to download * @returns Download result for each file, with content or error * * @example * ```typescript * const results = await sandbox.downloadFiles(["src/index.js", "missing.txt"]); * for (const result of results) { * if (result.content) { * console.log(new TextDecoder().decode(result.content)); * } else { * console.error(`Error: ${result.error}`); * } * } * ``` */ downloadFiles(paths: string[]): Promise; /** * Close the sandbox and release all resources. * * After closing, the sandbox cannot be used again. The sandbox is deleted * from Daytona's infrastructure. * * @example * ```typescript * try { * await sandbox.execute("npm run build"); * } finally { * await sandbox.close(); * } * ``` */ close(): Promise; /** * Stop the sandbox without deleting it. * * The sandbox can be restarted later using `start()`. * * @example * ```typescript * await sandbox.stop(); * // Later... * await sandbox.start(); * ``` */ stop(): Promise; /** * Start a stopped sandbox. * * @param timeout - Maximum time to wait in seconds (default: 60) * * @example * ```typescript * await sandbox.start(); * console.log("Sandbox is now running"); * ``` */ start(timeout?: number): Promise; /** * Forcefully terminate and delete the sandbox. * * Use this when you need to immediately stop the sandbox. * * @example * ```typescript * await sandbox.kill(); * ``` */ kill(): Promise; /** * Get the working directory path inside the sandbox. * * @returns The absolute path to the sandbox working directory * * @example * ```typescript * const workDir = await sandbox.getWorkDir(); * console.log(`Working directory: ${workDir}`); * ``` */ getWorkDir(): Promise; /** * Get the user's home directory path inside the sandbox. * * @returns The absolute path to the user's home directory * * @example * ```typescript * const homeDir = await sandbox.getUserHomeDir(); * console.log(`Home directory: ${homeDir}`); * ``` */ getUserHomeDir(): Promise; /** * Create and initialize a new DaytonaSandbox in one step. * * This is the recommended way to create a sandbox. It combines * construction and initialization into a single async operation. * * @param options - Configuration options for the sandbox * @returns An initialized and ready-to-use sandbox * * @example * ```typescript * const sandbox = await DaytonaSandbox.create({ * language: "typescript", * cpu: 2, * memory: 4, * }); * ``` */ static create(options?: DaytonaSandboxOptions): Promise; /** * Delete all sandboxes matching the given labels. * * This is useful for cleaning up stale sandboxes from previous test runs * or CI pipelines that may not have shut down cleanly. * * @param labels - Label key-value pairs to filter sandboxes * @param options - Optional auth configuration * @returns The number of sandboxes that were deleted * * @example * ```typescript * // Clean up all integration-test sandboxes * const deleted = await DaytonaSandbox.deleteAll({ * purpose: "integration-test", * package: "@langchain/daytona", * }); * console.log(`Deleted ${deleted} stale sandboxes`); * ``` */ static deleteAll(labels: Record, options?: Pick): Promise; /** * Connect to an existing sandbox by ID. * * This allows you to resume working with a sandbox that was created * earlier or that is still running. * * @param sandboxId - The ID of the sandbox to connect to * @param options - Optional auth configuration (for API key) * @returns A connected sandbox instance * * @example * ```typescript * // Resume a sandbox from a stored ID * const sandbox = await DaytonaSandbox.connect("sandbox-abc123"); * const result = await sandbox.execute("ls -la"); * ``` */ static fromId(id: string, options?: Pick): Promise; /** * Get a running sandbox by name from a deployed app. * * @param name - The name of the sandbox * @param options - Optional auth configuration * @returns A connected sandbox instance */ static fromName(name: string, options?: Pick): Promise; } /** * Async factory function type for creating Daytona Sandbox instances. * * This is similar to BackendFactory but supports async creation, * which is required for Daytona Sandbox since initialization is async. */ type AsyncDaytonaSandboxFactory = () => Promise; /** * Create an async factory function that creates a new Daytona Sandbox per invocation. * * Each call to the factory will create and initialize a new sandbox. * This is useful when you want fresh, isolated environments for each * agent invocation. * * **Important**: This returns an async factory. For use with middleware that * requires synchronous BackendFactory, use `createDaytonaSandboxFactoryFromSandbox()` * with a pre-created sandbox instead. * * @param options - Optional configuration for sandbox creation * @returns An async factory function that creates new sandboxes * * @example * ```typescript * import { DaytonaSandbox, createDaytonaSandboxFactory } from "@langchain/daytona"; * * // Create a factory for new sandboxes * const factory = createDaytonaSandboxFactory({ language: "typescript" }); * * // Each call creates a new sandbox * const sandbox1 = await factory(); * const sandbox2 = await factory(); * * try { * // Use sandboxes... * } finally { * await sandbox1.close(); * await sandbox2.close(); * } * ``` */ declare function createDaytonaSandboxFactory(options?: DaytonaSandboxOptions): AsyncDaytonaSandboxFactory; /** * Create a backend factory that reuses an existing Daytona Sandbox. * * This allows multiple agent invocations to share the same sandbox, * avoiding the startup overhead of creating new sandboxes. * * Important: You are responsible for managing the sandbox lifecycle * (calling `close()` when done). * * @param sandbox - An existing DaytonaSandbox instance (must be initialized) * @returns A BackendFactory that returns the provided sandbox * * @example * ```typescript * import { createDeepAgent, createFilesystemMiddleware } from "deepagents"; * import { DaytonaSandbox, createDaytonaSandboxFactoryFromSandbox } from "@langchain/daytona"; * * // Create and initialize a sandbox * const sandbox = await DaytonaSandbox.create({ language: "typescript" }); * * try { * const agent = createDeepAgent({ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }), * systemPrompt: "You are a coding assistant.", * middlewares: [ * createFilesystemMiddleware({ * backend: createDaytonaSandboxFactoryFromSandbox(sandbox), * }), * ], * }); * * await agent.invoke({ messages: [...] }); * } finally { * await sandbox.close(); * } * ``` */ declare function createDaytonaSandboxFactoryFromSandbox(sandbox: DaytonaSandbox): BackendFactory; //#endregion //#region src/auth.d.ts /** * Authentication credentials for Daytona API. */ interface DaytonaCredentials { /** Daytona API key */ apiKey: string; /** Daytona API URL */ apiUrl: string; /** Target region */ target?: string; } /** * Get the API key for Daytona API. * * Authentication is resolved in the following priority order: * * 1. **Explicit API key**: If `options.apiKey` is provided, it is used directly. * 2. **DAYTONA_API_KEY**: Environment variable for Daytona API key. * * If no API key is found, an error is thrown with setup instructions. * * ## Environment Variable Setup * * ```bash * # Get your API key from https://app.daytona.io * export DAYTONA_API_KEY=your_api_key_here * ``` * * @param options - Optional authentication configuration from DaytonaSandboxOptions * @returns The API key string * @throws {Error} If no API key is available * * @example * ```typescript * // With explicit API key * const apiKey = getAuthApiKey({ apiKey: "my-api-key" }); * * // Using environment variables (auto-detected) * const apiKey = getAuthApiKey(); * * // From DaytonaSandboxOptions * const options: DaytonaSandboxOptions = { * auth: { apiKey: "my-api-key" } * }; * const apiKey = getAuthApiKey(options.auth); * ``` */ declare function getAuthApiKey(options?: DaytonaSandboxOptions["auth"]): string; /** * Get the API URL for Daytona API. * * URL is resolved in the following priority order: * * 1. **Explicit API URL**: If `options.apiUrl` is provided, it is used directly. * 2. **DAYTONA_API_URL**: Environment variable for Daytona API URL. * 3. **Default**: Uses the default Daytona API URL. * * @param options - Optional authentication configuration from DaytonaSandboxOptions * @returns The API URL string */ declare function getAuthApiUrl(options?: DaytonaSandboxOptions["auth"]): string; /** * Get authentication credentials for Daytona API. * * This function returns the credentials needed for the Daytona SDK. * * @param options - Optional authentication configuration from DaytonaSandboxOptions * @param target - Optional target region * @returns Complete authentication credentials * @throws {Error} If no API key is available */ declare function getAuthCredentials(options?: DaytonaSandboxOptions["auth"], target?: string): DaytonaCredentials; //#endregion export { type AsyncDaytonaSandboxFactory, type DaytonaCredentials, DaytonaSandbox, DaytonaSandboxError, type DaytonaSandboxErrorCode, type DaytonaSandboxOptions, type DaytonaSandboxTarget, createDaytonaSandboxFactory, createDaytonaSandboxFactoryFromSandbox, getAuthApiKey, getAuthApiUrl, getAuthCredentials }; //# sourceMappingURL=index.d.cts.map