deepagents 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +736 -486
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +366 -164
- package/dist/index.d.ts +329 -127
- package/dist/index.js +736 -487
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["lines: string[]","resultLines: string[]","path","normalizedPath: string","matches: Array<[string, string]>","regex: RegExp","e: any","matches: GrepMatch[]","infos: FileInfo[]","path","responses: FileUploadResponse[]","updates: Record<string, FileData>","responses: FileDownloadResponse[]","z","result: Record<string, FileData>","result","path","lines: string[]","ToolMessage","Command","currentFile: string | null","accumulatedFiles: Record<string, FileData>","processedMessages: ToolMessage[]","filtered: Record<string, unknown>","Command","ToolMessage","agents: Record<string, ReactAgent | Runnable>","subagentDescriptions: string[]","HumanMessage","z","patchedMessages: any[]","AIMessage","ToolMessage","RemoveMessage","REMOVE_ALL_MESSAGES","allItems: Item[]","infos: FileInfo[]","path","e: any","files: Record<string, FileData>","responses: FileUploadResponse[]","responses: FileDownloadResponse[]","fsSync","path","fs","results: FileInfo[]","relativePath: string","content: string","e: any","stat: fsSync.Stats","baseFull: string","matches: GrepMatch[]","results: Record<string, Array<[number, string]>>","virtPath: string","regex: RegExp","responses: FileUploadResponse[]","responses: FileDownloadResponse[]","path","prefixed: FileInfo[]","results: FileInfo[]","allMatches: GrepMatch[]","results: Array<FileUploadResponse | null>","results: Array<FileDownloadResponse | null>","path","infos: FileInfo[]","lines: string[]","matches: GrepMatch[]","SystemMessage","path","fs","os","fs","path","resolvedBase: string","skills: SkillMetadata[]","entries: fs.Dirent[]","allSkills: Map<string, SkillMetadata>","z","lines: string[]","skillsMetadata: SkillMetadata[]","z","result: Record<string, string>","fs"],"sources":["../src/backends/protocol.ts","../src/backends/utils.ts","../src/backends/state.ts","../src/middleware/fs.ts","../src/middleware/subagents.ts","../src/middleware/patch_tool_calls.ts","../src/backends/store.ts","../src/backends/filesystem.ts","../src/backends/composite.ts","../src/backends/sandbox.ts","../src/agent.ts","../src/config.ts","../src/skills/loader.ts","../src/middleware/skills.ts","../src/middleware/agent-memory.ts"],"sourcesContent":["/**\n * Protocol definition for pluggable memory backends.\n *\n * This module defines the BackendProtocol that all backend implementations\n * must follow. Backends can store files in different locations (state, filesystem,\n * database, etc.) and provide a uniform interface for file operations.\n */\n\nimport type { BaseStore } from \"@langchain/langgraph-checkpoint\";\n\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Structured file listing info.\n *\n * Minimal contract used across backends. Only \"path\" is required.\n * Other fields are best-effort and may be absent depending on backend.\n */\nexport interface FileInfo {\n /** File path */\n path: string;\n /** Whether this is a directory */\n is_dir?: boolean;\n /** File size in bytes (approximate) */\n size?: number;\n /** ISO 8601 timestamp of last modification */\n modified_at?: string;\n}\n\n/**\n * Structured grep match entry.\n */\nexport interface GrepMatch {\n /** File path where match was found */\n path: string;\n /** Line number (1-indexed) */\n line: number;\n /** The matching line text */\n text: string;\n}\n\n/**\n * File data structure used by backends.\n *\n * All file data is represented as objects with this structure:\n */\nexport interface FileData {\n /** Lines of text content */\n content: string[];\n /** ISO format timestamp of creation */\n created_at: string;\n /** ISO format timestamp of last modification */\n modified_at: string;\n}\n\n/**\n * Result from backend write operations.\n *\n * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.\n * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).\n */\nexport interface WriteResult {\n /** Error message on failure, undefined on success */\n error?: string;\n /** File path of written file, undefined on failure */\n path?: string;\n /**\n * State update dict for checkpoint backends, null for external storage.\n * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.\n * External backends set null (already persisted to disk/S3/database/etc).\n */\n filesUpdate?: Record<string, FileData> | null;\n /** Metadata for the write operation, attached to the ToolMessage */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Result from backend edit operations.\n *\n * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.\n * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).\n */\nexport interface EditResult {\n /** Error message on failure, undefined on success */\n error?: string;\n /** File path of edited file, undefined on failure */\n path?: string;\n /**\n * State update dict for checkpoint backends, null for external storage.\n * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.\n * External backends set null (already persisted to disk/S3/database/etc).\n */\n filesUpdate?: Record<string, FileData> | null;\n /** Number of replacements made, undefined on failure */\n occurrences?: number;\n /** Metadata for the edit operation, attached to the ToolMessage */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Result of code execution.\n * Simplified schema optimized for LLM consumption.\n */\nexport interface ExecuteResponse {\n /** Combined stdout and stderr output of the executed command */\n output: string;\n /** The process exit code. 0 indicates success, non-zero indicates failure */\n exitCode: number | null;\n /** Whether the output was truncated due to backend limitations */\n truncated: boolean;\n}\n\n/**\n * Standardized error codes for file upload/download operations.\n */\nexport type FileOperationError =\n | \"file_not_found\"\n | \"permission_denied\"\n | \"is_directory\"\n | \"invalid_path\";\n\n/**\n * Result of a single file download operation.\n */\nexport interface FileDownloadResponse {\n /** The file path that was requested */\n path: string;\n /** File contents as Uint8Array on success, null on failure */\n content: Uint8Array | null;\n /** Standardized error code on failure, null on success */\n error: FileOperationError | null;\n}\n\n/**\n * Result of a single file upload operation.\n */\nexport interface FileUploadResponse {\n /** The file path that was requested */\n path: string;\n /** Standardized error code on failure, null on success */\n error: FileOperationError | null;\n}\n\n/**\n * Protocol for pluggable memory backends (single, unified).\n *\n * Backends can store files in different locations (state, filesystem, database, etc.)\n * and provide a uniform interface for file operations.\n *\n * All file data is represented as objects with the FileData structure.\n *\n * Methods can return either direct values or Promises, allowing both\n * synchronous and asynchronous implementations.\n */\nexport interface BackendProtocol {\n /**\n * Structured listing with file metadata.\n *\n * Lists files and directories in the specified directory (non-recursive).\n * Directories have a trailing / in their path and is_dir=true.\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory\n */\n lsInfo(path: string): MaybePromise<FileInfo[]>;\n\n /**\n * Read file content with line numbers or an error string.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed), default 0\n * @param limit - Maximum number of lines to read, default 2000\n * @returns Formatted file content with line numbers, or error message\n */\n read(filePath: string, offset?: number, limit?: number): MaybePromise<string>;\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n readRaw(filePath: string): MaybePromise<FileData>;\n\n /**\n * Structured search results or error string for invalid input.\n *\n * Searches file contents for a regex pattern.\n *\n * @param pattern - Regex pattern to search for\n * @param path - Base path to search from (default: null)\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @returns List of GrepMatch objects or error string for invalid regex\n */\n grepRaw(\n pattern: string,\n path?: string | null,\n glob?: string | null,\n ): MaybePromise<GrepMatch[] | string>;\n\n /**\n * Structured glob matching returning FileInfo objects.\n *\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param path - Base path to search from (default: \"/\")\n * @returns List of FileInfo objects matching the pattern\n */\n globInfo(pattern: string, path?: string): MaybePromise<FileInfo[]>;\n\n /**\n * Create a new file.\n *\n * @param filePath - Absolute file path\n * @param content - File content as string\n * @returns WriteResult with error populated on failure\n */\n write(filePath: string, content: string): MaybePromise<WriteResult>;\n\n /**\n * Edit a file by replacing string occurrences.\n *\n * @param filePath - Absolute file path\n * @param oldString - String to find and replace\n * @param newString - Replacement string\n * @param replaceAll - If true, replace all occurrences (default: false)\n * @returns EditResult with error, path, filesUpdate, and occurrences\n */\n edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll?: boolean,\n ): MaybePromise<EditResult>;\n\n /**\n * Upload multiple files.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): MaybePromise<FileUploadResponse[]>;\n\n /**\n * Download multiple files.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;\n}\n\n/**\n * Protocol for sandboxed backends with isolated runtime.\n * Sandboxed backends run in isolated environments (e.g., containers)\n * and communicate via defined interfaces.\n */\nexport interface SandboxBackendProtocol extends BackendProtocol {\n /**\n * Execute a command in the sandbox.\n *\n * @param command - Full shell command string to execute\n * @returns ExecuteResponse with combined output, exit code, and truncation flag\n */\n execute(command: string): MaybePromise<ExecuteResponse>;\n\n /** Unique identifier for the sandbox backend instance */\n readonly id: string;\n}\n\n/**\n * Type guard to check if a backend supports execution.\n *\n * @param backend - Backend instance to check\n * @returns True if the backend implements SandboxBackendProtocol\n */\nexport function isSandboxBackend(\n backend: BackendProtocol,\n): backend is SandboxBackendProtocol {\n return (\n typeof (backend as SandboxBackendProtocol).execute === \"function\" &&\n typeof (backend as SandboxBackendProtocol).id === \"string\"\n );\n}\n\n/**\n * State and store container for backend initialization.\n *\n * This provides a clean interface for what backends need to access:\n * - state: Current agent state (with files, messages, etc.)\n * - store: Optional persistent store for cross-conversation data\n *\n * Different contexts build this differently:\n * - Tools: Extract state via getCurrentTaskInput(config)\n * - Middleware: Use request.state directly\n */\nexport interface StateAndStore {\n /** Current agent state with files, messages, etc. */\n state: unknown;\n /** Optional BaseStore for persistent cross-conversation storage */\n store?: BaseStore;\n /** Optional assistant ID for per-assistant isolation in store */\n assistantId?: string;\n}\n\n/**\n * Factory function type for creating backend instances.\n *\n * Backends receive StateAndStore which contains the current state\n * and optional store, extracted from the execution context.\n *\n * @example\n * ```typescript\n * // Using in middleware\n * const middleware = createFilesystemMiddleware({\n * backend: (stateAndStore) => new StateBackend(stateAndStore)\n * });\n * ```\n */\nexport type BackendFactory = (stateAndStore: StateAndStore) => BackendProtocol;\n","/**\n * Shared utility functions for memory backend implementations.\n *\n * This module contains both user-facing string formatters and structured\n * helpers used by backends and the composite router. Structured helpers\n * enable composition without fragile string parsing.\n */\n\nimport micromatch from \"micromatch\";\nimport { basename } from \"path\";\nimport type { FileData, GrepMatch } from \"./protocol.js\";\n\n// Constants\nexport const EMPTY_CONTENT_WARNING =\n \"System reminder: File exists but has empty contents\";\nexport const MAX_LINE_LENGTH = 10000;\nexport const LINE_NUMBER_WIDTH = 6;\nexport const TOOL_RESULT_TOKEN_LIMIT = 20000; // Same threshold as eviction\nexport const TRUNCATION_GUIDANCE =\n \"... [results truncated, try being more specific with your parameters]\";\n\n/**\n * Sanitize tool_call_id to prevent path traversal and separator issues.\n *\n * Replaces dangerous characters (., /, \\) with underscores.\n */\nexport function sanitizeToolCallId(toolCallId: string): string {\n return toolCallId.replace(/\\./g, \"_\").replace(/\\//g, \"_\").replace(/\\\\/g, \"_\");\n}\n\n/**\n * Format file content with line numbers (cat -n style).\n *\n * Chunks lines longer than MAX_LINE_LENGTH with continuation markers (e.g., 5.1, 5.2).\n *\n * @param content - File content as string or list of lines\n * @param startLine - Starting line number (default: 1)\n * @returns Formatted content with line numbers and continuation markers\n */\nexport function formatContentWithLineNumbers(\n content: string | string[],\n startLine: number = 1,\n): string {\n let lines: string[];\n if (typeof content === \"string\") {\n lines = content.split(\"\\n\");\n if (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines = lines.slice(0, -1);\n }\n } else {\n lines = content;\n }\n\n const resultLines: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNum = i + startLine;\n\n if (line.length <= MAX_LINE_LENGTH) {\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${line}`,\n );\n } else {\n // Split long line into chunks with continuation markers\n const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH);\n for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) {\n const start = chunkIdx * MAX_LINE_LENGTH;\n const end = Math.min(start + MAX_LINE_LENGTH, line.length);\n const chunk = line.substring(start, end);\n if (chunkIdx === 0) {\n // First chunk: use normal line number\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n } else {\n // Continuation chunks: use decimal notation (e.g., 5.1, 5.2)\n const continuationMarker = `${lineNum}.${chunkIdx}`;\n resultLines.push(\n `${continuationMarker.padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n }\n }\n }\n }\n\n return resultLines.join(\"\\n\");\n}\n\n/**\n * Check if content is empty and return warning message.\n *\n * @param content - Content to check\n * @returns Warning message if empty, null otherwise\n */\nexport function checkEmptyContent(content: string): string | null {\n if (!content || content.trim() === \"\") {\n return EMPTY_CONTENT_WARNING;\n }\n return null;\n}\n\n/**\n * Convert FileData to plain string content.\n *\n * @param fileData - FileData object with 'content' key\n * @returns Content as string with lines joined by newlines\n */\nexport function fileDataToString(fileData: FileData): string {\n return fileData.content.join(\"\\n\");\n}\n\n/**\n * Create a FileData object with timestamps.\n *\n * @param content - File content as string\n * @param createdAt - Optional creation timestamp (ISO format)\n * @returns FileData object with content and timestamps\n */\nexport function createFileData(content: string, createdAt?: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: createdAt || now,\n modified_at: now,\n };\n}\n\n/**\n * Update FileData with new content, preserving creation timestamp.\n *\n * @param fileData - Existing FileData object\n * @param content - New content as string\n * @returns Updated FileData object\n */\nexport function updateFileData(fileData: FileData, content: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: fileData.created_at,\n modified_at: now,\n };\n}\n\n/**\n * Format file data for read response with line numbers.\n *\n * @param fileData - FileData object\n * @param offset - Line offset (0-indexed)\n * @param limit - Maximum number of lines\n * @returns Formatted content or error message\n */\nexport function formatReadResponse(\n fileData: FileData,\n offset: number,\n limit: number,\n): string {\n const content = fileDataToString(fileData);\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n}\n\n/**\n * Perform string replacement with occurrence validation.\n *\n * @param content - Original content\n * @param oldString - String to replace\n * @param newString - Replacement string\n * @param replaceAll - Whether to replace all occurrences\n * @returns Tuple of [new_content, occurrences] on success, or error message string\n */\nexport function performStringReplacement(\n content: string,\n oldString: string,\n newString: string,\n replaceAll: boolean,\n): [string, number] | string {\n // Use split to count occurrences (simpler than regex)\n const occurrences = content.split(oldString).length - 1;\n\n if (occurrences === 0) {\n return `Error: String not found in file: '${oldString}'`;\n }\n\n if (occurrences > 1 && !replaceAll) {\n return `Error: String '${oldString}' appears ${occurrences} times in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`;\n }\n\n // Python's str.replace() replaces ALL occurrences\n // Use split/join for consistent behavior\n const newContent = content.split(oldString).join(newString);\n\n return [newContent, occurrences];\n}\n\n/**\n * Truncate list or string result if it exceeds token limit (rough estimate: 4 chars/token).\n */\nexport function truncateIfTooLong(\n result: string[] | string,\n): string[] | string {\n if (Array.isArray(result)) {\n const totalChars = result.reduce((sum, item) => sum + item.length, 0);\n if (totalChars > TOOL_RESULT_TOKEN_LIMIT * 4) {\n const truncateAt = Math.floor(\n (result.length * TOOL_RESULT_TOKEN_LIMIT * 4) / totalChars,\n );\n return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE];\n }\n return result;\n }\n // string\n if (result.length > TOOL_RESULT_TOKEN_LIMIT * 4) {\n return (\n result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) +\n \"\\n\" +\n TRUNCATION_GUIDANCE\n );\n }\n return result;\n}\n\n/**\n * Validate and normalize a path.\n *\n * @param path - Path to validate\n * @returns Normalized path starting with / and ending with /\n * @throws Error if path is invalid\n */\nexport function validatePath(path: string | null | undefined): string {\n const pathStr = path || \"/\";\n if (!pathStr || pathStr.trim() === \"\") {\n throw new Error(\"Path cannot be empty\");\n }\n\n let normalized = pathStr.startsWith(\"/\") ? pathStr : \"/\" + pathStr;\n\n if (!normalized.endsWith(\"/\")) {\n normalized += \"/\";\n }\n\n return normalized;\n}\n\n/**\n * Search files dict for paths matching glob pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param path - Base path to search from\n * @returns Newline-separated file paths, sorted by modification time (most recent first).\n * Returns \"No files found\" if no matches.\n *\n * @example\n * ```typescript\n * const files = {\"/src/main.py\": FileData(...), \"/test.py\": FileData(...)};\n * globSearchFiles(files, \"*.py\", \"/\");\n * // Returns: \"/test.py\\n/src/main.py\" (sorted by modified_at)\n * ```\n */\nexport function globSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string = \"/\",\n): string {\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No files found\";\n }\n\n const filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n // Respect standard glob semantics:\n // - Patterns without path separators (e.g., \"*.py\") match only in the current\n // directory (non-recursive) relative to `path`.\n // - Use \"**\" explicitly for recursive matching.\n const effectivePattern = pattern;\n\n const matches: Array<[string, string]> = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n let relative = filePath.substring(normalizedPath.length);\n if (relative.startsWith(\"/\")) {\n relative = relative.substring(1);\n }\n if (!relative) {\n const parts = filePath.split(\"/\");\n relative = parts[parts.length - 1] || \"\";\n }\n\n if (\n micromatch.isMatch(relative, effectivePattern, {\n dot: true,\n nobrace: false,\n })\n ) {\n matches.push([filePath, fileData.modified_at]);\n }\n }\n\n matches.sort((a, b) => b[1].localeCompare(a[1])); // Sort by modified_at descending\n\n if (matches.length === 0) {\n return \"No files found\";\n }\n\n return matches.map(([fp]) => fp).join(\"\\n\");\n}\n\n/**\n * Format grep search results based on output mode.\n *\n * @param results - Dictionary mapping file paths to list of [line_num, line_content] tuples\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted string output\n */\nexport function formatGrepResults(\n results: Record<string, Array<[number, string]>>,\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (outputMode === \"files_with_matches\") {\n return Object.keys(results).sort().join(\"\\n\");\n }\n if (outputMode === \"count\") {\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n const count = results[filePath].length;\n lines.push(`${filePath}: ${count}`);\n }\n return lines.join(\"\\n\");\n }\n // content mode\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n lines.push(`${filePath}:`);\n for (const [lineNum, line] of results[filePath]) {\n lines.push(` ${lineNum}: ${line}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Search file contents for regex pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Regex pattern to search for\n * @param path - Base path to search from\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted search results. Returns \"No matches found\" if no results.\n *\n * @example\n * ```typescript\n * const files = {\"/file.py\": FileData({content: [\"import os\", \"print('hi')\"], ...})};\n * grepSearchFiles(files, \"import\", \"/\");\n * // Returns: \"/file.py\" (with output_mode=\"files_with_matches\")\n * ```\n */\nexport function grepSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n outputMode: \"files_with_matches\" | \"content\" | \"count\" = \"files_with_matches\",\n): string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No matches found\";\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n if (!results[filePath]) {\n results[filePath] = [];\n }\n results[filePath].push([lineNum, line]);\n }\n }\n }\n\n if (Object.keys(results).length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(results, outputMode);\n}\n\n// -------- Structured helpers for composition --------\n\n/**\n * Return structured grep matches from an in-memory files mapping.\n *\n * Returns a list of GrepMatch on success, or a string for invalid inputs\n * (e.g., invalid regex). We deliberately do not raise here to keep backends\n * non-throwing in tool contexts and preserve user-facing error messages.\n */\nexport function grepMatchesFromFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n): GrepMatch[] | string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return [];\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const matches: GrepMatch[] = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n matches.push({ path: filePath, line: lineNum, text: line });\n }\n }\n }\n\n return matches;\n}\n\n/**\n * Group structured matches into the legacy dict form used by formatters.\n */\nexport function buildGrepResultsDict(\n matches: GrepMatch[],\n): Record<string, Array<[number, string]>> {\n const grouped: Record<string, Array<[number, string]>> = {};\n for (const m of matches) {\n if (!grouped[m.path]) {\n grouped[m.path] = [];\n }\n grouped[m.path].push([m.line, m.text]);\n }\n return grouped;\n}\n\n/**\n * Format structured grep matches using existing formatting logic.\n */\nexport function formatGrepMatches(\n matches: GrepMatch[],\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (matches.length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(buildGrepResultsDict(matches), outputMode);\n}\n","/**\n * StateBackend: Store files in LangGraph agent state (ephemeral).\n */\n\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n StateAndStore,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n createFileData,\n fileDataToString,\n formatReadResponse,\n globSearchFiles,\n grepMatchesFromFiles,\n performStringReplacement,\n updateFileData,\n} from \"./utils.js\";\n\n/**\n * Backend that stores files in agent state (ephemeral).\n *\n * Uses LangGraph's state management and checkpointing. Files persist within\n * a conversation thread but not across threads. State is automatically\n * checkpointed after each agent step.\n *\n * Special handling: Since LangGraph state must be updated via Command objects\n * (not direct mutation), operations return filesUpdate in WriteResult/EditResult\n * for the middleware to apply via Command.\n */\nexport class StateBackend implements BackendProtocol {\n private stateAndStore: StateAndStore;\n\n constructor(stateAndStore: StateAndStore) {\n this.stateAndStore = stateAndStore;\n }\n\n /**\n * Get files from current state.\n */\n private getFiles(): Record<string, FileData> {\n return (\n ((this.stateAndStore.state as any).files as Record<string, FileData>) ||\n {}\n );\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n lsInfo(path: string): FileInfo[] {\n const files = this.getFiles();\n const infos: FileInfo[] = [];\n const subdirs = new Set<string>();\n\n // Normalize path to have trailing slash for proper prefix matching\n const normalizedPath = path.endsWith(\"/\") ? path : path + \"/\";\n\n for (const [k, fd] of Object.entries(files)) {\n // Check if file is in the specified directory or a subdirectory\n if (!k.startsWith(normalizedPath)) {\n continue;\n }\n\n // Get the relative path after the directory\n const relative = k.substring(normalizedPath.length);\n\n // If relative path contains '/', it's in a subdirectory\n if (relative.includes(\"/\")) {\n // Extract the immediate subdirectory name\n const subdirName = relative.split(\"/\")[0];\n subdirs.add(normalizedPath + subdirName + \"/\");\n continue;\n }\n\n // This is a file directly in the current directory\n const size = fd.content.join(\"\\n\").length;\n infos.push({\n path: k,\n is_dir: false,\n size: size,\n modified_at: fd.modified_at,\n });\n }\n\n // Add directories to the results\n for (const subdir of Array.from(subdirs).sort()) {\n infos.push({\n path: subdir,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n infos.sort((a, b) => a.path.localeCompare(b.path));\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n read(filePath: string, offset: number = 0, limit: number = 2000): string {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return `Error: File '${filePath}' not found`;\n }\n\n return formatReadResponse(fileData, offset, limit);\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n readRaw(filePath: string): FileData {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) throw new Error(`File '${filePath}' not found`);\n return fileData;\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult with filesUpdate to update LangGraph state.\n */\n write(filePath: string, content: string): WriteResult {\n const files = this.getFiles();\n\n if (filePath in files) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n const newFileData = createFileData(content);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult with filesUpdate and occurrences.\n */\n edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): EditResult {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const content = fileDataToString(fileData);\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n const newFileData = updateFileData(fileData, newContent);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n occurrences: occurrences,\n };\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): GrepMatch[] | string {\n const files = this.getFiles();\n return grepMatchesFromFiles(files, pattern, path, glob);\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n globInfo(pattern: string, path: string = \"/\"): FileInfo[] {\n const files = this.getFiles();\n const result = globSearchFiles(files, pattern, path);\n\n if (result === \"No files found\") {\n return [];\n }\n\n const paths = result.split(\"\\n\");\n const infos: FileInfo[] = [];\n for (const p of paths) {\n const fd = files[p];\n const size = fd ? fd.content.join(\"\\n\").length : 0;\n infos.push({\n path: p,\n is_dir: false,\n size: size,\n modified_at: fd?.modified_at || \"\",\n });\n }\n return infos;\n }\n\n /**\n * Upload multiple files.\n *\n * Note: Since LangGraph state must be updated via Command objects,\n * the caller must apply filesUpdate via Command after calling this method.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): FileUploadResponse[] & { filesUpdate?: Record<string, FileData> } {\n const responses: FileUploadResponse[] = [];\n const updates: Record<string, FileData> = {};\n\n for (const [path, content] of files) {\n try {\n const contentStr = new TextDecoder().decode(content);\n const fileData = createFileData(contentStr);\n updates[path] = fileData;\n responses.push({ path, error: null });\n } catch {\n responses.push({ path, error: \"invalid_path\" });\n }\n }\n\n // Attach filesUpdate for the caller to apply via Command\n const result = responses as FileUploadResponse[] & {\n filesUpdate?: Record<string, FileData>;\n };\n result.filesUpdate = updates;\n return result;\n }\n\n /**\n * Download multiple files.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n downloadFiles(paths: string[]): FileDownloadResponse[] {\n const files = this.getFiles();\n const responses: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n const fileData = files[path];\n if (!fileData) {\n responses.push({ path, content: null, error: \"file_not_found\" });\n continue;\n }\n\n const contentStr = fileDataToString(fileData);\n const content = new TextEncoder().encode(contentStr);\n responses.push({ path, content, error: null });\n }\n\n return responses;\n }\n}\n","/**\n * Middleware for providing filesystem tools to an agent.\n *\n * Provides ls, read_file, write_file, edit_file, glob, and grep tools with support for:\n * - Pluggable backends (StateBackend, StoreBackend, FilesystemBackend, CompositeBackend)\n * - Tool result eviction for large outputs\n */\n\nimport {\n createMiddleware,\n tool,\n ToolMessage,\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { Command, isCommand, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport { z } from \"zod/v4\";\nimport type {\n BackendProtocol,\n BackendFactory,\n FileData,\n StateAndStore,\n} from \"../backends/protocol.js\";\nimport { isSandboxBackend } from \"../backends/protocol.js\";\nimport { StateBackend } from \"../backends/state.js\";\nimport { sanitizeToolCallId } from \"../backends/utils.js\";\n\n/**\n * required for type inference\n */\nimport type * as _zodTypes from \"@langchain/core/utils/types\";\nimport type * as _zodMeta from \"@langchain/langgraph/zod\";\nimport type * as _messages from \"@langchain/core/messages\";\n\n/**\n * Zod v3 schema for FileData (re-export from backends)\n */\nconst FileDataSchema = z.object({\n content: z.array(z.string()),\n created_at: z.string(),\n modified_at: z.string(),\n});\n\nexport type { FileData };\n\n/**\n * Merge file updates with support for deletions.\n */\nfunction fileDataReducer(\n left: Record<string, FileData> | undefined,\n right: Record<string, FileData | null>,\n): Record<string, FileData> {\n if (left === undefined) {\n const result: Record<string, FileData> = {};\n for (const [key, value] of Object.entries(right)) {\n if (value !== null) {\n result[key] = value;\n }\n }\n return result;\n }\n\n const result = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (value === null) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Shared filesystem state schema.\n * Defined at module level to ensure the same object identity is used across all agents,\n * preventing \"Channel already exists with different type\" errors when multiple agents\n * use createFilesystemMiddleware.\n */\nconst FilesystemStateSchema = z.object({\n files: z\n .record(z.string(), FileDataSchema)\n .default({})\n .meta({\n reducer: {\n fn: fileDataReducer,\n schema: z.record(z.string(), FileDataSchema.nullable()),\n },\n }),\n});\n\n/**\n * Resolve backend from factory or instance.\n *\n * @param backend - Backend instance or factory function\n * @param stateAndStore - State and store container for backend initialization\n */\nfunction getBackend(\n backend: BackendProtocol | BackendFactory,\n stateAndStore: StateAndStore,\n): BackendProtocol {\n if (typeof backend === \"function\") {\n return backend(stateAndStore);\n }\n return backend;\n}\n\n// System prompts\nconst FILESYSTEM_SYSTEM_PROMPT = `You have access to a virtual filesystem. All file paths must start with a /.\n\n- ls: list files in a directory (requires absolute path)\n- read_file: read a file from the filesystem\n- write_file: write to a file in the filesystem\n- edit_file: edit a file in the filesystem\n- glob: find files matching a pattern (e.g., \"**/*.py\")\n- grep: search for text within files`;\n\n// Tool descriptions\nexport const LS_TOOL_DESCRIPTION = \"List files and directories in a directory\";\nexport const READ_FILE_TOOL_DESCRIPTION = \"Read the contents of a file\";\nexport const WRITE_FILE_TOOL_DESCRIPTION =\n \"Write content to a new file. Returns an error if the file already exists\";\nexport const EDIT_FILE_TOOL_DESCRIPTION =\n \"Edit a file by replacing a specific string with a new string\";\nexport const GLOB_TOOL_DESCRIPTION =\n \"Find files matching a glob pattern (e.g., '**/*.py' for all Python files)\";\nexport const GREP_TOOL_DESCRIPTION =\n \"Search for a regex pattern in files. Returns matching files and line numbers\";\nexport const EXECUTE_TOOL_DESCRIPTION = `Executes a given command in the sandbox environment with proper handling and security measures.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use the ls tool to verify the parent directory exists\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes\n - Commands run in an isolated sandbox environment\n - Returns combined stdout/stderr output with exit code\n\nUsage notes:\n - The command parameter is required\n - If the output is very large, it may be truncated\n - IMPORTANT: Avoid using search commands like find and grep. Use the grep, glob tools instead.\n - Avoid read tools like cat, head, tail - use read_file instead.\n - Use '&&' to chain dependent commands, ';' for independent commands\n - Try to use absolute paths to avoid cd`;\n\n// System prompt for execution capability\nexport const EXECUTION_SYSTEM_PROMPT = `## Execute Tool \\`execute\\`\n\nYou have access to an \\`execute\\` tool for running shell commands in a sandboxed environment.\nUse this tool to run commands, scripts, tests, builds, and other shell operations.\n\n- execute: run a shell command in the sandbox (returns output and exit code)`;\n\n/**\n * Create ls tool using backend.\n */\nfunction createLsTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const path = input.path || \"/\";\n const infos = await resolvedBackend.lsInfo(path);\n\n if (infos.length === 0) {\n return `No files found in ${path}`;\n }\n\n // Format output\n const lines: string[] = [];\n for (const info of infos) {\n if (info.is_dir) {\n lines.push(`${info.path} (directory)`);\n } else {\n const size = info.size ? ` (${info.size} bytes)` : \"\";\n lines.push(`${info.path}${size}`);\n }\n }\n return lines.join(\"\\n\");\n },\n {\n name: \"ls\",\n description: customDescription || LS_TOOL_DESCRIPTION,\n schema: z.object({\n path: z\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Directory path to list (default: /)\"),\n }),\n },\n );\n}\n\n/**\n * Create read_file tool using backend.\n */\nfunction createReadFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { file_path, offset = 0, limit = 2000 } = input;\n return await resolvedBackend.read(file_path, offset, limit);\n },\n {\n name: \"read_file\",\n description: customDescription || READ_FILE_TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to read\"),\n offset: z.coerce\n .number()\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from (0-indexed)\"),\n limit: z.coerce\n .number()\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n },\n );\n}\n\n/**\n * Create write_file tool using backend.\n */\nfunction createWriteFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { file_path, content } = input;\n const result = await resolvedBackend.write(file_path, content);\n\n if (result.error) {\n return result.error;\n }\n\n // If filesUpdate is present, return Command to update state\n const message = new ToolMessage({\n content: `Successfully wrote to '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"write_file\",\n metadata: result.metadata,\n });\n\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n return message;\n },\n {\n name: \"write_file\",\n description: customDescription || WRITE_FILE_TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to write\"),\n content: z.string().describe(\"Content to write to the file\"),\n }),\n },\n );\n}\n\n/**\n * Create edit_file tool using backend.\n */\nfunction createEditFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { file_path, old_string, new_string, replace_all = false } = input;\n const result = await resolvedBackend.edit(\n file_path,\n old_string,\n new_string,\n replace_all,\n );\n\n if (result.error) {\n return result.error;\n }\n\n const message = new ToolMessage({\n content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"edit_file\",\n metadata: result.metadata,\n });\n\n // If filesUpdate is present, return Command to update state\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n // External storage (filesUpdate is null)\n return message;\n },\n {\n name: \"edit_file\",\n description: customDescription || EDIT_FILE_TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to edit\"),\n old_string: z\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z.string().describe(\"String to replace with\"),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n },\n );\n}\n\n/**\n * Create glob tool using backend.\n */\nfunction createGlobTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { pattern, path = \"/\" } = input;\n const infos = await resolvedBackend.globInfo(pattern, path);\n\n if (infos.length === 0) {\n return `No files found matching pattern '${pattern}'`;\n }\n\n return infos.map((info) => info.path).join(\"\\n\");\n },\n {\n name: \"glob\",\n description: customDescription || GLOB_TOOL_DESCRIPTION,\n schema: z.object({\n pattern: z.string().describe(\"Glob pattern (e.g., '*.py', '**/*.ts')\"),\n path: z\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n }),\n },\n );\n}\n\n/**\n * Create grep tool using backend.\n */\nfunction createGrepTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { pattern, path = \"/\", glob = null } = input;\n const result = await resolvedBackend.grepRaw(pattern, path, glob);\n\n // If string, it's an error\n if (typeof result === \"string\") {\n return result;\n }\n\n if (result.length === 0) {\n return `No matches found for pattern '${pattern}'`;\n }\n\n // Format output: group by file\n const lines: string[] = [];\n let currentFile: string | null = null;\n for (const match of result) {\n if (match.path !== currentFile) {\n currentFile = match.path;\n lines.push(`\\n${currentFile}:`);\n }\n lines.push(` ${match.line}: ${match.text}`);\n }\n\n return lines.join(\"\\n\");\n },\n {\n name: \"grep\",\n description: customDescription || GREP_TOOL_DESCRIPTION,\n schema: z.object({\n pattern: z.string().describe(\"Regex pattern to search for\"),\n path: z\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n glob: z\n .string()\n .optional()\n .nullable()\n .describe(\"Optional glob pattern to filter files (e.g., '*.py')\"),\n }),\n },\n );\n}\n\n/**\n * Create execute tool using backend.\n */\nfunction createExecuteTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n\n // Runtime check - fail gracefully if not supported\n if (!isSandboxBackend(resolvedBackend)) {\n return (\n \"Error: Execution not available. This agent's backend \" +\n \"does not support command execution (SandboxBackendProtocol). \" +\n \"To use the execute tool, provide a backend that implements SandboxBackendProtocol.\"\n );\n }\n\n const result = await resolvedBackend.execute(input.command);\n\n // Format output for LLM consumption\n const parts = [result.output];\n\n if (result.exitCode !== null) {\n const status = result.exitCode === 0 ? \"succeeded\" : \"failed\";\n parts.push(`\\n[Command ${status} with exit code ${result.exitCode}]`);\n }\n\n if (result.truncated) {\n parts.push(\"\\n[Output was truncated due to size limits]\");\n }\n\n return parts.join(\"\");\n },\n {\n name: \"execute\",\n description: customDescription || EXECUTE_TOOL_DESCRIPTION,\n schema: z.object({\n command: z.string().describe(\"The shell command to execute\"),\n }),\n },\n );\n}\n\n/**\n * Options for creating filesystem middleware.\n */\nexport interface FilesystemMiddlewareOptions {\n /** Backend instance or factory (default: StateBackend) */\n backend?: BackendProtocol | BackendFactory;\n /** Optional custom system prompt override */\n systemPrompt?: string | null;\n /** Optional custom tool descriptions override */\n customToolDescriptions?: Record<string, string> | null;\n /** Optional token limit before evicting a tool result to the filesystem (default: 20000 tokens, ~80KB) */\n toolTokenLimitBeforeEvict?: number | null;\n}\n\n/**\n * Create filesystem middleware with all tools and features.\n */\nexport function createFilesystemMiddleware(\n options: FilesystemMiddlewareOptions = {},\n) {\n const {\n backend = (stateAndStore: StateAndStore) => new StateBackend(stateAndStore),\n systemPrompt: customSystemPrompt = null,\n customToolDescriptions = null,\n toolTokenLimitBeforeEvict = 20000,\n } = options;\n\n const baseSystemPrompt = customSystemPrompt || FILESYSTEM_SYSTEM_PROMPT;\n\n // All tools including execute (execute will be filtered at runtime if backend doesn't support it)\n const allTools = [\n createLsTool(backend, {\n customDescription: customToolDescriptions?.ls,\n }),\n createReadFileTool(backend, {\n customDescription: customToolDescriptions?.read_file,\n }),\n createWriteFileTool(backend, {\n customDescription: customToolDescriptions?.write_file,\n }),\n createEditFileTool(backend, {\n customDescription: customToolDescriptions?.edit_file,\n }),\n createGlobTool(backend, {\n customDescription: customToolDescriptions?.glob,\n }),\n createGrepTool(backend, {\n customDescription: customToolDescriptions?.grep,\n }),\n createExecuteTool(backend, {\n customDescription: customToolDescriptions?.execute,\n }),\n ];\n\n return createMiddleware({\n name: \"FilesystemMiddleware\",\n stateSchema: FilesystemStateSchema,\n tools: allTools,\n wrapModelCall: async (request, handler) => {\n // Check if backend supports execution\n const stateAndStore: StateAndStore = {\n state: request.state || {},\n // @ts-expect-error - request.config is incorrect typed\n store: request.config?.store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const supportsExecution = isSandboxBackend(resolvedBackend);\n\n // Filter tools based on backend capabilities\n let tools = request.tools;\n if (!supportsExecution) {\n tools = tools.filter((t: { name: string }) => t.name !== \"execute\");\n }\n\n // Build system prompt - add execution instructions if available\n let systemPrompt = baseSystemPrompt;\n if (supportsExecution) {\n systemPrompt = `${systemPrompt}\\n\\n${EXECUTION_SYSTEM_PROMPT}`;\n }\n\n // Combine with existing system prompt\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${currentSystemPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n\n return handler({ ...request, tools, systemPrompt: newSystemPrompt });\n },\n wrapToolCall: toolTokenLimitBeforeEvict\n ? async (request, handler) => {\n const result = await handler(request);\n\n async function processToolMessage(msg: ToolMessage) {\n if (\n typeof msg.content === \"string\" &&\n msg.content.length > toolTokenLimitBeforeEvict! * 4\n ) {\n // Build StateAndStore from request\n const stateAndStore: StateAndStore = {\n state: request.state || {},\n // @ts-expect-error - request.config is incorrect typed\n store: request.config?.store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const sanitizedId = sanitizeToolCallId(\n request.toolCall?.id || msg.tool_call_id,\n );\n const evictPath = `/large_tool_results/${sanitizedId}`;\n\n const writeResult = await resolvedBackend.write(\n evictPath,\n msg.content,\n );\n\n if (writeResult.error) {\n return { message: msg, filesUpdate: null };\n }\n\n const truncatedMessage = new ToolMessage({\n content: `Tool result too large (${Math.round(msg.content.length / 4)} tokens). Content saved to ${evictPath}`,\n tool_call_id: msg.tool_call_id,\n name: msg.name,\n });\n\n return {\n message: truncatedMessage,\n filesUpdate: writeResult.filesUpdate,\n };\n }\n return { message: msg, filesUpdate: null };\n }\n\n if (ToolMessage.isInstance(result)) {\n const processed = await processToolMessage(result);\n\n if (processed.filesUpdate) {\n return new Command({\n update: {\n files: processed.filesUpdate,\n messages: [processed.message],\n },\n });\n }\n\n return processed.message;\n }\n\n if (isCommand(result)) {\n const update = result.update as any;\n if (!update?.messages) {\n return result;\n }\n\n let hasLargeResults = false;\n const accumulatedFiles: Record<string, FileData> = {\n ...(update.files || {}),\n };\n const processedMessages: ToolMessage[] = [];\n\n for (const msg of update.messages) {\n if (ToolMessage.isInstance(msg)) {\n const processed = await processToolMessage(msg);\n processedMessages.push(processed.message);\n\n if (processed.filesUpdate) {\n hasLargeResults = true;\n Object.assign(accumulatedFiles, processed.filesUpdate);\n }\n } else {\n processedMessages.push(msg);\n }\n }\n\n if (hasLargeResults) {\n return new Command({\n update: {\n ...update,\n messages: processedMessages,\n files: accumulatedFiles,\n },\n });\n }\n }\n\n return result;\n }\n : undefined,\n });\n}\n","import { z } from \"zod/v3\";\nimport {\n createMiddleware,\n createAgent,\n AgentMiddleware,\n tool,\n ToolMessage,\n humanInTheLoopMiddleware,\n type InterruptOnConfig,\n type ReactAgent,\n StructuredTool,\n} from \"langchain\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport { HumanMessage } from \"@langchain/core/messages\";\n\nexport type { AgentMiddleware };\n\n// Constants\nconst DEFAULT_SUBAGENT_PROMPT =\n \"In order to complete the objective that the user asks of you, you have access to a number of standard tools.\";\n\n// State keys that should be excluded when passing state to subagents\n// NOTE: \"files\" is excluded to prevent concurrent subagents from writing to\n// the files channel simultaneously (which causes LastValue errors in LangGraph)\nconst EXCLUDED_STATE_KEYS = [\"messages\", \"todos\", \"jumpTo\", \"files\"] as const;\n\nconst DEFAULT_GENERAL_PURPOSE_DESCRIPTION =\n \"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.\";\n\n// Comprehensive task tool description from Python\nfunction getTaskToolDescription(subagentDescriptions: string[]): string {\n return `\nLaunch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.\n\nAvailable agent types and the tools they have access to:\n${subagentDescriptions.join(\"\\n\")}\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## Usage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.\n\n### Example usage of the general-purpose agent:\n\n<example_agent_descriptions>\n\"general-purpose\": use this agent for general purpose tasks, it has access to all tools as the main agent.\n</example_agent_descriptions>\n\n<example>\nUser: \"I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them.\"\nAssistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*\nAssistant: *Synthesizes the results of the three isolated research tasks and responds to the User*\n<commentary>\nResearch is a complex, multi-step task in it of itself.\nThe research of each individual player is not dependent on the research of the other players.\nThe assistant uses the task tool to break down the complex objective into three isolated tasks.\nEach research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.\nThis means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.\n</commentary>\n</example>\n\n<example>\nUser: \"Analyze a single large code repository for security vulnerabilities and generate a report.\"\nAssistant: *Launches a single \\`task\\` subagent for the repository analysis*\nAssistant: *Receives report and integrates results into final summary*\n<commentary>\nSubagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.\nIf the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.\n</commentary>\n</example>\n\n<example>\nUser: \"Schedule two meetings for me and prepare agendas for each.\"\nAssistant: *Calls the task tool in parallel to launch two \\`task\\` subagents (one per meeting) to prepare agendas*\nAssistant: *Returns final schedules and agendas*\n<commentary>\nTasks are simple individually, but subagents help silo agenda preparation.\nEach subagent only needs to worry about the agenda for one meeting.\n</commentary>\n</example>\n\n<example>\nUser: \"I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\"\nAssistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*\n<commentary>\nThe assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.\nIt is better to just complete the task directly and NOT use the \\`task\\`tool.\n</commentary>\n</example>\n\n### Example usage with custom agents:\n\n<example_agent_descriptions>\n\"content-reviewer\": use this agent after you are done creating significant content or documents\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n\"research-analyst\": use this agent to conduct thorough research on complex topics\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I'm going to use the Write tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince significant content was created and the task was completed, now use the content-reviewer agent to review the work\n</commentary>\nassistant: Now let me use the content-reviewer agent to review the code\nassistant: Uses the Task tool to launch with the content-reviewer agent\n</example>\n\n<example>\nuser: \"Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?\"\n<commentary>\nThis is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis\n</commentary>\nassistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.\nassistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take\n</example>\n\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the Task tool to launch with the greeting-responder agent\"\n</example>\n `.trim();\n}\n\nconst TASK_SYSTEM_PROMPT = `## \\`task\\` (subagent spawner)\n\nYou have access to a \\`task\\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.\n\nWhen to use the task tool:\n- When a task is complex and multi-step, and can be fully delegated in isolation\n- When a task is independent of other tasks and can run in parallel\n- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread\n- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)\n- When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)\n\nSubagent lifecycle:\n1. **Spawn** → Provide clear role, instructions, and expected output\n2. **Run** → The subagent completes the task autonomously\n3. **Return** → The subagent provides a single structured result\n4. **Reconcile** → Incorporate or synthesize the result into the main thread\n\nWhen NOT to use the task tool:\n- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)\n- If the task is trivial (a few tool calls or simple lookup)\n- If delegating does not reduce token usage, complexity, or context switching\n- If splitting would add latency without benefit\n\n## Important Task Tool Usage Notes to Remember\n- Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.\n- Remember to use the \\`task\\` tool to silo independent tasks within a multi-part objective.\n- You should use the \\`task\\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.`;\n\n/**\n * Type definitions for pre-compiled agents.\n */\nexport interface CompiledSubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The agent instance */\n runnable: ReactAgent | Runnable;\n}\n\n/**\n * Type definitions for subagents\n */\nexport interface SubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The system prompt to use for the agent */\n systemPrompt: string;\n /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */\n tools?: StructuredTool[];\n /** The model for the agent. Defaults to default_model */\n model?: LanguageModelLike | string;\n /** Additional middleware to append after default_middleware */\n middleware?: readonly AgentMiddleware[];\n /** The tool configs to use for the agent */\n interruptOn?: Record<string, boolean | InterruptOnConfig>;\n}\n\n/**\n * Filter state to exclude certain keys when passing to subagents\n */\nfunction filterStateForSubagent(\n state: Record<string, unknown>,\n): Record<string, unknown> {\n const filtered: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(state)) {\n if (!EXCLUDED_STATE_KEYS.includes(key as never)) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n\n/**\n * Create Command with filtered state update from subagent result\n */\nfunction returnCommandWithStateUpdate(\n result: Record<string, unknown>,\n toolCallId: string,\n): Command {\n const stateUpdate = filterStateForSubagent(result);\n const messages = result.messages as Array<{ content: string }>;\n const lastMessage = messages?.[messages.length - 1];\n\n return new Command({\n update: {\n ...stateUpdate,\n messages: [\n new ToolMessage({\n content: lastMessage?.content || \"Task completed\",\n tool_call_id: toolCallId,\n name: \"task\",\n }),\n ],\n },\n });\n}\n\n/**\n * Create subagent instances from specifications\n */\nfunction getSubagents(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n}): {\n agents: Record<string, ReactAgent | Runnable>;\n descriptions: string[];\n} {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n } = options;\n\n const defaultSubagentMiddleware = defaultMiddleware || [];\n const agents: Record<string, ReactAgent | Runnable> = {};\n const subagentDescriptions: string[] = [];\n\n // Create general-purpose agent if enabled\n if (generalPurposeAgent) {\n const generalPurposeMiddleware = [...defaultSubagentMiddleware];\n if (defaultInterruptOn) {\n generalPurposeMiddleware.push(\n humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn }),\n );\n }\n\n const generalPurposeSubagent = createAgent({\n model: defaultModel,\n systemPrompt: DEFAULT_SUBAGENT_PROMPT,\n tools: defaultTools as any,\n middleware: generalPurposeMiddleware,\n });\n\n agents[\"general-purpose\"] = generalPurposeSubagent;\n subagentDescriptions.push(\n `- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`,\n );\n }\n\n // Process custom subagents\n for (const agentParams of subagents) {\n subagentDescriptions.push(\n `- ${agentParams.name}: ${agentParams.description}`,\n );\n\n if (\"runnable\" in agentParams) {\n agents[agentParams.name] = agentParams.runnable;\n } else {\n const middleware = agentParams.middleware\n ? [...defaultSubagentMiddleware, ...agentParams.middleware]\n : [...defaultSubagentMiddleware];\n\n const interruptOn = agentParams.interruptOn || defaultInterruptOn;\n if (interruptOn)\n middleware.push(humanInTheLoopMiddleware({ interruptOn }));\n\n agents[agentParams.name] = createAgent({\n model: agentParams.model ?? defaultModel,\n systemPrompt: agentParams.systemPrompt,\n tools: agentParams.tools ?? defaultTools,\n middleware,\n });\n }\n }\n\n return { agents, descriptions: subagentDescriptions };\n}\n\n/**\n * Create the task tool for invoking subagents\n */\nfunction createTaskTool(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n taskDescription: string | null;\n}) {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n } = options;\n\n const { agents: subagentGraphs, descriptions: subagentDescriptions } =\n getSubagents({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n });\n\n const finalTaskDescription = taskDescription\n ? taskDescription\n : getTaskToolDescription(subagentDescriptions);\n\n return tool(\n async (\n input: { description: string; subagent_type: string },\n config,\n ): Promise<Command | string> => {\n const { description, subagent_type } = input;\n\n // Validate subagent type\n if (!(subagent_type in subagentGraphs)) {\n const allowedTypes = Object.keys(subagentGraphs)\n .map((k) => `\\`${k}\\``)\n .join(\", \");\n throw new Error(\n `Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`,\n );\n }\n\n const subagent = subagentGraphs[subagent_type];\n\n // Get current state and filter it for subagent\n const currentState = getCurrentTaskInput<Record<string, unknown>>();\n const subagentState = filterStateForSubagent(currentState);\n subagentState.messages = [new HumanMessage({ content: description })];\n\n // Invoke the subagent\n const result = (await subagent.invoke(subagentState, config)) as Record<\n string,\n unknown\n >;\n\n // Return command with filtered state update\n if (!config.toolCall?.id) {\n throw new Error(\"Tool call ID is required for subagent invocation\");\n }\n\n return returnCommandWithStateUpdate(result, config.toolCall.id);\n },\n {\n name: \"task\",\n description: finalTaskDescription,\n schema: z.object({\n description: z\n .string()\n .describe(\"The task to execute with the selected agent\"),\n subagent_type: z\n .string()\n .describe(\n `Name of the agent to use. Available: ${Object.keys(subagentGraphs).join(\", \")}`,\n ),\n }),\n },\n );\n}\n\n/**\n * Options for creating subagent middleware\n */\nexport interface SubAgentMiddlewareOptions {\n /** The model to use for subagents */\n defaultModel: LanguageModelLike | string;\n /** The tools to use for the default general-purpose subagent */\n defaultTools?: StructuredTool[];\n /** Default middleware to apply to all subagents */\n defaultMiddleware?: AgentMiddleware[] | null;\n /** The tool configs for the default general-purpose subagent */\n defaultInterruptOn?: Record<string, boolean | InterruptOnConfig> | null;\n /** A list of additional subagents to provide to the agent */\n subagents?: (SubAgent | CompiledSubAgent)[];\n /** Full system prompt override */\n systemPrompt?: string | null;\n /** Whether to include the general-purpose agent */\n generalPurposeAgent?: boolean;\n /** Custom description for the task tool */\n taskDescription?: string | null;\n}\n\n/**\n * Create subagent middleware with task tool\n */\nexport function createSubAgentMiddleware(options: SubAgentMiddlewareOptions) {\n const {\n defaultModel,\n defaultTools = [],\n defaultMiddleware = null,\n defaultInterruptOn = null,\n subagents = [],\n systemPrompt = TASK_SYSTEM_PROMPT,\n generalPurposeAgent = true,\n taskDescription = null,\n } = options;\n\n const taskTool = createTaskTool({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n });\n\n return createMiddleware({\n name: \"subAgentMiddleware\",\n tools: [taskTool],\n wrapModelCall: async (request, handler) => {\n if (systemPrompt !== null) {\n const currentPrompt = request.systemPrompt || \"\";\n const newPrompt = currentPrompt\n ? `${currentPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n\n return handler({\n ...request,\n systemPrompt: newPrompt,\n });\n }\n return handler(request);\n },\n });\n}\n","import {\n createMiddleware,\n ToolMessage,\n AIMessage,\n /**\n * required for type inference\n */\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { RemoveMessage } from \"@langchain/core/messages\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\n\n/**\n * Create middleware that patches dangling tool calls in the messages history.\n *\n * When an AI message contains tool_calls but subsequent messages don't include\n * the corresponding ToolMessage responses, this middleware adds synthetic\n * ToolMessages saying the tool call was cancelled.\n *\n * @returns AgentMiddleware that patches dangling tool calls\n *\n * @example\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { createPatchToolCallsMiddleware } from \"./middleware/patch_tool_calls\";\n *\n * const agent = createAgent({\n * model: \"claude-sonnet-4-5-20250929\",\n * middleware: [createPatchToolCallsMiddleware()],\n * });\n * ```\n */\nexport function createPatchToolCallsMiddleware() {\n return createMiddleware({\n name: \"patchToolCallsMiddleware\",\n beforeAgent: async (state) => {\n const messages = state.messages;\n\n if (!messages || messages.length === 0) {\n return;\n }\n\n const patchedMessages: any[] = [];\n\n // Iterate over the messages and add any dangling tool calls\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n patchedMessages.push(msg);\n\n // Check if this is an AI message with tool calls\n if (AIMessage.isInstance(msg) && msg.tool_calls != null) {\n for (const toolCall of msg.tool_calls) {\n // Look for a corresponding ToolMessage in the messages after this one\n const correspondingToolMsg = messages\n .slice(i)\n .find(\n (m: any) =>\n ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id,\n );\n\n if (!correspondingToolMsg) {\n // We have a dangling tool call which needs a ToolMessage\n const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`;\n patchedMessages.push(\n new ToolMessage({\n content: toolMsg,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n }),\n );\n }\n }\n }\n }\n\n // Return state update with RemoveMessage followed by patched messages\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n ...patchedMessages,\n ],\n };\n },\n });\n}\n","/**\n * StoreBackend: Adapter for LangGraph's BaseStore (persistent, cross-thread).\n */\n\nimport type { Item } from \"@langchain/langgraph\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n StateAndStore,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n createFileData,\n fileDataToString,\n formatReadResponse,\n globSearchFiles,\n grepMatchesFromFiles,\n performStringReplacement,\n updateFileData,\n} from \"./utils.js\";\n\n/**\n * Backend that stores files in LangGraph's BaseStore (persistent).\n *\n * Uses LangGraph's Store for persistent, cross-conversation storage.\n * Files are organized via namespaces and persist across all threads.\n *\n * The namespace can include an optional assistant_id for multi-agent isolation.\n */\nexport class StoreBackend implements BackendProtocol {\n private stateAndStore: StateAndStore;\n\n constructor(stateAndStore: StateAndStore) {\n this.stateAndStore = stateAndStore;\n }\n\n /**\n * Get the store instance.\n *\n * @returns BaseStore instance\n * @throws Error if no store is available\n */\n private getStore() {\n const store = this.stateAndStore.store;\n if (!store) {\n throw new Error(\"Store is required but not available in StateAndStore\");\n }\n return store;\n }\n\n /**\n * Get the namespace for store operations.\n *\n * If an assistant_id is available in stateAndStore, return\n * [assistant_id, \"filesystem\"] to provide per-assistant isolation.\n * Otherwise return [\"filesystem\"].\n */\n protected getNamespace(): string[] {\n const namespace = \"filesystem\";\n const assistantId = this.stateAndStore.assistantId;\n\n if (assistantId) {\n return [assistantId, namespace];\n }\n\n return [namespace];\n }\n\n /**\n * Convert a store Item to FileData format.\n *\n * @param storeItem - The store Item containing file data\n * @returns FileData object\n * @throws Error if required fields are missing or have incorrect types\n */\n private convertStoreItemToFileData(storeItem: Item): FileData {\n const value = storeItem.value as any;\n\n if (\n !value.content ||\n !Array.isArray(value.content) ||\n typeof value.created_at !== \"string\" ||\n typeof value.modified_at !== \"string\"\n ) {\n throw new Error(\n `Store item does not contain valid FileData fields. Got keys: ${Object.keys(value).join(\", \")}`,\n );\n }\n\n return {\n content: value.content,\n created_at: value.created_at,\n modified_at: value.modified_at,\n };\n }\n\n /**\n * Convert FileData to a value suitable for store.put().\n *\n * @param fileData - The FileData to convert\n * @returns Object with content, created_at, and modified_at fields\n */\n private convertFileDataToStoreValue(fileData: FileData): Record<string, any> {\n return {\n content: fileData.content,\n created_at: fileData.created_at,\n modified_at: fileData.modified_at,\n };\n }\n\n /**\n * Search store with automatic pagination to retrieve all results.\n *\n * @param store - The store to search\n * @param namespace - Hierarchical path prefix to search within\n * @param options - Optional query, filter, and page_size\n * @returns List of all items matching the search criteria\n */\n private async searchStorePaginated(\n store: any,\n namespace: string[],\n options: {\n query?: string;\n filter?: Record<string, any>;\n pageSize?: number;\n } = {},\n ): Promise<Item[]> {\n const { query, filter, pageSize = 100 } = options;\n const allItems: Item[] = [];\n let offset = 0;\n\n while (true) {\n const pageItems = await store.search(namespace, {\n query,\n filter,\n limit: pageSize,\n offset,\n });\n\n if (!pageItems || pageItems.length === 0) {\n break;\n }\n\n allItems.push(...pageItems);\n\n if (pageItems.length < pageSize) {\n break;\n }\n\n offset += pageSize;\n }\n\n return allItems;\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(path: string): Promise<FileInfo[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n\n // Retrieve all items and filter by path prefix locally to avoid\n // coupling to store-specific filter semantics\n const items = await this.searchStorePaginated(store, namespace);\n const infos: FileInfo[] = [];\n const subdirs = new Set<string>();\n\n // Normalize path to have trailing slash for proper prefix matching\n const normalizedPath = path.endsWith(\"/\") ? path : path + \"/\";\n\n for (const item of items) {\n const itemKey = String(item.key);\n\n // Check if file is in the specified directory or a subdirectory\n if (!itemKey.startsWith(normalizedPath)) {\n continue;\n }\n\n // Get the relative path after the directory\n const relative = itemKey.substring(normalizedPath.length);\n\n // If relative path contains '/', it's in a subdirectory\n if (relative.includes(\"/\")) {\n // Extract the immediate subdirectory name\n const subdirName = relative.split(\"/\")[0];\n subdirs.add(normalizedPath + subdirName + \"/\");\n continue;\n }\n\n // This is a file directly in the current directory\n try {\n const fd = this.convertStoreItemToFileData(item);\n const size = fd.content.join(\"\\n\").length;\n infos.push({\n path: itemKey,\n is_dir: false,\n size: size,\n modified_at: fd.modified_at,\n });\n } catch {\n // Skip invalid items\n continue;\n }\n }\n\n // Add directories to the results\n for (const subdir of Array.from(subdirs).sort()) {\n infos.push({\n path: subdir,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n infos.sort((a, b) => a.path.localeCompare(b.path));\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 2000,\n ): Promise<string> {\n try {\n const fileData = await this.readRaw(filePath);\n return formatReadResponse(fileData, offset, limit);\n } catch (e: any) {\n return `Error: ${e.message}`;\n }\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const item = await store.get(namespace, filePath);\n\n if (!item) throw new Error(`File '${filePath}' not found`);\n return this.convertStoreItemToFileData(item);\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n\n // Check if file exists\n const existing = await store.get(namespace, filePath);\n if (existing) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n // Create new file\n const fileData = createFileData(content);\n const storeValue = this.convertFileDataToStoreValue(fileData);\n await store.put(namespace, filePath, storeValue);\n return { path: filePath, filesUpdate: null };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n\n // Get existing file\n const item = await store.get(namespace, filePath);\n if (!item) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n try {\n const fileData = this.convertStoreItemToFileData(item);\n const content = fileDataToString(fileData);\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n const newFileData = updateFileData(fileData, newContent);\n\n // Update file in store\n const storeValue = this.convertFileDataToStoreValue(newFileData);\n await store.put(namespace, filePath, storeValue);\n return { path: filePath, filesUpdate: null, occurrences: occurrences };\n } catch (e: any) {\n return { error: `Error: ${e.message}` };\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const items = await this.searchStorePaginated(store, namespace);\n\n const files: Record<string, FileData> = {};\n for (const item of items) {\n try {\n files[item.key] = this.convertStoreItemToFileData(item);\n } catch {\n // Skip invalid items\n continue;\n }\n }\n\n return grepMatchesFromFiles(files, pattern, path, glob);\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(pattern: string, path: string = \"/\"): Promise<FileInfo[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const items = await this.searchStorePaginated(store, namespace);\n\n const files: Record<string, FileData> = {};\n for (const item of items) {\n try {\n files[item.key] = this.convertStoreItemToFileData(item);\n } catch {\n // Skip invalid items\n continue;\n }\n }\n\n const result = globSearchFiles(files, pattern, path);\n if (result === \"No files found\") {\n return [];\n }\n\n const paths = result.split(\"\\n\");\n const infos: FileInfo[] = [];\n for (const p of paths) {\n const fd = files[p];\n const size = fd ? fd.content.join(\"\\n\").length : 0;\n infos.push({\n path: p,\n is_dir: false,\n size: size,\n modified_at: fd?.modified_at || \"\",\n });\n }\n return infos;\n }\n\n /**\n * Upload multiple files.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const responses: FileUploadResponse[] = [];\n\n for (const [path, content] of files) {\n try {\n const contentStr = new TextDecoder().decode(content);\n const fileData = createFileData(contentStr);\n const storeValue = this.convertFileDataToStoreValue(fileData);\n await store.put(namespace, path, storeValue);\n responses.push({ path, error: null });\n } catch {\n responses.push({ path, error: \"invalid_path\" });\n }\n }\n\n return responses;\n }\n\n /**\n * Download multiple files.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const responses: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n try {\n const item = await store.get(namespace, path);\n if (!item) {\n responses.push({ path, content: null, error: \"file_not_found\" });\n continue;\n }\n\n const fileData = this.convertStoreItemToFileData(item);\n const contentStr = fileDataToString(fileData);\n const content = new TextEncoder().encode(contentStr);\n responses.push({ path, content, error: null });\n } catch {\n responses.push({ path, content: null, error: \"file_not_found\" });\n }\n }\n\n return responses;\n }\n}\n","/**\n * FilesystemBackend: Read and write files directly from the filesystem.\n *\n * Security and search upgrades:\n * - Secure path resolution with root containment when in virtual_mode (sandboxed to cwd)\n * - Prevent symlink-following on file I/O using O_NOFOLLOW when available\n * - Ripgrep-powered grep with JSON parsing, plus regex fallback\n * and optional glob include filtering, while preserving virtual path behavior\n */\n\nimport fs from \"node:fs/promises\";\nimport fsSync from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\n\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n checkEmptyContent,\n formatContentWithLineNumbers,\n performStringReplacement,\n} from \"./utils.js\";\n\nconst SUPPORTS_NOFOLLOW = fsSync.constants.O_NOFOLLOW !== undefined;\n\n/**\n * Backend that reads and writes files directly from the filesystem.\n *\n * Files are accessed using their actual filesystem paths. Relative paths are\n * resolved relative to the current working directory. Content is read/written\n * as plain text, and metadata (timestamps) are derived from filesystem stats.\n */\nexport class FilesystemBackend implements BackendProtocol {\n private cwd: string;\n private virtualMode: boolean;\n private maxFileSizeBytes: number;\n\n constructor(\n options: {\n rootDir?: string;\n virtualMode?: boolean;\n maxFileSizeMb?: number;\n } = {},\n ) {\n const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options;\n this.cwd = rootDir ? path.resolve(rootDir) : process.cwd();\n this.virtualMode = virtualMode;\n this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024;\n }\n\n /**\n * Resolve a file path with security checks.\n *\n * When virtualMode=true, treat incoming paths as virtual absolute paths under\n * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.\n * When virtualMode=false, preserve legacy behavior: absolute paths are allowed\n * as-is; relative paths resolve under cwd.\n *\n * @param key - File path (absolute, relative, or virtual when virtualMode=true)\n * @returns Resolved absolute path string\n * @throws Error if path traversal detected or path outside root\n */\n private resolvePath(key: string): string {\n if (this.virtualMode) {\n const vpath = key.startsWith(\"/\") ? key : \"/\" + key;\n if (vpath.includes(\"..\") || vpath.startsWith(\"~\")) {\n throw new Error(\"Path traversal not allowed\");\n }\n const full = path.resolve(this.cwd, vpath.substring(1));\n const relative = path.relative(this.cwd, full);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Path: ${full} outside root directory: ${this.cwd}`);\n }\n return full;\n }\n\n if (path.isAbsolute(key)) {\n return key;\n }\n return path.resolve(this.cwd, key);\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param dirPath - Absolute directory path to list files from\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(dirPath: string): Promise<FileInfo[]> {\n try {\n const resolvedPath = this.resolvePath(dirPath);\n const stat = await fs.stat(resolvedPath);\n\n if (!stat.isDirectory()) {\n return [];\n }\n\n const entries = await fs.readdir(resolvedPath, { withFileTypes: true });\n const results: FileInfo[] = [];\n\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n\n for (const entry of entries) {\n const fullPath = path.join(resolvedPath, entry.name);\n\n try {\n const entryStat = await fs.stat(fullPath);\n const isFile = entryStat.isFile();\n const isDir = entryStat.isDirectory();\n\n if (!this.virtualMode) {\n // Non-virtual mode: use absolute paths\n if (isFile) {\n results.push({\n path: fullPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: fullPath + path.sep,\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n } else {\n let relativePath: string;\n if (fullPath.startsWith(cwdStr)) {\n relativePath = fullPath.substring(cwdStr.length);\n } else if (fullPath.startsWith(this.cwd)) {\n relativePath = fullPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = fullPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virtPath = \"/\" + relativePath;\n\n if (isFile) {\n results.push({\n path: virtPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: virtPath + \"/\",\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n }\n } catch {\n // Skip entries we can't stat\n continue;\n }\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n } catch {\n return [];\n }\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute or relative file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 2000,\n ): Promise<string> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW,\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return `Error: Symlinks are not allowed: ${filePath}`;\n }\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n } catch (e: any) {\n return `Error reading file '${filePath}': ${e.message}`;\n }\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n let stat: fsSync.Stats;\n\n if (SUPPORTS_NOFOLLOW) {\n stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) throw new Error(`File '${filePath}' not found`);\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW,\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n throw new Error(`Symlinks are not allowed: ${filePath}`);\n }\n if (!stat.isFile()) throw new Error(`File '${filePath}' not found`);\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n return {\n content: content.split(\"\\n\"),\n created_at: stat.ctime.toISOString(),\n modified_at: stat.mtime.toISOString(),\n };\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n try {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return {\n error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`,\n };\n }\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n } catch {\n // File doesn't exist, good to proceed\n }\n\n await fs.mkdir(path.dirname(resolvedPath), { recursive: true });\n\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_CREAT |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags, 0o644);\n try {\n await fd.writeFile(content, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, content, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null };\n } catch (e: any) {\n return { error: `Error writing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW,\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return { error: `Error: Symlinks are not allowed: ${filePath}` };\n }\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n\n // Write securely\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags);\n try {\n await fd.writeFile(newContent, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, newContent, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null, occurrences: occurrences };\n } catch (e: any) {\n return { error: `Error editing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n dirPath: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n // Validate regex\n try {\n new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n // Resolve base path\n let baseFull: string;\n try {\n baseFull = this.resolvePath(dirPath || \".\");\n } catch {\n return [];\n }\n\n try {\n await fs.stat(baseFull);\n } catch {\n return [];\n }\n\n // Try ripgrep first, fallback to regex search\n let results = await this.ripgrepSearch(pattern, baseFull, glob);\n if (results === null) {\n results = await this.pythonSearch(pattern, baseFull, glob);\n }\n\n const matches: GrepMatch[] = [];\n for (const [fpath, items] of Object.entries(results)) {\n for (const [lineNum, lineText] of items) {\n matches.push({ path: fpath, line: lineNum, text: lineText });\n }\n }\n return matches;\n }\n\n /**\n * Try to use ripgrep for fast searching.\n * Returns null if ripgrep is not available or fails.\n */\n private async ripgrepSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null,\n ): Promise<Record<string, Array<[number, string]>> | null> {\n return new Promise((resolve) => {\n const args = [\"--json\"];\n if (includeGlob) {\n args.push(\"--glob\", includeGlob);\n }\n args.push(\"--\", pattern, baseFull);\n\n const proc = spawn(\"rg\", args, { timeout: 30000 });\n const results: Record<string, Array<[number, string]>> = {};\n let output = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n output += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n if (code !== 0 && code !== 1) {\n // Error (code 1 means no matches, which is ok)\n resolve(null);\n return;\n }\n\n for (const line of output.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const data = JSON.parse(line);\n if (data.type !== \"match\") continue;\n\n const pdata = data.data || {};\n const ftext = pdata.path?.text;\n if (!ftext) continue;\n\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const resolved = path.resolve(ftext);\n const relative = path.relative(this.cwd, resolved);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = ftext;\n }\n\n const ln = pdata.line_number;\n const lt = pdata.lines?.text?.replace(/\\n$/, \"\") || \"\";\n if (ln === undefined) continue;\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([ln, lt]);\n } catch {\n // Skip invalid JSON\n continue;\n }\n }\n\n resolve(results);\n });\n\n proc.on(\"error\", () => {\n resolve(null);\n });\n });\n }\n\n /**\n * Fallback regex search implementation.\n */\n private async pythonSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null,\n ): Promise<Record<string, Array<[number, string]>>> {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch {\n return {};\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n const stat = await fs.stat(baseFull);\n const root = stat.isDirectory() ? baseFull : path.dirname(baseFull);\n\n // Use fast-glob to recursively find all files\n const files = await fg(\"**/*\", {\n cwd: root,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const fp of files) {\n try {\n // Filter by glob if provided\n if (\n includeGlob &&\n !micromatch.isMatch(path.basename(fp), includeGlob)\n ) {\n continue;\n }\n\n // Check file size\n const stat = await fs.stat(fp);\n if (stat.size > this.maxFileSizeBytes) {\n continue;\n }\n\n // Read and search\n const content = await fs.readFile(fp, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (regex.test(line)) {\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const relative = path.relative(this.cwd, fp);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = fp;\n }\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([i + 1, line]);\n }\n }\n } catch {\n // Skip files we can't read\n continue;\n }\n }\n\n return results;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(\n pattern: string,\n searchPath: string = \"/\",\n ): Promise<FileInfo[]> {\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.substring(1);\n }\n\n const resolvedSearchPath =\n searchPath === \"/\" ? this.cwd : this.resolvePath(searchPath);\n\n try {\n const stat = await fs.stat(resolvedSearchPath);\n if (!stat.isDirectory()) {\n return [];\n }\n } catch {\n return [];\n }\n\n const results: FileInfo[] = [];\n\n try {\n // Use fast-glob for pattern matching\n const matches = await fg(pattern, {\n cwd: resolvedSearchPath,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const matchedPath of matches) {\n try {\n const stat = await fs.stat(matchedPath);\n if (!stat.isFile()) continue;\n\n // Normalize fast-glob paths to platform separators\n // fast-glob returns forward slashes on all platforms, but we need\n // platform-native separators for path comparisons on Windows\n const normalizedPath = matchedPath.split(\"/\").join(path.sep);\n\n if (!this.virtualMode) {\n results.push({\n path: normalizedPath,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n } else {\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n let relativePath: string;\n\n if (normalizedPath.startsWith(cwdStr)) {\n relativePath = normalizedPath.substring(cwdStr.length);\n } else if (normalizedPath.startsWith(this.cwd)) {\n relativePath = normalizedPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = normalizedPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virt = \"/\" + relativePath;\n results.push({\n path: virt,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n }\n } catch {\n // Skip files we can't stat\n continue;\n }\n }\n } catch {\n // Ignore glob errors\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n\n /**\n * Upload multiple files to the filesystem.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const responses: FileUploadResponse[] = [];\n\n for (const [filePath, content] of files) {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n // Ensure parent directory exists\n await fs.mkdir(path.dirname(resolvedPath), { recursive: true });\n\n // Write file\n await fs.writeFile(resolvedPath, content);\n responses.push({ path: filePath, error: null });\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n responses.push({ path: filePath, error: \"file_not_found\" });\n } else if (e.code === \"EACCES\") {\n responses.push({ path: filePath, error: \"permission_denied\" });\n } else if (e.code === \"EISDIR\") {\n responses.push({ path: filePath, error: \"is_directory\" });\n } else {\n responses.push({ path: filePath, error: \"invalid_path\" });\n }\n }\n }\n\n return responses;\n }\n\n /**\n * Download multiple files from the filesystem.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const responses: FileDownloadResponse[] = [];\n\n for (const filePath of paths) {\n try {\n const resolvedPath = this.resolvePath(filePath);\n const content = await fs.readFile(resolvedPath);\n responses.push({ path: filePath, content, error: null });\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n responses.push({\n path: filePath,\n content: null,\n error: \"file_not_found\",\n });\n } else if (e.code === \"EACCES\") {\n responses.push({\n path: filePath,\n content: null,\n error: \"permission_denied\",\n });\n } else if (e.code === \"EISDIR\") {\n responses.push({\n path: filePath,\n content: null,\n error: \"is_directory\",\n });\n } else {\n responses.push({\n path: filePath,\n content: null,\n error: \"invalid_path\",\n });\n }\n }\n }\n\n return responses;\n }\n}\n","/**\n * CompositeBackend: Route operations to different backends based on path prefix.\n */\n\nimport type {\n BackendProtocol,\n EditResult,\n ExecuteResponse,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport { isSandboxBackend } from \"./protocol.js\";\n\n/**\n * Backend that routes file operations to different backends based on path prefix.\n *\n * This enables hybrid storage strategies like:\n * - `/memories/` → StoreBackend (persistent, cross-thread)\n * - Everything else → StateBackend (ephemeral, per-thread)\n *\n * The CompositeBackend handles path prefix stripping/re-adding transparently.\n */\nexport class CompositeBackend implements BackendProtocol {\n private default: BackendProtocol;\n private routes: Record<string, BackendProtocol>;\n private sortedRoutes: Array<[string, BackendProtocol]>;\n\n constructor(\n defaultBackend: BackendProtocol,\n routes: Record<string, BackendProtocol>,\n ) {\n this.default = defaultBackend;\n this.routes = routes;\n\n // Sort routes by length (longest first) for correct prefix matching\n this.sortedRoutes = Object.entries(routes).sort(\n (a, b) => b[0].length - a[0].length,\n );\n }\n\n /**\n * Determine which backend handles this key and strip prefix.\n *\n * @param key - Original file path\n * @returns Tuple of [backend, stripped_key] where stripped_key has the route\n * prefix removed (but keeps leading slash).\n */\n private getBackendAndKey(key: string): [BackendProtocol, string] {\n // Check routes in order of length (longest first)\n for (const [prefix, backend] of this.sortedRoutes) {\n if (key.startsWith(prefix)) {\n // Strip full prefix and ensure a leading slash remains\n // e.g., \"/memories/notes.txt\" → \"/notes.txt\"; \"/memories/\" → \"/\"\n const suffix = key.substring(prefix.length);\n const strippedKey = suffix ? \"/\" + suffix : \"/\";\n return [backend, strippedKey];\n }\n }\n\n return [this.default, key];\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects with route prefixes added, for files and directories\n * directly in the directory. Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(path: string): Promise<FileInfo[]> {\n // Check if path matches a specific route\n for (const [routePrefix, backend] of this.sortedRoutes) {\n if (path.startsWith(routePrefix.replace(/\\/$/, \"\"))) {\n // Query only the matching routed backend\n const suffix = path.substring(routePrefix.length);\n const searchPath = suffix ? \"/\" + suffix : \"/\";\n const infos = await backend.lsInfo(searchPath);\n\n // Add route prefix back to paths\n const prefixed: FileInfo[] = [];\n for (const fi of infos) {\n prefixed.push({\n ...fi,\n path: routePrefix.slice(0, -1) + fi.path,\n });\n }\n return prefixed;\n }\n }\n\n // At root, aggregate default and all routed backends\n if (path === \"/\") {\n const results: FileInfo[] = [];\n const defaultInfos = await this.default.lsInfo(path);\n results.push(...defaultInfos);\n\n // Add the route itself as a directory (e.g., /memories/)\n for (const [routePrefix] of this.sortedRoutes) {\n results.push({\n path: routePrefix,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n\n // Path doesn't match a route: query only default backend\n return await this.default.lsInfo(path);\n }\n\n /**\n * Read file content, routing to appropriate backend.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 2000,\n ): Promise<string> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.read(strippedKey, offset, limit);\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.readRaw(strippedKey);\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n // If path targets a specific route, search only that backend\n for (const [routePrefix, backend] of this.sortedRoutes) {\n if (path.startsWith(routePrefix.replace(/\\/$/, \"\"))) {\n const searchPath = path.substring(routePrefix.length - 1);\n const raw = await backend.grepRaw(pattern, searchPath || \"/\", glob);\n\n if (typeof raw === \"string\") {\n return raw;\n }\n\n // Add route prefix back\n return raw.map((m) => ({\n ...m,\n path: routePrefix.slice(0, -1) + m.path,\n }));\n }\n }\n\n // Otherwise, search default and all routed backends and merge\n const allMatches: GrepMatch[] = [];\n const rawDefault = await this.default.grepRaw(pattern, path, glob);\n\n if (typeof rawDefault === \"string\") {\n return rawDefault;\n }\n\n allMatches.push(...rawDefault);\n\n // Search all routes\n for (const [routePrefix, backend] of Object.entries(this.routes)) {\n const raw = await backend.grepRaw(pattern, \"/\", glob);\n\n if (typeof raw === \"string\") {\n return raw;\n }\n\n // Add route prefix back\n allMatches.push(\n ...raw.map((m) => ({\n ...m,\n path: routePrefix.slice(0, -1) + m.path,\n })),\n );\n }\n\n return allMatches;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(pattern: string, path: string = \"/\"): Promise<FileInfo[]> {\n const results: FileInfo[] = [];\n\n // Route based on path, not pattern\n for (const [routePrefix, backend] of this.sortedRoutes) {\n if (path.startsWith(routePrefix.replace(/\\/$/, \"\"))) {\n const searchPath = path.substring(routePrefix.length - 1);\n const infos = await backend.globInfo(pattern, searchPath || \"/\");\n\n // Add route prefix back\n return infos.map((fi) => ({\n ...fi,\n path: routePrefix.slice(0, -1) + fi.path,\n }));\n }\n }\n\n // Path doesn't match any specific route - search default backend AND all routed backends\n const defaultInfos = await this.default.globInfo(pattern, path);\n results.push(...defaultInfos);\n\n for (const [routePrefix, backend] of Object.entries(this.routes)) {\n const infos = await backend.globInfo(pattern, \"/\");\n results.push(\n ...infos.map((fi) => ({\n ...fi,\n path: routePrefix.slice(0, -1) + fi.path,\n })),\n );\n }\n\n // Deterministic ordering\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n\n /**\n * Create a new file, routing to appropriate backend.\n *\n * @param filePath - Absolute file path\n * @param content - File content as string\n * @returns WriteResult with path or error\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.write(strippedKey, content);\n }\n\n /**\n * Edit a file, routing to appropriate backend.\n *\n * @param filePath - Absolute file path\n * @param oldString - String to find and replace\n * @param newString - Replacement string\n * @param replaceAll - If true, replace all occurrences\n * @returns EditResult with path, occurrences, or error\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.edit(strippedKey, oldString, newString, replaceAll);\n }\n\n /**\n * Execute a command via the default backend.\n * Execution is not path-specific, so it always delegates to the default backend.\n *\n * @param command - Full shell command string to execute\n * @returns ExecuteResponse with combined output, exit code, and truncation flag\n * @throws Error if the default backend doesn't support command execution\n */\n execute(command: string): Promise<ExecuteResponse> {\n if (!isSandboxBackend(this.default)) {\n throw new Error(\n \"Default backend doesn't support command execution (SandboxBackendProtocol). \" +\n \"To enable execution, provide a default backend that implements SandboxBackendProtocol.\",\n );\n }\n return Promise.resolve(this.default.execute(command));\n }\n\n /**\n * Upload multiple files, batching by backend for efficiency.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const results: Array<FileUploadResponse | null> = new Array(\n files.length,\n ).fill(null);\n const batchesByBackend = new Map<\n BackendProtocol,\n Array<{ idx: number; path: string; content: Uint8Array }>\n >();\n\n for (let idx = 0; idx < files.length; idx++) {\n const [path, content] = files[idx];\n const [backend, strippedPath] = this.getBackendAndKey(path);\n\n if (!batchesByBackend.has(backend)) {\n batchesByBackend.set(backend, []);\n }\n batchesByBackend.get(backend)!.push({ idx, path: strippedPath, content });\n }\n\n for (const [backend, batch] of batchesByBackend) {\n const batchFiles = batch.map(\n (b) => [b.path, b.content] as [string, Uint8Array],\n );\n const batchResponses = await backend.uploadFiles(batchFiles);\n\n for (let i = 0; i < batch.length; i++) {\n const originalIdx = batch[i].idx;\n results[originalIdx] = {\n path: files[originalIdx][0], // Original path\n error: batchResponses[i]?.error ?? null,\n };\n }\n }\n\n return results as FileUploadResponse[];\n }\n\n /**\n * Download multiple files, batching by backend for efficiency.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const results: Array<FileDownloadResponse | null> = new Array(\n paths.length,\n ).fill(null);\n const batchesByBackend = new Map<\n BackendProtocol,\n Array<{ idx: number; path: string }>\n >();\n\n for (let idx = 0; idx < paths.length; idx++) {\n const path = paths[idx];\n const [backend, strippedPath] = this.getBackendAndKey(path);\n\n if (!batchesByBackend.has(backend)) {\n batchesByBackend.set(backend, []);\n }\n batchesByBackend.get(backend)!.push({ idx, path: strippedPath });\n }\n\n for (const [backend, batch] of batchesByBackend) {\n const batchPaths = batch.map((b) => b.path);\n const batchResponses = await backend.downloadFiles(batchPaths);\n\n for (let i = 0; i < batch.length; i++) {\n const originalIdx = batch[i].idx;\n results[originalIdx] = {\n path: paths[originalIdx], // Original path\n content: batchResponses[i]?.content ?? null,\n error: batchResponses[i]?.error ?? null,\n };\n }\n }\n\n return results as FileDownloadResponse[];\n }\n}\n","/**\n * BaseSandbox: Abstract base class for sandbox backends with command execution.\n *\n * This class provides default implementations for all SandboxBackendProtocol\n * methods using shell commands executed via execute(). Concrete implementations\n * only need to implement the execute() method.\n *\n * Requires Node.js 20+ on the sandbox host.\n */\n\nimport type {\n EditResult,\n ExecuteResponse,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n MaybePromise,\n SandboxBackendProtocol,\n WriteResult,\n} from \"./protocol.js\";\n\n/**\n * Node.js command template for glob operations.\n * Uses web-standard atob() for base64 decoding.\n */\nfunction buildGlobCommand(searchPath: string, pattern: string): string {\n const pathB64 = btoa(searchPath);\n const patternB64 = btoa(pattern);\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst searchPath = atob('${pathB64}');\nconst pattern = atob('${patternB64}');\n\nfunction globMatch(relativePath, pattern) {\n const regexPattern = pattern\n .replace(/\\\\*\\\\*/g, '<<<GLOBSTAR>>>')\n .replace(/\\\\*/g, '[^/]*')\n .replace(/\\\\?/g, '.')\n .replace(/<<<GLOBSTAR>>>/g, '.*');\n return new RegExp('^' + regexPattern + '$').test(relativePath);\n}\n\nfunction walkDir(dir, baseDir, results) {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = path.relative(baseDir, fullPath);\n if (entry.isDirectory()) {\n walkDir(fullPath, baseDir, results);\n } else if (globMatch(relativePath, pattern)) {\n const stat = fs.statSync(fullPath);\n console.log(JSON.stringify({\n path: relativePath,\n size: stat.size,\n mtime: stat.mtimeMs,\n isDir: false\n }));\n }\n }\n } catch (e) {\n // Silent failure for non-existent paths\n }\n}\n\ntry {\n process.chdir(searchPath);\n walkDir('.', '.', []);\n} catch (e) {\n // Silent failure for non-existent paths\n}\n\"`;\n}\n\n/**\n * Node.js command template for listing directory contents.\n */\nfunction buildLsCommand(dirPath: string): string {\n const pathB64 = btoa(dirPath);\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst dirPath = atob('${pathB64}');\n\ntry {\n const entries = fs.readdirSync(dirPath, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n const stat = fs.statSync(fullPath);\n console.log(JSON.stringify({\n path: entry.isDirectory() ? fullPath + '/' : fullPath,\n size: stat.size,\n mtime: stat.mtimeMs,\n isDir: entry.isDirectory()\n }));\n }\n} catch (e) {\n console.error('Error: ' + e.message);\n process.exit(1);\n}\n\"`;\n}\n\n/**\n * Node.js command template for reading files.\n */\nfunction buildReadCommand(\n filePath: string,\n offset: number,\n limit: number,\n): string {\n const pathB64 = btoa(filePath);\n // Coerce offset and limit to safe non-negative integers before embedding in the shell command.\n const safeOffset =\n Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;\n const safeLimit =\n Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER\n ? Math.floor(limit)\n : 0;\n\n return `node -e \"\nconst fs = require('fs');\n\nconst filePath = atob('${pathB64}');\nconst offset = ${safeOffset};\nconst limit = ${safeLimit};\n\nif (!fs.existsSync(filePath)) {\n console.log('Error: File not found');\n process.exit(1);\n}\n\nconst stat = fs.statSync(filePath);\nif (stat.size === 0) {\n console.log('System reminder: File exists but has empty contents');\n process.exit(0);\n}\n\nconst content = fs.readFileSync(filePath, 'utf-8');\nconst lines = content.split('\\\\n');\nconst selected = lines.slice(offset, offset + limit);\n\nfor (let i = 0; i < selected.length; i++) {\n const lineNum = offset + i + 1;\n console.log(String(lineNum).padStart(6) + '\\\\t' + selected[i]);\n}\n\"`;\n}\n\n/**\n * Node.js command template for writing files.\n */\nfunction buildWriteCommand(filePath: string, content: string): string {\n const pathB64 = btoa(filePath);\n const contentB64 = btoa(content);\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst filePath = atob('${pathB64}');\nconst content = atob('${contentB64}');\n\nif (fs.existsSync(filePath)) {\n console.error('Error: File already exists');\n process.exit(1);\n}\n\nconst parentDir = path.dirname(filePath) || '.';\nfs.mkdirSync(parentDir, { recursive: true });\n\nfs.writeFileSync(filePath, content, 'utf-8');\nconsole.log('OK');\n\"`;\n}\n\n/**\n * Node.js command template for editing files.\n */\nfunction buildEditCommand(\n filePath: string,\n oldStr: string,\n newStr: string,\n replaceAll: boolean,\n): string {\n const pathB64 = btoa(filePath);\n const oldB64 = btoa(oldStr);\n const newB64 = btoa(newStr);\n\n return `node -e \"\nconst fs = require('fs');\n\nconst filePath = atob('${pathB64}');\nconst oldStr = atob('${oldB64}');\nconst newStr = atob('${newB64}');\nconst replaceAll = ${Boolean(replaceAll)};\n\nlet text;\ntry {\n text = fs.readFileSync(filePath, 'utf-8');\n} catch (e) {\n process.exit(3);\n}\n\nconst count = text.split(oldStr).length - 1;\n\nif (count === 0) {\n process.exit(1);\n}\nif (count > 1 && !replaceAll) {\n process.exit(2);\n}\n\nconst result = text.split(oldStr).join(newStr);\nfs.writeFileSync(filePath, result, 'utf-8');\nconsole.log(count);\n\"`;\n}\n\n/**\n * Node.js command template for grep operations.\n */\nfunction buildGrepCommand(\n pattern: string,\n searchPath: string,\n globPattern: string | null,\n): string {\n const patternB64 = btoa(pattern);\n const pathB64 = btoa(searchPath);\n const globB64 = globPattern ? btoa(globPattern) : \"\";\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst pattern = atob('${patternB64}');\nconst searchPath = atob('${pathB64}');\nconst globPattern = ${globPattern ? `atob('${globB64}')` : \"null\"};\n\nlet regex;\ntry {\n regex = new RegExp(pattern);\n} catch (e) {\n console.error('Invalid regex: ' + e.message);\n process.exit(1);\n}\n\nfunction globMatch(filePath, pattern) {\n if (!pattern) return true;\n const regexPattern = pattern\n .replace(/\\\\*\\\\*/g, '<<<GLOBSTAR>>>')\n .replace(/\\\\*/g, '[^/]*')\n .replace(/\\\\?/g, '.')\n .replace(/<<<GLOBSTAR>>>/g, '.*');\n return new RegExp('^' + regexPattern + '$').test(filePath);\n}\n\nfunction walkDir(dir, results) {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n walkDir(fullPath, results);\n } else {\n const relativePath = path.relative(searchPath, fullPath);\n if (globMatch(relativePath, globPattern)) {\n try {\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\\\n');\n for (let i = 0; i < lines.length; i++) {\n if (regex.test(lines[i])) {\n console.log(JSON.stringify({\n path: fullPath,\n line: i + 1,\n text: lines[i]\n }));\n }\n }\n } catch (e) {\n // Skip unreadable files\n }\n }\n }\n }\n } catch (e) {\n // Skip unreadable directories\n }\n}\n\ntry {\n walkDir(searchPath, []);\n} catch (e) {\n // Silent failure\n}\n\"`;\n}\n\n/**\n * Base sandbox implementation with execute() as the only abstract method.\n *\n * This class provides default implementations for all SandboxBackendProtocol\n * methods using shell commands executed via execute(). Concrete implementations\n * only need to implement the execute() method.\n *\n * Requires Node.js 20+ on the sandbox host.\n */\nexport abstract class BaseSandbox implements SandboxBackendProtocol {\n /** Unique identifier for the sandbox backend */\n abstract readonly id: string;\n\n /**\n * Execute a command in the sandbox.\n * This is the only method concrete implementations must provide.\n */\n abstract execute(command: string): MaybePromise<ExecuteResponse>;\n\n /**\n * Upload multiple files to the sandbox.\n * Implementations must support partial success.\n */\n abstract uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): MaybePromise<FileUploadResponse[]>;\n\n /**\n * Download multiple files from the sandbox.\n * Implementations must support partial success.\n */\n abstract downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n */\n async lsInfo(path: string): Promise<FileInfo[]> {\n const command = buildLsCommand(path);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n return [];\n }\n\n const infos: FileInfo[] = [];\n const lines = result.output.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n infos.push({\n path: parsed.path,\n is_dir: parsed.isDir,\n size: parsed.size,\n modified_at: parsed.mtime\n ? new Date(parsed.mtime).toISOString()\n : undefined,\n });\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 2000,\n ): Promise<string> {\n const command = buildReadCommand(filePath, offset, limit);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n return `Error: File '${filePath}' not found`;\n }\n\n return result.output;\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n const command = buildReadCommand(filePath, 0, Number.MAX_SAFE_INTEGER);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n throw new Error(`File '${filePath}' not found`);\n }\n\n // Parse the line-numbered output back to content\n const lines: string[] = [];\n for (const line of result.output.split(\"\\n\")) {\n // Format is \" 123\\tContent\"\n const tabIndex = line.indexOf(\"\\t\");\n if (tabIndex !== -1) {\n lines.push(line.substring(tabIndex + 1));\n }\n }\n\n const now = new Date().toISOString();\n return {\n content: lines,\n created_at: now,\n modified_at: now,\n };\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n const command = buildGrepCommand(pattern, path, glob);\n const result = await this.execute(command);\n\n if (result.exitCode === 1) {\n // Check if it's a regex error\n if (result.output.includes(\"Invalid regex:\")) {\n return result.output.trim();\n }\n }\n\n const matches: GrepMatch[] = [];\n const lines = result.output.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n matches.push({\n path: parsed.path,\n line: parsed.line,\n text: parsed.text,\n });\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return matches;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(pattern: string, path: string = \"/\"): Promise<FileInfo[]> {\n const command = buildGlobCommand(path, pattern);\n const result = await this.execute(command);\n\n const infos: FileInfo[] = [];\n const lines = result.output.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n infos.push({\n path: parsed.path,\n is_dir: parsed.isDir,\n size: parsed.size,\n modified_at: parsed.mtime\n ? new Date(parsed.mtime).toISOString()\n : undefined,\n });\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return infos;\n }\n\n /**\n * Create a new file with content.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n const command = buildWriteCommand(filePath, content);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n return { path: filePath, filesUpdate: null };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n const command = buildEditCommand(\n filePath,\n oldString,\n newString,\n replaceAll,\n );\n const result = await this.execute(command);\n\n switch (result.exitCode) {\n case 0: {\n const occurrences = parseInt(result.output.trim(), 10) || 1;\n return { path: filePath, filesUpdate: null, occurrences };\n }\n case 1:\n return { error: `String not found in file '${filePath}'` };\n case 2:\n return {\n error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.`,\n };\n case 3:\n return { error: `Error: File '${filePath}' not found` };\n default:\n return { error: `Unknown error editing file '${filePath}'` };\n }\n }\n}\n","import {\n createAgent,\n humanInTheLoopMiddleware,\n anthropicPromptCachingMiddleware,\n todoListMiddleware,\n summarizationMiddleware,\n SystemMessage,\n type AgentMiddleware,\n type ReactAgent,\n type CreateAgentParams as _CreateAgentParams,\n type AgentTypeConfig,\n type ResponseFormat,\n} from \"langchain\";\nimport type {\n ClientTool,\n ServerTool,\n StructuredTool,\n} from \"@langchain/core/tools\";\nimport type { BaseStore } from \"@langchain/langgraph-checkpoint\";\n\nimport {\n createFilesystemMiddleware,\n createSubAgentMiddleware,\n createPatchToolCallsMiddleware,\n type SubAgent,\n} from \"./middleware/index.js\";\nimport { StateBackend } from \"./backends/index.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { CompiledSubAgent } from \"./middleware/subagents.js\";\nimport type {\n CreateDeepAgentParams,\n FlattenSubAgentMiddleware,\n} from \"./types.js\";\n\n/**\n * required for type inference\n */\nimport type * as _messages from \"@langchain/core/messages\";\nimport type * as _Command from \"@langchain/langgraph\";\n\nconst BASE_PROMPT = `In order to complete the objective that the user asks of you, you have access to a number of standard tools.`;\n\n/**\n * Create a Deep Agent with middleware-based architecture.\n *\n * Matches Python's create_deep_agent function, using middleware for all features:\n * - Todo management (todoListMiddleware)\n * - Filesystem tools (createFilesystemMiddleware)\n * - Subagent delegation (createSubAgentMiddleware)\n * - Conversation summarization (summarizationMiddleware)\n * - Prompt caching (anthropicPromptCachingMiddleware)\n * - Tool call patching (createPatchToolCallsMiddleware)\n * - Human-in-the-loop (humanInTheLoopMiddleware) - optional\n *\n * @param params Configuration parameters for the agent\n * @returns ReactAgent instance ready for invocation with properly inferred state types\n *\n * @example\n * ```typescript\n * // Middleware with custom state\n * const ResearchMiddleware = createMiddleware({\n * name: \"ResearchMiddleware\",\n * stateSchema: z.object({ research: z.string().default(\"\") }),\n * });\n *\n * const agent = createDeepAgent({\n * middleware: [ResearchMiddleware],\n * });\n *\n * const result = await agent.invoke({ messages: [...] });\n * // result.research is properly typed as string\n * ```\n */\nexport function createDeepAgent<\n TResponse extends ResponseFormat = ResponseFormat,\n ContextSchema extends InteropZodObject = InteropZodObject,\n const TMiddleware extends readonly AgentMiddleware[] = readonly [],\n const TSubagents extends readonly (SubAgent | CompiledSubAgent)[] =\n readonly [],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly [],\n>(\n params: CreateDeepAgentParams<\n TResponse,\n ContextSchema,\n TMiddleware,\n TSubagents,\n TTools\n > = {} as CreateDeepAgentParams<\n TResponse,\n ContextSchema,\n TMiddleware,\n TSubagents,\n TTools\n >,\n) {\n const {\n model = \"claude-sonnet-4-5-20250929\",\n tools = [],\n systemPrompt,\n middleware: customMiddleware = [],\n subagents = [],\n responseFormat,\n contextSchema,\n checkpointer,\n store,\n backend,\n interruptOn,\n name,\n } = params;\n\n // Combine system prompt with base prompt like Python implementation\n const finalSystemPrompt = systemPrompt\n ? typeof systemPrompt === \"string\"\n ? `${systemPrompt}\\n\\n${BASE_PROMPT}`\n : new SystemMessage({\n content: [\n {\n type: \"text\",\n text: BASE_PROMPT,\n },\n ...(typeof systemPrompt.content === \"string\"\n ? [{ type: \"text\", text: systemPrompt.content }]\n : systemPrompt.content),\n ],\n })\n : BASE_PROMPT;\n\n // Create backend configuration for filesystem middleware\n // If no backend is provided, use a factory that creates a StateBackend\n const filesystemBackend = backend\n ? backend\n : (config: { state: unknown; store?: BaseStore }) =>\n new StateBackend(config);\n\n // Built-in middleware array\n const builtInMiddleware = [\n // Provides todo list management capabilities for tracking tasks\n todoListMiddleware(),\n // Enables filesystem operations and optional long-term memory storage\n createFilesystemMiddleware({ backend: filesystemBackend }),\n // Enables delegation to specialized subagents for complex tasks\n createSubAgentMiddleware({\n defaultModel: model,\n defaultTools: tools as StructuredTool[],\n defaultMiddleware: [\n // Subagent middleware: Todo list management\n todoListMiddleware(),\n // Subagent middleware: Filesystem operations\n createFilesystemMiddleware({\n backend: filesystemBackend,\n }),\n // Subagent middleware: Automatic conversation summarization when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Subagent middleware: Anthropic prompt caching for improved performance\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Subagent middleware: Patches tool calls for compatibility\n createPatchToolCallsMiddleware(),\n ],\n defaultInterruptOn: interruptOn,\n subagents: subagents as unknown as (SubAgent | CompiledSubAgent)[],\n generalPurposeAgent: true,\n }),\n // Automatically summarizes conversation history when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Enables Anthropic prompt caching for improved performance and reduced costs\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Patches tool calls to ensure compatibility across different model providers\n createPatchToolCallsMiddleware(),\n ] as const;\n\n // Add human-in-the-loop middleware if interrupt config provided\n if (interruptOn) {\n // builtInMiddleware is typed as readonly to enable type inference\n // however, we need to push to it to add the middleware, so let's ignore the type error\n // @ts-expect-error - builtInMiddleware is readonly\n builtInMiddleware.push(humanInTheLoopMiddleware({ interruptOn }));\n }\n\n // Combine built-in middleware with custom middleware\n // The custom middleware is typed as TMiddleware to preserve type information\n const allMiddleware = [\n ...builtInMiddleware,\n ...(customMiddleware as unknown as TMiddleware),\n ] as const;\n\n // Note: Recursion limit of 1000 (matching Python behavior) should be passed\n // at invocation time: agent.invoke(input, { recursionLimit: 1000 })\n const agent = createAgent({\n model,\n systemPrompt: finalSystemPrompt,\n tools: tools as StructuredTool[],\n middleware: allMiddleware as unknown as AgentMiddleware[],\n responseFormat: responseFormat as ResponseFormat,\n contextSchema,\n checkpointer,\n store,\n name,\n });\n\n // Combine custom middleware with flattened subagent middleware for complete type inference\n // This ensures InferMiddlewareStates captures state from both sources\n type AllMiddleware = readonly [\n ...typeof builtInMiddleware,\n ...TMiddleware,\n ...FlattenSubAgentMiddleware<TSubagents>,\n ];\n\n // Return as ReactAgent with proper AgentTypeConfig\n // - Response: TResponse (from responseFormat parameter)\n // - State: undefined (state comes from middleware)\n // - Context: ContextSchema\n // - Middleware: AllMiddleware (custom + subagent middleware for state inference)\n // - Tools: TTools\n return agent as unknown as ReactAgent<\n AgentTypeConfig<TResponse, undefined, ContextSchema, AllMiddleware, TTools>\n >;\n}\n","/**\n * Configuration and settings for deepagents.\n *\n * Provides project detection, path management, and environment configuration\n * for skills and agent memory middleware.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\n/**\n * Options for creating a Settings instance.\n */\nexport interface SettingsOptions {\n /** Starting directory for project detection (defaults to cwd) */\n startPath?: string;\n}\n\n/**\n * Settings interface for project detection and path management.\n *\n * Provides access to:\n * - Project root detection (via .git directory)\n * - User-level deepagents directory (~/.deepagents)\n * - Agent-specific directories and files\n * - Skills directories (user and project level)\n */\nexport interface Settings {\n /** Detected project root directory, or null if not in a git project */\n readonly projectRoot: string | null;\n\n /** Base user-level .deepagents directory (~/.deepagents) */\n readonly userDeepagentsDir: string;\n\n /** Check if currently in a git project */\n readonly hasProject: boolean;\n\n /**\n * Get the agent directory path.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}\n * @throws Error if agent name is invalid\n */\n getAgentDir(agentName: string): string;\n\n /**\n * Ensure agent directory exists and return path.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}\n * @throws Error if agent name is invalid\n */\n ensureAgentDir(agentName: string): string;\n\n /**\n * Get user-level agent.md path for a specific agent.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}/agent.md\n */\n getUserAgentMdPath(agentName: string): string;\n\n /**\n * Get project-level agent.md path.\n * @returns Path to {projectRoot}/.deepagents/agent.md, or null if not in a project\n */\n getProjectAgentMdPath(): string | null;\n\n /**\n * Get user-level skills directory path for a specific agent.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}/skills/\n */\n getUserSkillsDir(agentName: string): string;\n\n /**\n * Ensure user-level skills directory exists and return path.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}/skills/\n */\n ensureUserSkillsDir(agentName: string): string;\n\n /**\n * Get project-level skills directory path.\n * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project\n */\n getProjectSkillsDir(): string | null;\n\n /**\n * Ensure project-level skills directory exists and return path.\n * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project\n */\n ensureProjectSkillsDir(): string | null;\n\n /**\n * Ensure project .deepagents directory exists.\n * @returns Path to {projectRoot}/.deepagents/, or null if not in a project\n */\n ensureProjectDeepagentsDir(): string | null;\n}\n\n/**\n * Find the project root by looking for .git directory.\n *\n * Walks up the directory tree from startPath (or cwd) looking for a .git\n * directory, which indicates the project root.\n *\n * @param startPath - Directory to start searching from. Defaults to current working directory.\n * @returns Path to the project root if found, null otherwise.\n */\nexport function findProjectRoot(startPath?: string): string | null {\n let current = path.resolve(startPath || process.cwd());\n\n // Walk up the directory tree\n while (current !== path.dirname(current)) {\n const gitDir = path.join(current, \".git\");\n if (fs.existsSync(gitDir)) {\n return current;\n }\n current = path.dirname(current);\n }\n\n // Check root directory as well\n const rootGitDir = path.join(current, \".git\");\n if (fs.existsSync(rootGitDir)) {\n return current;\n }\n\n return null;\n}\n\n/**\n * Validate agent name to prevent invalid filesystem paths and security issues.\n *\n * @param agentName - The agent name to validate\n * @returns True if valid, false otherwise\n */\nfunction isValidAgentName(agentName: string): boolean {\n if (!agentName || !agentName.trim()) {\n return false;\n }\n // Allow only alphanumeric, hyphens, underscores, and whitespace\n return /^[a-zA-Z0-9_\\-\\s]+$/.test(agentName);\n}\n\n/**\n * Create a Settings instance with detected environment.\n *\n * @param options - Configuration options\n * @returns Settings instance with project detection and path management\n */\nexport function createSettings(options: SettingsOptions = {}): Settings {\n const projectRoot = findProjectRoot(options.startPath);\n const userDeepagentsDir = path.join(os.homedir(), \".deepagents\");\n\n return {\n projectRoot,\n userDeepagentsDir,\n hasProject: projectRoot !== null,\n\n getAgentDir(agentName: string): string {\n if (!isValidAgentName(agentName)) {\n throw new Error(\n `Invalid agent name: ${JSON.stringify(agentName)}. ` +\n \"Agent names can only contain letters, numbers, hyphens, underscores, and spaces.\",\n );\n }\n return path.join(userDeepagentsDir, agentName);\n },\n\n ensureAgentDir(agentName: string): string {\n const agentDir = this.getAgentDir(agentName);\n fs.mkdirSync(agentDir, { recursive: true });\n return agentDir;\n },\n\n getUserAgentMdPath(agentName: string): string {\n return path.join(this.getAgentDir(agentName), \"agent.md\");\n },\n\n getProjectAgentMdPath(): string | null {\n if (!projectRoot) {\n return null;\n }\n return path.join(projectRoot, \".deepagents\", \"agent.md\");\n },\n\n getUserSkillsDir(agentName: string): string {\n return path.join(this.getAgentDir(agentName), \"skills\");\n },\n\n ensureUserSkillsDir(agentName: string): string {\n const skillsDir = this.getUserSkillsDir(agentName);\n fs.mkdirSync(skillsDir, { recursive: true });\n return skillsDir;\n },\n\n getProjectSkillsDir(): string | null {\n if (!projectRoot) {\n return null;\n }\n return path.join(projectRoot, \".deepagents\", \"skills\");\n },\n\n ensureProjectSkillsDir(): string | null {\n const skillsDir = this.getProjectSkillsDir();\n if (!skillsDir) {\n return null;\n }\n fs.mkdirSync(skillsDir, { recursive: true });\n return skillsDir;\n },\n\n ensureProjectDeepagentsDir(): string | null {\n if (!projectRoot) {\n return null;\n }\n const deepagentsDir = path.join(projectRoot, \".deepagents\");\n fs.mkdirSync(deepagentsDir, { recursive: true });\n return deepagentsDir;\n },\n };\n}\n","/**\n * Skill loader for parsing and loading agent skills from SKILL.md files.\n *\n * This module implements Anthropic's agent skills pattern with YAML frontmatter parsing.\n * Each skill is a directory containing a SKILL.md file with:\n * - YAML frontmatter (name, description required)\n * - Markdown instructions for the agent\n * - Optional supporting files (scripts, configs, etc.)\n *\n * @example\n * ```markdown\n * ---\n * name: web-research\n * description: Structured approach to conducting thorough web research\n * ---\n *\n * # Web Research Skill\n *\n * ## When to Use\n * - User asks you to research a topic\n * ...\n * ```\n *\n * @see https://agentskills.io/specification\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport yaml from \"yaml\";\n\n/** Maximum size for SKILL.md files (10MB) */\nexport const MAX_SKILL_FILE_SIZE = 10 * 1024 * 1024;\n\n/** Agent Skills spec constraints */\nexport const MAX_SKILL_NAME_LENGTH = 64;\nexport const MAX_SKILL_DESCRIPTION_LENGTH = 1024;\n\n/** Pattern for validating skill names per Agent Skills spec */\nconst SKILL_NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n/** Pattern for extracting YAML frontmatter */\nconst FRONTMATTER_PATTERN = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/;\n\n/**\n * Metadata for a skill per Agent Skills spec.\n * @see https://agentskills.io/specification\n */\nexport interface SkillMetadata {\n /** Name of the skill (max 64 chars, lowercase alphanumeric and hyphens) */\n name: string;\n\n /** Description of what the skill does (max 1024 chars) */\n description: string;\n\n /** Absolute path to the SKILL.md file */\n path: string;\n\n /** Source of the skill ('user' or 'project') */\n source: \"user\" | \"project\";\n\n /** Optional: License name or reference to bundled license file */\n license?: string;\n\n /** Optional: Environment requirements (max 500 chars) */\n compatibility?: string;\n\n /** Optional: Arbitrary key-value mapping for additional metadata */\n metadata?: Record<string, string>;\n\n /** Optional: Space-delimited list of pre-approved tools */\n allowedTools?: string;\n}\n\n/**\n * Options for listing skills.\n */\nexport interface ListSkillsOptions {\n /** Path to user-level skills directory */\n userSkillsDir?: string | null;\n\n /** Path to project-level skills directory */\n projectSkillsDir?: string | null;\n}\n\n/**\n * Result of skill name validation.\n */\ninterface ValidationResult {\n valid: boolean;\n error?: string;\n}\n\n/**\n * Check if a path is safely contained within base_dir.\n *\n * This prevents directory traversal attacks via symlinks or path manipulation.\n * The function resolves both paths to their canonical form (following symlinks)\n * and verifies that the target path is within the base directory.\n *\n * @param targetPath - The path to validate\n * @param baseDir - The base directory that should contain the path\n * @returns True if the path is safely within baseDir, false otherwise\n */\nfunction isSafePath(targetPath: string, baseDir: string): boolean {\n try {\n // Resolve both paths to their canonical form (follows symlinks)\n const resolvedPath = fs.realpathSync(targetPath);\n const resolvedBase = fs.realpathSync(baseDir);\n\n // Check if the resolved path is within the base directory\n return (\n resolvedPath.startsWith(resolvedBase + path.sep) ||\n resolvedPath === resolvedBase\n );\n } catch {\n // Error resolving paths (e.g., circular symlinks, too many levels)\n return false;\n }\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n *\n * Requirements:\n * - Max 64 characters\n * - Lowercase alphanumeric and hyphens only (a-z, 0-9, -)\n * - Cannot start or end with hyphen\n * - No consecutive hyphens\n * - Must match parent directory name\n *\n * @param name - The skill name from YAML frontmatter\n * @param directoryName - The parent directory name\n * @returns Validation result with error message if invalid\n */\nfunction validateSkillName(\n name: string,\n directoryName: string,\n): ValidationResult {\n if (!name) {\n return { valid: false, error: \"name is required\" };\n }\n if (name.length > MAX_SKILL_NAME_LENGTH) {\n return { valid: false, error: \"name exceeds 64 characters\" };\n }\n // Pattern: lowercase alphanumeric, single hyphens between segments, no start/end hyphen\n if (!SKILL_NAME_PATTERN.test(name)) {\n return {\n valid: false,\n error: \"name must be lowercase alphanumeric with single hyphens only\",\n };\n }\n if (name !== directoryName) {\n return {\n valid: false,\n error: `name '${name}' must match directory name '${directoryName}'`,\n };\n }\n return { valid: true };\n}\n\n/**\n * Parse YAML frontmatter from content.\n *\n * @param content - The file content\n * @returns Parsed frontmatter object, or null if parsing fails\n */\nfunction parseFrontmatter(content: string): Record<string, unknown> | null {\n const match = content.match(FRONTMATTER_PATTERN);\n if (!match) {\n return null;\n }\n\n try {\n const parsed = yaml.parse(match[1]);\n return typeof parsed === \"object\" && parsed !== null ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Parse YAML frontmatter from a SKILL.md file per Agent Skills spec.\n *\n * @param skillMdPath - Path to the SKILL.md file\n * @param source - Source of the skill ('user' or 'project')\n * @returns SkillMetadata with all fields, or null if parsing fails\n */\nexport function parseSkillMetadata(\n skillMdPath: string,\n source: \"user\" | \"project\",\n): SkillMetadata | null {\n try {\n // Security: Check file size to prevent DoS attacks\n const stats = fs.statSync(skillMdPath);\n if (stats.size > MAX_SKILL_FILE_SIZE) {\n // eslint-disable-next-line no-console\n console.warn(\n `Skipping ${skillMdPath}: file too large (${stats.size} bytes)`,\n );\n return null;\n }\n\n const content = fs.readFileSync(skillMdPath, \"utf-8\");\n const frontmatter = parseFrontmatter(content);\n\n if (!frontmatter) {\n // eslint-disable-next-line no-console\n console.warn(`Skipping ${skillMdPath}: no valid YAML frontmatter found`);\n return null;\n }\n\n // Validate required fields\n const name = frontmatter.name;\n const description = frontmatter.description;\n\n if (!name || !description) {\n // eslint-disable-next-line no-console\n console.warn(\n `Skipping ${skillMdPath}: missing required 'name' or 'description'`,\n );\n return null;\n }\n\n // Validate name format per spec (warn but still load for backwards compatibility)\n const directoryName = path.basename(path.dirname(skillMdPath));\n const validation = validateSkillName(String(name), directoryName);\n if (!validation.valid) {\n // eslint-disable-next-line no-console\n console.warn(\n `Skill '${name}' in ${skillMdPath} does not follow Agent Skills spec: ${validation.error}. ` +\n \"Consider renaming to be spec-compliant.\",\n );\n }\n\n // Truncate description if too long (spec: max 1024 chars)\n let descriptionStr = String(description);\n if (descriptionStr.length > MAX_SKILL_DESCRIPTION_LENGTH) {\n // eslint-disable-next-line no-console\n console.warn(\n `Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH} chars in ${skillMdPath}, truncating`,\n );\n descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH);\n }\n\n return {\n name: String(name),\n description: descriptionStr,\n path: skillMdPath,\n source,\n license: frontmatter.license ? String(frontmatter.license) : undefined,\n compatibility: frontmatter.compatibility\n ? String(frontmatter.compatibility)\n : undefined,\n metadata:\n frontmatter.metadata && typeof frontmatter.metadata === \"object\"\n ? (frontmatter.metadata as Record<string, string>)\n : undefined,\n allowedTools: frontmatter[\"allowed-tools\"]\n ? String(frontmatter[\"allowed-tools\"])\n : undefined,\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(`Error reading ${skillMdPath}: ${error}`);\n return null;\n }\n}\n\n/**\n * List all skills from a single skills directory (internal helper).\n *\n * Scans the skills directory for subdirectories containing SKILL.md files,\n * parses YAML frontmatter, and returns skill metadata.\n *\n * Skills are organized as:\n * ```\n * skills/\n * ├── skill-name/\n * │ ├── SKILL.md # Required: instructions with YAML frontmatter\n * │ ├── script.py # Optional: supporting files\n * │ └── config.json # Optional: supporting files\n * ```\n *\n * @param skillsDir - Path to the skills directory\n * @param source - Source of the skills ('user' or 'project')\n * @returns List of skill metadata\n */\nfunction listSkillsFromDir(\n skillsDir: string,\n source: \"user\" | \"project\",\n): SkillMetadata[] {\n // Check if skills directory exists\n const expandedDir = skillsDir.startsWith(\"~\")\n ? path.join(\n process.env.HOME || process.env.USERPROFILE || \"\",\n skillsDir.slice(1),\n )\n : skillsDir;\n\n if (!fs.existsSync(expandedDir)) {\n return [];\n }\n\n // Resolve base directory to canonical path for security checks\n let resolvedBase: string;\n try {\n resolvedBase = fs.realpathSync(expandedDir);\n } catch {\n // Can't resolve base directory, fail safe\n return [];\n }\n\n const skills: SkillMetadata[] = [];\n\n // Iterate through subdirectories\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(resolvedBase, { withFileTypes: true });\n } catch {\n return [];\n }\n\n for (const entry of entries) {\n const skillDir = path.join(resolvedBase, entry.name);\n\n // Security: Catch symlinks pointing outside the skills directory\n if (!isSafePath(skillDir, resolvedBase)) {\n continue;\n }\n\n if (!entry.isDirectory()) {\n continue;\n }\n\n // Look for SKILL.md file\n const skillMdPath = path.join(skillDir, \"SKILL.md\");\n if (!fs.existsSync(skillMdPath)) {\n continue;\n }\n\n // Security: Validate SKILL.md path is safe before reading\n if (!isSafePath(skillMdPath, resolvedBase)) {\n continue;\n }\n\n // Parse metadata\n const metadata = parseSkillMetadata(skillMdPath, source);\n if (metadata) {\n skills.push(metadata);\n }\n }\n\n return skills;\n}\n\n/**\n * List skills from user and/or project directories.\n *\n * When both directories are provided, project skills with the same name as\n * user skills will override them.\n *\n * @param options - Options specifying which directories to search\n * @returns Merged list of skill metadata from both sources, with project skills\n * taking precedence over user skills when names conflict\n */\nexport function listSkills(options: ListSkillsOptions): SkillMetadata[] {\n const allSkills: Map<string, SkillMetadata> = new Map();\n\n // Load user skills first (foundation)\n if (options.userSkillsDir) {\n const userSkills = listSkillsFromDir(options.userSkillsDir, \"user\");\n for (const skill of userSkills) {\n allSkills.set(skill.name, skill);\n }\n }\n\n // Load project skills second (override/augment)\n if (options.projectSkillsDir) {\n const projectSkills = listSkillsFromDir(\n options.projectSkillsDir,\n \"project\",\n );\n for (const skill of projectSkills) {\n // Project skills override user skills with the same name\n allSkills.set(skill.name, skill);\n }\n }\n\n return Array.from(allSkills.values());\n}\n","/**\n * Middleware for loading and exposing agent skills to the system prompt.\n *\n * This middleware implements Anthropic's \"Agent Skills\" pattern with progressive disclosure:\n * 1. Parse YAML frontmatter from SKILL.md files at session start\n * 2. Inject skills metadata (name + description) into system prompt\n * 3. Agent reads full SKILL.md content when relevant to a task\n *\n * Skills directory structure (per-agent + project):\n * User-level: ~/.deepagents/{AGENT_NAME}/skills/\n * Project-level: {PROJECT_ROOT}/.deepagents/skills/\n *\n * @example\n * ```\n * ~/.deepagents/{AGENT_NAME}/skills/\n * ├── web-research/\n * │ ├── SKILL.md # Required: YAML frontmatter + instructions\n * │ └── helper.py # Optional: supporting files\n * ├── code-review/\n * │ ├── SKILL.md\n * │ └── checklist.md\n *\n * .deepagents/skills/\n * ├── project-specific/\n * │ └── SKILL.md # Project-specific skills\n * ```\n */\n\nimport { z } from \"zod\";\nimport { createMiddleware } from \"langchain\";\nimport { listSkills, type SkillMetadata } from \"../skills/loader.js\";\n\n/**\n * required for type inference\n */\nimport type { AgentMiddleware as _AgentMiddleware } from \"langchain\";\n\n/**\n * Options for the skills middleware.\n */\nexport interface SkillsMiddlewareOptions {\n /** Path to the user-level skills directory (per-agent) */\n skillsDir: string;\n\n /** The agent identifier for path references in prompts */\n assistantId: string;\n\n /** Optional path to project-level skills directory */\n projectSkillsDir?: string;\n}\n\n/**\n * State schema for skills middleware.\n */\nconst SkillsStateSchema = z.object({\n skillsMetadata: z\n .array(\n z.object({\n name: z.string(),\n description: z.string(),\n path: z.string(),\n source: z.enum([\"user\", \"project\"]),\n license: z.string().optional(),\n compatibility: z.string().optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n allowedTools: z.string().optional(),\n }),\n )\n .optional(),\n});\n\n/**\n * Skills System Documentation prompt template.\n */\nconst SKILLS_SYSTEM_PROMPT = `\n\n## Skills System\n\nYou have access to a skills library that provides specialized capabilities and domain knowledge.\n\n{skills_locations}\n\n**Available Skills:**\n\n{skills_list}\n\n**How to Use Skills (Progressive Disclosure):**\n\nSkills follow a **progressive disclosure** pattern - you know they exist (name + description above), but you only read the full instructions when needed:\n\n1. **Recognize when a skill applies**: Check if the user's task matches any skill's description\n2. **Read the skill's full instructions**: The skill list above shows the exact path to use with read_file\n3. **Follow the skill's instructions**: SKILL.md contains step-by-step workflows, best practices, and examples\n4. **Access supporting files**: Skills may include Python scripts, configs, or reference docs - use absolute paths\n\n**When to Use Skills:**\n- When the user's request matches a skill's domain (e.g., \"research X\" → web-research skill)\n- When you need specialized knowledge or structured workflows\n- When a skill provides proven patterns for complex tasks\n\n**Skills are Self-Documenting:**\n- Each SKILL.md tells you exactly what the skill does and how to use it\n- The skill list above shows the full path for each skill's SKILL.md file\n\n**Executing Skill Scripts:**\nSkills may contain Python scripts or other executable files. Always use absolute paths from the skill list.\n\n**Example Workflow:**\n\nUser: \"Can you research the latest developments in quantum computing?\"\n\n1. Check available skills above → See \"web-research\" skill with its full path\n2. Read the skill using the path shown in the list\n3. Follow the skill's research workflow (search → organize → synthesize)\n4. Use any helper scripts with absolute paths\n\nRemember: Skills are tools to make you more capable and consistent. When in doubt, check if a skill exists for the task!\n`;\n\n/**\n * Format skills locations for display in system prompt.\n */\nfunction formatSkillsLocations(\n userSkillsDisplay: string,\n projectSkillsDir?: string,\n): string {\n const locations = [`**User Skills**: \\`${userSkillsDisplay}\\``];\n if (projectSkillsDir) {\n locations.push(\n `**Project Skills**: \\`${projectSkillsDir}\\` (overrides user skills)`,\n );\n }\n return locations.join(\"\\n\");\n}\n\n/**\n * Format skills metadata for display in system prompt.\n */\nfunction formatSkillsList(\n skills: SkillMetadata[],\n userSkillsDisplay: string,\n projectSkillsDir?: string,\n): string {\n if (skills.length === 0) {\n const locations = [userSkillsDisplay];\n if (projectSkillsDir) {\n locations.push(projectSkillsDir);\n }\n return `(No skills available yet. You can create skills in ${locations.join(\" or \")})`;\n }\n\n // Group skills by source\n const userSkills = skills.filter((s) => s.source === \"user\");\n const projectSkills = skills.filter((s) => s.source === \"project\");\n\n const lines: string[] = [];\n\n // Show user skills\n if (userSkills.length > 0) {\n lines.push(\"**User Skills:**\");\n for (const skill of userSkills) {\n lines.push(`- **${skill.name}**: ${skill.description}`);\n lines.push(` → Read \\`${skill.path}\\` for full instructions`);\n }\n lines.push(\"\");\n }\n\n // Show project skills\n if (projectSkills.length > 0) {\n lines.push(\"**Project Skills:**\");\n for (const skill of projectSkills) {\n lines.push(`- **${skill.name}**: ${skill.description}`);\n lines.push(` → Read \\`${skill.path}\\` for full instructions`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Create middleware for loading and exposing agent skills.\n *\n * This middleware implements Anthropic's agent skills pattern:\n * - Loads skills metadata (name, description) from YAML frontmatter at session start\n * - Injects skills list into system prompt for discoverability\n * - Agent reads full SKILL.md content when a skill is relevant (progressive disclosure)\n *\n * Supports both user-level and project-level skills:\n * - User skills: ~/.deepagents/{AGENT_NAME}/skills/\n * - Project skills: {PROJECT_ROOT}/.deepagents/skills/\n * - Project skills override user skills with the same name\n *\n * @param options - Configuration options\n * @returns AgentMiddleware for skills loading and injection\n */\nexport function createSkillsMiddleware(options: SkillsMiddlewareOptions) {\n const { skillsDir, assistantId, projectSkillsDir } = options;\n\n // Store display paths for prompts\n const userSkillsDisplay = `~/.deepagents/${assistantId}/skills`;\n\n return createMiddleware({\n name: \"SkillsMiddleware\",\n stateSchema: SkillsStateSchema as any,\n\n beforeAgent() {\n // We re-load skills on every new interaction with the agent to capture\n // any changes in the skills directories.\n const skills = listSkills({\n userSkillsDir: skillsDir,\n projectSkillsDir: projectSkillsDir,\n });\n return { skillsMetadata: skills };\n },\n\n wrapModelCall(request: any, handler: any) {\n // Get skills metadata from state\n const skillsMetadata: SkillMetadata[] =\n request.state?.skillsMetadata || [];\n\n // Format skills locations and list\n const skillsLocations = formatSkillsLocations(\n userSkillsDisplay,\n projectSkillsDir,\n );\n const skillsList = formatSkillsList(\n skillsMetadata,\n userSkillsDisplay,\n projectSkillsDir,\n );\n\n // Format the skills documentation\n const skillsSection = SKILLS_SYSTEM_PROMPT.replace(\n \"{skills_locations}\",\n skillsLocations,\n ).replace(\"{skills_list}\", skillsList);\n\n // Append to existing system prompt\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${currentSystemPrompt}\\n\\n${skillsSection}`\n : skillsSection;\n\n return handler({ ...request, systemPrompt: newSystemPrompt });\n },\n });\n}\n","/**\n * Middleware for loading agent-specific long-term memory into the system prompt.\n *\n * This middleware loads the agent's long-term memory from agent.md files\n * and injects it into the system prompt. Memory is loaded from:\n * - User memory: ~/.deepagents/{agent_name}/agent.md\n * - Project memory: {project_root}/.deepagents/agent.md\n */\n\nimport fs from \"node:fs\";\nimport { z } from \"zod\";\nimport {\n createMiddleware,\n /**\n * required for type inference\n */\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\n\nimport type { Settings } from \"../config.js\";\n\n/**\n * Options for the agent memory middleware.\n */\nexport interface AgentMemoryMiddlewareOptions {\n /** Settings instance with project detection and paths */\n settings: Settings;\n\n /** The agent identifier */\n assistantId: string;\n\n /** Optional custom template for injecting agent memory into system prompt */\n systemPromptTemplate?: string;\n}\n\n/**\n * State schema for agent memory middleware.\n */\nconst AgentMemoryStateSchema = z.object({\n /** Personal preferences from ~/.deepagents/{agent}/ (applies everywhere) */\n userMemory: z.string().optional(),\n\n /** Project-specific context (loaded from project root) */\n projectMemory: z.string().optional(),\n});\n\n/**\n * Default template for memory injection.\n */\nconst DEFAULT_MEMORY_TEMPLATE = `<user_memory>\n{user_memory}\n</user_memory>\n\n<project_memory>\n{project_memory}\n</project_memory>`;\n\n/**\n * Long-term Memory Documentation system prompt.\n */\nconst LONGTERM_MEMORY_SYSTEM_PROMPT = `\n\n## Long-term Memory\n\nYour long-term memory is stored in files on the filesystem and persists across sessions.\n\n**User Memory Location**: \\`{agent_dir_absolute}\\` (displays as \\`{agent_dir_display}\\`)\n**Project Memory Location**: {project_memory_info}\n\nYour system prompt is loaded from TWO sources at startup:\n1. **User agent.md**: \\`{agent_dir_absolute}/agent.md\\` - Your personal preferences across all projects\n2. **Project agent.md**: Loaded from project root if available - Project-specific instructions\n\nProject-specific agent.md is loaded from these locations (both combined if both exist):\n- \\`[project-root]/.deepagents/agent.md\\` (preferred)\n- \\`[project-root]/agent.md\\` (fallback, but also included if both exist)\n\n**When to CHECK/READ memories (CRITICAL - do this FIRST):**\n- **At the start of ANY new session**: Check both user and project memories\n - User: \\`ls {agent_dir_absolute}\\`\n - Project: \\`ls {project_deepagents_dir}\\` (if in a project)\n- **BEFORE answering questions**: If asked \"what do you know about X?\" or \"how do I do Y?\", check project memories FIRST, then user\n- **When user asks you to do something**: Check if you have project-specific guides or examples\n- **When user references past work**: Search project memory files for related context\n\n**Memory-first response pattern:**\n1. User asks a question → Check project directory first: \\`ls {project_deepagents_dir}\\`\n2. If relevant files exist → Read them with \\`read_file '{project_deepagents_dir}/[filename]'\\`\n3. Check user memory if needed → \\`ls {agent_dir_absolute}\\`\n4. Base your answer on saved knowledge supplemented by general knowledge\n\n**When to update memories:**\n- **IMMEDIATELY when the user describes your role or how you should behave**\n- **IMMEDIATELY when the user gives feedback on your work** - Update memories to capture what was wrong and how to do it better\n- When the user explicitly asks you to remember something\n- When patterns or preferences emerge (coding styles, conventions, workflows)\n- After significant work where context would help in future sessions\n\n**Learning from feedback:**\n- When user says something is better/worse, capture WHY and encode it as a pattern\n- Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions\n- When user says \"you should remember X\" or \"be careful about Y\", treat this as HIGH PRIORITY - update memories IMMEDIATELY\n- Look for the underlying principle behind corrections, not just the specific mistake\n\n## Deciding Where to Store Memory\n\nWhen writing or updating agent memory, decide whether each fact, configuration, or behavior belongs in:\n\n### User Agent File: \\`{agent_dir_absolute}/agent.md\\`\n→ Describes the agent's **personality, style, and universal behavior** across all projects.\n\n**Store here:**\n- Your general tone and communication style\n- Universal coding preferences (formatting, comment style, etc.)\n- General workflows and methodologies you follow\n- Tool usage patterns that apply everywhere\n- Personal preferences that don't change per-project\n\n**Examples:**\n- \"Be concise and direct in responses\"\n- \"Always use type hints in Python\"\n- \"Prefer functional programming patterns\"\n\n### Project Agent File: \\`{project_deepagents_dir}/agent.md\\`\n→ Describes **how this specific project works** and **how the agent should behave here only.**\n\n**Store here:**\n- Project-specific architecture and design patterns\n- Coding conventions specific to this codebase\n- Project structure and organization\n- Testing strategies for this project\n- Deployment processes and workflows\n- Team conventions and guidelines\n\n**Examples:**\n- \"This project uses FastAPI with SQLAlchemy\"\n- \"Tests go in tests/ directory mirroring src/ structure\"\n- \"All API changes require updating OpenAPI spec\"\n\n### Project Memory Files: \\`{project_deepagents_dir}/*.md\\`\n→ Use for **project-specific reference information** and structured notes.\n\n**Store here:**\n- API design documentation\n- Architecture decisions and rationale\n- Deployment procedures\n- Common debugging patterns\n- Onboarding information\n\n**Examples:**\n- \\`{project_deepagents_dir}/api-design.md\\` - REST API patterns used\n- \\`{project_deepagents_dir}/architecture.md\\` - System architecture overview\n- \\`{project_deepagents_dir}/deployment.md\\` - How to deploy this project\n\n### File Operations:\n\n**User memory:**\n\\`\\`\\`\nls {agent_dir_absolute} # List user memory files\nread_file '{agent_dir_absolute}/agent.md' # Read user preferences\nedit_file '{agent_dir_absolute}/agent.md' ... # Update user preferences\n\\`\\`\\`\n\n**Project memory (preferred for project-specific information):**\n\\`\\`\\`\nls {project_deepagents_dir} # List project memory files\nread_file '{project_deepagents_dir}/agent.md' # Read project instructions\nedit_file '{project_deepagents_dir}/agent.md' ... # Update project instructions\nwrite_file '{project_deepagents_dir}/agent.md' ... # Create project memory file\n\\`\\`\\`\n\n**Important**:\n- Project memory files are stored in \\`.deepagents/\\` inside the project root\n- Always use absolute paths for file operations\n- Check project memories BEFORE user when answering project-specific questions`;\n\n/**\n * Create middleware for loading agent-specific long-term memory.\n *\n * This middleware loads the agent's long-term memory from a file (agent.md)\n * and injects it into the system prompt. The memory is loaded once at the\n * start of the conversation and stored in state.\n *\n * @param options - Configuration options\n * @returns AgentMiddleware for memory loading and injection\n */\nexport function createAgentMemoryMiddleware(\n options: AgentMemoryMiddlewareOptions,\n) {\n const { settings, assistantId, systemPromptTemplate } = options;\n\n // Compute paths\n const agentDir = settings.getAgentDir(assistantId);\n const agentDirDisplay = `~/.deepagents/${assistantId}`;\n const agentDirAbsolute = agentDir;\n const projectRoot = settings.projectRoot;\n\n // Build project memory info for documentation\n const projectMemoryInfo = projectRoot\n ? `\\`${projectRoot}\\` (detected)`\n : \"None (not in a git project)\";\n\n // Build project deepagents directory path\n const projectDeepagentsDir = projectRoot\n ? `${projectRoot}/.deepagents`\n : \"[project-root]/.deepagents (not in a project)\";\n\n const template = systemPromptTemplate || DEFAULT_MEMORY_TEMPLATE;\n\n return createMiddleware({\n name: \"AgentMemoryMiddleware\",\n stateSchema: AgentMemoryStateSchema as any,\n\n beforeAgent(state: any) {\n const result: Record<string, string> = {};\n\n // Load user memory if not already in state\n if (!(\"userMemory\" in state)) {\n const userPath = settings.getUserAgentMdPath(assistantId);\n if (fs.existsSync(userPath)) {\n try {\n result.userMemory = fs.readFileSync(userPath, \"utf-8\");\n } catch {\n // Ignore read errors\n }\n }\n }\n\n // Load project memory if not already in state\n if (!(\"projectMemory\" in state)) {\n const projectPath = settings.getProjectAgentMdPath();\n if (projectPath && fs.existsSync(projectPath)) {\n try {\n result.projectMemory = fs.readFileSync(projectPath, \"utf-8\");\n } catch {\n // Ignore read errors\n }\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n },\n\n wrapModelCall(request: any, handler: any) {\n // Extract memory from state\n const userMemory = request.state?.userMemory;\n const projectMemory = request.state?.projectMemory;\n const baseSystemPrompt = request.systemPrompt || \"\";\n\n // Format memory section with both memories\n const memorySection = template\n .replace(\"{user_memory}\", userMemory || \"(No user agent.md)\")\n .replace(\"{project_memory}\", projectMemory || \"(No project agent.md)\");\n\n // Format long-term memory documentation\n const memoryDocs = LONGTERM_MEMORY_SYSTEM_PROMPT.replaceAll(\n \"{agent_dir_absolute}\",\n agentDirAbsolute,\n )\n .replaceAll(\"{agent_dir_display}\", agentDirDisplay)\n .replaceAll(\"{project_memory_info}\", projectMemoryInfo)\n .replaceAll(\"{project_deepagents_dir}\", projectDeepagentsDir);\n\n // Memory content at start, base prompt in middle, documentation at end\n let systemPrompt = memorySection;\n if (baseSystemPrompt) {\n systemPrompt += \"\\n\\n\" + baseSystemPrompt;\n }\n systemPrompt += \"\\n\\n\" + memoryDocs;\n\n return handler({ ...request, systemPrompt });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqRA,SAAgB,iBACd,SACmC;AACnC,QACE,OAAQ,QAAmC,YAAY,cACvD,OAAQ,QAAmC,OAAO;;;;;;;;;;;;AC7QtD,MAAa,wBACX;AACF,MAAa,kBAAkB;AAC/B,MAAa,oBAAoB;;;;;;AAUjC,SAAgB,mBAAmB,YAA4B;AAC7D,QAAO,WAAW,QAAQ,OAAO,IAAI,CAAC,QAAQ,OAAO,IAAI,CAAC,QAAQ,OAAO,IAAI;;;;;;;;;;;AAY/E,SAAgB,6BACd,SACA,YAAoB,GACZ;CACR,IAAIA;AACJ,KAAI,OAAO,YAAY,UAAU;AAC/B,UAAQ,QAAQ,MAAM,KAAK;AAC3B,MAAI,MAAM,SAAS,KAAK,MAAM,MAAM,SAAS,OAAO,GAClD,SAAQ,MAAM,MAAM,GAAG,GAAG;OAG5B,SAAQ;CAGV,MAAMC,cAAwB,EAAE;AAChC,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM;EACnB,MAAM,UAAU,IAAI;AAEpB,MAAI,KAAK,UAAU,gBACjB,aAAY,KACV,GAAG,QAAQ,UAAU,CAAC,SAAS,kBAAkB,CAAC,IAAI,OACvD;OACI;GAEL,MAAM,YAAY,KAAK,KAAK,KAAK,SAAS,gBAAgB;AAC1D,QAAK,IAAI,WAAW,GAAG,WAAW,WAAW,YAAY;IACvD,MAAM,QAAQ,WAAW;IACzB,MAAM,MAAM,KAAK,IAAI,QAAQ,iBAAiB,KAAK,OAAO;IAC1D,MAAM,QAAQ,KAAK,UAAU,OAAO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AAM,mBAAmB;CACzB,MAAM,cAAc,SAAS;CAG7B,MAAM,oBAAoB,cACtB,KAAK,YAAY,iBACjB;CAGJ,MAAM,uBAAuB,cACzB,GAAG,YAAY,gBACf;CAEJ,MAAM,WAAW,wBAAwB;AAEzC,wCAAwB;EACtB,MAAM;EACN,aAAa;EAEb,YAAY,OAAY;GACtB,MAAMC,SAAiC,EAAE;AAGzC,OAAI,EAAE,gBAAgB,QAAQ;IAC5B,MAAM,WAAW,SAAS,mBAAmB,YAAY;AACzD,QAAIC,gBAAG,WAAW,SAAS,CACzB,KAAI;AACF,YAAO,aAAaA,gBAAG,aAAa,UAAU,QAAQ;YAChD;;AAOZ,OAAI,EAAE,mBAAmB,QAAQ;IAC/B,MAAM,cAAc,SAAS,uBAAuB;AACpD,QAAI,eAAeA,gBAAG,WAAW,YAAY,CAC3C,KAAI;AACF,YAAO,gBAAgBA,gBAAG,aAAa,aAAa,QAAQ;YACtD;;AAMZ,UAAO,OAAO,KAAK,OAAO,CAAC,SAAS,IAAI,SAAS;;EAGnD,cAAc,SAAc,SAAc;GAExC,MAAM,aAAa,QAAQ,OAAO;GAClC,MAAM,gBAAgB,QAAQ,OAAO;GACrC,MAAM,mBAAmB,QAAQ,gBAAgB;GAGjD,MAAM,gBAAgB,SACnB,QAAQ,iBAAiB,cAAc,qBAAqB,CAC5D,QAAQ,oBAAoB,iBAAiB,wBAAwB;GAGxE,MAAM,aAAa,8BAA8B,WAC/C,wBACA,iBACD,CACE,WAAW,uBAAuB,gBAAgB,CAClD,WAAW,yBAAyB,kBAAkB,CACtD,WAAW,4BAA4B,qBAAqB;GAG/D,IAAI,eAAe;AACnB,OAAI,iBACF,iBAAgB,SAAS;AAE3B,mBAAgB,SAAS;AAEzB,UAAO,QAAQ;IAAE,GAAG;IAAS;IAAc,CAAC;;EAE/C,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["path","path","z","result","path","ToolMessage","Command","Command","ToolMessage","HumanMessage","z","SystemMessage","AIMessage","ToolMessage","RemoveMessage","REMOVE_ALL_MESSAGES","z","path","getBackend","z","validateSkillName","getBackend","path","fsSync","path","fs","path","path","SystemMessage","path","fs","os","z","fs","MAX_SKILL_FILE_SIZE","MAX_SKILL_NAME_LENGTH","MAX_SKILL_DESCRIPTION_LENGTH","fs","path"],"sources":["../src/backends/protocol.ts","../src/backends/utils.ts","../src/backends/state.ts","../src/middleware/fs.ts","../src/middleware/subagents.ts","../src/middleware/patch_tool_calls.ts","../src/middleware/memory.ts","../src/middleware/skills.ts","../src/backends/store.ts","../src/backends/filesystem.ts","../src/backends/composite.ts","../src/backends/sandbox.ts","../src/agent.ts","../src/config.ts","../src/middleware/agent-memory.ts","../src/skills/loader.ts"],"sourcesContent":["/**\n * Protocol definition for pluggable memory backends.\n *\n * This module defines the BackendProtocol that all backend implementations\n * must follow. Backends can store files in different locations (state, filesystem,\n * database, etc.) and provide a uniform interface for file operations.\n */\n\nimport type { BaseStore } from \"@langchain/langgraph-checkpoint\";\n\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Structured file listing info.\n *\n * Minimal contract used across backends. Only \"path\" is required.\n * Other fields are best-effort and may be absent depending on backend.\n */\nexport interface FileInfo {\n /** File path */\n path: string;\n /** Whether this is a directory */\n is_dir?: boolean;\n /** File size in bytes (approximate) */\n size?: number;\n /** ISO 8601 timestamp of last modification */\n modified_at?: string;\n}\n\n/**\n * Structured grep match entry.\n */\nexport interface GrepMatch {\n /** File path where match was found */\n path: string;\n /** Line number (1-indexed) */\n line: number;\n /** The matching line text */\n text: string;\n}\n\n/**\n * File data structure used by backends.\n *\n * All file data is represented as objects with this structure:\n */\nexport interface FileData {\n /** Lines of text content */\n content: string[];\n /** ISO format timestamp of creation */\n created_at: string;\n /** ISO format timestamp of last modification */\n modified_at: string;\n}\n\n/**\n * Result from backend write operations.\n *\n * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.\n * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).\n */\nexport interface WriteResult {\n /** Error message on failure, undefined on success */\n error?: string;\n /** File path of written file, undefined on failure */\n path?: string;\n /**\n * State update dict for checkpoint backends, null for external storage.\n * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.\n * External backends set null (already persisted to disk/S3/database/etc).\n */\n filesUpdate?: Record<string, FileData> | null;\n /** Metadata for the write operation, attached to the ToolMessage */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Result from backend edit operations.\n *\n * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.\n * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).\n */\nexport interface EditResult {\n /** Error message on failure, undefined on success */\n error?: string;\n /** File path of edited file, undefined on failure */\n path?: string;\n /**\n * State update dict for checkpoint backends, null for external storage.\n * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.\n * External backends set null (already persisted to disk/S3/database/etc).\n */\n filesUpdate?: Record<string, FileData> | null;\n /** Number of replacements made, undefined on failure */\n occurrences?: number;\n /** Metadata for the edit operation, attached to the ToolMessage */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Result of code execution.\n * Simplified schema optimized for LLM consumption.\n */\nexport interface ExecuteResponse {\n /** Combined stdout and stderr output of the executed command */\n output: string;\n /** The process exit code. 0 indicates success, non-zero indicates failure */\n exitCode: number | null;\n /** Whether the output was truncated due to backend limitations */\n truncated: boolean;\n}\n\n/**\n * Standardized error codes for file upload/download operations.\n */\nexport type FileOperationError =\n | \"file_not_found\"\n | \"permission_denied\"\n | \"is_directory\"\n | \"invalid_path\";\n\n/**\n * Result of a single file download operation.\n */\nexport interface FileDownloadResponse {\n /** The file path that was requested */\n path: string;\n /** File contents as Uint8Array on success, null on failure */\n content: Uint8Array | null;\n /** Standardized error code on failure, null on success */\n error: FileOperationError | null;\n}\n\n/**\n * Result of a single file upload operation.\n */\nexport interface FileUploadResponse {\n /** The file path that was requested */\n path: string;\n /** Standardized error code on failure, null on success */\n error: FileOperationError | null;\n}\n\n/**\n * Protocol for pluggable memory backends (single, unified).\n *\n * Backends can store files in different locations (state, filesystem, database, etc.)\n * and provide a uniform interface for file operations.\n *\n * All file data is represented as objects with the FileData structure.\n *\n * Methods can return either direct values or Promises, allowing both\n * synchronous and asynchronous implementations.\n */\nexport interface BackendProtocol {\n /**\n * Structured listing with file metadata.\n *\n * Lists files and directories in the specified directory (non-recursive).\n * Directories have a trailing / in their path and is_dir=true.\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory\n */\n lsInfo(path: string): MaybePromise<FileInfo[]>;\n\n /**\n * Read file content with line numbers or an error string.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed), default 0\n * @param limit - Maximum number of lines to read, default 500\n * @returns Formatted file content with line numbers, or error message\n */\n read(filePath: string, offset?: number, limit?: number): MaybePromise<string>;\n\n /**\n * Structured search results or error string for invalid input.\n *\n * Searches file contents for a regex pattern.\n *\n * @param pattern - Regex pattern to search for\n * @param path - Base path to search from (default: null)\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @returns List of GrepMatch objects or error string for invalid regex\n */\n grepRaw(\n pattern: string,\n path?: string | null,\n glob?: string | null,\n ): MaybePromise<GrepMatch[] | string>;\n\n /**\n * Structured glob matching returning FileInfo objects.\n *\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param path - Base path to search from (default: \"/\")\n * @returns List of FileInfo objects matching the pattern\n */\n globInfo(pattern: string, path?: string): MaybePromise<FileInfo[]>;\n\n /**\n * Create a new file.\n *\n * @param filePath - Absolute file path\n * @param content - File content as string\n * @returns WriteResult with error populated on failure\n */\n write(filePath: string, content: string): MaybePromise<WriteResult>;\n\n /**\n * Edit a file by replacing string occurrences.\n *\n * @param filePath - Absolute file path\n * @param oldString - String to find and replace\n * @param newString - Replacement string\n * @param replaceAll - If true, replace all occurrences (default: false)\n * @returns EditResult with error, path, filesUpdate, and occurrences\n */\n edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll?: boolean,\n ): MaybePromise<EditResult>;\n\n /**\n * Upload multiple files.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): MaybePromise<FileUploadResponse[]>;\n\n /**\n * Download multiple files.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;\n}\n\n/**\n * Protocol for sandboxed backends with isolated runtime.\n * Sandboxed backends run in isolated environments (e.g., containers)\n * and communicate via defined interfaces.\n */\nexport interface SandboxBackendProtocol extends BackendProtocol {\n /**\n * Execute a command in the sandbox.\n *\n * @param command - Full shell command string to execute\n * @returns ExecuteResponse with combined output, exit code, and truncation flag\n */\n execute(command: string): MaybePromise<ExecuteResponse>;\n\n /** Unique identifier for the sandbox backend instance */\n readonly id: string;\n}\n\n/**\n * Type guard to check if a backend supports execution.\n *\n * @param backend - Backend instance to check\n * @returns True if the backend implements SandboxBackendProtocol\n */\nexport function isSandboxBackend(\n backend: BackendProtocol,\n): backend is SandboxBackendProtocol {\n return (\n typeof (backend as SandboxBackendProtocol).execute === \"function\" &&\n typeof (backend as SandboxBackendProtocol).id === \"string\"\n );\n}\n\n/**\n * State and store container for backend initialization.\n *\n * This provides a clean interface for what backends need to access:\n * - state: Current agent state (with files, messages, etc.)\n * - store: Optional persistent store for cross-conversation data\n *\n * Different contexts build this differently:\n * - Tools: Extract state via getCurrentTaskInput(config)\n * - Middleware: Use request.state directly\n */\nexport interface StateAndStore {\n /** Current agent state with files, messages, etc. */\n state: unknown;\n /** Optional BaseStore for persistent cross-conversation storage */\n store?: BaseStore;\n /** Optional assistant ID for per-assistant isolation in store */\n assistantId?: string;\n}\n\n/**\n * Factory function type for creating backend instances.\n *\n * Backends receive StateAndStore which contains the current state\n * and optional store, extracted from the execution context.\n *\n * @example\n * ```typescript\n * // Using in middleware\n * const middleware = createFilesystemMiddleware({\n * backend: (stateAndStore) => new StateBackend(stateAndStore)\n * });\n * ```\n */\nexport type BackendFactory = (stateAndStore: StateAndStore) => BackendProtocol;\n","/**\n * Shared utility functions for memory backend implementations.\n *\n * This module contains both user-facing string formatters and structured\n * helpers used by backends and the composite router. Structured helpers\n * enable composition without fragile string parsing.\n */\n\nimport micromatch from \"micromatch\";\nimport { basename } from \"path\";\nimport type { FileData, GrepMatch } from \"./protocol.js\";\n\n// Constants\nexport const EMPTY_CONTENT_WARNING =\n \"System reminder: File exists but has empty contents\";\nexport const MAX_LINE_LENGTH = 10000;\nexport const LINE_NUMBER_WIDTH = 6;\nexport const TOOL_RESULT_TOKEN_LIMIT = 20000; // Same threshold as eviction\nexport const TRUNCATION_GUIDANCE =\n \"... [results truncated, try being more specific with your parameters]\";\n\n/**\n * Sanitize tool_call_id to prevent path traversal and separator issues.\n *\n * Replaces dangerous characters (., /, \\) with underscores.\n */\nexport function sanitizeToolCallId(toolCallId: string): string {\n return toolCallId.replace(/\\./g, \"_\").replace(/\\//g, \"_\").replace(/\\\\/g, \"_\");\n}\n\n/**\n * Format file content with line numbers (cat -n style).\n *\n * Chunks lines longer than MAX_LINE_LENGTH with continuation markers (e.g., 5.1, 5.2).\n *\n * @param content - File content as string or list of lines\n * @param startLine - Starting line number (default: 1)\n * @returns Formatted content with line numbers and continuation markers\n */\nexport function formatContentWithLineNumbers(\n content: string | string[],\n startLine: number = 1,\n): string {\n let lines: string[];\n if (typeof content === \"string\") {\n lines = content.split(\"\\n\");\n if (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines = lines.slice(0, -1);\n }\n } else {\n lines = content;\n }\n\n const resultLines: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNum = i + startLine;\n\n if (line.length <= MAX_LINE_LENGTH) {\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${line}`,\n );\n } else {\n // Split long line into chunks with continuation markers\n const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH);\n for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) {\n const start = chunkIdx * MAX_LINE_LENGTH;\n const end = Math.min(start + MAX_LINE_LENGTH, line.length);\n const chunk = line.substring(start, end);\n if (chunkIdx === 0) {\n // First chunk: use normal line number\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n } else {\n // Continuation chunks: use decimal notation (e.g., 5.1, 5.2)\n const continuationMarker = `${lineNum}.${chunkIdx}`;\n resultLines.push(\n `${continuationMarker.padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n }\n }\n }\n }\n\n return resultLines.join(\"\\n\");\n}\n\n/**\n * Check if content is empty and return warning message.\n *\n * @param content - Content to check\n * @returns Warning message if empty, null otherwise\n */\nexport function checkEmptyContent(content: string): string | null {\n if (!content || content.trim() === \"\") {\n return EMPTY_CONTENT_WARNING;\n }\n return null;\n}\n\n/**\n * Convert FileData to plain string content.\n *\n * @param fileData - FileData object with 'content' key\n * @returns Content as string with lines joined by newlines\n */\nexport function fileDataToString(fileData: FileData): string {\n return fileData.content.join(\"\\n\");\n}\n\n/**\n * Create a FileData object with timestamps.\n *\n * @param content - File content as string\n * @param createdAt - Optional creation timestamp (ISO format)\n * @returns FileData object with content and timestamps\n */\nexport function createFileData(content: string, createdAt?: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: createdAt || now,\n modified_at: now,\n };\n}\n\n/**\n * Update FileData with new content, preserving creation timestamp.\n *\n * @param fileData - Existing FileData object\n * @param content - New content as string\n * @returns Updated FileData object\n */\nexport function updateFileData(fileData: FileData, content: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: fileData.created_at,\n modified_at: now,\n };\n}\n\n/**\n * Format file data for read response with line numbers.\n *\n * @param fileData - FileData object\n * @param offset - Line offset (0-indexed)\n * @param limit - Maximum number of lines\n * @returns Formatted content or error message\n */\nexport function formatReadResponse(\n fileData: FileData,\n offset: number,\n limit: number,\n): string {\n const content = fileDataToString(fileData);\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n}\n\n/**\n * Perform string replacement with occurrence validation.\n *\n * @param content - Original content\n * @param oldString - String to replace\n * @param newString - Replacement string\n * @param replaceAll - Whether to replace all occurrences\n * @returns Tuple of [new_content, occurrences] on success, or error message string\n */\nexport function performStringReplacement(\n content: string,\n oldString: string,\n newString: string,\n replaceAll: boolean,\n): [string, number] | string {\n // Use split to count occurrences (simpler than regex)\n const occurrences = content.split(oldString).length - 1;\n\n if (occurrences === 0) {\n return `Error: String not found in file: '${oldString}'`;\n }\n\n if (occurrences > 1 && !replaceAll) {\n return `Error: String '${oldString}' appears ${occurrences} times in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`;\n }\n\n // Python's str.replace() replaces ALL occurrences\n // Use split/join for consistent behavior\n const newContent = content.split(oldString).join(newString);\n\n return [newContent, occurrences];\n}\n\n/**\n * Truncate list or string result if it exceeds token limit (rough estimate: 4 chars/token).\n */\nexport function truncateIfTooLong(\n result: string[] | string,\n): string[] | string {\n if (Array.isArray(result)) {\n const totalChars = result.reduce((sum, item) => sum + item.length, 0);\n if (totalChars > TOOL_RESULT_TOKEN_LIMIT * 4) {\n const truncateAt = Math.floor(\n (result.length * TOOL_RESULT_TOKEN_LIMIT * 4) / totalChars,\n );\n return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE];\n }\n return result;\n }\n // string\n if (result.length > TOOL_RESULT_TOKEN_LIMIT * 4) {\n return (\n result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) +\n \"\\n\" +\n TRUNCATION_GUIDANCE\n );\n }\n return result;\n}\n\n/**\n * Validate and normalize a path.\n *\n * @param path - Path to validate\n * @returns Normalized path starting with / and ending with /\n * @throws Error if path is invalid\n */\nexport function validatePath(path: string | null | undefined): string {\n const pathStr = path || \"/\";\n if (!pathStr || pathStr.trim() === \"\") {\n throw new Error(\"Path cannot be empty\");\n }\n\n let normalized = pathStr.startsWith(\"/\") ? pathStr : \"/\" + pathStr;\n\n if (!normalized.endsWith(\"/\")) {\n normalized += \"/\";\n }\n\n return normalized;\n}\n\n/**\n * Search files dict for paths matching glob pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param path - Base path to search from\n * @returns Newline-separated file paths, sorted by modification time (most recent first).\n * Returns \"No files found\" if no matches.\n *\n * @example\n * ```typescript\n * const files = {\"/src/main.py\": FileData(...), \"/test.py\": FileData(...)};\n * globSearchFiles(files, \"*.py\", \"/\");\n * // Returns: \"/test.py\\n/src/main.py\" (sorted by modified_at)\n * ```\n */\nexport function globSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string = \"/\",\n): string {\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No files found\";\n }\n\n const filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n // Respect standard glob semantics:\n // - Patterns without path separators (e.g., \"*.py\") match only in the current\n // directory (non-recursive) relative to `path`.\n // - Use \"**\" explicitly for recursive matching.\n const effectivePattern = pattern;\n\n const matches: Array<[string, string]> = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n let relative = filePath.substring(normalizedPath.length);\n if (relative.startsWith(\"/\")) {\n relative = relative.substring(1);\n }\n if (!relative) {\n const parts = filePath.split(\"/\");\n relative = parts[parts.length - 1] || \"\";\n }\n\n if (\n micromatch.isMatch(relative, effectivePattern, {\n dot: true,\n nobrace: false,\n })\n ) {\n matches.push([filePath, fileData.modified_at]);\n }\n }\n\n matches.sort((a, b) => b[1].localeCompare(a[1])); // Sort by modified_at descending\n\n if (matches.length === 0) {\n return \"No files found\";\n }\n\n return matches.map(([fp]) => fp).join(\"\\n\");\n}\n\n/**\n * Format grep search results based on output mode.\n *\n * @param results - Dictionary mapping file paths to list of [line_num, line_content] tuples\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted string output\n */\nexport function formatGrepResults(\n results: Record<string, Array<[number, string]>>,\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (outputMode === \"files_with_matches\") {\n return Object.keys(results).sort().join(\"\\n\");\n }\n if (outputMode === \"count\") {\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n const count = results[filePath].length;\n lines.push(`${filePath}: ${count}`);\n }\n return lines.join(\"\\n\");\n }\n // content mode\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n lines.push(`${filePath}:`);\n for (const [lineNum, line] of results[filePath]) {\n lines.push(` ${lineNum}: ${line}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Search file contents for regex pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Regex pattern to search for\n * @param path - Base path to search from\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted search results. Returns \"No matches found\" if no results.\n *\n * @example\n * ```typescript\n * const files = {\"/file.py\": FileData({content: [\"import os\", \"print('hi')\"], ...})};\n * grepSearchFiles(files, \"import\", \"/\");\n * // Returns: \"/file.py\" (with output_mode=\"files_with_matches\")\n * ```\n */\nexport function grepSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n outputMode: \"files_with_matches\" | \"content\" | \"count\" = \"files_with_matches\",\n): string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No matches found\";\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n if (!results[filePath]) {\n results[filePath] = [];\n }\n results[filePath].push([lineNum, line]);\n }\n }\n }\n\n if (Object.keys(results).length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(results, outputMode);\n}\n\n// -------- Structured helpers for composition --------\n\n/**\n * Return structured grep matches from an in-memory files mapping.\n *\n * Returns a list of GrepMatch on success, or a string for invalid inputs\n * (e.g., invalid regex). We deliberately do not raise here to keep backends\n * non-throwing in tool contexts and preserve user-facing error messages.\n */\nexport function grepMatchesFromFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n): GrepMatch[] | string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return [];\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const matches: GrepMatch[] = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n matches.push({ path: filePath, line: lineNum, text: line });\n }\n }\n }\n\n return matches;\n}\n\n/**\n * Group structured matches into the legacy dict form used by formatters.\n */\nexport function buildGrepResultsDict(\n matches: GrepMatch[],\n): Record<string, Array<[number, string]>> {\n const grouped: Record<string, Array<[number, string]>> = {};\n for (const m of matches) {\n if (!grouped[m.path]) {\n grouped[m.path] = [];\n }\n grouped[m.path].push([m.line, m.text]);\n }\n return grouped;\n}\n\n/**\n * Format structured grep matches using existing formatting logic.\n */\nexport function formatGrepMatches(\n matches: GrepMatch[],\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (matches.length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(buildGrepResultsDict(matches), outputMode);\n}\n","/**\n * StateBackend: Store files in LangGraph agent state (ephemeral).\n */\n\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n StateAndStore,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n createFileData,\n fileDataToString,\n formatReadResponse,\n globSearchFiles,\n grepMatchesFromFiles,\n performStringReplacement,\n updateFileData,\n} from \"./utils.js\";\n\n/**\n * Backend that stores files in agent state (ephemeral).\n *\n * Uses LangGraph's state management and checkpointing. Files persist within\n * a conversation thread but not across threads. State is automatically\n * checkpointed after each agent step.\n *\n * Special handling: Since LangGraph state must be updated via Command objects\n * (not direct mutation), operations return filesUpdate in WriteResult/EditResult\n * for the middleware to apply via Command.\n */\nexport class StateBackend implements BackendProtocol {\n private stateAndStore: StateAndStore;\n\n constructor(stateAndStore: StateAndStore) {\n this.stateAndStore = stateAndStore;\n }\n\n /**\n * Get files from current state.\n */\n private getFiles(): Record<string, FileData> {\n return (\n ((this.stateAndStore.state as any).files as Record<string, FileData>) ||\n {}\n );\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n lsInfo(path: string): FileInfo[] {\n const files = this.getFiles();\n const infos: FileInfo[] = [];\n const subdirs = new Set<string>();\n\n // Normalize path to have trailing slash for proper prefix matching\n const normalizedPath = path.endsWith(\"/\") ? path : path + \"/\";\n\n for (const [k, fd] of Object.entries(files)) {\n // Check if file is in the specified directory or a subdirectory\n if (!k.startsWith(normalizedPath)) {\n continue;\n }\n\n // Get the relative path after the directory\n const relative = k.substring(normalizedPath.length);\n\n // If relative path contains '/', it's in a subdirectory\n if (relative.includes(\"/\")) {\n // Extract the immediate subdirectory name\n const subdirName = relative.split(\"/\")[0];\n subdirs.add(normalizedPath + subdirName + \"/\");\n continue;\n }\n\n // This is a file directly in the current directory\n const size = fd.content.join(\"\\n\").length;\n infos.push({\n path: k,\n is_dir: false,\n size: size,\n modified_at: fd.modified_at,\n });\n }\n\n // Add directories to the results\n for (const subdir of Array.from(subdirs).sort()) {\n infos.push({\n path: subdir,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n infos.sort((a, b) => a.path.localeCompare(b.path));\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n read(filePath: string, offset: number = 0, limit: number = 500): string {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return `Error: File '${filePath}' not found`;\n }\n\n return formatReadResponse(fileData, offset, limit);\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult with filesUpdate to update LangGraph state.\n */\n write(filePath: string, content: string): WriteResult {\n const files = this.getFiles();\n\n if (filePath in files) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n const newFileData = createFileData(content);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult with filesUpdate and occurrences.\n */\n edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): EditResult {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const content = fileDataToString(fileData);\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n const newFileData = updateFileData(fileData, newContent);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n occurrences: occurrences,\n };\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): GrepMatch[] | string {\n const files = this.getFiles();\n return grepMatchesFromFiles(files, pattern, path, glob);\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n globInfo(pattern: string, path: string = \"/\"): FileInfo[] {\n const files = this.getFiles();\n const result = globSearchFiles(files, pattern, path);\n\n if (result === \"No files found\") {\n return [];\n }\n\n const paths = result.split(\"\\n\");\n const infos: FileInfo[] = [];\n for (const p of paths) {\n const fd = files[p];\n const size = fd ? fd.content.join(\"\\n\").length : 0;\n infos.push({\n path: p,\n is_dir: false,\n size: size,\n modified_at: fd?.modified_at || \"\",\n });\n }\n return infos;\n }\n\n /**\n * Upload multiple files.\n *\n * Note: Since LangGraph state must be updated via Command objects,\n * the caller must apply filesUpdate via Command after calling this method.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): FileUploadResponse[] & { filesUpdate?: Record<string, FileData> } {\n const responses: FileUploadResponse[] = [];\n const updates: Record<string, FileData> = {};\n\n for (const [path, content] of files) {\n try {\n const contentStr = new TextDecoder().decode(content);\n const fileData = createFileData(contentStr);\n updates[path] = fileData;\n responses.push({ path, error: null });\n } catch {\n responses.push({ path, error: \"invalid_path\" });\n }\n }\n\n // Attach filesUpdate for the caller to apply via Command\n const result = responses as FileUploadResponse[] & {\n filesUpdate?: Record<string, FileData>;\n };\n result.filesUpdate = updates;\n return result;\n }\n\n /**\n * Download multiple files.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n downloadFiles(paths: string[]): FileDownloadResponse[] {\n const files = this.getFiles();\n const responses: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n const fileData = files[path];\n if (!fileData) {\n responses.push({ path, content: null, error: \"file_not_found\" });\n continue;\n }\n\n const contentStr = fileDataToString(fileData);\n const content = new TextEncoder().encode(contentStr);\n responses.push({ path, content, error: null });\n }\n\n return responses;\n }\n}\n","/**\n * Middleware for providing filesystem tools to an agent.\n *\n * Provides ls, read_file, write_file, edit_file, glob, and grep tools with support for:\n * - Pluggable backends (StateBackend, StoreBackend, FilesystemBackend, CompositeBackend)\n * - Tool result eviction for large outputs\n */\n\nimport {\n createMiddleware,\n tool,\n ToolMessage,\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { Command, isCommand, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport { z } from \"zod/v4\";\nimport type {\n BackendProtocol,\n BackendFactory,\n FileData,\n StateAndStore,\n} from \"../backends/protocol.js\";\nimport { isSandboxBackend } from \"../backends/protocol.js\";\nimport { StateBackend } from \"../backends/state.js\";\nimport { sanitizeToolCallId } from \"../backends/utils.js\";\n\n/**\n * required for type inference\n */\nimport type * as _zodTypes from \"@langchain/core/utils/types\";\nimport type * as _zodMeta from \"@langchain/langgraph/zod\";\nimport type * as _messages from \"@langchain/core/messages\";\n\n/**\n * Zod v3 schema for FileData (re-export from backends)\n */\nconst FileDataSchema = z.object({\n content: z.array(z.string()),\n created_at: z.string(),\n modified_at: z.string(),\n});\n\nexport type { FileData };\n\n/**\n * Merge file updates with support for deletions.\n */\nfunction fileDataReducer(\n left: Record<string, FileData> | undefined,\n right: Record<string, FileData | null>,\n): Record<string, FileData> {\n if (left === undefined) {\n const result: Record<string, FileData> = {};\n for (const [key, value] of Object.entries(right)) {\n if (value !== null) {\n result[key] = value;\n }\n }\n return result;\n }\n\n const result = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (value === null) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Shared filesystem state schema.\n * Defined at module level to ensure the same object identity is used across all agents,\n * preventing \"Channel already exists with different type\" errors when multiple agents\n * use createFilesystemMiddleware.\n */\nconst FilesystemStateSchema = z.object({\n files: z\n .record(z.string(), FileDataSchema)\n .default({})\n .meta({\n reducer: {\n fn: fileDataReducer,\n schema: z.record(z.string(), FileDataSchema.nullable()),\n },\n }),\n});\n\n/**\n * Resolve backend from factory or instance.\n *\n * @param backend - Backend instance or factory function\n * @param stateAndStore - State and store container for backend initialization\n */\nfunction getBackend(\n backend: BackendProtocol | BackendFactory,\n stateAndStore: StateAndStore,\n): BackendProtocol {\n if (typeof backend === \"function\") {\n return backend(stateAndStore);\n }\n return backend;\n}\n\n// System prompts\nconst FILESYSTEM_SYSTEM_PROMPT = `You have access to a virtual filesystem. All file paths must start with a /.\n\n- ls: list files in a directory (requires absolute path)\n- read_file: read a file from the filesystem\n- write_file: write to a file in the filesystem\n- edit_file: edit a file in the filesystem\n- glob: find files matching a pattern (e.g., \"**/*.py\")\n- grep: search for text within files`;\n\n// Tool descriptions\nexport const LS_TOOL_DESCRIPTION = \"List files and directories in a directory\";\nexport const READ_FILE_TOOL_DESCRIPTION = \"Read the contents of a file\";\nexport const WRITE_FILE_TOOL_DESCRIPTION =\n \"Write content to a new file. Returns an error if the file already exists\";\nexport const EDIT_FILE_TOOL_DESCRIPTION =\n \"Edit a file by replacing a specific string with a new string\";\nexport const GLOB_TOOL_DESCRIPTION =\n \"Find files matching a glob pattern (e.g., '**/*.py' for all Python files)\";\nexport const GREP_TOOL_DESCRIPTION =\n \"Search for a regex pattern in files. Returns matching files and line numbers\";\nexport const EXECUTE_TOOL_DESCRIPTION = `Executes a given command in the sandbox environment with proper handling and security measures.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use the ls tool to verify the parent directory exists\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes\n - Commands run in an isolated sandbox environment\n - Returns combined stdout/stderr output with exit code\n\nUsage notes:\n - The command parameter is required\n - If the output is very large, it may be truncated\n - IMPORTANT: Avoid using search commands like find and grep. Use the grep, glob tools instead.\n - Avoid read tools like cat, head, tail - use read_file instead.\n - Use '&&' to chain dependent commands, ';' for independent commands\n - Try to use absolute paths to avoid cd`;\n\n// System prompt for execution capability\nexport const EXECUTION_SYSTEM_PROMPT = `## Execute Tool \\`execute\\`\n\nYou have access to an \\`execute\\` tool for running shell commands in a sandboxed environment.\nUse this tool to run commands, scripts, tests, builds, and other shell operations.\n\n- execute: run a shell command in the sandbox (returns output and exit code)`;\n\n/**\n * Create ls tool using backend.\n */\nfunction createLsTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const path = input.path || \"/\";\n const infos = await resolvedBackend.lsInfo(path);\n\n if (infos.length === 0) {\n return `No files found in ${path}`;\n }\n\n // Format output\n const lines: string[] = [];\n for (const info of infos) {\n if (info.is_dir) {\n lines.push(`${info.path} (directory)`);\n } else {\n const size = info.size ? ` (${info.size} bytes)` : \"\";\n lines.push(`${info.path}${size}`);\n }\n }\n return lines.join(\"\\n\");\n },\n {\n name: \"ls\",\n description: customDescription || LS_TOOL_DESCRIPTION,\n schema: z.object({\n path: z\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Directory path to list (default: /)\"),\n }),\n },\n );\n}\n\n/**\n * Create read_file tool using backend.\n */\nfunction createReadFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { file_path, offset = 0, limit = 500 } = input;\n return await resolvedBackend.read(file_path, offset, limit);\n },\n {\n name: \"read_file\",\n description: customDescription || READ_FILE_TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to read\"),\n offset: z.coerce\n .number()\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from (0-indexed)\"),\n limit: z.coerce\n .number()\n .optional()\n .default(500)\n .describe(\"Maximum number of lines to read\"),\n }),\n },\n );\n}\n\n/**\n * Create write_file tool using backend.\n */\nfunction createWriteFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { file_path, content } = input;\n const result = await resolvedBackend.write(file_path, content);\n\n if (result.error) {\n return result.error;\n }\n\n // If filesUpdate is present, return Command to update state\n const message = new ToolMessage({\n content: `Successfully wrote to '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"write_file\",\n metadata: result.metadata,\n });\n\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n return message;\n },\n {\n name: \"write_file\",\n description: customDescription || WRITE_FILE_TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to write\"),\n content: z.string().describe(\"Content to write to the file\"),\n }),\n },\n );\n}\n\n/**\n * Create edit_file tool using backend.\n */\nfunction createEditFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { file_path, old_string, new_string, replace_all = false } = input;\n const result = await resolvedBackend.edit(\n file_path,\n old_string,\n new_string,\n replace_all,\n );\n\n if (result.error) {\n return result.error;\n }\n\n const message = new ToolMessage({\n content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"edit_file\",\n metadata: result.metadata,\n });\n\n // If filesUpdate is present, return Command to update state\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n // External storage (filesUpdate is null)\n return message;\n },\n {\n name: \"edit_file\",\n description: customDescription || EDIT_FILE_TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to edit\"),\n old_string: z\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z.string().describe(\"String to replace with\"),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n },\n );\n}\n\n/**\n * Create glob tool using backend.\n */\nfunction createGlobTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { pattern, path = \"/\" } = input;\n const infos = await resolvedBackend.globInfo(pattern, path);\n\n if (infos.length === 0) {\n return `No files found matching pattern '${pattern}'`;\n }\n\n return infos.map((info) => info.path).join(\"\\n\");\n },\n {\n name: \"glob\",\n description: customDescription || GLOB_TOOL_DESCRIPTION,\n schema: z.object({\n pattern: z.string().describe(\"Glob pattern (e.g., '*.py', '**/*.ts')\"),\n path: z\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n }),\n },\n );\n}\n\n/**\n * Create grep tool using backend.\n */\nfunction createGrepTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const { pattern, path = \"/\", glob = null } = input;\n const result = await resolvedBackend.grepRaw(pattern, path, glob);\n\n // If string, it's an error\n if (typeof result === \"string\") {\n return result;\n }\n\n if (result.length === 0) {\n return `No matches found for pattern '${pattern}'`;\n }\n\n // Format output: group by file\n const lines: string[] = [];\n let currentFile: string | null = null;\n for (const match of result) {\n if (match.path !== currentFile) {\n currentFile = match.path;\n lines.push(`\\n${currentFile}:`);\n }\n lines.push(` ${match.line}: ${match.text}`);\n }\n\n return lines.join(\"\\n\");\n },\n {\n name: \"grep\",\n description: customDescription || GREP_TOOL_DESCRIPTION,\n schema: z.object({\n pattern: z.string().describe(\"Regex pattern to search for\"),\n path: z\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n glob: z\n .string()\n .optional()\n .nullable()\n .describe(\"Optional glob pattern to filter files (e.g., '*.py')\"),\n }),\n },\n );\n}\n\n/**\n * Create execute tool using backend.\n */\nfunction createExecuteTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined },\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n\n // Runtime check - fail gracefully if not supported\n if (!isSandboxBackend(resolvedBackend)) {\n return (\n \"Error: Execution not available. This agent's backend \" +\n \"does not support command execution (SandboxBackendProtocol). \" +\n \"To use the execute tool, provide a backend that implements SandboxBackendProtocol.\"\n );\n }\n\n const result = await resolvedBackend.execute(input.command);\n\n // Format output for LLM consumption\n const parts = [result.output];\n\n if (result.exitCode !== null) {\n const status = result.exitCode === 0 ? \"succeeded\" : \"failed\";\n parts.push(`\\n[Command ${status} with exit code ${result.exitCode}]`);\n }\n\n if (result.truncated) {\n parts.push(\"\\n[Output was truncated due to size limits]\");\n }\n\n return parts.join(\"\");\n },\n {\n name: \"execute\",\n description: customDescription || EXECUTE_TOOL_DESCRIPTION,\n schema: z.object({\n command: z.string().describe(\"The shell command to execute\"),\n }),\n },\n );\n}\n\n/**\n * Options for creating filesystem middleware.\n */\nexport interface FilesystemMiddlewareOptions {\n /** Backend instance or factory (default: StateBackend) */\n backend?: BackendProtocol | BackendFactory;\n /** Optional custom system prompt override */\n systemPrompt?: string | null;\n /** Optional custom tool descriptions override */\n customToolDescriptions?: Record<string, string> | null;\n /** Optional token limit before evicting a tool result to the filesystem (default: 20000 tokens, ~80KB) */\n toolTokenLimitBeforeEvict?: number | null;\n}\n\n/**\n * Create filesystem middleware with all tools and features.\n */\nexport function createFilesystemMiddleware(\n options: FilesystemMiddlewareOptions = {},\n) {\n const {\n backend = (stateAndStore: StateAndStore) => new StateBackend(stateAndStore),\n systemPrompt: customSystemPrompt = null,\n customToolDescriptions = null,\n toolTokenLimitBeforeEvict = 20000,\n } = options;\n\n const baseSystemPrompt = customSystemPrompt || FILESYSTEM_SYSTEM_PROMPT;\n\n // All tools including execute (execute will be filtered at runtime if backend doesn't support it)\n const allTools = [\n createLsTool(backend, {\n customDescription: customToolDescriptions?.ls,\n }),\n createReadFileTool(backend, {\n customDescription: customToolDescriptions?.read_file,\n }),\n createWriteFileTool(backend, {\n customDescription: customToolDescriptions?.write_file,\n }),\n createEditFileTool(backend, {\n customDescription: customToolDescriptions?.edit_file,\n }),\n createGlobTool(backend, {\n customDescription: customToolDescriptions?.glob,\n }),\n createGrepTool(backend, {\n customDescription: customToolDescriptions?.grep,\n }),\n createExecuteTool(backend, {\n customDescription: customToolDescriptions?.execute,\n }),\n ];\n\n return createMiddleware({\n name: \"FilesystemMiddleware\",\n stateSchema: FilesystemStateSchema,\n tools: allTools,\n wrapModelCall: async (request, handler) => {\n // Check if backend supports execution\n const stateAndStore: StateAndStore = {\n state: request.state || {},\n // @ts-expect-error - request.config is incorrect typed\n store: request.config?.store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const supportsExecution = isSandboxBackend(resolvedBackend);\n\n // Filter tools based on backend capabilities\n let tools = request.tools;\n if (!supportsExecution) {\n tools = tools.filter((t: { name: string }) => t.name !== \"execute\");\n }\n\n // Build system prompt - add execution instructions if available\n let systemPrompt = baseSystemPrompt;\n if (supportsExecution) {\n systemPrompt = `${systemPrompt}\\n\\n${EXECUTION_SYSTEM_PROMPT}`;\n }\n\n // Combine with existing system prompt\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${currentSystemPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n\n return handler({ ...request, tools, systemPrompt: newSystemPrompt });\n },\n wrapToolCall: toolTokenLimitBeforeEvict\n ? async (request, handler) => {\n const result = await handler(request);\n\n async function processToolMessage(msg: ToolMessage) {\n if (\n typeof msg.content === \"string\" &&\n msg.content.length > toolTokenLimitBeforeEvict! * 4\n ) {\n // Build StateAndStore from request\n const stateAndStore: StateAndStore = {\n state: request.state || {},\n // @ts-expect-error - request.config is incorrect typed\n store: request.config?.store,\n };\n const resolvedBackend = getBackend(backend, stateAndStore);\n const sanitizedId = sanitizeToolCallId(\n request.toolCall?.id || msg.tool_call_id,\n );\n const evictPath = `/large_tool_results/${sanitizedId}`;\n\n const writeResult = await resolvedBackend.write(\n evictPath,\n msg.content,\n );\n\n if (writeResult.error) {\n return { message: msg, filesUpdate: null };\n }\n\n const truncatedMessage = new ToolMessage({\n content: `Tool result too large (${Math.round(msg.content.length / 4)} tokens). Content saved to ${evictPath}`,\n tool_call_id: msg.tool_call_id,\n name: msg.name,\n });\n\n return {\n message: truncatedMessage,\n filesUpdate: writeResult.filesUpdate,\n };\n }\n return { message: msg, filesUpdate: null };\n }\n\n if (ToolMessage.isInstance(result)) {\n const processed = await processToolMessage(result);\n\n if (processed.filesUpdate) {\n return new Command({\n update: {\n files: processed.filesUpdate,\n messages: [processed.message],\n },\n });\n }\n\n return processed.message;\n }\n\n if (isCommand(result)) {\n const update = result.update as any;\n if (!update?.messages) {\n return result;\n }\n\n let hasLargeResults = false;\n const accumulatedFiles: Record<string, FileData> = {\n ...(update.files || {}),\n };\n const processedMessages: ToolMessage[] = [];\n\n for (const msg of update.messages) {\n if (ToolMessage.isInstance(msg)) {\n const processed = await processToolMessage(msg);\n processedMessages.push(processed.message);\n\n if (processed.filesUpdate) {\n hasLargeResults = true;\n Object.assign(accumulatedFiles, processed.filesUpdate);\n }\n } else {\n processedMessages.push(msg);\n }\n }\n\n if (hasLargeResults) {\n return new Command({\n update: {\n ...update,\n messages: processedMessages,\n files: accumulatedFiles,\n },\n });\n }\n }\n\n return result;\n }\n : undefined,\n });\n}\n","import { z } from \"zod/v3\";\nimport {\n createMiddleware,\n createAgent,\n AgentMiddleware,\n tool,\n ToolMessage,\n humanInTheLoopMiddleware,\n SystemMessage,\n type InterruptOnConfig,\n type ReactAgent,\n StructuredTool,\n} from \"langchain\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport { HumanMessage } from \"@langchain/core/messages\";\n\nexport type { AgentMiddleware };\n\n// Constants\nconst DEFAULT_SUBAGENT_PROMPT =\n \"In order to complete the objective that the user asks of you, you have access to a number of standard tools.\";\n\n// State keys that are excluded when passing state to subagents and when returning\n// updates from subagents.\n// When returning updates:\n// 1. The messages key is handled explicitly to ensure only the final message is included\n// 2. The todos and structuredResponse keys are excluded as they do not have a defined reducer\n// and no clear meaning for returning them from a subagent to the main agent.\n// 3. The files key is excluded to prevent concurrent subagents from writing to the files\n// channel simultaneously (which causes LastValue errors in LangGraph).\nconst EXCLUDED_STATE_KEYS = [\n \"messages\",\n \"todos\",\n \"structuredResponse\",\n \"files\",\n] as const;\n\nconst DEFAULT_GENERAL_PURPOSE_DESCRIPTION =\n \"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.\";\n\n// Comprehensive task tool description from Python\nfunction getTaskToolDescription(subagentDescriptions: string[]): string {\n return `\nLaunch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.\n\nAvailable agent types and the tools they have access to:\n${subagentDescriptions.join(\"\\n\")}\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## Usage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.\n\n### Example usage of the general-purpose agent:\n\n<example_agent_descriptions>\n\"general-purpose\": use this agent for general purpose tasks, it has access to all tools as the main agent.\n</example_agent_descriptions>\n\n<example>\nUser: \"I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them.\"\nAssistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*\nAssistant: *Synthesizes the results of the three isolated research tasks and responds to the User*\n<commentary>\nResearch is a complex, multi-step task in it of itself.\nThe research of each individual player is not dependent on the research of the other players.\nThe assistant uses the task tool to break down the complex objective into three isolated tasks.\nEach research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.\nThis means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.\n</commentary>\n</example>\n\n<example>\nUser: \"Analyze a single large code repository for security vulnerabilities and generate a report.\"\nAssistant: *Launches a single \\`task\\` subagent for the repository analysis*\nAssistant: *Receives report and integrates results into final summary*\n<commentary>\nSubagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.\nIf the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.\n</commentary>\n</example>\n\n<example>\nUser: \"Schedule two meetings for me and prepare agendas for each.\"\nAssistant: *Calls the task tool in parallel to launch two \\`task\\` subagents (one per meeting) to prepare agendas*\nAssistant: *Returns final schedules and agendas*\n<commentary>\nTasks are simple individually, but subagents help silo agenda preparation.\nEach subagent only needs to worry about the agenda for one meeting.\n</commentary>\n</example>\n\n<example>\nUser: \"I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\"\nAssistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*\n<commentary>\nThe assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.\nIt is better to just complete the task directly and NOT use the \\`task\\`tool.\n</commentary>\n</example>\n\n### Example usage with custom agents:\n\n<example_agent_descriptions>\n\"content-reviewer\": use this agent after you are done creating significant content or documents\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n\"research-analyst\": use this agent to conduct thorough research on complex topics\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I'm going to use the Write tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince significant content was created and the task was completed, now use the content-reviewer agent to review the work\n</commentary>\nassistant: Now let me use the content-reviewer agent to review the code\nassistant: Uses the Task tool to launch with the content-reviewer agent\n</example>\n\n<example>\nuser: \"Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?\"\n<commentary>\nThis is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis\n</commentary>\nassistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.\nassistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take\n</example>\n\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the Task tool to launch with the greeting-responder agent\"\n</example>\n `.trim();\n}\n\nconst TASK_SYSTEM_PROMPT = `## \\`task\\` (subagent spawner)\n\nYou have access to a \\`task\\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.\n\nWhen to use the task tool:\n- When a task is complex and multi-step, and can be fully delegated in isolation\n- When a task is independent of other tasks and can run in parallel\n- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread\n- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)\n- When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)\n\nSubagent lifecycle:\n1. **Spawn** → Provide clear role, instructions, and expected output\n2. **Run** → The subagent completes the task autonomously\n3. **Return** → The subagent provides a single structured result\n4. **Reconcile** → Incorporate or synthesize the result into the main thread\n\nWhen NOT to use the task tool:\n- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)\n- If the task is trivial (a few tool calls or simple lookup)\n- If delegating does not reduce token usage, complexity, or context switching\n- If splitting would add latency without benefit\n\n## Important Task Tool Usage Notes to Remember\n- Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.\n- Remember to use the \\`task\\` tool to silo independent tasks within a multi-part objective.\n- You should use the \\`task\\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.`;\n\n/**\n * Type definitions for pre-compiled agents.\n *\n * @typeParam TRunnable - The type of the runnable (ReactAgent or Runnable).\n * When using `createAgent`, this preserves the middleware types for type inference.\n */\nexport interface CompiledSubAgent<\n TRunnable extends ReactAgent | Runnable = ReactAgent | Runnable,\n> {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The agent instance */\n runnable: TRunnable;\n}\n\n/**\n * Type definitions for subagents\n */\nexport interface SubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The system prompt to use for the agent */\n systemPrompt: string;\n /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */\n tools?: StructuredTool[];\n /** The model for the agent. Defaults to default_model */\n model?: LanguageModelLike | string;\n /** Additional middleware to append after default_middleware */\n middleware?: readonly AgentMiddleware[];\n /** The tool configs to use for the agent */\n interruptOn?: Record<string, boolean | InterruptOnConfig>;\n}\n\n/**\n * Filter state to exclude certain keys when passing to subagents\n */\nfunction filterStateForSubagent(\n state: Record<string, unknown>,\n): Record<string, unknown> {\n const filtered: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(state)) {\n if (!EXCLUDED_STATE_KEYS.includes(key as never)) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n\n/**\n * Create Command with filtered state update from subagent result\n */\nfunction returnCommandWithStateUpdate(\n result: Record<string, unknown>,\n toolCallId: string,\n): Command {\n const stateUpdate = filterStateForSubagent(result);\n const messages = result.messages as Array<{ content: string }>;\n const lastMessage = messages?.[messages.length - 1];\n\n return new Command({\n update: {\n ...stateUpdate,\n messages: [\n new ToolMessage({\n content: lastMessage?.content || \"Task completed\",\n tool_call_id: toolCallId,\n name: \"task\",\n }),\n ],\n },\n });\n}\n\n/**\n * Create subagent instances from specifications\n */\nfunction getSubagents(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n}): {\n agents: Record<string, ReactAgent | Runnable>;\n descriptions: string[];\n} {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n } = options;\n\n const defaultSubagentMiddleware = defaultMiddleware || [];\n const agents: Record<string, ReactAgent | Runnable> = {};\n const subagentDescriptions: string[] = [];\n\n // Create general-purpose agent if enabled\n if (generalPurposeAgent) {\n const generalPurposeMiddleware = [...defaultSubagentMiddleware];\n if (defaultInterruptOn) {\n generalPurposeMiddleware.push(\n humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn }),\n );\n }\n\n const generalPurposeSubagent = createAgent({\n model: defaultModel,\n systemPrompt: DEFAULT_SUBAGENT_PROMPT,\n tools: defaultTools as any,\n middleware: generalPurposeMiddleware,\n });\n\n agents[\"general-purpose\"] = generalPurposeSubagent;\n subagentDescriptions.push(\n `- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`,\n );\n }\n\n // Process custom subagents\n for (const agentParams of subagents) {\n subagentDescriptions.push(\n `- ${agentParams.name}: ${agentParams.description}`,\n );\n\n if (\"runnable\" in agentParams) {\n agents[agentParams.name] = agentParams.runnable;\n } else {\n const middleware = agentParams.middleware\n ? [...defaultSubagentMiddleware, ...agentParams.middleware]\n : [...defaultSubagentMiddleware];\n\n const interruptOn = agentParams.interruptOn || defaultInterruptOn;\n if (interruptOn)\n middleware.push(humanInTheLoopMiddleware({ interruptOn }));\n\n agents[agentParams.name] = createAgent({\n model: agentParams.model ?? defaultModel,\n systemPrompt: agentParams.systemPrompt,\n tools: agentParams.tools ?? defaultTools,\n middleware,\n });\n }\n }\n\n return { agents, descriptions: subagentDescriptions };\n}\n\n/**\n * Create the task tool for invoking subagents\n */\nfunction createTaskTool(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n taskDescription: string | null;\n}) {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n } = options;\n\n const { agents: subagentGraphs, descriptions: subagentDescriptions } =\n getSubagents({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n });\n\n const finalTaskDescription = taskDescription\n ? taskDescription\n : getTaskToolDescription(subagentDescriptions);\n\n return tool(\n async (\n input: { description: string; subagent_type: string },\n config,\n ): Promise<Command | string> => {\n const { description, subagent_type } = input;\n\n // Validate subagent type\n if (!(subagent_type in subagentGraphs)) {\n const allowedTypes = Object.keys(subagentGraphs)\n .map((k) => `\\`${k}\\``)\n .join(\", \");\n throw new Error(\n `Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`,\n );\n }\n\n const subagent = subagentGraphs[subagent_type];\n\n // Get current state and filter it for subagent\n const currentState = getCurrentTaskInput<Record<string, unknown>>();\n const subagentState = filterStateForSubagent(currentState);\n subagentState.messages = [new HumanMessage({ content: description })];\n\n // Invoke the subagent\n const result = (await subagent.invoke(subagentState, config)) as Record<\n string,\n unknown\n >;\n\n // Return command with filtered state update\n if (!config.toolCall?.id) {\n throw new Error(\"Tool call ID is required for subagent invocation\");\n }\n\n return returnCommandWithStateUpdate(result, config.toolCall.id);\n },\n {\n name: \"task\",\n description: finalTaskDescription,\n schema: z.object({\n description: z\n .string()\n .describe(\"The task to execute with the selected agent\"),\n subagent_type: z\n .string()\n .describe(\n `Name of the agent to use. Available: ${Object.keys(subagentGraphs).join(\", \")}`,\n ),\n }),\n },\n );\n}\n\n/**\n * Options for creating subagent middleware\n */\nexport interface SubAgentMiddlewareOptions {\n /** The model to use for subagents */\n defaultModel: LanguageModelLike | string;\n /** The tools to use for the default general-purpose subagent */\n defaultTools?: StructuredTool[];\n /** Default middleware to apply to all subagents */\n defaultMiddleware?: AgentMiddleware[] | null;\n /** The tool configs for the default general-purpose subagent */\n defaultInterruptOn?: Record<string, boolean | InterruptOnConfig> | null;\n /** A list of additional subagents to provide to the agent */\n subagents?: (SubAgent | CompiledSubAgent)[];\n /** Full system prompt override */\n systemPrompt?: string | null;\n /** Whether to include the general-purpose agent */\n generalPurposeAgent?: boolean;\n /** Custom description for the task tool */\n taskDescription?: string | null;\n}\n\n/**\n * Create subagent middleware with task tool\n */\nexport function createSubAgentMiddleware(options: SubAgentMiddlewareOptions) {\n const {\n defaultModel,\n defaultTools = [],\n defaultMiddleware = null,\n defaultInterruptOn = null,\n subagents = [],\n systemPrompt = TASK_SYSTEM_PROMPT,\n generalPurposeAgent = true,\n taskDescription = null,\n } = options;\n\n const taskTool = createTaskTool({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n });\n\n return createMiddleware({\n name: \"subAgentMiddleware\",\n tools: [taskTool],\n wrapModelCall: async (request, handler) => {\n if (systemPrompt !== null) {\n return handler({\n ...request,\n systemMessage: request.systemMessage.concat(\n new SystemMessage({ content: systemPrompt }),\n ),\n });\n }\n return handler(request);\n },\n });\n}\n","import {\n createMiddleware,\n ToolMessage,\n AIMessage,\n /**\n * required for type inference\n */\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { RemoveMessage } from \"@langchain/core/messages\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\n\n/**\n * Create middleware that patches dangling tool calls in the messages history.\n *\n * When an AI message contains tool_calls but subsequent messages don't include\n * the corresponding ToolMessage responses, this middleware adds synthetic\n * ToolMessages saying the tool call was cancelled.\n *\n * @returns AgentMiddleware that patches dangling tool calls\n *\n * @example\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { createPatchToolCallsMiddleware } from \"./middleware/patch_tool_calls\";\n *\n * const agent = createAgent({\n * model: \"claude-sonnet-4-5-20250929\",\n * middleware: [createPatchToolCallsMiddleware()],\n * });\n * ```\n */\nexport function createPatchToolCallsMiddleware() {\n return createMiddleware({\n name: \"patchToolCallsMiddleware\",\n beforeAgent: async (state) => {\n const messages = state.messages;\n\n if (!messages || messages.length === 0) {\n return;\n }\n\n const patchedMessages: any[] = [];\n\n // Iterate over the messages and add any dangling tool calls\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n patchedMessages.push(msg);\n\n // Check if this is an AI message with tool calls\n if (AIMessage.isInstance(msg) && msg.tool_calls != null) {\n for (const toolCall of msg.tool_calls) {\n // Look for a corresponding ToolMessage in the messages after this one\n const correspondingToolMsg = messages\n .slice(i)\n .find(\n (m: any) =>\n ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id,\n );\n\n if (!correspondingToolMsg) {\n // We have a dangling tool call which needs a ToolMessage\n const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`;\n patchedMessages.push(\n new ToolMessage({\n content: toolMsg,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n }),\n );\n }\n }\n }\n }\n\n // Return state update with RemoveMessage followed by patched messages\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n ...patchedMessages,\n ],\n };\n },\n });\n}\n","/**\n * Middleware for loading agent memory/context from AGENTS.md files.\n *\n * This module implements support for the AGENTS.md specification (https://agents.md/),\n * loading memory/context from configurable sources and injecting into the system prompt.\n *\n * ## Overview\n *\n * AGENTS.md files provide project-specific context and instructions to help AI agents\n * work effectively. Unlike skills (which are on-demand workflows), memory is always\n * loaded and provides persistent context.\n *\n * ## Usage\n *\n * ```typescript\n * import { createMemoryMiddleware } from \"@anthropic/deepagents\";\n * import { FilesystemBackend } from \"@anthropic/deepagents\";\n *\n * // Security: FilesystemBackend allows reading/writing from the entire filesystem.\n * // Either ensure the agent is running within a sandbox OR add human-in-the-loop (HIL)\n * // approval to file operations.\n * const backend = new FilesystemBackend({ rootDir: \"/\" });\n *\n * const middleware = createMemoryMiddleware({\n * backend,\n * sources: [\n * \"~/.deepagents/AGENTS.md\",\n * \"./.deepagents/AGENTS.md\",\n * ],\n * });\n *\n * const agent = createDeepAgent({ middleware: [middleware] });\n * ```\n *\n * ## Memory Sources\n *\n * Sources are simply paths to AGENTS.md files that are loaded in order and combined.\n * Multiple sources are concatenated in order, with all content included.\n * Later sources appear after earlier ones in the combined prompt.\n *\n * ## File Format\n *\n * AGENTS.md files are standard Markdown with no required structure.\n * Common sections include:\n * - Project overview\n * - Build/test commands\n * - Code style guidelines\n * - Architecture notes\n */\n\nimport { z } from \"zod\";\nimport {\n createMiddleware,\n /**\n * required for type inference\n */\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\n\nimport type { BackendProtocol, BackendFactory } from \"../backends/protocol.js\";\nimport type { StateBackend } from \"../backends/state.js\";\nimport type { BaseStore } from \"@langchain/langgraph-checkpoint\";\n\n/**\n * Options for the memory middleware.\n */\nexport interface MemoryMiddlewareOptions {\n /**\n * Backend instance or factory function for file operations.\n * Use a factory for StateBackend since it requires runtime state.\n */\n backend:\n | BackendProtocol\n | BackendFactory\n | ((config: { state: unknown; store?: BaseStore }) => StateBackend);\n\n /**\n * List of memory file paths to load (e.g., [\"~/.deepagents/AGENTS.md\", \"./.deepagents/AGENTS.md\"]).\n * Display names are automatically derived from the paths.\n * Sources are loaded in order.\n */\n sources: string[];\n}\n\n/**\n * State schema for memory middleware.\n */\nconst MemoryStateSchema = z.object({\n /**\n * Dict mapping source paths to their loaded content.\n * Marked as private so it's not included in the final agent state.\n */\n memoryContents: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Default system prompt template for memory.\n * Ported from Python's comprehensive memory guidelines.\n */\nconst MEMORY_SYSTEM_PROMPT = `<agent_memory>\n{memory_contents}\n</agent_memory>\n\n<memory_guidelines>\n The above <agent_memory> was loaded in from files in your filesystem. As you learn from your interactions with the user, you can save new knowledge by calling the \\`edit_file\\` tool.\n\n **Learning from feedback:**\n - One of your MAIN PRIORITIES is to learn from your interactions with the user. These learnings can be implicit or explicit. This means that in the future, you will remember this important information.\n - When you need to remember something, updating memory must be your FIRST, IMMEDIATE action - before responding to the user, before calling other tools, before doing anything else. Just update memory immediately.\n - When user says something is better/worse, capture WHY and encode it as a pattern.\n - Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions.\n - A great opportunity to update your memories is when the user interrupts a tool call and provides feedback. You should update your memories immediately before revising the tool call.\n - Look for the underlying principle behind corrections, not just the specific mistake.\n - The user might not explicitly ask you to remember something, but if they provide information that is useful for future use, you should update your memories immediately.\n\n **Asking for information:**\n - If you lack context to perform an action (e.g. send a Slack DM, requires a user ID/email) you should explicitly ask the user for this information.\n - It is preferred for you to ask for information, don't assume anything that you do not know!\n - When the user provides information that is useful for future use, you should update your memories immediately.\n\n **When to update memories:**\n - When the user explicitly asks you to remember something (e.g., \"remember my email\", \"save this preference\")\n - When the user describes your role or how you should behave (e.g., \"you are a web researcher\", \"always do X\")\n - When the user gives feedback on your work - capture what was wrong and how to improve\n - When the user provides information required for tool use (e.g., slack channel ID, email addresses)\n - When the user provides context useful for future tasks, such as how to use tools, or which actions to take in a particular situation\n - When you discover new patterns or preferences (coding styles, conventions, workflows)\n\n **When to NOT update memories:**\n - When the information is temporary or transient (e.g., \"I'm running late\", \"I'm on my phone right now\")\n - When the information is a one-time task request (e.g., \"Find me a recipe\", \"What's 25 * 4?\")\n - When the information is a simple question that doesn't reveal lasting preferences (e.g., \"What day is it?\", \"Can you explain X?\")\n - When the information is an acknowledgment or small talk (e.g., \"Sounds good!\", \"Hello\", \"Thanks for that\")\n - When the information is stale or irrelevant in future conversations\n - Never store API keys, access tokens, passwords, or any other credentials in any file, memory, or system prompt.\n - If the user asks where to put API keys or provides an API key, do NOT echo or save it.\n\n **Examples:**\n Example 1 (remembering user information):\n User: Can you connect to my google account?\n Agent: Sure, I'll connect to your google account, what's your google account email?\n User: john@example.com\n Agent: Let me save this to my memory.\n Tool Call: edit_file(...) -> remembers that the user's google account email is john@example.com\n\n Example 2 (remembering implicit user preferences):\n User: Can you write me an example for creating a deep agent in LangChain?\n Agent: Sure, I'll write you an example for creating a deep agent in LangChain <example code in Python>\n User: Can you do this in JavaScript\n Agent: Let me save this to my memory.\n Tool Call: edit_file(...) -> remembers that the user prefers to get LangChain code examples in JavaScript\n Agent: Sure, here is the JavaScript example<example code in JavaScript>\n\n Example 3 (do not remember transient information):\n User: I'm going to play basketball tonight so I will be offline for a few hours.\n Agent: Okay I'll add a block to your calendar.\n Tool Call: create_calendar_event(...) -> just calls a tool, does not commit anything to memory, as it is transient information\n</memory_guidelines>`;\n\n/**\n * Format loaded memory contents for injection into prompt.\n * Pairs memory locations with their contents for clarity.\n */\nfunction formatMemoryContents(\n contents: Record<string, string>,\n sources: string[],\n): string {\n if (Object.keys(contents).length === 0) {\n return \"(No memory loaded)\";\n }\n\n const sections: string[] = [];\n for (const path of sources) {\n if (contents[path]) {\n sections.push(`${path}\\n${contents[path]}`);\n }\n }\n\n if (sections.length === 0) {\n return \"(No memory loaded)\";\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/**\n * Load memory content from a backend path.\n *\n * @param backend - Backend to load from.\n * @param path - Path to the AGENTS.md file.\n * @returns File content if found, null otherwise.\n */\nasync function loadMemoryFromBackend(\n backend: BackendProtocol,\n path: string,\n): Promise<string | null> {\n const results = await backend.downloadFiles([path]);\n\n // Should get exactly one response for one path\n if (results.length !== 1) {\n throw new Error(\n `Expected 1 response for path ${path}, got ${results.length}`,\n );\n }\n const response = results[0];\n\n if (response.error != null) {\n // For now, memory files are treated as optional. file_not_found is expected\n // and we skip silently to allow graceful degradation.\n if (response.error === \"file_not_found\") {\n return null;\n }\n // Other errors should be raised\n throw new Error(`Failed to download ${path}: ${response.error}`);\n }\n\n if (response.content != null) {\n // Content is a Uint8Array, decode to string\n return new TextDecoder().decode(response.content);\n }\n\n return null;\n}\n\n/**\n * Create middleware for loading agent memory from AGENTS.md files.\n *\n * Loads memory content from configured sources and injects into the system prompt.\n * Supports multiple sources that are combined together.\n *\n * @param options - Configuration options\n * @returns AgentMiddleware for memory loading and injection\n *\n * @example\n * ```typescript\n * const middleware = createMemoryMiddleware({\n * backend: new FilesystemBackend({ rootDir: \"/\" }),\n * sources: [\n * \"~/.deepagents/AGENTS.md\",\n * \"./.deepagents/AGENTS.md\",\n * ],\n * });\n * ```\n */\nexport function createMemoryMiddleware(options: MemoryMiddlewareOptions) {\n const { backend, sources } = options;\n\n /**\n * Resolve backend from instance or factory.\n */\n function getBackend(state: unknown): BackendProtocol {\n if (typeof backend === \"function\") {\n // It's a factory - call it with state\n return backend({ state }) as BackendProtocol;\n }\n return backend;\n }\n\n return createMiddleware({\n name: \"MemoryMiddleware\",\n stateSchema: MemoryStateSchema,\n\n async beforeAgent(state) {\n // Skip if already loaded\n if (\"memoryContents\" in state && state.memoryContents != null) {\n return undefined;\n }\n\n const resolvedBackend = getBackend(state);\n const contents: Record<string, string> = {};\n\n for (const path of sources) {\n try {\n const content = await loadMemoryFromBackend(resolvedBackend, path);\n if (content) {\n contents[path] = content;\n }\n } catch (error) {\n // Log but continue - memory is optional\n // eslint-disable-next-line no-console\n console.debug(`Failed to load memory from ${path}:`, error);\n }\n }\n\n return { memoryContents: contents };\n },\n\n wrapModelCall(request, handler) {\n // Get memory contents from state\n const memoryContents: Record<string, string> =\n request.state?.memoryContents || {};\n\n // Format memory section\n const formattedContents = formatMemoryContents(memoryContents, sources);\n\n const memorySection = MEMORY_SYSTEM_PROMPT.replace(\n \"{memory_contents}\",\n formattedContents,\n );\n\n // Prepend memory section to system prompt\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${memorySection}\\n\\n${currentSystemPrompt}`\n : memorySection;\n\n return handler({ ...request, systemPrompt: newSystemPrompt });\n },\n });\n}\n","/* eslint-disable no-console */\n/**\n * Backend-agnostic skills middleware for loading agent skills from any backend.\n *\n * This middleware implements Anthropic's agent skills pattern with progressive disclosure,\n * loading skills from backend storage via configurable sources.\n *\n * ## Architecture\n *\n * Skills are loaded from one or more **sources** - paths in a backend where skills are\n * organized. Sources are loaded in order, with later sources overriding earlier ones\n * when skills have the same name (last one wins). This enables layering: base -> user\n * -> project -> team skills.\n *\n * The middleware uses backend APIs exclusively (no direct filesystem access), making it\n * portable across different storage backends (filesystem, state, remote storage, etc.).\n *\n * ## Usage\n *\n * ```typescript\n * import { createSkillsMiddleware, FilesystemBackend } from \"@anthropic/deepagents\";\n *\n * const middleware = createSkillsMiddleware({\n * backend: new FilesystemBackend({ rootDir: \"/\" }),\n * sources: [\n * \"/skills/user/\",\n * \"/skills/project/\",\n * ],\n * });\n *\n * const agent = createDeepAgent({ middleware: [middleware] });\n * ```\n *\n * Or use the `skills` parameter on createDeepAgent:\n *\n * ```typescript\n * const agent = createDeepAgent({\n * skills: [\"/skills/user/\", \"/skills/project/\"],\n * });\n * ```\n */\n\nimport { z } from \"zod\";\nimport yaml from \"yaml\";\nimport {\n createMiddleware,\n /**\n * required for type inference\n */\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\n\nimport type { BackendProtocol, BackendFactory } from \"../backends/protocol.js\";\nimport type { StateBackend } from \"../backends/state.js\";\nimport type { BaseStore } from \"@langchain/langgraph-checkpoint\";\n\n// Security: Maximum size for SKILL.md files to prevent DoS attacks (10MB)\nexport const MAX_SKILL_FILE_SIZE = 10 * 1024 * 1024;\n\n// Agent Skills specification constraints (https://agentskills.io/specification)\nexport const MAX_SKILL_NAME_LENGTH = 64;\nexport const MAX_SKILL_DESCRIPTION_LENGTH = 1024;\n\n/**\n * Metadata for a skill per Agent Skills specification.\n */\nexport interface SkillMetadata {\n /** Skill identifier (max 64 chars, lowercase alphanumeric and hyphens) */\n name: string;\n\n /** What the skill does (max 1024 chars) */\n description: string;\n\n /** Path to the SKILL.md file in the backend */\n path: string;\n\n /** License name or reference to bundled license file */\n license?: string | null;\n\n /** Environment requirements (max 500 chars) */\n compatibility?: string | null;\n\n /** Arbitrary key-value mapping for additional metadata */\n metadata?: Record<string, string>;\n\n /** List of pre-approved tools (experimental) */\n allowedTools?: string[];\n}\n\n/**\n * Options for the skills middleware.\n */\nexport interface SkillsMiddlewareOptions {\n /**\n * Backend instance or factory function for file operations.\n * Use a factory for StateBackend since it requires runtime state.\n */\n backend:\n | BackendProtocol\n | BackendFactory\n | ((config: { state: unknown; store?: BaseStore }) => StateBackend);\n\n /**\n * List of skill source paths to load (e.g., [\"/skills/user/\", \"/skills/project/\"]).\n * Paths must use POSIX conventions (forward slashes).\n * Later sources override earlier ones for skills with the same name (last one wins).\n */\n sources: string[];\n}\n\n/**\n * State schema for skills middleware.\n */\nconst SkillsStateSchema = z.object({\n skillsMetadata: z\n .array(\n z.object({\n name: z.string(),\n description: z.string(),\n path: z.string(),\n license: z.string().nullable().optional(),\n compatibility: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n allowedTools: z.array(z.string()).optional(),\n }),\n )\n .optional(),\n});\n\n/**\n * Skills System Documentation prompt template.\n */\nconst SKILLS_SYSTEM_PROMPT = `\n## Skills System\n\nYou have access to a skills library that provides specialized capabilities and domain knowledge.\n\n{skills_locations}\n\n**Available Skills:**\n\n{skills_list}\n\n**How to Use Skills (Progressive Disclosure):**\n\nSkills follow a **progressive disclosure** pattern - you know they exist (name + description above), but you only read the full instructions when needed:\n\n1. **Recognize when a skill applies**: Check if the user's task matches any skill's description\n2. **Read the skill's full instructions**: The skill list above shows the exact path to use with read_file\n3. **Follow the skill's instructions**: SKILL.md contains step-by-step workflows, best practices, and examples\n4. **Access supporting files**: Skills may include Python scripts, configs, or reference docs - use absolute paths\n\n**When to Use Skills:**\n- When the user's request matches a skill's domain (e.g., \"research X\" → web-research skill)\n- When you need specialized knowledge or structured workflows\n- When a skill provides proven patterns for complex tasks\n\n**Skills are Self-Documenting:**\n- Each SKILL.md tells you exactly what the skill does and how to use it\n- The skill list above shows the full path for each skill's SKILL.md file\n\n**Executing Skill Scripts:**\nSkills may contain Python scripts or other executable files. Always use absolute paths from the skill list.\n\n**Example Workflow:**\n\nUser: \"Can you research the latest developments in quantum computing?\"\n\n1. Check available skills above → See \"web-research\" skill with its full path\n2. Read the skill using the path shown in the list\n3. Follow the skill's research workflow (search → organize → synthesize)\n4. Use any helper scripts with absolute paths\n\nRemember: Skills are tools to make you more capable and consistent. When in doubt, check if a skill exists for the task!\n`;\n\n/**\n * Validate skill name per Agent Skills specification.\n */\nfunction validateSkillName(\n name: string,\n directoryName: string,\n): { valid: boolean; error: string } {\n if (!name) {\n return { valid: false, error: \"name is required\" };\n }\n if (name.length > MAX_SKILL_NAME_LENGTH) {\n return { valid: false, error: \"name exceeds 64 characters\" };\n }\n // Pattern: lowercase alphanumeric, single hyphens between segments, no start/end hyphen\n if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) {\n return {\n valid: false,\n error: \"name must be lowercase alphanumeric with single hyphens only\",\n };\n }\n if (name !== directoryName) {\n return {\n valid: false,\n error: `name '${name}' must match directory name '${directoryName}'`,\n };\n }\n return { valid: true, error: \"\" };\n}\n\n/**\n * Parse YAML frontmatter from SKILL.md content.\n */\nfunction parseSkillMetadataFromContent(\n content: string,\n skillPath: string,\n directoryName: string,\n): SkillMetadata | null {\n if (content.length > MAX_SKILL_FILE_SIZE) {\n console.warn(\n `Skipping ${skillPath}: content too large (${content.length} bytes)`,\n );\n return null;\n }\n\n // Match YAML frontmatter between --- delimiters\n const frontmatterPattern = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/;\n const match = content.match(frontmatterPattern);\n\n if (!match) {\n console.warn(`Skipping ${skillPath}: no valid YAML frontmatter found`);\n return null;\n }\n\n const frontmatterStr = match[1];\n\n // Parse YAML\n let frontmatterData: Record<string, unknown>;\n try {\n frontmatterData = yaml.parse(frontmatterStr);\n } catch (e) {\n console.warn(`Invalid YAML in ${skillPath}:`, e);\n return null;\n }\n\n if (!frontmatterData || typeof frontmatterData !== \"object\") {\n console.warn(`Skipping ${skillPath}: frontmatter is not a mapping`);\n return null;\n }\n\n // Validate required fields\n const name = frontmatterData.name as string | undefined;\n const description = frontmatterData.description as string | undefined;\n\n if (!name || !description) {\n console.warn(\n `Skipping ${skillPath}: missing required 'name' or 'description'`,\n );\n return null;\n }\n\n // Validate name format per spec (warn but continue for backwards compatibility)\n const validation = validateSkillName(String(name), directoryName);\n if (!validation.valid) {\n console.warn(\n `Skill '${name}' in ${skillPath} does not follow Agent Skills specification: ${validation.error}. Consider renaming for spec compliance.`,\n );\n }\n\n // Validate description length per spec (max 1024 chars)\n let descriptionStr = String(description).trim();\n if (descriptionStr.length > MAX_SKILL_DESCRIPTION_LENGTH) {\n console.warn(\n `Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH} characters in ${skillPath}, truncating`,\n );\n descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH);\n }\n\n // Parse allowed-tools\n const allowedToolsStr = frontmatterData[\"allowed-tools\"] as\n | string\n | undefined;\n const allowedTools = allowedToolsStr ? allowedToolsStr.split(\" \") : [];\n\n return {\n name: String(name),\n description: descriptionStr,\n path: skillPath,\n metadata: (frontmatterData.metadata as Record<string, string>) || {},\n license:\n typeof frontmatterData.license === \"string\"\n ? frontmatterData.license.trim() || null\n : null,\n compatibility:\n typeof frontmatterData.compatibility === \"string\"\n ? frontmatterData.compatibility.trim() || null\n : null,\n allowedTools,\n };\n}\n\n/**\n * List all skills from a backend source.\n */\nasync function listSkillsFromBackend(\n backend: BackendProtocol,\n sourcePath: string,\n): Promise<SkillMetadata[]> {\n const skills: SkillMetadata[] = [];\n\n // Normalize path to ensure it ends with /\n const normalizedPath = sourcePath.endsWith(\"/\")\n ? sourcePath\n : `${sourcePath}/`;\n\n // List directories in the source path using lsInfo\n let fileInfos: { path: string; is_dir?: boolean }[];\n try {\n fileInfos = await backend.lsInfo(normalizedPath);\n } catch {\n // Source path doesn't exist or can't be listed\n return [];\n }\n\n // Convert FileInfo[] to entries format\n const entries = fileInfos.map((info) => ({\n name: info.path.replace(/\\/$/, \"\").split(\"/\").pop() || \"\",\n type: (info.is_dir ? \"directory\" : \"file\") as \"file\" | \"directory\",\n }));\n\n // Look for subdirectories containing SKILL.md\n for (const entry of entries) {\n if (entry.type !== \"directory\") {\n continue;\n }\n\n const skillMdPath = `${normalizedPath}${entry.name}/SKILL.md`;\n\n // Try to download the SKILL.md file\n const results = await backend.downloadFiles([skillMdPath]);\n if (results.length !== 1) {\n continue;\n }\n\n const response = results[0];\n if (response.error != null || response.content == null) {\n continue;\n }\n\n // Decode content and parse metadata\n const content = new TextDecoder().decode(response.content);\n const metadata = parseSkillMetadataFromContent(\n content,\n skillMdPath,\n entry.name,\n );\n\n if (metadata) {\n skills.push(metadata);\n }\n }\n\n return skills;\n}\n\n/**\n * Format skills locations for display in system prompt.\n */\nfunction formatSkillsLocations(sources: string[]): string {\n if (sources.length === 0) {\n return \"**Skills Sources:** None configured\";\n }\n\n const lines = [\"**Skills Sources:**\"];\n for (const source of sources) {\n lines.push(`- \\`${source}\\``);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Format skills metadata for display in system prompt.\n */\nfunction formatSkillsList(skills: SkillMetadata[], sources: string[]): string {\n if (skills.length === 0) {\n return `(No skills available yet. Skills can be created in ${sources.join(\" or \")})`;\n }\n\n const lines: string[] = [];\n for (const skill of skills) {\n lines.push(`- **${skill.name}**: ${skill.description}`);\n lines.push(` → Read \\`${skill.path}\\` for full instructions`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Create backend-agnostic middleware for loading and exposing agent skills.\n *\n * This middleware loads skills from configurable backend sources and injects\n * skill metadata into the system prompt. It implements the progressive disclosure\n * pattern: skill names and descriptions are shown in the prompt, but the agent\n * reads full SKILL.md content only when needed.\n *\n * @param options - Configuration options\n * @returns AgentMiddleware for skills loading and injection\n *\n * @example\n * ```typescript\n * const middleware = createSkillsMiddleware({\n * backend: new FilesystemBackend({ rootDir: \"/\" }),\n * sources: [\"/skills/user/\", \"/skills/project/\"],\n * });\n * ```\n */\nexport function createSkillsMiddleware(options: SkillsMiddlewareOptions) {\n const { backend, sources } = options;\n\n // Closure variable to store loaded skills - wrapModelCall can access this\n // directly since beforeAgent state updates aren't immediately available\n let loadedSkills: SkillMetadata[] = [];\n\n /**\n * Resolve backend from instance or factory.\n */\n function getBackend(state: unknown): BackendProtocol {\n if (typeof backend === \"function\") {\n return backend({ state }) as BackendProtocol;\n }\n return backend;\n }\n\n return createMiddleware({\n name: \"SkillsMiddleware\",\n stateSchema: SkillsStateSchema,\n\n async beforeAgent(state) {\n // Skip if already loaded (check both closure and state)\n if (loadedSkills.length > 0) {\n return undefined;\n }\n if (\"skillsMetadata\" in state && state.skillsMetadata != null) {\n // Restore from state (e.g., after checkpoint restore)\n loadedSkills = state.skillsMetadata as SkillMetadata[];\n return undefined;\n }\n\n const resolvedBackend = getBackend(state);\n const allSkills: Map<string, SkillMetadata> = new Map();\n\n // Load skills from each source in order (later sources override earlier)\n for (const sourcePath of sources) {\n try {\n const skills = await listSkillsFromBackend(\n resolvedBackend,\n sourcePath,\n );\n for (const skill of skills) {\n allSkills.set(skill.name, skill);\n }\n } catch (error) {\n // Log but continue - individual source failures shouldn't break everything\n console.debug(\n `[BackendSkillsMiddleware] Failed to load skills from ${sourcePath}:`,\n error,\n );\n }\n }\n\n // Store in closure for immediate access by wrapModelCall\n loadedSkills = Array.from(allSkills.values());\n\n return { skillsMetadata: loadedSkills };\n },\n\n wrapModelCall(request, handler) {\n // Use closure variable which is populated by beforeAgent\n // Fall back to state for checkpoint restore scenarios\n const skillsMetadata: SkillMetadata[] =\n loadedSkills.length > 0\n ? loadedSkills\n : (request.state?.skillsMetadata as SkillMetadata[]) || [];\n\n // Format skills section\n const skillsLocations = formatSkillsLocations(sources);\n const skillsList = formatSkillsList(skillsMetadata, sources);\n\n const skillsSection = SKILLS_SYSTEM_PROMPT.replace(\n \"{skills_locations}\",\n skillsLocations,\n ).replace(\"{skills_list}\", skillsList);\n\n // Append to existing system prompt\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${currentSystemPrompt}\\n\\n${skillsSection}`\n : skillsSection;\n\n return handler({ ...request, systemPrompt: newSystemPrompt });\n },\n });\n}\n","/**\n * StoreBackend: Adapter for LangGraph's BaseStore (persistent, cross-thread).\n */\n\nimport type { Item } from \"@langchain/langgraph\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n StateAndStore,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n createFileData,\n fileDataToString,\n formatReadResponse,\n globSearchFiles,\n grepMatchesFromFiles,\n performStringReplacement,\n updateFileData,\n} from \"./utils.js\";\n\n/**\n * Backend that stores files in LangGraph's BaseStore (persistent).\n *\n * Uses LangGraph's Store for persistent, cross-conversation storage.\n * Files are organized via namespaces and persist across all threads.\n *\n * The namespace can include an optional assistant_id for multi-agent isolation.\n */\nexport class StoreBackend implements BackendProtocol {\n private stateAndStore: StateAndStore;\n\n constructor(stateAndStore: StateAndStore) {\n this.stateAndStore = stateAndStore;\n }\n\n /**\n * Get the store instance.\n *\n * @returns BaseStore instance\n * @throws Error if no store is available\n */\n private getStore() {\n const store = this.stateAndStore.store;\n if (!store) {\n throw new Error(\"Store is required but not available in StateAndStore\");\n }\n return store;\n }\n\n /**\n * Get the namespace for store operations.\n *\n * If an assistant_id is available in stateAndStore, return\n * [assistant_id, \"filesystem\"] to provide per-assistant isolation.\n * Otherwise return [\"filesystem\"].\n */\n protected getNamespace(): string[] {\n const namespace = \"filesystem\";\n const assistantId = this.stateAndStore.assistantId;\n\n if (assistantId) {\n return [assistantId, namespace];\n }\n\n return [namespace];\n }\n\n /**\n * Convert a store Item to FileData format.\n *\n * @param storeItem - The store Item containing file data\n * @returns FileData object\n * @throws Error if required fields are missing or have incorrect types\n */\n private convertStoreItemToFileData(storeItem: Item): FileData {\n const value = storeItem.value as any;\n\n if (\n !value.content ||\n !Array.isArray(value.content) ||\n typeof value.created_at !== \"string\" ||\n typeof value.modified_at !== \"string\"\n ) {\n throw new Error(\n `Store item does not contain valid FileData fields. Got keys: ${Object.keys(value).join(\", \")}`,\n );\n }\n\n return {\n content: value.content,\n created_at: value.created_at,\n modified_at: value.modified_at,\n };\n }\n\n /**\n * Convert FileData to a value suitable for store.put().\n *\n * @param fileData - The FileData to convert\n * @returns Object with content, created_at, and modified_at fields\n */\n private convertFileDataToStoreValue(fileData: FileData): Record<string, any> {\n return {\n content: fileData.content,\n created_at: fileData.created_at,\n modified_at: fileData.modified_at,\n };\n }\n\n /**\n * Search store with automatic pagination to retrieve all results.\n *\n * @param store - The store to search\n * @param namespace - Hierarchical path prefix to search within\n * @param options - Optional query, filter, and page_size\n * @returns List of all items matching the search criteria\n */\n private async searchStorePaginated(\n store: any,\n namespace: string[],\n options: {\n query?: string;\n filter?: Record<string, any>;\n pageSize?: number;\n } = {},\n ): Promise<Item[]> {\n const { query, filter, pageSize = 100 } = options;\n const allItems: Item[] = [];\n let offset = 0;\n\n while (true) {\n const pageItems = await store.search(namespace, {\n query,\n filter,\n limit: pageSize,\n offset,\n });\n\n if (!pageItems || pageItems.length === 0) {\n break;\n }\n\n allItems.push(...pageItems);\n\n if (pageItems.length < pageSize) {\n break;\n }\n\n offset += pageSize;\n }\n\n return allItems;\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(path: string): Promise<FileInfo[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n\n // Retrieve all items and filter by path prefix locally to avoid\n // coupling to store-specific filter semantics\n const items = await this.searchStorePaginated(store, namespace);\n const infos: FileInfo[] = [];\n const subdirs = new Set<string>();\n\n // Normalize path to have trailing slash for proper prefix matching\n const normalizedPath = path.endsWith(\"/\") ? path : path + \"/\";\n\n for (const item of items) {\n const itemKey = String(item.key);\n\n // Check if file is in the specified directory or a subdirectory\n if (!itemKey.startsWith(normalizedPath)) {\n continue;\n }\n\n // Get the relative path after the directory\n const relative = itemKey.substring(normalizedPath.length);\n\n // If relative path contains '/', it's in a subdirectory\n if (relative.includes(\"/\")) {\n // Extract the immediate subdirectory name\n const subdirName = relative.split(\"/\")[0];\n subdirs.add(normalizedPath + subdirName + \"/\");\n continue;\n }\n\n // This is a file directly in the current directory\n try {\n const fd = this.convertStoreItemToFileData(item);\n const size = fd.content.join(\"\\n\").length;\n infos.push({\n path: itemKey,\n is_dir: false,\n size: size,\n modified_at: fd.modified_at,\n });\n } catch {\n // Skip invalid items\n continue;\n }\n }\n\n // Add directories to the results\n for (const subdir of Array.from(subdirs).sort()) {\n infos.push({\n path: subdir,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n infos.sort((a, b) => a.path.localeCompare(b.path));\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 500,\n ): Promise<string> {\n try {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const item = await store.get(namespace, filePath);\n\n if (!item) {\n return `Error: File '${filePath}' not found`;\n }\n\n const fileData = this.convertStoreItemToFileData(item);\n return formatReadResponse(fileData, offset, limit);\n } catch (e: any) {\n return `Error: ${e.message}`;\n }\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n\n // Check if file exists\n const existing = await store.get(namespace, filePath);\n if (existing) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n // Create new file\n const fileData = createFileData(content);\n const storeValue = this.convertFileDataToStoreValue(fileData);\n await store.put(namespace, filePath, storeValue);\n return { path: filePath, filesUpdate: null };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n\n // Get existing file\n const item = await store.get(namespace, filePath);\n if (!item) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n try {\n const fileData = this.convertStoreItemToFileData(item);\n const content = fileDataToString(fileData);\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n const newFileData = updateFileData(fileData, newContent);\n\n // Update file in store\n const storeValue = this.convertFileDataToStoreValue(newFileData);\n await store.put(namespace, filePath, storeValue);\n return { path: filePath, filesUpdate: null, occurrences: occurrences };\n } catch (e: any) {\n return { error: `Error: ${e.message}` };\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const items = await this.searchStorePaginated(store, namespace);\n\n const files: Record<string, FileData> = {};\n for (const item of items) {\n try {\n files[item.key] = this.convertStoreItemToFileData(item);\n } catch {\n // Skip invalid items\n continue;\n }\n }\n\n return grepMatchesFromFiles(files, pattern, path, glob);\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(pattern: string, path: string = \"/\"): Promise<FileInfo[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const items = await this.searchStorePaginated(store, namespace);\n\n const files: Record<string, FileData> = {};\n for (const item of items) {\n try {\n files[item.key] = this.convertStoreItemToFileData(item);\n } catch {\n // Skip invalid items\n continue;\n }\n }\n\n const result = globSearchFiles(files, pattern, path);\n if (result === \"No files found\") {\n return [];\n }\n\n const paths = result.split(\"\\n\");\n const infos: FileInfo[] = [];\n for (const p of paths) {\n const fd = files[p];\n const size = fd ? fd.content.join(\"\\n\").length : 0;\n infos.push({\n path: p,\n is_dir: false,\n size: size,\n modified_at: fd?.modified_at || \"\",\n });\n }\n return infos;\n }\n\n /**\n * Upload multiple files.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const responses: FileUploadResponse[] = [];\n\n for (const [path, content] of files) {\n try {\n const contentStr = new TextDecoder().decode(content);\n const fileData = createFileData(contentStr);\n const storeValue = this.convertFileDataToStoreValue(fileData);\n await store.put(namespace, path, storeValue);\n responses.push({ path, error: null });\n } catch {\n responses.push({ path, error: \"invalid_path\" });\n }\n }\n\n return responses;\n }\n\n /**\n * Download multiple files.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const store = this.getStore();\n const namespace = this.getNamespace();\n const responses: FileDownloadResponse[] = [];\n\n for (const path of paths) {\n try {\n const item = await store.get(namespace, path);\n if (!item) {\n responses.push({ path, content: null, error: \"file_not_found\" });\n continue;\n }\n\n const fileData = this.convertStoreItemToFileData(item);\n const contentStr = fileDataToString(fileData);\n const content = new TextEncoder().encode(contentStr);\n responses.push({ path, content, error: null });\n } catch {\n responses.push({ path, content: null, error: \"file_not_found\" });\n }\n }\n\n return responses;\n }\n}\n","/**\n * FilesystemBackend: Read and write files directly from the filesystem.\n *\n * Security and search upgrades:\n * - Secure path resolution with root containment when in virtual_mode (sandboxed to cwd)\n * - Prevent symlink-following on file I/O using O_NOFOLLOW when available\n * - Ripgrep-powered grep with JSON parsing, plus regex fallback\n * and optional glob include filtering, while preserving virtual path behavior\n */\n\nimport fs from \"node:fs/promises\";\nimport fsSync from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\n\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\nimport type {\n BackendProtocol,\n EditResult,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n checkEmptyContent,\n formatContentWithLineNumbers,\n performStringReplacement,\n} from \"./utils.js\";\n\nconst SUPPORTS_NOFOLLOW = fsSync.constants.O_NOFOLLOW !== undefined;\n\n/**\n * Backend that reads and writes files directly from the filesystem.\n *\n * Files are accessed using their actual filesystem paths. Relative paths are\n * resolved relative to the current working directory. Content is read/written\n * as plain text, and metadata (timestamps) are derived from filesystem stats.\n */\nexport class FilesystemBackend implements BackendProtocol {\n private cwd: string;\n private virtualMode: boolean;\n private maxFileSizeBytes: number;\n\n constructor(\n options: {\n rootDir?: string;\n virtualMode?: boolean;\n maxFileSizeMb?: number;\n } = {},\n ) {\n const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options;\n this.cwd = rootDir ? path.resolve(rootDir) : process.cwd();\n this.virtualMode = virtualMode;\n this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024;\n }\n\n /**\n * Resolve a file path with security checks.\n *\n * When virtualMode=true, treat incoming paths as virtual absolute paths under\n * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.\n * When virtualMode=false, preserve legacy behavior: absolute paths are allowed\n * as-is; relative paths resolve under cwd.\n *\n * @param key - File path (absolute, relative, or virtual when virtualMode=true)\n * @returns Resolved absolute path string\n * @throws Error if path traversal detected or path outside root\n */\n private resolvePath(key: string): string {\n if (this.virtualMode) {\n const vpath = key.startsWith(\"/\") ? key : \"/\" + key;\n if (vpath.includes(\"..\") || vpath.startsWith(\"~\")) {\n throw new Error(\"Path traversal not allowed\");\n }\n const full = path.resolve(this.cwd, vpath.substring(1));\n const relative = path.relative(this.cwd, full);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Path: ${full} outside root directory: ${this.cwd}`);\n }\n return full;\n }\n\n if (path.isAbsolute(key)) {\n return key;\n }\n return path.resolve(this.cwd, key);\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param dirPath - Absolute directory path to list files from\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(dirPath: string): Promise<FileInfo[]> {\n try {\n const resolvedPath = this.resolvePath(dirPath);\n const stat = await fs.stat(resolvedPath);\n\n if (!stat.isDirectory()) {\n return [];\n }\n\n const entries = await fs.readdir(resolvedPath, { withFileTypes: true });\n const results: FileInfo[] = [];\n\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n\n for (const entry of entries) {\n const fullPath = path.join(resolvedPath, entry.name);\n\n try {\n const entryStat = await fs.stat(fullPath);\n const isFile = entryStat.isFile();\n const isDir = entryStat.isDirectory();\n\n if (!this.virtualMode) {\n // Non-virtual mode: use absolute paths\n if (isFile) {\n results.push({\n path: fullPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: fullPath + path.sep,\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n } else {\n let relativePath: string;\n if (fullPath.startsWith(cwdStr)) {\n relativePath = fullPath.substring(cwdStr.length);\n } else if (fullPath.startsWith(this.cwd)) {\n relativePath = fullPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = fullPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virtPath = \"/\" + relativePath;\n\n if (isFile) {\n results.push({\n path: virtPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: virtPath + \"/\",\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n }\n } catch {\n // Skip entries we can't stat\n continue;\n }\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n } catch {\n return [];\n }\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute or relative file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 500,\n ): Promise<string> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW,\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return `Error: Symlinks are not allowed: ${filePath}`;\n }\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n } catch (e: any) {\n return `Error reading file '${filePath}': ${e.message}`;\n }\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n try {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return {\n error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`,\n };\n }\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n } catch {\n // File doesn't exist, good to proceed\n }\n\n await fs.mkdir(path.dirname(resolvedPath), { recursive: true });\n\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_CREAT |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags, 0o644);\n try {\n await fd.writeFile(content, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, content, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null };\n } catch (e: any) {\n return { error: `Error writing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW,\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return { error: `Error: Symlinks are not allowed: ${filePath}` };\n }\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n\n // Write securely\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags);\n try {\n await fd.writeFile(newContent, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, newContent, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null, occurrences: occurrences };\n } catch (e: any) {\n return { error: `Error editing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n dirPath: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n // Validate regex\n try {\n new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n // Resolve base path\n let baseFull: string;\n try {\n baseFull = this.resolvePath(dirPath || \".\");\n } catch {\n return [];\n }\n\n try {\n await fs.stat(baseFull);\n } catch {\n return [];\n }\n\n // Try ripgrep first, fallback to regex search\n let results = await this.ripgrepSearch(pattern, baseFull, glob);\n if (results === null) {\n results = await this.pythonSearch(pattern, baseFull, glob);\n }\n\n const matches: GrepMatch[] = [];\n for (const [fpath, items] of Object.entries(results)) {\n for (const [lineNum, lineText] of items) {\n matches.push({ path: fpath, line: lineNum, text: lineText });\n }\n }\n return matches;\n }\n\n /**\n * Try to use ripgrep for fast searching.\n * Returns null if ripgrep is not available or fails.\n */\n private async ripgrepSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null,\n ): Promise<Record<string, Array<[number, string]>> | null> {\n return new Promise((resolve) => {\n const args = [\"--json\"];\n if (includeGlob) {\n args.push(\"--glob\", includeGlob);\n }\n args.push(\"--\", pattern, baseFull);\n\n const proc = spawn(\"rg\", args, { timeout: 30000 });\n const results: Record<string, Array<[number, string]>> = {};\n let output = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n output += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n if (code !== 0 && code !== 1) {\n // Error (code 1 means no matches, which is ok)\n resolve(null);\n return;\n }\n\n for (const line of output.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const data = JSON.parse(line);\n if (data.type !== \"match\") continue;\n\n const pdata = data.data || {};\n const ftext = pdata.path?.text;\n if (!ftext) continue;\n\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const resolved = path.resolve(ftext);\n const relative = path.relative(this.cwd, resolved);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = ftext;\n }\n\n const ln = pdata.line_number;\n const lt = pdata.lines?.text?.replace(/\\n$/, \"\") || \"\";\n if (ln === undefined) continue;\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([ln, lt]);\n } catch {\n // Skip invalid JSON\n continue;\n }\n }\n\n resolve(results);\n });\n\n proc.on(\"error\", () => {\n resolve(null);\n });\n });\n }\n\n /**\n * Fallback regex search implementation.\n */\n private async pythonSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null,\n ): Promise<Record<string, Array<[number, string]>>> {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch {\n return {};\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n const stat = await fs.stat(baseFull);\n const root = stat.isDirectory() ? baseFull : path.dirname(baseFull);\n\n // Use fast-glob to recursively find all files\n const files = await fg(\"**/*\", {\n cwd: root,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const fp of files) {\n try {\n // Filter by glob if provided\n if (\n includeGlob &&\n !micromatch.isMatch(path.basename(fp), includeGlob)\n ) {\n continue;\n }\n\n // Check file size\n const stat = await fs.stat(fp);\n if (stat.size > this.maxFileSizeBytes) {\n continue;\n }\n\n // Read and search\n const content = await fs.readFile(fp, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (regex.test(line)) {\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const relative = path.relative(this.cwd, fp);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = fp;\n }\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([i + 1, line]);\n }\n }\n } catch {\n // Skip files we can't read\n continue;\n }\n }\n\n return results;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(\n pattern: string,\n searchPath: string = \"/\",\n ): Promise<FileInfo[]> {\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.substring(1);\n }\n\n const resolvedSearchPath =\n searchPath === \"/\" ? this.cwd : this.resolvePath(searchPath);\n\n try {\n const stat = await fs.stat(resolvedSearchPath);\n if (!stat.isDirectory()) {\n return [];\n }\n } catch {\n return [];\n }\n\n const results: FileInfo[] = [];\n\n try {\n // Use fast-glob for pattern matching\n const matches = await fg(pattern, {\n cwd: resolvedSearchPath,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const matchedPath of matches) {\n try {\n const stat = await fs.stat(matchedPath);\n if (!stat.isFile()) continue;\n\n // Normalize fast-glob paths to platform separators\n // fast-glob returns forward slashes on all platforms, but we need\n // platform-native separators for path comparisons on Windows\n const normalizedPath = matchedPath.split(\"/\").join(path.sep);\n\n if (!this.virtualMode) {\n results.push({\n path: normalizedPath,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n } else {\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n let relativePath: string;\n\n if (normalizedPath.startsWith(cwdStr)) {\n relativePath = normalizedPath.substring(cwdStr.length);\n } else if (normalizedPath.startsWith(this.cwd)) {\n relativePath = normalizedPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = normalizedPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virt = \"/\" + relativePath;\n results.push({\n path: virt,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n }\n } catch {\n // Skip files we can't stat\n continue;\n }\n }\n } catch {\n // Ignore glob errors\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n\n /**\n * Upload multiple files to the filesystem.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const responses: FileUploadResponse[] = [];\n\n for (const [filePath, content] of files) {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n // Ensure parent directory exists\n await fs.mkdir(path.dirname(resolvedPath), { recursive: true });\n\n // Write file\n await fs.writeFile(resolvedPath, content);\n responses.push({ path: filePath, error: null });\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n responses.push({ path: filePath, error: \"file_not_found\" });\n } else if (e.code === \"EACCES\") {\n responses.push({ path: filePath, error: \"permission_denied\" });\n } else if (e.code === \"EISDIR\") {\n responses.push({ path: filePath, error: \"is_directory\" });\n } else {\n responses.push({ path: filePath, error: \"invalid_path\" });\n }\n }\n }\n\n return responses;\n }\n\n /**\n * Download multiple files from the filesystem.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const responses: FileDownloadResponse[] = [];\n\n for (const filePath of paths) {\n try {\n const resolvedPath = this.resolvePath(filePath);\n const content = await fs.readFile(resolvedPath);\n responses.push({ path: filePath, content, error: null });\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n responses.push({\n path: filePath,\n content: null,\n error: \"file_not_found\",\n });\n } else if (e.code === \"EACCES\") {\n responses.push({\n path: filePath,\n content: null,\n error: \"permission_denied\",\n });\n } else if (e.code === \"EISDIR\") {\n responses.push({\n path: filePath,\n content: null,\n error: \"is_directory\",\n });\n } else {\n responses.push({\n path: filePath,\n content: null,\n error: \"invalid_path\",\n });\n }\n }\n }\n\n return responses;\n }\n}\n","/**\n * CompositeBackend: Route operations to different backends based on path prefix.\n */\n\nimport type {\n BackendProtocol,\n EditResult,\n ExecuteResponse,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport { isSandboxBackend } from \"./protocol.js\";\n\n/**\n * Backend that routes file operations to different backends based on path prefix.\n *\n * This enables hybrid storage strategies like:\n * - `/memories/` → StoreBackend (persistent, cross-thread)\n * - Everything else → StateBackend (ephemeral, per-thread)\n *\n * The CompositeBackend handles path prefix stripping/re-adding transparently.\n */\nexport class CompositeBackend implements BackendProtocol {\n private default: BackendProtocol;\n private routes: Record<string, BackendProtocol>;\n private sortedRoutes: Array<[string, BackendProtocol]>;\n\n constructor(\n defaultBackend: BackendProtocol,\n routes: Record<string, BackendProtocol>,\n ) {\n this.default = defaultBackend;\n this.routes = routes;\n\n // Sort routes by length (longest first) for correct prefix matching\n this.sortedRoutes = Object.entries(routes).sort(\n (a, b) => b[0].length - a[0].length,\n );\n }\n\n /**\n * Determine which backend handles this key and strip prefix.\n *\n * @param key - Original file path\n * @returns Tuple of [backend, stripped_key] where stripped_key has the route\n * prefix removed (but keeps leading slash).\n */\n private getBackendAndKey(key: string): [BackendProtocol, string] {\n // Check routes in order of length (longest first)\n for (const [prefix, backend] of this.sortedRoutes) {\n if (key.startsWith(prefix)) {\n // Strip full prefix and ensure a leading slash remains\n // e.g., \"/memories/notes.txt\" → \"/notes.txt\"; \"/memories/\" → \"/\"\n const suffix = key.substring(prefix.length);\n const strippedKey = suffix ? \"/\" + suffix : \"/\";\n return [backend, strippedKey];\n }\n }\n\n return [this.default, key];\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects with route prefixes added, for files and directories\n * directly in the directory. Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(path: string): Promise<FileInfo[]> {\n // Check if path matches a specific route\n for (const [routePrefix, backend] of this.sortedRoutes) {\n if (path.startsWith(routePrefix.replace(/\\/$/, \"\"))) {\n // Query only the matching routed backend\n const suffix = path.substring(routePrefix.length);\n const searchPath = suffix ? \"/\" + suffix : \"/\";\n const infos = await backend.lsInfo(searchPath);\n\n // Add route prefix back to paths\n const prefixed: FileInfo[] = [];\n for (const fi of infos) {\n prefixed.push({\n ...fi,\n path: routePrefix.slice(0, -1) + fi.path,\n });\n }\n return prefixed;\n }\n }\n\n // At root, aggregate default and all routed backends\n if (path === \"/\") {\n const results: FileInfo[] = [];\n const defaultInfos = await this.default.lsInfo(path);\n results.push(...defaultInfos);\n\n // Add the route itself as a directory (e.g., /memories/)\n for (const [routePrefix] of this.sortedRoutes) {\n results.push({\n path: routePrefix,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n\n // Path doesn't match a route: query only default backend\n return await this.default.lsInfo(path);\n }\n\n /**\n * Read file content, routing to appropriate backend.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 500,\n ): Promise<string> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.read(strippedKey, offset, limit);\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n // If path targets a specific route, search only that backend\n for (const [routePrefix, backend] of this.sortedRoutes) {\n if (path.startsWith(routePrefix.replace(/\\/$/, \"\"))) {\n const searchPath = path.substring(routePrefix.length - 1);\n const raw = await backend.grepRaw(pattern, searchPath || \"/\", glob);\n\n if (typeof raw === \"string\") {\n return raw;\n }\n\n // Add route prefix back\n return raw.map((m) => ({\n ...m,\n path: routePrefix.slice(0, -1) + m.path,\n }));\n }\n }\n\n // Otherwise, search default and all routed backends and merge\n const allMatches: GrepMatch[] = [];\n const rawDefault = await this.default.grepRaw(pattern, path, glob);\n\n if (typeof rawDefault === \"string\") {\n return rawDefault;\n }\n\n allMatches.push(...rawDefault);\n\n // Search all routes\n for (const [routePrefix, backend] of Object.entries(this.routes)) {\n const raw = await backend.grepRaw(pattern, \"/\", glob);\n\n if (typeof raw === \"string\") {\n return raw;\n }\n\n // Add route prefix back\n allMatches.push(\n ...raw.map((m) => ({\n ...m,\n path: routePrefix.slice(0, -1) + m.path,\n })),\n );\n }\n\n return allMatches;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(pattern: string, path: string = \"/\"): Promise<FileInfo[]> {\n const results: FileInfo[] = [];\n\n // Route based on path, not pattern\n for (const [routePrefix, backend] of this.sortedRoutes) {\n if (path.startsWith(routePrefix.replace(/\\/$/, \"\"))) {\n const searchPath = path.substring(routePrefix.length - 1);\n const infos = await backend.globInfo(pattern, searchPath || \"/\");\n\n // Add route prefix back\n return infos.map((fi) => ({\n ...fi,\n path: routePrefix.slice(0, -1) + fi.path,\n }));\n }\n }\n\n // Path doesn't match any specific route - search default backend AND all routed backends\n const defaultInfos = await this.default.globInfo(pattern, path);\n results.push(...defaultInfos);\n\n for (const [routePrefix, backend] of Object.entries(this.routes)) {\n const infos = await backend.globInfo(pattern, \"/\");\n results.push(\n ...infos.map((fi) => ({\n ...fi,\n path: routePrefix.slice(0, -1) + fi.path,\n })),\n );\n }\n\n // Deterministic ordering\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n\n /**\n * Create a new file, routing to appropriate backend.\n *\n * @param filePath - Absolute file path\n * @param content - File content as string\n * @returns WriteResult with path or error\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.write(strippedKey, content);\n }\n\n /**\n * Edit a file, routing to appropriate backend.\n *\n * @param filePath - Absolute file path\n * @param oldString - String to find and replace\n * @param newString - Replacement string\n * @param replaceAll - If true, replace all occurrences\n * @returns EditResult with path, occurrences, or error\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n const [backend, strippedKey] = this.getBackendAndKey(filePath);\n return await backend.edit(strippedKey, oldString, newString, replaceAll);\n }\n\n /**\n * Execute a command via the default backend.\n * Execution is not path-specific, so it always delegates to the default backend.\n *\n * @param command - Full shell command string to execute\n * @returns ExecuteResponse with combined output, exit code, and truncation flag\n * @throws Error if the default backend doesn't support command execution\n */\n execute(command: string): Promise<ExecuteResponse> {\n if (!isSandboxBackend(this.default)) {\n throw new Error(\n \"Default backend doesn't support command execution (SandboxBackendProtocol). \" +\n \"To enable execution, provide a default backend that implements SandboxBackendProtocol.\",\n );\n }\n return Promise.resolve(this.default.execute(command));\n }\n\n /**\n * Upload multiple files, batching by backend for efficiency.\n *\n * @param files - List of [path, content] tuples to upload\n * @returns List of FileUploadResponse objects, one per input file\n */\n async uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): Promise<FileUploadResponse[]> {\n const results: Array<FileUploadResponse | null> = new Array(\n files.length,\n ).fill(null);\n const batchesByBackend = new Map<\n BackendProtocol,\n Array<{ idx: number; path: string; content: Uint8Array }>\n >();\n\n for (let idx = 0; idx < files.length; idx++) {\n const [path, content] = files[idx];\n const [backend, strippedPath] = this.getBackendAndKey(path);\n\n if (!batchesByBackend.has(backend)) {\n batchesByBackend.set(backend, []);\n }\n batchesByBackend.get(backend)!.push({ idx, path: strippedPath, content });\n }\n\n for (const [backend, batch] of batchesByBackend) {\n const batchFiles = batch.map(\n (b) => [b.path, b.content] as [string, Uint8Array],\n );\n const batchResponses = await backend.uploadFiles(batchFiles);\n\n for (let i = 0; i < batch.length; i++) {\n const originalIdx = batch[i].idx;\n results[originalIdx] = {\n path: files[originalIdx][0], // Original path\n error: batchResponses[i]?.error ?? null,\n };\n }\n }\n\n return results as FileUploadResponse[];\n }\n\n /**\n * Download multiple files, batching by backend for efficiency.\n *\n * @param paths - List of file paths to download\n * @returns List of FileDownloadResponse objects, one per input path\n */\n async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {\n const results: Array<FileDownloadResponse | null> = new Array(\n paths.length,\n ).fill(null);\n const batchesByBackend = new Map<\n BackendProtocol,\n Array<{ idx: number; path: string }>\n >();\n\n for (let idx = 0; idx < paths.length; idx++) {\n const path = paths[idx];\n const [backend, strippedPath] = this.getBackendAndKey(path);\n\n if (!batchesByBackend.has(backend)) {\n batchesByBackend.set(backend, []);\n }\n batchesByBackend.get(backend)!.push({ idx, path: strippedPath });\n }\n\n for (const [backend, batch] of batchesByBackend) {\n const batchPaths = batch.map((b) => b.path);\n const batchResponses = await backend.downloadFiles(batchPaths);\n\n for (let i = 0; i < batch.length; i++) {\n const originalIdx = batch[i].idx;\n results[originalIdx] = {\n path: paths[originalIdx], // Original path\n content: batchResponses[i]?.content ?? null,\n error: batchResponses[i]?.error ?? null,\n };\n }\n }\n\n return results as FileDownloadResponse[];\n }\n}\n","/**\n * BaseSandbox: Abstract base class for sandbox backends with command execution.\n *\n * This class provides default implementations for all SandboxBackendProtocol\n * methods using shell commands executed via execute(). Concrete implementations\n * only need to implement the execute() method.\n *\n * Requires Node.js 20+ on the sandbox host.\n */\n\nimport type {\n EditResult,\n ExecuteResponse,\n FileDownloadResponse,\n FileInfo,\n FileUploadResponse,\n GrepMatch,\n MaybePromise,\n SandboxBackendProtocol,\n WriteResult,\n} from \"./protocol.js\";\n\n/**\n * Node.js command template for glob operations.\n * Uses web-standard atob() for base64 decoding.\n */\nfunction buildGlobCommand(searchPath: string, pattern: string): string {\n const pathB64 = btoa(searchPath);\n const patternB64 = btoa(pattern);\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst searchPath = atob('${pathB64}');\nconst pattern = atob('${patternB64}');\n\nfunction globMatch(relativePath, pattern) {\n const regexPattern = pattern\n .replace(/\\\\*\\\\*/g, '<<<GLOBSTAR>>>')\n .replace(/\\\\*/g, '[^/]*')\n .replace(/\\\\?/g, '.')\n .replace(/<<<GLOBSTAR>>>/g, '.*');\n return new RegExp('^' + regexPattern + '$').test(relativePath);\n}\n\nfunction walkDir(dir, baseDir, results) {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = path.relative(baseDir, fullPath);\n if (entry.isDirectory()) {\n walkDir(fullPath, baseDir, results);\n } else if (globMatch(relativePath, pattern)) {\n const stat = fs.statSync(fullPath);\n console.log(JSON.stringify({\n path: relativePath,\n size: stat.size,\n mtime: stat.mtimeMs,\n isDir: false\n }));\n }\n }\n } catch (e) {\n // Silent failure for non-existent paths\n }\n}\n\ntry {\n process.chdir(searchPath);\n walkDir('.', '.', []);\n} catch (e) {\n // Silent failure for non-existent paths\n}\n\"`;\n}\n\n/**\n * Node.js command template for listing directory contents.\n */\nfunction buildLsCommand(dirPath: string): string {\n const pathB64 = btoa(dirPath);\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst dirPath = atob('${pathB64}');\n\ntry {\n const entries = fs.readdirSync(dirPath, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n const stat = fs.statSync(fullPath);\n console.log(JSON.stringify({\n path: entry.isDirectory() ? fullPath + '/' : fullPath,\n size: stat.size,\n mtime: stat.mtimeMs,\n isDir: entry.isDirectory()\n }));\n }\n} catch (e) {\n console.error('Error: ' + e.message);\n process.exit(1);\n}\n\"`;\n}\n\n/**\n * Node.js command template for reading files.\n */\nfunction buildReadCommand(\n filePath: string,\n offset: number,\n limit: number,\n): string {\n const pathB64 = btoa(filePath);\n // Coerce offset and limit to safe non-negative integers before embedding in the shell command.\n const safeOffset =\n Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;\n const safeLimit =\n Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER\n ? Math.floor(limit)\n : 0;\n\n return `node -e \"\nconst fs = require('fs');\n\nconst filePath = atob('${pathB64}');\nconst offset = ${safeOffset};\nconst limit = ${safeLimit};\n\nif (!fs.existsSync(filePath)) {\n console.log('Error: File not found');\n process.exit(1);\n}\n\nconst stat = fs.statSync(filePath);\nif (stat.size === 0) {\n console.log('System reminder: File exists but has empty contents');\n process.exit(0);\n}\n\nconst content = fs.readFileSync(filePath, 'utf-8');\nconst lines = content.split('\\\\n');\nconst selected = lines.slice(offset, offset + limit);\n\nfor (let i = 0; i < selected.length; i++) {\n const lineNum = offset + i + 1;\n console.log(String(lineNum).padStart(6) + '\\\\t' + selected[i]);\n}\n\"`;\n}\n\n/**\n * Node.js command template for writing files.\n */\nfunction buildWriteCommand(filePath: string, content: string): string {\n const pathB64 = btoa(filePath);\n const contentB64 = btoa(content);\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst filePath = atob('${pathB64}');\nconst content = atob('${contentB64}');\n\nif (fs.existsSync(filePath)) {\n console.error('Error: File already exists');\n process.exit(1);\n}\n\nconst parentDir = path.dirname(filePath) || '.';\nfs.mkdirSync(parentDir, { recursive: true });\n\nfs.writeFileSync(filePath, content, 'utf-8');\nconsole.log('OK');\n\"`;\n}\n\n/**\n * Node.js command template for editing files.\n */\nfunction buildEditCommand(\n filePath: string,\n oldStr: string,\n newStr: string,\n replaceAll: boolean,\n): string {\n const pathB64 = btoa(filePath);\n const oldB64 = btoa(oldStr);\n const newB64 = btoa(newStr);\n\n return `node -e \"\nconst fs = require('fs');\n\nconst filePath = atob('${pathB64}');\nconst oldStr = atob('${oldB64}');\nconst newStr = atob('${newB64}');\nconst replaceAll = ${Boolean(replaceAll)};\n\nlet text;\ntry {\n text = fs.readFileSync(filePath, 'utf-8');\n} catch (e) {\n process.exit(3);\n}\n\nconst count = text.split(oldStr).length - 1;\n\nif (count === 0) {\n process.exit(1);\n}\nif (count > 1 && !replaceAll) {\n process.exit(2);\n}\n\nconst result = text.split(oldStr).join(newStr);\nfs.writeFileSync(filePath, result, 'utf-8');\nconsole.log(count);\n\"`;\n}\n\n/**\n * Node.js command template for grep operations.\n */\nfunction buildGrepCommand(\n pattern: string,\n searchPath: string,\n globPattern: string | null,\n): string {\n const patternB64 = btoa(pattern);\n const pathB64 = btoa(searchPath);\n const globB64 = globPattern ? btoa(globPattern) : \"\";\n\n return `node -e \"\nconst fs = require('fs');\nconst path = require('path');\n\nconst pattern = atob('${patternB64}');\nconst searchPath = atob('${pathB64}');\nconst globPattern = ${globPattern ? `atob('${globB64}')` : \"null\"};\n\nlet regex;\ntry {\n regex = new RegExp(pattern);\n} catch (e) {\n console.error('Invalid regex: ' + e.message);\n process.exit(1);\n}\n\nfunction globMatch(filePath, pattern) {\n if (!pattern) return true;\n const regexPattern = pattern\n .replace(/\\\\*\\\\*/g, '<<<GLOBSTAR>>>')\n .replace(/\\\\*/g, '[^/]*')\n .replace(/\\\\?/g, '.')\n .replace(/<<<GLOBSTAR>>>/g, '.*');\n return new RegExp('^' + regexPattern + '$').test(filePath);\n}\n\nfunction walkDir(dir, results) {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n walkDir(fullPath, results);\n } else {\n const relativePath = path.relative(searchPath, fullPath);\n if (globMatch(relativePath, globPattern)) {\n try {\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\\\n');\n for (let i = 0; i < lines.length; i++) {\n if (regex.test(lines[i])) {\n console.log(JSON.stringify({\n path: fullPath,\n line: i + 1,\n text: lines[i]\n }));\n }\n }\n } catch (e) {\n // Skip unreadable files\n }\n }\n }\n }\n } catch (e) {\n // Skip unreadable directories\n }\n}\n\ntry {\n walkDir(searchPath, []);\n} catch (e) {\n // Silent failure\n}\n\"`;\n}\n\n/**\n * Base sandbox implementation with execute() as the only abstract method.\n *\n * This class provides default implementations for all SandboxBackendProtocol\n * methods using shell commands executed via execute(). Concrete implementations\n * only need to implement the execute() method.\n *\n * Requires Node.js 20+ on the sandbox host.\n */\nexport abstract class BaseSandbox implements SandboxBackendProtocol {\n /** Unique identifier for the sandbox backend */\n abstract readonly id: string;\n\n /**\n * Execute a command in the sandbox.\n * This is the only method concrete implementations must provide.\n */\n abstract execute(command: string): MaybePromise<ExecuteResponse>;\n\n /**\n * Upload multiple files to the sandbox.\n * Implementations must support partial success.\n */\n abstract uploadFiles(\n files: Array<[string, Uint8Array]>,\n ): MaybePromise<FileUploadResponse[]>;\n\n /**\n * Download multiple files from the sandbox.\n * Implementations must support partial success.\n */\n abstract downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n */\n async lsInfo(path: string): Promise<FileInfo[]> {\n const command = buildLsCommand(path);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n return [];\n }\n\n const infos: FileInfo[] = [];\n const lines = result.output.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n infos.push({\n path: parsed.path,\n is_dir: parsed.isDir,\n size: parsed.size,\n modified_at: parsed.mtime\n ? new Date(parsed.mtime).toISOString()\n : undefined,\n });\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 500,\n ): Promise<string> {\n const command = buildReadCommand(filePath, offset, limit);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n return `Error: File '${filePath}' not found`;\n }\n\n return result.output;\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): Promise<GrepMatch[] | string> {\n const command = buildGrepCommand(pattern, path, glob);\n const result = await this.execute(command);\n\n if (result.exitCode === 1) {\n // Check if it's a regex error\n if (result.output.includes(\"Invalid regex:\")) {\n return result.output.trim();\n }\n }\n\n const matches: GrepMatch[] = [];\n const lines = result.output.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n matches.push({\n path: parsed.path,\n line: parsed.line,\n text: parsed.text,\n });\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return matches;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(pattern: string, path: string = \"/\"): Promise<FileInfo[]> {\n const command = buildGlobCommand(path, pattern);\n const result = await this.execute(command);\n\n const infos: FileInfo[] = [];\n const lines = result.output.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const parsed = JSON.parse(line);\n infos.push({\n path: parsed.path,\n is_dir: parsed.isDir,\n size: parsed.size,\n modified_at: parsed.mtime\n ? new Date(parsed.mtime).toISOString()\n : undefined,\n });\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return infos;\n }\n\n /**\n * Create a new file with content.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n const command = buildWriteCommand(filePath, content);\n const result = await this.execute(command);\n\n if (result.exitCode !== 0) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n return { path: filePath, filesUpdate: null };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): Promise<EditResult> {\n const command = buildEditCommand(\n filePath,\n oldString,\n newString,\n replaceAll,\n );\n const result = await this.execute(command);\n\n switch (result.exitCode) {\n case 0: {\n const occurrences = parseInt(result.output.trim(), 10) || 1;\n return { path: filePath, filesUpdate: null, occurrences };\n }\n case 1:\n return { error: `String not found in file '${filePath}'` };\n case 2:\n return {\n error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.`,\n };\n case 3:\n return { error: `Error: File '${filePath}' not found` };\n default:\n return { error: `Unknown error editing file '${filePath}'` };\n }\n }\n}\n","import {\n createAgent,\n humanInTheLoopMiddleware,\n anthropicPromptCachingMiddleware,\n todoListMiddleware,\n summarizationMiddleware,\n SystemMessage,\n type AgentMiddleware,\n type ResponseFormat,\n} from \"langchain\";\nimport type {\n ClientTool,\n ServerTool,\n StructuredTool,\n} from \"@langchain/core/tools\";\nimport type { BaseStore } from \"@langchain/langgraph-checkpoint\";\n\nimport {\n createFilesystemMiddleware,\n createSubAgentMiddleware,\n createPatchToolCallsMiddleware,\n createMemoryMiddleware,\n createSkillsMiddleware,\n type SubAgent,\n} from \"./middleware/index.js\";\nimport { StateBackend } from \"./backends/index.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { CompiledSubAgent } from \"./middleware/subagents.js\";\nimport type {\n CreateDeepAgentParams,\n DeepAgent,\n DeepAgentTypeConfig,\n FlattenSubAgentMiddleware,\n} from \"./types.js\";\n\n/**\n * required for type inference\n */\nimport type * as _messages from \"@langchain/core/messages\";\nimport type * as _Command from \"@langchain/langgraph\";\n\nconst BASE_PROMPT = `In order to complete the objective that the user asks of you, you have access to a number of standard tools.`;\n\n/**\n * Create a Deep Agent with middleware-based architecture.\n *\n * Matches Python's create_deep_agent function, using middleware for all features:\n * - Todo management (todoListMiddleware)\n * - Filesystem tools (createFilesystemMiddleware)\n * - Subagent delegation (createSubAgentMiddleware)\n * - Conversation summarization (summarizationMiddleware)\n * - Prompt caching (anthropicPromptCachingMiddleware)\n * - Tool call patching (createPatchToolCallsMiddleware)\n * - Human-in-the-loop (humanInTheLoopMiddleware) - optional\n *\n * @param params Configuration parameters for the agent\n * @returns ReactAgent instance ready for invocation with properly inferred state types\n *\n * @example\n * ```typescript\n * // Middleware with custom state\n * const ResearchMiddleware = createMiddleware({\n * name: \"ResearchMiddleware\",\n * stateSchema: z.object({ research: z.string().default(\"\") }),\n * });\n *\n * const agent = createDeepAgent({\n * middleware: [ResearchMiddleware],\n * });\n *\n * const result = await agent.invoke({ messages: [...] });\n * // result.research is properly typed as string\n * ```\n */\nexport function createDeepAgent<\n TResponse extends ResponseFormat = ResponseFormat,\n ContextSchema extends InteropZodObject = InteropZodObject,\n const TMiddleware extends readonly AgentMiddleware[] = readonly [],\n const TSubagents extends readonly (SubAgent | CompiledSubAgent)[] =\n readonly [],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly [],\n>(\n params: CreateDeepAgentParams<\n TResponse,\n ContextSchema,\n TMiddleware,\n TSubagents,\n TTools\n > = {} as CreateDeepAgentParams<\n TResponse,\n ContextSchema,\n TMiddleware,\n TSubagents,\n TTools\n >,\n) {\n const {\n model = \"claude-sonnet-4-5-20250929\",\n tools = [],\n systemPrompt,\n middleware: customMiddleware = [],\n subagents = [],\n responseFormat,\n contextSchema,\n checkpointer,\n store,\n backend,\n interruptOn,\n name,\n memory,\n skills,\n } = params;\n\n // Combine system prompt with base prompt like Python implementation\n const finalSystemPrompt = systemPrompt\n ? typeof systemPrompt === \"string\"\n ? `${systemPrompt}\\n\\n${BASE_PROMPT}`\n : new SystemMessage({\n content: [\n {\n type: \"text\",\n text: BASE_PROMPT,\n },\n ...(typeof systemPrompt.content === \"string\"\n ? [{ type: \"text\", text: systemPrompt.content }]\n : systemPrompt.content),\n ],\n })\n : BASE_PROMPT;\n\n // Create backend configuration for filesystem middleware\n // If no backend is provided, use a factory that creates a StateBackend\n const filesystemBackend = backend\n ? backend\n : (config: { state: unknown; store?: BaseStore }) =>\n new StateBackend(config);\n\n // Add skills middleware if skill sources provided\n const skillsMiddleware =\n skills != null && skills.length > 0\n ? [\n createSkillsMiddleware({\n backend: filesystemBackend,\n sources: skills,\n }),\n ]\n : [];\n\n // Built-in middleware array\n const builtInMiddleware = [\n // Provides todo list management capabilities for tracking tasks\n todoListMiddleware(),\n // Add skills middleware if skill sources provided\n ...skillsMiddleware,\n // Enables filesystem operations and optional long-term memory storage\n createFilesystemMiddleware({ backend: filesystemBackend }),\n // Enables delegation to specialized subagents for complex tasks\n createSubAgentMiddleware({\n defaultModel: model,\n defaultTools: tools as StructuredTool[],\n defaultMiddleware: [\n // Subagent middleware: Todo list management\n todoListMiddleware(),\n // Subagent middleware: Skills (if provided)\n ...skillsMiddleware,\n // Subagent middleware: Filesystem operations\n createFilesystemMiddleware({\n backend: filesystemBackend,\n }),\n // Subagent middleware: Automatic conversation summarization when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Subagent middleware: Anthropic prompt caching for improved performance\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Subagent middleware: Patches tool calls for compatibility\n createPatchToolCallsMiddleware(),\n ],\n defaultInterruptOn: interruptOn,\n subagents: subagents as unknown as (SubAgent | CompiledSubAgent)[],\n generalPurposeAgent: true,\n }),\n // Automatically summarizes conversation history when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Enables Anthropic prompt caching for improved performance and reduced costs\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Patches tool calls to ensure compatibility across different model providers\n createPatchToolCallsMiddleware(),\n // Add memory middleware if memory sources provided\n ...(memory != null && memory.length > 0\n ? [\n createMemoryMiddleware({\n backend: filesystemBackend,\n sources: memory,\n }),\n ]\n : []),\n ] as const;\n\n // Add human-in-the-loop middleware if interrupt config provided\n if (interruptOn) {\n // builtInMiddleware is typed as readonly to enable type inference\n // however, we need to push to it to add the middleware, so let's ignore the type error\n // @ts-expect-error - builtInMiddleware is readonly\n builtInMiddleware.push(humanInTheLoopMiddleware({ interruptOn }));\n }\n\n // Combine built-in middleware with custom middleware\n // The custom middleware is typed as TMiddleware to preserve type information\n const allMiddleware = [\n ...builtInMiddleware,\n ...(customMiddleware as unknown as TMiddleware),\n ] as const;\n\n // Note: Recursion limit of 1000 (matching Python behavior) should be passed\n // at invocation time: agent.invoke(input, { recursionLimit: 1000 })\n const agent = createAgent({\n model,\n systemPrompt: finalSystemPrompt,\n tools: tools as StructuredTool[],\n middleware: allMiddleware as unknown as AgentMiddleware[],\n responseFormat: responseFormat as ResponseFormat,\n contextSchema,\n checkpointer,\n store,\n name,\n });\n\n // Combine custom middleware with flattened subagent middleware for complete type inference\n // This ensures InferMiddlewareStates captures state from both sources\n type AllMiddleware = readonly [\n ...typeof builtInMiddleware,\n ...TMiddleware,\n ...FlattenSubAgentMiddleware<TSubagents>,\n ];\n\n // Return as DeepAgent with proper DeepAgentTypeConfig\n // - Response: TResponse (from responseFormat parameter)\n // - State: undefined (state comes from middleware)\n // - Context: ContextSchema\n // - Middleware: AllMiddleware (built-in + custom + subagent middleware for state inference)\n // - Tools: TTools\n // - Subagents: TSubagents (for type-safe streaming)\n return agent as unknown as DeepAgent<\n DeepAgentTypeConfig<\n TResponse,\n undefined,\n ContextSchema,\n AllMiddleware,\n TTools,\n TSubagents\n >\n >;\n}\n","/**\n * Configuration and settings for deepagents.\n *\n * Provides project detection, path management, and environment configuration\n * for skills and agent memory middleware.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\n/**\n * Options for creating a Settings instance.\n */\nexport interface SettingsOptions {\n /** Starting directory for project detection (defaults to cwd) */\n startPath?: string;\n}\n\n/**\n * Settings interface for project detection and path management.\n *\n * Provides access to:\n * - Project root detection (via .git directory)\n * - User-level deepagents directory (~/.deepagents)\n * - Agent-specific directories and files\n * - Skills directories (user and project level)\n */\nexport interface Settings {\n /** Detected project root directory, or null if not in a git project */\n readonly projectRoot: string | null;\n\n /** Base user-level .deepagents directory (~/.deepagents) */\n readonly userDeepagentsDir: string;\n\n /** Check if currently in a git project */\n readonly hasProject: boolean;\n\n /**\n * Get the agent directory path.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}\n * @throws Error if agent name is invalid\n */\n getAgentDir(agentName: string): string;\n\n /**\n * Ensure agent directory exists and return path.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}\n * @throws Error if agent name is invalid\n */\n ensureAgentDir(agentName: string): string;\n\n /**\n * Get user-level agent.md path for a specific agent.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}/agent.md\n */\n getUserAgentMdPath(agentName: string): string;\n\n /**\n * Get project-level agent.md path.\n * @returns Path to {projectRoot}/.deepagents/agent.md, or null if not in a project\n */\n getProjectAgentMdPath(): string | null;\n\n /**\n * Get user-level skills directory path for a specific agent.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}/skills/\n */\n getUserSkillsDir(agentName: string): string;\n\n /**\n * Ensure user-level skills directory exists and return path.\n * @param agentName - Name of the agent\n * @returns Path to ~/.deepagents/{agentName}/skills/\n */\n ensureUserSkillsDir(agentName: string): string;\n\n /**\n * Get project-level skills directory path.\n * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project\n */\n getProjectSkillsDir(): string | null;\n\n /**\n * Ensure project-level skills directory exists and return path.\n * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project\n */\n ensureProjectSkillsDir(): string | null;\n\n /**\n * Ensure project .deepagents directory exists.\n * @returns Path to {projectRoot}/.deepagents/, or null if not in a project\n */\n ensureProjectDeepagentsDir(): string | null;\n}\n\n/**\n * Find the project root by looking for .git directory.\n *\n * Walks up the directory tree from startPath (or cwd) looking for a .git\n * directory, which indicates the project root.\n *\n * @param startPath - Directory to start searching from. Defaults to current working directory.\n * @returns Path to the project root if found, null otherwise.\n */\nexport function findProjectRoot(startPath?: string): string | null {\n let current = path.resolve(startPath || process.cwd());\n\n // Walk up the directory tree\n while (current !== path.dirname(current)) {\n const gitDir = path.join(current, \".git\");\n if (fs.existsSync(gitDir)) {\n return current;\n }\n current = path.dirname(current);\n }\n\n // Check root directory as well\n const rootGitDir = path.join(current, \".git\");\n if (fs.existsSync(rootGitDir)) {\n return current;\n }\n\n return null;\n}\n\n/**\n * Validate agent name to prevent invalid filesystem paths and security issues.\n *\n * @param agentName - The agent name to validate\n * @returns True if valid, false otherwise\n */\nfunction isValidAgentName(agentName: string): boolean {\n if (!agentName || !agentName.trim()) {\n return false;\n }\n // Allow only alphanumeric, hyphens, underscores, and whitespace\n return /^[a-zA-Z0-9_\\-\\s]+$/.test(agentName);\n}\n\n/**\n * Create a Settings instance with detected environment.\n *\n * @param options - Configuration options\n * @returns Settings instance with project detection and path management\n */\nexport function createSettings(options: SettingsOptions = {}): Settings {\n const projectRoot = findProjectRoot(options.startPath);\n const userDeepagentsDir = path.join(os.homedir(), \".deepagents\");\n\n return {\n projectRoot,\n userDeepagentsDir,\n hasProject: projectRoot !== null,\n\n getAgentDir(agentName: string): string {\n if (!isValidAgentName(agentName)) {\n throw new Error(\n `Invalid agent name: ${JSON.stringify(agentName)}. ` +\n \"Agent names can only contain letters, numbers, hyphens, underscores, and spaces.\",\n );\n }\n return path.join(userDeepagentsDir, agentName);\n },\n\n ensureAgentDir(agentName: string): string {\n const agentDir = this.getAgentDir(agentName);\n fs.mkdirSync(agentDir, { recursive: true });\n return agentDir;\n },\n\n getUserAgentMdPath(agentName: string): string {\n return path.join(this.getAgentDir(agentName), \"agent.md\");\n },\n\n getProjectAgentMdPath(): string | null {\n if (!projectRoot) {\n return null;\n }\n return path.join(projectRoot, \".deepagents\", \"agent.md\");\n },\n\n getUserSkillsDir(agentName: string): string {\n return path.join(this.getAgentDir(agentName), \"skills\");\n },\n\n ensureUserSkillsDir(agentName: string): string {\n const skillsDir = this.getUserSkillsDir(agentName);\n fs.mkdirSync(skillsDir, { recursive: true });\n return skillsDir;\n },\n\n getProjectSkillsDir(): string | null {\n if (!projectRoot) {\n return null;\n }\n return path.join(projectRoot, \".deepagents\", \"skills\");\n },\n\n ensureProjectSkillsDir(): string | null {\n const skillsDir = this.getProjectSkillsDir();\n if (!skillsDir) {\n return null;\n }\n fs.mkdirSync(skillsDir, { recursive: true });\n return skillsDir;\n },\n\n ensureProjectDeepagentsDir(): string | null {\n if (!projectRoot) {\n return null;\n }\n const deepagentsDir = path.join(projectRoot, \".deepagents\");\n fs.mkdirSync(deepagentsDir, { recursive: true });\n return deepagentsDir;\n },\n };\n}\n","/**\n * Middleware for loading agent-specific long-term memory into the system prompt.\n *\n * This middleware loads the agent's long-term memory from agent.md files\n * and injects it into the system prompt. Memory is loaded from:\n * - User memory: ~/.deepagents/{agent_name}/agent.md\n * - Project memory: {project_root}/.deepagents/agent.md\n */\n\nimport fs from \"node:fs\";\nimport { z } from \"zod\";\nimport {\n createMiddleware,\n /**\n * required for type inference\n */\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\n\nimport type { Settings } from \"../config.js\";\n\n/**\n * Options for the agent memory middleware.\n */\nexport interface AgentMemoryMiddlewareOptions {\n /** Settings instance with project detection and paths */\n settings: Settings;\n\n /** The agent identifier */\n assistantId: string;\n\n /** Optional custom template for injecting agent memory into system prompt */\n systemPromptTemplate?: string;\n}\n\n/**\n * State schema for agent memory middleware.\n */\nconst AgentMemoryStateSchema = z.object({\n /** Personal preferences from ~/.deepagents/{agent}/ (applies everywhere) */\n userMemory: z.string().optional(),\n\n /** Project-specific context (loaded from project root) */\n projectMemory: z.string().optional(),\n});\n\n/**\n * Default template for memory injection.\n */\nconst DEFAULT_MEMORY_TEMPLATE = `<user_memory>\n{user_memory}\n</user_memory>\n\n<project_memory>\n{project_memory}\n</project_memory>`;\n\n/**\n * Long-term Memory Documentation system prompt.\n */\nconst LONGTERM_MEMORY_SYSTEM_PROMPT = `\n\n## Long-term Memory\n\nYour long-term memory is stored in files on the filesystem and persists across sessions.\n\n**User Memory Location**: \\`{agent_dir_absolute}\\` (displays as \\`{agent_dir_display}\\`)\n**Project Memory Location**: {project_memory_info}\n\nYour system prompt is loaded from TWO sources at startup:\n1. **User agent.md**: \\`{agent_dir_absolute}/agent.md\\` - Your personal preferences across all projects\n2. **Project agent.md**: Loaded from project root if available - Project-specific instructions\n\nProject-specific agent.md is loaded from these locations (both combined if both exist):\n- \\`[project-root]/.deepagents/agent.md\\` (preferred)\n- \\`[project-root]/agent.md\\` (fallback, but also included if both exist)\n\n**When to CHECK/READ memories (CRITICAL - do this FIRST):**\n- **At the start of ANY new session**: Check both user and project memories\n - User: \\`ls {agent_dir_absolute}\\`\n - Project: \\`ls {project_deepagents_dir}\\` (if in a project)\n- **BEFORE answering questions**: If asked \"what do you know about X?\" or \"how do I do Y?\", check project memories FIRST, then user\n- **When user asks you to do something**: Check if you have project-specific guides or examples\n- **When user references past work**: Search project memory files for related context\n\n**Memory-first response pattern:**\n1. User asks a question → Check project directory first: \\`ls {project_deepagents_dir}\\`\n2. If relevant files exist → Read them with \\`read_file '{project_deepagents_dir}/[filename]'\\`\n3. Check user memory if needed → \\`ls {agent_dir_absolute}\\`\n4. Base your answer on saved knowledge supplemented by general knowledge\n\n**When to update memories:**\n- **IMMEDIATELY when the user describes your role or how you should behave**\n- **IMMEDIATELY when the user gives feedback on your work** - Update memories to capture what was wrong and how to do it better\n- When the user explicitly asks you to remember something\n- When patterns or preferences emerge (coding styles, conventions, workflows)\n- After significant work where context would help in future sessions\n\n**Learning from feedback:**\n- When user says something is better/worse, capture WHY and encode it as a pattern\n- Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions\n- When user says \"you should remember X\" or \"be careful about Y\", treat this as HIGH PRIORITY - update memories IMMEDIATELY\n- Look for the underlying principle behind corrections, not just the specific mistake\n\n## Deciding Where to Store Memory\n\nWhen writing or updating agent memory, decide whether each fact, configuration, or behavior belongs in:\n\n### User Agent File: \\`{agent_dir_absolute}/agent.md\\`\n→ Describes the agent's **personality, style, and universal behavior** across all projects.\n\n**Store here:**\n- Your general tone and communication style\n- Universal coding preferences (formatting, comment style, etc.)\n- General workflows and methodologies you follow\n- Tool usage patterns that apply everywhere\n- Personal preferences that don't change per-project\n\n**Examples:**\n- \"Be concise and direct in responses\"\n- \"Always use type hints in Python\"\n- \"Prefer functional programming patterns\"\n\n### Project Agent File: \\`{project_deepagents_dir}/agent.md\\`\n→ Describes **how this specific project works** and **how the agent should behave here only.**\n\n**Store here:**\n- Project-specific architecture and design patterns\n- Coding conventions specific to this codebase\n- Project structure and organization\n- Testing strategies for this project\n- Deployment processes and workflows\n- Team conventions and guidelines\n\n**Examples:**\n- \"This project uses FastAPI with SQLAlchemy\"\n- \"Tests go in tests/ directory mirroring src/ structure\"\n- \"All API changes require updating OpenAPI spec\"\n\n### Project Memory Files: \\`{project_deepagents_dir}/*.md\\`\n→ Use for **project-specific reference information** and structured notes.\n\n**Store here:**\n- API design documentation\n- Architecture decisions and rationale\n- Deployment procedures\n- Common debugging patterns\n- Onboarding information\n\n**Examples:**\n- \\`{project_deepagents_dir}/api-design.md\\` - REST API patterns used\n- \\`{project_deepagents_dir}/architecture.md\\` - System architecture overview\n- \\`{project_deepagents_dir}/deployment.md\\` - How to deploy this project\n\n### File Operations:\n\n**User memory:**\n\\`\\`\\`\nls {agent_dir_absolute} # List user memory files\nread_file '{agent_dir_absolute}/agent.md' # Read user preferences\nedit_file '{agent_dir_absolute}/agent.md' ... # Update user preferences\n\\`\\`\\`\n\n**Project memory (preferred for project-specific information):**\n\\`\\`\\`\nls {project_deepagents_dir} # List project memory files\nread_file '{project_deepagents_dir}/agent.md' # Read project instructions\nedit_file '{project_deepagents_dir}/agent.md' ... # Update project instructions\nwrite_file '{project_deepagents_dir}/agent.md' ... # Create project memory file\n\\`\\`\\`\n\n**Important**:\n- Project memory files are stored in \\`.deepagents/\\` inside the project root\n- Always use absolute paths for file operations\n- Check project memories BEFORE user when answering project-specific questions`;\n\n/**\n * Create middleware for loading agent-specific long-term memory.\n *\n * This middleware loads the agent's long-term memory from a file (agent.md)\n * and injects it into the system prompt. The memory is loaded once at the\n * start of the conversation and stored in state.\n *\n * @param options - Configuration options\n * @returns AgentMiddleware for memory loading and injection\n */\nexport function createAgentMemoryMiddleware(\n options: AgentMemoryMiddlewareOptions,\n) {\n const { settings, assistantId, systemPromptTemplate } = options;\n\n // Compute paths\n const agentDir = settings.getAgentDir(assistantId);\n const agentDirDisplay = `~/.deepagents/${assistantId}`;\n const agentDirAbsolute = agentDir;\n const projectRoot = settings.projectRoot;\n\n // Build project memory info for documentation\n const projectMemoryInfo = projectRoot\n ? `\\`${projectRoot}\\` (detected)`\n : \"None (not in a git project)\";\n\n // Build project deepagents directory path\n const projectDeepagentsDir = projectRoot\n ? `${projectRoot}/.deepagents`\n : \"[project-root]/.deepagents (not in a project)\";\n\n const template = systemPromptTemplate || DEFAULT_MEMORY_TEMPLATE;\n\n return createMiddleware({\n name: \"AgentMemoryMiddleware\",\n stateSchema: AgentMemoryStateSchema as any,\n\n beforeAgent(state: any) {\n const result: Record<string, string> = {};\n\n // Load user memory if not already in state\n if (!(\"userMemory\" in state)) {\n const userPath = settings.getUserAgentMdPath(assistantId);\n if (fs.existsSync(userPath)) {\n try {\n result.userMemory = fs.readFileSync(userPath, \"utf-8\");\n } catch {\n // Ignore read errors\n }\n }\n }\n\n // Load project memory if not already in state\n if (!(\"projectMemory\" in state)) {\n const projectPath = settings.getProjectAgentMdPath();\n if (projectPath && fs.existsSync(projectPath)) {\n try {\n result.projectMemory = fs.readFileSync(projectPath, \"utf-8\");\n } catch {\n // Ignore read errors\n }\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n },\n\n wrapModelCall(request: any, handler: any) {\n // Extract memory from state\n const userMemory = request.state?.userMemory;\n const projectMemory = request.state?.projectMemory;\n const baseSystemPrompt = request.systemPrompt || \"\";\n\n // Format memory section with both memories\n const memorySection = template\n .replace(\"{user_memory}\", userMemory || \"(No user agent.md)\")\n .replace(\"{project_memory}\", projectMemory || \"(No project agent.md)\");\n\n // Format long-term memory documentation\n const memoryDocs = LONGTERM_MEMORY_SYSTEM_PROMPT.replaceAll(\n \"{agent_dir_absolute}\",\n agentDirAbsolute,\n )\n .replaceAll(\"{agent_dir_display}\", agentDirDisplay)\n .replaceAll(\"{project_memory_info}\", projectMemoryInfo)\n .replaceAll(\"{project_deepagents_dir}\", projectDeepagentsDir);\n\n // Memory content at start, base prompt in middle, documentation at end\n let systemPrompt = memorySection;\n if (baseSystemPrompt) {\n systemPrompt += \"\\n\\n\" + baseSystemPrompt;\n }\n systemPrompt += \"\\n\\n\" + memoryDocs;\n\n return handler({ ...request, systemPrompt });\n },\n });\n}\n","/**\n * Skill loader for parsing and loading agent skills from SKILL.md files.\n *\n * This module implements Anthropic's agent skills pattern with YAML frontmatter parsing.\n * Each skill is a directory containing a SKILL.md file with:\n * - YAML frontmatter (name, description required)\n * - Markdown instructions for the agent\n * - Optional supporting files (scripts, configs, etc.)\n *\n * @example\n * ```markdown\n * ---\n * name: web-research\n * description: Structured approach to conducting thorough web research\n * ---\n *\n * # Web Research Skill\n *\n * ## When to Use\n * - User asks you to research a topic\n * ...\n * ```\n *\n * @see https://agentskills.io/specification\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport yaml from \"yaml\";\n\n/** Maximum size for SKILL.md files (10MB) */\nexport const MAX_SKILL_FILE_SIZE = 10 * 1024 * 1024;\n\n/** Agent Skills spec constraints */\nexport const MAX_SKILL_NAME_LENGTH = 64;\nexport const MAX_SKILL_DESCRIPTION_LENGTH = 1024;\n\n/** Pattern for validating skill names per Agent Skills spec */\nconst SKILL_NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n/** Pattern for extracting YAML frontmatter */\nconst FRONTMATTER_PATTERN = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/;\n\n/**\n * Metadata for a skill per Agent Skills spec.\n * @see https://agentskills.io/specification\n */\nexport interface SkillMetadata {\n /** Name of the skill (max 64 chars, lowercase alphanumeric and hyphens) */\n name: string;\n\n /** Description of what the skill does (max 1024 chars) */\n description: string;\n\n /** Absolute path to the SKILL.md file */\n path: string;\n\n /** Source of the skill ('user' or 'project') */\n source: \"user\" | \"project\";\n\n /** Optional: License name or reference to bundled license file */\n license?: string;\n\n /** Optional: Environment requirements (max 500 chars) */\n compatibility?: string;\n\n /** Optional: Arbitrary key-value mapping for additional metadata */\n metadata?: Record<string, string>;\n\n /** Optional: Space-delimited list of pre-approved tools */\n allowedTools?: string;\n}\n\n/**\n * Options for listing skills.\n */\nexport interface ListSkillsOptions {\n /** Path to user-level skills directory */\n userSkillsDir?: string | null;\n\n /** Path to project-level skills directory */\n projectSkillsDir?: string | null;\n}\n\n/**\n * Result of skill name validation.\n */\ninterface ValidationResult {\n valid: boolean;\n error?: string;\n}\n\n/**\n * Check if a path is safely contained within base_dir.\n *\n * This prevents directory traversal attacks via symlinks or path manipulation.\n * The function resolves both paths to their canonical form (following symlinks)\n * and verifies that the target path is within the base directory.\n *\n * @param targetPath - The path to validate\n * @param baseDir - The base directory that should contain the path\n * @returns True if the path is safely within baseDir, false otherwise\n */\nfunction isSafePath(targetPath: string, baseDir: string): boolean {\n try {\n // Resolve both paths to their canonical form (follows symlinks)\n const resolvedPath = fs.realpathSync(targetPath);\n const resolvedBase = fs.realpathSync(baseDir);\n\n // Check if the resolved path is within the base directory\n return (\n resolvedPath.startsWith(resolvedBase + path.sep) ||\n resolvedPath === resolvedBase\n );\n } catch {\n // Error resolving paths (e.g., circular symlinks, too many levels)\n return false;\n }\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n *\n * Requirements:\n * - Max 64 characters\n * - Lowercase alphanumeric and hyphens only (a-z, 0-9, -)\n * - Cannot start or end with hyphen\n * - No consecutive hyphens\n * - Must match parent directory name\n *\n * @param name - The skill name from YAML frontmatter\n * @param directoryName - The parent directory name\n * @returns Validation result with error message if invalid\n */\nfunction validateSkillName(\n name: string,\n directoryName: string,\n): ValidationResult {\n if (!name) {\n return { valid: false, error: \"name is required\" };\n }\n if (name.length > MAX_SKILL_NAME_LENGTH) {\n return { valid: false, error: \"name exceeds 64 characters\" };\n }\n // Pattern: lowercase alphanumeric, single hyphens between segments, no start/end hyphen\n if (!SKILL_NAME_PATTERN.test(name)) {\n return {\n valid: false,\n error: \"name must be lowercase alphanumeric with single hyphens only\",\n };\n }\n if (name !== directoryName) {\n return {\n valid: false,\n error: `name '${name}' must match directory name '${directoryName}'`,\n };\n }\n return { valid: true };\n}\n\n/**\n * Parse YAML frontmatter from content.\n *\n * @param content - The file content\n * @returns Parsed frontmatter object, or null if parsing fails\n */\nfunction parseFrontmatter(content: string): Record<string, unknown> | null {\n const match = content.match(FRONTMATTER_PATTERN);\n if (!match) {\n return null;\n }\n\n try {\n const parsed = yaml.parse(match[1]);\n return typeof parsed === \"object\" && parsed !== null ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Parse YAML frontmatter from a SKILL.md file per Agent Skills spec.\n *\n * @param skillMdPath - Path to the SKILL.md file\n * @param source - Source of the skill ('user' or 'project')\n * @returns SkillMetadata with all fields, or null if parsing fails\n */\nexport function parseSkillMetadata(\n skillMdPath: string,\n source: \"user\" | \"project\",\n): SkillMetadata | null {\n try {\n // Security: Check file size to prevent DoS attacks\n const stats = fs.statSync(skillMdPath);\n if (stats.size > MAX_SKILL_FILE_SIZE) {\n // eslint-disable-next-line no-console\n console.warn(\n `Skipping ${skillMdPath}: file too large (${stats.size} bytes)`,\n );\n return null;\n }\n\n const content = fs.readFileSync(skillMdPath, \"utf-8\");\n const frontmatter = parseFrontmatter(content);\n\n if (!frontmatter) {\n // eslint-disable-next-line no-console\n console.warn(`Skipping ${skillMdPath}: no valid YAML frontmatter found`);\n return null;\n }\n\n // Validate required fields\n const name = frontmatter.name;\n const description = frontmatter.description;\n\n if (!name || !description) {\n // eslint-disable-next-line no-console\n console.warn(\n `Skipping ${skillMdPath}: missing required 'name' or 'description'`,\n );\n return null;\n }\n\n // Validate name format per spec (warn but still load for backwards compatibility)\n const directoryName = path.basename(path.dirname(skillMdPath));\n const validation = validateSkillName(String(name), directoryName);\n if (!validation.valid) {\n // eslint-disable-next-line no-console\n console.warn(\n `Skill '${name}' in ${skillMdPath} does not follow Agent Skills spec: ${validation.error}. ` +\n \"Consider renaming to be spec-compliant.\",\n );\n }\n\n // Truncate description if too long (spec: max 1024 chars)\n let descriptionStr = String(description);\n if (descriptionStr.length > MAX_SKILL_DESCRIPTION_LENGTH) {\n // eslint-disable-next-line no-console\n console.warn(\n `Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH} chars in ${skillMdPath}, truncating`,\n );\n descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH);\n }\n\n return {\n name: String(name),\n description: descriptionStr,\n path: skillMdPath,\n source,\n license: frontmatter.license ? String(frontmatter.license) : undefined,\n compatibility: frontmatter.compatibility\n ? String(frontmatter.compatibility)\n : undefined,\n metadata:\n frontmatter.metadata && typeof frontmatter.metadata === \"object\"\n ? (frontmatter.metadata as Record<string, string>)\n : undefined,\n allowedTools: frontmatter[\"allowed-tools\"]\n ? String(frontmatter[\"allowed-tools\"])\n : undefined,\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(`Error reading ${skillMdPath}: ${error}`);\n return null;\n }\n}\n\n/**\n * List all skills from a single skills directory (internal helper).\n *\n * Scans the skills directory for subdirectories containing SKILL.md files,\n * parses YAML frontmatter, and returns skill metadata.\n *\n * Skills are organized as:\n * ```\n * skills/\n * ├── skill-name/\n * │ ├── SKILL.md # Required: instructions with YAML frontmatter\n * │ ├── script.py # Optional: supporting files\n * │ └── config.json # Optional: supporting files\n * ```\n *\n * @param skillsDir - Path to the skills directory\n * @param source - Source of the skills ('user' or 'project')\n * @returns List of skill metadata\n */\nfunction listSkillsFromDir(\n skillsDir: string,\n source: \"user\" | \"project\",\n): SkillMetadata[] {\n // Check if skills directory exists\n const expandedDir = skillsDir.startsWith(\"~\")\n ? path.join(\n process.env.HOME || process.env.USERPROFILE || \"\",\n skillsDir.slice(1),\n )\n : skillsDir;\n\n if (!fs.existsSync(expandedDir)) {\n return [];\n }\n\n // Resolve base directory to canonical path for security checks\n let resolvedBase: string;\n try {\n resolvedBase = fs.realpathSync(expandedDir);\n } catch {\n // Can't resolve base directory, fail safe\n return [];\n }\n\n const skills: SkillMetadata[] = [];\n\n // Iterate through subdirectories\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(resolvedBase, { withFileTypes: true });\n } catch {\n return [];\n }\n\n for (const entry of entries) {\n const skillDir = path.join(resolvedBase, entry.name);\n\n // Security: Catch symlinks pointing outside the skills directory\n if (!isSafePath(skillDir, resolvedBase)) {\n continue;\n }\n\n if (!entry.isDirectory()) {\n continue;\n }\n\n // Look for SKILL.md file\n const skillMdPath = path.join(skillDir, \"SKILL.md\");\n if (!fs.existsSync(skillMdPath)) {\n continue;\n }\n\n // Security: Validate SKILL.md path is safe before reading\n if (!isSafePath(skillMdPath, resolvedBase)) {\n continue;\n }\n\n // Parse metadata\n const metadata = parseSkillMetadata(skillMdPath, source);\n if (metadata) {\n skills.push(metadata);\n }\n }\n\n return skills;\n}\n\n/**\n * List skills from user and/or project directories.\n *\n * When both directories are provided, project skills with the same name as\n * user skills will override them.\n *\n * @param options - Options specifying which directories to search\n * @returns Merged list of skill metadata from both sources, with project skills\n * taking precedence over user skills when names conflict\n */\nexport function listSkills(options: ListSkillsOptions): SkillMetadata[] {\n const allSkills: Map<string, SkillMetadata> = new Map();\n\n // Load user skills first (foundation)\n if (options.userSkillsDir) {\n const userSkills = listSkillsFromDir(options.userSkillsDir, \"user\");\n for (const skill of userSkills) {\n allSkills.set(skill.name, skill);\n }\n }\n\n // Load project skills second (override/augment)\n if (options.projectSkillsDir) {\n const projectSkills = listSkillsFromDir(\n options.projectSkillsDir,\n \"project\",\n );\n for (const skill of projectSkills) {\n // Project skills override user skills with the same name\n allSkills.set(skill.name, skill);\n }\n }\n\n return Array.from(allSkills.values());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6QA,SAAgB,iBACd,SACmC;AACnC,QACE,OAAQ,QAAmC,YAAY,cACvD,OAAQ,QAAmC,OAAO;;;;;;;;;;;;ACrQtD,MAAa,wBACX;AACF,MAAa,kBAAkB;AAC/B,MAAa,oBAAoB;;;;;;A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