import * as _$zod_v30 from "zod/v3"; import * as _langchain from "langchain"; import { AgentMiddleware, AgentMiddleware as AgentMiddleware$1, AgentRunStream, AgentTypeConfig, CreateAgentParams, HumanMessage, InferMiddlewareStates, InterruptOnConfig, ProviderStrategy, ReactAgent, ResponseFormat, ResponseFormatUndefined, Runtime, StructuredTool, SystemMessage, ToolCallStreamUnion, ToolMessage, ToolRuntime, ToolStrategy } from "langchain"; import * as _langgraph from "@langchain/langgraph"; import { AnnotationRoot, ChatModelStream, Command, Namespace, NativeStreamTransformer, ReducedValue, StateSchema, StreamTransformer } from "@langchain/langgraph"; import { z } from "zod/v4"; import { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint"; import * as _messages from "@langchain/core/messages"; import * as z$2 from "zod"; import { z as z$1 } from "zod"; import * as _$zod_v4_core0 from "zod/v4/core"; import * as _$_langchain_core_tools0 from "@langchain/core/tools"; import { ClientTool, ServerTool, StructuredTool as StructuredTool$1 } from "@langchain/core/tools"; import { InteropZodObject } from "@langchain/core/utils/types"; import { BaseLanguageModel, LanguageModelLike } from "@langchain/core/language_models/base"; import { Client } from "langsmith"; import { CaptureSnapshotOptions, CaptureSnapshotOptions as LangSmithCaptureSnapshotOptions, CreateSandboxOptions, Sandbox, Snapshot, Snapshot as LangSmithSnapshot, StartSandboxOptions, StartSandboxOptions as LangSmithStartSandboxOptions } from "langsmith/experimental/sandbox"; import { Runnable } from "@langchain/core/runnables"; import { BaseChatModel } from "@langchain/core/language_models/chat_models"; //#region src/backends/v1/protocol.d.ts /** * Protocol for pluggable memory backends (single, unified). * * Backends can store files in different locations (state, filesystem, database, etc.) * and provide a uniform interface for file operations. * * All file data is represented as objects with the FileData structure. * * Methods can return either direct values or Promises, allowing both * synchronous and asynchronous implementations. * * @deprecated Use {@link BackendProtocolV2} instead. */ interface BackendProtocolV1 { /** * Structured listing with file metadata. * * Lists files and directories in the specified directory (non-recursive). * Directories have a trailing / in their path and is_dir=true. * * @param path - Absolute path to directory * @returns List of FileInfo objects for files and directories directly in the directory */ lsInfo(path: string): MaybePromise; /** * Read file content. * * @param filePath - Absolute file path * @param offset - Line offset to start reading from (0-indexed), default 0 * @param limit - Maximum number of lines to read, default 500 * @returns File content as plain string on success or error on failure */ read(filePath: string, offset?: number, limit?: number): MaybePromise; /** * Read file content as raw FileData. * * @param filePath - Absolute file path * @returns Raw file content as FileData */ readRaw(filePath: string): MaybePromise; /** * Search file contents for a literal text pattern. * * Binary files (determined by MIME type) are skipped. * * @param pattern - Literal text pattern to search for * @param path - Base path to search from (default: null) * @param glob - Optional glob pattern to filter files (e.g., "*.py") * @returns Array of GrepMatch on success or error string on failure */ grepRaw(pattern: string, path?: string | null, glob?: string | null): MaybePromise; /** * Structured glob matching returning FileInfo objects. * * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`) * @param path - Base path to search from (default: "/") * @returns List of FileInfo objects matching the pattern */ globInfo(pattern: string, path?: string): MaybePromise; /** * Create a new file. * * @param filePath - Absolute file path * @param content - File content as string * @returns WriteResult with error populated on failure */ write(filePath: string, content: string): MaybePromise; /** * Edit a file by replacing string occurrences. * * @param filePath - Absolute file path * @param oldString - String to find and replace * @param newString - Replacement string * @param replaceAll - If true, replace all occurrences (default: false) * @returns EditResult with error, path, filesUpdate, and occurrences */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): MaybePromise; /** * Upload multiple files. * Optional - backends that don't support file upload can omit this. * * @param files - List of [path, content] tuples to upload * @returns List of FileUploadResponse objects, one per input file */ uploadFiles?(files: Array<[string, Uint8Array]>): MaybePromise; /** * Download multiple files. * Optional - backends that don't support file download can omit this. * * @param paths - List of file paths to download * @returns List of FileDownloadResponse objects, one per input path */ downloadFiles?(paths: string[]): MaybePromise; } /** * Protocol for sandboxed backends with isolated runtime. * Sandboxed backends run in isolated environments (e.g., containers) * and communicate via defined interfaces. * * @deprecated Use {@link SandboxBackendProtocolV2} instead. */ interface SandboxBackendProtocolV1 extends BackendProtocolV1 { /** * Execute a command in the sandbox. * * @param command - Full shell command string to execute * @returns ExecuteResponse with combined output, exit code, and truncation flag */ execute(command: string): MaybePromise; /** Unique identifier for the sandbox backend instance */ readonly id: string; } //#endregion //#region src/backends/v2/protocol.d.ts /** * Updated protocol for pluggable memory backends. * * Key differences from {@link BackendProtocol}: * - `read()` returns {@link ReadResult} instead of a plain string * - `readRaw()` returns {@link ReadRawResult} instead of FileData * - `grep()` returns {@link GrepResult} instead of `GrepMatch[] | string` * - `ls()` returns {@link LsResult} instead of FileInfo[] * - `glob()` returns {@link GlobResult} instead of FileInfo[] * * Existing v1 backends can be adapted to this interface using * {@link adaptBackendProtocol} from utils. */ interface BackendProtocolV2 extends Omit { /** * Structured listing with file metadata. * * Lists files and directories in the specified directory (non-recursive). * Directories have a trailing / in their path and is_dir=true. * * @param path - Absolute path to directory * @returns LsResult with list of FileInfo objects on success or error on failure */ ls(path: string): MaybePromise; /** * Read file content. * * For text files, content is paginated by line offset/limit. * For binary files, the full raw Uint8Array content is returned. * * @param filePath - Absolute file path * @param offset - Line offset to start reading from (0-indexed), default 0 * @param limit - Maximum number of lines to read, default 500 * @returns ReadResult with content on success or error on failure */ read(filePath: string, offset?: number, limit?: number): MaybePromise; /** * Read file content as raw FileData. * * @param filePath - Absolute file path * @returns ReadRawResult with raw file data on success or error on failure */ readRaw(filePath: string): MaybePromise; /** * Search file contents for a literal text pattern. * * Binary files (determined by MIME type) are skipped. * * @param pattern - Literal text pattern to search for * @param path - Base path to search from (default: null) * @param glob - Optional glob pattern to filter files (e.g., "*.py") * @returns GrepResult with matches on success or error on failure */ grep(pattern: string, path?: string | null, glob?: string | null): MaybePromise; /** * Structured glob matching returning FileInfo objects. * * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`) * @param path - Base path to search from (default: "/") * @returns GlobResult with list of FileInfo objects matching the pattern on success or error on failure */ glob(pattern: string, path?: string): MaybePromise; } /** * Protocol for sandboxed backends with isolated runtime. * * Key differences from {@link SandboxBackendProtocol}: * - Extends {@link BackendProtocolV2} instead of {@link BackendProtocol} * - All methods return structured Result types for consistent error handling */ interface SandboxBackendProtocolV2 extends BackendProtocolV2 { /** * Execute a command in the sandbox. * * @param command - Full shell command string to execute * @returns ExecuteResponse with combined output, exit code, and truncation flag */ execute(command: string): MaybePromise; /** Unique identifier for the sandbox backend instance */ readonly id: string; } //#endregion //#region src/backends/protocol.d.ts /** @deprecated Use {@link BackendProtocolV2} instead. */ interface BackendProtocol extends BackendProtocolV1 {} /** @deprecated Use {@link SandboxBackendProtocolV2} instead. */ interface SandboxBackendProtocol extends SandboxBackendProtocolV1 {} type MaybePromise = T | Promise; /** * Structured file listing info. * * Minimal contract used across backends. Only "path" is required. * Other fields are best-effort and may be absent depending on backend. */ interface FileInfo { /** File path */ path: string; /** Whether this is a directory */ is_dir?: boolean; /** File size in bytes (approximate) */ size?: number; /** ISO 8601 timestamp of last modification */ modified_at?: string; } /** * Structured grep match entry. */ interface GrepMatch { /** File path where match was found */ path: string; /** Line number (1-indexed) */ line: number; /** The matching line text */ text: string; } /** * Structured result from grep/search operations. */ interface GrepResult { /** Error message on failure, undefined on success */ error?: string; /** Structured grep match entries, undefined on failure */ matches?: GrepMatch[]; } /** * Legacy file data format (v1). * * Content is stored as an array of lines (split on "\n"). This format * only supports text files and is retained for backwards compatibility * with existing state/store data. */ interface FileDataV1 { /** File content as an array of lines */ content: string[]; /** ISO format timestamp of creation */ created_at: string; /** ISO format timestamp of last modification */ modified_at: string; } /** * Current file data format (v2). * * Content is stored as a string for text files, or as a Uint8Array for * binary files (images, PDFs, audio, etc.). The MIME type is stored * alongside the content, allowing backend implementations to determine * it however they see fit (e.g. from file extension, HTTP headers, * database metadata, etc.). */ interface FileDataV2 { /** File content: string for text, Uint8Array for binary */ content: string | Uint8Array; /** MIME type of the file (e.g. "image/png", "text/plain") */ mimeType: string; /** ISO format timestamp of creation */ created_at: string; /** ISO format timestamp of last modification */ modified_at: string; } /** * Union of v1 and v2 file data formats. * * Backends may encounter either format when reading from state or store * (v1 from legacy data, v2 from new writes). Use {@link isFileDataV1} * from utils for runtime discrimination. */ type FileData = FileDataV1 | FileDataV2; /** * Structured result from backend read operations. * * Replaces the previous plain string return, giving callers a * programmatic way to distinguish errors from content. */ interface ReadResult { /** Error message on failure, undefined on success */ error?: string; /** File content: string for text, Uint8Array for binary. Undefined on failure. */ content?: string | Uint8Array; /** MIME type of the file, when available */ mimeType?: string; } /** * Structured result from backend readRaw operations. */ interface ReadRawResult { /** Error message on failure, undefined on success */ error?: string; /** Raw file data, undefined on failure */ data?: FileData; } /** * Structured result from backend ls operations. */ interface LsResult { /** Error message on failure, undefined on success */ error?: string; /** List of FileInfo objects, undefined on failure */ files?: FileInfo[]; } /** * Structured result from backend glob operations. */ interface GlobResult { /** Error message on failure, undefined on success */ error?: string; /** List of FileInfo objects matching the pattern, undefined on failure */ files?: FileInfo[]; } /** * Result from backend write operations. * * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state. * External backends set filesUpdate to null (already persisted to disk/S3/database/etc). */ interface WriteResult { /** Error message on failure, undefined on success */ error?: string; /** File path of written file, undefined on failure */ path?: string; /** * State update dict for checkpoint backends, null for external storage. * Checkpoint backends populate this with {file_path: file_data} for LangGraph state. * External backends set null (already persisted to disk/S3/database/etc). * * @deprecated Zero-arg backends send state updates internally via * `__pregel_send`. Check `if (result.filesUpdate)` before using. */ filesUpdate?: Record | null; /** Metadata for the write operation, attached to the ToolMessage */ metadata?: Record; } /** * Result from backend edit operations. * * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state. * External backends set filesUpdate to null (already persisted to disk/S3/database/etc). */ interface EditResult { /** Error message on failure, undefined on success */ error?: string; /** File path of edited file, undefined on failure */ path?: string; /** * State update dict for checkpoint backends, null for external storage. * Checkpoint backends populate this with {file_path: file_data} for LangGraph state. * External backends set null (already persisted to disk/S3/database/etc). * * @deprecated Zero-arg backends send state updates internally via * `__pregel_send`. Check `if (result.filesUpdate)` before using. */ filesUpdate?: Record | null; /** Number of replacements made, undefined on failure */ occurrences?: number; /** Metadata for the edit operation, attached to the ToolMessage */ metadata?: Record; } /** * Result of code execution. * Simplified schema optimized for LLM consumption. */ interface ExecuteResponse { /** Combined stdout and stderr output of the executed command */ output: string; /** The process exit code. 0 indicates success, non-zero indicates failure */ exitCode: number | null; /** Whether the output was truncated due to backend limitations */ truncated: boolean; } /** * Standardized error codes for file upload/download operations. */ type FileOperationError = "file_not_found" | "permission_denied" | "is_directory" | "invalid_path"; /** * Result of a single file download operation. */ interface FileDownloadResponse { /** The file path that was requested */ path: string; /** File contents as Uint8Array on success, null on failure */ content: Uint8Array | null; /** Standardized error code on failure, null on success */ error: FileOperationError | null; } /** * Result of a single file upload operation. */ interface FileUploadResponse { /** The file path that was requested */ path: string; /** Standardized error code on failure, null on success */ error: FileOperationError | null; } /** * Common options shared across backend constructors. */ interface BackendOptions { /** File data format to use for new writes. Defaults to "v2". */ fileFormat?: "v1" | "v2"; } /** * Type guard to check if a backend supports execution. * * @param backend - Backend instance to check * @returns True if the backend implements SandboxBackendProtocolV2 */ declare function isSandboxBackend(backend: unknown): backend is SandboxBackendProtocolV2; /** * Union of v1 and v2 sandbox backend protocols. * * Use this when accepting either protocol version. Pass through * {@link adaptSandboxProtocol} to normalize to {@link SandboxBackendProtocolV2}. */ type AnySandboxProtocol = SandboxBackendProtocol | SandboxBackendProtocolV2; /** * Type guard to check if a backend is a sandbox protocol (v1 or v2). * * Checks for the presence of `execute` function and `id` string, * which are the defining features of sandbox protocols. * * @param backend - Backend instance to check * @returns True if the backend implements sandbox protocol (v1 or v2) */ declare function isSandboxProtocol(backend: unknown): backend is AnySandboxProtocol; /** * Metadata for a single sandbox instance. * * This lightweight structure is returned from list operations and provides * basic information about a sandbox without requiring a full connection. * * @typeParam MetadataT - Type of the metadata field. Providers can define * their own interface for type-safe metadata access. * * @example * ```typescript * // Using default metadata type * const info: SandboxInfo = { * sandboxId: "sb_abc123", * metadata: { status: "running", createdAt: "2024-01-15T10:30:00Z" }, * }; * * // Using typed metadata * interface MyMetadata { * status: "running" | "stopped"; * createdAt: string; * } * const typedInfo: SandboxInfo = { * sandboxId: "sb_abc123", * metadata: { status: "running", createdAt: "2024-01-15T10:30:00Z" }, * }; * ``` */ interface SandboxInfo> { /** Unique identifier for the sandbox instance */ sandboxId: string; /** Optional provider-specific metadata (e.g., creation time, status, template) */ metadata?: MetadataT; } /** * Paginated response from a sandbox list operation. * * This structure supports cursor-based pagination for efficiently browsing * large collections of sandboxes. * * @typeParam MetadataT - Type of the metadata field in SandboxInfo items. * * @example * ```typescript * const response: SandboxListResponse = { * items: [ * { sandboxId: "sb_001", metadata: { status: "running" } }, * { sandboxId: "sb_002", metadata: { status: "stopped" } }, * ], * cursor: "eyJvZmZzZXQiOjEwMH0=", * }; * * // Fetch next page * const nextResponse = await provider.list({ cursor: response.cursor }); * ``` */ interface SandboxListResponse> { /** List of sandbox metadata objects for the current page */ items: SandboxInfo[]; /** * Opaque continuation token for retrieving the next page. * null indicates no more pages available. */ cursor: string | null; } /** * Options for listing sandboxes. */ interface SandboxListOptions { /** * Continuation token from a previous list() call. * Pass undefined to start from the beginning. */ cursor?: string; } /** * Options for getting or creating a sandbox. */ interface SandboxGetOrCreateOptions { /** * Unique identifier of an existing sandbox to retrieve. * If undefined, creates a new sandbox instance. * If provided but the sandbox doesn't exist, an error will be thrown. */ sandboxId?: string; } /** * Options for deleting a sandbox. */ interface SandboxDeleteOptions { /** Unique identifier of the sandbox to delete */ sandboxId: string; } /** * Common error codes shared across all sandbox provider implementations. * * These represent the core error conditions that any sandbox provider may encounter. * Provider-specific error codes should extend this type with additional codes. * * @example * ```typescript * // Provider-specific error code type extending the common codes: * type MySandboxErrorCode = SandboxErrorCode | "CUSTOM_ERROR"; * ``` */ type SandboxErrorCode = /** Sandbox has not been initialized - call initialize() first */"NOT_INITIALIZED" /** Sandbox is already initialized - cannot initialize twice */ | "ALREADY_INITIALIZED" /** Command execution timed out */ | "COMMAND_TIMEOUT" /** Command execution failed */ | "COMMAND_FAILED" /** File operation (read/write) failed */ | "FILE_OPERATION_FAILED"; declare const SANDBOX_ERROR_SYMBOL: unique symbol; /** * Custom error class for sandbox operations. * * @param message - Human-readable error description * @param code - Structured error code for programmatic handling * @returns SandboxError with message and code * * @example * ```typescript * try { * await sandbox.execute("some command"); * } catch (error) { * if (error instanceof SandboxError) { * 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 SandboxError extends Error { readonly code: string; readonly cause?: Error | undefined; /** Symbol for identifying sandbox error instances */ [SANDBOX_ERROR_SYMBOL]: true; /** Error name for instanceof checks and logging */ readonly name: string; /** * Creates a new SandboxError. * * @param message - Human-readable error description * @param code - Structured error code for programmatic handling */ constructor(message: string, code: string, cause?: Error | undefined); static isInstance(error: unknown): error is SandboxError; } /** * State and store container for backend initialization. * * This provides a clean interface for what backends need to access: * - state: Current agent state (with files, messages, etc.) * - store: Optional persistent store for cross-conversation data * * Different contexts build this differently: * - Tools: Extract state via getCurrentTaskInput(config) * - Middleware: Use request.state directly * * @deprecated Use {@link BackendRuntime} instead. */ interface StateAndStore { /** Current agent state with files, messages, etc. */ state: unknown; /** Optional BaseStore for persistent cross-conversation storage */ store?: BaseStore; /** Optional assistant ID for per-assistant isolation in store */ assistantId?: string; } /** * Union of v1 and v2 backend protocols. * * Use this when accepting either protocol version. Pass through * {@link adaptBackendProtocol} to normalize to {@link BackendProtocolV2}. */ type AnyBackendProtocol = BackendProtocolV1 | BackendProtocolV2; /** * Agent {@link Runtime} with `state` * * @deprecated Backends now read state from the LangGraph execution context * via `getCurrentTaskInput()`, `getConfig()`, and `getStore()`. */ interface BackendRuntime extends Runtime { /** Current agent state with files, messages, etc. */ state: StateT; } /** * Factory function type for creating backend instances. * * Backends receive {@link BackendRuntime} which contains the current state * and runtime information, extracted from the execution context. * * @deprecated Pass a pre-constructed backend instance instead of a factory. * E.g., `backend: new StateBackend()` instead of `backend: (runtime) => new StateBackend(runtime)`. * * @example * ```typescript * // Using in middleware * const middleware = createFilesystemMiddleware({ * backend: (runtime) => new StateBackend(runtime) * }); * ``` */ type BackendFactory = (runtime: BackendRuntime) => MaybePromise; /** * Resolve a backend instance or await a {@link BackendFactory}. * * Accepts {@link BackendRuntime} or {@link ToolRuntime} — store typing differs * between LangGraph checkpoint stores and core `ToolRuntime`; factories receive * a value that is structurally compatible at runtime. * * @internal */ declare function resolveBackend(backend: AnyBackendProtocol | BackendFactory, runtime: BackendRuntime | ToolRuntime): Promise; //#endregion //#region src/permissions/types.d.ts /** * The filesystem operations a permission rule can govern. */ type FilesystemOperation = "read" | "write"; /** * Whether a matched rule permits or blocks the operation. */ type PermissionMode = "allow" | "deny"; /** * A single filesystem permission rule. * * Rules are evaluated in declaration order; the first rule whose * `operations` includes the requested operation AND whose `paths` * glob-matches the target path determines the outcome. If no rule * matches, access is **allowed** (permissive default). * * All `paths` must be absolute glob patterns (start with `/`, no `..` or `~`). * Supports `**` (any depth), `*` (within one segment), and `{a,b}` brace expansion. * Paths are validated when passed to {@link createFilesystemMiddleware}. */ interface FilesystemPermission { /** * The operations this rule applies to. */ operations: readonly FilesystemOperation[]; /** * Absolute glob patterns for paths this rule matches. * Must start with `/`; must not contain `..` or `~`. * Supports `**` (any depth), `*` (within one segment), and `{a,b}` brace expansion. */ paths: string[]; /** * Whether matching paths are permitted or blocked. Defaults to `"allow"`. */ mode?: PermissionMode; } //#endregion //#region src/middleware/fs.d.ts /** * Tools that should be excluded from the large result eviction logic. * * This array contains tools that should NOT have their results evicted to the filesystem * when they exceed token limits. Tools are excluded for different reasons: * * 1. Tools with built-in truncation (ls, glob, grep): * These tools truncate their own output when it becomes too large. When these tools * produce truncated output due to many matches, it typically indicates the query * needs refinement rather than full result preservation. In such cases, the truncated * matches are potentially more like noise and the LLM should be prompted to narrow * its search criteria instead. * * 2. Tools with problematic truncation behavior (read_file): * read_file is tricky to handle as the failure mode here is single long lines * (e.g., imagine a jsonl file with very long payloads on each line). If we try to * truncate the result of read_file, the agent may then attempt to re-read the * truncated file using read_file again, which won't help. * * 3. Tools that never exceed limits (edit_file, write_file): * These tools return minimal confirmation messages and are never expected to produce * output large enough to exceed token limits, so checking them would be unnecessary. */ /** * All tool names registered by FilesystemMiddleware. * This is the single source of truth — used by createDeepAgent to detect * collisions with user-supplied tools at construction time. */ declare const FILESYSTEM_TOOL_NAMES: readonly ["ls", "read_file", "write_file", "edit_file", "glob", "grep", "execute"]; /** * Type for the files state record. */ type FilesRecord = Record; /** * Type for file updates, where null indicates deletion. */ type FilesRecordUpdate = Record; /** * Options for creating filesystem middleware. */ interface FilesystemMiddlewareOptions { /** Backend instance or factory (default: StateBackend) */ backend?: AnyBackendProtocol | BackendFactory; /** Optional custom system prompt override */ systemPrompt?: string | null; /** Optional custom tool descriptions override */ customToolDescriptions?: Record | null; /** Optional token limit before evicting a tool result to the filesystem (default: 20000 tokens, ~80KB) */ toolTokenLimitBeforeEvict?: number | null; /** Optional token limit before evicting a HumanMessage to the filesystem (default: 50000 tokens, ~200KB) */ humanMessageTokenLimitBeforeEvict?: number | null; /** * Filesystem permission rules enforced on every tool call. * * Rules are evaluated in declaration order; first match wins; permissive * default. Applies to `ls`, `read_file`, `write_file`, `edit_file`, * `glob`, and `grep`. * * **Note on `execute`**: permissions are not enforced on `execute` because * shell commands can access any path regardless of path-based rules. Using * permissions with an execution-capable backend (one where `isSandboxBackend` * returns `true`) throws a `ConfigurationError` unless the backend is a * `CompositeBackend` and every permission path is scoped to a route prefix. * * When omitted or empty, all filesystem operations are permitted. */ permissions?: FilesystemPermission[]; } /** * Create filesystem middleware with all tools and features. */ declare function createFilesystemMiddleware(options?: FilesystemMiddlewareOptions): AgentMiddleware; }>, undefined, unknown, (_langchain.DynamicStructuredTool>; }, z.core.$strip>, { path: string; }, { path?: string | undefined; }, string, unknown, "ls"> | _langchain.DynamicStructuredTool>>; limit: z.ZodDefault>>; }, z.core.$strip>, { file_path: string; offset: number; limit: number; }, { file_path: string; offset?: unknown; limit?: unknown; }, { type: string; text: string; }[] | { type: string; mimeType: string; data: string; }[], unknown, "read_file"> | _langchain.DynamicStructuredTool; }, z.core.$strip>, { file_path: string; content: string; }, { file_path: string; content?: string | undefined; }, string | ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | Command; messages: ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[]; }, string>, unknown, "write_file"> | _langchain.DynamicStructuredTool>; }, z.core.$strip>, { file_path: string; old_string: string; new_string: string; replace_all: boolean; }, { file_path: string; old_string: string; new_string: string; replace_all?: boolean | undefined; }, string | ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | Command; messages: ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[]; }, string>, unknown, "edit_file"> | _langchain.DynamicStructuredTool>; }, z.core.$strip>, { pattern: string; path: string; }, { pattern: string; path?: string | undefined; }, string, unknown, "glob"> | _langchain.DynamicStructuredTool>; glob: z.ZodDefault>>; }, z.core.$strip>, { pattern: string; path: string; glob: string | null; }, { pattern: string; path?: string | undefined; glob?: string | null | undefined; }, string, unknown, "grep"> | _langchain.DynamicStructuredTool, { command: string; }, { command: string; }, string, unknown, "execute">)[]>; //#endregion //#region src/backends/state.d.ts /** * Backend that stores files in agent state (ephemeral). * * Uses LangGraph's state management and checkpointing. Files persist within * a conversation thread but not across threads. State is automatically * checkpointed after each agent step. * * Special handling: Since LangGraph state must be updated via Command objects * (not direct mutation), operations return filesUpdate in WriteResult/EditResult * for the middleware to apply via Command. */ declare class StateBackend implements BackendProtocolV2 { private runtime; private fileFormat; constructor(options?: BackendOptions); /** * @deprecated Pass no `runtime` argument */ constructor(runtime: BackendRuntime, options?: BackendOptions); /** * Whether this instance was constructed with the legacy factory pattern. * * When true, state is read from the injected `runtime` and `filesUpdate` * is returned to the caller. When false, state is read from LangGraph's * execution context and updates are sent via `__pregel_send`. */ private get isLegacy(); /** * Get files from current state. * * In legacy mode, reads from the injected {@link BackendRuntime}. * In zero-arg mode, reads via {@link PREGEL_READ_KEY} with fresh=true, * which applies any pending task writes through the reducer before returning. */ private get files(); /** * Push a files state update through LangGraph's internal send channel. * * In zero-arg mode, sends the update via the `__pregel_send` function * from {@link getConfig}, mirroring Python's `CONFIG_KEY_SEND`. * In legacy mode, this is a no-op — the caller uses `filesUpdate` * from the return value instead. * * @param update - Map of file paths to their updated {@link FileData} */ private sendFilesUpdate; /** * List files and directories in the specified directory (non-recursive). * * @param path - Absolute path to directory * @returns LsResult with list of FileInfo objects on success or error on failure. * Directories have a trailing / in their path and is_dir=true. */ ls(path: string): LsResult; /** * Read file content. * * Text files are paginated by line offset/limit. * Binary files return full Uint8Array content (offset/limit ignored). * * @param filePath - Absolute file path * @param offset - Line offset to start reading from (0-indexed) * @param limit - Maximum number of lines to read * @returns ReadResult with content on success or error on failure */ read(filePath: string, offset?: number, limit?: number): ReadResult; /** * Read file content as raw FileData. * * @param filePath - Absolute file path * @returns ReadRawResult with raw file data on success or error on failure */ readRaw(filePath: string): ReadRawResult; /** * Create a new file with content. * Returns WriteResult with filesUpdate to update LangGraph state. */ write(filePath: string, content: string): WriteResult; /** * Edit a file by replacing string occurrences. * Returns EditResult with filesUpdate and occurrences. */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): EditResult; /** * Search file contents for a literal text pattern. * Binary files are skipped. */ grep(pattern: string, path?: string, glob?: string | null): GrepResult; /** * Structured glob matching returning FileInfo objects. */ glob(pattern: string, path?: string): GlobResult; /** * Upload multiple files. * * Note: Since LangGraph state must be updated via Command objects, * the caller must apply filesUpdate via Command after calling this method. * * @param files - List of [path, content] tuples to upload * @returns List of FileUploadResponse objects, one per input file */ uploadFiles(files: Array<[string, Uint8Array]>): FileUploadResponse[] & { filesUpdate?: Record; }; /** * Download multiple files. * * @param paths - List of file paths to download * @returns List of FileDownloadResponse objects, one per input path */ downloadFiles(paths: string[]): FileDownloadResponse[]; } //#endregion //#region src/backends/store.d.ts /** * Context provided to dynamic namespace factory functions. */ interface StoreBackendContext { /** * Current graph state, when available. * * In legacy factory mode this is the injected runtime state. In zero-arg mode * this is read from the current LangGraph execution context. */ state: StateT; /** * Runnable config, when available. * * This mirrors the Python implementation's access to config metadata for * namespace resolution. */ config?: { metadata?: Record; configurable?: Record; }; /** * Legacy assistant identifier, resolved from config metadata first and then * from the injected runtime for backwards compatibility. */ assistantId?: string; } type StoreBackendNamespaceFactory = (context: StoreBackendContext) => string[]; /** * Options for StoreBackend constructor. */ interface StoreBackendOptions extends BackendOptions { /** * Explicit store instance to use for persistence. * * This mirrors the Python API and allows constructing a backend directly with * a store instance, e.g. `new StoreBackend({ store })`. * * When omitted, the backend uses the legacy injected runtime store or the * LangGraph execution-context store. */ store?: BaseStore; /** * Custom namespace for store operations. * * Accepts either a static namespace array or a factory that derives the * namespace from the current backend context. * * If not provided, falls back to legacy assistant-id detection from config * metadata, then the injected runtime's `assistantId`, and finally * `["filesystem"]`. * * @example * ```typescript * // Static namespace * new StoreBackend({ * namespace: ["memories", orgId, userId, "filesystem"], * }); * * // Dynamic namespace * new StoreBackend({ * namespace: ({ state }) => [ * "memories", * (state as { userId: string }).userId, * "filesystem", * ], * }); * ``` */ namespace?: string[] | StoreBackendNamespaceFactory; } /** * Backend that stores files in LangGraph's BaseStore (persistent). * * Uses LangGraph's Store for persistent, cross-conversation storage. * Files are organized via namespaces and persist across all threads. * * The namespace can be customized via a factory function for flexible * isolation patterns (user-scoped, org-scoped, etc.), or falls back * to legacy assistant_id-based isolation. */ declare class StoreBackend implements BackendProtocolV2 { private stateAndStore; private storeOverride; private _namespace; private fileFormat; constructor(options?: StoreBackendOptions); /** * @deprecated Pass no `stateAndStore` argument */ constructor(stateAndStore: StateAndStore, options?: StoreBackendOptions); /** * Get the BaseStore instance for persistent storage operations. * * In legacy mode, reads from the injected {@link StateAndStore}. * In zero-arg mode, retrieves the store from the LangGraph execution * context via {@link getLangGraphStore}. * * @returns BaseStore instance * @throws Error if no store is available in either mode */ private getStore; /** * Get the current graph state when available. */ private getState; /** * Get the most relevant runnable config for namespace resolution. */ private getNamespaceConfig; /** * Legacy assistant-id detection compatible with both Python and the * historical TypeScript `assistantId` runtime property. */ private getLegacyAssistantId; /** * Get the namespace for store operations. * * Resolution order: * 1. Explicit namespace from constructor options * 2. Namespace factory resolved from the current backend context * 3. Assistant ID from runtime config / LangGraph config metadata * 4. Legacy `assistantId` from the injected runtime * 5. `["filesystem"]` */ protected getNamespace(): string[]; /** * Convert a store Item to FileData format. * * @param storeItem - The store Item containing file data * @returns FileData object * @throws Error if required fields are missing or have incorrect types */ private convertStoreItemToFileData; /** * Convert FileData to a value suitable for store.put(). * * @param fileData - The FileData to convert * @returns Object with content, mimeType, created_at, and modified_at fields */ private convertFileDataToStoreValue; /** * Search store with automatic pagination to retrieve all results. * * @param store - The store to search * @param namespace - Hierarchical path prefix to search within * @param options - Optional query, filter, and page_size * @returns List of all items matching the search criteria */ private searchStorePaginated; /** * List files and directories in the specified directory (non-recursive). * * @param path - Absolute path to directory * @returns LsResult with list of FileInfo objects on success or error on failure. * Directories have a trailing / in their path and is_dir=true. */ ls(path: string): Promise; /** * Read file content. * * Text files are paginated by line offset/limit. * Binary files return full Uint8Array content (offset/limit ignored). * * @param filePath - Absolute file path * @param offset - Line offset to start reading from (0-indexed) * @param limit - Maximum number of lines to read * @returns ReadResult with content on success or error on failure */ read(filePath: string, offset?: number, limit?: number): Promise; /** * Read file content as raw FileData. * * @param filePath - Absolute file path * @returns ReadRawResult with raw file data on success or error on failure */ readRaw(filePath: string): Promise; /** * Create a new file with content. * Returns WriteResult. External storage sets filesUpdate=null. */ write(filePath: string, content: string): Promise; /** * Edit a file by replacing string occurrences. * Returns EditResult. External storage sets filesUpdate=null. */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise; /** * Search file contents for a literal text pattern. * Binary files are skipped. */ grep(pattern: string, path?: string, glob?: string | null): Promise; /** * Structured glob matching returning FileInfo objects. */ glob(pattern: string, path?: string): Promise; /** * Upload multiple files. * * @param files - List of [path, content] tuples to upload * @returns List of FileUploadResponse objects, one per input file */ uploadFiles(files: Array<[string, Uint8Array]>): Promise; /** * Download multiple files. * * @param paths - List of file paths to download * @returns List of FileDownloadResponse objects, one per input path */ downloadFiles(paths: string[]): Promise; } //#endregion //#region src/backends/filesystem.d.ts /** * Backend that reads and writes files directly from the filesystem. * * Files are accessed using their actual filesystem paths. Relative paths are * resolved relative to the current working directory. Content is read/written * as plain text, and metadata (timestamps) are derived from filesystem stats. */ declare class FilesystemBackend implements BackendProtocolV2 { protected cwd: string; protected virtualMode: boolean; private maxFileSizeBytes; constructor(options?: { rootDir?: string; virtualMode?: boolean; maxFileSizeMb?: number; }); /** * Resolve a file path with security checks. * * When virtualMode=true, treat incoming paths as virtual absolute paths under * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root. * When virtualMode=false, preserve legacy behavior: absolute paths are allowed * as-is; relative paths resolve under cwd. * * @param key - File path (absolute, relative, or virtual when virtualMode=true) * @returns Resolved absolute path string * @throws Error if path traversal detected or path outside root */ private resolvePath; /** * List files and directories in the specified directory (non-recursive). * * @param dirPath - Absolute directory path to list files from * @returns List of FileInfo objects for files and directories directly in the directory. * Directories have a trailing / in their path and is_dir=true. */ ls(dirPath: string): Promise; /** * Read file content with line numbers. * * @param filePath - Absolute or relative file path * @param offset - Line offset to start reading from (0-indexed) * @param limit - Maximum number of lines to read * @returns Formatted file content with line numbers, or error message */ read(filePath: string, offset?: number, limit?: number): Promise; /** * Read file content as raw FileData. * * @param filePath - Absolute file path * @returns ReadRawResult with raw file data on success or error on failure */ readRaw(filePath: string): Promise; /** * Create a new file with content. * Returns WriteResult. External storage sets filesUpdate=null. */ write(filePath: string, content: string): Promise; /** * Edit a file by replacing string occurrences. * Returns EditResult. External storage sets filesUpdate=null. */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise; /** * Search for a literal text pattern in files. * * Uses ripgrep if available, falling back to substring search. * * @param pattern - Literal string to search for (NOT regex). * @param dirPath - Directory or file path to search in. Defaults to current directory. * @param glob - Optional glob pattern to filter which files to search. * @returns List of GrepMatch dicts containing path, line number, and matched text. */ grep(pattern: string, dirPath?: string, glob?: string | null): Promise; /** * Search using ripgrep with fixed-string (literal) mode. * * @param pattern - Literal string to search for (unescaped). * @param baseFull - Resolved base path to search in. * @param includeGlob - Optional glob pattern to filter files. * @returns Dict mapping file paths to list of (line_number, line_text) tuples. * Returns null if ripgrep is unavailable or times out. */ private ripgrepSearch; /** * Fallback search using literal substring matching when ripgrep is unavailable. * * Recursively searches files, respecting maxFileSizeBytes limit. * * @param pattern - Literal string to search for. * @param baseFull - Resolved base path to search in. * @param includeGlob - Optional glob pattern to filter files by name. * @returns Dict mapping file paths to list of (line_number, line_text) tuples. */ private literalSearch; /** * Structured glob matching returning FileInfo objects. */ glob(pattern: string, searchPath?: string): Promise; /** * Upload multiple files to the filesystem. * * @param files - List of [path, content] tuples to upload * @returns List of FileUploadResponse objects, one per input file */ uploadFiles(files: Array<[string, Uint8Array]>): Promise; /** * Download multiple files from the filesystem. * * @param paths - List of file paths to download * @returns List of FileDownloadResponse objects, one per input path */ downloadFiles(paths: string[]): Promise; } //#endregion //#region src/backends/composite.d.ts /** * Backend that routes file operations to different backends based on path prefix. * * This enables hybrid storage strategies like: * - `/memories/` → StoreBackend (persistent, cross-thread) * - Everything else → StateBackend (ephemeral, per-thread) * * The CompositeBackend handles path prefix stripping/re-adding transparently. */ declare class CompositeBackend implements BackendProtocolV2 { private default; private routes; private sortedRoutes; constructor(defaultBackend: AnyBackendProtocol, routes: Record); /** Delegates to default backend's id if it is a sandbox, otherwise empty string. */ get id(): string; /** Route prefixes registered on this backend (e.g. `["/workspace"]`). */ get routePrefixes(): string[]; /** * Type guard — returns true if `backend` is a {@link CompositeBackend}. * * Uses duck-typing on `routePrefixes` so it works across module boundaries * where `instanceof` may fail. */ static isInstance(backend: unknown): backend is CompositeBackend; /** * Determine which backend handles this key and strip prefix. * * @param key - Original file path * @returns Tuple of [backend, stripped_key] where stripped_key has the route * prefix removed (but keeps leading slash). */ private getBackendAndKey; /** * List files and directories in the specified directory (non-recursive). * * @param path - Absolute path to directory * @returns LsResult with list of FileInfo objects (with route prefixes added) on success or error on failure. * Directories have a trailing / in their path and is_dir=true. */ ls(path: string): Promise; /** * Read file content, routing to appropriate backend. * * @param filePath - Absolute file path * @param offset - Line offset to start reading from (0-indexed) * @param limit - Maximum number of lines to read * @returns Formatted file content with line numbers, or error message */ read(filePath: string, offset?: number, limit?: number): Promise; /** * Read file content as raw FileData. * * @param filePath - Absolute file path * @returns ReadRawResult with raw file data on success or error on failure */ readRaw(filePath: string): Promise; /** * Structured search results or error string for invalid input. */ grep(pattern: string, path?: string, glob?: string | null): Promise; /** * Structured glob matching returning FileInfo objects. */ glob(pattern: string, path?: string): Promise; /** * Create a new file, routing to appropriate backend. * * @param filePath - Absolute file path * @param content - File content as string * @returns WriteResult with path or error */ write(filePath: string, content: string): Promise; /** * Edit a file, routing to appropriate backend. * * @param filePath - Absolute file path * @param oldString - String to find and replace * @param newString - Replacement string * @param replaceAll - If true, replace all occurrences * @returns EditResult with path, occurrences, or error */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise; /** * Execute a command via the default backend. * Execution is not path-specific, so it always delegates to the default backend. * * @param command - Full shell command string to execute * @returns ExecuteResponse with combined output, exit code, and truncation flag * @throws Error if the default backend doesn't support command execution */ execute(command: string): Promise; /** * Upload multiple files, batching by backend for efficiency. * * @param files - List of [path, content] tuples to upload * @returns List of FileUploadResponse objects, one per input file */ uploadFiles(files: Array<[string, Uint8Array]>): Promise; /** * Download multiple files, batching by backend for efficiency. * * @param paths - List of file paths to download * @returns List of FileDownloadResponse objects, one per input path */ downloadFiles(paths: string[]): Promise; } //#endregion //#region src/backends/context-hub.d.ts /** * Backend that stores files in a LangSmith Hub agent repo (persistent). */ declare class ContextHubBackend implements BackendProtocolV2 { private identifier; private client; private cache; private linkedEntries; private commitHash; constructor(identifier: string, options?: { client?: Client; }); private static stripPrefix; private static toHubUnavailableError; private loadTree; private ensureCache; private commit; /** * Return linked-entry paths mapped to their repo handles. */ getLinkedEntries(): Promise>; /** * Return true if the hub repo already exists with at least one commit. */ hasPriorCommits(): Promise; ls(path?: string): Promise; read(filePath: string, offset?: number, limit?: number): Promise; readRaw(filePath: string): Promise; grep(pattern: string, path?: string | null, glob?: string | null): Promise; glob(pattern: string, _path?: string): Promise; write(filePath: string, content: string): Promise; edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise; uploadFiles(files: Array<[string, Uint8Array]>): Promise; downloadFiles(paths: string[]): Promise; } //#endregion //#region src/backends/local-shell.d.ts /** * Options for creating a LocalShellBackend instance. */ interface LocalShellBackendOptions { /** * Working directory for both filesystem operations and shell commands. * @defaultValue `process.cwd()` */ rootDir?: string; /** * Enable virtual path mode for filesystem operations. * When true, treats rootDir as a virtual root filesystem. * Does NOT restrict shell commands. * @defaultValue `false` */ virtualMode?: boolean; /** * Maximum time in seconds to wait for shell command execution. * Commands exceeding this timeout will be terminated. * @defaultValue `120` */ timeout?: number; /** * Maximum number of bytes to capture from command output. * Output exceeding this limit will be truncated. * @defaultValue `100_000` */ maxOutputBytes?: number; /** * Environment variables for shell commands. If undefined, starts with an empty * environment (unless inheritEnv is true). * @defaultValue `undefined` */ env?: Record; /** * Whether to inherit the parent process's environment variables. * When false, only variables in env dict are available. * When true, inherits all process.env variables and applies env overrides. * @defaultValue `false` */ inheritEnv?: boolean; /** * Files to create on disk during `create()`. * Keys are file paths (resolved via the backend's path handling), * values are string content. * @defaultValue `undefined` */ initialFiles?: Record; } /** * Filesystem backend with unrestricted local shell command execution. * * This backend extends FilesystemBackend to add shell command execution * capabilities. Commands are executed directly on the host system without any * sandboxing, process isolation, or security restrictions. * * **Security Warning:** * This backend grants agents BOTH direct filesystem access AND unrestricted * shell execution on your local machine. Use with extreme caution and only in * appropriate environments. * * **Appropriate use cases:** * - Local development CLIs (coding assistants, development tools) * - Personal development environments where you trust the agent's code * - CI/CD pipelines with proper secret management * * **Inappropriate use cases:** * - Production environments (e.g., web servers, APIs, multi-tenant systems) * - Processing untrusted user input or executing untrusted code * * Use StateBackend, StoreBackend, or extend BaseSandbox for production. * * @example * ```typescript * import { LocalShellBackend } from "@langchain/deepagents"; * * // Create backend with explicit environment * const backend = new LocalShellBackend({ * rootDir: "/home/user/project", * env: { PATH: "/usr/bin:/bin" }, * }); * * // Execute shell commands (runs directly on host) * const result = await backend.execute("ls -la"); * console.log(result.output); * console.log(result.exitCode); * * // Use filesystem operations (inherited from FilesystemBackend) * const content = await backend.read("/README.md"); * await backend.write("/output.txt", "Hello world"); * * // Inherit all environment variables * const backend2 = new LocalShellBackend({ * rootDir: "/home/user/project", * inheritEnv: true, * }); * ``` */ declare class LocalShellBackend extends FilesystemBackend implements SandboxBackendProtocolV2 { #private; constructor(options?: LocalShellBackendOptions); /** Unique identifier for this backend instance (format: "local-{random_hex}"). */ get id(): string; /** Whether the backend has been initialized and is ready to use. */ get isInitialized(): boolean; /** Alias for `isInitialized`, matching the standard sandbox interface. */ get isRunning(): boolean; /** * Initialize the backend by ensuring the rootDir exists. * * Creates the rootDir (and any parent directories) if it does not already * exist. Safe to call on an existing directory. Must be called before * `execute()`, or use the static `LocalShellBackend.create()` factory. * * @throws {SandboxError} If already initialized (`ALREADY_INITIALIZED`) */ initialize(): Promise; /** * Mark the backend as no longer running. * * For local shell backends there is no remote resource to tear down, * so this simply flips the `isRunning` / `isInitialized` flag. */ close(): Promise; /** * Read a file, adapting error messages to the standard sandbox format. */ read(filePath: string, offset?: number, limit?: number): Promise; /** * Edit a file, adapting error messages to the standard sandbox format. */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise; /** * List directory contents, returning paths relative to rootDir. */ ls(dirPath: string): Promise; /** * Glob matching that returns relative paths and includes directories. */ glob(pattern: string, searchPath?: string): Promise; /** * Execute a shell command directly on the host system. * * Commands are executed directly on your host system using `spawn()` * with `shell: true`. There is NO sandboxing, isolation, or security * restrictions. The command runs with your user's full permissions. * * The command is executed using the system shell with the working directory * set to the backend's rootDir. Stdout and stderr are combined into a single * output stream, with stderr lines prefixed with `[stderr]`. * * @param command - Shell command string to execute * @returns ExecuteResponse containing output, exit code, and truncation flag */ execute(command: string): Promise; /** * Create and initialize a new LocalShellBackend in one step. * * This is the recommended way to create a backend when the rootDir may * not exist yet. It combines construction and initialization (ensuring * rootDir exists) into a single async operation. * * @param options - Configuration options for the backend * @returns An initialized and ready-to-use backend */ static create(options?: LocalShellBackendOptions): Promise; } //#endregion //#region src/backends/sandbox.d.ts /** * Base sandbox implementation with execute() as the only abstract method. * * This class provides default implementations for all SandboxBackendProtocol * methods using shell commands executed via execute(). Concrete implementations * only need to implement execute(), uploadFiles(), and downloadFiles(). * * All shell commands use pure POSIX utilities (awk, grep, find, stat) that are * available on any Linux including Alpine/busybox. No Python, Node.js, or * other runtime is required on the sandbox host. */ declare abstract class BaseSandbox implements SandboxBackendProtocolV2 { /** Unique identifier for the sandbox backend */ abstract readonly id: string; /** * Execute a command in the sandbox. * This is the only method concrete implementations must provide. */ abstract execute(command: string): MaybePromise; /** * Upload multiple files to the sandbox. * Implementations must support partial success. */ abstract uploadFiles(files: Array<[string, Uint8Array]>): MaybePromise; /** * Download multiple files from the sandbox. * Implementations must support partial success. */ abstract downloadFiles(paths: string[]): MaybePromise; /** * List files and directories in the specified directory (non-recursive). * * Uses pure POSIX shell (find + stat) via execute() — works on any Linux * including Alpine. No Python or Node.js needed. * * @param path - Absolute path to directory * @returns LsResult with list of FileInfo objects on success or error on failure. */ ls(path: string): Promise; /** * Read file content with line numbers. * * Uses pure POSIX shell (awk) via execute() — only the requested slice * is returned over the wire, making this efficient for large files. * Works on any Linux including Alpine (no Python or Node.js needed). * * @param filePath - Absolute file path * @param offset - Line offset to start reading from (0-indexed) * @param limit - Maximum number of lines to read * @returns Formatted file content with line numbers, or error message */ read(filePath: string, offset?: number, limit?: number): Promise; /** * Read file content as raw FileData. * * Uses downloadFiles() directly — no runtime needed on the sandbox host. * * @param filePath - Absolute file path * @returns ReadRawResult with raw file data on success or error on failure */ readRaw(filePath: string): Promise; /** * Search for a literal text pattern in files using grep. * * @param pattern - Literal string to search for (NOT regex). * @param path - Directory or file path to search in. * @param glob - Optional glob pattern to filter which files to search. * @returns List of GrepMatch dicts containing path, line number, and matched text. */ grep(pattern: string, path?: string, glob?: string | null): Promise; /** * Structured glob matching returning FileInfo objects. * * Uses pure POSIX shell (find + stat) via execute() to list all files, * then applies glob-to-regex matching in TypeScript. No Python or Node.js * needed on the sandbox host. * * Glob patterns are matched against paths relative to the search base: * - `*` matches any characters except `/` * - `**` matches any characters including `/` (recursive) * - `?` matches a single character except `/` * - `[...]` character classes */ glob(pattern: string, path?: string): Promise; /** * Create a new file with content. * * Uses downloadFiles() to check existence and uploadFiles() to write. * No runtime needed on the sandbox host. */ write(filePath: string, content: string): Promise; /** * Edit a file by replacing string occurrences. * * Uses downloadFiles() to read, performs string replacement in TypeScript, * then uploadFiles() to write back. No runtime needed on the sandbox host. * * Memory-conscious: releases intermediate references early so the GC can * reclaim buffers before the next large allocation is made. */ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise; } //#endregion //#region src/backends/langsmith.d.ts /** Options for constructing a LangSmithSandbox from an existing Sandbox instance. */ interface LangSmithSandboxOptions { /** An already-created LangSmith Sandbox instance to wrap. */ sandbox: Sandbox; /** * Default command timeout in seconds. * @default 1800 (30 minutes) */ defaultTimeout?: number; } /** Options for the `LangSmithSandbox.create()` static factory. */ interface LangSmithSandboxCreateOptions extends Omit { /** * Snapshot ID to boot from. * Mutually exclusive with `templateName`. */ snapshotId?: string; /** * Name of the LangSmith sandbox template to use. * Mutually exclusive with `snapshotId`. * @deprecated Use `snapshotId` instead. Template-based creation will be * removed in a future release. */ templateName?: string; /** * LangSmith API key. Defaults to the `LANGSMITH_API_KEY` environment variable. */ apiKey?: string; /** * Default command timeout in seconds. * @default 1800 (30 minutes) */ defaultTimeout?: number; } /** * LangSmith Sandbox backend for deepagents. * * Extends `BaseSandbox` to provide command execution and file operations * via the LangSmith Sandbox API. * * Use the static `LangSmithSandbox.create()` factory for the simplest setup, * or construct directly with an existing `Sandbox` instance. * * @experimental This feature is experimental, and breaking changes are expected. */ declare class LangSmithSandbox extends BaseSandbox { #private; constructor(options: LangSmithSandboxOptions); /** Whether the sandbox is currently active. */ get isRunning(): boolean; /** Return the LangSmith sandbox name as the unique identifier. */ get id(): string; /** * Execute a shell command in the LangSmith sandbox. * * @param command - Shell command string to execute * @param options.timeout - Override timeout in seconds; 0 disables timeout */ execute(command: string, options?: { timeout?: number; }): Promise; /** * Download files from the sandbox using LangSmith's native file read API. * @param paths - List of file paths to download * @returns List of FileDownloadResponse objects, one per input path */ downloadFiles(paths: string[]): Promise; /** * Upload files to the sandbox using LangSmith's native file write API. * @param files - List of [path, content] tuples to upload * @returns List of FileUploadResponse objects, one per input file */ uploadFiles(files: Array<[string, Uint8Array]>): Promise; /** * Delete this sandbox and mark it as no longer running. * * After calling this, `isRunning` will be `false` and the sandbox * cannot be used again. */ close(): Promise; /** * Start a stopped sandbox and wait until it is ready. * * After calling this, `isRunning` will be `true` and the sandbox * can be used for command execution and file operations again. * * @param options - Start options (timeout, signal). */ start(options?: StartSandboxOptions): Promise; /** * Stop the sandbox without deleting it. * * Sandbox files are preserved and the sandbox can be restarted later * with `start()`. After calling this, `isRunning` will be `false`. */ stop(): Promise; /** * Capture a snapshot from this running sandbox. * * Snapshots can be used to create new sandboxes via * `LangSmithSandbox.create({ snapshotId })`. * * @param name - Name for the snapshot. * @param options - Capture options (checkpoint, timeout). * @returns The created Snapshot in "ready" status. */ captureSnapshot(name: string, options?: CaptureSnapshotOptions): Promise; /** * Create and return a new LangSmithSandbox in one step. * * This is the recommended way to create a sandbox — no need to import * anything from `langsmith/experimental/sandbox` directly. * * @example * ```typescript * const sandbox = await LangSmithSandbox.create({ * snapshotId: "abc-123", * }); * * try { * const agent = createDeepAgent({ model, backend: sandbox }); * await agent.invoke({ messages: [...] }); * } finally { * await sandbox.close(); * } * ``` */ static create(options: LangSmithSandboxCreateOptions): Promise; } //#endregion //#region src/backends/utils.d.ts /** * Adapt a v1 {@link BackendProtocol} to {@link BackendProtocolV2}. * * If the backend already implements v2, it is returned as-is. * For v1 backends, wraps returns in Result types: * - `read()` string returns wrapped in {@link ReadResult} * - `readRaw()` FileData returns wrapped in {@link ReadRawResult} * - `grep()` returns wrapped in {@link GrepResult} * - `ls()` FileInfo[] returns wrapped in {@link LsResult} * - `glob()` FileInfo[] returns wrapped in {@link GlobResult} * * Note: For sandbox instances, use {@link adaptSandboxProtocol} instead. * * @param backend - Backend instance (v1 or v2) * @returns BackendProtocolV2-compatible backend */ declare function adaptBackendProtocol(backend: AnyBackendProtocol): BackendProtocolV2; /** * Adapt a sandbox backend from v1 to v2 interface. * * This extends {@link adaptBackendProtocol} to also preserve sandbox-specific * properties from {@link SandboxBackendProtocol}: `execute` and `id`. * * @param sandbox - Sandbox backend (v1 or v2) * @returns SandboxBackendProtocolV2-compatible sandbox */ declare function adaptSandboxProtocol(sandbox: AnySandboxProtocol): SandboxBackendProtocolV2; //#endregion //#region src/middleware/subagents.d.ts /** * Default system prompt for subagents. * Provides a minimal base prompt that can be extended by specific subagent configurations. */ declare const DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools."; /** * Default description for the general-purpose subagent. * This description is shown to the model when selecting which subagent to use. */ declare const DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent."; /** * System prompt section that explains how to use the task tool for spawning subagents. * * This prompt is automatically appended to the main agent's system prompt when * using `createSubAgentMiddleware`. It provides guidance on: * - When to use the task tool * - Subagent lifecycle (spawn → run → return → reconcile) * - When NOT to use the task tool * - Best practices for parallel task execution * * You can provide a custom `systemPrompt` to `createSubAgentMiddleware` to override * or extend this default. */ declare const TASK_SYSTEM_PROMPT: string; /** * Type definitions for pre-compiled agents. * * @typeParam TRunnable - The type of the runnable (ReactAgent or Runnable). * When using `createAgent` or `createDeepAgent`, this preserves the middleware * types for type inference. Uses `ReactAgent` to accept agents with any * type configuration (including DeepAgent instances). */ interface CompiledSubAgent | Runnable = ReactAgent | Runnable> { /** The name of the agent */ name: string; /** The description of the agent */ description: string; /** The agent instance */ runnable: TRunnable; } /** * Specification for a subagent that can be dynamically created. * * When using `createDeepAgent`, subagents automatically receive a default middleware * stack (todoListMiddleware, filesystemMiddleware, summarizationMiddleware, etc.) before * any custom `middleware` specified in this spec. * * Required fields: * - `name`: Identifier used to select this subagent in the task tool * - `description`: Shown to the model for subagent selection * - `systemPrompt`: The system prompt for the subagent * * Optional fields: * - `model`: Override the default model for this subagent * - `tools`: Override the default tools for this subagent * - `middleware`: Additional middleware appended after defaults * - `interruptOn`: Human-in-the-loop configuration for specific tools * - `skills`: Skill source paths for SkillsMiddleware (e.g., `["/skills/user/", "/skills/project/"]`) * * @example * ```typescript * const researcher: SubAgent = { * name: "researcher", * description: "Research assistant for complex topics", * systemPrompt: "You are a research assistant.", * tools: [webSearchTool], * skills: ["/skills/research/"], * }; * ``` */ interface SubAgent { /** Identifier used to select this subagent in the task tool */ name: string; /** Description shown to the model for subagent selection */ description: string; /** The system prompt to use for the agent */ systemPrompt: string; /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */ tools?: StructuredTool[]; /** The model for the agent. Defaults to defaultModel */ model?: LanguageModelLike | string; /** Additional middleware to append after default_middleware */ middleware?: readonly AgentMiddleware$1[]; /** Human-in-the-loop configuration for specific tools. Requires a checkpointer. */ interruptOn?: Record; /** * Skill source paths for SkillsMiddleware. * * List of paths to skill directories (e.g., `["/skills/user/", "/skills/project/"]`). * When specified, the subagent will have its own SkillsMiddleware that loads skills * from these paths. This allows subagents to have different skill sets than the main agent. * * Note: Custom subagents do NOT inherit skills from the main agent by default. * Only the general-purpose subagent inherits the main agent's skills. * * @example * ```typescript * const researcher: SubAgent = { * name: "researcher", * description: "Research assistant", * systemPrompt: "You are a researcher.", * skills: ["/skills/research/", "/skills/web-search/"], * }; * ``` */ skills?: string[]; /** * Structured output response format for the subagent. * * When specified, the subagent will produce a `structuredResponse` conforming to the * given schema. The structured response is JSON-serialized and returned as the * ToolMessage content to the parent agent, replacing the default last-message extraction. * * Accepts any format supported by `createAgent`: Zod schemas, JSON schema objects, * `toolStrategy(schema)`, `providerStrategy(schema)`, etc. * * @example * ```typescript * import { z } from "zod" * * const analyzer: SubAgent = { * name: "analyzer", * description: "Analyzes data and returns structured findings", * systemPrompt: "Analyze the data and return your findings.", * responseFormat: z.object({ * findings: z.string(), * confidence: z.number(), * }), * }; * ``` */ responseFormat?: CreateAgentParams["responseFormat"]; /** * Filesystem permission rules for this subagent. * * When specified, these rules **replace** the parent agent's permissions * for all tool calls made by this subagent. When omitted, the subagent * inherits the parent agent's permissions. * * Subagent permissions are a full replacement, not a merge. * * @example * ```ts * // Parent denies /restricted/**; this subagent can read it. * const reader: SubAgent = { * name: "reader", * permissions: [ * { operations: ["read"], paths: ["/restricted/**"] }, * ], * }; * ``` */ permissions?: FilesystemPermission[]; } /** * Base specification for the general-purpose subagent. * * This constant provides the default configuration for the general-purpose subagent * that is automatically included when `generalPurposeAgent: true` (the default). * * The general-purpose subagent: * - Has access to all tools from the main agent * - Inherits skills from the main agent (when skills are configured) * - Uses the same model as the main agent (by default) * - Is ideal for delegating complex, multi-step tasks * * You can spread this constant and override specific properties when creating * custom subagents that should behave similarly to the general-purpose agent: * * @example * ```typescript * import { GENERAL_PURPOSE_SUBAGENT, createDeepAgent } from "@anthropic/deepagents"; * * // Use as-is (automatically included with generalPurposeAgent: true) * const agent = createDeepAgent({ model: "claude-sonnet-4-5-20250929" }); * * // Or create a custom variant with different tools * const customGP: SubAgent = { * ...GENERAL_PURPOSE_SUBAGENT, * name: "research-gp", * tools: [webSearchTool, readFileTool], * }; * * const agent = createDeepAgent({ * model: "claude-sonnet-4-5-20250929", * subagents: [customGP], * // Disable the default general-purpose agent since we're providing our own * // (handled automatically when using createSubAgentMiddleware directly) * }); * ``` */ declare const GENERAL_PURPOSE_SUBAGENT: Pick; /** * Options for creating subagent middleware */ interface SubAgentMiddlewareOptions { /** The model to use for subagents */ defaultModel: LanguageModelLike | string; /** The tools to use for the default general-purpose subagent */ defaultTools?: StructuredTool[]; /** Default middleware to apply to custom subagents (WITHOUT skills from main agent) */ defaultMiddleware?: AgentMiddleware$1[] | null; /** * Middleware specifically for the general-purpose subagent (includes skills from main agent). * If not provided, falls back to defaultMiddleware. */ generalPurposeMiddleware?: AgentMiddleware$1[] | null; /** The tool configs for the default general-purpose subagent */ defaultInterruptOn?: Record | null; /** A list of additional subagents to provide to the agent */ subagents?: (SubAgent | CompiledSubAgent)[]; /** Full system prompt override */ systemPrompt?: string | null; /** Whether to include the general-purpose agent */ generalPurposeAgent?: boolean; /** Custom description for the task tool */ taskDescription?: string | null; } /** * Create subagent middleware with task tool */ declare function createSubAgentMiddleware(options: SubAgentMiddlewareOptions): AgentMiddleware$1, { description: string; subagent_type: string; }, { description: string; subagent_type: string; }, string | Command, string>, unknown, "task">]>; //#endregion //#region src/middleware/patch_tool_calls.d.ts /** * Create middleware that enforces strict tool call / tool response parity in * the messages history. * * Two kinds of violations are repaired: * 1. **Dangling tool_calls** — an AIMessage contains tool_calls with no * matching ToolMessage responses. Synthetic cancellation ToolMessages are * injected so every tool_call has a response. * 2. **Orphaned ToolMessages** — a ToolMessage exists whose `tool_call_id` * does not match any tool_call in a preceding AIMessage. These are removed. * * This is critical for providers like Google Gemini that reject requests with * mismatched function call / function response counts (400 INVALID_ARGUMENT). * * This middleware patches in two places: * 1. `beforeAgent`: Patches state at the start of the agent loop (handles most cases) * 2. `wrapModelCall`: Patches the request right before model invocation (handles * edge cases like HITL rejection during graph resume where state updates from * beforeAgent may not be applied in time) * * @returns AgentMiddleware that enforces tool call / response parity * * @example * ```typescript * import { createAgent } from "langchain"; * import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls"; * * const agent = createAgent({ * model: "claude-sonnet-4-5-20250929", * middleware: [createPatchToolCallsMiddleware()], * }); * ``` */ declare function createPatchToolCallsMiddleware(): AgentMiddleware; //#endregion //#region src/middleware/memory.d.ts /** * Options for the memory middleware. */ interface MemoryMiddlewareOptions { /** * Backend instance or factory function for file operations. * Use a factory for StateBackend since it requires runtime state. */ backend: AnyBackendProtocol | BackendFactory | ((config: { state: unknown; store?: BaseStore; }) => StateBackend); /** * List of memory file paths to load (e.g., ["~/.deepagents/AGENTS.md", "./.deepagents/AGENTS.md"]). * Display names are automatically derived from the paths. * Sources are loaded in order. */ sources: string[]; /** * Whether to add cache_control breakpoints to the memory content block. * When true, the memory block is tagged with `cache_control: { type: "ephemeral" }` * to enable prompt caching for providers that support it (e.g., Anthropic). * @default false */ addCacheControl?: boolean; } /** * Create middleware for loading agent memory from AGENTS.md files. * * Loads memory content from configured sources and injects into the system prompt. * Supports multiple sources that are combined together. * * @param options - Configuration options * @returns AgentMiddleware for memory loading and injection * * @example * ```typescript * const middleware = createMemoryMiddleware({ * backend: new FilesystemBackend({ rootDir: "/" }), * sources: [ * "~/.deepagents/AGENTS.md", * "./.deepagents/AGENTS.md", * ], * }); * ``` */ declare function createMemoryMiddleware(options: MemoryMiddlewareOptions): AgentMiddleware>; files: _langgraph.ReducedValue; }>, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>; //#endregion //#region src/middleware/skills.d.ts declare const MAX_SKILL_FILE_SIZE: number; declare const MAX_SKILL_NAME_LENGTH = 64; declare const MAX_SKILL_DESCRIPTION_LENGTH = 1024; /** * Metadata for a skill per Agent Skills specification. */ interface SkillMetadata$1 { /** * Skill identifier. * * Constraints per Agent Skills specification: * * - 1-64 characters * - Unicode lowercase alphanumeric and hyphens only (`a-z` and `-`). * - Must not start or end with `-` * - Must not contain consecutive `--` * - Must match the parent directory name containing the `SKILL.md` file */ name: string; /** * What the skill does. * * Constraints per Agent Skills specification: * * - 1-1024 characters * - Should describe both what the skill does and when to use it * - Should include specific keywords that help agents identify relevant tasks */ description: string; /** Path to the SKILL.md file in the backend */ path: string; /** License name or reference to bundled license file. */ license?: string | null; /** * Environment requirements. * * Constraints per Agent Skills specification: * * - 1-500 characters if provided * - Should only be included if there are specific compatibility requirements * - Can indicate intended product, required packages, etc. */ compatibility?: string | null; /** * Arbitrary key-value mapping for additional metadata. * * Clients can use this to store additional properties not defined by the spec. * * It is recommended to keep key names unique to avoid conflicts. */ metadata?: Record; /** * Tool names the skill recommends using. * * Warning: this is experimental. * * Constraints per Agent Skills specification: * * - Space-delimited list of tool names */ allowedTools?: string[]; /** * Path to a JS/TS entrypoint file for a QuickJS REPL module, relative to the skill * directory. */ module?: string; } /** * Options for the skills middleware. */ interface SkillsMiddlewareOptions { /** * Backend instance or factory function for file operations. * Use a factory for StateBackend since it requires runtime state. */ backend: AnyBackendProtocol | BackendFactory | ((config: { state: unknown; store?: BaseStore; }) => StateBackend); /** * List of skill source paths to load (e.g., ["/skills/user/", "/skills/project/"]). * Paths must use POSIX conventions (forward slashes). * Later sources override earlier ones for skills with the same name (last one wins). */ sources: string[]; } /** * Create backend-agnostic middleware for loading and exposing agent skills. * * This middleware loads skills from configurable backend sources and injects * skill metadata into the system prompt. It implements the progressive disclosure * pattern: skill names and descriptions are shown in the prompt, but the agent * reads full SKILL.md content only when needed. * * @param options - Configuration options * @returns AgentMiddleware for skills loading and injection * * @example * ```typescript * const middleware = createSkillsMiddleware({ * backend: new FilesystemBackend({ rootDir: "/" }), * sources: ["/skills/user/", "/skills/project/"], * }); * ``` */ declare function createSkillsMiddleware(options: SkillsMiddlewareOptions): AgentMiddleware | undefined; allowedTools?: string[] | undefined; module?: string | undefined; }[] | undefined, { name: string; description: string; path: string; license?: string | null | undefined; compatibility?: string | null | undefined; metadata?: Record | undefined; allowedTools?: string[] | undefined; module?: string | undefined; }[] | undefined>; files: ReducedValue; }>, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>; //#endregion //#region src/middleware/completion_callback.d.ts /** * Options for creating the completion callback middleware. */ interface CompletionCallbackOptions { /** * Callback graph or assistant identifier. Used as the `assistant_id` * argument in `runs.create()`. */ callbackGraphId: string; /** * URL of the callback LangGraph server. Omit to use same-deployment * ASGI transport. */ url?: string; /** * Additional headers to include in requests to the callback server. */ headers?: Record; } /** * Create a completion callback middleware for async subagents. * * **Experimental** — this middleware is experimental and may change. * * This middleware is added to a subagent's middleware stack. On success or * model-call error, it sends a notification to the configured callback * thread by calling `runs.create()`. * * The callback destination is configured with `callbackGraphId` and * optional `url` and `headers`. The target thread is read from * `callbackThreadId` in the subagent state. * * If `callbackThreadId` is not present in state, the middleware does * nothing. * * @param options - Configuration options. * @returns An `AgentMiddleware` instance. * * @example * ```typescript * import { createCompletionCallbackMiddleware } from "deepagents"; * * const notifier = createCompletionCallbackMiddleware({ * callbackGraphId: "supervisor", * }); * * const agent = createDeepAgent({ * model: "claude-sonnet-4-5-20250929", * middleware: [notifier], * }); * ``` */ declare function createCompletionCallbackMiddleware(options: CompletionCallbackOptions): AgentMiddleware; }, z$2.core.$strip>, undefined, unknown, readonly (_$_langchain_core_tools0.ClientTool | _$_langchain_core_tools0.ServerTool)[]>; //#endregion //#region src/middleware/summarization.d.ts /** * Context size specification for summarization triggers and retention policies. */ interface ContextSize { /** Type of context measurement */ type: "messages" | "tokens" | "fraction"; /** Threshold value */ value: number; } /** * Settings for truncating large tool arguments in old messages. */ interface TruncateArgsSettings { /** * Threshold to trigger argument truncation. * If not provided, truncation is disabled. */ trigger?: ContextSize; /** * Context retention policy for message truncation. * Defaults to keeping last 20 messages. */ keep?: ContextSize; /** * Maximum character length for tool arguments before truncation. * Defaults to 2000. */ maxLength?: number; /** * Text to replace truncated arguments with. * Defaults to "...(argument truncated)". */ truncationText?: string; } /** * Options for the summarization middleware. */ interface SummarizationMiddlewareOptions { /** * The language model to use for generating summaries. * Can be a model string (e.g., "gpt-4o-mini") or a language model instance. * If omitted, middleware will use the active request model. */ model?: string | BaseChatModel | BaseLanguageModel; /** * Backend instance or factory for persisting conversation history. */ backend: AnyBackendProtocol | BackendFactory | ((config: { state: unknown; store?: BaseStore; }) => StateBackend); /** * Threshold(s) that trigger summarization. * Can be a single ContextSize or an array for multiple triggers. */ trigger?: ContextSize | ContextSize[]; /** * Context retention policy after summarization. * Defaults to keeping last 20 messages. */ keep?: ContextSize; /** * Prompt template for generating summaries. */ summaryPrompt?: string; /** * Max tokens to include when generating summary. * Defaults to 4000. */ trimTokensToSummarize?: number; /** * Path prefix for storing conversation history. * Defaults to "/conversation_history". */ historyPathPrefix?: string; /** * Settings for truncating large tool arguments in old messages. * If not provided, argument truncation is disabled. */ truncateArgsSettings?: TruncateArgsSettings; } /** * Compute summarization defaults based on model profile. * Mirrors Python's `_compute_summarization_defaults`. * * If the model has a profile with `maxInputTokens`, uses fraction-based * settings. Otherwise, uses fixed token/message counts. * * @param resolvedModel - The resolved chat model instance. */ declare function computeSummarizationDefaults(resolvedModel: BaseChatModel): { trigger: ContextSize; keep: ContextSize; truncateArgsSettings: TruncateArgsSettings; }; /** * Create summarization middleware with backend support for conversation history offloading. * * This middleware: * 1. Monitors conversation length against configured thresholds * 2. When triggered, offloads old messages to backend storage * 3. Generates a summary of offloaded messages * 4. Replaces old messages with the summary, preserving recent context * * @param options - Configuration options * @returns AgentMiddleware for summarization and history offloading */ declare function createSummarizationMiddleware(options: SummarizationMiddlewareOptions): AgentMiddleware; _summarizationEvent: z$1.ZodOptional>, HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>>; filePath: z$1.ZodNullable; }, z$1.core.$strip>>; }, z$1.core.$strip>, undefined, unknown, readonly (ClientTool | ServerTool)[]>; //#endregion //#region src/middleware/async_subagents.d.ts /** * Specification for an async subagent running on a remote [Agent Protocol](https://github.com/langchain-ai/agent-protocol) * server. * * Async subagents connect to any Agent Protocol-compliant server via the * LangGraph SDK. They run as background tasks that the main agent can * monitor and update. * * Compatible with LangGraph Platform (managed) and self-hosted servers. * Authentication for LangGraph Platform is handled automatically by the SDK * via environment variables (`LANGGRAPH_API_KEY`, `LANGSMITH_API_KEY`, or * `LANGCHAIN_API_KEY`). For self-hosted servers, pass custom auth via `headers`. */ interface AsyncSubAgent { /** Unique identifier for the async subagent. */ name: string; /** What this subagent does. The main agent uses this to decide when to delegate. */ description: string; /** The graph name or assistant ID on the Agent Protocol server. */ graphId: string; /** URL of the Agent Protocol server. Defaults to the LangGraph SDK's default endpoint. */ url?: string; /** Additional headers to include in requests to the server (e.g. for custom auth). */ headers?: Record; } /** * Possible statuses for an async subagent task. * * Statuses set by the middleware tools: `"running"`, `"success"`, `"error"`, `"cancelled"`. * Statuses that may be returned by the remote server: `"pending"`, `"timeout"`, `"interrupted"`. */ type AsyncTaskStatus = "pending" | "running" | "success" | "error" | "cancelled" | "timeout" | "interrupted"; /** * A tracked async subagent task persisted in agent state. * * Each task maps to a single thread + run on a remote Agent Protocol server. * The `taskId` is the same as `threadId`, so it can be used to look up * the thread directly via the SDK. */ interface AsyncTask { /** Unique identifier for the task (same as thread id). */ taskId: string; /** Name of the async subagent type that is running. */ agentName: string; /** Thread ID on the remote server. */ threadId: string; /** Run ID for the current execution on the thread. */ runId: string; /** Current task status. */ status: AsyncTaskStatus; /** ISO timestamp of when the task was launched. */ createdAt: string; /** The prompt/description passed to the subagent when the task was launched. */ description?: string; /** ISO timestamp of the most recent task update — set when the task status changes or a follow-up message is sent via the update tool. */ updatedAt?: string; /** ISO timestamp of the most recent status poll via the check tool. */ checkedAt?: string; } /** * Task statuses that will never change. * * When listing tasks, live-status fetches are skipped for tasks whose * cached status is in this set, since they are guaranteed to be final. */ /** * Names of the tools added by the async subagent middleware. * * Exported so `agent.ts` can include them in `BUILTIN_TOOL_NAMES` and * surface a `ConfigurationError` if a user-provided tool collides. */ declare const ASYNC_TASK_TOOL_NAMES: readonly ["start_async_task", "check_async_task", "update_async_task", "cancel_async_task", "list_async_tasks"]; /** * Options for creating async subagent middleware. */ interface AsyncSubAgentMiddlewareOptions { /** List of async subagent specifications. Must have at least one. */ asyncSubAgents: AsyncSubAgent[]; /** System prompt override. Set to `null` to disable. Defaults to {@link ASYNC_TASK_SYSTEM_PROMPT}. */ systemPrompt?: string; } /** * Create middleware that adds async subagent tools to an agent. * * Provides five tools for launching, checking, updating, cancelling, and * listing background tasks on remote Agent Protocol servers. Task state is * persisted in the `asyncTasks` state channel so it survives * context compaction. * * Works with any Agent Protocol-compliant server — LangGraph Platform (managed) * or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec). * * @throws {Error} If no async subagents are provided or names are duplicated. * * @example * ```ts * const middleware = createAsyncSubAgentMiddleware({ * asyncSubAgents: [{ * name: "researcher", * description: "Research agent for deep analysis", * url: "https://my-agent-protocol-server.example.com", * graphId: "research_agent", * }], * }); * ``` */ /** * Type guard to distinguish async SubAgents from sync SubAgents/CompiledSubAgents. * * Uses the presence of the `graphId` field as the runtime discriminant — * `AsyncSubAgent` requires it, while `SubAgent` and `CompiledSubAgent` do not have it. */ declare function isAsyncSubAgent(subAgent: AnySubAgent): subAgent is AsyncSubAgent; declare function createAsyncSubAgentMiddleware(options: AsyncSubAgentMiddlewareOptions): _langchain.AgentMiddleware | undefined, Record | undefined>; }>, undefined, unknown, (_langchain.DynamicStructuredTool, { description: string; agentName: string; }, { description: string; agentName: string; }, string | Command, string>, unknown, "start_async_task"> | _langchain.DynamicStructuredTool, { taskId: string; }, { taskId: string; }, string | Command, string>, unknown, "check_async_task"> | _langchain.DynamicStructuredTool, { taskId: string; message: string; }, { taskId: string; message: string; }, string | Command, string>, unknown, "update_async_task"> | _langchain.DynamicStructuredTool, { taskId: string; }, { taskId: string; }, string | Command, string>, unknown, "cancel_async_task"> | _langchain.DynamicStructuredTool>; }, z.core.$strip>, { statusFilter?: string | null | undefined; }, { statusFilter?: string | null | undefined; }, string | Command, string>, unknown, "list_async_tasks">)[]>; //#endregion //#region src/stream.d.ts /** * Represents a single subagent invocation observed during a deep agent run. * * @typeParam TOutput - The subagent's output state type. Defaults to * `unknown`; inferred to the subagent's `MergedAgentState` for * `CompiledSubAgent` via {@link SubagentRunStreamUnion}. */ interface SubagentRunStream { readonly name: string; readonly taskInput: Promise; readonly output: Promise; readonly messages: AsyncIterable; readonly toolCalls: AsyncIterable>; readonly subagents: AsyncIterable; } /** * Extract the output state type from a subagent spec. * For `CompiledSubAgent>`, resolves to the agent's * invoke return type. Falls back to `unknown` for `SubAgent` and * `AsyncSubAgent`. */ type SubagentOutputOf = T extends CompiledSubAgent ? R extends ReactAgent ? Awaited["invoke"]>> : unknown : unknown; /** * Extract the tools tuple from a subagent spec. * For `CompiledSubAgent>`, resolves to `Types["Tools"]`. * Falls back to the default `(ClientTool | ServerTool)[]` for `SubAgent` * and `AsyncSubAgent`. */ type SubagentToolsOf = T extends CompiledSubAgent ? R extends ReactAgent ? Types["Tools"] : readonly (ClientTool | ServerTool)[] : readonly (ClientTool | ServerTool)[]; /** * A typed `SubagentRunStream` variant for a single subagent spec. * Narrows `.name` to the literal string type, `.output` to the * inferred state type, and `.toolCalls` to the subagent's tools * when available. */ type NamedSubagentRunStream = T extends { name: infer N extends string; } ? SubagentRunStream, SubagentToolsOf> & { readonly name: N; } : SubagentRunStream; /** * Discriminated union of {@link SubagentRunStream} variants, one per * subagent in `TSubagents`. Enables TypeScript to narrow `.output` * when the consumer checks `sub.name === "someSubagentName"`. */ type SubagentRunStreamUnion = { [K in keyof TSubagents]: NamedSubagentRunStream }[number]; /** * An {@link AgentRunStream} with native deep-agent projections assigned * directly on the instance by `createGraphRunStream` (via `__native` * transformers). * * This is a pure type overlay — no runtime class exists. The * `subagents` property is populated at runtime by the * `createSubagentTransformer` registered at compile time. */ type DeepAgentRunStream, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TSubagents extends readonly AnySubAgent[] = readonly AnySubAgent[], TExtensions extends Record = Record> = AgentRunStream & { /** Subagent invocation streams from the native SubagentTransformer. */subagents: AsyncIterable>; }; interface SubagentProjection { subagents: AsyncIterable; } /** * Native transformer that correlates `task` tool calls into * {@link SubagentRunStream} objects and routes child-namespace * `tools` and `messages` events into per-subagent channels. * * Marked `__native: true` — the `subagents` projection key lands * directly on the `GraphRunStream` instance as `run.subagents`. */ declare function createSubagentTransformer(path: Namespace): () => NativeStreamTransformer; //#endregion //#region src/types.d.ts type AnyAnnotationRoot = AnnotationRoot; /** * Literal union of all built-in deep agent tool names. * These are always present on the agent regardless of user-provided tools. */ type DeepAgentBuiltinToolName = (typeof FILESYSTEM_TOOL_NAMES)[number] | (typeof ASYNC_TASK_TOOL_NAMES)[number] | "task" | "write_todos"; /** * A placeholder StructuredTool type with a literal `name` for each * built-in tool. Used to thread built-in tool names into the * `ToolCallStreamUnion` so they appear in `run.toolCalls` alongside * user-provided tools. */ type BuiltinToolPlaceholder = { name: N; } & StructuredTool$1; /** * Tuple of placeholder tool types for all built-in deep agent tools. * Combined with `TTypes["Tools"]` in the `DeepAgentRunStream` return type. */ type DeepAgentBuiltinToolsTuple = { [K in DeepAgentBuiltinToolName]: BuiltinToolPlaceholder }[DeepAgentBuiltinToolName][]; type InferDeepAgentStreamExtensions StreamTransformer>> = T extends readonly [] ? Record : T extends readonly [() => StreamTransformer, ...infer Rest extends ReadonlyArray<() => StreamTransformer>] ? P & InferDeepAgentStreamExtensions : Record; /** Any subagent specification — sync, compiled, or async. */ type AnySubAgent = SubAgent | CompiledSubAgent | AsyncSubAgent; interface TypedToolStrategy extends Array> { _schemaType?: T; } /** * Helper type to extract middleware from a SubAgent definition * Handles both mutable and readonly middleware arrays */ type ExtractSubAgentMiddleware = T extends { middleware?: infer M; } ? M extends readonly AgentMiddleware[] ? M : M extends AgentMiddleware[] ? M : readonly [] : readonly []; /** * Helper type to flatten and merge middleware from all subagents */ type FlattenSubAgentMiddleware = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? Rest extends readonly AnySubAgent[] ? readonly [...ExtractSubAgentMiddleware, ...FlattenSubAgentMiddleware] : ExtractSubAgentMiddleware : readonly []; /** * Helper type to merge states from subagent middleware */ type InferSubAgentMiddlewareStates = InferMiddlewareStates>; /** * Combined state type including custom middleware and subagent middleware states */ type MergedDeepAgentState = InferMiddlewareStates & InferSubAgentMiddlewareStates; /** * Union of all response format types accepted by `createDeepAgent`. * * Matches the formats supported by LangChain's `createAgent`: * - `ToolStrategy` — from `ToolStrategy.fromSchema(schema)` * - `ProviderStrategy` — from `providerStrategy(schema)` * - `TypedToolStrategy` — from `toolStrategy(schema)` * - `ResponseFormat` — the base union of the above single-strategy types */ type SupportedResponseFormat = ResponseFormat | TypedToolStrategy; /** * Utility type to extract the parsed response type from a ResponseFormat strategy. * * Maps `ToolStrategy`, `ProviderStrategy`, and `TypedToolStrategy` to `T` * (the parsed output type), so that `structuredResponse` is correctly typed as the * schema's inferred type rather than the strategy wrapper. * * When no `responseFormat` is provided (i.e. `T` defaults to the full * `SupportedResponseFormat` union), this resolves to `ResponseFormatUndefined` so * that `structuredResponse` is excluded from the agent's output state. * * @example * ```typescript * type T1 = InferStructuredResponse>; // { city: string } * type T2 = InferStructuredResponse>; // { answer: string } * type T3 = InferStructuredResponse>; // { city: string } * type T4 = InferStructuredResponse; // ResponseFormatUndefined (default/unset) * ``` */ type InferStructuredResponse = SupportedResponseFormat extends T ? ResponseFormatUndefined : T extends TypedToolStrategy ? U : T extends ToolStrategy ? U : T extends ProviderStrategy ? U : ResponseFormatUndefined; /** * Type bag that extends AgentTypeConfig with subagent type information. * * This interface bundles all the generic type parameters used throughout the deep agent system * including subagent types for type-safe streaming and delegation. * * @typeParam TResponse - The structured response type when using `responseFormat`. * @typeParam TState - The custom state schema type. * @typeParam TContext - The context schema type. * @typeParam TMiddleware - The middleware array type. * @typeParam TTools - The combined tools type. * @typeParam TSubagents - The subagents array type for type-safe streaming. * * @example * ```typescript * const agent = createDeepAgent({ * middleware: [ResearchMiddleware], * subagents: [ * { name: "researcher", description: "...", middleware: [CounterMiddleware] } * ] as const, * }); * * // Type inference for streaming * type Types = InferDeepAgentType; * ``` */ interface DeepAgentTypeConfig | ResponseFormatUndefined = Record | ResponseFormatUndefined, TState extends AnyAnnotationRoot | InteropZodObject | undefined = AnyAnnotationRoot | InteropZodObject | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TSubagents extends readonly AnySubAgent[] = readonly AnySubAgent[], TStreamTransformers extends ReadonlyArray<() => StreamTransformer> = ReadonlyArray<() => StreamTransformer>> extends AgentTypeConfig { /** The subagents array type for type-safe streaming */ Subagents: TSubagents; } /** * Default type configuration for deep agents. * Used when no explicit type parameters are provided. */ interface DefaultDeepAgentTypeConfig extends DeepAgentTypeConfig { Response: Record; State: undefined; Context: AnyAnnotationRoot; Middleware: readonly AgentMiddleware[]; Tools: readonly (ClientTool | ServerTool)[]; Subagents: readonly AnySubAgent[]; StreamTransformers: readonly []; } /** * DeepAgent extends ReactAgent with additional subagent type information. * * This type wraps ReactAgent but includes the DeepAgentTypeConfig which * contains subagent types for type-safe streaming and delegation. * * @typeParam TTypes - The DeepAgentTypeConfig containing all type parameters * * @example * ```typescript * const agent: DeepAgent> = createDeepAgent({ ... }); * * // Access subagent types for streaming * type Subagents = InferDeepAgentSubagents; * ``` */ interface DeepAgent extends ReactAgent { /** Type brand for DeepAgent type inference */ readonly "~deepAgentTypes": TTypes; /** * Executes the agent with the v3 streaming interface, returning an * {@link DeepAgentRunStream} that provides ergonomic, typed projections for * messages, tool calls, subagents, and middleware events. * * Pass `version: "v3"` to opt into this projection-oriented stream. Omitting * `version` preserves the legacy internal LangGraph event-stream behavior * for compatibility with LangGraph Platform integrations. * * This v3 stream is experimental and its API may change in future releases. * It will become the default in a future major release. * * @param state - The initial state for the agent execution. Can be: * - An object containing `messages` array and any middleware-specific state properties * - A Command object for more advanced control flow * * @param config - Runtime configuration including: * @param config.version - Must be `"v3"` to use the {@link DeepAgentRunStream} * interface. The default legacy event stream is maintained for internal * integrations and should not be used for new user-facing agent streaming. * @param config.context - The context for the agent execution. * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc. * @param config.store - The store for the agent execution for persisting state. * @param config.signal - An optional AbortSignal for the agent execution. * @param config.recursionLimit - The recursion limit for the agent execution. * * @returns A Promise that resolves to an {@link DeepAgentRunStream} providing: * - `run.messages` — all AI message lifecycles with streaming `.text` and `.reasoning` * - `run.toolCalls` — individual tool call streams with `.input`, `.output`, `.status` * - `run.subagents` — subagent delegation streams * - `run.middleware` — middleware lifecycle events (before/after agent/model) * - `run.values` — state snapshots (async iterable + promise-like) * - `run.output` — final agent state when the run completes * - `run.subgraphs` — child subgraph run streams * - `run.extensions` — merged projections from user-supplied transformers * * @example * ```typescript * const run = await agent.streamEvents( * { * messages: [{ role: "user", content: "What's the weather in Paris?" }], * }, * { version: "v3" } * ); * * // Stream all messages * for await (const msg of run.messages) { * for await (const token of msg.text) { * process.stdout.write(token); * } * } * * // Observe tool calls * for await (const call of run.toolCalls) { * console.log(`Tool: ${call.name}`, call.input); * console.log(`Result:`, await call.output); * } * * // Observe subagent delegations * for await (const subagent of run.subagents) { * console.log(`Subagent: ${subagent.name}`); * * for await (const msg of subagent.messages) { * for await (const token of msg.text) { * process.stdout.write(token); * } * } * } * * // Get final state * const state = await run.output; * ``` */ streamEvents: ((state: Parameters["invoke"]>[0], config: NonNullable["invoke"]>[1]> & { version: "v3"; }) => Promise["invoke"]>>, readonly [...TTypes["Tools"], ...DeepAgentBuiltinToolsTuple], TTypes["Subagents"], InferDeepAgentStreamExtensions>>) & ReactAgent["streamEvents"]; } /** * Helper type to resolve a DeepAgentTypeConfig from either: * - A DeepAgentTypeConfig directly * - A DeepAgent instance (using `typeof agent`) * * @example * ```typescript * const agent = createDeepAgent({ ... }); * type Types = ResolveDeepAgentTypeConfig; * ``` */ type ResolveDeepAgentTypeConfig = T extends { "~deepAgentTypes": infer Types; } ? Types extends DeepAgentTypeConfig ? Types : never : T extends DeepAgentTypeConfig ? T : never; /** * Helper type to extract any property from a DeepAgentTypeConfig or DeepAgent. * * @typeParam T - The DeepAgentTypeConfig or DeepAgent to extract from * @typeParam K - The property key to extract * * @example * ```typescript * const agent = createDeepAgent({ subagents: [...] }); * type Subagents = InferDeepAgentType; * ``` */ type InferDeepAgentType = ResolveDeepAgentTypeConfig[K]; /** * Shorthand helper to extract the Subagents type from a DeepAgentTypeConfig or DeepAgent. * * @example * ```typescript * const agent = createDeepAgent({ subagents: [subagent1, subagent2] }); * type Subagents = InferDeepAgentSubagents; * ``` */ type InferDeepAgentSubagents = InferDeepAgentType; /** * Helper type to extract a subagent by name from a DeepAgent. * * @typeParam T - The DeepAgent to extract from * @typeParam TName - The name of the subagent to extract * * @example * ```typescript * const agent = createDeepAgent({ * subagents: [ * { name: "researcher", description: "...", middleware: [ResearchMiddleware] } * ] as const, * }); * * type ResearcherAgent = InferSubagentByName; * ``` */ type InferSubagentByName = InferDeepAgentSubagents extends readonly (infer SA)[] ? SA extends { name: TName; } ? SA : never : never; /** * Helper type to extract the ReactAgent type from a subagent definition. * This is useful for type-safe streaming of subagent events. * * @typeParam TSubagent - The subagent definition * * @example * ```typescript * type SubagentMiddleware = ExtractSubAgentMiddleware; * type SubagentState = InferMiddlewareStates; * ``` */ type InferSubagentReactAgentType = TSubagent extends CompiledSubAgent ? TSubagent["runnable"] : TSubagent extends SubAgent ? ReactAgent, readonly []>> : never; /** * Configuration parameters for creating a Deep Agent * Matches Python's create_deep_agent parameters * * @typeParam TResponse - The structured response type when using responseFormat * @typeParam ContextSchema - The context schema type * @typeParam TMiddleware - The middleware array type for proper type inference * @typeParam TSubagents - The subagents array type for extracting subagent middleware states * @typeParam TTools - The tools array type * @typeParam TStreamTransformers - Custom stream transformer factories */ interface CreateDeepAgentParams | InteropZodObject = AnnotationRoot, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TSubagents extends readonly AnySubAgent[] = readonly AnySubAgent[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TStreamTransformers extends ReadonlyArray<() => StreamTransformer> = readonly []> { /** The model to use (model name string or LanguageModelLike instance). Defaults to claude-sonnet-4-5-20250929 */ model?: BaseLanguageModel | string; /** Tools the agent should have access to */ tools?: TTools | StructuredTool$1[]; /** Custom system prompt for the agent. This will be combined with the base agent prompt */ systemPrompt?: string | SystemMessage; /** Custom middleware to apply after standard middleware */ middleware?: TMiddleware; /** * List of subagent specifications for task delegation. * * Supports sync SubAgents, CompiledSubAgents, and AsyncSubAgents in the same array. * AsyncSubAgents (identified by their `graphId` field) are automatically separated * at runtime and wired to the async SubAgent middleware. */ subagents?: TSubagents; /** Structured output response format for the agent (Zod schema or other format) */ responseFormat?: TResponse; /** Optional schema for context (not persisted between invocations) */ contextSchema?: ContextSchema; /** Optional checkpointer for persisting agent state between runs */ checkpointer?: BaseCheckpointSaver | boolean; /** Optional store for persisting longterm memories */ store?: BaseStore; /** * Optional backend for filesystem operations. * Can be either a backend instance or a factory function that creates one. * The factory receives a config object with state and store. */ backend?: AnyBackendProtocol | ((config: { state: unknown; store?: BaseStore; }) => AnyBackendProtocol); /** Optional interrupt configuration mapping tool names to interrupt configs */ interruptOn?: Record; /** The name of the agent */ name?: string; /** * Optional list of memory file paths (AGENTS.md files) to load * (e.g., ["~/.deepagents/AGENTS.md", "./.deepagents/AGENTS.md"]). * Display names are automatically derived from paths. * Memory is loaded at agent startup and added into the system prompt. */ memory?: string[]; /** * Optional list of skill source paths (e.g., `["/skills/user/", "/skills/project/"]`). * * Paths use POSIX conventions (forward slashes) and are relative to the backend's root. * Later sources override earlier ones for skills with the same name (last one wins). * * @example * ```typescript * // With FilesystemBackend - skills loaded from disk * const agent = await createDeepAgent({ * backend: new FilesystemBackend({ rootDir: "/home/user/.deepagents" }), * skills: ["/skills/"], * }); * * // With StateBackend - skills provided in state * const agent = await createDeepAgent({ * skills: ["/skills/"], * }); * const result = await agent.invoke({ * messages: [...], * files: { * "/skills/my-skill/SKILL.md": { * content: ["---", "name: my-skill", "description: ...", "---", "# My Skill"], * created_at: new Date().toISOString(), * modified_at: new Date().toISOString(), * }, * }, * }); * ``` */ skills?: string[]; /** * Filesystem permission rules for this agent. * * Rules are evaluated in declaration order; first match wins; permissive * default. Applied to `ls`, `read_file`, `write_file`, `edit_file`, `glob`, * and `grep`. Subagents inherit these rules unless they specify their own * `permissions` field. * * @example * ```ts * createDeepAgent({ * permissions: [ * { operations: ["read"], paths: ["/workspace/**"] }, * { operations: ["read"], paths: ["/**"], mode: "deny" }, * ], * }); * ``` */ permissions?: FilesystemPermission[]; /** * Optional {@link StreamTransformer} factories to register with the underlying agent. * * Deepagents always registers its built-in subagent transformer; custom * transformers are appended after it and are exposed on `run.extensions` * when using `streamEvents(..., { version: "v3" })`. */ streamTransformers?: TStreamTransformers; } //#endregion //#region src/agent.d.ts /** * Create a Deep Agent. * * This is the main entry point for building a production-style agent with * deepagents. It gives you a strong default runtime (filesystem, tasks, * subagents, summarization) and lets you opt into skills, memory, * human-in-the-loop interrupts, async subagents, and custom middleware. * * The runtime is intentionally opinionated: defaults work out of the box, and * when you customize behavior, the middleware ordering stays deterministic. * * @param params Configuration parameters for the agent * @returns Deep Agent instance with inferred state/response types * * @example * ```typescript * // Middleware with custom state * const ResearchMiddleware = createMiddleware({ * name: "ResearchMiddleware", * stateSchema: z.object({ research: z.string().default("") }), * }); * * const agent = createDeepAgent({ * middleware: [ResearchMiddleware], * }); * * const result = await agent.invoke({ messages: [...] }); * // result.research is properly typed as string * ``` */ declare function createDeepAgent StreamTransformer> = readonly []>(params?: CreateDeepAgentParams): DeepAgent, undefined, ContextSchema, readonly [AgentMiddleware<_$zod_v30.ZodObject<{ todos: _$zod_v30.ZodDefault<_$zod_v30.ZodArray<_$zod_v30.ZodObject<{ content: _$zod_v30.ZodString; status: _$zod_v30.ZodEnum<["pending", "in_progress", "completed"]>; }, "strip", _$zod_v30.ZodTypeAny, { content: string; status: "completed" | "in_progress" | "pending"; }, { content: string; status: "completed" | "in_progress" | "pending"; }>, "many">>; }, "strip", _$zod_v30.ZodTypeAny, { todos: { content: string; status: "completed" | "in_progress" | "pending"; }[]; }, { todos?: { content: string; status: "completed" | "in_progress" | "pending"; }[] | undefined; }>, undefined, unknown, readonly [_langchain.DynamicStructuredTool<_$zod_v30.ZodObject<{ todos: _$zod_v30.ZodArray<_$zod_v30.ZodObject<{ content: _$zod_v30.ZodString; status: _$zod_v30.ZodEnum<["pending", "in_progress", "completed"]>; }, "strip", _$zod_v30.ZodTypeAny, { content: string; status: "completed" | "in_progress" | "pending"; }, { content: string; status: "completed" | "in_progress" | "pending"; }>, "many">; }, "strip", _$zod_v30.ZodTypeAny, { todos: { content: string; status: "completed" | "in_progress" | "pending"; }[]; }, { todos: { content: string; status: "completed" | "in_progress" | "pending"; }[]; }>, { todos: { content: string; status: "completed" | "in_progress" | "pending"; }[]; }, { todos: { content: string; status: "completed" | "in_progress" | "pending"; }[]; }, _langgraph.Command>[]; }, string>, unknown, "write_todos">]>, AgentMiddleware<_langgraph.StateSchema<{ files: _langgraph.ReducedValue; }>, undefined, unknown, (_langchain.DynamicStructuredTool>; }, _$zod_v4_core0.$strip>, { path: string; }, { path?: string | undefined; }, string, unknown, "ls"> | _langchain.DynamicStructuredTool>>; limit: z$2.ZodDefault>>; }, _$zod_v4_core0.$strip>, { file_path: string; offset: number; limit: number; }, { file_path: string; offset?: unknown; limit?: unknown; }, { type: string; text: string; }[] | { type: string; mimeType: string; data: string; }[], unknown, "read_file"> | _langchain.DynamicStructuredTool; }, _$zod_v4_core0.$strip>, { file_path: string; content: string; }, { file_path: string; content?: string | undefined; }, string | _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | _langgraph.Command; messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[]; }, string>, unknown, "write_file"> | _langchain.DynamicStructuredTool>; }, _$zod_v4_core0.$strip>, { file_path: string; old_string: string; new_string: string; replace_all: boolean; }, { file_path: string; old_string: string; new_string: string; replace_all?: boolean | undefined; }, string | _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | _langgraph.Command; messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[]; }, string>, unknown, "edit_file"> | _langchain.DynamicStructuredTool>; }, _$zod_v4_core0.$strip>, { pattern: string; path: string; }, { pattern: string; path?: string | undefined; }, string, unknown, "glob"> | _langchain.DynamicStructuredTool>; glob: z$2.ZodDefault>>; }, _$zod_v4_core0.$strip>, { pattern: string; path: string; glob: string | null; }, { pattern: string; path?: string | undefined; glob?: string | null | undefined; }, string, unknown, "grep"> | _langchain.DynamicStructuredTool, { command: string; }, { command: string; }, string, unknown, "execute">)[]>, AgentMiddleware, { description: string; subagent_type: string; }, { description: string; subagent_type: string; }, string | _langgraph.Command, string>, unknown, "task">]>, AgentMiddleware; _summarizationEvent: z$2.ZodOptional>, _messages.HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>>; filePath: z$2.ZodNullable; }, _$zod_v4_core0.$strip>>; }, _$zod_v4_core0.$strip>, undefined, unknown, readonly (ClientTool | ServerTool)[]>, AgentMiddleware, ...TMiddleware, ...FlattenSubAgentMiddleware], TTools, TSubagents, TStreamTransformers>>; //#endregion //#region src/errors.d.ts /** * Error codes for {@link ConfigurationError}. * * Each code represents a distinct misconfiguration that can be detected at * agent-construction time. Add new codes here as new validations are added. */ type ConfigurationErrorCode = "TOOL_NAME_COLLISION"; declare const CONFIGURATION_ERROR_SYMBOL: unique symbol; /** * Thrown when `createDeepAgent` receives invalid configuration. * * Follows the same pattern as {@link SandboxError}: a human-readable * `message`, a structured `code` for programmatic handling, and a * static `isInstance` guard that works across realms. * * @example * ```typescript * try { * createDeepAgent({ tools: [myTool] }); * } catch (error) { * if (ConfigurationError.isInstance(error)) { * switch (error.code) { * case "TOOL_NAME_COLLISION": * console.error("Rename your tool:", error.message); * break; * } * } * } * ``` */ declare class ConfigurationError extends Error { readonly code: ConfigurationErrorCode; readonly cause?: Error | undefined; [CONFIGURATION_ERROR_SYMBOL]: true; readonly name: string; constructor(message: string, code: ConfigurationErrorCode, cause?: Error | undefined); static isInstance(error: unknown): error is ConfigurationError; } //#endregion //#region src/profiles/harness/types.d.ts /** * Middleware names that provide essential agent capabilities and cannot * be excluded via `excludedMiddleware`. * * - `FilesystemMiddleware` backs all built-in file tools and enforces * filesystem permissions. * - `SubAgentMiddleware` backs the `task` tool for subagent delegation. */ declare const REQUIRED_MIDDLEWARE_NAMES: Set; /** * Configuration for the auto-added general-purpose subagent. * * All fields use three-state semantics: `undefined` inherits the * default, an explicit value overrides it. This allows model-level * profiles to selectively override provider-level defaults without * clobbering fields they don't care about. */ interface GeneralPurposeSubagentConfig { /** * Whether to auto-add the general-purpose subagent. * * - `undefined` — inherit the default (enabled). * - `true` — force inclusion even if a provider profile disables it. * - `false` — disable the GP subagent entirely. * * @default undefined */ enabled?: boolean; /** * Override the default GP subagent description shown to the model. * * @default undefined (uses `DEFAULT_GENERAL_PURPOSE_DESCRIPTION`) */ description?: string; /** * Override the default GP subagent system prompt. * * When both this and `HarnessProfile.baseSystemPrompt` are set, this * more-specific value wins for the GP subagent. * * @default undefined (uses `DEFAULT_SUBAGENT_PROMPT`) */ systemPrompt?: string; } /** * User-facing options for creating a {@link HarnessProfile}. * * Accepts plain arrays and records; the factory function converts them * to their frozen counterparts. All fields are optional — an empty * object produces a no-op profile. */ interface HarnessProfileOptions { /** * Replaces the default `BASE_AGENT_PROMPT` when set. * * Use this when a model requires a fundamentally different base * prompt rather than an additive suffix. Most profiles should prefer * `systemPromptSuffix` instead. * * @default undefined (keeps the default base prompt) */ baseSystemPrompt?: string; /** * Text appended to the assembled base prompt with a blank-line * separator (`\n\n`). * * This is the primary mechanism for model-specific prompt tuning. * Applied uniformly to the main agent, declarative subagents, and * the auto-added general-purpose subagent. * * @default undefined (no suffix appended) */ systemPromptSuffix?: string; /** * Per-tool description replacements keyed by tool name. * * Allows profiles to rewrite tool descriptions for models that * respond better to different phrasing. Keys that don't match any * tool in the final tool set are silently ignored. * * @default {} (no overrides) */ toolDescriptionOverrides?: Record; /** * Tool names to remove from the agent's visible tool set. * * Applied via a filtering middleware after all tool-injecting * middleware have run, so it catches both user-provided and * middleware-provided tools. * * @default [] (no tools excluded) */ excludedTools?: string[]; /** * Middleware names to remove from the assembled middleware stack. * * Matched against each middleware's `.name` property. Cannot include * required scaffolding names (`FilesystemMiddleware`, * `SubAgentMiddleware`) — attempting to do so throws at construction * time. * * @default [] (no middleware excluded) */ excludedMiddleware?: string[]; /** * Additional middleware appended to the stack after user middleware. * * Can be a static array or a zero-arg factory that returns fresh * instances per agent construction (important when middleware carries * mutable state). * * @default [] (no extra middleware) */ extraMiddleware?: AgentMiddleware[] | (() => AgentMiddleware[]); /** * Configuration for the auto-added general-purpose subagent. * * @default undefined (GP subagent uses all defaults) */ generalPurposeSubagent?: GeneralPurposeSubagentConfig; } /** * Frozen runtime harness profile that shapes agent behavior at * assembly time. * * Created by {@link createHarnessProfile} from user-provided * {@link HarnessProfileOptions}. Collection types are narrowed * (arrays → `Set`, records frozen) and all fields are required. * The object is frozen via `Object.freeze()` to prevent mutation * after construction. * * Profiles are **orthogonal to model selection**: they control prompt * assembly, tool visibility, middleware composition, and subagent * configuration — not which model is used. */ interface HarnessProfile { /** * Replaces the default `BASE_AGENT_PROMPT` when set. * * Use this when a model requires a fundamentally different base * prompt rather than an additive suffix. Most profiles should prefer * `systemPromptSuffix` instead. */ baseSystemPrompt: string | undefined; /** * Text appended to the assembled base prompt with a blank-line * separator (`\n\n`). * * This is the primary mechanism for model-specific prompt tuning. * Applied uniformly to the main agent, declarative subagents, and * the auto-added general-purpose subagent. */ systemPromptSuffix: string | undefined; /** * Per-tool description replacements keyed by tool name. * * Allows profiles to rewrite tool descriptions for models that * respond better to different phrasing. Keys that don't match any * tool in the final tool set are silently ignored. */ toolDescriptionOverrides: Record; /** * Tool names to remove from the agent's visible tool set. * * Applied via a filtering middleware after all tool-injecting * middleware have run, so it catches both user-provided and * middleware-provided tools. */ excludedTools: Set; /** * Middleware names to remove from the assembled middleware stack. * * Matched against each middleware's `.name` property. Cannot include * required scaffolding names (`FilesystemMiddleware`, * `SubAgentMiddleware`) — attempting to do so throws at construction * time. */ excludedMiddleware: Set; /** * Additional middleware appended to the stack after user middleware. * * Can be a static array or a zero-arg factory that returns fresh * instances per agent construction (important when middleware carries * mutable state). */ extraMiddleware: AgentMiddleware[] | (() => AgentMiddleware[]); /** * Configuration for the auto-added general-purpose subagent. */ generalPurposeSubagent: GeneralPurposeSubagentConfig | undefined; } //#endregion //#region src/profiles/harness/create.d.ts /** * Create a frozen {@link HarnessProfile} from user-provided options. * * Validates all fields, converts mutable collections to their * frozen counterparts, and returns a frozen object. * Empty options produce a no-op profile (all defaults). * * @param options - Partial profile configuration. * @returns A frozen, validated `HarnessProfile`. * @throws {Error} When any field violates validation rules (invalid * middleware names, scaffolding exclusion attempts). * * @example * ```typescript * const profile = createHarnessProfile({ * systemPromptSuffix: "Think step by step.", * excludedTools: ["execute"], * }); * ``` */ declare function createHarnessProfile(options?: HarnessProfileOptions): HarnessProfile; /** * An empty no-op profile used as the default when no registered * profile matches. Avoids creating a new object on every miss. */ declare const EMPTY_HARNESS_PROFILE: HarnessProfile; //#endregion //#region src/profiles/harness/serialization.d.ts /** * Zod schema for the general-purpose subagent config section of an * external harness profile config file. */ declare const generalPurposeSubagentConfigSchema: z.ZodObject<{ enabled: z.ZodOptional; description: z.ZodOptional; systemPrompt: z.ZodOptional; }, z.core.$strict>; /** * Zod schema for parsing a harness profile from an external JSON or * YAML config file. * * Uses `.strict()` to reject unknown keys (catches typos early). Array * fields (`excludedTools`, `excludedMiddleware`) accept arrays of * strings; the result is passed to {@link createHarnessProfile} which * converts them to `Set`. * * Does not include `extraMiddleware` — middleware instances cannot be * represented in JSON/YAML. * * @example * ```typescript * import { readFileSync } from "fs"; * import YAML from "yaml"; * * const raw = YAML.parse(readFileSync("profile.yaml", "utf-8")); * const config = harnessProfileConfigSchema.parse(raw); * const profile = createHarnessProfile(config); * ``` */ declare const harnessProfileConfigSchema: z.ZodObject<{ baseSystemPrompt: z.ZodOptional; systemPromptSuffix: z.ZodOptional; toolDescriptionOverrides: z.ZodOptional>; excludedTools: z.ZodOptional>; excludedMiddleware: z.ZodOptional>; generalPurposeSubagent: z.ZodOptional; description: z.ZodOptional; systemPrompt: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>; /** * TypeScript type inferred from the Zod config schema. * * Represents the JSON/YAML-compatible shape of a harness profile. This * is the type of data that comes out of `harnessProfileConfigSchema.parse()`. */ type HarnessProfileConfigData = z.infer; /** * Parse an untrusted JSON/YAML object into a validated * {@link HarnessProfile}. * * Combines Zod schema validation with prototype-pollution protection * and profile construction validation. Use this for any config data * that originates from files, network, or user input. * * @param data - Raw object from `JSON.parse()` or `YAML.parse()`. * @returns A frozen, validated `HarnessProfile`. * @throws {z.ZodError} When the data fails schema validation. * @throws {Error} When profile-level validation fails (e.g., * scaffolding violation in `excludedMiddleware`). */ declare function parseHarnessProfileConfig(data: unknown): HarnessProfile; /** * Serialize a {@link HarnessProfile} to a JSON-compatible object. * * Omits `undefined` fields and `extraMiddleware` (runtime-only). * Throws if `extraMiddleware` contains instances — callers should * strip it before serializing if they've set it. * * @param profile - The profile to serialize. * @returns A plain object matching {@link HarnessProfileConfigData}. * @throws {Error} When `extraMiddleware` is non-empty (cannot be * serialized to JSON). */ declare function serializeProfile(profile: HarnessProfile): HarnessProfileConfigData; //#endregion //#region src/profiles/harness/registry.d.ts /** * Register a harness profile for a provider or specific model. * * Accepts either a pre-built {@link HarnessProfile} (from * {@link createHarnessProfile}) or raw {@link HarnessProfileOptions} * that will be validated and frozen automatically. * * Registrations are **additive**: if a profile already exists under * `key`, the new profile is merged on top. The incoming profile's * fields win on scalar conflicts; set fields union; middleware * sequences merge by name. * * @param key - Either a bare provider (`"openai"`) for provider-wide * defaults, or `"provider:model"` for a per-model override. * @param profile - A `HarnessProfile` or options to build one from. * @throws {Error} When `key` is malformed or profile validation * fails. * * @example * ```typescript * import { registerHarnessProfile } from "@langchain/deepagents"; * * registerHarnessProfile("openai", { * systemPromptSuffix: "Respond concisely.", * }); * * registerHarnessProfile("openai:gpt-5.4", { * excludedTools: ["execute"], * }); * ``` */ declare function registerHarnessProfile(key: string, profile: HarnessProfile | HarnessProfileOptions): void; /** * Look up the {@link HarnessProfile} for a model spec string. * * Resolution order: * * 1. **Exact match** on `spec` (e.g., `"openai:gpt-5.4"`). * 2. **Provider prefix** (everything before `:`) when `spec` contains * a colon and both halves are non-empty. * 3. When both exist, they are **merged** (provider as base, exact as * override). * 4. `undefined` when nothing matches. * * Malformed specs (empty, multiple colons, empty halves) return * `undefined` without consulting the registry. * * @param spec - Model spec in `"provider:model"` format, or a bare * provider/model identifier. * @returns The matching profile, or `undefined`. */ declare function getHarnessProfile(spec: string): HarnessProfile | undefined; //#endregion //#region src/config.d.ts /** * Configuration and settings for deepagents. * * Provides project detection, path management, and environment configuration * for skills and agent memory middleware. */ /** * Options for creating a Settings instance. */ interface SettingsOptions { /** Starting directory for project detection (defaults to cwd) */ startPath?: string; } /** * Settings interface for project detection and path management. * * Provides access to: * - Project root detection (via .git directory) * - User-level deepagents directory (~/.deepagents) * - Agent-specific directories and files * - Skills directories (user and project level) */ interface Settings { /** Detected project root directory, or null if not in a git project */ readonly projectRoot: string | null; /** Base user-level .deepagents directory (~/.deepagents) */ readonly userDeepagentsDir: string; /** Check if currently in a git project */ readonly hasProject: boolean; /** * Get the agent directory path. * @param agentName - Name of the agent * @returns Path to ~/.deepagents/{agentName} * @throws Error if agent name is invalid */ getAgentDir(agentName: string): string; /** * Ensure agent directory exists and return path. * @param agentName - Name of the agent * @returns Path to ~/.deepagents/{agentName} * @throws Error if agent name is invalid */ ensureAgentDir(agentName: string): string; /** * Get user-level agent.md path for a specific agent. * @param agentName - Name of the agent * @returns Path to ~/.deepagents/{agentName}/agent.md */ getUserAgentMdPath(agentName: string): string; /** * Get project-level agent.md path. * @returns Path to {projectRoot}/.deepagents/agent.md, or null if not in a project */ getProjectAgentMdPath(): string | null; /** * Get user-level skills directory path for a specific agent. * @param agentName - Name of the agent * @returns Path to ~/.deepagents/{agentName}/skills/ */ getUserSkillsDir(agentName: string): string; /** * Ensure user-level skills directory exists and return path. * @param agentName - Name of the agent * @returns Path to ~/.deepagents/{agentName}/skills/ */ ensureUserSkillsDir(agentName: string): string; /** * Get project-level skills directory path. * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project */ getProjectSkillsDir(): string | null; /** * Ensure project-level skills directory exists and return path. * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project */ ensureProjectSkillsDir(): string | null; /** * Ensure project .deepagents directory exists. * @returns Path to {projectRoot}/.deepagents/, or null if not in a project */ ensureProjectDeepagentsDir(): string | null; } /** * Find the project root by looking for .git directory. * * Walks up the directory tree from startPath (or cwd) looking for a .git * directory, which indicates the project root. * * @param startPath - Directory to start searching from. Defaults to current working directory. * @returns Path to the project root if found, null otherwise. */ declare function findProjectRoot(startPath?: string): string | null; /** * Create a Settings instance with detected environment. * * @param options - Configuration options * @returns Settings instance with project detection and path management */ declare function createSettings(options?: SettingsOptions): Settings; //#endregion //#region src/values.d.ts /** * Shared ReducedValue for file data state management. * * This provides a reusable pattern for managing file state with automatic * merging of concurrent updates from parallel subagents. Files can be updated * or deleted (using null values) and the reducer handles the merge logic. * * Similar to LangGraph's messagesValue, this encapsulates the common pattern * of managing files in agent state so you don't have to manually configure * the ReducedValue each time. * * @example * ```typescript * import { filesValue } from "@anthropic/deepagents"; * import { StateSchema } from "@langchain/langgraph"; * * const MyStateSchema = new StateSchema({ * files: filesValue, * // ... other state fields * }); * ``` */ declare const filesValue: ReducedValue; //#endregion //#region src/middleware/agent-memory.d.ts /** * Options for the agent memory middleware. */ interface AgentMemoryMiddlewareOptions { /** Settings instance with project detection and paths */ settings: Settings; /** The agent identifier */ assistantId: string; /** Optional custom template for injecting agent memory into system prompt */ systemPromptTemplate?: string; } /** * Create middleware for loading agent-specific long-term memory. * * This middleware loads the agent's long-term memory from a file (agent.md) * and injects it into the system prompt. The memory is loaded once at the * start of the conversation and stored in state. * * @param options - Configuration options * @returns AgentMiddleware for memory loading and injection * * @deprecated Use `createMemoryMiddleware` from `./memory.js` instead. * This function uses direct filesystem access which limits portability. */ declare function createAgentMemoryMiddleware(options: AgentMemoryMiddlewareOptions): AgentMiddleware; //#endregion //#region src/skills/loader.d.ts /** * Metadata for a skill per Agent Skills spec. * @see https://agentskills.io/specification */ interface SkillMetadata { /** Name of the skill (max 64 chars, lowercase alphanumeric and hyphens) */ name: string; /** Description of what the skill does (max 1024 chars) */ description: string; /** Absolute path to the SKILL.md file */ path: string; /** Source of the skill ('user' or 'project') */ source: "user" | "project"; /** Optional: License name or reference to bundled license file */ license?: string; /** Optional: Environment requirements (max 500 chars) */ compatibility?: string; /** Optional: Arbitrary key-value mapping for additional metadata */ metadata?: Record; /** Optional: Space-delimited list of pre-approved tools */ allowedTools?: string; } /** * Options for listing skills. */ interface ListSkillsOptions { /** Path to user-level skills directory */ userSkillsDir?: string | null; /** Path to project-level skills directory */ projectSkillsDir?: string | null; } /** * Parse YAML frontmatter from a SKILL.md file per Agent Skills spec. * * @param skillMdPath - Path to the SKILL.md file * @param source - Source of the skill ('user' or 'project') * @returns SkillMetadata with all fields, or null if parsing fails */ declare function parseSkillMetadata(skillMdPath: string, source: "user" | "project"): SkillMetadata | null; /** * List skills from user and/or project directories. * * When both directories are provided, project skills with the same name as * user skills will override them. * * @param options - Options specifying which directories to search * @returns Merged list of skill metadata from both sources, with project skills * taking precedence over user skills when names conflict */ declare function listSkills(options: ListSkillsOptions): SkillMetadata[]; //#endregion export { type AgentMemoryMiddlewareOptions, type AnyBackendProtocol, type AnySubAgent, type AsyncSubAgent, type AsyncSubAgentMiddlewareOptions, type AsyncTask, type AsyncTaskStatus, type BackendFactory, type BackendProtocol, type BackendProtocolV1, type BackendProtocolV2, type BackendRuntime, BaseSandbox, type CompiledSubAgent, type CompletionCallbackOptions, CompositeBackend, ConfigurationError, type ConfigurationErrorCode, ContextHubBackend, type CreateDeepAgentParams, DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT, type DeepAgent, type DeepAgentRunStream, type DeepAgentTypeConfig, type DefaultDeepAgentTypeConfig, EMPTY_HARNESS_PROFILE, type EditResult, type ExecuteResponse, type ExtractSubAgentMiddleware, type FileData, type FileDownloadResponse, type FileInfo, type FileOperationError, type FileUploadResponse, FilesystemBackend, type FilesystemMiddlewareOptions, type FilesystemOperation, type FilesystemPermission, type FlattenSubAgentMiddleware, GENERAL_PURPOSE_SUBAGENT, type GeneralPurposeSubagentConfig, type GlobResult, type GrepMatch, type GrepResult, type HarnessProfile, type HarnessProfileConfigData, type HarnessProfileOptions, type InferDeepAgentSubagents, type InferDeepAgentType, type InferStructuredResponse, type InferSubAgentMiddlewareStates, type InferSubagentByName, type InferSubagentReactAgentType, type LangSmithCaptureSnapshotOptions, LangSmithSandbox, type LangSmithSandboxCreateOptions, type LangSmithSandboxOptions, type LangSmithSnapshot, type LangSmithStartSandboxOptions, type ListSkillsOptions, type SkillMetadata as LoaderSkillMetadata, LocalShellBackend, type LocalShellBackendOptions, type LsResult, MAX_SKILL_DESCRIPTION_LENGTH, MAX_SKILL_FILE_SIZE, MAX_SKILL_NAME_LENGTH, type MaybePromise, type MemoryMiddlewareOptions, type MergedDeepAgentState, type PermissionMode, REQUIRED_MIDDLEWARE_NAMES, type ReadRawResult, type ReadResult, type ResolveDeepAgentTypeConfig, type SandboxBackendProtocol, type SandboxBackendProtocolV1, type SandboxBackendProtocolV2, type SandboxDeleteOptions, SandboxError, type SandboxErrorCode, type SandboxGetOrCreateOptions, type SandboxInfo, type SandboxListOptions, type SandboxListResponse, type Settings, type SettingsOptions, type SkillMetadata$1 as SkillMetadata, type SkillsMiddlewareOptions, type StateAndStore, StateBackend, StoreBackend, type StoreBackendContext, type StoreBackendNamespaceFactory, type StoreBackendOptions, type SubAgent, type SubAgentMiddlewareOptions, type SubagentRunStream, type SupportedResponseFormat, TASK_SYSTEM_PROMPT, type WriteResult, adaptBackendProtocol, adaptSandboxProtocol, computeSummarizationDefaults, createAgentMemoryMiddleware, createAsyncSubAgentMiddleware, createCompletionCallbackMiddleware, createDeepAgent, createFilesystemMiddleware, createHarnessProfile, createMemoryMiddleware, createPatchToolCallsMiddleware, createSettings, createSkillsMiddleware, createSubAgentMiddleware, createSubagentTransformer, createSummarizationMiddleware, filesValue, findProjectRoot, generalPurposeSubagentConfigSchema, getHarnessProfile, harnessProfileConfigSchema, isAsyncSubAgent, isSandboxBackend, isSandboxProtocol, listSkills, parseHarnessProfileConfig, parseSkillMetadata, registerHarnessProfile, resolveBackend, serializeProfile }; //# sourceMappingURL=index.d.cts.map