@mastra/core
Version:
1 lines • 955 kB
Source Map (JSON)
{"version":3,"file":"workspace-BVFsqhNw.cjs","names":["posixPath","PermissionError","FilesystemError","MastraBase","RegisteredLogger","normalizeTextExtension","isTextFile","FilesystemNotReadyError","resolveToBasePath","nodePath","expandTilde","realpathSync","isEnoentError","lstatSync","readlinkSync","PermissionError","WorkspaceReadOnlyError","fs","fsConstants","IsDirectoryError","FileNotFoundError","NotDirectoryError","DirectoryNotFoundError","StaleFileError","isEexistError","FileExistsError","DirectoryNotEmptyError","fsExists","fsStat","getMimeType","nodePath","nodePath","createHash","Readable","Writable","MastraBase","RegisteredLogger","importModule","readFileSync","existsSync","realpathSync","expandTilde","fs","realpathSync","path","posix","WorkspaceNotAvailableError","FilesystemNotAvailableError","SandboxNotAvailableError","FileNotFoundError","StaleFileError","createTool","z","WorkspaceReadOnlyError","createRequire","createTool","z","WorkspaceReadOnlyError","FileNotFoundError","SandboxFeatureNotSupportedError","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","createTool","z","WorkspaceReadOnlyError","createTool","z","WorkspaceReadOnlyError","createHash","isValidationError","z","SandboxFeatureNotSupportedError","createTool","createTool","z","FileNotFoundError","createTool","z","SandboxFeatureNotSupportedError","isEnoentError","createTool","z","isTextFile","isGlobPattern","extractGlobBase","createGlobMatcher","UnsupportedGrepPatternError","isEnoentError","isEnotdirError","createTool","z","createTool","z","SandboxFeatureNotSupportedError","createGlobMatcher","joinPath","DirectoryNotFoundError","NotDirectoryError","createTool","z","fs","fileURLToPath","createTool","z","createTool","z","WorkspaceReadOnlyError","createTool","z","z","createTool","createTool","z","WorkspaceReadOnlyError","path","nodePath","RequestContext","FileReadRequiredError","FileNotFoundError","posixPath","z","createRequire","pathToFileURL","fileURLToPath","createRequire","pathToFileURL","join","existsSync","parse","dirname","extractSkillFrontmatter","createTool","z","WorkspaceError","SearchEngine","ResolvedSourceWorkspaceSkills","RequestContext","WorkspaceSkillsImpl","LocalSkillSource","SearchNotAvailableError","SKILL_SCOPE_DOCUMENT_PREFIX","resolvePathPattern","splitIntoChunks","WorkspaceNotReadyError","toStandardSchema","standardSchemaToJSONSchema"],"sources":["../src/workspace/sandbox/utils.ts","../src/workspace/constants/index.ts","../src/workspace/lifecycle.ts","../src/workspace/filesystem/composite-filesystem.ts","../src/workspace/filesystem/mastra-filesystem.ts","../src/workspace/utils.ts","../src/workspace/filesystem/local-filesystem.ts","../src/workspace/filesystem/file-read-tracker.ts","../src/workspace/filesystem/file-write-lock.ts","../src/workspace/sandbox/errors.ts","../src/workspace/sandbox/mounts/types.ts","../src/workspace/sandbox/mount-manager.ts","../src/workspace/sandbox/sandbox.ts","../src/workspace/sandbox/process-manager/process-handle.ts","../src/workspace/sandbox/mastra-sandbox.ts","../src/workspace/sandbox/execa.ts","../src/workspace/sandbox/process-manager/process-manager.ts","../src/workspace/sandbox/local-process-manager.ts","../src/workspace/sandbox/native-sandbox/detect.ts","../src/workspace/sandbox/native-sandbox/seatbelt.ts","../src/workspace/sandbox/native-sandbox/bubblewrap.ts","../src/workspace/sandbox/native-sandbox/wrapper.ts","../src/workspace/sandbox/local-sandbox.ts","../src/workspace/tools/apply-patch-parser.ts","../src/workspace/tools/helpers.ts","../src/workspace/tools/tracing.ts","../src/workspace/tools/apply-patch.ts","../src/workspace/tools/ast-edit.ts","../src/workspace/tools/media.ts","../src/workspace/tools/computer-helpers.ts","../src/workspace/tools/computer-click.ts","../src/workspace/tools/computer-double-click.ts","../src/workspace/tools/computer-drag.ts","../src/workspace/tools/computer-get-screen-info.ts","../src/workspace/tools/computer-move-mouse.ts","../src/workspace/tools/computer-press-key.ts","../src/workspace/tools/computer-right-click.ts","../src/workspace/tools/computer-screenshot.ts","../src/workspace/tools/computer-scroll.ts","../src/workspace/tools/computer-type.ts","../src/workspace/tools/computer-wait.ts","../src/workspace/tools/delete-file.ts","../src/workspace/line-utils.ts","../src/workspace/tools/edit-file.ts","../src/browser/cli-handler.ts","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.6.0/394289cb1bed8c542941f77748eea1a31bd3419018d0fb2ac7029ece2458cdd1/node_modules/tokenx/dist/index.mjs","../src/utils/slice-by-tokens.ts","../src/workspace/tools/output-helpers.ts","../src/workspace/tools/execute-command.ts","../src/workspace/tools/file-stat.ts","../src/workspace/tools/get-process-output.ts","../src/workspace/gitignore.ts","../src/workspace/tools/grep.ts","../src/workspace/tools/index-content.ts","../src/workspace/tools/kill-process.ts","../src/workspace/tools/tree-formatter.ts","../src/workspace/tools/list-files.ts","../src/workspace/tools/lsp-inspect.ts","../src/workspace/tools/mkdir.ts","../src/workspace/tools/read-file.ts","../src/workspace/tools/search.ts","../src/workspace/tools/write-file.ts","../src/workspace/tools/tools.ts","../src/workspace/lsp/language.ts","../src/workspace/lsp/client.ts","../src/workspace/lsp/servers.ts","../src/workspace/lsp/manager.ts","../src/workspace/skills/versioned-skill-source.ts","../src/workspace/skills/composite-versioned-skill-source.ts","../src/workspace/skills/publish.ts","../src/workspace/skills/tools.ts","../src/workspace/workspace.ts","../src/workspace/factory-sandbox.ts"],"sourcesContent":["/**\n * Shell-quote an argument for safe interpolation into a shell command string.\n * Safe characters (alphanumeric, `.`, `_`, `-`, `/`, `=`, `:`, `@`) pass through.\n * Everything else is wrapped in single quotes with embedded quotes escaped.\n */\nexport function shellQuote(arg: string): string {\n if (/^[a-zA-Z0-9._\\-\\/=:@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Result of splitting a shell command string.\n */\nexport interface ShellSplitResult {\n /** Command parts between operators */\n parts: string[];\n /** Operators that were found (&&, ||, ;) */\n operators: string[];\n}\n\n/**\n * Split a shell command string on operators (&&, ||, ;) while respecting quotes.\n *\n * This is a quote-aware splitter that won't split inside single or double quoted strings.\n * Handles escaped quotes within quoted strings.\n *\n * @example\n * ```typescript\n * splitShellCommand('echo \"hello && world\" && ls')\n * // => { parts: ['echo \"hello && world\"', 'ls'], operators: ['&&'] }\n *\n * splitShellCommand(\"bash -c 'cd /tmp && pwd' || echo fail\")\n * // => { parts: [\"bash -c 'cd /tmp && pwd'\", 'echo fail'], operators: ['||'] }\n * ```\n */\nexport function splitShellCommand(command: string): ShellSplitResult {\n const parts: string[] = [];\n const operators: string[] = [];\n\n let current = '';\n let i = 0;\n let inSingleQuote = false;\n let inDoubleQuote = false;\n\n while (i < command.length) {\n const char = command[i]!;\n const next = command[i + 1];\n\n // Handle escape sequences (backslash)\n if (char === '\\\\' && i + 1 < command.length) {\n current += char + next;\n i += 2;\n continue;\n }\n\n // Toggle quote states\n if (char === \"'\" && !inDoubleQuote) {\n inSingleQuote = !inSingleQuote;\n current += char;\n i++;\n continue;\n }\n\n if (char === '\"' && !inSingleQuote) {\n inDoubleQuote = !inDoubleQuote;\n current += char;\n i++;\n continue;\n }\n\n // Only check for operators when not inside quotes\n if (!inSingleQuote && !inDoubleQuote) {\n // Check for && or ||\n if ((char === '&' && next === '&') || (char === '|' && next === '|')) {\n parts.push(current.trim());\n operators.push(char + next);\n current = '';\n i += 2;\n // Skip whitespace after operator\n while (i < command.length && /\\s/.test(command[i]!)) i++;\n continue;\n }\n\n // Check for ;\n if (char === ';') {\n parts.push(current.trim());\n operators.push(';');\n current = '';\n i++;\n // Skip whitespace after operator\n while (i < command.length && /\\s/.test(command[i]!)) i++;\n continue;\n }\n }\n\n current += char;\n i++;\n }\n\n // Add the final part\n if (current.trim()) {\n parts.push(current.trim());\n }\n\n return { parts, operators };\n}\n\n/**\n * Reassemble command parts with their operators.\n *\n * @example\n * ```typescript\n * reassembleShellCommand(['echo hello', 'ls'], ['&&'])\n * // => 'echo hello && ls'\n * ```\n */\nexport function reassembleShellCommand(parts: string[], operators: string[]): string {\n let result = parts[0] ?? '';\n for (let i = 0; i < operators.length; i++) {\n result += ` ${operators[i]} ${parts[i + 1] ?? ''}`;\n }\n return result.trim();\n}\n","export const WORKSPACE_TOOLS_PREFIX = 'mastra_workspace' as const;\n\n/**\n * Workspace tool name constants.\n * Use these to reference workspace tools by name.\n *\n * @example\n * ```typescript\n * import { WORKSPACE_TOOLS } from '@mastra/core/workspace';\n *\n * if (toolName === WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND) {\n * // Handle sandbox execution\n * }\n * ```\n */\nexport const WORKSPACE_TOOLS = {\n FILESYSTEM: {\n READ_FILE: `${WORKSPACE_TOOLS_PREFIX}_read_file` as const,\n WRITE_FILE: `${WORKSPACE_TOOLS_PREFIX}_write_file` as const,\n EDIT_FILE: `${WORKSPACE_TOOLS_PREFIX}_edit_file` as const,\n LIST_FILES: `${WORKSPACE_TOOLS_PREFIX}_list_files` as const,\n DELETE: `${WORKSPACE_TOOLS_PREFIX}_delete` as const,\n FILE_STAT: `${WORKSPACE_TOOLS_PREFIX}_file_stat` as const,\n MKDIR: `${WORKSPACE_TOOLS_PREFIX}_mkdir` as const,\n GREP: `${WORKSPACE_TOOLS_PREFIX}_grep` as const,\n AST_EDIT: `${WORKSPACE_TOOLS_PREFIX}_ast_edit` as const,\n APPLY_PATCH: `${WORKSPACE_TOOLS_PREFIX}_apply_patch` as const,\n },\n SANDBOX: {\n EXECUTE_COMMAND: `${WORKSPACE_TOOLS_PREFIX}_execute_command` as const,\n GET_PROCESS_OUTPUT: `${WORKSPACE_TOOLS_PREFIX}_get_process_output` as const,\n KILL_PROCESS: `${WORKSPACE_TOOLS_PREFIX}_kill_process` as const,\n },\n COMPUTER: {\n SCREENSHOT: `${WORKSPACE_TOOLS_PREFIX}_computer_screenshot` as const,\n CLICK: `${WORKSPACE_TOOLS_PREFIX}_computer_click` as const,\n DOUBLE_CLICK: `${WORKSPACE_TOOLS_PREFIX}_computer_double_click` as const,\n RIGHT_CLICK: `${WORKSPACE_TOOLS_PREFIX}_computer_right_click` as const,\n MOVE_MOUSE: `${WORKSPACE_TOOLS_PREFIX}_computer_move_mouse` as const,\n DRAG: `${WORKSPACE_TOOLS_PREFIX}_computer_drag` as const,\n TYPE: `${WORKSPACE_TOOLS_PREFIX}_computer_type` as const,\n PRESS_KEY: `${WORKSPACE_TOOLS_PREFIX}_computer_press_key` as const,\n SCROLL: `${WORKSPACE_TOOLS_PREFIX}_computer_scroll` as const,\n GET_SCREEN_INFO: `${WORKSPACE_TOOLS_PREFIX}_computer_get_screen_info` as const,\n WAIT: `${WORKSPACE_TOOLS_PREFIX}_computer_wait` as const,\n },\n SEARCH: {\n SEARCH: `${WORKSPACE_TOOLS_PREFIX}_search` as const,\n INDEX: `${WORKSPACE_TOOLS_PREFIX}_index` as const,\n },\n LSP: {\n LSP_INSPECT: `${WORKSPACE_TOOLS_PREFIX}_lsp_inspect` as const,\n },\n} as const;\n\n/**\n * Type representing any workspace tool name.\n */\nexport type WorkspaceToolName =\n | (typeof WORKSPACE_TOOLS.FILESYSTEM)[keyof typeof WORKSPACE_TOOLS.FILESYSTEM]\n | (typeof WORKSPACE_TOOLS.SEARCH)[keyof typeof WORKSPACE_TOOLS.SEARCH]\n | (typeof WORKSPACE_TOOLS.SANDBOX)[keyof typeof WORKSPACE_TOOLS.SANDBOX]\n | (typeof WORKSPACE_TOOLS.COMPUTER)[keyof typeof WORKSPACE_TOOLS.COMPUTER]\n | (typeof WORKSPACE_TOOLS.LSP)[keyof typeof WORKSPACE_TOOLS.LSP];\n","/**\n * Workspace Lifecycle Interfaces\n *\n * Defines lifecycle contracts for workspace providers (filesystem, sandbox).\n * The base `Lifecycle` holds shared members while `FilesystemLifecycle` and\n * `SandboxLifecycle` add the methods each provider kind actually uses.\n */\n\nimport type { SandboxStartOptions } from './sandbox/mastra-sandbox';\n\n// =============================================================================\n// Base Lifecycle Interface\n// =============================================================================\n\n/**\n * Shared lifecycle base for workspace providers.\n *\n * Contains status tracking, destroy, readiness check, and info retrieval.\n * Provider-specific lifecycle methods live in the extended interfaces:\n * - {@link FilesystemLifecycle} adds `init()`\n * - {@link SandboxLifecycle} adds `start()` / `stop()`\n *\n * @typeParam TInfo - The type returned by getInfo() (e.g., FilesystemInfo, SandboxInfo)\n */\nexport interface Lifecycle<TInfo = unknown> {\n /** Current status */\n status: ProviderStatus;\n\n /** Error message when status is 'error' */\n error?: string;\n\n /**\n * Clean up all resources.\n *\n * Called when the workspace is being permanently shut down.\n * Use for operations like:\n * - Terminating cloud instances\n * - Closing all connections\n * - Cleaning up temporary files\n */\n destroy?(): void | Promise<void>;\n\n /** @deprecated Use `status === 'running'` instead. */\n isReady?(): boolean | Promise<boolean>;\n\n /**\n * Get status and metadata.\n *\n * Returns information about the current state of the provider.\n */\n getInfo?(): TInfo | Promise<TInfo>;\n}\n\n// =============================================================================\n// Filesystem Lifecycle\n// =============================================================================\n\n/**\n * Lifecycle interface for filesystem providers (two-phase: init → destroy).\n *\n * @typeParam TInfo - The type returned by getInfo()\n */\nexport interface FilesystemLifecycle<TInfo = unknown> extends Lifecycle<TInfo> {\n /**\n * One-time setup operations.\n *\n * Called once when the workspace is first initialized.\n * Use for operations like:\n * - Creating base directories\n * - Setting up database tables\n * - Provisioning cloud resources\n * - Installing dependencies\n */\n init?(): void | Promise<void>;\n}\n\n// =============================================================================\n// Sandbox Lifecycle\n// =============================================================================\n\n/**\n * How a sandbox `start()` acquired its VM.\n *\n * - `'created'`: this start provisioned a fresh VM.\n * - `'connected'`: this start reconnected to (or resumed) a VM that already\n * existed. Providers deliberately don't distinguish resume from plain\n * reconnect — most SDKs can't report it honestly.\n */\nexport type SandboxStartOutcome = 'created' | 'connected';\n\n/**\n * Result reported by a sandbox provider's `start()`.\n *\n * Providers that implement the id-keyed getOrCreate contract report the\n * acquisition outcome. Providers that don't yet report return `void`, which\n * callers treat as \"unknown\". Callers joining a coalesced start share the one\n * attempt's result.\n */\nexport interface SandboxStartResult {\n /** `'created'` when start() provisioned a fresh VM; `'connected'` when it reconnected to / resumed an existing one. */\n outcome: SandboxStartOutcome;\n}\n\n/**\n * Lifecycle interface for sandbox providers (three-phase: start → stop → destroy).\n *\n * @typeParam TInfo - The type returned by getInfo()\n */\nexport interface SandboxLifecycle<TInfo = unknown> extends Lifecycle<TInfo> {\n /**\n * Begin active operation.\n *\n * Called to transition from initialized to running state.\n * Use for operations like:\n * - Establishing connection pools\n * - Spinning up cloud instances\n * - Starting background processes\n * - Warming up caches\n *\n * Id-keyed getOrCreate contract: a sandbox constructed with a known `id`\n * resolves that id on start — reconnect/resume when the provider finds an\n * existing VM for it, create otherwise — and reports which via\n * {@link SandboxStartResult}. Returning `void` means \"unknown\" (provider\n * not yet migrated); callers fall back to sentinel-guarded idempotency.\n */\n start?(options?: SandboxStartOptions): void | Promise<SandboxStartResult | void>;\n\n /**\n * Pause operation, keeping state for potential restart.\n *\n * Called to temporarily stop without full cleanup.\n * Use for operations like:\n * - Closing connections (but keeping config)\n * - Pausing cloud instances\n * - Flushing buffers\n */\n stop?(): void | Promise<void>;\n}\n\n// =============================================================================\n// Status Types\n// =============================================================================\n\n/**\n * Common status values for stateful providers.\n *\n * Not all providers need status tracking - local/stateless providers\n * may not use this. But providers with connection pools or cloud\n * instances can use these states.\n */\nexport type ProviderStatus =\n | 'pending' // Created but not initialized\n | 'initializing' // Running init()\n | 'ready' // Initialized, waiting to start (or stateless and ready)\n | 'starting' // Running start()\n | 'running' // Active and accepting requests\n | 'stopping' // Running stop()\n | 'stopped' // Stopped but can restart\n | 'destroying' // Running destroy()\n | 'destroyed' // Fully cleaned up\n | 'error'; // Something went wrong\n\n// =============================================================================\n// Lifecycle Helper\n// =============================================================================\n\n/**\n * Provider that may have lifecycle methods.\n * Used by `callLifecycle` to dispatch to the correct method.\n */\ninterface LifecycleProvider {\n _init?(): void | Promise<void>;\n // `_start` may resolve to a SandboxStartResult. This helper drops it: the\n // outcome is consumed by the onStart hook inside _start, before it returns.\n _start?(): void | Promise<unknown>;\n _stop?(): void | Promise<void>;\n _destroy?(): void | Promise<void>;\n init?(): void | Promise<void>;\n start?(): void | Promise<unknown>;\n stop?(): void | Promise<void>;\n destroy?(): void | Promise<void>;\n}\n\n/**\n * Call a lifecycle method on a provider, preferring the `_`-prefixed wrapper\n * (which adds status tracking & race-condition safety) when available,\n * falling back to the plain method for interface-only implementations.\n *\n * @example\n * ```typescript\n * await callLifecycle(sandbox, 'start'); // calls sandbox._start() ?? sandbox.start()\n * await callLifecycle(filesystem, 'init'); // calls filesystem._init() ?? filesystem.init()\n * ```\n */\nexport async function callLifecycle(\n provider: LifecycleProvider,\n method: 'init' | 'start' | 'stop' | 'destroy',\n): Promise<void> {\n const wrapped = `_${method}` as const;\n const wrappedFn = provider[wrapped];\n if (typeof wrappedFn === 'function') {\n await wrappedFn.call(provider);\n } else {\n const plainFn = provider[method];\n if (typeof plainFn === 'function') {\n await plainFn.call(provider);\n }\n }\n}\n","/**\n * CompositeFilesystem - Routes operations to mounted filesystems based on path.\n *\n * Creates a unified filesystem view by combining multiple filesystems at different\n * mount points. Useful for composing local storage, S3, and other backends.\n *\n * @example\n * ```typescript\n * const cfs = new CompositeFilesystem({\n * mounts: {\n * '/local': new LocalFilesystem({ basePath: './data' }),\n * '/s3': new S3Filesystem({ bucket: 'my-bucket', ... }),\n * }\n * });\n *\n * // readdir('/') returns ['local', 's3']\n * // readFile('/local/file.txt') reads from LocalFilesystem\n * // readFile('/s3/data.json') reads from S3Filesystem\n * ```\n */\n\nimport posixPath from 'node:path/posix';\n\nimport type { RequestContext } from '../../request-context';\nimport { FilesystemError, PermissionError } from '../errors';\nimport { callLifecycle } from '../lifecycle';\nimport type { ProviderStatus } from '../lifecycle';\nimport type {\n WorkspaceFilesystem,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemInfo,\n ReadOptions,\n WriteOptions,\n ListOptions,\n CopyOptions,\n RemoveOptions,\n} from './filesystem';\n\n/**\n * Configuration for CompositeFilesystem.\n */\nexport interface CompositeFilesystemConfig<\n TMounts extends Record<string, WorkspaceFilesystem> = Record<string, WorkspaceFilesystem>,\n> {\n /** Map of mount paths to filesystem instances */\n mounts: TMounts;\n}\n\ninterface ResolvedMount {\n fs: WorkspaceFilesystem;\n fsPath: string;\n mountPath: string;\n}\n\n/**\n * CompositeFilesystem implementation.\n *\n * Routes file operations to the appropriate underlying filesystem based on path.\n * Supports cross-mount operations (copy/move between different filesystems).\n *\n * The generic parameter preserves the concrete types of mounted filesystems,\n * enabling typed access via `mounts.get()`.\n *\n * @example\n * ```typescript\n * const cfs = new CompositeFilesystem({\n * mounts: {\n * '/local': new LocalFilesystem({ basePath: './data' }),\n * '/s3': new S3Filesystem({ bucket: 'my-bucket' }),\n * },\n * });\n *\n * cfs.mounts.get('/local') // LocalFilesystem\n * cfs.mounts.get('/s3') // S3Filesystem\n * ```\n */\nexport class CompositeFilesystem<\n TMounts extends Record<string, WorkspaceFilesystem> = Record<string, WorkspaceFilesystem>,\n> implements WorkspaceFilesystem {\n readonly id: string;\n readonly name = 'CompositeFilesystem';\n readonly provider = 'composite';\n\n readonly readOnly?: boolean;\n status: ProviderStatus = 'ready';\n\n private readonly _mounts: Map<string, WorkspaceFilesystem>;\n\n constructor(config: CompositeFilesystemConfig<TMounts>) {\n this.id = `cfs-${Date.now().toString(36)}`;\n this._mounts = new Map();\n\n for (const [path, fs] of Object.entries(config.mounts)) {\n const normalized = this.normalizePath(path);\n this._mounts.set(normalized, fs);\n }\n\n if (this._mounts.size === 0) {\n throw new Error('CompositeFilesystem requires at least one mount');\n }\n\n // Composite is read-only when every mount is read-only\n this.readOnly = [...this._mounts.values()].every(fs => fs.readOnly) || undefined;\n\n // Validate no nested mount paths (e.g., /data and /data/sub)\n const mountPaths = [...this._mounts.keys()];\n for (const a of mountPaths) {\n for (const b of mountPaths) {\n if (a !== b && b.startsWith(a + '/')) {\n throw new Error(`Nested mount paths are not supported: \"${b}\" is nested under \"${a}\"`);\n }\n }\n }\n }\n\n /**\n * Get all mount paths.\n */\n get mountPaths(): string[] {\n return Array.from(this._mounts.keys());\n }\n\n /**\n * Get the mounts map.\n * Returns a typed map where `get()` preserves the concrete filesystem type per mount path.\n */\n get mounts(): ReadonlyMountMap<TMounts> {\n return this._mounts as unknown as ReadonlyMountMap<TMounts>;\n }\n\n /**\n * Get status and metadata for this composite filesystem.\n * Includes info from each mounted filesystem in `metadata.mounts`.\n */\n async getInfo(): Promise<FilesystemInfo> {\n const mounts: Record<string, FilesystemInfo | null> = {};\n for (const [mountPath, fs] of this._mounts) {\n mounts[mountPath] = (await fs.getInfo?.()) ?? null;\n }\n\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n readOnly: this.readOnly,\n metadata: { mounts },\n };\n }\n\n /**\n * Get the underlying filesystem for a given path.\n * Returns undefined if the path doesn't resolve to any mount.\n */\n getFilesystemForPath(path: string): WorkspaceFilesystem | undefined {\n const resolved = this.resolveMount(path);\n return resolved?.fs;\n }\n\n /**\n * Get the mount path for a given path.\n * Returns undefined if the path doesn't resolve to any mount.\n */\n getMountPathForPath(path: string): string | undefined {\n const resolved = this.resolveMount(path);\n return resolved?.mountPath;\n }\n\n /**\n * Resolve a workspace-relative path to an absolute disk path.\n * Strips the mount prefix and delegates to the underlying filesystem.\n */\n resolveAbsolutePath(path: string): string | undefined {\n const r = this.resolveMount(path);\n if (!r) return undefined;\n return r.fs.resolveAbsolutePath?.(r.fsPath);\n }\n\n private normalizePath(path: string): string {\n if (!path || path === '/' || path === '.') return '/';\n // posix.normalize resolves dot segments (./foo → foo, a/../b → b)\n let n = posixPath.normalize(path);\n if (n === '.') return '/';\n if (!n.startsWith('/')) n = `/${n}`;\n if (n.length > 1 && n.endsWith('/')) n = n.slice(0, -1);\n return n;\n }\n\n private resolveMount(path: string): ResolvedMount | null {\n const normalized = this.normalizePath(path);\n let best: { mountPath: string; fs: WorkspaceFilesystem } | null = null;\n\n for (const [mountPath, fs] of this._mounts) {\n if (normalized === mountPath || normalized.startsWith(mountPath + '/')) {\n if (!best || mountPath.length > best.mountPath.length) {\n best = { mountPath, fs };\n }\n }\n }\n\n if (!best) return null;\n\n let fsPath = normalized.slice(best.mountPath.length);\n // Strip the leading slash so the path is relative to the mounted filesystem's basePath\n if (fsPath === '/') fsPath = '';\n else if (fsPath.startsWith('/')) fsPath = fsPath.slice(1);\n\n return { fs: best.fs, fsPath, mountPath: best.mountPath };\n }\n\n private getVirtualEntries(path: string): FileEntry[] | null {\n const normalized = this.normalizePath(path);\n if (this.resolveMount(normalized)) return null;\n\n const entriesMap = new Map<string, FileEntry>();\n for (const [mountPath, fs] of this._mounts.entries()) {\n const isUnder = normalized === '/' ? mountPath.startsWith('/') : mountPath.startsWith(normalized + '/');\n\n if (isUnder) {\n const remaining = normalized === '/' ? mountPath.slice(1) : mountPath.slice(normalized.length + 1);\n const next = remaining.split('/')[0];\n if (next && !entriesMap.has(next)) {\n // Check if this is a direct mount point (e.g., listing '/' and mount is '/s3')\n const isDirectMount = remaining === next;\n const entry: FileEntry = { name: next, type: 'directory' as const };\n\n // If it's a direct mount point, include filesystem metadata\n if (isDirectMount) {\n entry.mount = {\n provider: fs.provider,\n icon: fs.icon,\n displayName: fs.displayName,\n description: fs.description,\n status: fs.status,\n error: fs.error,\n };\n }\n\n entriesMap.set(next, entry);\n }\n }\n }\n\n return entriesMap.size > 0 ? Array.from(entriesMap.values()) : null;\n }\n\n private isVirtualPath(path: string): boolean {\n const normalized = this.normalizePath(path);\n if (normalized === '/' && !this._mounts.has('/')) return true;\n for (const mountPath of this._mounts.keys()) {\n if (mountPath.startsWith(normalized + '/')) return true;\n }\n return false;\n }\n\n /**\n * Assert that a filesystem is writable (not read-only).\n * @throws {PermissionError} if the filesystem is read-only\n */\n private assertWritable(fs: WorkspaceFilesystem, path: string, operation: string): void {\n if (fs.readOnly) {\n throw new PermissionError(path, `${operation} (filesystem is read-only)`);\n }\n }\n\n // ===========================================================================\n // WorkspaceFilesystem Implementation\n // ===========================================================================\n\n async init(): Promise<void> {\n this.status = 'initializing';\n for (const [mountPath, fs] of this._mounts.entries()) {\n try {\n await callLifecycle(fs, 'init');\n } catch (e) {\n // Individual mount failed - it will have status='error'\n // Log but continue with other mounts\n const message = e instanceof Error ? e.message : String(e);\n console.warn(`[CompositeFilesystem] Mount \"${mountPath}\" failed to initialize: ${message}`);\n }\n }\n // CompositeFilesystem is ready even if some mounts failed\n // Operations on errored mounts will be handled by the underlying filesystem\n this.status = 'ready';\n }\n\n async destroy(): Promise<void> {\n this.status = 'destroying';\n const errors: Error[] = [];\n for (const fs of this._mounts.values()) {\n try {\n await callLifecycle(fs, 'destroy');\n } catch (e) {\n errors.push(e instanceof Error ? e : new Error(String(e)));\n }\n }\n if (errors.length > 0) {\n this.status = 'error';\n throw new AggregateError(errors, 'Some filesystems failed to destroy');\n }\n this.status = 'destroyed';\n }\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const r = this.resolveMount(path);\n if (!r) throw new FilesystemError(`No mount for path: ${path}`, 'ENOENT', path);\n return r.fs.readFile(r.fsPath, options);\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const r = this.resolveMount(path);\n if (!r) throw new Error(`No mount for path: ${path}`);\n this.assertWritable(r.fs, path, 'writeFile');\n return r.fs.writeFile(r.fsPath, content, options);\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n const r = this.resolveMount(path);\n if (!r) throw new Error(`No mount for path: ${path}`);\n this.assertWritable(r.fs, path, 'appendFile');\n return r.fs.appendFile(r.fsPath, content);\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n const r = this.resolveMount(path);\n if (!r) throw new Error(`No mount for path: ${path}`);\n this.assertWritable(r.fs, path, 'deleteFile');\n return r.fs.deleteFile(r.fsPath, options);\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcR = this.resolveMount(src);\n const destR = this.resolveMount(dest);\n if (!srcR) throw new Error(`No mount for source: ${src}`);\n if (!destR) throw new Error(`No mount for dest: ${dest}`);\n this.assertWritable(destR.fs, dest, 'copyFile');\n\n // Same mount - delegate\n if (srcR.mountPath === destR.mountPath) {\n return srcR.fs.copyFile(srcR.fsPath, destR.fsPath, options);\n }\n\n // Cross-mount copy - read then write\n const content = await srcR.fs.readFile(srcR.fsPath);\n await destR.fs.writeFile(destR.fsPath, content, { overwrite: options?.overwrite });\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcR = this.resolveMount(src);\n const destR = this.resolveMount(dest);\n if (!srcR) throw new Error(`No mount for source: ${src}`);\n if (!destR) throw new Error(`No mount for dest: ${dest}`);\n this.assertWritable(destR.fs, dest, 'moveFile');\n this.assertWritable(srcR.fs, src, 'moveFile'); // Source must be writable for delete\n\n // Same mount - delegate\n if (srcR.mountPath === destR.mountPath) {\n return srcR.fs.moveFile(srcR.fsPath, destR.fsPath, options);\n }\n\n // Cross-mount move - copy then delete\n await this.copyFile(src, dest, options);\n await srcR.fs.deleteFile(srcR.fsPath);\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const virtual = this.getVirtualEntries(path);\n if (virtual) return virtual;\n\n const r = this.resolveMount(path);\n if (!r) throw new FilesystemError(`No mount for path: ${path}`, 'ENOENT', path);\n return r.fs.readdir(r.fsPath, options);\n }\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const r = this.resolveMount(path);\n if (!r) throw new Error(`No mount for path: ${path}`);\n this.assertWritable(r.fs, path, 'mkdir');\n return r.fs.mkdir(r.fsPath, options);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n const r = this.resolveMount(path);\n if (!r) throw new Error(`No mount for path: ${path}`);\n this.assertWritable(r.fs, path, 'rmdir');\n return r.fs.rmdir(r.fsPath, options);\n }\n\n async exists(path: string): Promise<boolean> {\n if (this.isVirtualPath(path)) return true;\n const r = this.resolveMount(path);\n if (!r) return false;\n // Mount point root always exists (even if errored)\n if (r.fsPath === '') return true;\n return r.fs.exists(r.fsPath);\n }\n\n async stat(path: string): Promise<FileStat> {\n const normalized = this.normalizePath(path);\n\n if (this.isVirtualPath(path)) {\n const parts = normalized.split('/').filter(Boolean);\n const now = new Date();\n return {\n name: parts[parts.length - 1] || '',\n path: normalized,\n type: 'directory',\n size: 0,\n createdAt: now,\n modifiedAt: now,\n };\n }\n\n const r = this.resolveMount(path);\n if (!r) throw new FilesystemError(`No mount for path: ${path}`, 'ENOENT', path);\n\n // Mount point root always returns directory stat (even if errored)\n if (r.fsPath === '') {\n const parts = normalized.split('/').filter(Boolean);\n const now = new Date();\n return {\n name: parts[parts.length - 1] || '',\n path: normalized,\n type: 'directory',\n size: 0,\n createdAt: now,\n modifiedAt: now,\n };\n }\n\n return r.fs.stat(r.fsPath);\n }\n\n async isFile(path: string): Promise<boolean> {\n if (this.isVirtualPath(path)) return false;\n const r = this.resolveMount(path);\n if (!r) return false;\n try {\n const stat = await r.fs.stat(r.fsPath);\n return stat.type === 'file';\n } catch {\n return false;\n }\n }\n\n async isDirectory(path: string): Promise<boolean> {\n if (this.isVirtualPath(path)) return true;\n const r = this.resolveMount(path);\n if (!r) return false;\n // Mount point root is always a directory (even if errored)\n if (r.fsPath === '') return true;\n try {\n const stat = await r.fs.stat(r.fsPath);\n return stat.type === 'directory';\n } catch {\n return false;\n }\n }\n\n /**\n * Get instructions describing the mounted filesystems.\n * Used by agents to understand available storage locations.\n */\n getInstructions(_opts?: { requestContext?: RequestContext }): string {\n const mountDescriptions = Array.from(this._mounts.entries())\n .map(([mountPath, fs]) => {\n const name = fs.displayName || fs.provider;\n const access = fs.readOnly ? '(read-only)' : '(read-write)';\n return `- ${mountPath}: ${name} ${access}`;\n })\n .join('\\n');\n\n return `Filesystem mount points:\\n${mountDescriptions}`;\n }\n}\n\n/**\n * Distributive mapped type that produces a union of correlated `[key, value]` tuples.\n *\n * For `{ '/local': LocalFilesystem, '/s3': S3Filesystem }` this yields:\n * `['/local', LocalFilesystem] | ['/s3', S3Filesystem]`\n *\n * This enables discriminated-union narrowing when iterating entries without destructuring:\n * ```typescript\n * for (const entry of mounts.entries()) {\n * if (entry[0] === '/local') {\n * entry[1] // LocalFilesystem\n * }\n * }\n * ```\n */\nexport type MountMapEntry<TMounts extends Record<string, WorkspaceFilesystem>> = {\n [K in string & keyof TMounts]: [K, TMounts[K]];\n}[string & keyof TMounts];\n\n/**\n * A read-only view of mounted filesystems with typed per-key access.\n *\n * Unlike `ReadonlyMap<string, WorkspaceFilesystem>`, this preserves the\n * concrete filesystem type for each mount path via an overloaded `get()`.\n *\n * Iteration methods return correlated `[key, value]` tuples ({@link MountMapEntry})\n * so that checking `entry[0]` narrows `entry[1]` to the concrete filesystem type.\n *\n * @example\n * ```typescript\n * const mounts = cfs.mounts;\n * mounts.get('/local') // LocalFilesystem\n * mounts.get('/s3') // S3Filesystem\n * ```\n */\nexport interface ReadonlyMountMap<TMounts extends Record<string, WorkspaceFilesystem>> {\n /** Get a mounted filesystem by path. Returns the concrete type for known mount paths. */\n get<K extends string & keyof TMounts>(key: K): TMounts[K];\n get(key: string): WorkspaceFilesystem | undefined;\n\n has(key: string): boolean;\n readonly size: number;\n\n keys(): IterableIterator<string & keyof TMounts>;\n values(): IterableIterator<TMounts[keyof TMounts & string]>;\n entries(): IterableIterator<MountMapEntry<TMounts>>;\n forEach(\n callbackfn: (\n value: TMounts[keyof TMounts & string],\n key: string & keyof TMounts,\n map: ReadonlyMountMap<TMounts>,\n ) => void,\n ): void;\n [Symbol.iterator](): IterableIterator<MountMapEntry<TMounts>>;\n}\n","/**\n * MastraFilesystem Base Class\n *\n * Abstract base class for filesystem providers that want automatic logger integration\n * and lifecycle management.\n *\n * Extends MastraBase to receive the Mastra logger when registered with a Mastra instance.\n *\n * ## Lifecycle Management\n *\n * The base class provides race-condition-safe lifecycle wrappers:\n * - `_init()` - Handles concurrent calls, status management\n * - `_destroy()` - Handles concurrent calls and status management\n *\n * Subclasses override the plain `init()` and `destroy()` methods to provide\n * their implementation. Callers use the `_`-prefixed wrappers (or `callLifecycle()`)\n * which add status tracking and race-condition safety.\n *\n * External providers can extend this class to get logger support, or implement\n * the WorkspaceFilesystem interface directly if they don't need logging.\n */\n\nimport { MastraBase } from '../../base';\nimport { RegisteredLogger } from '../../logger/constants';\nimport { FilesystemNotReadyError } from '../errors';\nimport type { ProviderStatus } from '../lifecycle';\nimport type {\n WorkspaceFilesystem,\n FileContent,\n FileStat,\n FileEntry,\n ReadOptions,\n WriteOptions,\n ListOptions,\n RemoveOptions,\n CopyOptions,\n} from './filesystem';\nimport { isTextFile, normalizeTextExtension } from './fs-utils';\n\n/**\n * Lifecycle hook that fires during filesystem state transitions.\n * Receives the filesystem instance so users can inspect state, log, etc.\n */\nexport type FilesystemLifecycleHook = (args: { filesystem: WorkspaceFilesystem }) => void | Promise<void>;\n\n/**\n * Options for the MastraFilesystem base class constructor.\n * Providers extend this to add their own options while inheriting lifecycle hooks.\n */\nexport interface MastraFilesystemOptions {\n /** Called after the filesystem reaches 'ready' status */\n onInit?: FilesystemLifecycleHook;\n /** Called before the filesystem is destroyed */\n onDestroy?: FilesystemLifecycleHook;\n /**\n * Additional file extensions to treat as text, extending (not replacing) the\n * built-in set. Affects which files tools like `grep` will search.\n *\n * Values are normalized to lowercase and dot-prefixed, so `'sas'`, `'.sas'`,\n * and `'.SAS'` are equivalent.\n *\n * @example\n * ```typescript\n * new LocalFilesystem({ basePath: '.', textExtensions: ['.sas', '.log'] })\n * ```\n */\n textExtensions?: string[];\n}\n\n/**\n * Abstract base class for filesystem providers with logger support and lifecycle management.\n *\n * Providers that extend this class automatically receive the Mastra logger\n * when the filesystem is used with a Mastra instance.\n *\n * @example\n * ```typescript\n * class MyCustomFilesystem extends MastraFilesystem {\n * readonly id = 'my-fs';\n * readonly name = 'MyCustomFilesystem';\n * readonly provider = 'custom';\n * status: ProviderStatus = 'pending';\n *\n * constructor() {\n * super({ name: 'MyCustomFilesystem' });\n * }\n *\n * // Override init() to provide initialization logic\n * async init(): Promise<void> {\n * // Your initialization logic here\n * }\n *\n * async readFile(path: string): Promise<string | Buffer> {\n * await this.ensureReady();\n * this.logger.debug('Reading file', { path });\n * // Implementation...\n * }\n * // ... implement other WorkspaceFilesystem methods\n * }\n * ```\n */\nexport abstract class MastraFilesystem extends MastraBase implements WorkspaceFilesystem {\n /** Unique identifier for this filesystem instance */\n abstract readonly id: string;\n\n /** Human-readable name (e.g., 'LocalFilesystem', 'AgentFS') */\n abstract readonly name: string;\n\n /** Provider type identifier */\n abstract readonly provider: string;\n\n /** Current status of the filesystem */\n abstract status: ProviderStatus;\n\n /** Error message when status is 'error' */\n error?: string;\n\n // ---------------------------------------------------------------------------\n // Lifecycle Promise Tracking (prevents race conditions)\n // ---------------------------------------------------------------------------\n\n /** Promise for _init() to prevent race conditions from concurrent calls */\n private _initPromise?: Promise<void>;\n\n /** Promise for _destroy() to prevent race conditions from concurrent calls */\n private _destroyPromise?: Promise<void>;\n\n /** Lifecycle callbacks */\n private readonly _onInit?: FilesystemLifecycleHook;\n private readonly _onDestroy?: FilesystemLifecycleHook;\n\n /** Additional (normalized) text extensions configured for this filesystem */\n protected readonly _textExtensions: ReadonlySet<string>;\n\n constructor(options: { name: string } & MastraFilesystemOptions) {\n super({ name: options.name, component: RegisteredLogger.WORKSPACE });\n\n this._onInit = options.onInit;\n this._onDestroy = options.onDestroy;\n this._textExtensions = new Set((options.textExtensions ?? []).map(normalizeTextExtension));\n }\n\n /**\n * Check if a file should be treated as text, honoring any `textExtensions`\n * configured on this filesystem in addition to the built-in set.\n */\n isTextFile(filename: string): boolean {\n return isTextFile(filename, this._textExtensions);\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle Wrappers (race-condition-safe)\n // ---------------------------------------------------------------------------\n\n /**\n * Initialize the filesystem (wrapper with status management and race-condition safety).\n *\n * This method is race-condition-safe - concurrent calls will return the same promise.\n * Handles status management automatically.\n *\n * Subclasses override `init()` to provide their initialization logic.\n */\n async _init(): Promise<void> {\n // Already ready\n // Note: intentionally allows re-init after destroy() for reconnect scenarios\n if (this.status === 'ready') {\n return;\n }\n\n // Wait for any in-progress destroy to complete before (re-)initializing\n if (this._destroyPromise) {\n try {\n await this._destroyPromise;\n } catch {\n // Ignore destroy errors — we're re-initializing anyway\n }\n }\n\n // Init already in progress - return existing promise\n if (this._initPromise) {\n return this._initPromise;\n }\n\n // Create and store the init promise\n this._initPromise = this._executeInit();\n\n try {\n await this._initPromise;\n } finally {\n this._initPromise = undefined;\n }\n }\n\n /**\n * Internal init execution - handles status.\n */\n private async _executeInit(): Promise<void> {\n this.status = 'initializing';\n this.error = undefined;\n\n try {\n await this.init();\n this.status = 'ready';\n\n // Fire onInit callback after filesystem is ready — treat failure as non-fatal\n // so that a bad callback doesn't kill an otherwise healthy filesystem\n try {\n await this._onInit?.({ filesystem: this });\n } catch (error) {\n this.logger.warn('onInit callback failed', { error });\n }\n } catch (error) {\n this.status = 'error';\n this.error = error instanceof Error ? error.message : String(error);\n this.logger.error('Failed to initialize filesystem', { error, id: this.id });\n throw error;\n }\n }\n\n /**\n * Override this method to implement filesystem initialization logic.\n *\n * Called by `_init()` after status is set to 'initializing'.\n * Status will be set to 'ready' on success, 'error' on failure.\n *\n * @example\n * ```typescript\n * async init(): Promise<void> {\n * this._client = new StorageClient({ ... });\n * await this._client.connect();\n * }\n * ```\n */\n async init(): Promise<void> {\n // Default no-op - subclasses override\n }\n\n /**\n * Ensure the filesystem is ready.\n *\n * Calls `_init()` if status is not 'ready'. Useful for lazy initialization\n * where operations should automatically initialize the filesystem if needed.\n *\n * @throws {FilesystemNotReadyError} if the filesystem fails to reach 'ready' status\n *\n * @example\n * ```typescript\n * async readFile(path: string): Promise<string | Buffer> {\n * await this.ensureReady();\n * // Now safe to use the filesystem\n * }\n * ```\n */\n protected async ensureReady(): Promise<void> {\n if (this.status !== 'ready') {\n await this._init();\n }\n if (this.status !== 'ready') {\n throw new FilesystemNotReadyError(this.id);\n }\n }\n\n /**\n * Destroy the filesystem and clean up all resources (wrapper with status management).\n *\n * This method is race-condition-safe - concurrent calls will return the same promise.\n * Handles status management.\n *\n * Subclasses override `destroy()` to provide their destroy logic.\n */\n async _destroy(): Promise<void> {\n // Already destroyed\n if (this.status === 'destroyed') {\n return;\n }\n\n // Never initialized — nothing to tear down\n if (this.status === 'pending') {\n this.status = 'destroyed';\n return;\n }\n\n // Destroy already in progress - return existing promise\n if (this._destroyPromise) {\n return this._destroyPromise;\n }\n\n // Create and store the destroy promise\n this._destroyPromise = this._executeDestroy();\n\n try {\n await this._destroyPromise;\n } finally {\n this._destroyPromise = undefined;\n }\n }\n\n /**\n * Internal destroy execution - handles status.\n */\n private async _executeDestroy(): Promise<void> {\n // Wait for any in-progress init to complete before destroying\n if (this._initPromise) {\n try {\n await this._initPromise;\n } catch {\n // Ignore init errors — we're destroying anyway\n }\n }\n this.status = 'destroying';\n\n try {\n // Fire onDestroy callback before destroying\n await this._onDestroy?.({ filesystem: this });\n\n await this.destroy();\n this.status = 'destroyed';\n } catch (error) {\n this.status = 'error';\n this.logger.error('Failed to destroy filesystem', { error, id: this.id });\n throw error;\n }\n }\n\n /**\n * Override this method to implement filesystem destroy logic.\n *\n * Called by `_destroy()` after status is set to 'destroying'.\n * Status will be set to 'destroyed' on success, 'error' on failure.\n */\n async destroy(): Promise<void> {\n // Default no-op - subclasses override\n }\n\n // ---------------------------------------------------------------------------\n // Abstract methods - implementations must provide these\n // ---------------------------------------------------------------------------\n\n abstract readFile(path: string, options?: ReadOptions): Promise<string | Buffer>;\n abstract writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void>;\n abstract appendFile(path: string, content: FileContent): Promise<void>;\n abstract deleteFile(path: string, options?: RemoveOptions): Promise<void>;\n abstract copyFile(src: string, dest: string, options?: CopyOptions): Promise<void>;\n abstract moveFile(src: string, dest: string, options?: CopyOptions): Promise<void>;\n abstract mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;\n abstract rmdir(path: string, options?: RemoveOptions): Promise<void>;\n abstract readdir(path: string, options?: ListOptions): Promise<FileEntry[]>;\n abstract exists(path: string): Promise<boolean>;\n abstract stat(path: string): Promise<FileStat>;\n}\n","import type { RequestContext } from '../request-context';\nimport type { InstructionsOption } from './types';\n\n/**\n * Resolve an instructions override against default instructions.\n *\n * - `undefined` → return default\n * - `string` → return the string as-is\n * - `function` → call with { defaultInstructions, requestContext }\n */\nexport function resolveInstructions(\n override: InstructionsOption | undefined,\n getDefault: () => string,\n requestContext?: RequestContext,\n): string {\n if (typeof override === 'string') return override;\n const defaultInstructions = getDefault();\n if (override === undefined) return defaultInstructions;\n return override({ defaultInstructions, requestContext });\n}\n","/**\n * Local Filesystem Provider\n *\n * A filesystem implementation backed by a folder on the local disk.\n * This is the default filesystem for development and local agents.\n */\n\nimport { constants as fsConstants, lstatSync, readlinkSync, realpathSync } from 'node:fs';\nimport type { Stats } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport * as nodePath from 'node:path';\nimport type { RequestContext } from '../../request-context';\nimport {\n FileNotFoundError,\n DirectoryNotFoundError,\n FileExistsError,\n IsDirectoryError,\n NotDirectoryError,\n DirectoryNotEmptyError,\n PermissionError,\n StaleFileError,\n WorkspaceReadOnlyError,\n} from '../errors';\nimport type { ProviderStatus } from '../lifecycle';\nimport type { InstructionsOption } from '../types';\nimport { resolveInstructions } from '../utils';\nimport type {\n FilesystemInfo,\n FileContent,\n FileStat,\n FileEntry,\n ReadOptions,\n WriteOptions,\n ListOptions,\n RemoveOptions,\n CopyOptions,\n} from './filesystem';\nimport {\n expandTilde,\n fsExists,\n fsStat,\n getMimeType,\n isEnoentError,\n isEexistError,\n resolveToBasePath,\n} from './fs-utils';\nimport { MastraFilesystem } from './mastra-filesystem';\nimport type { MastraFilesystemOptions } from './mastra-filesystem';\nimport type { FilesystemMountConfig } from './mount';\n\n/**\n * Local filesystem provider configuration.\n */\nexport interface LocalFilesystemOptions extends MastraFilesystemOptions {\n /** Unique identifier for this filesystem instance */\n id?: string;\n /** Base directory path on disk */\n basePath: string;\n /**\n * When true, all file operations are restricted to stay within basePath.\n * Prevents path traversal attacks and symlink escapes.\n *\n * - `contained: true` (default) — File access is restricted to basePath\n * (and any allowedPaths). Paths that escape these boundaries throw a\n * PermissionError.\n * - `contained: false` — No access restrictions. Any path on the host\n * filesystem is accessible.\n *\n * Set to `false` when the filesystem needs to access paths outside basePath,\n * such as global skills directories or user home directories.\n *\n * @default true\n */\n contained?: boolean;\n /**\n * When true, all write operations to this filesystem are blocked.\n * Read operations are still allowed.\n * @default false\n */\n readOnly?: boolean;\n /**\n * Additional directories the agent can access outside of `basePath`.\n *\n * Relative paths resolve against `basePath`.\n * Absolute and tilde paths are used as-is.\n *\n * @example\n * ```typescript\n * new LocalFilesystem({\n * basePath: './workspace',\n * contained: true,\n * allowedPaths: ['../skills', '~/.claude/skills'],\n * })\n * ```\n */\n allowedPaths?: string[];\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions.\n * Pass an empty string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and\n * optional request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n}\n\n/**\n * Mount configuration for local filesystems.\n *\n * When a `LocalFilesystem` is used as a mount in a Workspace with `LocalSandbox`,\n * the sandbox creates a symlink from `<workingDir>/<mountPath>` → `basePath`.\n * No FUSE tools are needed for local mounts.\n *\n * **Note:** When mounted with `contained: false`, the agent can access any\n * path on the host filesystem through this mount. Workspace logs a warning\n * at construction time if this combination is detected.\n */\nexport interface LocalMountConfig extends FilesystemMountConfig {\n type: 'local';\n basePath: string;\n}\n\n/**\n * Stores workspace files in a folder on the host machine for development\n * and persistent local storage.\n *\n * @example\n * ```typescript\n * import { Workspace, LocalFilesystem } from '@mastra/core/workspace';\n *\n * const workspace = new Workspace({\n * filesystem: new LocalFilesystem({ basePath: './my-workspace' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/core/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Local filesystem documentation](https://mastra.ai/reference/workspace/local-filesystem)\n * if packaged docs are unavailable.\n */\nexport class LocalFilesystem extends MastraFilesystem {\n readonly id: string;\n readonly name = 'LocalFilesystem';\n readonly provider = 'local';\n readonly readOnly?: boolean;\n\n status: ProviderStatus = 'pending';\n\n private readonly _basePath: string;\n private readonly _contained: boolean;\n private _allowedPaths: string[];\n private readonly _instructionsOverride?: InstructionsOption;\n\n /**\n * The absolute base path on disk where files are stored.\n * Useful for understanding how workspace paths map to disk paths.\n */\n get basePath(): string {\n return this._basePath;\n }\n\n /**\n * Whether file operations are restricted to stay within basePath.\n *\n * When `true` (default), relative paths resolve against basePath and\n * absolute paths are kept as-is. Any resolved path that falls outside\n * basePath (and allowedPaths) throws a PermissionError. When `false`,\n * no containment check is applied.\n *\n * **Note:** When used as a CompositeFilesystem mount with `contained: false`,\n * the agent can access any path on the host filesystem through this mount.\n */\n get contained(): boolean {\n return this._contained;\n }\n\n /**\n * Current set of resolved allowed paths.\n * These paths are permitted beyond basePath when containment is enabled.\n */\n get allowedPaths(): readonly string[] {\n return this._allowedPaths;\n }\n\n /**\n * Update allowed paths. Accepts a direct array or an updater callback\n * receiving the current paths (React setState pattern).\n *\n * @example\n * ```typescript\n * // Set directly\n * fs.setAllowedPaths(['../shared-data']);\n *\n * // Update with callback\n * fs.setAllowedPaths(prev => [...prev, '~/.claude/skills']);\n * ```\n */\n setAllowedPaths(pathsOrUpdater: string[] | ((current: readonly string[]) => string[])): void {\n const newPaths = typeof pathsOrUpdater === 'function' ? pathsOrUpdater(this._allowedPaths) : pathsOrUpdater;\n this._allowedPaths = newPaths.map(p => resolveToBasePath(this._basePath, p));\n }\n\n constructor(options: LocalFilesystemOptions) {\n super({ ...options, name: 'LocalFilesystem' });\n this.id = options.id ?? this.generateId();\n this._basePath = nodePath.resolve(expandTilde(options.basePath));\n this._contained = options.contained ?? true;\n this.readOnly = options.readOnly;\n this._allowedPaths = (options.allowedPaths ?? []).map(p => resolveToBasePath(this._basePath, p));\n this._instructionsOverride = options.instructions;\n }\n\n /**\n * Return mount config for sandbox integration.\n * LocalSandbox uses this to create a symlink from the mount path to basePath.\n */\n getMountConfig(): LocalMountConfig {\n return { type: 'local', basePath: this._basePath };\n }\n\n private generateId(): string {\n return `local-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Check if an absolute path falls within basePath or any allowed path.\n */\n private _isWithinRoot(absolutePath: string, root: string): boolean {\n const relative = nodePath.relative(root, absolutePath);\n return !relative.startsWith('..') && !nodePath.isAbsolute(relative);\n }\n\n private _resolvePathForContainment(absolutePath: string): string | undefined {\n try {\n return realpathSync.native(absolutePath);\n } catch (error: unknown) {\n if (!isEnoentError(error)) throw error;\n }\n\n // Missing targets need component-wise resolution: normalizing a symlink's\n // target before following its links would give `..` the wrong parent.\n let currentPath = nodePath.parse(absolutePath).root;\n const pending = absolutePath.slice(currentPath.length).split(nodePath.sep);\n let symlinkDepth = 0;\n let currentIsDirectory: boolean | undefined = true;\n\n while (pending.length > 0) {\n const component = pending.shift();\n if (!component) continue;\n if (currentIsDirectory === false) {\n // Preserve the native ENOTDIR error, including for `file/..`.\n realpathSync.native(`${currentPath}${nodePath.sep}${component}`);\n }\n if (component === '.') continue;\n if (component === '..') {\n currentPath = nodePath.dirname(currentPath);\n currentIsDirectory = undefined;\n continue;\n }\n\n const candidate = nodePath.join(currentPath, component);\n try {\n const stat = lstatSync(candidate);\n if (stat.isSymbolicLink()) {\n if (++symlinkDepth > 40) return undefined;\n const target = readlinkSync(candidate);\n const root = nodePath.parse(target).root;\n if (root) currentPath = root;\n pending.unshift(...target.slice(root.length).split(nodePath.sep));\n currentIsDirectory = undefined;\n continue;\n }\n currentIsDirectory = stat.isDirectory();\n // Resolve natively so Windows 8.3 short names expand the same way the root does.\n currentPath = realpathSync.native(candidate);\n continue;\n } catch (error: unknown) {\n if (!isEnoentError(error)) throw error;\n currentIsDirectory = undefined;\n }\n currentPath = candidate;\n }\n\n return currentPath;\n }\n\n private _isWithinAnyRoot(absolutePath: string): boolean {\n const roots = [this._basePath, ...this._allowedPaths];\n const resolvedPath = this._resolvePathForContainment(absolutePath);\n if (!resolvedPath) {\n return false;\n }\n\n return roots.some(root => {\n const resolvedRoot = this._resolvePathForContainment(root);\n return resolvedRoot ? this._isWithinRoot(resolvedPath, resolvedRoot) : false;\n });\n }\n\n private toBuffer(content: FileContent): Buffer {\n if (Buffer.isBuffer(content)) return content;\n if (content instanceof Uint8Array) return Buffer.from(content);\n return Buffer.from(content, 'utf-8');\n }\n\n private resolvePath(inputPath: string): string {\n const absolutePath = resolveToBasePath(this._basePath, inputPath);\n\n if (this._contained) {\n if (!this._isWithinAnyRoot(absolutePath)) {\n throw new PermissionError(inputPath, this._accessOperationHint(inputPath));\n }\n }\n\n return absolutePath;\n }\n\n /**\n * Build the operation string for a containment-violation `PermissionError`.\n *\n * When the caller passed an absolute path, suggest a concrete relative form\n * only when that suffix names an existing entry under the workspace (e.g.\n * `/src/app.ts` → `src/app.ts` if `<basePath>/src` exists). Otherwise emit a\n * soft hint that doesn't lie about specific paths — agents that mistake `/`\n * for the workspace root learn the workspace is sandboxed without us\n * inventing a fictitious in-workspace location for `/etc/passwd`.\n */\n private _accessOperationHint(inputPath: string): string {\n if (!nodePath.isAbsolute(inputPath)) return 'access';\n\n const stripped = inputPath.replace(/^[/\\\\]+/, '');\n if (!stripped) return 'access';\n\n // If the first segment exists under basePath, the LLM almost certainly\n // meant a workspace-relative path. Suggest the exact form. Reject any\n // segment that would escape basePath (`.`, `..`) — suggesting those would\n // just produce another containment failure on the next turn.\n const firstSegment = stripped.split(/[/\\\\]/, 1)[0];\n if (firstSegment && firstSegment !== '.' && firstSegment !== '..') {\n try {\n if (realpathSync(nodePath.join(this._basePath, firstSegment))) {\n return `access (path is outside the workspace; use a relative path like \"${stripped}\")`;\n }\n } catch {\n // Fall through to the soft hint\n }\n }\n\n return 'access (path is outside the workspace; use a path relative to the workspace root, without a leading \"/\")';\n }\n\n /**\n * Resolve a workspace-relative path to an absolute disk path.\n * Uses the same resolution logic as internal file operations.\n * Returns `undefined` if the path violates containment.\n */\n resolveAbsolutePath(inputPath: string): string | undefined {\n try {\n return this.resolvePath(inputPath);\n } catch {\n // PermissionError from containment check — path is not resolvable\n return undefined;\n }\n }\n\n private toRelativePath(absolutePath: string): string {\n return nodePath.relative(this._basePath, absolutePath).replace(/\\\\/g, '/');\n }\n\n private assertWritable(operation: string): void {\n if (this.readOnly) {\n throw new WorkspaceReadOnlyError(operation);\n }\n }\n\n /**\n * Check canonical roots even when the target does not exist yet: the nearest\n * existing ancestor may be a symlink outside the workspace.\n */\n private async assertPathContained(absolutePath: string): Promise<void> {\n if (this._contained && !this._isWithinAnyRoot(absolutePath)) {\n throw new PermissionError(absolutePath, 'access');\n }\n }\n\n private async containedRoots(): Promise<string[]> {\n const roots: string[] = [];\n for (const root of [this._basePath, ...this._allowedPaths]) {\n try {\n roots.push(await fs.realpath(root));\n } catch (error) {\n if (!isEnoentError(error)) throw error;\n }\n }\n return roots;\n }\n\n private assertCanonicalPathContained(canonicalPath: string, absolutePath: string, roots: string[]): void {\n if (!roots.some(root => this._isWithinRoot(canonicalPath, root))) {\n throw new PermissionError(absolutePath, 'access');\n }\n }\n\n private async openContainedPath(\n absolutePath: string,\n metadataOnly = false,\n ): Promise<{ handle: FileHandle; canonicalPath: string }> {\n const roots = await this.containedRoots();\n const checkedPath = await fs.realpath(absolutePath);\n this.assertCanonicalPathContained(checkedPath, absolutePath, roots);\n // O_PATH opens a metadata-only descriptor without requiring file read permission on Linux.\n const flags = metadataOnly\n ? process.platform === 'linux'\n ? 0o10000000 // O_PATH, not exposed by Node's fs.constants\n : fsConstants.O_RDONLY | fsConstants.O_NONBLOCK\n : 'r';\n const handle = await fs.open(absolutePath, flags);\n try {\n const opened = await handle.stat({ bigint: true });\n const canonicalPath = await fs.realpath(absolutePath);\n this.assertCanonicalPathContained(canonicalPath, absolutePath, roots);\n const current = await fs.stat(canonicalPath, { bigint: true });\n if (\n opened.dev === 0n ||\n opened.ino === 0n ||\n current.dev === 0n ||\n current.ino === 0n ||\n opened.dev !== current.dev ||\n opened.ino !== current.ino\n ) {\n throw new PermissionError(absolutePath, 'access');\n }\n return { handle, canonicalPath };\n } catch (error) {\n await handle.close();\n throw error;\n }\n }\n\n async readFile(inputPath: string, options?: ReadOptions): Promise<string | Buffer> {\n this.logger.debug('Reading file', { path: inputPath, encoding: options?.encoding });\n await this.ensureReady();\n const absolutePath = this.resolvePath(inputPath);\n\n try {\n if (this._contained) {\n const { handle } = await this.openContainedPath(absolutePath);\n try {\n if ((await handle.stat()).isDirectory()) throw new IsDirectoryError(inputPath);\n return options?.encoding ? await handle.readFile({ encoding: options.encoding }) : await handle.readFile();\n } finally {\n await handle.close();\n }\n }\n const stats = await fs.stat(absolutePath);\n if (stats.isDirectory()) throw new IsDirectoryError(inputPath);\n return options?.encoding\n ? await fs.readFile(absolutePath, { encoding: options.encoding })\n : await fs.readFile(absolutePath);\n } catch (error: unknown) {\n if (error instanceof IsDirectoryError) throw error;\n if (isEnoentError(error)) throw new FileNotFoundError(inputPath);\n throw error;\n }\n }\n\n async writeFile(inputPath: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const contentSize = Buffer.isBuffer(content) ? content.length : content.length;\n this.logger.debug('Writing file', { path: inputPath, size: contentSize, recursive: options?.recursive });\n await this.ensureReady();\n this.assertWritable('writeFile');\n const absolutePath = this.resolvePath(inputPath);\n await this.assertPathContained(absolutePath);\n\n // When recursive is explicitly false, verify parent directory exists\n if (options?.recursive === false) {\n const dir = nodePath.dirname(absolutePath);\n const parentPath = nodePath.dirname(inputPath);\n try {\n const stat = await fs.stat(dir);\n if (!stat.isDirectory()) {\n throw new NotDirectoryError(parentPath);\n }\n } catch (error: unknown) {\n if (error instanceof NotDirectoryError) throw error;\n if (isEnoentError(error)) {\n throw new DirectoryNotFoundError(parentPath);\n }\n throw error;\n }\n }\n\n if (options?.recursive !== false) {\n const dir = nodePath.dirname(absolutePath);\n await fs.mkdir(dir, { recursive: true });\n }\n\n // Optimistic concurrency: reject if file was modified since caller last read it\n if (options?.expectedMtime) {\n try {\n const currentStat = await fs.stat(absolutePath);\n // Compare via Date objects — Node's stats.mtime applies internal\n // rounding that can diverge from Math.floor(stats.mtimeMs).\n if (currentStat.mtime.getTime() !== options.expectedMtime.getTime()) {\n throw new StaleFileError(inputPath, options.expectedMtime, currentStat.mtime);\n }\n } catch (error: unknown) {\n if (error instanceof StaleFileError) throw error;\n // File doesn't exist yet — no conflict possible, proceed with write\n if (!isEnoentError(error)) throw error;\n }\n }\n\n // Use 'wx' flag for atomic overwrite check (avoids TOCTOU race)\n const writeFlag = options?.overwrite === false ? 'wx' : 'w';\n try {\n await fs.writeFile(absolutePath, this.toBuffer(content), { flag: writeFlag });\n } catch (error: unknown) {\n if (options?.overwrite === false && isEexistError(error)) {\n throw new FileExistsError(inputPath);\n }\n throw error;\n }\n }\n\n async appendFile(inputPath: string, content: FileContent): Promise<void> {\n const contentSize = Buffer.isBuffer(content) ? content.length : content.length;\n this.logger.debug('Appending to file', { path: inputPath, size: contentSize });\n await this.ensureReady();\n this.assertWritable('appendFile');\n const absolutePath = this.resolvePath(inputPath);\n await this.assertPathContained(absolutePath);\n const dir = nodePath.dirname(absolutePath);\n await fs.mkdir(dir, { recursive: true });\n await fs.appendFile(absolutePath, this.toBuffer(content));\n }\n\n async deleteFile(inputPath: string, options?: RemoveOptions): Promise<void> {\n this.logger.debug('Deleting file', { path: inputPath, force: options?.force });\n await this.ensureReady();\n this.assertWritable('deleteFile');\n const absolutePath = this.resolvePath(inputPath);\n await this.assertPathContained(absolutePath);\n\n try {\n const stats = await fs.stat(absolutePath);\n if (stats.isDirectory()) {\n throw new IsDirectoryError(inputPath);\n }\n await fs.unlink(absolutePath);\n } catch (error: unknown) {\n if (error instanceof IsDirectoryError) throw error;\n if (isEnoentError(error)) {\n if (!options?.force) {\n throw new FileNotFoundError(inputPath);\n }\n } else {\n throw error;\n }\n }\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n this.logger.debug('Copying file', { src, dest, recursive: options?.recursive });\n await this.ensureReady();\n this.assertWritable('copyFile');\n const srcPath = this.resolvePath(src);\n const destPath = this.resolvePath(dest);\n await this.assertPathContained(srcPath);\n await this.assertPathContained(destPath);\n\n try {\n const stats = await fs.stat(srcPath);\n if (stats.isDirectory()) {\n if (!options?.recursive) {\n throw new IsDirectoryError(src);\n }\n await this.copyDirectory(srcPath, destPath, options);\n } else {\n await fs.mkdir(nodePath.dirname(destPath), { recursive: true });\n // Use COPYFILE_EXCL for atomic overwrite check (avoids TOCTOU race)\n const copyFlags = options?.overwrite === false ? fsConstants.COPYFILE_EXCL : 0;\n try {\n await fs.copyFile(srcPath, destPath, copyFlags);\n } catch (error: unknown) {\n if (options?.overwrite === false && isEexistError(error)) {\n throw new FileExistsError(dest);\n }\n throw error;\n }\n }\n } catch (error: unknown) {\n if (error instanceof IsDirectoryError || error instanceof FileExistsError) throw error;\n if (isEnoentError(error)) {\n throw new FileNotFoundError(src);\n }\n throw error;\n }\n }\n\n private async copyDirectory(src: string, dest: string, options?: CopyOptions): Promise<void> {\n await this.ensureReady();\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcEntry = nodePath.join(src, entry.name);\n const destEntry = nodePath.join(dest, entry.name);\n\n // Verify entries don't escape sandbox via symlink\n await this.assertPathContained(srcEntry);\n await this.assertPathContained(destEntry);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcEntry, destEntry, options);\n } else {\n // Use COPYFILE_EXCL for atomic overwrite check (avoids TOCTOU race)\n const copyFlags = options?.overwrite === false ? fsConstants.COPYFILE_EXCL : 0;\n try {\n await fs.copyFile(srcEntry, destEntry, copyFlags);\n } catch (error: unknown) {\n if (options?.overwrite === false && isEexistError(error)) {\n // Skip existing files when overwrite is false\n continue;\n }\n throw error;\n }\n }\n }\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n this.logger.debug('Moving file', { src, dest, overwrite: options?.overwrite });\n await this.ensureReady();\n this.assertWritable('moveFile');\n const srcPath = this.resolvePath(src);\n const destPath = this.resolvePath(dest);\n await this.assertPathContained(srcPath);\n await this.assertPathContained(destPath);\n\n try {\n await fs.mkdir(nodePath.dirname(destPath), { recursive: true });\n\n // When overwrite: false, use copy+delete to avoid TOCTOU race condition.\n // copyFile uses COPYFILE_EXCL which atomically checks and writes.\n if (options?.overwrite === false) {\n await this.copyFile(src, dest, { ...options, overwrite: false });\n await fs.rm(srcPath, { recursive: true, force: true });\n return;\n }\n\n try {\n await fs.rename(srcPath, destPath);\n } catch (error: unknown) {\n // Only fall back to copy+delete for cross-device moves (EXDEV)\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EXDEV') {\n throw error;\n }\n await this.copyFile(src, dest, options);\n await fs.rm(srcPath, { recursive: true, force: true });\n }\n } catch (error: unknown) {\n if (error instanceof FileExistsError) throw error;\n if (isEnoentError(error)) {\n throw new FileNotFoundError(src);\n }\n throw error;\n }\n }\n\n async mkdir(inputPath: string, options?: { recursive?: boolean }): Promise<void> {\n this.logger.debug('Creating directory', { path: inputPath, recursive: options?.recursive });\n await this.ensureReady();\n this.assertWritable('mkdir');\n const absolutePath = this.resolvePath(inputPath);\n await this.assertPathContained(absolutePath);\n\n try {\n await fs.mkdir(absolutePath, { recursive: options?.recursive ?? true });\n } catch (error: unknown) {\n if (isEexistError(error)) {\n const stats = await fs.stat(absolutePath);\n if (!stats.isDirectory()) {\n throw new FileExistsError(inputPath);\n }\n } else if (isEnoentError(error)) {\n // Parent directory doesn't exist (only happens when recursive: false)\n const parentPath = nodePath.dirname(inputPath);\n throw new DirectoryNotFoundError(parentPath);\n } else {\n throw error;\n }\n }\n }\n\n async rmdir(inputPath: string, options?: RemoveOptions): Promise<void> {\n this.logger.debug('Removing directory', { path: inputPath, recursive: options?.recursive, force: options?.force });\n await this.ensureReady();\n this.assertWritable('rmdir');\n const absolutePath = this.resolvePath(inputPath);\n await this.assertPathContained(absolutePath);\n\n try {\n const stats = await fs.stat(absolutePath);\n if (!stats.isDirectory()) {\n throw new NotDirectoryError(inputPath);\n }\n\n if (options?.recursive) {\n await fs.rm(absolutePath, { recursive: true, force: options?.force ?? false });\n } else {\n const entries = await fs.readdir(absolutePath);\n if (entries.length > 0) {\n throw new DirectoryNotEmptyError(inputPath);\n }\n await fs.rmdir(absolutePath);\n }\n } catch (error: unknown) {\n if (error instanceof NotDirectoryError || error instanceof DirectoryNotEmptyError) {\n throw error;\n }\n if (isEnoentError(error)) {\n if (!options?.force) {\n throw new DirectoryNotFoundError(inputPath);\n }\n } else {\n throw error;\n }\n }\n }\n\n async readdir(inputPath: string, options?: ListOptions): Promise<FileEntry[]> {\n this.logger.debug('Reading directory', { path: inputPath, recursive: options?.recursive });\n await this.ensureReady();\n const absolutePath = this.resolvePath(inputPath);\n let directoryHandle: FileHandle | undefined;\n\n try {\n if (this._contained) {\n directoryHandle = (await this.openContainedPath(absolutePath)).handle;\n }\n const stats = directoryHandle\n ? await directoryHandle.stat({ bigint: true })\n : await fs.stat(absolutePath, { bigint: true });\n if (!stats.isDirectory()) {\n throw new NotDirectoryError(inputPath);\n }\n\n // Linux supports fd-backed child paths. Other platforms use the original\n // path and revalidate the directory before returning.\n const directoryPath =\n directoryHandle && process.platform === 'linux' ? `/proc/self/fd/${directoryHandle.fd}` : absolutePath;\n const entries = await fs.readdir(directoryPath, { withFileTypes: true });\n const result: FileEntry[] = [];\n\n for (const entry of entries) {\n const entryPath = nodePath.join(absolutePath, entry.name);\n const entryDiskPath = nodePath.join(directoryPath, entry.name);\n\n if (options?.extension) {\n const extensions = Array.isArray(options.extension) ? options.extension : [options.extension];\n if (entry.isFile()) {\n const ext = nodePath.extname(entry.name);\n if (!extensions.some(e => e === ext || e === ext.slice(1))) {\n continue;\n }\n }\n }\n\n // Check if entry is a symlink\n const isSymlink = entry.isSymbolicLink();\n let symlinkTarget: string | undefined;\n let resolvedType: 'file' | 'directory' = 'file';\n\n if (isSymlink) {\n try {\n // Get the symlink target path\n symlinkTarget = await fs.readlink(entryDiskPath);\n // Determine the type of the target (follow the symlink)\n const targetStat = await fs.stat(entryDiskPath);\n resolvedType = targetStat.isDirectory() ? 'directory' : 'file';\n } catch {\n // If we can't read the symlink target or it's broken, treat as file\n resolvedType = 'file';\n }\n } else {\n resolvedType = entry.isDirectory() ? 'directory' : 'file';\n }\n\n const fileEntry: FileEntry = {\n name: entry.name,\n type: resolvedType,\n isSymlink: isSymlink || undefined,\n symlinkTarget,\n };\n\n if (resolvedType === 'file' && !isSymlink) {\n try {\n const stat = await fs.stat(entryDiskPath);\n fileEntry.size = stat.size;\n } catch {\n // Ignore\n }\n }\n\n result.push(fileEntry);\n\n // Only recurse into directories (follow symlinks to directories)\n if (options?.recursive && resolvedType === 'directory') {\n // Default to 100 to prevent stack overflow on deeply nested structures\n const depth = options.maxDepth ?? 100;\n if (depth > 0) {\n const subEntries = await this.readdir(this.toRelativePath(entryPath), { ...options, maxDepth: depth - 1 });\n result.push(\n ...subEntries.map(e => ({\n ...e,\n name: `${entry.name}/${e.name}`,\n })),\n );\n }\n }\n }\n\n if (directoryHandle && directoryPath === absolutePath) {\n const current = await this.openContainedPath(absolutePath);\n try {\n const currentStat = await current.handle.stat({ bigint: true });\n if (\n stats.dev === 0n ||\n stats.ino === 0n ||\n currentStat.dev === 0n ||\n currentStat.ino === 0n ||\n stats.dev !== currentStat.dev ||\n stats.ino !== currentStat.ino\n ) {\n throw new PermissionError(absolutePath, 'access');\n }\n } finally {\n await current.handle.close();\n }\n }\n return result;\n } catch (error: unknown) {\n if (error instanceof NotDirectoryError) throw error;\n if (isEnoentError(error)) {\n throw new DirectoryNotFoundError(inputPath);\n }\n throw error;\n } finally {\n await directoryHandle?.close();\n }\n }\n\n private async containedMetadata(absolutePath: string): Promise<Stats> {\n if (process.platform === 'linux') {\n const { handle } = await this.openContainedPath(absolutePath, true);\n try {\n return await handle.stat();\n } finally {\n await handle.close();\n }\n }\n\n // Node does not expose a portable metadata-only open on other platforms.\n // Recheck canonical path and identity around stat when read access is denied.\n try {\n const { handle } = await this.openContainedPath(absolutePath, true);\n try {\n return await handle.stat();\n } finally {\n await handle.close();\n }\n } catch (error) {\n if (!(error instanceof Error) || !('code' in error) || error.code !== 'EACCES') throw error;\n const roots = await this.containedRoots();\n const before = await fs.realpath(absolutePath);\n this.assertCanonicalPathContained(before, absolutePath, roots);\n const stats = await fs.stat(absolutePath);\n const after = await fs.realpath(absolutePath);\n this.assertCanonicalPathContained(after, absolutePath, roots);\n const current = await fs.stat(after, { bigint: true });\n if (\n before !== after ||\n !Number.isSafeInteger(stats.dev) ||\n !Number.isSafeInteger(stats.ino) ||\n current.dev === 0n ||\n current.ino === 0n ||\n BigInt(stats.dev) !== current.dev ||\n BigInt(stats.ino) !== current.ino\n ) {\n throw new PermissionError(absolutePath, 'access');\n }\n return stats;\n }\n }\n\n async exists(inputPath: string): Promise<boolean> {\n await this.ensureReady();\n const absolutePath = this.resolvePath(inputPath);\n if (!this._contained) return fsExists(absolutePath);\n try {\n await this.containedMetadata(absolutePath);\n return true;\n } catch (error) {\n if (isEnoentError(error)) return false;\n throw error;\n }\n }\n\n async stat(inputPath: string): Promise<FileStat> {\n await this.ensureReady();\n const absolutePath = this.resolvePath(inputPath);\n if (!this._contained) {\n const result = await fsStat(absolutePath, inputPath);\n return { ...result, path: this.toRelativePath(absolutePath) };\n }\n try {\n const stats = await this.containedMetadata(absolutePath);\n return {\n name: nodePath.basename(absolutePath),\n path: this.toRelativePath(absolutePath),\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n createdAt: stats.birthtime,\n modifiedAt: stats.mtime,\n mimeType: stats.isFile() ? getMimeType(absolutePath) : undefined,\n };\n } catch (error) {\n if (isEnoentError(error)) throw new FileNotFoundError(inputPath);\n throw error;\n }\n }\n\n async realpath(inputPath: string): Promise<string> {\n await this.ensureReady();\n const absolutePath = this.resolvePath(inputPath);\n if (!this._contained) return this.toRelativePath(await fs.realpath(absolutePath));\n const { handle, canonicalPath } = await this.openContainedPath(absolutePath, true);\n await handle.close();\n return this.toRelativePath(canonicalPath);\n }\n\n /**\n * Initialize the local filesystem by creating the base directory.\n * Status management is handled by the base class.\n */\n async init(): Promise<void> {\n this.logger.debug('Initializing filesystem', { basePath: this._basePath });\n await fs.mkdir(this._basePath, { recursive: true });\n this.logger.debug('Filesystem initialized', { basePath: this._basePath });\n }\n\n /**\n * Clean up the local filesystem.\n * LocalFilesystem doesn't delete files on destroy by default.\n * Status management is handled by the base class.\n */\n async destroy(): Promise<void> {\n // LocalFilesystem doesn't delete files on destroy\n }\n\n getInfo(): FilesystemInfo<{ basePath: string; contained: boolean; allowedPaths?: string[] }> {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n readOnly: this.readOnly,\n status: this.status,\n error: this.error,\n metadata: {\n basePath: this.basePath,\n contained: this._contained,\n ...(this._allowedPaths.length > 0 && { allowedPaths: [...this._allowedPaths] }),\n },\n };\n }\n\n getInstructions(opts?: { requestContext?: RequestContext<any> }): string {\n return resolveInstructions(this._instructionsOverride, () => this._getDefaultInstructions(), opts?.requestContext);\n }\n\n private _getDefaultInstructions(): string {\n const parts = [`Local filesystem at \"${this.basePath}\". Relative paths resolve from this directory.`];\n\n if (this._contained) {\n if (this._allowedPaths.length > 0) {\n parts.push(\n `File access is restricted to this directory and the following allowed paths: ${this._allowedPaths.join(', ')}.`,\n );\n } else {\n parts.push('File access is restricted to this directory.');\n }\n } else {\n parts.push('Containment is disabled, so any path on the host filesystem is accessible.');\n }\n\n return parts.join(' ');\n }\n}\n","import * as nodePath from 'node:path';\nimport type { WorkspaceFilesystem } from './filesystem';\n\n/**\n * File Read Tracker\n *\n * Tracks when files were last read by the workspace.\n * Used to enforce \"read before write\" semantics.\n */\n\n/**\n * Record of when a file was read.\n */\nexport interface FileReadRecord {\n /** The file path that was read */\n path: string;\n /** When the file was read */\n readAt: Date;\n /** The file's modification time when it was read */\n modifiedAtRead: Date;\n /**\n * Filesystem scope the file was read from (see {@link deriveReadScope}).\n * A record only satisfies the read-before-write gate for writes on a\n * filesystem with the same scope.\n */\n scope?: string;\n}\n\n/**\n * Interface for tracking file reads.\n *\n * Methods may return promises so implementations can be backed by external\n * storage (e.g. to persist read records across process restarts in\n * serverless environments).\n */\nexport interface FileReadTracker {\n /** Record that a file was read, optionally tagged with a filesystem scope */\n recordRead(path: string, modifiedAt: Date, scope?: string): void | Promise<void>;\n\n /** Get the last read record for a path */\n getReadRecord(path: string): FileReadRecord | undefined | Promise<FileReadRecord | undefined>;\n\n /**\n * Check if file needs re-reading.\n * Returns needsReRead: true if the file was never read, was modified since\n * last read, or was read on a filesystem with a different scope.\n */\n needsReRead(\n path: string,\n currentModifiedAt: Date,\n scope?: string,\n ): { needsReRead: boolean; reason?: string } | Promise<{ needsReRead: boolean; reason?: string }>;\n\n /** Clear read record (typically after a successful write) */\n clearReadRecord(path: string): void | Promise<void>;\n\n /** Clear all records */\n clear(): void | Promise<void>;\n}\n\n/**\n * Derive a stable read-record scope for a filesystem from its configuration.\n *\n * The scope identifies the *backing file store*, not the object instance:\n * two `LocalFilesystem` instances with the same `basePath` point at the same\n * files and must share read records (suspend/resume creates fresh instances),\n * while different base paths are different files and must not. Instance ids\n * (`filesystem.id`, `workspace.id`) are auto-generated per construction and\n * would break record persistence across resume for dynamically resolved\n * workspaces — so the scope is derived from `provider` + `basePath` instead.\n *\n * Filesystems without a `basePath` (e.g. in-memory or composite filesystems)\n * fall back to the bare provider string. That is deliberately coarse:\n * same-provider filesystems share records, which matches the pre-scoping\n * behavior and is still guarded by the mtime staleness check. Per-mount scope\n * routing for CompositeFilesystem is a possible follow-up.\n */\nexport function deriveReadScope(fs: Pick<WorkspaceFilesystem, 'provider' | 'basePath'>): string {\n return fs.basePath ? `${fs.provider}:${fs.basePath}` : fs.provider;\n}\n\n/**\n * Normalize a path for read-record keying: unify separators, resolve dot\n * segments, remove trailing slash. Shared by all FileReadTracker\n * implementations so records key identically regardless of backing store.\n */\nexport function normalizeReadTrackerPath(pathStr: string): string {\n const normalized = nodePath.posix.normalize(pathStr.replace(/\\\\/g, '/'));\n return normalized.replace(/\\/$/, '') || '/';\n}\n\n/**\n * Evaluate whether a file needs re-reading given its read record (if any) and\n * its current modification time. Shared by all FileReadTracker implementations\n * so the policy semantics and error messages stay identical.\n */\nexport function evaluateReadRecord(\n path: string,\n record: FileReadRecord | undefined,\n currentModifiedAt: Date,\n scope?: string,\n): { needsReRead: boolean; reason?: string } {\n if (!record) {\n return {\n needsReRead: true,\n reason: `File \"${path}\" has not been read. You must read a file before writing to it.`,\n };\n }\n\n // A record only counts for the filesystem it was read from. Records without\n // a scope fail closed when a scope is expected.\n if (record.scope !== scope) {\n return {\n needsReRead: true,\n reason: `File \"${path}\" was read in a different filesystem. You must read a file before writing to it.`,\n };\n }\n\n // Compare timestamps - if current modification time is newer than when we read it\n if (currentModifiedAt.getTime() > record.modifiedAtRead.getTime()) {\n return {\n needsReRead: true,\n reason: `File \"${path}\" was modified since last read (read at: ${record.modifiedAtRead.toISOString()}, current: ${currentModifiedAt.toISOString()}). Please re-read the file to get the latest contents.`,\n };\n }\n\n return { needsReRead: false };\n}\n\n/**\n * In-memory implementation of FileReadTracker.\n */\nexport class InMemoryFileReadTracker implements FileReadTracker {\n private records = new Map<string, FileReadRecord>();\n\n recordRead(path: string, modifiedAt: Date, scope?: string): void {\n const normalizedPath = normalizeReadTrackerPath(path);\n this.records.set(normalizedPath, {\n path: normalizedPath,\n readAt: new Date(),\n modifiedAtRead: modifiedAt,\n scope,\n });\n }\n\n getReadRecord(path: string): FileReadRecord | undefined {\n return this.records.get(normalizeReadTrackerPath(path));\n }\n\n needsReRead(path: string, currentModifiedAt: Date, scope?: string): { needsReRead: boolean; reason?: string } {\n return evaluateReadRecord(path, this.getReadRecord(path), currentModifiedAt, scope);\n }\n\n clearReadRecord(path: string): void {\n this.records.delete(normalizeReadTrackerPath(path));\n }\n\n clear(): void {\n this.records.clear();\n }\n}\n","import * as nodePath from 'node:path';\n\n/**\n * File Write Lock\n *\n * Per-file promise queue that serializes write operations to the same path.\n * Prevents read-modify-write race conditions when multiple tool calls\n * target the same file concurrently.\n */\n\n/** Options for constructing a FileWriteLock. */\nexport interface FileWriteLockOptions {\n /** Maximum time (ms) a single lock-holder may run before being rejected. Default: 30 000. */\n timeoutMs?: number;\n}\n\n/**\n * Interface for per-file write locking.\n */\nexport interface FileWriteLock {\n /** Execute `fn` while holding an exclusive lock on `filePath`. */\n withLock<T>(filePath: string, fn: () => Promise<T>): Promise<T>;\n\n /** Number of paths that currently have queued operations. */\n get size(): number;\n}\n\n/**\n * In-memory implementation of FileWriteLock using per-path promise queues.\n *\n * Adapted from mastracode's `withWriteLock` pattern.\n */\nexport class InMemoryFileWriteLock implements FileWriteLock {\n private queues = new Map<string, Promise<void>>();\n private readonly timeoutMs: number;\n\n constructor(opts?: FileWriteLockOptions) {\n this.timeoutMs = opts?.timeoutMs ?? 30_000;\n }\n\n get size(): number {\n return this.queues.size;\n }\n\n withLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n const key = this.normalizePath(filePath);\n\n // Get the current queue for this file (or a resolved promise if none)\n const currentQueue = this.queues.get(key) ?? Promise.resolve();\n\n // Create a deferred promise for our result\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const resultPromise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // Chain our operation onto the queue\n const queuePromise = currentQueue\n .catch(() => {}) // Ignore errors from previous operations\n .then(async () => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n const result = await Promise.race([\n fn(),\n new Promise<never>((_, rej) => {\n timeoutId = setTimeout(\n () => rej(new Error(`write-lock timeout on \"${key}\" after ${this.timeoutMs}ms`)),\n this.timeoutMs,\n );\n }),\n ]);\n clearTimeout(timeoutId);\n resolve(result);\n } catch (error) {\n clearTimeout(timeoutId);\n reject(error);\n }\n });\n\n // Update the queue\n this.queues.set(key, queuePromise);\n\n // Clean up when our operation completes\n void queuePromise.finally(() => {\n // Only delete if we're still the last in queue\n if (this.queues.get(key) === queuePromise) {\n this.queues.delete(key);\n }\n });\n\n return resultPromise;\n }\n\n private normalizePath(pathStr: string): string {\n // Normalize path: unify separators, resolve dot segments, remove trailing slash.\n //\n // Known limitations:\n // - Case-sensitive comparison: on case-insensitive filesystems (macOS HFS+,\n // Windows NTFS) \"Foo.txt\" and \"foo.txt\" produce different lock keys.\n // Acceptable because workspace tool calls echo paths back consistently.\n // - No base-directory resolution: \"foo.txt\" and \"/workspace/foo.txt\" are\n // distinct keys. Workspace tools pass paths relative to the workspace root,\n // so this doesn't arise in practice.\n // Collapse leading //+ before normalize (POSIX preserves leading //)\n const normalized = nodePath.posix.normalize(pathStr.replace(/\\\\/g, '/').replace(/^\\/\\/+/, '/'));\n return normalized.replace(/\\/+$/, '') || '/';\n }\n}\n","/**\n * Sandbox Errors\n *\n * Error classes for sandbox operations including execution and mounting.\n */\n\nimport type { SandboxOperation } from './types';\n\n// =============================================================================\n// Base Error\n// =============================================================================\n\nexport class SandboxError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'SandboxError';\n }\n}\n\n// =============================================================================\n// Execution Errors\n// =============================================================================\n\nexport class SandboxExecutionError extends SandboxError {\n constructor(\n message: string,\n public readonly exitCode: number,\n public readonly stdout: string,\n public readonly stderr: string,\n ) {\n super(message, 'EXECUTION_FAILED', { exitCode, stdout, stderr });\n this.name = 'SandboxExecutionError';\n }\n}\n\nexport class SandboxTimeoutError extends SandboxError {\n constructor(\n public readonly timeoutMs: number,\n public readonly operation: SandboxOperation,\n ) {\n super(`Execution timed out after ${timeoutMs}ms`, 'TIMEOUT', { timeoutMs, operation });\n this.name = 'SandboxTimeoutError';\n }\n}\n\nexport class SandboxNotReadyError extends SandboxError {\n constructor(idOrStatus: string) {\n super(`Sandbox is not ready: ${idOrStatus}`, 'NOT_READY', { id: idOrStatus });\n this.name = 'SandboxNotReadyError';\n }\n}\n\n/**\n * Thrown when a caller requests a sandbox feature that the active provider\n * cannot honor (e.g. an explicit per-file permission mode on a provider whose\n * upload mechanism does not support one).\n */\nexport class SandboxUnsupportedFeatureError extends SandboxError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'UNSUPPORTED_FEATURE', details);\n this.name = 'SandboxUnsupportedFeatureError';\n }\n}\n\n/**\n * Thrown when a sandbox operation is cancelled via an {@link AbortSignal}.\n * Carries a stable `code` of `ABORTED` so callers can reliably detect cancellation.\n */\nexport class SandboxAbortError extends SandboxError {\n constructor(operation: string = 'operation', reason?: unknown) {\n super(`Sandbox operation aborted: ${operation}`, 'ABORTED', { operation, reason });\n this.name = 'SandboxAbortError';\n this.cause = reason;\n }\n}\n\nexport class IsolationUnavailableError extends SandboxError {\n constructor(\n public readonly backend: string,\n public readonly reason: string,\n ) {\n super(`Isolation backend '${backend}' is not available: ${reason}`, 'ISOLATION_UNAVAILABLE', { backend, reason });\n this.name = 'IsolationUnavailableError';\n }\n}\n\n// =============================================================================\n// Mount Errors\n// =============================================================================\n\n/**\n * Base error for mount operations.\n */\nexport class MountError extends SandboxError {\n constructor(\n message: string,\n public readonly mountPath: string,\n details?: Record<string, unknown>,\n ) {\n super(message, 'MOUNT_ERROR', { ...details, mountPath });\n this.name = 'MountError';\n }\n}\n\n/**\n * Error thrown when sandbox doesn't support mounting.\n */\nexport class MountNotSupportedError extends SandboxError {\n constructor(sandboxProvider: string) {\n super(`Sandbox provider '${sandboxProvider}' does not support mounting`, 'MOUNT_NOT_SUPPORTED', {\n sandboxProvider,\n });\n this.name = 'MountNotSupportedError';\n }\n}\n\n/**\n * Error thrown when a filesystem cannot be mounted.\n */\nexport class FilesystemNotMountableError extends SandboxError {\n constructor(filesystemProvider: string, reason?: string) {\n const message = reason\n ? `Filesystem '${filesystemProvider}' cannot be mounted: ${reason}`\n : `Filesystem '${filesystemProvider}' does not support mounting`;\n super(message, 'FILESYSTEM_NOT_MOUNTABLE', { filesystemProvider, reason });\n this.name = 'FilesystemNotMountableError';\n }\n}\n","/**\n * Shared types for local mount operations.\n */\n\nexport const LOG_PREFIX = '[LocalSandbox]';\n\n/**\n * Context for local mount operations.\n * Uses a run function instead of E2B's sandbox.commands.run().\n */\nexport interface LocalMountContext {\n run: (\n command: string,\n args: string[],\n options?: { timeout?: number },\n ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n platform: NodeJS.Platform;\n logger: {\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n };\n}\n\n/**\n * Error thrown when a required FUSE tool (s3fs, gcsfuse, macFUSE) is not installed.\n *\n * Distinguished from general mount errors so `LocalSandbox.mount()` can mark the\n * mount as `unavailable` (warning) rather than `error`. The workspace still works\n * via SDK filesystem methods — only sandbox process access to the mount path is affected.\n */\nexport class MountToolNotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'MountToolNotFoundError';\n }\n}\n","/**\n * Mount Manager\n *\n * Encapsulates all mount-related state and operations for sandboxes.\n * Used by BaseSandbox to manage filesystem mounts.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport type { IMastraLogger } from '../../logger';\nimport type { WorkspaceFilesystem } from '../filesystem/filesystem';\nimport type { FilesystemMountConfig, MountResult } from '../filesystem/mount';\n\nimport type { Workspace } from '../workspace';\nimport { MountToolNotFoundError } from './mounts/types';\nimport type { WorkspaceSandbox } from './sandbox';\nimport type { MountEntry, MountState } from './types';\n\n// Type-only import — erased at compile time, no circular dependency at runtime.\n\n/**\n * Mount function signature.\n */\nexport type MountFn = (filesystem: WorkspaceFilesystem, mountPath: string) => Promise<MountResult>;\n\n/**\n * onMount hook result.\n * - false: skip mount\n * - { success, error? }: hook handled it\n * - void: use default mount\n */\nexport type OnMountResult = false | { success: boolean; error?: string } | void;\n\n/**\n * Arguments passed to the onMount hook.\n */\nexport interface OnMountArgs {\n /** The filesystem being mounted */\n filesystem: WorkspaceFilesystem;\n /** The mount path in the sandbox */\n mountPath: string;\n /** The mount configuration from filesystem.getMountConfig() (undefined if not supported) */\n config: FilesystemMountConfig | undefined;\n /** The sandbox instance for custom mount implementations */\n sandbox: WorkspaceSandbox;\n /** The workspace instance */\n workspace: Workspace;\n}\n\n/**\n * onMount hook function.\n *\n * Called for each filesystem before mounting into sandbox.\n * Return value controls mounting behavior (see {@link OnMountResult}).\n *\n * @example Skip local filesystems\n * ```typescript\n * onMount: ({ filesystem }) => {\n * if (filesystem.provider === 'local') return false;\n * }\n * ```\n *\n * @example Custom mount implementation\n * ```typescript\n * onMount: async ({ filesystem, mountPath, sandbox }) => {\n * if (mountPath === '/custom') {\n * await sandbox.executeCommand?.('my-mount-script', [mountPath]);\n * return { success: true };\n * }\n * }\n * ```\n */\nexport type OnMountHook = (args: OnMountArgs) => Promise<OnMountResult> | OnMountResult;\n\n/**\n * MountManager configuration.\n */\nexport interface MountManagerConfig {\n /** The mount implementation from the sandbox */\n mount: MountFn;\n /** Logger instance */\n logger: IMastraLogger;\n}\n\n/**\n * Manages filesystem mounts for a sandbox.\n *\n * Provides methods for tracking mount state, updating entries,\n * and processing pending mounts.\n */\nexport class MountManager {\n private _entries: Map<string, MountEntry> = new Map();\n private _mountFn: MountFn;\n private _onMount?: OnMountHook;\n private _sandbox?: WorkspaceSandbox;\n private _workspace?: Workspace;\n private logger: IMastraLogger;\n\n constructor(config: MountManagerConfig) {\n this._mountFn = config.mount;\n this.logger = config.logger;\n }\n\n /**\n * Set the sandbox and workspace references for onMount hook args.\n * Called by Workspace during construction.\n */\n setContext(context: { sandbox: WorkspaceSandbox; workspace: Workspace }): void {\n this._sandbox = context.sandbox;\n this._workspace = context.workspace;\n }\n\n /**\n * Set the onMount hook for custom mount handling.\n * Called before each mount - can skip, handle, or defer to default.\n */\n setOnMount(hook: OnMountHook | undefined): void {\n this._onMount = hook;\n }\n\n /**\n * Update the logger instance.\n * Called when the sandbox receives a logger from Mastra.\n * @internal\n */\n __setLogger(logger: IMastraLogger): void {\n this.logger = logger;\n }\n\n // ---------------------------------------------------------------------------\n // Entry Access\n // ---------------------------------------------------------------------------\n\n /**\n * Get all mount entries.\n */\n get entries(): ReadonlyMap<string, MountEntry> {\n return this._entries;\n }\n\n /**\n * Get a mount entry by path.\n */\n get(path: string): MountEntry | undefined {\n return this._entries.get(path);\n }\n\n /**\n * Check if a mount exists at the given path.\n */\n has(path: string): boolean {\n return this._entries.has(path);\n }\n\n // ---------------------------------------------------------------------------\n // Entry Modification\n // ---------------------------------------------------------------------------\n\n /**\n * Add pending mounts from workspace config.\n * These will be processed when `processPending()` is called.\n */\n add(mounts: Record<string, WorkspaceFilesystem>): void {\n const paths = Object.keys(mounts);\n this.logger.debug('Adding pending mounts', { count: paths.length, paths });\n\n for (const [path, filesystem] of Object.entries(mounts)) {\n this._entries.set(path, {\n filesystem,\n state: 'pending',\n });\n }\n }\n\n /**\n * Update a mount entry's state.\n * Creates the entry if it doesn't exist.\n */\n set(\n path: string,\n updates: {\n filesystem?: WorkspaceFilesystem;\n state: MountState;\n config?: FilesystemMountConfig;\n error?: string;\n },\n ): void {\n const existing = this._entries.get(path);\n\n if (existing) {\n existing.state = updates.state;\n if (updates.config) {\n existing.config = updates.config;\n existing.configHash = this.hashConfig(updates.config);\n }\n if ('error' in updates) {\n existing.error = updates.error;\n }\n } else if (updates.filesystem) {\n // Create new entry (for direct mount() calls without add())\n this._entries.set(path, {\n filesystem: updates.filesystem,\n state: updates.state,\n config: updates.config,\n configHash: updates.config ? this.hashConfig(updates.config) : undefined,\n error: updates.error,\n });\n } else {\n this.logger.debug('set() called for unknown path without filesystem', { path });\n }\n }\n\n /**\n * Delete a mount entry.\n */\n delete(path: string): boolean {\n return this._entries.delete(path);\n }\n\n /**\n * Clear all mount entries.\n */\n clear(): void {\n this._entries.clear();\n }\n\n // ---------------------------------------------------------------------------\n // Mount Processing\n // ---------------------------------------------------------------------------\n\n /**\n * Process all pending mounts.\n * Call this after sandbox is ready (in start()).\n */\n async processPending(): Promise<void> {\n const pendingCount = [...this._entries.values()].filter(e => e.state === 'pending').length;\n if (pendingCount === 0) {\n return;\n }\n\n this.logger.debug('Processing pending mounts', { count: pendingCount });\n\n for (const [path, entry] of this._entries) {\n if (entry.state !== 'pending') {\n continue;\n }\n\n const fsProvider = entry.filesystem.provider;\n\n // Get config if available\n const config = entry.filesystem.getMountConfig?.();\n\n // Call onMount hook if configured\n if (this._onMount) {\n try {\n const hookResult = await this._onMount({\n filesystem: entry.filesystem,\n mountPath: path,\n config,\n sandbox: this._sandbox!,\n workspace: this._workspace!,\n });\n\n // false = skip mount entirely\n if (hookResult === false) {\n entry.state = 'unsupported';\n entry.error = 'Skipped by onMount hook';\n this.logger.debug('Mount skipped by onMount hook', { path, provider: fsProvider });\n continue;\n }\n\n // { success, error? } = hook handled it\n if (hookResult && typeof hookResult === 'object') {\n if (hookResult.success) {\n entry.state = 'mounted';\n entry.config = config;\n entry.configHash = config ? this.hashConfig(config) : undefined;\n this.logger.info('Mount handled by onMount hook', { path, provider: fsProvider });\n } else {\n entry.state = 'error';\n entry.error = hookResult.error ?? 'Mount hook failed';\n this.logger.error('Mount hook failed', { path, provider: fsProvider, error: entry.error });\n }\n continue;\n }\n\n // void = continue with default mount\n } catch (err) {\n entry.state = 'error';\n entry.error = `Mount hook error: ${String(err)}`;\n this.logger.error('Mount hook threw error', { path, provider: fsProvider, error: entry.error });\n continue;\n }\n }\n\n // Check if filesystem supports mounting (for default behavior)\n if (!config) {\n entry.state = 'unsupported';\n entry.error = 'Filesystem does not support mounting';\n this.logger.debug('Filesystem does not support mounting', { path, provider: fsProvider });\n continue;\n }\n\n // Store config and mark as mounting\n entry.config = config;\n entry.configHash = this.hashConfig(config);\n entry.state = 'mounting';\n\n this.logger.debug('Mounting filesystem', { path, provider: fsProvider, type: config.type });\n\n // Call the sandbox's mount implementation\n try {\n const result = await this._mountFn(entry.filesystem, path);\n if (result.success) {\n entry.state = 'mounted';\n this.logger.info('Mount successful', { path, provider: fsProvider });\n } else if (result.unavailable) {\n entry.state = 'unavailable';\n entry.error = result.error ?? 'FUSE tool not installed';\n this.logger.warn('FUSE mount unavailable', { path, provider: fsProvider, error: entry.error });\n } else {\n entry.state = 'error';\n entry.error = result.error ?? 'Mount failed';\n this.logger.error('Mount failed', { path, provider: fsProvider, error: entry.error });\n }\n } catch (err) {\n if (err instanceof MountToolNotFoundError) {\n entry.state = 'unavailable';\n entry.error = String(err);\n this.logger.warn('FUSE mount unavailable', { path, provider: fsProvider, error: entry.error });\n } else {\n entry.state = 'error';\n entry.error = String(err);\n this.logger.error('Mount threw error', { path, provider: fsProvider, error: entry.error });\n }\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Marker File Helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Generate a marker filename for a mount path.\n * Used by sandboxes to store mount metadata for reconnection detection.\n *\n * @param mountPath - The mount path to generate a filename for\n * @returns A safe filename like \"mount-abc123\"\n */\n markerFilename(mountPath: string): string {\n let hash = 0;\n for (let i = 0; i < mountPath.length; i++) {\n const char = mountPath.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash |= 0; // Convert to 32-bit integer\n }\n return `mount-${Math.abs(hash).toString(36)}`;\n }\n\n /**\n * Generate marker file content for a mount path.\n * Format: \"path|configHash\" - used for detecting config changes on reconnect.\n *\n * @param mountPath - The mount path\n * @returns Marker content string, or null if no config hash available\n */\n getMarkerContent(mountPath: string): string | null {\n const entry = this._entries.get(mountPath);\n if (!entry?.configHash) {\n return null;\n }\n return `${mountPath}|${entry.configHash}`;\n }\n\n /**\n * Parse marker file content.\n *\n * @param content - The marker file content (format: \"path|configHash\")\n * @returns Parsed path and configHash, or null if invalid format\n */\n parseMarkerContent(content: string): { path: string; configHash: string } | null {\n const separatorIndex = content.lastIndexOf('|');\n if (separatorIndex <= 0) {\n return null;\n }\n const path = content.slice(0, separatorIndex);\n const configHash = content.slice(separatorIndex + 1);\n if (!path || !configHash) return null;\n return { path, configHash };\n }\n\n /**\n * Check if a config hash matches the expected hash for a mount path.\n *\n * @param mountPath - The mount path to check\n * @param storedHash - The hash from the marker file\n * @returns true if the hashes match\n */\n isConfigMatching(mountPath: string, storedHash: string): boolean {\n const entry = this._entries.get(mountPath);\n return entry?.configHash === storedHash;\n }\n\n /**\n * Compute a hash for a mount config. Used for comparing configs across mounts.\n *\n * @param config - The config to hash\n * @returns A hash string suitable for comparison\n */\n computeConfigHash(config: FilesystemMountConfig): string {\n return this.hashConfig(config);\n }\n\n // ---------------------------------------------------------------------------\n // Internal\n // ---------------------------------------------------------------------------\n\n /**\n * Hash a mount config for comparison.\n */\n private hashConfig(config: FilesystemMountConfig): string {\n const normalized = JSON.stringify(this.sortKeysDeep(config));\n return createHash('sha256').update(normalized).digest('hex').slice(0, 16);\n }\n\n private sortKeysDeep(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') return obj;\n if (Array.isArray(obj)) return obj.map(item => this.sortKeysDeep(item));\n return Object.keys(obj as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = this.sortKeysDeep((obj as Record<string, unknown>)[key]);\n return acc;\n }, {});\n }\n}\n","/**\n * Workspace Sandbox Interface\n *\n * Defines the contract for sandbox providers that can be used with Workspace.\n * Users pass sandbox provider instances to the Workspace constructor.\n *\n * Sandboxes provide isolated environments for code and command execution.\n * They may have their own filesystem that's separate from the workspace FS.\n *\n * Built-in providers (via ComputeSDK):\n * - E2B: Cloud sandboxes\n * - Modal: GPU-enabled sandboxes\n * - Docker: Container-based execution\n * - Local: Development-only local execution\n *\n * @example\n * ```typescript\n * import { Workspace } from '@mastra/core';\n * import { ComputeSDKSandbox } from '@mastra/workspace-sandbox-computesdk';\n *\n * const workspace = new Workspace({\n * sandbox: new ComputeSDKSandbox({ provider: 'e2b' }),\n * });\n * ```\n */\n\nimport type { RequestContext } from '../../request-context';\nimport type { WorkspaceFilesystem } from '../filesystem/filesystem';\nimport type { MountResult } from '../filesystem/mount';\nimport type { SandboxLifecycle } from '../lifecycle';\n\nexport type { SandboxStartOutcome, SandboxStartResult } from '../lifecycle';\n\nimport { SandboxError, SandboxUnsupportedFeatureError } from './errors';\nimport type { SandboxStartHook } from './mastra-sandbox';\nimport type { MountManager } from './mount-manager';\nimport type { SandboxProcessManager } from './process-manager';\nimport type { CommandResult, ExecuteCommandOptions, SandboxInfo } from './types';\n\n// =============================================================================\n// Networking Capability\n// =============================================================================\n\n/**\n * Optional networking capability for sandboxes that can expose ports publicly.\n *\n * Providers that support public port exposure (Vercel Sandbox, E2B, Daytona,\n * Modal, Blaxel, etc.) implement this to surface public URLs through the\n * abstraction. Enables preview URLs and sandbox deploys.\n *\n * Some providers keep ports private by default, so the URL may ask for\n * sign-in before it serves anything, depending on the provider.\n */\nexport interface SandboxNetworking {\n /**\n * Get the public URL for an exposed port.\n *\n * @param port - The port number inside the sandbox\n * @returns The URL for the port, or null if the port is not exposed\n * or the sandbox is not running\n */\n getPortUrl(port: number): Promise<string | null>;\n}\n\n/** A file to write into the sandbox filesystem via {@link WorkspaceSandbox.writeFiles}. */\nexport interface SandboxFileInput {\n /** Destination path inside the sandbox */\n path: string;\n /** File contents */\n content: string | Buffer;\n /**\n * Optional POSIX permission mode for the written file (e.g. `0o600`).\n *\n * Must be an integer in the range `0o001`–`0o777` (permission bits only; no\n * setuid/setgid/sticky bits). A mode of `0` (no permissions) is rejected: it\n * is not usefully provisionable and cannot be represented by every provider's\n * upload transport. When omitted, the provider's default applies (Docker uses\n * `0644`). Providers that cannot honor an explicit mode reject it rather than\n * silently discarding it.\n */\n mode?: number;\n}\n\n/** Minimum permitted {@link SandboxFileInput.mode} value. */\nexport const MIN_SANDBOX_FILE_MODE = 0o001;\n/** Maximum permitted {@link SandboxFileInput.mode} value (permission bits only). */\nexport const MAX_SANDBOX_FILE_MODE = 0o777;\n\n/**\n * Validate an explicit {@link SandboxFileInput.mode} value.\n *\n * @throws {SandboxError} with code `INVALID_ARGUMENT` if the mode is not an\n * integer in the range `0o001`–`0o777`.\n */\nexport function validateSandboxFileMode(mode: number): void {\n if (!Number.isInteger(mode) || mode < MIN_SANDBOX_FILE_MODE || mode > MAX_SANDBOX_FILE_MODE) {\n throw new SandboxError(\n `Invalid file mode ${mode}: must be an integer between 0o001 (1) and 0o777 (${MAX_SANDBOX_FILE_MODE}).`,\n 'INVALID_ARGUMENT',\n { mode },\n );\n }\n}\n\n/**\n * Assert that no file in the list requests an explicit permission mode.\n *\n * Used by providers whose upload mechanism cannot honor a mode, so that an\n * explicit mode is rejected rather than silently discarded.\n *\n * @throws {SandboxUnsupportedFeatureError} if any file specifies a `mode`.\n */\nexport function assertModesUnsupported(files: SandboxFileInput[], provider: string): void {\n if (files.some(f => f.mode !== undefined)) {\n throw new SandboxUnsupportedFeatureError(\n `The ${provider} sandbox does not support per-file permission modes in writeFiles(). Omit 'mode' to use the provider default.`,\n { provider },\n );\n }\n}\n\n/** Options for {@link WorkspaceSandbox.writeFiles}. */\nexport interface WriteFilesOptions {\n /**\n * Abort signal to cancel the write.\n *\n * Observing the signal is provider-dependent. `DockerSandbox` terminates the\n * in-flight upload when the signal aborts; providers that do not observe the\n * signal run to completion. Providers that observe the signal reject an\n * already-aborted write before archive creation or upload begins.\n *\n * Cancellation rejects with a {@link SandboxAbortError} (code `ABORTED`).\n * Because upload and cancellation race, an upload that completes before the\n * abort is observed resolves normally. Cancellation does not roll back writes:\n * files transferred or extracted before the abort may remain in the sandbox,\n * so callers are responsible for any cleanup or sandbox disposal.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * Type guard: does this sandbox support the networking capability?\n *\n * @example\n * ```typescript\n * if (supportsNetworking(sandbox)) {\n * const url = await sandbox.networking.getPortUrl(4111);\n * }\n * ```\n */\nexport function supportsNetworking(\n sandbox: WorkspaceSandbox,\n): sandbox is WorkspaceSandbox & { networking: SandboxNetworking } {\n return typeof sandbox.networking?.getPortUrl === 'function';\n}\n\n// =============================================================================\n// Computer (Desktop) Capability\n// =============================================================================\n\n/** A screenshot of the sandbox's desktop display. */\nexport interface ComputerScreenshot {\n /** Raw image bytes */\n data: Uint8Array;\n /** Image media type (providers normalize to PNG) */\n mediaType: 'image/png';\n}\n\n/** Screen dimensions in pixels. */\nexport interface ComputerScreenSize {\n width: number;\n height: number;\n}\n\n/** A position on the sandbox's desktop display, in pixels from the top-left corner. */\nexport interface ComputerPosition {\n x: number;\n y: number;\n}\n\n/**\n * Optional computer-use (desktop) capability for sandboxes that run a GUI\n * desktop environment.\n *\n * Providers with a controllable display (Daytona Computer Use, E2B Desktop,\n * etc.) implement this to surface screenshot, mouse, and keyboard control\n * through the abstraction. When present on a statically configured workspace\n * sandbox, the workspace tools factory emits the\n * `mastra_workspace_computer_*` tools automatically. Resolver-backed sandboxes\n * do not register these tools because their capabilities are unavailable when\n * the tool list is constructed.\n *\n * Coordinates are in pixels from the top-left corner of the display.\n * Providers normalize their SDK semantics (key names, scroll units) onto\n * this surface and may expose richer native APIs via their own accessors.\n */\nexport interface SandboxComputer {\n /** Capture the current display as a PNG image. */\n screenshot(): Promise<ComputerScreenshot>;\n\n /** Left-click at the given coordinates. */\n leftClick(x: number, y: number): Promise<void>;\n\n /** Right-click at the given coordinates. */\n rightClick(x: number, y: number): Promise<void>;\n\n /** Double-click (left button) at the given coordinates. */\n doubleClick(x: number, y: number): Promise<void>;\n\n /** Move the mouse cursor to the given coordinates without clicking. */\n moveMouse(x: number, y: number): Promise<void>;\n\n /** Press the left button at `from`, drag to `to`, and release. */\n drag(from: ComputerPosition, to: ComputerPosition): Promise<void>;\n\n /**\n * Scroll the display.\n *\n * @param direction - Scroll direction\n * @param amount - Scroll amount in provider-normalized ticks (positive integer)\n */\n scroll(direction: 'up' | 'down', amount: number): Promise<void>;\n\n /** Type text into the focused element using the keyboard. */\n type(text: string): Promise<void>;\n\n /**\n * Press a key or key combination.\n *\n * A single string presses one key (e.g. `'Enter'`, `'Tab'`, `'a'`).\n * An array presses a chord/hotkey (e.g. `['ctrl', 's']`).\n */\n press(key: string | string[]): Promise<void>;\n\n /** Get the display dimensions. */\n getScreenSize(): Promise<ComputerScreenSize>;\n\n /** Get the current mouse cursor position. */\n getCursorPosition(): Promise<ComputerPosition>;\n\n /**\n * Get a URL for a live view of the desktop (e.g. noVNC), or null when\n * unavailable. Optional — not all providers expose a viewer.\n */\n streamUrl?(): Promise<string | null>;\n}\n\n/**\n * Type guard: does this sandbox support the computer-use (desktop) capability?\n *\n * @example\n * ```typescript\n * if (supportsComputer(sandbox)) {\n * const { data } = await sandbox.computer.screenshot();\n * }\n * ```\n */\nexport function supportsComputer(\n sandbox: WorkspaceSandbox,\n): sandbox is WorkspaceSandbox & { computer: SandboxComputer } {\n const computer = sandbox.computer;\n return (\n typeof computer?.screenshot === 'function' &&\n typeof computer.leftClick === 'function' &&\n typeof computer.rightClick === 'function' &&\n typeof computer.doubleClick === 'function' &&\n typeof computer.moveMouse === 'function' &&\n typeof computer.drag === 'function' &&\n typeof computer.scroll === 'function' &&\n typeof computer.type === 'function' &&\n typeof computer.press === 'function' &&\n typeof computer.getScreenSize === 'function' &&\n typeof computer.getCursorPosition === 'function'\n );\n}\n\n// =============================================================================\n// Sandbox Derivation\n// =============================================================================\n\n/**\n * Options for cloning a configured sandbox's configuration into an independent\n * sibling sandbox. See {@link WorkspaceSandbox.clone}.\n */\nexport interface SandboxCloneOptions {\n /** Unique identifier for the sandbox clone instance. */\n id?: string;\n /**\n * Reattach to an existing provider sandbox (by the provider's own id)\n * instead of provisioning a new one.\n */\n sandboxId?: string;\n /** Environment variables baked into the sandbox clone. */\n env?: Record<string, string>;\n /** Provider working directory for the sandbox clone. */\n workingDirectory?: string;\n /** Idle teardown window (minutes) for the sandbox clone. */\n idleTimeoutMinutes?: number;\n /**\n * Named checkpoint (the persisted artifact written by `snapshot()`) used to\n * seed the sandbox clone on boot and preserve its state across restarts.\n * Providers without checkpoint support may ignore this option.\n */\n checkpointName?: string;\n /**\n * Fallback checkpoint used to seed the sandbox when `checkpointName` has no\n * stored state yet (e.g. a repo-level warm base checkpoint for a brand-new\n * session). Boot-only: `snapshot()` keeps writing to `checkpointName` and\n * never overwrites the seed.\n * Providers without checkpoint support may ignore this option.\n */\n seedCheckpointName?: string;\n /** Opaque user subject attributed to provider requests for this clone. */\n actingUserId?: string;\n}\n\n// =============================================================================\n// Sandbox Interface\n// =============================================================================\n\n/**\n * Abstract sandbox interface for code and command execution.\n *\n * Providers implement this interface to provide execution capabilities.\n * Users instantiate providers and pass them to the Workspace constructor.\n *\n * Sandboxes provide isolated environments for running untrusted code.\n * They may have their own filesystem that's separate from the workspace FS.\n *\n * Lifecycle methods (from SandboxLifecycle interface) are all optional:\n * - start(): Begin operation (spin up instance)\n * - stop(): Pause operation (pause instance)\n * - destroy(): Clean up resources (terminate instance)\n * - isReady(): Check if ready for operations\n * - getInfo(): Get status and metadata\n */\nexport interface WorkspaceSandbox extends SandboxLifecycle<SandboxInfo> {\n /** Unique identifier for this sandbox instance */\n readonly id: string;\n\n /** Human-readable name (e.g., 'E2B Sandbox', 'Docker') */\n readonly name: string;\n\n /** Provider type identifier */\n readonly provider: string;\n\n /**\n * The provider's physical, reattachable sandbox id, resolved after the VM is\n * started (connected or created). Distinct from `id`, which is the logical\n * identity: persist this to reattach deterministically to the same VM on a\n * later resume. Undefined until the sandbox has been started, or for\n * providers with no separate physical id (e.g. local process sandboxes).\n */\n readonly sandboxId?: string;\n\n /**\n * Capture the sandbox's current state as a checkpoint when the provider\n * supports it. Terminology: *snapshot* is the act of capturing; the named,\n * persisted artifact it writes is a *checkpoint*\n * (see `SandboxCloneOptions.checkpointName`).\n * Providers without checkpoint support resolve without performing work.\n */\n snapshot(): Promise<void>;\n\n /**\n * Whether `snapshot()` persists real checkpoints that can later seed a\n * sandbox (via `SandboxCloneOptions.checkpointName`). Providers whose\n * `snapshot()` is a no-op leave this unset/false so checkpoint-dependent\n * features (base checkpoints, boot-from-checkpoint, revival from\n * checkpoint) know to skip them.\n */\n readonly supportsCheckpoints?: boolean;\n\n /**\n * Get instructions describing how this sandbox works.\n * Used in tool descriptions to help agents understand execution context.\n *\n * @param opts - Optional options including request context for per-request customisation\n * @returns A string describing how to use this sandbox\n */\n getInstructions?(opts?: { requestContext?: RequestContext }): string;\n\n // ---------------------------------------------------------------------------\n // Cloning (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Construct an independent sibling sandbox that inherits this sandbox's\n * configuration (credentials, provider settings, defaults) with\n * per-instance overrides.\n *\n * Performs no I/O — the sandbox clone provisions (or reattaches, when\n * `sandboxId` is set) on its own `start()`. Implement this when one\n * configured sandbox should act as the template for a fleet of independent\n * sandboxes (e.g. one per project).\n *\n * Optional — consumers that need fleets (like the MastraCode web factory)\n * only support sandboxes that implement it.\n */\n clone?(options?: SandboxCloneOptions): WorkspaceSandbox;\n\n // ---------------------------------------------------------------------------\n // Command Execution\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a shell command and wait for it to complete.\n * Optional - if not implemented, the workspace_execute_command tool won't be available.\n *\n * @example\n * ```typescript\n * await sandbox.executeCommand('npm install');\n *\n * // With options\n * await sandbox.executeCommand('npm install', [], { timeout: 60000 });\n *\n * // With args array (each arg is shell-quoted automatically)\n * await sandbox.executeCommand('npm', ['install'], { timeout: 60000 });\n * ```\n *\n * @throws {SandboxExecutionError} if command fails to start\n * @throws {SandboxTimeoutError} if command times out\n */\n executeCommand?(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult>;\n\n /**\n * Update the sandbox's runtime environment overlay.\n *\n * The updater receives a copy of the current overlay and returns the new\n * one. Values are made visible to subsequent commands and processes routed\n * through the sandbox's process manager; this is not VM-level environment.\n * Optional - available on sandboxes that support runtime env updates.\n *\n * @example\n * ```typescript\n * sandbox.setEnv(env => ({ ...env, GH_TOKEN: token }));\n * ```\n */\n setEnv?(update: (env: Record<string, string | undefined>) => Record<string, string | undefined>): void;\n\n /**\n * Attach or replace the sandbox's start hook after construction.\n *\n * The updater receives the currently installed hook and returns the one to\n * install, so callers compose rather than clobber. The hook runs inside every\n * start, and a thrown error fails that start. Only starts beginning after the\n * call see the new hook.\n * Optional - available on sandboxes that support runtime hook updates.\n *\n * @example\n * ```typescript\n * sandbox.setOnStart(prev => async args => {\n * await runSetup(args);\n * await prev?.(args);\n * });\n * ```\n */\n setOnStart?(update: (previous: SandboxStartHook | undefined) => SandboxStartHook): void;\n\n // ---------------------------------------------------------------------------\n // Networking (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Networking capability for sandboxes that can expose ports publicly.\n * Optional - only available on providers that support public port exposure.\n * Enables preview URLs and sandbox deploys.\n *\n * @example\n * ```typescript\n * const url = await sandbox.networking?.getPortUrl(4111);\n * ```\n */\n readonly networking?: SandboxNetworking;\n\n // ---------------------------------------------------------------------------\n // Computer Use (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Computer-use (desktop) capability for sandboxes with a GUI desktop.\n * Optional - only available on providers with a controllable display.\n * When present, workspace computer tools (screenshot/click/type/…) are\n * emitted automatically.\n *\n * @example\n * ```typescript\n * const { data } = await sandbox.computer?.screenshot();\n * ```\n */\n readonly computer?: SandboxComputer;\n\n // ---------------------------------------------------------------------------\n // File Upload (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Bulk-write files into the sandbox's own filesystem.\n * Optional fast path - providers with a native file-upload API implement this.\n * Callers should fall back to `executeCommand` when unavailable.\n *\n * @example\n * ```typescript\n * await sandbox.writeFiles?.([{ path: '/app/index.mjs', content: bundle }]);\n * ```\n *\n * Pass `options.abortSignal` to cancel the write. See {@link WriteFilesOptions}\n * for the cancellation contract (provider-dependent observance, the\n * completion-versus-cancellation race, and the partial-write boundary).\n */\n writeFiles?(files: SandboxFileInput[], options?: WriteFilesOptions): Promise<void>;\n\n // ---------------------------------------------------------------------------\n // Native filesystem (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Direct access to the sandbox's own disk through the provider's file API.\n * Optional fast path - providers with a native file API implement this so\n * file operations don't need a shell command each. Callers should fall back\n * to `executeCommand` when unavailable.\n *\n * Paths are absolute paths inside the sandbox. The provider owns containment:\n * no workspace-root or symlink confinement is implied, so a caller that needs\n * it must check paths itself.\n *\n * @example\n * ```typescript\n * const content = sandbox.filesystem\n * ? await sandbox.filesystem.readFile('/workspace/app/package.json', { encoding: 'utf-8' })\n * : (await sandbox.executeCommand?.('cat', ['/workspace/app/package.json']))?.stdout;\n * ```\n */\n readonly filesystem?: WorkspaceFilesystem;\n\n // ---------------------------------------------------------------------------\n // Process Management (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Process manager.\n * Optional - if not implemented, process management tools won't be available.\n *\n * Provides methods to spawn long-running processes, list them, and interact\n * with them via their {@link ProcessHandle} (kill, sendStdin, wait, read output).\n *\n * @example\n * ```typescript\n * const handle = await sandbox.processes.spawn('node server.js');\n * console.log(handle.pid);\n *\n * const procs = await sandbox.processes.list();\n * const proc = await sandbox.processes.get(handle.pid);\n * // Read without releasing an exited process, so other readers still find it\n * const peek = await sandbox.processes.get(handle.pid, { release: false });\n * await proc?.sendStdin('hello\\n');\n * await proc?.kill();\n * ```\n */\n readonly processes?: SandboxProcessManager;\n\n // ---------------------------------------------------------------------------\n // Mounting Support (Optional)\n // ---------------------------------------------------------------------------\n\n /**\n * Mount manager for tracking and processing filesystem mounts.\n * Only available if the sandbox implements mount().\n *\n * @example\n * ```typescript\n * // Add pending mounts\n * sandbox.mounts?.add({ '/data': s3fs });\n *\n * // Check mount entries\n * const entries = sandbox.mounts?.entries;\n * ```\n */\n readonly mounts?: MountManager;\n\n /**\n * Mount a filesystem at a path in the sandbox.\n * Uses FUSE tools (s3fs, gcsfuse) to mount cloud storage.\n *\n * @param filesystem - The filesystem to mount\n * @param mountPath - Path in the sandbox where filesystem should be mounted\n * @returns Mount result with success status and mount path\n * @throws {MountError} if mount fails\n * @throws {MountNotSupportedError} if sandbox doesn't support mounting\n * @throws {FilesystemNotMountableError} if filesystem cannot be mounted\n */\n mount?(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult>;\n\n /**\n * Unmount a filesystem from a path in the sandbox.\n *\n * @param mountPath - Path to unmount\n */\n unmount?(mountPath: string): Promise<void>;\n}\n","/**\n * Process Handle (Base Class)\n *\n * Abstract base class for process handles.\n * Manages stdout/stderr callback dispatch and provides lazy\n * reader/writer stream getters — subclasses only implement\n * the platform-specific primitives.\n */\n\nimport { Readable, Writable } from 'node:stream';\n\nimport type { CommandResult } from '../types';\nimport type { SpawnProcessOptions } from './types';\n\nexport const DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES = 1024 * 1024;\n/**\n * Most output one stream can retain, even with `maxRetainedBytes: Infinity`.\n * Retained chunks are joined into one string, and V8 throws `RangeError: Invalid string length`\n * past ~512 Mi UTF-16 code units. A string never has more code units than UTF-8 bytes, so\n * 256 MiB keeps the join well inside that limit.\n */\nexport const MAX_RETAINED_PROCESS_OUTPUT_BYTES = 256 * 1024 * 1024;\n\n/**\n * A process asked to keep all of its output (`maxRetainedBytes` above\n * {@link MAX_RETAINED_PROCESS_OUTPUT_BYTES}, e.g. Infinity) produced more than can be held.\n * The process is killed and `wait()` rejects with this error rather than returning partial output.\n */\nexport class ProcessOutputLimitError extends Error {\n readonly name = 'ProcessOutputLimitError';\n\n constructor(\n readonly stream: 'stdout' | 'stderr',\n readonly limitBytes: number,\n ) {\n super(\n `Process ${stream} exceeded ${limitBytes} bytes, the most output that can be retained in full; the process was killed. ` +\n 'Redirect large output to a file or set a finite maxRetainedBytes to keep only the newest output.',\n );\n }\n}\nconst RETAINED_OUTPUT_COMPACT_CHUNK_THRESHOLD = 128;\n\n/** @internal */\nexport function validateMaxRetainedProcessOutputBytes(maxRetainedBytes: number): number {\n if (maxRetainedBytes === Infinity) return maxRetainedBytes;\n if (!Number.isFinite(maxRetainedBytes) || maxRetainedBytes < 0 || !Number.isInteger(maxRetainedBytes)) {\n throw new RangeError('maxRetainedBytes must be a non-negative integer or Infinity');\n }\n return maxRetainedBytes;\n}\n\nfunction advanceStartByUtf8Bytes(\n value: string,\n start: number,\n minimumBytesToDrop: number,\n): { start: number; droppedBytes: number } {\n let nextStart = start;\n let droppedBytes = 0;\n\n while (nextStart < value.length && droppedBytes < minimumBytesToDrop) {\n const codePoint = value.codePointAt(nextStart)!;\n\n if (codePoint < 0x80) droppedBytes += 1;\n else if (codePoint < 0x800) droppedBytes += 2;\n else if (codePoint < 0x10000) droppedBytes += 3;\n else droppedBytes += 4;\n\n nextStart += codePoint > 0xffff ? 2 : 1;\n }\n\n return { start: nextStart, droppedBytes };\n}\n\ninterface RetainedOutputChunk {\n data: string;\n start: number;\n bytes: number;\n dataBytes: number;\n}\n\nexport class RetainedOutputBuffer {\n private chunks: RetainedOutputChunk[] = [];\n private bytes = 0;\n private droppedBytes = 0;\n private cachedValue: string | undefined;\n private overflowedLimit = false;\n\n /**\n * @param maxBytes keep the newest `maxBytes`; above `hardLimitBytes` (e.g. Infinity) means keep everything\n * @param hardLimitBytes overridable only so tests can reach the limit without allocating 256 MiB\n */\n constructor(\n private readonly maxBytes: number,\n readonly hardLimitBytes: number = MAX_RETAINED_PROCESS_OUTPUT_BYTES,\n ) {}\n\n /**\n * True once a keep-everything buffer received more than `hardLimitBytes`.\n * It then stops retaining: what it holds is incomplete and further data is only counted as dropped.\n */\n get overflowed(): boolean {\n return this.overflowedLimit;\n }\n\n append(data: string): void {\n const dataBytes = Buffer.byteLength(data);\n if (dataBytes === 0) return;\n if (this.overflowedLimit) {\n this.droppedBytes += dataBytes;\n return;\n }\n if (this.maxBytes > this.hardLimitBytes && this.bytes + dataBytes > this.hardLimitBytes) {\n this.overflowedLimit = true;\n this.droppedBytes += dataBytes;\n return;\n }\n if (this.maxBytes === 0) {\n this.droppedBytes += dataBytes;\n return;\n }\n\n this.chunks.push({ data, start: 0, bytes: dataBytes, dataBytes });\n this.bytes += dataBytes;\n this.cachedValue = undefined;\n\n this.trim();\n this.compactIfNeeded();\n }\n\n toString(): string {\n this.cachedValue ??= this.chunks.map(chunk => chunk.data.slice(chunk.start)).join('');\n return this.cachedValue;\n }\n\n get truncated(): boolean {\n return this.droppedBytes > 0;\n }\n\n get dropped(): number {\n return this.droppedBytes;\n }\n\n private trim(): void {\n if (this.maxBytes === Infinity) return;\n\n while (this.bytes > this.maxBytes && this.chunks.length > 0) {\n const overflowBytes = this.bytes - this.maxBytes;\n const firstChunk = this.chunks[0]!;\n\n if (firstChunk.bytes <= overflowBytes) {\n this.chunks.shift();\n this.bytes -= firstChunk.bytes;\n this.droppedBytes += firstChunk.bytes;\n continue;\n }\n\n const { start, droppedBytes } = advanceStartByUtf8Bytes(firstChunk.data, firstChunk.start, overflowBytes);\n firstChunk.start = start;\n firstChunk.bytes -= droppedBytes;\n this.bytes -= droppedBytes;\n this.droppedBytes += droppedBytes;\n\n if (firstChunk.bytes === 0) {\n this.chunks.shift();\n continue;\n }\n\n if (firstChunk.dataBytes > this.maxBytes) {\n // V8 sliced strings retain their parent, so detach a bounded suffix from an oversized source chunk.\n firstChunk.data = Buffer.from(firstChunk.data.slice(firstChunk.start), 'utf8').toString('utf8');\n firstChunk.start = 0;\n firstChunk.dataBytes = firstChunk.bytes;\n }\n }\n }\n\n private compactIfNeeded(): void {\n if (this.chunks.length <= RETAINED_OUTPUT_COMPACT_CHUNK_THRESHOLD) return;\n const data = this.toString();\n this.bytes = Buffer.byteLength(data);\n this.chunks = this.bytes === 0 ? [] : [{ data, start: 0, bytes: this.bytes, dataBytes: this.bytes }];\n this.cachedValue = data;\n }\n}\n\n/**\n * Thrown by {@link ProcessHandle.closeStdin} when the sandbox provider has no\n * way to close a running process's stdin.\n *\n * `handle.writer.end()` treats this error as a successful finish, so piping to\n * a process stays safe on providers without stdin close support.\n */\nexport class UnsupportedStdinCloseError extends Error {\n readonly name = 'UnsupportedStdinCloseError';\n}\n\n/**\n * Handle to a spawned process.\n *\n * Subclasses implement the platform-specific primitives (kill, sendStdin,\n * wait). The base class handles bounded stdout/stderr accumulation, callback\n * dispatch via `emitStdout`/`emitStderr`, lazy `reader`/`writer` stream\n * getters, and optional streaming callbacks on `wait()`.\n *\n * **For consumers:**\n * - `handle.stdout` — poll retained output\n * - `handle.wait()` — wait for exit, optionally with streaming callbacks\n * - `handle.reader` / `handle.writer` — Node.js stream interop (LSP, JSON-RPC, pipes)\n * - `onStdout`/`onStderr` callbacks in {@link SpawnProcessOptions} — stream at spawn time\n *\n * **For implementors:** Call `emitStdout(data)` / `emitStderr(data)` from\n * your transport callback (ChildProcess events, WebSocket messages, etc.)\n * to dispatch data. Pass `options` through to `super(options)` to wire\n * user callbacks automatically.\n *\n * @example\n * ```typescript\n * // Poll model\n * const handle = await sandbox.processes.spawn('node server.js');\n * console.log(handle.stdout);\n *\n * // Stream model — callbacks at spawn time\n * const handle = await sandbox.processes.spawn('npm run dev', {\n * onStdout: (data) => console.log(data),\n * });\n *\n * // Stream model — callbacks during wait\n * const result = await handle.wait({\n * onStdout: (data) => process.stdout.write(data),\n * onStderr: (data) => process.stderr.write(data),\n * });\n *\n * // Stream model — pipe to LSP, JSON-RPC, etc.\n * const handle = await sandbox.processes.spawn('typescript-language-server --stdio');\n * const connection = createMessageConnection(\n * new StreamMessageReader(handle.reader),\n * new StreamMessageWriter(handle.writer),\n * );\n * ```\n */\nexport abstract class ProcessHandle {\n /** Process ID */\n abstract readonly pid: string;\n /** Exit code, undefined while the process is still running */\n abstract readonly exitCode: number | undefined;\n /** The command that was spawned (set by the process manager) */\n command?: string;\n /** Kill the running process (SIGKILL). Returns true if killed, false if not found. */\n abstract kill(): Promise<boolean>;\n /** Send data to the process's stdin */\n abstract sendStdin(data: string): Promise<void>;\n\n /**\n * Close the process's stdin, signaling EOF.\n *\n * Providers that cannot close stdin throw {@link UnsupportedStdinCloseError}.\n * The default implementation is the unsupported case, so providers only\n * override this when their transport exposes a stdin close primitive.\n */\n async closeStdin(): Promise<void> {\n throw new UnsupportedStdinCloseError(`${this.constructor.name} does not support closing stdin`);\n }\n\n /**\n * Wait for the process to finish and return the result.\n *\n * Optionally pass `onStdout`/`onStderr` callbacks to stream output chunks\n * while waiting. The callbacks are automatically removed when `wait()`\n * resolves, so there's no cleanup needed by the caller.\n *\n * Optionally pass an `abortSignal` to couple the blocking wait to a caller\n * lifetime: on abort the process is killed (mirroring the spawn-time\n * `abortSignal` convention in {@link CommandOptions}), which lets the wait\n * settle with the killed process's result instead of blocking forever.\n *\n * Subclasses implement `wait()` with platform-specific logic; the base\n * constructor wraps it to handle the optional streaming callbacks.\n */\n async wait(_options?: {\n onStdout?: (data: string) => void;\n onStderr?: (data: string) => void;\n abortSignal?: AbortSignal;\n }): Promise<CommandResult> {\n throw new Error(`${this.constructor.name} must implement wait()`);\n }\n\n private _stdout: RetainedOutputBuffer;\n private _stderr: RetainedOutputBuffer;\n private _outputLimitError?: ProcessOutputLimitError;\n private _killedByAbort = false;\n private _abortKill?: Promise<void>;\n private _stdoutListeners = new Set<(data: string) => void>();\n private _stderrListeners = new Set<(data: string) => void>();\n private _reader?: Readable;\n private _writer?: Writable;\n\n constructor(\n options?: Pick<SpawnProcessOptions, 'maxRetainedBytes' | 'onStdout' | 'onStderr'> & {\n /** @internal Lets tests reach the retention limit without producing 256 MiB of output. */\n retainedOutputHardLimitBytes?: number;\n },\n ) {\n const maxRetainedBytes = validateMaxRetainedProcessOutputBytes(\n options?.maxRetainedBytes ?? DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES,\n );\n this._stdout = new RetainedOutputBuffer(maxRetainedBytes, options?.retainedOutputHardLimitBytes);\n this._stderr = new RetainedOutputBuffer(maxRetainedBytes, options?.retainedOutputHardLimitBytes);\n\n // Spawn-time callbacks are permanent listeners\n if (options?.onStdout) this._stdoutListeners.add(options.onStdout);\n if (options?.onStderr) this._stderrListeners.add(options.onStderr);\n\n // Capture subclass wait() (via prototype chain) before shadowing\n // with a wrapper that handles optional streaming callbacks.\n const implWait = this.wait.bind(this);\n\n this.wait = async (waitOptions?: {\n onStdout?: (data: string) => void;\n onStderr?: (data: string) => void;\n abortSignal?: AbortSignal;\n }) => {\n if (waitOptions?.onStdout) this._stdoutListeners.add(waitOptions.onStdout);\n if (waitOptions?.onStderr) this._stderrListeners.add(waitOptions.onStderr);\n // Abort kills the process (same convention as spawn-time `abortSignal`\n // in the process manager) so the wait settles via the normal exit path\n // instead of blocking past the caller's lifetime.\n const abortSignal = waitOptions?.abortSignal;\n const onAbort = () => {\n void this.killForAbort().catch(() => {});\n };\n if (abortSignal?.aborted) onAbort();\n else abortSignal?.addEventListener('abort', onAbort, { once: true });\n try {\n let result: CommandResult;\n try {\n result = await implWait();\n } catch (error) {\n // Killing for the output limit can make the provider's wait reject; report why.\n throw this._outputLimitError ?? error;\n }\n if (this._outputLimitError) throw this._outputLimitError;\n return {\n ...result,\n stdoutTruncated: this.stdoutTruncated,\n stderrTruncated: this.stderrTruncated,\n stdoutDroppedBytes: this.stdoutDroppedBytes,\n stderrDroppedBytes: this.stderrDroppedBytes,\n };\n } finally {\n abortSignal?.removeEventListener('abort', onAbort);\n if (waitOptions?.onStdout) this._stdoutListeners.delete(waitOptions.onStdout);\n if (waitOptions?.onStderr) this._stderrListeners.delete(waitOptions.onStderr);\n }\n };\n }\n\n /**\n * @internal Whether the process was killed because an `abortSignal` passed to spawn or\n * `wait()` fired while it was still running. A direct `kill()` does not set it.\n */\n get killedByAbort(): boolean {\n return this._killedByAbort;\n }\n\n /** @internal Kill the process for a fired abort signal and record it in {@link killedByAbort}. */\n async killForAbort(): Promise<void> {\n if (this.exitCode !== undefined) return;\n // Spawn and wait() can both listen to the same signal; share one kill so a\n // second kill() reporting \"already gone\" can't clear the first one's flag.\n return (this._abortKill ??= this.runAbortKill());\n }\n\n private async runAbortKill(): Promise<void> {\n this._killedByAbort = true;\n try {\n // `false` means the process exited on its own before the kill landed.\n if (!(await this.kill())) {\n this._killedByAbort = false;\n this._abortKill = undefined;\n }\n } catch (error) {\n this._killedByAbort = false;\n this._abortKill = undefined;\n throw error;\n }\n }\n\n /** Retained stdout so far */\n get stdout(): string {\n return this._stdout.toString();\n }\n\n /** Retained stderr so far */\n get stderr(): string {\n return this._stderr.toString();\n }\n\n /** Whether stdout has dropped older output due to the retention limit */\n get stdoutTruncated(): boolean {\n return this._stdout.truncated;\n }\n\n /** Whether stderr has dropped older output due to the retention limit */\n get stderrTruncated(): boolean {\n return this._stderr.truncated;\n }\n\n /** Number of stdout bytes dropped due to the retention limit */\n get stdoutDroppedBytes(): number {\n return this._stdout.dropped;\n }\n\n /** Number of stderr bytes dropped due to the retention limit */\n get stderrDroppedBytes(): number {\n return this._stderr.dropped;\n }\n\n /**\n * Emit stdout data — accumulates, dispatches to user callback, and pushes to reader stream.\n * @internal Called by subclasses and process managers to dispatch transport data.\n */\n emitStdout(data: string): void {\n this._stdout.append(data);\n if (this._stdout.overflowed) this.failForOutputLimit('stdout', this._stdout.hardLimitBytes);\n for (const listener of this._stdoutListeners) listener(data);\n this._reader?.push(data);\n }\n\n /**\n * Emit stderr data — accumulates and dispatches to user callback.\n * @internal Called by subclasses and process managers to dispatch transport data.\n */\n emitStderr(data: string): void {\n this._stderr.append(data);\n if (this._stderr.overflowed) this.failForOutputLimit('stderr', this._stderr.hardLimitBytes);\n for (const listener of this._stderrListeners) listener(data);\n }\n\n private failForOutputLimit(stream: 'stdout' | 'stderr', limitBytes: number): void {\n if (this._outputLimitError) return;\n this._outputLimitError = new ProcessOutputLimitError(stream, limitBytes);\n // Called from the transport's data handler: nothing can catch a throw or rejection here.\n void this.kill().catch(() => {});\n }\n\n /** Readable stream of stdout (for use with StreamMessageReader, pipes, etc.) */\n get reader(): Readable {\n if (!this._reader) {\n this._reader = new Readable({ read() {} });\n void this.wait().then(\n () => this._reader!.push(null),\n () => this._reader!.push(null),\n );\n }\n return this._reader;\n }\n\n /** Writable stream to stdin (for use with StreamMessageWriter, pipes, etc.) */\n get writer(): Writable {\n if (!this._writer) {\n this._writer = new Writable({\n write: (chunk, _encoding, cb) => {\n this.sendStdin(chunk.toString()).then(() => cb(), cb);\n },\n final: cb => {\n this.closeStdin().then(\n () => cb(),\n (err: unknown) => cb(err instanceof UnsupportedStdinCloseError ? null : (err as Error)),\n );\n },\n });\n }\n return this._writer;\n }\n}\n","/**\n * MastraSandbox Base Class\n *\n * Abstract base class for sandbox providers that want automatic logger integration.\n * Extends MastraBase to receive the Mastra logger when registered with a Mastra instance.\n *\n * MountManager is automatically created if the subclass implements `mount()`.\n * Use `declare readonly mounts: MountManager` to get non-optional typing.\n *\n * ## Lifecycle Management\n *\n * The base class provides race-condition-safe lifecycle wrappers:\n * - `_start()` - Handles concurrent calls, status management, and mount processing\n * - `_stop()` - Handles concurrent calls and status management\n * - `_destroy()` - Handles concurrent calls and status management\n *\n * Subclasses override the plain `start()`, `stop()`, and `destroy()` methods\n * to provide their implementation. Callers use the `_`-prefixed wrappers\n * (or `callLifecycle()`) which add status tracking and race-condition safety.\n *\n * External providers can extend this class to get logger support, or implement\n * the WorkspaceSandbox interface directly if they don't need logging.\n */\n\nimport { MastraBase } from '../../base';\nimport type { IMastraLogger } from '../../logger';\nimport { RegisteredLogger } from '../../logger/constants';\nimport type { WorkspaceFilesystem } from '../filesystem/filesystem';\nimport type { MountResult } from '../filesystem/mount';\nimport type { ProviderStatus, SandboxStartOutcome, SandboxStartResult } from '../lifecycle';\nimport { SandboxNotReadyError } from './errors';\nimport { MountManager } from './mount-manager';\nimport type { SandboxProcessManager } from './process-manager';\nimport { DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES } from './process-manager/process-handle';\nimport type {\n SandboxComputer,\n SandboxFileInput,\n SandboxNetworking,\n WorkspaceSandbox,\n WriteFilesOptions,\n} from './sandbox';\nimport type { CommandResult, ExecuteCommandOptions, SandboxInfo } from './types';\nimport { shellQuote } from './utils';\n\n/**\n * Lifecycle hook that fires during sandbox state transitions.\n * Receives the sandbox instance so users can call `executeCommand`, read files, etc.\n */\nexport type SandboxLifecycleHook = (args: { sandbox: WorkspaceSandbox }) => void | Promise<void>;\n\n/**\n * Start hook: a {@link SandboxLifecycleHook} that additionally receives the\n * provider's {@link SandboxStartResult} `outcome`: `'created'` = this start\n * provisioned a fresh VM, `'connected'` = reconnected/resumed an existing\n * one, `undefined` = the provider doesn't report (not yet migrated).\n */\nexport type SandboxStartHook = (args: {\n sandbox: WorkspaceSandbox;\n outcome?: SandboxStartOutcome;\n}) => void | Promise<void>;\n\n/** Options forwarded to a provider's sandbox start implementation. */\nexport interface SandboxStartOptions {\n abortSignal?: AbortSignal;\n}\n\n/**\n * Options for the MastraSandbox base class constructor.\n * Providers extend this to add their own options while inheriting lifecycle hooks.\n */\nexport interface MastraSandboxOptions {\n /**\n * Called after the sandbox reaches 'running' status, before pending mounts\n * are processed. Fires on EVERY start regardless of trigger (explicit,\n * `ensureRunning()` from a lazy command, a revival after the VM was\n * replaced), which makes it the seam for once-per-VM setup: branch on\n * `outcome` and probe/run whatever the environment needs.\n *\n * A thrown error is FATAL: `start()` rejects and the sandbox is marked\n * `error`, and the next start retries the hook. (`onStop`/`onDestroy` stay\n * non-fatal, since teardown proceeds best-effort.)\n */\n onStart?: SandboxStartHook;\n /** Called before the sandbox stops */\n onStop?: SandboxLifecycleHook;\n /** Called before the sandbox is destroyed */\n onDestroy?: SandboxLifecycleHook;\n\n /**\n * Initial values for the sandbox's runtime environment overlay.\n *\n * These values are made visible to every command and spawned process\n * routed through the sandbox's process manager (which also backs the\n * built-in `executeCommand`), merged per spawn. This is an overlay, not\n * VM-level environment — providers may additionally consume their own\n * env options for creation-time semantics, and providers with custom\n * execution transports that bypass the process manager must consume the\n * overlay themselves. Update at runtime with `setEnv`.\n */\n env?: Record<string, string | undefined>;\n\n /**\n * Default directory for command execution and process spawns when a\n * per-command `cwd` is not provided. A per-command `cwd` always wins.\n *\n * The value is passed to the provider as-is — absolute paths are\n * recommended; `~`-prefixed paths work only where the provider documents\n * expansion. The sandbox does not create the directory. Providers without\n * the concept in their runtime fall back to their prior default.\n */\n workingDirectory?: string;\n\n /**\n * Process manager for this sandbox.\n *\n * When provided, the base class automatically:\n * 1. Sets the sandbox back-reference on the process manager\n * 2. Exposes it via `this.processes`\n * 3. Creates a default `executeCommand` implementation (spawn + wait)\n *\n * @example\n * ```typescript\n * class MySandbox extends MastraSandbox {\n * constructor() {\n * super({\n * name: 'MySandbox',\n * processes: new MyProcessManager({ env: myEnv }),\n * });\n * }\n * }\n * ```\n */\n processes?: SandboxProcessManager;\n}\n\n/**\n * Abstract base class for sandbox providers with logger support.\n *\n * Providers that extend this class automatically receive the Mastra logger\n * when the sandbox is used with a Mastra instance. MountManager is also\n * automatically created if the subclass implements `mount()`.\n *\n * @example\n * ```typescript\n * class MyCustomSandbox extends MastraSandbox {\n * declare readonly mounts: MountManager; // Non-optional type\n * readonly id = 'my-sandbox';\n * readonly name = 'MyCustomSandbox';\n * readonly provider = 'custom';\n * status: ProviderStatus = 'pending';\n *\n * constructor() {\n * super({\n * name: 'MyCustomSandbox',\n * processes: new MyProcessManager({ env: myEnv }),\n * });\n * }\n *\n * async start(): Promise<void> { /* startup logic *\\/ }\n * async mount(filesystem, mountPath) { ... }\n * async unmount(mountPath) { ... }\n * }\n * ```\n */\nexport abstract class MastraSandbox<THandle = unknown> extends MastraBase implements WorkspaceSandbox {\n /** Unique identifier for this sandbox instance */\n abstract readonly id: string;\n\n /** Human-readable name (e.g., 'E2B Sandbox', 'Docker') */\n abstract readonly name: string;\n\n /** Provider type identifier */\n abstract readonly provider: string;\n\n /** Current status of the sandbox */\n abstract status: ProviderStatus;\n\n // ---------------------------------------------------------------------------\n // Optional WorkspaceSandbox members\n //\n // Re-declared here so that variables typed as `MastraSandbox` (not just\n // `WorkspaceSandbox`) can see them. TypeScript's `implements` is a\n // constraint check, not a type merge — optional interface members are\n // invisible on the class type unless explicitly listed.\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a shell command and wait for completion.\n *\n * Method syntax (not property syntax) is intentional — it prevents\n * `useDefineForClassFields` from emitting `this.executeCommand = undefined`\n * which would shadow prototype methods defined by subclasses.\n */\n executeCommand?(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult>;\n\n /** Default timeout for foreground commands; background spawns are unaffected. */\n protected defaultCommandTimeout?: number;\n\n /** Optional networking capability - implement to expose public port URLs */\n readonly networking?: SandboxNetworking;\n\n /** Optional computer-use (desktop) capability - implement to enable workspace computer tools */\n readonly computer?: SandboxComputer;\n\n /**\n * Optional bulk file upload into the sandbox's own filesystem.\n *\n * Method syntax (not property syntax) is intentional — it prevents\n * `useDefineForClassFields` from emitting `this.writeFiles = undefined`\n * which would shadow prototype methods defined by subclasses.\n */\n writeFiles?(files: SandboxFileInput[], options?: WriteFilesOptions): Promise<void>;\n\n /** Process manager */\n readonly processes?: SandboxProcessManager;\n\n /** Mount manager - automatically created if subclass implements mount() */\n readonly mounts?: MountManager;\n\n /** Optional mount method - implement to enable mounting support */\n mount?(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult>;\n\n /** Optional unmount method */\n unmount?(mountPath: string): Promise<void>;\n\n /** Get instructions describing how this sandbox works */\n getInstructions?(): string;\n\n /** Get sandbox status and metadata */\n getInfo?(): SandboxInfo | Promise<SandboxInfo>;\n\n /**\n * Persist the sandbox's current state when supported.\n *\n * The default implementation is a no-op for providers without snapshot support.\n */\n async snapshot(): Promise<void> {}\n\n /**\n * Whether `snapshot()` persists real checkpoints. Providers overriding\n * `snapshot()` with a real implementation should also override this to true.\n */\n readonly supportsCheckpoints: boolean = false;\n\n // ---------------------------------------------------------------------------\n // Lifecycle Promise Tracking (prevents race conditions)\n // ---------------------------------------------------------------------------\n\n /** Promise for _start() to prevent race conditions from concurrent calls */\n protected _startPromise?: Promise<SandboxStartResult | void>;\n\n /** The subclass's `start()`, captured before the constructor shadows it. */\n private readonly _implStart: (options?: SandboxStartOptions) => void | Promise<SandboxStartResult | void>;\n\n /** Whether acquisition runs through {@link find}/{@link connect}/{@link create}. */\n private readonly _useAcquisitionPrimitives: boolean;\n\n /** Promise for _stop() to prevent race conditions from concurrent calls */\n protected _stopPromise?: Promise<void>;\n\n /** Promise for _destroy() to prevent race conditions from concurrent calls */\n protected _destroyPromise?: Promise<void>;\n\n /** Lifecycle callbacks */\n private _onStart?: SandboxStartHook;\n private readonly _onStop?: SandboxLifecycleHook;\n private readonly _onDestroy?: SandboxLifecycleHook;\n\n /**\n * Runtime environment overlay, merged into every process spawn.\n *\n * JS-private (`#`) rather than TS `private` so subclasses that declare\n * their own `env` member (several providers do) can never collide with it.\n */\n #env: Record<string, string | undefined>;\n\n /**\n * Effective default working directory, exposed via the\n * {@link workingDirectory} getter. Protected so providers that compute or\n * probe their effective value (e.g. a default like `/workspace`, or a\n * runtime probe) can write it back with {@link setWorkingDirectory} and\n * keep the getter truthful.\n */\n protected _workingDirectory?: string;\n\n constructor(options: { name: string } & MastraSandboxOptions) {\n super({ name: options.name, component: RegisteredLogger.WORKSPACE });\n\n this._onStart = options.onStart;\n this._onStop = options.onStop;\n this._onDestroy = options.onDestroy;\n this.#env = { ...options.env };\n this._workingDirectory = options.workingDirectory;\n\n // Shadow start() with the lifecycle wrapper (same pattern as\n // SandboxProcessManager) so DIRECT start() calls get the same coalescing,\n // status handling, and onStart hook as `_start()`/`ensureRunning()`.\n const hasStartOverride = this.start !== MastraSandbox.prototype.start;\n this._implStart = this.start.bind(this);\n this.start = options => this._start(options);\n // Rung selection: a subclass `start()` override wins; otherwise the\n // primitives drive acquisition when `create()` is implemented. Anything\n // declared as a class field is invisible here and lands on the base\n // `start()`, which throws.\n this._useAcquisitionPrimitives = !hasStartOverride && typeof this.create === 'function';\n // A handle nobody adopts would still report `outcome: 'connected'`, so the\n // sandbox would look reconnected while running against nothing.\n if (this._useAcquisitionPrimitives && typeof this.find === 'function' && typeof this.connect !== 'function') {\n throw new Error(`${this.constructor.name}: find() requires connect() to adopt the handle it returns.`);\n }\n\n // Automatically create MountManager if subclass implements mount()\n if (this.mount) {\n this.mounts = new MountManager({\n mount: this.mount.bind(this),\n logger: this.logger,\n });\n }\n\n // Wire up process manager if provided\n if (options.processes) {\n const pm = options.processes;\n // Set the sandbox back-reference. The process manager reads this\n // lazily (at call time), so it's fine that the subclass constructor\n // hasn't finished yet.\n pm.sandbox = this;\n this.processes = pm;\n\n // Auto-create executeCommand (spawn + wait) unless the subclass\n // defines its own implementation.\n if (!this.executeCommand) {\n this.executeCommand = async (command: string, args?: string[], opts?: ExecuteCommandOptions) => {\n const fullCommand = args?.length ? `${command} ${args.map(a => shellQuote(a)).join(' ')}` : command;\n this.logger.debug('Executing command', { sandbox: this.name, command: fullCommand, cwd: opts?.cwd });\n\n const handle = await pm.spawn(fullCommand, {\n ...opts,\n timeout: opts?.timeout ?? this.defaultCommandTimeout,\n ...(args?.length ? { originalInvocation: { command, args: [...args] } } : {}),\n // Unbounded retention lets a command with huge output grow the buffer past\n // V8's max string length, which throws RangeError inside the stdout handler\n // and crashes the process. Callers that need every byte pass Infinity.\n maxRetainedBytes: opts?.maxRetainedBytes ?? DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES,\n // executeCommand runs to completion and collects output; nothing can\n // feed the process's stdin, so close it at spawn. Otherwise a command\n // that reads stdin (e.g. `rg` with no path argument) blocks forever.\n stdinMode: 'ignore',\n });\n try {\n const result = await handle.wait();\n // A process the command left behind can still hold its output after\n // the command returns. Nothing gets a PID to manage it once the\n // handle is released, so stop it now.\n if (handle.exitCode === undefined) await handle.kill();\n\n this.logger.debug('Command completed', {\n sandbox: this.name,\n exitCode: result.exitCode,\n duration: result.executionTimeMs,\n });\n\n return { ...result, command: fullCommand };\n } finally {\n pm.release(handle.pid);\n }\n };\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Runtime environment overlay\n // ---------------------------------------------------------------------------\n\n /**\n * Update the sandbox's runtime environment overlay.\n *\n * The updater receives a copy of the current overlay and returns the new\n * one, so a single call can set, unset, or batch-update variables:\n *\n * ```typescript\n * sandbox.setEnv(env => ({ ...env, GH_TOKEN: token }));\n * ```\n *\n * Changes apply immediately to subsequent commands and processes routed\n * through the sandbox's process manager (including the built-in\n * `executeCommand`), survive provider pause/resume and VM replacement,\n * and are never written into the VM — the overlay is merged per spawn,\n * not persisted. Removing a key removes it from the overlay only;\n * env values a provider supplies on its own still apply.\n */\n setEnv(update: (env: Record<string, string | undefined>) => Record<string, string | undefined>): void {\n // Clone both directions: the updater gets a copy, and its return value is\n // cloned before storage so callers retaining either object can't mutate\n // the stored overlay.\n this.#env = { ...update({ ...this.#env }) };\n }\n\n /**\n * Snapshot of the current runtime environment overlay.\n *\n * Returns a fresh copy — mutating it never affects the stored overlay; use\n * {@link setEnv} to change it. The process manager reads this per spawn to\n * merge the overlay into command environments.\n */\n getEnv(): Record<string, string | undefined> {\n return { ...this.#env };\n }\n\n /**\n * The sandbox's default working directory, when one is configured.\n *\n * Commands and process spawns without a per-command `cwd` run here;\n * per-command `cwd` always wins. `undefined` means the provider's own\n * default applies (typically the home directory).\n */\n get workingDirectory(): string | undefined {\n return this._workingDirectory;\n }\n\n /**\n * Set the effective working directory after construction. For providers\n * that resolve the value themselves — a computed default, or a runtime\n * probe that needs a running VM — so the {@link workingDirectory} getter\n * stays truthful.\n */\n protected setWorkingDirectory(dir: string): void {\n this._workingDirectory = dir;\n }\n\n /**\n * Attach or replace the start hook after construction. The updater receives\n * the installed hook and returns its replacement, so callers compose instead\n * of clobbering a hook they didn't know about; ignoring `prev` replaces it.\n *\n * ```typescript\n * sandbox.setOnStart(prev => async args => {\n * await prev?.(args); // whatever prepared the sandbox runs first\n * await mySetup(args);\n * });\n * ```\n *\n * Errors stay FATAL, so a throw stops the hooks after it. Each call wraps\n * the current hook, so attach once per sandbox or the work stacks.\n */\n setOnStart(update: (previous: SandboxStartHook | undefined) => SandboxStartHook): void {\n this._onStart = update(this._onStart);\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle Wrappers (race-condition-safe)\n // ---------------------------------------------------------------------------\n\n /**\n * Start the sandbox (wrapper with status management and race-condition safety).\n *\n * This method is race-condition-safe - concurrent calls will return the same promise.\n * Handles status management and automatically processes pending mounts after startup.\n *\n * Subclasses override `start()` to provide their startup logic.\n */\n async _start(options?: SandboxStartOptions): Promise<SandboxStartResult | void> {\n // Already running — definitionally not a fresh create. Reporting\n // 'connected' (rather than nothing) keeps every path through the wrapper\n // result-bearing for providers whose `start()` always reports one.\n if (this.status === 'running') {\n return { outcome: 'connected' };\n }\n\n // Wait for in-flight stop/destroy before starting.\n // Intentionally no .catch() — if teardown is failing, _start() should propagate\n // that error rather than silently starting on top of a broken state.\n if (this._stopPromise) await this._stopPromise;\n if (this._destroyPromise) await this._destroyPromise;\n\n // Cannot start a destroyed sandbox\n if (this.status === 'destroyed') {\n throw new Error('Cannot start a destroyed sandbox');\n }\n\n // Start already in progress — join it and share its result. The slot is\n // cleared on settle, so a failed attempt is never latched.\n if (this._startPromise) {\n return this._startPromise;\n }\n\n // Create and store the start promise\n this._startPromise = this._executeStart(options);\n\n try {\n return await this._startPromise;\n } finally {\n this._startPromise = undefined;\n }\n }\n\n /**\n * Internal start execution - handles status, the onStart hook, and mount\n * processing.\n */\n private async _executeStart(options?: SandboxStartOptions): Promise<SandboxStartResult | void> {\n this.status = 'starting';\n\n let result: SandboxStartResult | void;\n try {\n result = this._useAcquisitionPrimitives ? await this._acquire(options) : await this._implStart(options);\n // Status must flip to 'running' BEFORE the onStart hook: hooks run\n // commands, which reach `ensureRunning()` and would otherwise join the\n // in-flight `_startPromise` and deadlock awaiting their own start.\n // Accepted window: commands fired concurrently with start() can\n // interleave with the hook, and a start() arriving DURING the hook takes\n // the already-running early return. Callers awaiting the ORIGINAL\n // start() always observe a sandbox whose hook finished.\n this.status = 'running';\n } catch (error) {\n this.status = 'error';\n throw error;\n }\n\n const outcome = result?.outcome;\n\n // Hook failures are FATAL: a caller must never observe a running sandbox\n // whose setup failed. Nothing latches, so the next start() retries it.\n // The environment acquired above is NOT released first: providers that\n // implement find() reconnect to it on retry, but a create-only provider\n // provisions another one and leaves the first to its idle timeout.\n try {\n await this._onStart?.({ sandbox: this, outcome });\n } catch (error) {\n this.status = 'error';\n throw new Error(`Sandbox '${this.id}' onStart hook failed: ${error instanceof Error ? error.message : error}`, {\n cause: error,\n });\n }\n\n // Process any pending mounts after successful start\n // Mount failures are tracked individually in MountManager and\n // shouldn't mark the sandbox itself as errored\n try {\n await this.mounts?.processPending();\n } catch (error) {\n // Mount failures are tracked in MountManager — log but don't affect sandbox status\n this.logger.warn('Unexpected error processing pending mounts', { error });\n }\n\n return result;\n }\n\n // ---------------------------------------------------------------------------\n // Acquisition primitives (optional — see start() for the rung ladder)\n // ---------------------------------------------------------------------------\n\n /**\n * Locate an existing VM/environment for this sandbox's logical id. Returns\n * a provider-native handle for {@link connect} to adopt, or `undefined` when\n * nothing usable exists. Avoid side effects where the provider's API allows.\n */\n protected find?(options?: SandboxStartOptions): Promise<THandle | undefined>;\n\n /**\n * Adopt/wake/resume the handle {@link find} returned. Throwing fails\n * `start()`: a provider that should fall back to creating fresh puts that\n * policy in `find` (return `undefined` for an unusable handle) instead.\n */\n protected connect?(handle: THandle, options?: SandboxStartOptions): Promise<void> | void;\n\n /**\n * Provision a fresh VM/environment for this sandbox's logical id.\n * Implementing this without overriding `start()` opts into base-orchestrated\n * acquisition, which derives the outcome from the branch that ran: find then\n * connect reports 'connected', create reports 'created'.\n */\n protected create?(options?: SandboxStartOptions): Promise<void> | void;\n\n /** Base-orchestrated acquisition (rung 1 — see {@link start}). */\n private async _acquire(options?: SandboxStartOptions): Promise<SandboxStartResult> {\n const handle = this.find ? await this.find(options) : undefined;\n if (handle != null) {\n // Checked rather than optional: adopting nothing would still report\n // 'connected'. The constructor rejects this pairing, but a `connect`\n // declared as a class field is invisible there.\n if (!this.connect) {\n throw new Error(`${this.constructor.name}: find() requires connect() to adopt the handle it returns.`);\n }\n await this.connect(handle, options);\n return { outcome: 'connected' };\n }\n await this.create!(options);\n return { outcome: 'created' };\n }\n\n /**\n * Sandbox startup. Providers plug in at one of three rungs (best available\n * wins); either way the base owns coalescing, status management, the\n * onStart setup hook, and mount processing:\n *\n * 1. Implement the {@link find}/{@link connect}/{@link create} primitives\n * (and do NOT override `start()`) — the base orchestrates acquisition\n * and derives the outcome structurally. For providers whose API\n * decomposes into lookup/wake/provision.\n * 2. Override `start()` returning {@link SandboxStartResult} — for\n * providers with a fused getOrCreate-style API where decomposition\n * would add round-trips.\n * 3. Override `start()` returning void — the outcome is unknown.\n *\n * The base constructor wraps `start()` so direct calls are routed through\n * `_start()`. Use METHOD syntax when overriding — a class-field `start`\n * initializer would overwrite the wrapper. Implementing neither rung throws:\n * a sandbox with nothing to start says so with an empty `async start() {}`.\n *\n * Id-keyed getOrCreate contract: a sandbox constructed with a known `id`\n * resolves that id on start — reconnect/resume when the provider finds an\n * existing VM for it, create otherwise.\n */\n async start(_options?: SandboxStartOptions): Promise<SandboxStartResult | void> {\n // Also where a misspelled override and a class-FIELD `start`/`create` land,\n // since field initializers run too late for the constructor to see them.\n throw new Error(\n `${this.constructor.name} implements neither start() nor the create() acquisition primitive, so starting it would do nothing. Implement one using method syntax.`,\n );\n }\n\n /**\n * Ensure the sandbox is running.\n *\n * Calls `_start()` if status is not 'running'. Useful for lazy initialization\n * where operations should automatically start the sandbox if needed.\n *\n * This is the lazy entry point into the id-keyed getOrCreate contract\n * described on {@link start}.\n *\n * @throws {SandboxNotReadyError} if the sandbox fails to reach 'running' status\n *\n * @example\n * ```typescript\n * async executeCommand(command: string): Promise<CommandResult> {\n * await this.ensureRunning();\n * // Now safe to use the sandbox\n * }\n * ```\n */\n async ensureRunning(): Promise<void> {\n // Already destroyed — cannot use this sandbox\n if (this.status === 'destroyed') {\n throw new SandboxNotReadyError(this.id);\n }\n // During teardown the sandbox is still operational (e.g. destroy()\n // may need to list/kill processes). Allow operations to proceed\n // without trying to restart.\n if (this.status === 'destroying' || this.status === 'stopping') {\n return;\n }\n if (this.status !== 'running') {\n await this._start();\n }\n if (this.status !== 'running') {\n throw new SandboxNotReadyError(this.id);\n }\n }\n\n /**\n * Stop the sandbox (wrapper with status management and race-condition safety).\n *\n * This method is race-condition-safe - concurrent calls will return the same promise.\n * Handles status management.\n *\n * Subclasses override `stop()` to provide their stop logic.\n */\n async _stop(): Promise<void> {\n // Already stopped\n if (this.status === 'stopped') {\n return;\n }\n\n // Wait for in-flight start before stopping\n if (this._startPromise) await this._startPromise.catch(() => {});\n\n // Stop already in progress - return existing promise\n if (this._stopPromise) {\n return this._stopPromise;\n }\n\n // Create and store the stop promise\n this._stopPromise = this._executeStop();\n\n try {\n await this._stopPromise;\n } finally {\n this._stopPromise = undefined;\n }\n }\n\n /**\n * Internal stop execution - handles status.\n */\n private async _executeStop(): Promise<void> {\n this.status = 'stopping';\n\n try {\n // Fire onStop callback before stopping\n await this._onStop?.({ sandbox: this });\n\n await this.stop();\n this.status = 'stopped';\n } catch (error) {\n this.status = 'error';\n throw error;\n }\n }\n\n /**\n * Override this method to implement sandbox stop logic.\n *\n * Called by `_stop()` after status is set to 'stopping'.\n * Status will be set to 'stopped' on success, 'error' on failure.\n */\n async stop(): Promise<void> {\n // Default no-op - subclasses override\n }\n\n /**\n * Destroy the sandbox and clean up all resources (wrapper with status management).\n *\n * This method is race-condition-safe - concurrent calls will return the same promise.\n * Handles status management.\n *\n * Subclasses override `destroy()` to provide their destroy logic.\n */\n async _destroy(): Promise<void> {\n // Already destroyed\n if (this.status === 'destroyed') {\n return;\n }\n\n // Never started — nothing to clean up\n if (this.status === 'pending') {\n this.status = 'destroyed';\n return;\n }\n\n // Wait for in-flight start/stop before destroying\n if (this._startPromise) await this._startPromise.catch(() => {});\n if (this._stopPromise) await this._stopPromise.catch(() => {});\n\n // Destroy already in progress - return existing promise\n if (this._destroyPromise) {\n return this._destroyPromise;\n }\n\n // Create and store the destroy promise\n this._destroyPromise = this._executeDestroy();\n\n try {\n await this._destroyPromise;\n } finally {\n this._destroyPromise = undefined;\n }\n }\n\n /**\n * Internal destroy execution - handles status.\n */\n private async _executeDestroy(): Promise<void> {\n this.status = 'destroying';\n\n try {\n // Fire onDestroy callback before destroying\n await this._onDestroy?.({ sandbox: this });\n\n await this.destroy();\n this.status = 'destroyed';\n } catch (error) {\n this.status = 'error';\n throw error;\n }\n }\n\n /**\n * Override this method to implement sandbox destroy logic.\n *\n * Called by `_destroy()` after status is set to 'destroying'.\n * Status will be set to 'destroyed' on success, 'error' on failure.\n */\n async destroy(): Promise<void> {\n // Default no-op - subclasses override\n }\n\n // ---------------------------------------------------------------------------\n // Logger Propagation\n // ---------------------------------------------------------------------------\n\n /**\n * Override to propagate logger to MountManager.\n * @internal\n */\n override __setLogger(logger: IMastraLogger): void {\n super.__setLogger(logger);\n // Propagate to MountManager if it exists\n this.mounts?.__setLogger(logger);\n }\n}\n","import type { execa as execaType } from 'execa';\n\nlet cached: typeof execaType | undefined;\nlet loading: Promise<typeof execaType> | undefined;\n\n// Keep the specifier as a parameter so tsdown cannot fold it into a literal dynamic import.\nconst importModule = (moduleName: string) => import(/* @vite-ignore */ /* webpackIgnore: true */ moduleName);\n\n/**\n * Lazily imports execa using a runtime-constructed module specifier.\n * This prevents bundlers (Vite/Rollup/esbuild) from resolving execa at build time,\n * which is necessary for Cloudflare Workers where execa's transitive deps\n * (npm-run-path → unicorn-magic) use Node-only conditional exports.\n */\nexport async function getExeca(): Promise<typeof execaType> {\n if (cached) {\n return cached;\n }\n if (!loading) {\n loading = (async () => {\n try {\n const execa = (await importModule('execa')).execa;\n cached = execa;\n return execa;\n } catch (err) {\n throw new Error(\n 'execa is required for local process execution but is not available in this environment. ' +\n 'LocalProcessManager is not supported in Cloudflare Workers or other non-Node runtimes.',\n { cause: err },\n );\n }\n })();\n }\n return loading;\n}\n","/**\n * Sandbox Process Manager (Base Class)\n *\n * Abstract base class for sandbox process management.\n * Wraps all methods with ensureRunning() so the sandbox is\n * automatically started before any process operation.\n * Subclasses implement spawn(), list(), get().\n */\n\nimport type { MastraSandbox } from '../mastra-sandbox';\nimport { validateMaxRetainedProcessOutputBytes } from './process-handle';\nimport type { ProcessHandle } from './process-handle';\nimport type { ProcessInfo, SpawnProcessOptions } from './types';\n\n// =============================================================================\n// Sandbox Process Manager (Base Class)\n// =============================================================================\n\n/**\n * Abstract base class for process management in sandboxes.\n *\n * Wraps subclass overrides of `spawn()`, `list()`, and `get()` with\n * `sandbox.ensureRunning()` so the sandbox is lazily started before\n * any process operation.\n *\n * Subclasses implement the actual platform-specific logic for all methods.\n *\n * @typeParam TSandbox - The sandbox type. Subclasses narrow this to access\n * sandbox-specific properties (e.g. `workingDirectory`, `instance`).\n *\n * @example\n * ```typescript\n * const handle = await sandbox.processes.spawn('node server.js');\n * console.log(handle.pid, handle.stdout);\n *\n * const all = await sandbox.processes.list();\n * const proc = await sandbox.processes.get(handle.pid);\n * await proc?.kill();\n * ```\n */\nexport interface ProcessManagerOptions {\n env?: Record<string, string | undefined>;\n}\n\nexport abstract class SandboxProcessManager<TSandbox extends MastraSandbox = MastraSandbox> {\n /**\n * The sandbox this process manager belongs to.\n * Set automatically by MastraSandbox when processes are passed into the constructor.\n * @internal\n */\n sandbox!: TSandbox;\n\n protected readonly env: Record<string, string | undefined>;\n\n /** Tracked process handles keyed by PID. Populated by spawn(), used by get()/kill(). */\n protected readonly _tracked = new Map<string, ProcessHandle>();\n\n /** PIDs that have been read after exit and should not be re-discovered by subclass fallbacks. */\n protected readonly _dismissed = new Set<string>();\n\n constructor({ env = {} }: ProcessManagerOptions = {}) {\n this.env = env;\n\n // Capture subclass overrides (via prototype chain) before shadowing\n // with wrapped versions that add ensureRunning().\n const impl = {\n spawn: this.spawn.bind(this),\n list: this.list.bind(this),\n get: this.get.bind(this),\n };\n\n this.spawn = async (...args: Parameters<typeof impl.spawn>) => {\n // Validate before starting a sandbox; ProcessHandle validates again for direct subclass construction.\n if (args[1]?.maxRetainedBytes !== undefined) {\n validateMaxRetainedProcessOutputBytes(args[1].maxRetainedBytes);\n }\n await this.sandbox.ensureRunning();\n\n // Merge the sandbox's runtime env into the spawn options.\n // Read per spawn (never captured at construction) so values installed\n // via setEnv() after construction reach every subsequent process.\n // Per-call env wins over the sandbox env. When the sandbox env is\n // empty, leave the args untouched — provider spawn implementations\n // branch on `options.env !== undefined` and must not observe a new\n // empty object. The optional call tolerates hand-rolled sandbox\n // stubs (common in provider tests) that don't extend MastraSandbox.\n const sandboxEnv = this.sandbox.getEnv?.();\n if (sandboxEnv && Object.keys(sandboxEnv).length > 0) {\n args[1] = { ...args[1], env: { ...sandboxEnv, ...args[1]?.env } };\n }\n\n const handle = await impl.spawn(...args);\n this._dismissed.delete(handle.pid);\n handle.command = args[0];\n\n // Wire abort signal to handle.kill() so all providers get abort support automatically.\n const abortSignal = args[1]?.abortSignal;\n if (abortSignal) {\n const onAbort = () => {\n handle.killForAbort().catch(() => {});\n };\n if (abortSignal.aborted) {\n onAbort();\n } else {\n abortSignal.addEventListener('abort', onAbort, { once: true });\n // Clean up listener when process exits\n handle.wait().then(\n () => abortSignal.removeEventListener('abort', onAbort),\n () => abortSignal.removeEventListener('abort', onAbort),\n );\n }\n }\n\n return handle;\n };\n\n this.list = async () => {\n await this.sandbox.ensureRunning();\n return impl.list();\n };\n\n this.get = async (...args: Parameters<typeof impl.get>) => {\n await this.sandbox.ensureRunning();\n // Skip PIDs that were already read after exit and dismissed.\n if (this._dismissed.has(args[0])) return undefined;\n const handle = await impl.get(...args);\n // Prune exited processes when their output is read — this is the\n // only automatic cleanup path. Keeps output available until the\n // consumer has seen it at least once. `release: false` lets an\n // observer (such as a UI) read without taking it from the agent.\n if (handle?.exitCode !== undefined && args[1]?.release !== false) {\n this._tracked.delete(handle.pid);\n this._dismissed.add(handle.pid);\n }\n return handle;\n };\n }\n\n /** Spawn a process. */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n throw new Error(`${this.constructor.name} must implement spawn()`);\n }\n\n /** List all tracked processes. */\n async list(): Promise<ProcessInfo[]> {\n throw new Error(`${this.constructor.name} must implement list()`);\n }\n\n /**\n * Get a handle to a process by PID. Subclasses can override for fallback behavior.\n *\n * Reading an exited process releases it by default: later calls return\n * `undefined`. Pass `{ release: false }` to read it and leave it available,\n * for example to show its output without taking it from the agent.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async get(pid: string, options?: { release?: boolean }): Promise<ProcessHandle | undefined> {\n return this._tracked.get(pid);\n }\n\n /** Release a completed process handle and its retained output. */\n release(pid: string): void {\n this._tracked.delete(pid);\n this._dismissed.add(pid);\n }\n\n /** Kill a process by PID. Returns true if killed, false if not found. */\n async kill(pid: string): Promise<boolean> {\n const handle = await this.get(pid);\n if (!handle) return false;\n const killed = await handle.kill();\n if (killed) {\n // Wait for termination so handle.exitCode is populated before returning.\n // Without this, a subsequent get() could still report the process as running.\n await handle.wait().catch(() => {});\n }\n // Release tracked handle to free accumulated output buffers.\n this.release(handle.pid);\n return killed;\n }\n}\n","/**\n * Local Process Manager\n *\n * Local implementation of SandboxProcessManager using execa.\n * Tracks processes in-memory since there's no server to query.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { ResultPromise, Options as ExecaOptions } from 'execa';\n\nimport { getExeca } from './execa';\nimport type { LocalSandbox } from './local-sandbox';\nimport { ProcessHandle, SandboxProcessManager } from './process-manager';\nimport type { ProcessInfo, SpawnProcessOptions } from './process-manager';\nimport type { ProcessManagerOptions } from './process-manager/process-manager';\nimport type { CommandResult } from './types';\nimport { shellQuote } from './utils';\n\nconst isWindows = process.platform === 'win32';\n\n/** How long a timed-out process tree gets to exit after SIGTERM before it is sent SIGKILL. */\nconst TIMEOUT_KILL_GRACE_MS = 2_000;\n\n/** How long output may keep draining after the process exits before wait() settles without it. */\nconst EXIT_OUTPUT_GRACE_MS = 2_000;\n\nconst OOM_SCORE_ADJ_PATH = '/proc/self/oom_score_adj';\n\n/** `oom_score_adj` given to spawned commands unless `MASTRA_COMMAND_OOM_SCORE_ADJ` overrides it. */\nconst DEFAULT_COMMAND_OOM_SCORE_ADJ = 500;\n\n/**\n * The `oom_score_adj` to give spawned commands: `MASTRA_COMMAND_OOM_SCORE_ADJ` (1-1000), or the\n * default when it is unset or not a number. `0`, `off` or `false` turns the adjustment off.\n */\nfunction commandOomScoreAdj(): number | undefined {\n const configured = process.env.MASTRA_COMMAND_OOM_SCORE_ADJ?.trim();\n if (configured && /^(0+|off|false)$/i.test(configured)) return undefined;\n if (configured && /^\\d+$/.test(configured)) return Math.min(Number(configured), 1000);\n return DEFAULT_COMMAND_OOM_SCORE_ADJ;\n}\n\n/**\n * Prefix a shell command so that its shell raises its own `oom_score_adj` first (Linux only).\n *\n * The agent and the commands it runs share one memory limit in a container. When a command's\n * processes use it all up, the kernel OOM killer kills the process with the highest score, and a\n * Node agent holding a few hundred MB often outscores each of many smaller workers. Everything the\n * shell starts inherits the raised score (also across `exec`), so the kernel kills the workload\n * instead, and the agent sees `Killed` / exit 137 in the command result.\n *\n * Raising your own score needs no privilege. A failed write (no `/proc`, read-only `/proc`) is\n * silent, and the prefix changes neither the command's output nor its exit status. It stays on\n * the command's first line, so shell error line numbers are unchanged. It is skipped when the\n * agent's own score is already at or above the target, since lowering a score needs privilege.\n */\nfunction withRaisedOomScore(command: string): string {\n if (process.platform !== 'linux') return command;\n const target = commandOomScoreAdj();\n if (target === undefined) return command;\n let current: number;\n try {\n current = Number.parseInt(readFileSync(OOM_SCORE_ADJ_PATH, 'utf8'), 10);\n } catch {\n return command;\n }\n if (!(current < target)) return command;\n return `{ echo ${target} >${OOM_SCORE_ADJ_PATH}; } 2>/dev/null; ${command}`;\n}\n\n/**\n * Find a POSIX shell on Windows for commands built with POSIX quoting.\n * Checks `MASTRA_WINDOWS_SHELL`, then Git Bash next to a `git.exe` on the command's PATH\n * (Git for Windows puts `Git\\cmd` on PATH, not `Git\\bin`), then the default\n * Git for Windows install location. Bare `bash` on PATH is skipped on purpose:\n * it is often WSL's launcher, which can't see Windows paths.\n */\nfunction findWindowsPosixShell(searchPath: string | undefined): string | undefined {\n const candidates: string[] = [];\n const configured = process.env.MASTRA_WINDOWS_SHELL?.trim();\n // A bare `cmd`/`cmd.exe` opt-out resolves through PATH at spawn time, so there's no file to check.\n if (configured && /^cmd(\\.exe)?$/i.test(configured)) return configured;\n if (configured) candidates.push(configured);\n for (const dir of (searchPath ?? '').split(path.win32.delimiter)) {\n if (dir && existsSync(path.win32.join(dir, 'git.exe'))) {\n candidates.push(\n path.win32.join(dir, '..', 'bin', 'bash.exe'),\n path.win32.join(dir, '..', '..', 'bin', 'bash.exe'),\n );\n }\n }\n candidates.push(path.win32.join(process.env.ProgramFiles ?? 'C:\\\\Program Files', 'Git', 'bin', 'bash.exe'));\n return candidates.find(candidate => existsSync(candidate));\n}\n\n// =============================================================================\n// Local Process Handle\n// =============================================================================\n\n/**\n * Local implementation of ProcessHandle wrapping an execa subprocess.\n * Not exported — internal to this module.\n */\nclass LocalProcessHandle extends ProcessHandle {\n readonly pid: string;\n exitCode: number | undefined;\n\n private readonly _numericPid: number;\n private subprocess: ResultPromise;\n private readonly waitPromise: Promise<CommandResult>;\n private readonly startTime: number;\n\n constructor(\n subprocess: ResultPromise,\n pid: number,\n startTime: number,\n options?: SpawnProcessOptions,\n outputEncoding = 'utf-8',\n ) {\n super(options);\n this.pid = String(pid);\n this._numericPid = pid;\n this.subprocess = subprocess;\n this.startTime = startTime;\n\n let timedOut = false;\n let killTimeoutId: ReturnType<typeof setTimeout> | undefined;\n let releaseTimeoutId: ReturnType<typeof setTimeout> | undefined;\n let exitGraceId: ReturnType<typeof setTimeout> | undefined;\n const timeoutId = options?.timeout\n ? setTimeout(() => {\n timedOut = true;\n // Kill the entire process tree so child processes are also terminated.\n // We handle timeout ourselves rather than using execa's timeout option\n // because execa only kills the direct subprocess, not the process tree.\n void killProcessTree(this._numericPid, subprocess, 'SIGTERM');\n // A process can ignore SIGTERM, and the shell can exit while a descendant\n // keeps stdout open. Either way 'close' never fires, so escalate to SIGKILL.\n killTimeoutId = setTimeout(() => {\n void killProcessTree(this._numericPid, subprocess, 'SIGKILL');\n // A descendant that left the process group can still hold the pipes.\n // Stop reading them so wait() settles instead of hanging.\n releaseTimeoutId = setTimeout(() => {\n subprocess.stdout?.destroy();\n subprocess.stderr?.destroy();\n }, TIMEOUT_KILL_GRACE_MS);\n }, TIMEOUT_KILL_GRACE_MS);\n }, options.timeout)\n : undefined;\n const clearTimers = () => {\n clearTimeout(timeoutId);\n clearTimeout(killTimeoutId);\n clearTimeout(releaseTimeoutId);\n clearTimeout(exitGraceId);\n };\n const toExitCode = (code: number | null, signal: NodeJS.Signals | null) =>\n signal && code === null ? 128 : (code ?? 0);\n\n const stdoutDecoder = new TextDecoder(outputEncoding);\n const stderrDecoder = new TextDecoder(outputEncoding);\n let stdoutDecoderEnded = false;\n let stderrDecoderEnded = false;\n\n const flushStdoutDecoder = () => {\n if (stdoutDecoderEnded) return;\n stdoutDecoderEnded = true;\n const data = stdoutDecoder.decode();\n if (data) this.emitStdout(data);\n };\n\n const flushStderrDecoder = () => {\n if (stderrDecoderEnded) return;\n stderrDecoderEnded = true;\n const data = stderrDecoder.decode();\n if (data) this.emitStderr(data);\n };\n\n this.waitPromise = new Promise<CommandResult>(resolve => {\n let settled = false;\n const settle = (exitCode: number, signal: NodeJS.Signals | null) => {\n if (settled) return;\n settled = true;\n resolve({\n success: exitCode === 0,\n exitCode,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this.startTime,\n killed: signal !== null,\n timedOut,\n });\n };\n subprocess.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n clearTimers();\n flushStdoutDecoder();\n flushStderrDecoder();\n if (timedOut) {\n const timeoutMsg = `\\nProcess timed out after ${options!.timeout}ms`;\n this.emitStderr(timeoutMsg);\n this.exitCode = 124;\n } else {\n this.exitCode = toExitCode(code, signal);\n }\n settle(this.exitCode, signal);\n });\n // 'close' waits for stdout and stderr to close too, and a descendant the\n // process left behind (`cmd &`, or one in its own process group such as\n // `timeout`'s) can hold them open long after the process exited. wait()\n // settles on the exit once its output has had time to drain. exitCode\n // stays unset until 'close', so the handle still counts as running while\n // the descendant holds its output: kill() and sandbox stop still reach it,\n // and the process manager keeps listing it. A timed-out process is left\n // to the timeout's own kill escalation and pipe release.\n subprocess.on('exit', (code: number | null, signal: NodeJS.Signals | null) => {\n exitGraceId = setTimeout(() => {\n if (!timedOut) settle(toExitCode(code, signal), signal);\n }, EXIT_OUTPUT_GRACE_MS);\n });\n\n subprocess.on('error', (err: Error) => {\n settled = true;\n clearTimers();\n flushStdoutDecoder();\n flushStderrDecoder();\n this.emitStderr(err.message);\n this.exitCode = 1;\n resolve({\n success: false,\n exitCode: 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this.startTime,\n });\n });\n });\n\n subprocess.stdout?.on('data', (data: Buffer) => {\n const decoded = stdoutDecoder.decode(data, { stream: true });\n if (decoded) this.emitStdout(decoded);\n });\n subprocess.stdout?.on('end', flushStdoutDecoder);\n\n subprocess.stderr?.on('data', (data: Buffer) => {\n const decoded = stderrDecoder.decode(data, { stream: true });\n if (decoded) this.emitStderr(decoded);\n });\n subprocess.stderr?.on('end', flushStderrDecoder);\n }\n\n async wait(): Promise<CommandResult> {\n return this.waitPromise;\n }\n\n async kill(): Promise<boolean> {\n if (this.exitCode !== undefined) return false;\n // Kill the entire process tree to ensure child processes spawned by the\n // shell are also terminated. Without this, commands like\n // \"echo foo; sleep 60\" would leave orphaned children holding stdio open.\n await killProcessTree(this._numericPid, this.subprocess, 'SIGKILL');\n return true;\n }\n\n async sendStdin(data: string): Promise<void> {\n if (this.exitCode !== undefined) {\n throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);\n }\n if (!this.subprocess.stdin) {\n throw new Error(`Process ${this.pid} does not have stdin available`);\n }\n return new Promise<void>((resolve, reject) => {\n this.subprocess.stdin!.write(data, (err: Error | null | undefined) => (err ? reject(err) : resolve()));\n });\n }\n\n async closeStdin(): Promise<void> {\n if (this.exitCode !== undefined) {\n throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);\n }\n if (!this.subprocess.stdin) {\n throw new Error(`Process ${this.pid} does not have stdin available`);\n }\n if (this.subprocess.stdin.writableEnded) return;\n return new Promise<void>((resolve, reject) => {\n this.subprocess.stdin!.end((err?: Error | null) => (err ? reject(err) : resolve()));\n });\n }\n}\n\n// =============================================================================\n// Process Tree Killing\n// =============================================================================\n\n/**\n * Kill a process and all its children.\n *\n * On Unix, we use process groups (negative PID) since processes are spawned\n * with `detached: true` which creates a new process group.\n *\n * On Windows, `process.kill(-pid)` doesn't work (no process groups), and\n * `detached: true` opens a new console window. Instead we use `taskkill /T`\n * which recursively kills the process tree by PID.\n */\nasync function killProcessTree(pid: number, subprocess: ResultPromise, signal: NodeJS.Signals): Promise<void> {\n if (isWindows) {\n try {\n // /T = kill child processes, /F = force, /PID = target process\n const execa = await getExeca();\n await execa('taskkill', ['/T', '/F', '/PID', String(pid)], { reject: false, stdio: 'ignore' });\n } catch {\n // taskkill binary not found — fall back to direct kill\n subprocess.kill(signal);\n }\n } else {\n try {\n process.kill(-pid, signal);\n } catch {\n subprocess.kill(signal);\n }\n }\n}\n\n// =============================================================================\n// Local Process Manager\n// =============================================================================\n\n/**\n * Local implementation of SandboxProcessManager.\n * Spawns processes via execa and tracks them in-memory.\n */\nexport interface LocalProcessManagerOptions extends ProcessManagerOptions {\n /** Encoding used to decode child stdout/stderr (any WHATWG encoding label). Default: 'utf-8'. */\n outputEncoding?: string;\n}\n\nexport class LocalProcessManager extends SandboxProcessManager<LocalSandbox> {\n private readonly outputEncoding: string;\n\n constructor({ outputEncoding = 'utf-8', ...options }: LocalProcessManagerOptions = {}) {\n super(options);\n // Fail fast on unsupported labels (e.g. Node builds without full ICU).\n new TextDecoder(outputEncoding);\n this.outputEncoding = outputEncoding;\n }\n\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n let cwd = this.sandbox.workingDirectory;\n if (options.cwd) {\n if (path.isAbsolute(options.cwd)) {\n cwd = options.cwd;\n } else {\n // Prevent duplicate nesting when agent passes cwd that's already workspace-relative\n const normalizedWorkingDir = path.resolve(this.sandbox.workingDirectory);\n const normalizedOptionsCwd = path.resolve(options.cwd);\n // Check if path is already under workspace (exact match or nested subpath)\n const isAlreadyWorkspacePath =\n normalizedOptionsCwd === normalizedWorkingDir ||\n normalizedOptionsCwd.startsWith(`${normalizedWorkingDir}${path.sep}`);\n\n cwd = isAlreadyWorkspacePath ? normalizedOptionsCwd : path.resolve(this.sandbox.workingDirectory, options.cwd);\n }\n }\n let env = this.sandbox.buildEnv(options.env);\n const invocation = options.originalInvocation;\n // Argv invocations are joined with POSIX quoting (see MastraSandbox.executeCommand),\n // which cmd.exe can't parse, so route them through a POSIX shell when one exists.\n // Plain string commands are caller-authored and keep using cmd.exe, as do argv\n // calls to Windows command interpreters, whose `/c`-style switches need cmd.exe.\n const posixShell =\n isWindows &&\n this.sandbox.isolation === 'none' &&\n invocation !== undefined &&\n !/^(cmd|powershell|pwsh)(\\.exe)?$/i.test(path.win32.basename(invocation.command))\n ? findWindowsPosixShell(env.PATH)\n : undefined;\n const usesBash = posixShell !== undefined && !/^cmd(\\.exe)?$/i.test(path.win32.basename(posixShell));\n if (usesBash) {\n // Stop Git Bash/MSYS2 from rewriting `/F`-style switches and paths passed to native tools.\n env = { MSYS_NO_PATHCONV: '1', MSYS2_ARG_CONV_EXCL: '*', ...env };\n }\n // Preserve the script as one argument instead of letting cmd.exe interpret its operators.\n const directShell =\n isWindows &&\n this.sandbox.isolation === 'none' &&\n invocation !== undefined &&\n /^(sh|sh\\.exe)$/i.test(path.win32.basename(invocation.command)) &&\n invocation.args[0] === '-c' &&\n invocation.args.length >= 2;\n const wrapped = directShell\n ? {\n command: usesBash && /^sh(\\.exe)?$/i.test(invocation.command) ? posixShell : invocation.command,\n args: invocation.args,\n }\n : usesBash && invocation\n ? // Quote the program too: bash reads the backslashes in C:\\tools\\node.exe as escapes.\n { command: [invocation.command, ...invocation.args].map(shellQuote).join(' '), args: [] }\n : this.sandbox.wrapCommandForIsolation(withRaisedOomScore(command));\n\n // Base options shared across all platforms.\n //\n // `stdinMode: 'ignore'` closes the child's stdin at spawn so it sees EOF\n // immediately. Without it, a stdin-reading command (e.g. `rg` with no path\n // argument) blocks forever waiting for input nothing will ever send, and the\n // caller hangs. Callers that need to drive the process's stdin (`spawn` for\n // an LSP server) keep the default writable pipe.\n const stdio = options.stdinMode === 'ignore' ? (['ignore', 'pipe', 'pipe'] as const) : ('pipe' as const);\n const baseOptions = {\n cwd,\n env,\n stdio,\n // Don't throw on non-zero exit — we handle exit codes ourselves.\n reject: false,\n // Don't buffer output — we stream it via ProcessHandle callbacks.\n buffer: false,\n // Don't strip newlines — preserve raw output for ProcessHandle accumulation.\n stripFinalNewline: false,\n // Don't extend process.env — the sandbox controls the full environment via buildEnv().\n extendEnv: false,\n };\n\n let execaOptions: ExecaOptions;\n\n if (isWindows) {\n // On Windows, `detached: true` opens a new console window (visible cmd.exe\n // popup) and breaks stdout/stderr piping. A shell without `detached`\n // pipes stdout/stderr back to the parent process without any visible window.\n // Node runs a non-cmd shell as `<shell> -c \"<command>\"`.\n //\n // Process tree killing uses `taskkill /T` instead of Unix process groups.\n execaOptions = {\n ...baseOptions,\n shell: !directShell && this.sandbox.isolation === 'none' && (posixShell ?? true),\n windowsHide: true,\n };\n } else {\n // On Unix, `detached: true` creates a new process group so we can kill the\n // entire tree via `process.kill(-pid, signal)`.\n //\n // Non-isolated: use shell mode so the host shell interprets the command string\n // (pipes, redirects, chaining, etc.). Isolated (seatbelt/bwrap): the wrapper\n // already includes `sh -c` inside the sandbox, so we spawn the wrapper directly.\n execaOptions = {\n ...baseOptions,\n detached: true,\n shell: this.sandbox.isolation === 'none',\n };\n }\n\n const execa = await getExeca();\n const subprocess = execa(wrapped.command, wrapped.args, execaOptions);\n\n // execa sets pid synchronously when the process spawns successfully.\n // If pid is undefined, the spawn failed (bad cwd, missing command, etc.).\n // Await the subprocess to get execa's detailed error message.\n if (!subprocess.pid) {\n const result = await subprocess;\n throw new Error(result.message || 'Process failed to spawn');\n }\n\n const handle = new LocalProcessHandle(subprocess, subprocess.pid, Date.now(), options, this.outputEncoding);\n this._tracked.set(handle.pid, handle);\n return handle;\n }\n\n async list(): Promise<ProcessInfo[]> {\n return Array.from(this._tracked.values()).map(handle => ({\n pid: handle.pid,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n }));\n }\n}\n","/**\n * Platform Detection\n *\n * Detects available sandboxing backends for the current platform.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport os from 'node:os';\n\nimport type { IsolationBackend, SandboxDetectionResult } from './types';\n\n/**\n * Check if a command exists on the system.\n */\nfunction commandExists(command: string): boolean {\n try {\n // Use 'which' on Unix-like systems\n execFileSync('which', [command], { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if seatbelt (sandbox-exec) is available.\n * This is built-in on macOS.\n */\nexport function isSeatbeltAvailable(): boolean {\n if (os.platform() !== 'darwin') {\n return false;\n }\n return commandExists('sandbox-exec');\n}\n\n/**\n * Check if bubblewrap (bwrap) is available.\n * This must be installed on Linux systems.\n */\nexport function isBwrapAvailable(): boolean {\n if (os.platform() !== 'linux') {\n return false;\n }\n return commandExists('bwrap');\n}\n\n/**\n * Detect the best available isolation backend for the current platform.\n *\n * @returns The recommended isolation backend and availability info\n *\n * @example\n * ```typescript\n * const result = detectIsolation();\n * if (result.available) {\n * console.log(`Using ${result.backend} for sandboxing`);\n * } else {\n * console.warn(result.message);\n * }\n * ```\n */\nexport function detectIsolation(): SandboxDetectionResult {\n const platform = os.platform();\n\n if (platform === 'darwin') {\n const available = isSeatbeltAvailable();\n return {\n backend: 'seatbelt',\n available,\n message: available\n ? 'macOS seatbelt (sandbox-exec) is available'\n : 'macOS seatbelt (sandbox-exec) not found - this is unexpected on macOS',\n };\n }\n\n if (platform === 'linux') {\n const available = isBwrapAvailable();\n return {\n backend: 'bwrap',\n available,\n message: available\n ? 'Linux bubblewrap (bwrap) is available'\n : 'Linux bubblewrap (bwrap) not found. Install with: apt install bubblewrap (Debian/Ubuntu) or dnf install bubblewrap (Fedora)',\n };\n }\n\n // Windows or other platforms\n return {\n backend: 'none',\n available: false,\n message: `Native sandboxing is not supported on ${platform}. Commands will run without isolation.`,\n };\n}\n\n/**\n * Check if a specific isolation backend is available.\n *\n * @param backend - The isolation backend to check\n * @returns Whether the backend is available on this system\n */\nexport function isIsolationAvailable(backend: IsolationBackend): boolean {\n switch (backend) {\n case 'seatbelt':\n return isSeatbeltAvailable();\n case 'bwrap':\n return isBwrapAvailable();\n case 'none':\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Get the recommended isolation backend for this platform.\n * Returns 'none' if no sandboxing is available.\n */\nexport function getRecommendedIsolation(): IsolationBackend {\n const result = detectIsolation();\n return result.available ? result.backend : 'none';\n}\n","/**\n * Seatbelt (macOS sandbox-exec)\n *\n * macOS built-in sandboxing using sandbox-exec with SBPL profiles.\n *\n * Important: Uses `-p` (inline profile) instead of `-f` (file) because\n * `-f` doesn't work reliably with path filters on modern macOS.\n *\n * Note on macOS sandbox limitations:\n * - `(allow file-read* (subpath ...))` only works WITH a preceding `(allow file-read*)`\n * - So for reads: allow all, then deny specific paths\n * - For writes: allow specific paths with subpath filters\n *\n * Based on the approach used by Claude Code's sandbox-runtime:\n * https://github.com/anthropic-experimental/sandbox-runtime\n */\n\nimport { realpathSync } from 'node:fs';\n\nimport type { NativeSandboxConfig } from './types';\n\n/**\n * Mach services needed for basic operation\n */\nconst MACH_SERVICES = [\n 'com.apple.distributed_notifications@Uv3',\n 'com.apple.logd',\n 'com.apple.system.logger',\n 'com.apple.system.notification_center',\n 'com.apple.system.opendirectoryd.libinfo',\n 'com.apple.system.opendirectoryd.membership',\n 'com.apple.bsd.dirhelper',\n 'com.apple.securityd.xpc',\n 'com.apple.SecurityServer',\n 'com.apple.trustd.agent',\n];\n\n/**\n * SBPL comment that marks a profile as generated by Mastra.\n *\n * Written into every generated profile. A profile file that carries this marker is ours,\n * even when it sits at a path the user configured, so Mastra regenerates it instead of\n * treating it as user-authored SBPL.\n */\nexport const GENERATED_PROFILE_MARKER = '; mastra-generated-profile (regenerated on every start)';\n\n/**\n * Check whether a profile file was generated by Mastra.\n *\n * @param profile - The SBPL profile content read from disk\n * @returns True when the content carries the generated-profile marker\n */\nexport function isGeneratedSeatbeltProfile(profile: string): boolean {\n return profile.includes(GENERATED_PROFILE_MARKER);\n}\n\n/**\n * Escape a path for use in SBPL profile.\n * Uses JSON.stringify for proper escaping.\n */\nfunction escapePath(pathStr: string): string {\n return JSON.stringify(pathStr);\n}\n\nfunction canonicalizePath(pathStr: string): string {\n try {\n return realpathSync(pathStr);\n } catch {\n return pathStr;\n }\n}\n\n/**\n * Generate a seatbelt profile for the given configuration.\n *\n * The profile:\n * - Allows all file reads (can't restrict with subpath on macOS)\n * - Restricts file writes to temp directories, configured writable paths, and the workspace unless read-only\n * - Blocks network unless explicitly allowed\n *\n * @param workspacePath - The workspace directory to sandbox\n * @param config - Additional sandbox configuration\n * @returns The generated SBPL profile content\n */\nexport function generateSeatbeltProfile(workspacePath: string, config: NativeSandboxConfig): string {\n // Fail-closed: seatbelt cannot restrict process-exec, so reject unsupported config\n if (config.allowSystemBinaries === false) {\n throw new Error(\n 'allowSystemBinaries: false is not supported by seatbelt (macOS). ' +\n 'Use bubblewrap on Linux or remove this restriction.',\n );\n }\n\n const lines: string[] = [];\n\n // Version and default deny\n lines.push('(version 1)');\n // Marker comment, so a profile Mastra wrote is still known as ours on a later run.\n lines.push(GENERATED_PROFILE_MARKER);\n lines.push('(deny default (with message \"mastra-sandbox\"))');\n lines.push('');\n\n // Process permissions\n lines.push('; Process permissions');\n lines.push('(allow process-exec)');\n lines.push('(allow process-fork)');\n lines.push('(allow process-info* (target same-sandbox))');\n lines.push('(allow signal (target same-sandbox))');\n lines.push('');\n\n // Mach IPC\n lines.push('; Mach IPC');\n lines.push('(allow mach-lookup');\n for (const service of MACH_SERVICES) {\n lines.push(` (global-name \"${service}\")`);\n }\n lines.push(')');\n lines.push('');\n\n // IPC\n lines.push('; IPC');\n lines.push('(allow ipc-posix-shm)');\n lines.push('(allow ipc-posix-sem)');\n lines.push('');\n\n // User preferences\n lines.push('; User preferences');\n lines.push('(allow user-preference-read)');\n lines.push('');\n\n // sysctl\n lines.push('; sysctl');\n lines.push('(allow sysctl-read)');\n lines.push('');\n\n // Device files\n // `file-ioctl` alone is not enough: opening a device node O_RDWR (as git,\n // ssh, and shell redirections do) also needs `file-write-data`, which the\n // default-deny profile otherwise withholds (write rules below are\n // workspace/temp-scoped).\n lines.push('; Device files');\n for (const device of ['/dev/null', '/dev/zero', '/dev/random', '/dev/urandom', '/dev/tty']) {\n lines.push(`(allow file-ioctl (literal \"${device}\"))`);\n lines.push(`(allow file-write-data (literal \"${device}\"))`);\n }\n lines.push('');\n\n // File read access - allow all reads (macOS limitation: can't use subpath without this)\n lines.push('; File read access (allow all - macOS sandbox limitation)');\n lines.push('(allow file-read*)');\n\n // Add custom read-only paths as additional allows (technically redundant but explicit)\n for (const p of config.readOnlyPaths ?? []) {\n lines.push(`(allow file-read* (subpath ${escapePath(p)}))`);\n }\n lines.push('');\n\n // File write access - restrict to workspace and temp\n lines.push('; File write access (restricted to workspace and temp)');\n\n const canonicalWorkspacePath = canonicalizePath(workspacePath);\n\n // Workspace\n if (!config.readOnly) {\n lines.push(`(allow file-write* (subpath ${escapePath(canonicalWorkspacePath)}))`);\n }\n\n // Temp directories (needed for many operations). When the workspace is read-only,\n // exclude it from these broad allows so temp-backed workspaces remain protected.\n for (const tempPath of ['/private/tmp', '/var/folders', '/private/var/folders']) {\n if (config.readOnly) {\n lines.push(\n `(allow file-write* (require-all (subpath ${escapePath(tempPath)}) (require-not (subpath ${escapePath(canonicalWorkspacePath)}))))`,\n );\n } else {\n lines.push(`(allow file-write* (subpath ${escapePath(tempPath)}))`);\n }\n }\n\n // Custom read-write paths\n for (const p of config.readWritePaths ?? []) {\n lines.push(`(allow file-write* (subpath ${escapePath(canonicalizePath(p))}))`);\n }\n lines.push('');\n\n // Network\n lines.push('; Network');\n if (config.allowNetwork) {\n lines.push('(allow network*)');\n } else {\n lines.push('(deny network* (with message \"mastra-sandbox-network\"))');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Build the command arguments for sandbox-exec.\n *\n * Uses `-p` (inline profile) instead of `-f` (file) because\n * `-f` doesn't work reliably with path filters on modern macOS.\n *\n * @param command - The full shell command string to run\n * @param profile - The SBPL profile content (not a file path)\n * @returns Wrapped command and arguments for sandbox-exec\n */\nexport function buildSeatbeltCommand(command: string, profile: string): { command: string; args: string[] } {\n return {\n command: 'sandbox-exec',\n args: ['-p', profile, 'sh', '-c', command],\n };\n}\n","/**\n * Bubblewrap (Linux bwrap)\n *\n * Linux sandboxing using user namespaces and bind mounts.\n * https://github.com/containers/bubblewrap\n */\n\nimport * as path from 'node:path';\n\nimport type { NativeSandboxConfig } from './types';\n\n/**\n * System paths to mount read-only by default.\n * These are needed for basic command execution.\n */\nconst DEFAULT_READONLY_BINDS = [\n '/usr',\n '/lib',\n '/lib64',\n '/bin',\n '/sbin',\n '/etc/alternatives',\n '/etc/ssl',\n '/etc/ca-certificates',\n '/etc/resolv.conf',\n '/etc/hosts',\n '/etc/passwd',\n '/etc/group',\n '/etc/nsswitch.conf',\n '/etc/ld.so.cache',\n '/etc/localtime',\n];\n\n/**\n * Build the bwrap command arguments for the given configuration.\n *\n * @param command - The full shell command string to run inside the sandbox\n * @param workspacePath - The workspace directory (mounted read-write)\n * @param config - Additional sandbox configuration\n * @returns Wrapped command and arguments for bwrap\n */\nexport function buildBwrapCommand(\n command: string,\n workspacePath: string,\n config: NativeSandboxConfig,\n): { command: string; args: string[] } {\n // If custom bwrap args are provided, use them directly\n if (config.bwrapArgs && config.bwrapArgs.length > 0) {\n return {\n command: 'bwrap',\n args: [...config.bwrapArgs, '--', 'sh', '-c', command],\n };\n }\n\n const bwrapArgs: string[] = [];\n\n // Create new namespaces for isolation\n bwrapArgs.push('--unshare-pid'); // PID namespace (can't see host processes)\n bwrapArgs.push('--unshare-ipc'); // IPC namespace\n bwrapArgs.push('--unshare-uts'); // UTS namespace (separate hostname)\n\n // Network isolation (unless explicitly allowed)\n if (!config.allowNetwork) {\n bwrapArgs.push('--unshare-net');\n }\n\n // Mount a new /proc for the PID namespace\n bwrapArgs.push('--proc', '/proc');\n\n // Mount a tmpfs at /tmp\n bwrapArgs.push('--tmpfs', '/tmp');\n\n // Mount system paths read-only\n for (const path of DEFAULT_READONLY_BINDS) {\n // Use --ro-bind-try to skip paths that don't exist on this system\n bwrapArgs.push('--ro-bind-try', path, path);\n }\n\n // Mount custom read-only paths\n for (const path of config.readOnlyPaths ?? []) {\n bwrapArgs.push('--ro-bind', path, path);\n }\n\n // Allow system binaries by default (node, python, etc.)\n if (config.allowSystemBinaries !== false) {\n // Include the Node.js binary location\n const nodePath = process.execPath;\n const nodeDir = path.dirname(nodePath);\n\n // Mount the node directory if it's not already covered\n if (!DEFAULT_READONLY_BINDS.some(p => nodeDir.startsWith(p))) {\n bwrapArgs.push('--ro-bind', nodeDir, nodeDir);\n }\n\n // Also mount common runtime locations\n bwrapArgs.push('--ro-bind-try', '/opt', '/opt');\n bwrapArgs.push('--ro-bind-try', '/snap', '/snap');\n }\n\n // Mount workspace (read-only or read-write)\n if (config.readOnly) {\n bwrapArgs.push('--ro-bind', workspacePath, workspacePath);\n } else {\n bwrapArgs.push('--bind', workspacePath, workspacePath);\n }\n\n // Mount custom read-write paths\n for (const path of config.readWritePaths ?? []) {\n bwrapArgs.push('--bind', path, path);\n }\n\n // Mount a fresh /dev with the standard device nodes (null, zero, random,\n // urandom, tty, ...). Without it the namespace has no devices at all, so\n // git/ssh and ordinary shell redirections (`2>/dev/null`) fail with ENOENT.\n // IMPORTANT: this must come AFTER all bind loops — in bwrap, later mounts\n // win, and callers commonly pass readOnlyPaths: ['/dev'] as a workaround for\n // this very bug. A bind of /dev is mounted nodev, so it would shadow the\n // device mount and turn the ENOENT into EACCES.\n bwrapArgs.push('--dev', '/dev');\n\n // Set the working directory\n bwrapArgs.push('--chdir', workspacePath);\n\n // Die with parent (clean up if the parent process dies)\n bwrapArgs.push('--die-with-parent');\n\n // Add the command separator and run via sh -c for shell interpretation\n bwrapArgs.push('--', 'sh', '-c', command);\n\n return {\n command: 'bwrap',\n args: bwrapArgs,\n };\n}\n","/**\n * Command Wrapper\n *\n * Wraps commands with the appropriate sandbox backend.\n */\n\nimport { buildBwrapCommand } from './bubblewrap';\nimport { buildSeatbeltCommand, generateSeatbeltProfile } from './seatbelt';\nimport type { IsolationBackend, NativeSandboxConfig } from './types';\n\nexport interface WrappedCommand {\n command: string;\n args: string[];\n}\n\nexport interface WrapCommandOptions {\n /** The isolation backend to use */\n backend: IsolationBackend;\n /** The workspace directory path */\n workspacePath: string;\n /** Pre-generated seatbelt profile content (optional, will be generated if not provided) */\n seatbeltProfile?: string;\n /** Native sandbox configuration */\n config: NativeSandboxConfig;\n}\n\n/**\n * Wrap a command with the appropriate sandbox backend.\n *\n * @param command - The full shell command string to run\n * @param options - Wrapping options\n * @returns The wrapped command and arguments\n *\n * @example\n * ```typescript\n * const wrapped = wrapCommand('node script.js', {\n * backend: 'seatbelt',\n * workspacePath: '/workspace',\n * config: { allowNetwork: false },\n * });\n * // wrapped.command = 'sandbox-exec'\n * // wrapped.args = ['-p', '<profile>', 'sh', '-c', 'node script.js']\n * ```\n */\nexport function wrapCommand(command: string, options: WrapCommandOptions): WrappedCommand {\n switch (options.backend) {\n case 'seatbelt': {\n const profile = options.seatbeltProfile ?? generateSeatbeltProfile(options.workspacePath, options.config);\n return buildSeatbeltCommand(command, profile);\n }\n\n case 'bwrap': {\n return buildBwrapCommand(command, options.workspacePath, options.config);\n }\n\n case 'none':\n default:\n return { command, args: [] };\n }\n}\n","/**\n * Local Sandbox Provider\n *\n * A sandbox implementation that executes commands on the local machine.\n * This is the default sandbox for development and local agents.\n *\n * Supports optional native OS sandboxing:\n * - macOS: Uses seatbelt (sandbox-exec) for filesystem and network isolation\n * - Linux: Uses bubblewrap (bwrap) for namespace isolation\n */\n\nimport { realpathSync } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { RequestContext } from '../../request-context';\n\nimport type { WorkspaceFilesystem } from '../filesystem/filesystem';\nimport { expandTilde } from '../filesystem/fs-utils';\nimport type { FilesystemMountConfig, MountResult } from '../filesystem/mount';\nimport type { ProviderStatus } from '../lifecycle';\nimport type { InstructionsOption } from '../types';\nimport { resolveInstructions } from '../utils';\nimport { IsolationUnavailableError } from './errors';\nimport { LocalProcessManager } from './local-process-manager';\nimport { MastraSandbox } from './mastra-sandbox';\nimport type { MastraSandboxOptions } from './mastra-sandbox';\nimport type { MountManager } from './mount-manager';\nimport type { IsolationBackend, NativeSandboxConfig } from './native-sandbox';\nimport {\n detectIsolation,\n isIsolationAvailable,\n generateSeatbeltProfile,\n isGeneratedSeatbeltProfile,\n wrapCommand,\n} from './native-sandbox';\nimport type { SandboxCloneOptions } from './sandbox';\nimport type { SandboxInfo } from './types';\n\n// =============================================================================\n// Mount Path Validation\n// =============================================================================\n\n/**\n * Directory for mount marker files used to detect config changes across restarts.\n *\n * Resolved lazily so `os.tmpdir()` is never invoked at module-load time. The\n * Agent/evals runtime (which transitively imports this module) is bundled into\n * the Studio client, where `node:os` is shimmed to an empty object and\n * `os.tmpdir` is `undefined`. Evaluating it at import time crashes Studio boot.\n * See https://github.com/mastra-ai/mastra/issues/18519.\n */\nexport function getMarkerDir(): string {\n return path.join(os.tmpdir(), '.mastra-mounts');\n}\n\n/** Allowlist pattern for mount paths — absolute path with safe characters only. */\nconst SAFE_MOUNT_PATH = /^\\/[a-zA-Z0-9_.\\-/]+$/;\n\nfunction validateMountPath(mountPath: string): void {\n if (!SAFE_MOUNT_PATH.test(mountPath)) {\n throw new Error(\n `Invalid mount path: ${mountPath}. Must be an absolute path with alphanumeric, dash, dot, underscore, or slash characters only.`,\n );\n }\n const segments = mountPath.split('/').filter(Boolean);\n if (segments.length === 0) {\n throw new Error(`Invalid mount path: ${mountPath}. Root path \"/\" is not allowed.`);\n }\n if (segments.some(seg => seg === '.' || seg === '..')) {\n throw new Error(`Invalid mount path: ${mountPath}. Path segments cannot be \".\" or \"..\".`);\n }\n}\n\n/** Canonicalize mount path so `/data`, `/data/`, `//data` all resolve to `/data`. */\nfunction normalizeMountPath(mountPath: string): string {\n return `/${mountPath.split('/').filter(Boolean).join('/')}`;\n}\n\n// =============================================================================\n// Local Sandbox\n// =============================================================================\n\n/**\n * Local sandbox provider configuration.\n */\nexport interface LocalSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Unique identifier for this sandbox instance */\n id?: string;\n /** Working directory for command execution */\n workingDirectory?: string;\n /**\n * Environment variables to set for command execution.\n * PATH is included by default unless overridden (needed for finding executables).\n * Other host environment variables are not inherited unless explicitly passed.\n *\n * @example\n * ```typescript\n * // Default - only PATH is available\n * env: undefined\n *\n * // Add specific variables\n * env: { NODE_ENV: 'production', HOME: process.env.HOME }\n *\n * // Full host environment (less secure)\n * env: process.env\n * ```\n */\n env?: NodeJS.ProcessEnv;\n /**\n * Encoding used to decode command stdout/stderr (any WHATWG encoding label, e.g. 'gbk').\n * Useful on Windows systems whose native commands emit a legacy code page. Default: 'utf-8'.\n */\n outputEncoding?: string;\n /**\n * Default timeout for executeCommand in ms (default: 30000).\n * Use 0 to disable. Does not apply to processes.spawn.\n */\n timeout?: number;\n /**\n * Isolation backend for sandboxed execution.\n * - 'none': No sandboxing (direct execution on host) - default\n * - 'seatbelt': macOS sandbox-exec (built-in on macOS)\n * - 'bwrap': Linux bubblewrap (requires installation)\n *\n * Use `LocalSandbox.detectIsolation()` to get the recommended backend.\n * @default 'none'\n */\n isolation?: IsolationBackend;\n /**\n * Configuration for native sandboxing.\n * Only used when isolation is 'seatbelt' or 'bwrap'.\n */\n nativeSandbox?: NativeSandboxConfig;\n /**\n * Custom instructions that override the default instructions\n * returned by `getInstructions()`.\n *\n * - `string` — Fully replaces the default instructions.\n * Pass an empty string to suppress instructions entirely.\n * - `(opts) => string` — Receives the default instructions and\n * optional request context so you can extend or customise per-request.\n */\n instructions?: InstructionsOption;\n /**\n * Named checkpoint to seed the working directory from on `start()` and to\n * persist to on `snapshot()`. When set and a matching checkpoint exists\n * under `checkpointsDirectory`, an empty/missing working directory is seeded\n * from it before start. A missing checkpoint falls back to a normal empty\n * working directory.\n */\n checkpointName?: string;\n /**\n * Fallback checkpoint used to seed the working directory when\n * `checkpointName` has no stored checkpoint yet (e.g. a repo-level warm base\n * image for a brand-new session). Boot-only: `snapshot()` keeps writing to\n * `checkpointName`.\n */\n seedCheckpointName?: string;\n /**\n * Directory where named checkpoints are stored.\n * Defaults to `<parent of workingDirectory>/.checkpoints`.\n */\n checkpointsDirectory?: string;\n}\n\n/**\n * Executes workspace commands on the host machine for development and trusted\n * local execution. Isolation requires explicit configuration.\n *\n * @example\n * ```typescript\n * import { Workspace, LocalSandbox } from '@mastra/core/workspace';\n *\n * const workspace = new Workspace({\n * sandbox: new LocalSandbox({ workingDirectory: './my-workspace' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/core/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Local sandbox documentation](https://mastra.ai/reference/workspace/local-sandbox)\n * if packaged docs are unavailable.\n */\nexport class LocalSandbox extends MastraSandbox<string> {\n readonly id: string;\n readonly name = 'LocalSandbox';\n readonly provider = 'local';\n\n status: ProviderStatus = 'pending';\n\n readonly isolation: IsolationBackend;\n declare readonly processes: LocalProcessManager;\n declare readonly mounts: MountManager;\n private readonly env: NodeJS.ProcessEnv;\n private readonly _outputEncoding?: string;\n private readonly timeout: number;\n private _nativeSandboxConfig: NativeSandboxConfig;\n /**\n * SBPL the user wrote, read from `seatbeltProfilePath` at start. Set only when that file\n * already existed and does not carry our generated-profile marker. While it is undefined,\n * `wrapCommand()` generates the profile from the live `_nativeSandboxConfig` on every call,\n * so the profile always tracks the allowlist.\n */\n private _customSeatbeltProfile?: string;\n /** Where the profile file lives on disk: the configured path, or one we generated. */\n private _seatbeltProfilePath?: string;\n private _sandboxFolderPath?: string;\n private readonly _createdAt: Date;\n private readonly _instructionsOverride?: InstructionsOption;\n private _activeMountPaths: Set<string> = new Set();\n /** Snapshot of `readWritePaths` from ctor; entries here are never removed on unmount. */\n private readonly _initialReadWritePaths: Set<string>;\n /** Refcount for isolation paths added by mounts (not present in `_initialReadWritePaths`). */\n private _mountIsolationRefCount = new Map<string, number>();\n /** Normalized mount path → canonical isolation path recorded for that mount. */\n private _mountPathToIsolationPath = new Map<string, string>();\n /** Named checkpoint to seed from on start and persist to on snapshot. */\n private readonly _checkpointName?: string;\n /** Boot-only fallback checkpoint used when `_checkpointName` has no state. */\n private readonly _seedCheckpointName?: string;\n /** Directory where named checkpoints live. */\n private readonly _checkpointsDirectory: string;\n /** Chains snapshot() calls so concurrent captures never interleave. */\n private _snapshotChain: Promise<void> = Promise.resolve();\n\n /**\n * The effective working directory. Narrowed to `string`: the constructor\n * always computes a value (the option, expanded, or `<cwd>/.sandbox`), so\n * unlike the base getter this never returns `undefined`.\n */\n override get workingDirectory(): string {\n return this._workingDirectory!;\n }\n\n constructor(options: LocalSandboxOptions = {}) {\n // Validate isolation backend before super (fail fast)\n const requestedIsolation = options.isolation ?? 'none';\n if (requestedIsolation === 'seatbelt' && process.platform === 'win32') {\n throw new IsolationUnavailableError('seatbelt', 'Seatbelt isolation is only supported on macOS, not Windows.');\n }\n if (requestedIsolation !== 'none' && !isIsolationAvailable(requestedIsolation)) {\n const detection = detectIsolation();\n throw new IsolationUnavailableError(requestedIsolation, detection.message);\n }\n\n super({\n ...options,\n name: 'LocalSandbox',\n processes: new LocalProcessManager({ env: options.env ?? {}, outputEncoding: options.outputEncoding }),\n });\n\n this.timeout = options.timeout ?? 30_000;\n this.defaultCommandTimeout = this.timeout;\n\n this.id = options.id ?? this.generateId();\n this._createdAt = new Date();\n this.setWorkingDirectory(expandTilde(options.workingDirectory ?? path.join(process.cwd(), '.sandbox')));\n this.env = options.env ?? {};\n this._outputEncoding = options.outputEncoding;\n this._nativeSandboxConfig = {\n ...options.nativeSandbox,\n readWritePaths: [...(options.nativeSandbox?.readWritePaths ?? [])],\n readOnlyPaths: [...(options.nativeSandbox?.readOnlyPaths ?? [])],\n };\n this._initialReadWritePaths = new Set(this._nativeSandboxConfig.readWritePaths ?? []);\n this.isolation = requestedIsolation;\n this._instructionsOverride = options.instructions;\n this._checkpointName = options.checkpointName;\n this._seedCheckpointName = options.seedCheckpointName;\n this._checkpointsDirectory = options.checkpointsDirectory\n ? expandTilde(options.checkpointsDirectory)\n : path.join(path.dirname(this.workingDirectory), '.checkpoints');\n }\n\n // ---------------------------------------------------------------------------\n // Cloning\n // ---------------------------------------------------------------------------\n\n /**\n * Construct a sibling `LocalSandbox` that inherits this sandbox's\n * configuration (isolation, native sandbox config, instructions) with\n * per-instance overrides.\n *\n * Performs no I/O — the sandbox clone creates its working directory on its\n * own `start()`. `sandboxId` and `idleTimeoutMinutes` have no local\n * equivalent and are ignored: local sandboxes reattach by logical `id` and\n * have no provider-managed idle teardown.\n */\n clone(options: SandboxCloneOptions = {}): LocalSandbox {\n return new LocalSandbox({\n ...(options.id !== undefined && { id: options.id }),\n workingDirectory: options.workingDirectory ?? this.workingDirectory,\n env: options.env ?? this.env,\n timeout: this.timeout,\n isolation: this.isolation,\n outputEncoding: this._outputEncoding,\n nativeSandbox: {\n ...this._nativeSandboxConfig,\n readWritePaths: [...this._initialReadWritePaths],\n readOnlyPaths: [...(this._nativeSandboxConfig.readOnlyPaths ?? [])],\n },\n ...(this._instructionsOverride !== undefined && { instructions: this._instructionsOverride }),\n ...((options.checkpointName ?? this._checkpointName) !== undefined && {\n checkpointName: options.checkpointName ?? this._checkpointName,\n }),\n ...((options.seedCheckpointName ?? this._seedCheckpointName) !== undefined && {\n seedCheckpointName: options.seedCheckpointName ?? this._seedCheckpointName,\n }),\n checkpointsDirectory: this._checkpointsDirectory,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Acquisition primitives (base-orchestrated start): an existing working\n * directory is the \"found sandbox\" — reattaching reports `outcome: 'connected'`,\n * a missing directory means a fresh sandbox (`outcome: 'created'`).\n *\n * This stat and the `mkdir` in `create()` are not atomic, so `'created'` is\n * best-effort: two processes starting on the same working directory can both\n * report it. Keep onStart setup idempotent.\n */\n protected override async find(): Promise<string | undefined> {\n try {\n await fs.stat(this.workingDirectory);\n return this.workingDirectory;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw err;\n }\n return undefined;\n }\n }\n\n protected override async connect(_handle: string): Promise<void> {\n await this._prepareWorkspace();\n }\n\n protected override async create(): Promise<void> {\n await this._prepareWorkspace();\n }\n\n /**\n * Shared start body for both branches: ensure the working directory\n * exists, seed it from a checkpoint when empty, and set up the seatbelt\n * profile on macOS. Everything here is idempotent.\n */\n private async _prepareWorkspace(): Promise<void> {\n this.logger.debug('Starting sandbox', {\n workingDirectory: this.workingDirectory,\n isolation: this.isolation,\n });\n\n await fs.mkdir(this.workingDirectory, { recursive: true });\n\n await this._seedFromCheckpoint();\n\n // Set up seatbelt profile for macOS sandboxing\n if (this.isolation === 'seatbelt') {\n const userProvidedPath = this._nativeSandboxConfig.seatbeltProfilePath;\n\n if (userProvidedPath) {\n // User provided a custom path\n this._seatbeltProfilePath = userProvidedPath;\n\n // Check if file exists at user's path\n let existingProfile: string | undefined;\n try {\n existingProfile = await fs.readFile(userProvidedPath, 'utf-8');\n } catch (err: unknown) {\n if (err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw err;\n }\n }\n\n if (existingProfile !== undefined && !isGeneratedSeatbeltProfile(existingProfile)) {\n // The user wrote this SBPL. Keep it and pass it to sandbox-exec exactly as written.\n this._customSeatbeltProfile = existingProfile;\n } else {\n // The file is missing, or it carries our marker from an earlier run. Either way the\n // profile is ours, so generate it again and clear `_customSeatbeltProfile`: it must\n // keep tracking the allowlist that mounts change. Clearing matters when this instance\n // was started before with a user-authored profile that has since been removed or taken\n // over by us, because `stop()` leaves the cached profile in place for a later `start()`.\n this._customSeatbeltProfile = undefined;\n const generatedProfile = generateSeatbeltProfile(this.workingDirectory, this._nativeSandboxConfig);\n // Ensure parent directory exists\n await fs.mkdir(path.dirname(userProvidedPath), { recursive: true });\n await fs.writeFile(userProvidedPath, generatedProfile, 'utf-8');\n }\n } else {\n // No custom path, use default location\n const generatedProfile = generateSeatbeltProfile(this.workingDirectory, this._nativeSandboxConfig);\n\n // Generate a deterministic hash from workspace path and config\n // This allows identical sandboxes to share profiles while preventing collisions\n const configHash = Buffer.from(\n await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(this.workingDirectory + JSON.stringify(this._nativeSandboxConfig)),\n ),\n )\n .toString('hex')\n .slice(0, 8);\n\n // Write profile to .sandbox-profiles/ in cwd (outside working directory)\n // This prevents sandboxed processes from reading/modifying their own security profile\n this._sandboxFolderPath = path.join(process.cwd(), '.sandbox-profiles');\n await fs.mkdir(this._sandboxFolderPath, { recursive: true });\n this._seatbeltProfilePath = path.join(this._sandboxFolderPath, `seatbelt-${configHash}.sb`);\n await fs.writeFile(this._seatbeltProfilePath, generatedProfile, 'utf-8');\n }\n }\n\n this.logger.debug('Sandbox started', { workingDirectory: this.workingDirectory });\n }\n\n // ---------------------------------------------------------------------------\n // Checkpoints\n // ---------------------------------------------------------------------------\n\n /** LocalSandbox persists real filesystem-backed checkpoints. */\n readonly supportsCheckpoints = true;\n\n /** Resolve the on-disk directory for a named checkpoint, rejecting unsafe names. */\n private _checkpointPath(name: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.includes('..')) {\n throw new Error(`Invalid checkpoint name: ${name}`);\n }\n return path.join(this._checkpointsDirectory, name);\n }\n\n /**\n * Seed an empty/missing working directory from the configured checkpoint.\n * Missing checkpoint or already-populated workdir → no-op (normal start).\n */\n private async _seedFromCheckpoint(): Promise<void> {\n if (!this._checkpointName && !this._seedCheckpointName) return;\n\n // Only seed an empty working directory; a populated one wins.\n const entries = await fs.readdir(this.workingDirectory).catch(() => []);\n if (entries.length > 0) return;\n\n // Prefer the primary checkpoint; fall back to the boot-only seed checkpoint.\n const candidates = [this._checkpointName, this._seedCheckpointName].filter(\n (name): name is string => name !== undefined,\n );\n candidates: for (const name of candidates) {\n const checkpointDir = this._checkpointPath(name);\n if (!(await this._checkpointIdentity(checkpointDir))) {\n // Missing checkpoint → try the next candidate (same contract as provider 404).\n continue;\n }\n\n this.logger.debug('Seeding working directory from checkpoint', {\n checkpointName: name,\n checkpointDir,\n });\n // `fs.cp` is not a point-in-time copy: a concurrent `_captureCheckpoint`\n // can swap the checkpoint directory mid-copy, mixing one version's entry\n // list with another's file contents. Pin the directory's identity and\n // retry the whole copy until it stays unchanged across it.\n for (let attempt = 0; attempt < 5; attempt++) {\n const before = await this._checkpointIdentity(checkpointDir);\n if (!before) continue candidates;\n try {\n await fs.cp(checkpointDir, this.workingDirectory, { recursive: true });\n if ((await this._checkpointIdentity(checkpointDir)) === before) return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n // A failed wipe must throw: copying over leftovers would pass the identity check with mixed contents.\n await fs.rm(this.workingDirectory, { recursive: true, force: true });\n await fs.mkdir(this.workingDirectory, { recursive: true });\n }\n throw new Error(`Checkpoint \"${name}\" kept changing while seeding the working directory`);\n }\n }\n\n /**\n * Identity of the directory currently at `checkpointDir`, or undefined if no\n * directory is there. Retries briefly to cover the instant in\n * `_captureCheckpoint` where the old checkpoint has been renamed away but the\n * replacement has not yet been renamed into place. The window is two atomic\n * renames, so a couple of short retries close it.\n */\n private async _checkpointIdentity(checkpointDir: string): Promise<string | undefined> {\n for (let attempt = 0; attempt < 3; attempt++) {\n if (attempt > 0) await new Promise(resolve => setTimeout(resolve, 25));\n try {\n const stat = await fs.stat(checkpointDir, { bigint: true });\n return stat.isDirectory() ? `${stat.dev}:${stat.ino}:${stat.ctimeNs}` : undefined;\n } catch {\n // Missing right now — may be mid-swap; retry.\n }\n }\n return undefined;\n }\n\n /**\n * Persist the working directory as the configured named checkpoint.\n * Copies to a temp sibling, then swaps it into place with rename so a\n * concurrent boot always observes a complete checkpoint. No-op when no\n * checkpoint name is set.\n */\n async snapshot(): Promise<void> {\n if (!this._checkpointName) return;\n const run = this._snapshotChain.then(() => this._captureCheckpoint(this._checkpointName!));\n // Keep the chain alive even if this capture fails.\n this._snapshotChain = run.catch(() => {});\n return run;\n }\n\n private async _captureCheckpoint(name: string): Promise<void> {\n const target = this._checkpointPath(name);\n await fs.mkdir(this._checkpointsDirectory, { recursive: true });\n const tmp = path.join(\n this._checkpointsDirectory,\n `.tmp-${name}-${Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(6))).toString('hex')}`,\n );\n const backup = path.join(\n this._checkpointsDirectory,\n `.bak-${name}-${Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(6))).toString('hex')}`,\n );\n let targetMoved = false;\n try {\n await fs.cp(this.workingDirectory, tmp, { recursive: true });\n try {\n await fs.rename(target, backup);\n targetMoved = true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n await fs.rename(tmp, target);\n } catch (error) {\n await fs.rm(tmp, { recursive: true, force: true }).catch(() => {});\n if (targetMoved) {\n await fs.rename(backup, target).catch(() => {});\n }\n throw error;\n }\n if (targetMoved) {\n await fs.rm(backup, { recursive: true, force: true }).catch(() => {});\n }\n this.logger.debug('Captured checkpoint', { checkpointName: name, target });\n }\n\n /**\n * Stop the local sandbox.\n * Kills background processes and unmounts all active mounts. Unlike remote\n * providers, a local sandbox has no suspend/resume — its background\n * processes ARE the runtime state, so a stopped sandbox must not leave them\n * running. Files in the working directory are untouched and `start()` works\n * again afterwards.\n * Status management is handled by the base class.\n */\n async stop(): Promise<void> {\n this.logger.debug('Stopping sandbox', { workingDirectory: this.workingDirectory });\n\n // Kill all background processes — \"stopped\" means not running.\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n\n // Unmount all active mounts (best-effort)\n for (const mountPath of [...this._activeMountPaths]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Best-effort unmount\n }\n }\n }\n\n /**\n * Destroy the local sandbox and clean up resources.\n * Unmounts all filesystems, clears mount state, and cleans up seatbelt profile.\n * Status management is handled by the base class.\n */\n async destroy(): Promise<void> {\n this.logger.debug('Destroying sandbox', { workingDirectory: this.workingDirectory });\n\n // Kill all background processes\n const procs = await this.processes.list();\n await Promise.all(procs.map(p => this.processes.kill(p.pid)));\n\n // Unmount all active mounts\n for (const mountPath of [...this._activeMountPaths]) {\n try {\n await this.unmount(mountPath);\n } catch {\n // Ignore errors during cleanup\n }\n }\n this._activeMountPaths.clear();\n this.mounts.clear();\n\n // Clean up the profile file only when we chose its location. A path the user configured\n // belongs to the user, so never unlink it.\n if (this._seatbeltProfilePath && !this._nativeSandboxConfig.seatbeltProfilePath) {\n try {\n await fs.unlink(this._seatbeltProfilePath);\n } catch {\n // Ignore errors if file doesn't exist\n }\n }\n this._seatbeltProfilePath = undefined;\n this._customSeatbeltProfile = undefined;\n\n // Try to remove .sandbox folder if empty\n if (this._sandboxFolderPath) {\n try {\n await fs.rmdir(this._sandboxFolderPath);\n } catch {\n // Ignore errors - folder may not be empty or may not exist\n }\n this._sandboxFolderPath = undefined;\n }\n }\n\n /** @deprecated Use `status === 'running'` instead. */\n async isReady(): Promise<boolean> {\n return this.status === 'running';\n }\n\n async getInfo(): Promise<SandboxInfo> {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n createdAt: this._createdAt,\n resources: {\n memoryMB: Math.round(os.totalmem() / 1024 / 1024),\n cpuCores: os.cpus().length,\n },\n metadata: {\n workingDirectory: this.workingDirectory,\n platform: os.platform(),\n nodeVersion: process.version,\n isolation: this.isolation,\n isolationConfig:\n this.isolation !== 'none'\n ? {\n allowNetwork: this._nativeSandboxConfig.allowNetwork ?? false,\n readOnlyPaths: this._nativeSandboxConfig.readOnlyPaths,\n readWritePaths: this._nativeSandboxConfig.readWritePaths,\n }\n : undefined,\n },\n };\n }\n\n getInstructions(opts?: { requestContext?: RequestContext }): string {\n return resolveInstructions(this._instructionsOverride, () => this._getDefaultInstructions(), opts?.requestContext);\n }\n\n private _getDefaultInstructions(): string {\n return `Local command execution. Working directory: \"${this.workingDirectory}\".`;\n }\n\n // ---------------------------------------------------------------------------\n // Internal Utils\n // ---------------------------------------------------------------------------\n\n private generateId(): string {\n return `local-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n /**\n * Build the environment object for execution.\n * Always includes PATH by default (needed for finding executables).\n * Merges the sandbox's configured env with any additional env from the command.\n * @internal Used by LocalProcessManager.\n */\n buildEnv(additionalEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return {\n PATH: process.env.PATH, // Always include PATH for finding executables\n ...this.env,\n ...additionalEnv,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Mount Support\n // ---------------------------------------------------------------------------\n\n /**\n * Mount a filesystem at a path on the local host.\n *\n * - **local** — Creates a symlink from `<workingDir>/<mount>` to the basePath.\n *\n * Virtual mount paths (e.g. `/s3`) are resolved under the sandbox's workingDirectory.\n * Other mount types can be handled via the `onMount` hook.\n */\n async mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult> {\n validateMountPath(mountPath);\n mountPath = normalizeMountPath(mountPath);\n\n // Resolve virtual mount path to host filesystem path\n const hostPath = this.resolveHostPath(mountPath);\n\n this.logger.debug('Mounting', { mountPath, hostPath });\n\n // Get mount config\n const config = filesystem.getMountConfig?.() as FilesystemMountConfig | undefined;\n if (!config) {\n const error = `Filesystem \"${filesystem.id}\" does not provide a mount config`;\n this.logger.error('Filesystem does not provide a mount config', { filesystemId: filesystem.id });\n this.mounts.set(mountPath, { filesystem, state: 'error', error });\n return { success: false, mountPath, error };\n }\n\n // Check if already mounted with matching config\n const existingMount = await this.checkExistingMount(hostPath, config);\n if (existingMount === 'matching') {\n this.logger.debug('Detected existing mount with correct config, skipping', {\n provider: filesystem.provider,\n filesystemId: filesystem.id,\n hostPath,\n });\n this.mounts.set(mountPath, { filesystem, state: 'mounted', config });\n this._activeMountPaths.add(mountPath);\n this.addMountPathToIsolation(mountPath, hostPath);\n return { success: true, mountPath };\n } else if (existingMount === 'foreign') {\n // Something is already mounted/symlinked here but we didn't create it — refuse to touch it\n const error = `Cannot mount at ${hostPath}: path is already occupied by an existing mount or symlink that was not created by Mastra. Unmount it manually or use a different mount path.`;\n this.logger.error('Mount path occupied by foreign mount or symlink', { hostPath });\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n } else if (existingMount === 'mismatched') {\n this.logger.debug('Config mismatch on our mount, unmounting to re-mount with new config');\n await this.unmount(mountPath);\n }\n\n this.logger.debug('Mount config type', { type: config.type });\n\n // Reject unsupported types early — before any filesystem work\n if (config.type !== 'local') {\n const error = `Unsupported mount type: ${(config as FilesystemMountConfig).type}`;\n this.mounts.set(mountPath, { filesystem, state: 'unsupported', config, error });\n return { success: false, mountPath, error };\n }\n\n this.mounts.set(mountPath, { filesystem, state: 'mounting', config });\n\n // Check if host path exists and would conflict with the symlink\n try {\n const entries = await fs.readdir(hostPath);\n if (entries.length > 0) {\n const error = `Cannot mount at ${hostPath}: directory exists and is not empty. Mounting would hide existing files. Use a different path or empty the directory first.`;\n this.logger.error('Cannot mount at non-empty directory', { hostPath });\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n // Empty directory from a previous failed attempt — remove so symlink can be created\n await fs.rmdir(hostPath);\n } catch (err: unknown) {\n const code = err instanceof Error && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;\n if (code === 'ENOTDIR') {\n const error = `Cannot mount at ${hostPath}: path is a regular file. Use a different mount path or remove the file first.`;\n this.logger.error('Cannot mount at path that is a regular file', { hostPath });\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error });\n return { success: false, mountPath, error };\n }\n // ENOENT: path doesn't exist yet — exactly what we want for symlink creation\n }\n\n // Create symlink: ensure parent directory exists, then link\n const localConfig = config as { type: 'local'; basePath: string };\n try {\n await fs.mkdir(path.dirname(hostPath), { recursive: true });\n await fs.symlink(localConfig.basePath, hostPath);\n this.logger.debug('Symlinked local mount', { hostPath, basePath: localConfig.basePath });\n } catch (error) {\n this.logger.error('Error mounting filesystem', {\n provider: filesystem.provider,\n filesystemId: filesystem.id,\n hostPath,\n error,\n });\n this.mounts.set(mountPath, { filesystem, state: 'error', config, error: String(error) });\n\n return { success: false, mountPath, error: String(error) };\n }\n\n // Mark as mounted\n this.mounts.set(mountPath, { filesystem, state: 'mounted', config });\n this._activeMountPaths.add(mountPath);\n\n // Write marker file\n await this.writeMarkerFile(mountPath, hostPath);\n\n // Dynamically add host path to isolation allowlist\n this.addMountPathToIsolation(mountPath, hostPath);\n\n this.logger.debug('Mounted', { mountPath, hostPath });\n return { success: true, mountPath };\n }\n\n /**\n * Unmount a filesystem from a path.\n */\n async unmount(mountPath: string): Promise<void> {\n validateMountPath(mountPath);\n mountPath = normalizeMountPath(mountPath);\n\n const hostPath = this.resolveHostPath(mountPath);\n\n this.logger.debug('Unmounting', { mountPath, hostPath });\n\n this.removeMountIsolationForPath(mountPath);\n\n // Check if it's a symlink — symlinks are just unlinked, not FUSE-unmounted\n let isSymlink = false;\n try {\n const stats = await fs.lstat(hostPath);\n isSymlink = stats.isSymbolicLink();\n } catch {\n // Path doesn't exist — proceed with cleanup\n }\n\n this.mounts.delete(mountPath);\n this._activeMountPaths.delete(mountPath);\n\n // Clean up marker file\n const filename = this.mounts.markerFilename(hostPath);\n const markerPath = path.join(getMarkerDir(), filename);\n try {\n await fs.unlink(markerPath);\n } catch {\n // Ignore if doesn't exist\n }\n\n // Remove symlink\n if (isSymlink) {\n try {\n await fs.unlink(hostPath);\n this.logger.debug('Unmounted and removed symlink', { hostPath });\n } catch {\n this.logger.debug('Could not remove symlink', { hostPath });\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Mount Helpers (private)\n // ---------------------------------------------------------------------------\n\n /**\n * Write a marker file for detecting config changes.\n * Uses hostPath (resolved OS path) for the marker filename and content,\n * and mountPath (virtual path) for looking up the entry.\n */\n private async writeMarkerFile(mountPath: string, hostPath: string): Promise<void> {\n const entry = this.mounts.get(mountPath);\n if (!entry?.configHash) return;\n\n const filename = this.mounts.markerFilename(hostPath);\n const markerContent = `${hostPath}|${entry.configHash}`;\n const markerFilePath = path.join(getMarkerDir(), filename);\n\n try {\n await fs.mkdir(getMarkerDir(), { recursive: true });\n await fs.writeFile(markerFilePath, markerContent, 'utf-8');\n } catch {\n this.logger.debug('Could not write marker file', { markerFilePath });\n }\n }\n\n /**\n * Check if a path is already mounted and if the config matches.\n * Uses hostPath (resolved OS path) for checking the actual mount point.\n */\n private async checkExistingMount(\n hostPath: string,\n newConfig: FilesystemMountConfig,\n ): Promise<'not_mounted' | 'matching' | 'mismatched' | 'foreign'> {\n // Check if it's a symlink (local mount)\n try {\n const stats = await fs.lstat(hostPath);\n if (stats.isSymbolicLink() && newConfig.type === 'local') {\n // Validate symlink target matches config before checking marker\n const linkTarget = await fs.readlink(hostPath).catch(() => null);\n const resolvedTarget = linkTarget ? path.resolve(path.dirname(hostPath), linkTarget) : null;\n const expectedTarget = path.resolve((newConfig as { type: 'local'; basePath: string }).basePath);\n if (!resolvedTarget || resolvedTarget !== expectedTarget) {\n // Symlink exists but points somewhere else — check if we created it\n return (await this.hasMarkerFile(hostPath)) ? 'mismatched' : 'foreign';\n }\n // Symlink target matches — validate via marker file\n return this.checkMarkerFile(hostPath, newConfig);\n } else if (stats.isSymbolicLink()) {\n // Symlink exists for a non-local config — check if we created it\n return (await this.hasMarkerFile(hostPath)) ? 'mismatched' : 'foreign';\n }\n } catch {\n // Not a symlink or doesn't exist — treat as not mounted\n }\n return 'not_mounted';\n }\n\n /**\n * Check if a marker file exists for a given host path (regardless of content).\n * Returns true if we previously created a mount here.\n */\n private async hasMarkerFile(hostPath: string): Promise<boolean> {\n const filename = this.mounts.markerFilename(hostPath);\n const markerPath = path.join(getMarkerDir(), filename);\n try {\n await fs.access(markerPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Check if a marker file matches the given config.\n * Returns 'matching' if hash matches, 'mismatched' if hash differs,\n * or 'foreign' if no marker exists (we didn't create this mount).\n */\n private async checkMarkerFile(\n hostPath: string,\n newConfig: FilesystemMountConfig,\n ): Promise<'matching' | 'mismatched' | 'foreign'> {\n const filename = this.mounts.markerFilename(hostPath);\n const markerPath = path.join(getMarkerDir(), filename);\n\n try {\n const content = await fs.readFile(markerPath, 'utf-8');\n const parsed = this.mounts.parseMarkerContent(content.trim());\n\n if (!parsed) {\n // Marker exists but is malformed — we created it but can't verify, treat as ours\n return 'mismatched';\n }\n\n const newConfigHash = this.mounts.computeConfigHash(newConfig);\n this.logger.debug('Marker check', { storedHash: parsed.configHash, newConfigHash });\n\n if (parsed.path === hostPath && parsed.configHash === newConfigHash) {\n return 'matching';\n }\n\n return 'mismatched';\n } catch {\n // No marker file — this mount was not created by us\n return 'foreign';\n }\n }\n\n /**\n * Dynamically add a mount path to the sandbox isolation allowlist.\n *\n * - Seatbelt: pushes to readWritePaths (wrapCommand reads config each call)\n * - Bwrap: pushes to readWritePaths (buildBwrapCommand reads config each call)\n *\n * Local mounts are symlinks under `workingDirectory`. Bubblewrap cannot\n * `--bind` a symlink (it fails with \"Unable to mount source on destination\"),\n * so we store the canonical path (`realpath`) of the mount point — the same\n * directory the symlink refers to.\n */\n private addMountPathToIsolation(mountPath: string, hostPath: string): void {\n if (this.isolation === 'none') return;\n\n const normMount = normalizeMountPath(mountPath);\n if (this._mountPathToIsolationPath.has(normMount)) {\n return;\n }\n\n let isolationPath = hostPath;\n try {\n isolationPath = realpathSync(hostPath);\n } catch {\n // Symlink not visible yet or race; keep literal path for best-effort allowlist\n }\n\n if (!this._nativeSandboxConfig.readWritePaths) {\n this._nativeSandboxConfig = { ...this._nativeSandboxConfig, readWritePaths: [] };\n }\n const paths = this._nativeSandboxConfig.readWritePaths!;\n\n if (!paths.includes(isolationPath)) {\n paths.push(isolationPath);\n }\n if (!this._initialReadWritePaths.has(isolationPath)) {\n this._mountIsolationRefCount.set(isolationPath, (this._mountIsolationRefCount.get(isolationPath) ?? 0) + 1);\n }\n this._mountPathToIsolationPath.set(normMount, isolationPath);\n // Both backends read config.readWritePaths on every wrapCommand() call, so no extra work needed\n }\n\n /**\n * Reverse {@link addMountPathToIsolation}: drop refcounted paths from the allowlist on unmount\n * while preserving user-provided `readWritePaths` from construction.\n */\n private removeMountIsolationForPath(mountPath: string): void {\n if (this.isolation === 'none') return;\n\n const normMount = normalizeMountPath(mountPath);\n const isolationPath = this._mountPathToIsolationPath.get(normMount);\n if (isolationPath === undefined) {\n return;\n }\n this._mountPathToIsolationPath.delete(normMount);\n\n if (this._initialReadWritePaths.has(isolationPath)) {\n return;\n }\n\n const prev = this._mountIsolationRefCount.get(isolationPath) ?? 0;\n const next = prev - 1;\n if (next <= 0) {\n this._mountIsolationRefCount.delete(isolationPath);\n const paths = this._nativeSandboxConfig.readWritePaths;\n if (paths) {\n const idx = paths.indexOf(isolationPath);\n if (idx !== -1) {\n paths.splice(idx, 1);\n }\n }\n } else {\n this._mountIsolationRefCount.set(isolationPath, next);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Isolation\n // ---------------------------------------------------------------------------\n\n /**\n * Resolve a virtual mount path to a host filesystem path.\n *\n * Virtual paths like \"/s3\" become `<workingDir>/s3`. This differs from E2B\n * where root-level paths like `/s3` are used directly (E2B runs in a VM with sudo).\n * LocalSandbox runs on the host, so mounts are scoped under workingDirectory.\n */\n private resolveHostPath(mountPath: string): string {\n return path.join(this.workingDirectory, mountPath.replace(/^\\/+/, ''));\n }\n\n /**\n * Wrap a command with the configured isolation backend.\n * @internal Used by LocalProcessManager for background process isolation.\n */\n wrapCommandForIsolation(command: string): { command: string; args: string[] } {\n if (this.isolation === 'none') {\n return { command, args: [] };\n }\n\n return wrapCommand(command, {\n backend: this.isolation,\n workspacePath: this.workingDirectory,\n // Undefined unless the user wrote their own profile file. wrapCommand() then generates\n // one from the current config, so mounts added after start() are in the allowlist.\n seatbeltProfile: this._customSeatbeltProfile,\n config: this._nativeSandboxConfig,\n });\n }\n\n /**\n * Detect the best available isolation backend for this platform.\n * Returns detection result with backend recommendation and availability.\n *\n * @example\n * ```typescript\n * const result = LocalSandbox.detectIsolation();\n * const sandbox = new LocalSandbox({\n * isolation: result.available ? result.backend : 'none',\n * });\n * ```\n */\n static detectIsolation() {\n return detectIsolation();\n }\n}\n","import { posix } from 'node:path';\n\n/**\n * Parser and in-memory applier for the apply_patch format used by OpenAI Codex\n * and OpenCode:\n *\n * ```\n * *** Begin Patch\n * *** Add File: path/to/new.ts\n * +line one\n * *** Update File: path/to/existing.ts\n * *** Move to: path/to/renamed.ts\n * @@ optional context line\n * unchanged line\n * -removed line\n * +added line\n * *** Delete File: path/to/old.ts\n * *** End Patch\n * ```\n *\n * Parsing and applying are pure: nothing here touches a filesystem.\n */\n\nexport class ApplyPatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ApplyPatchError';\n }\n}\n\nexport interface UpdateChunk {\n /** Line from `@@ <context>` used to locate the chunk, if given. */\n context?: string;\n oldLines: string[];\n newLines: string[];\n /**\n * For each entry of `newLines`, the index in `oldLines` it was copied from\n * when it is a context line. Lets context keep the file's exact text when\n * the hunk only matched after ignoring whitespace.\n */\n contextSource: Array<number | undefined>;\n /** Set by `*** End of File`: the chunk must match the end of the file. */\n isEndOfFile: boolean;\n}\n\nexport type PatchOperation =\n | { type: 'add'; path: string; content: string }\n | { type: 'delete'; path: string }\n | { type: 'update'; path: string; moveTo?: string; chunks: UpdateChunk[] };\n\nconst BEGIN_PATCH = '*** Begin Patch';\nconst END_PATCH = '*** End Patch';\nconst ADD_FILE = '*** Add File: ';\nconst DELETE_FILE = '*** Delete File: ';\nconst UPDATE_FILE = '*** Update File: ';\nconst MOVE_TO = '*** Move to: ';\nconst END_OF_FILE = '*** End of File';\n\nfunction isFileHeader(line: string): boolean {\n return (\n line.startsWith(ADD_FILE) || line.startsWith(DELETE_FILE) || line.startsWith(UPDATE_FILE) || line === END_PATCH\n );\n}\n\nfunction headerPath(line: string, prefix: string, lineNumber: number): string {\n const path = line.slice(prefix.length).trim();\n if (!path) {\n throw new ApplyPatchError(`Line ${lineNumber}: missing file path after \"${prefix.trim()}\"`);\n }\n // Canonical form so 'a.ts', './a.ts' and 'src//../a.ts' count as one path\n // for the duplicate check and share one write lock.\n return posix.normalize(path);\n}\n\n/**\n * Parse a patch into its file operations. Throws {@link ApplyPatchError} on\n * malformed input or when the same path is touched more than once.\n */\nexport function parsePatch(patch: string): PatchOperation[] {\n const lines = patch.replace(/\\r\\n/g, '\\n').split('\\n');\n // Tolerate surrounding blank lines.\n while (lines.length > 0 && lines[0]!.trim() === '') lines.shift();\n while (lines.length > 0 && lines[lines.length - 1]!.trim() === '') lines.pop();\n\n if (lines[0]?.trim() !== BEGIN_PATCH) {\n throw new ApplyPatchError(`The first line of the patch must be \"${BEGIN_PATCH}\"`);\n }\n if (lines.length < 2 || lines[lines.length - 1]!.trim() !== END_PATCH) {\n throw new ApplyPatchError(`The last line of the patch must be \"${END_PATCH}\"`);\n }\n\n const operations: PatchOperation[] = [];\n let i = 1;\n const last = lines.length - 1;\n\n while (i < last) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n if (line.startsWith(ADD_FILE)) {\n const path = headerPath(line, ADD_FILE, lineNumber);\n i++;\n const contentLines: string[] = [];\n while (i < last && !isFileHeader(lines[i]!)) {\n const bodyLine = lines[i]!;\n if (!bodyLine.startsWith('+')) {\n throw new ApplyPatchError(`Line ${i + 1}: every line of an added file must start with \"+\"`);\n }\n contentLines.push(bodyLine.slice(1));\n i++;\n }\n operations.push({ type: 'add', path, content: contentLines.length ? contentLines.join('\\n') + '\\n' : '' });\n continue;\n }\n\n if (line.startsWith(DELETE_FILE)) {\n operations.push({ type: 'delete', path: headerPath(line, DELETE_FILE, lineNumber) });\n i++;\n continue;\n }\n\n if (line.startsWith(UPDATE_FILE)) {\n const path = headerPath(line, UPDATE_FILE, lineNumber);\n i++;\n let moveTo: string | undefined;\n if (i < last && lines[i]!.startsWith(MOVE_TO)) {\n moveTo = headerPath(lines[i]!, MOVE_TO, i + 1);\n i++;\n }\n\n const chunks: UpdateChunk[] = [];\n let current: UpdateChunk | undefined;\n while (i < last && !isFileHeader(lines[i]!)) {\n const bodyLine = lines[i]!;\n if (bodyLine === '@@' || bodyLine.startsWith('@@ ')) {\n const context = bodyLine.slice(2).trim();\n current = {\n context: context || undefined,\n oldLines: [],\n newLines: [],\n contextSource: [],\n isEndOfFile: false,\n };\n chunks.push(current);\n } else if (bodyLine.trim() === END_OF_FILE) {\n if (!current) {\n throw new ApplyPatchError(`Line ${i + 1}: \"${END_OF_FILE}\" must follow a hunk`);\n }\n current.isEndOfFile = true;\n current = undefined;\n } else {\n if (!current) {\n // The first hunk of a file may omit its \"@@\" header.\n if (chunks.length > 0) {\n throw new ApplyPatchError(`Line ${i + 1}: expected \"@@\" to start a new hunk`);\n }\n current = { oldLines: [], newLines: [], contextSource: [], isEndOfFile: false };\n chunks.push(current);\n }\n const marker = bodyLine[0];\n const text = bodyLine.slice(1);\n if (bodyLine === '' || marker === ' ') {\n current.contextSource.push(current.oldLines.length);\n current.oldLines.push(text);\n current.newLines.push(text);\n } else if (marker === '-') {\n current.oldLines.push(text);\n } else if (marker === '+') {\n current.contextSource.push(undefined);\n current.newLines.push(text);\n } else {\n throw new ApplyPatchError(\n `Line ${i + 1}: hunk lines must start with \" \" (context), \"-\" (remove) or \"+\" (add)`,\n );\n }\n }\n i++;\n }\n\n if (chunks.length === 0 && !moveTo) {\n throw new ApplyPatchError(`Line ${lineNumber}: \"${UPDATE_FILE.trim()}\" for ${path} has no hunks`);\n }\n // A context-only hunk (`@@ class B {` with no lines) narrows the search for the\n // next hunk, so it is allowed unless it is bare or the last one.\n const isEmpty = (chunk: UpdateChunk) => chunk.oldLines.length === 0 && chunk.newLines.length === 0;\n if (chunks.some((chunk, k) => isEmpty(chunk) && (chunk.context === undefined || k === chunks.length - 1))) {\n throw new ApplyPatchError(`Line ${lineNumber}: \"${UPDATE_FILE.trim()}\" for ${path} has an empty hunk`);\n }\n operations.push({ type: 'update', path, moveTo, chunks });\n continue;\n }\n\n throw new ApplyPatchError(\n `Line ${lineNumber}: expected \"${ADD_FILE.trim()}\", \"${UPDATE_FILE.trim()}\" or \"${DELETE_FILE.trim()}\", got \"${line}\"`,\n );\n }\n\n if (operations.length === 0) {\n throw new ApplyPatchError('The patch contains no file operations');\n }\n\n const seen = new Set<string>();\n for (const path of patchPaths(operations)) {\n if (seen.has(path)) {\n throw new ApplyPatchError(`The patch touches ${path} more than once; combine those changes into one operation`);\n }\n seen.add(path);\n }\n\n return operations;\n}\n\n/** Every path a set of operations reads or writes, including move destinations. */\nexport function patchPaths(operations: PatchOperation[]): string[] {\n return operations.flatMap(op => (op.type === 'update' && op.moveTo ? [op.path, op.moveTo] : [op.path]));\n}\n\n/**\n * Find `pattern` in `lines` at or after `start`. Tries an exact match first,\n * then ignores trailing whitespace, then ignores surrounding whitespace.\n */\nfunction seekSequence(lines: string[], pattern: string[], start: number, endOfFile: boolean): number {\n if (pattern.length === 0) return start;\n if (pattern.length > lines.length) return -1;\n\n const lastStart = lines.length - pattern.length;\n const from = endOfFile ? lastStart : start;\n const normalizers: Array<(s: string) => string> = [s => s, s => s.trimEnd(), s => s.trim()];\n\n for (const normalize of normalizers) {\n for (let i = from; i <= lastStart; i++) {\n let matched = true;\n for (let j = 0; j < pattern.length; j++) {\n if (normalize(lines[i + j]!) !== normalize(pattern[j]!)) {\n matched = false;\n break;\n }\n }\n if (matched) return i;\n }\n }\n return -1;\n}\n\n/**\n * Apply update hunks to file content in memory. Throws {@link ApplyPatchError}\n * when a hunk cannot be located. Preserves the file's line endings and whether\n * it ends with a newline.\n */\nexport function applyChunks(content: string, chunks: UpdateChunk[], path: string): string {\n const eol = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const hadTrailingNewline = content.length === 0 || content.endsWith('\\n');\n const lines = content.split(/\\r?\\n/);\n if (hadTrailingNewline) lines.pop();\n\n const replacements: Array<{ start: number; deleteCount: number; newLines: string[] }> = [];\n let cursor = 0;\n\n for (const chunk of chunks) {\n if (chunk.context !== undefined) {\n const contextIndex = seekSequence(lines, [chunk.context], cursor, false);\n if (contextIndex === -1) {\n throw new ApplyPatchError(`Could not find context line \"${chunk.context}\" in ${path}`);\n }\n cursor = contextIndex + 1;\n }\n\n if (chunk.oldLines.length === 0 && chunk.newLines.length === 0) {\n continue;\n }\n\n if (chunk.oldLines.length === 0) {\n // Pure insertion: after the context line if one was given, otherwise at the end.\n const at = chunk.context !== undefined ? cursor : lines.length;\n replacements.push({ start: at, deleteCount: 0, newLines: chunk.newLines });\n cursor = at;\n continue;\n }\n\n let oldLines = chunk.oldLines;\n let newLines = chunk.newLines;\n let index = seekSequence(lines, oldLines, cursor, chunk.isEndOfFile);\n if (index === -1 && oldLines[oldLines.length - 1] === '') {\n // A trailing blank context line often stands for the file's final newline.\n oldLines = oldLines.slice(0, -1);\n if (newLines[newLines.length - 1] === '') newLines = newLines.slice(0, -1);\n index = seekSequence(lines, oldLines, cursor, chunk.isEndOfFile);\n }\n if (index === -1) {\n throw new ApplyPatchError(\n `Could not find the lines to replace in ${path}:\\n${chunk.oldLines.join('\\n')}\\n` +\n 'Read the file again and make sure context and \"-\" lines match its current content.',\n );\n }\n replacements.push({\n start: index,\n deleteCount: oldLines.length,\n newLines: newLines.map((line, k) => {\n const source = chunk.contextSource[k];\n return source !== undefined && source < oldLines.length ? lines[index + source]! : line;\n }),\n });\n cursor = index + oldLines.length;\n }\n\n for (const { start, deleteCount, newLines } of [...replacements].reverse()) {\n lines.splice(start, deleteCount, ...newLines);\n }\n\n if (lines.length === 0) return '';\n return lines.join(eol) + (hadTrailingNewline ? eol : '');\n}\n","/**\n * Workspace Tool Helpers\n *\n * Runtime assertions for extracting workspace resources from tool execution context.\n */\n\nimport path from 'node:path';\n\nimport type { ToolExecutionContext } from '../../tools/types';\nimport { WorkspaceNotAvailableError, FilesystemNotAvailableError, SandboxNotAvailableError } from '../errors';\nimport type { WorkspaceFilesystem } from '../filesystem';\nimport type { LSPDiagnostic, DiagnosticSeverity } from '../lsp/types';\nimport type { WorkspaceSandbox } from '../sandbox';\nimport type { Workspace } from '../workspace';\n\nconst NUMERIC_STRING_REGEX = /^-?\\d+(?:\\.\\d+)?$/;\n\n/**\n * Preprocessor for numeric tool params: models sometimes send numbers as\n * strings (e.g. `\"10\"` instead of `10`), and a strict `z.number()` rejects\n * the call outright. Coerce unambiguous numeric strings; anything else\n * passes through unchanged so schema validation still reports it.\n */\nexport function coerceNumericString(value: unknown): unknown {\n if (typeof value !== 'string') {\n return value;\n }\n const trimmed = value.trim();\n return NUMERIC_STRING_REGEX.test(trimmed) ? Number(trimmed) : value;\n}\n\n/**\n * Extract workspace from tool execution context.\n * Throws if workspace is not available.\n */\nexport function requireWorkspace(context: ToolExecutionContext): Workspace {\n if (!context?.workspace) {\n throw new WorkspaceNotAvailableError();\n }\n return context.workspace;\n}\n\n/**\n * Extract filesystem from workspace in tool execution context.\n * Throws if workspace or filesystem is not available.\n */\nexport function requireFilesystem(context: ToolExecutionContext): {\n workspace: Workspace;\n filesystem: WorkspaceFilesystem;\n} {\n const workspace = requireWorkspace(context);\n if (!workspace.filesystem) {\n throw new FilesystemNotAvailableError();\n }\n return { workspace, filesystem: workspace.filesystem };\n}\n\n/**\n * Extract sandbox from workspace in tool execution context.\n * Throws if workspace or sandbox is not available.\n */\nexport function requireSandbox(context: ToolExecutionContext): {\n workspace: Workspace;\n sandbox: WorkspaceSandbox;\n} {\n const workspace = requireWorkspace(context);\n if (!workspace.sandbox) {\n throw new SandboxNotAvailableError();\n }\n return { workspace, sandbox: workspace.sandbox };\n}\n\nexport function getDynamicSandboxCacheKeyHint(workspace: Workspace): string {\n const hasResolver = workspace.hasSandboxResolver();\n const hasCacheKey = workspace.hasSandboxCacheKey();\n\n if (!hasResolver || hasCacheKey) return '';\n\n return ' If this process was started from a dynamic sandbox resolver, configure sandboxCacheKey or have the resolver return the same sandbox for follow-up calls.';\n}\n\n/**\n * Emit workspace metadata as a data chunk so the UI can render workspace info immediately.\n * Should be called at the start of every workspace tool's execute function.\n */\nexport async function emitWorkspaceMetadata(context: ToolExecutionContext, toolName: string) {\n const workspace = requireWorkspace(context);\n const info = await workspace.getInfo({ requestContext: context?.requestContext, resolveDynamicProviders: false });\n const toolCallId = context?.agent?.toolCallId;\n await context?.writer?.custom({\n type: 'data-workspace-metadata',\n data: { toolName, toolCallId, ...info },\n });\n}\n\n/**\n * Get LSP diagnostics text to append to edit tool results.\n * Non-blocking — returns empty string on any failure.\n *\n * LSP is a Workspace-level feature. This helper checks if the workspace\n * has an LSP manager and uses it to get diagnostics for the edited file.\n *\n * @param workspace - The workspace (must have an LSP manager for diagnostics)\n * @param filePath - Relative path within the filesystem (as used by the tool)\n * @param content - The file content after the edit\n * @returns Formatted diagnostics text, or empty string if unavailable\n */\nexport async function getEditDiagnosticsText(workspace: Workspace, filePath: string, content: string): Promise<string> {\n try {\n const lspManager = workspace.lsp;\n if (!lspManager) return '';\n\n // Use the filesystem's path resolution to get the real disk path.\n // This correctly handles contained: true (virtual paths → basePath)\n // and contained: false (absolute paths used as-is).\n // Use posix resolve to ensure POSIX LSP paths don't get Windows drive letters appended,\n // but fall back to win32 resolve if the root is explicitly a Windows absolute path.\n const isWindowsRoot =\n /^[A-Za-z]:[\\\\/]/.test(lspManager.root) || /^(?:\\\\\\\\|\\/\\/)[^\\\\]+[\\\\][^\\\\/]+/.test(lspManager.root);\n const absolutePath =\n workspace.filesystem?.resolveAbsolutePath?.(filePath) ??\n (isWindowsRoot\n ? path.win32.resolve(lspManager.root, filePath.replace(/^\\/+/, ''))\n : path.posix.resolve(lspManager.root, filePath.replace(/^\\/+/, '')));\n\n const DIAG_TIMEOUT_MS = 10_000;\n let diagTimer: ReturnType<typeof setTimeout>;\n const diagnostics = await Promise.race([\n lspManager.getDiagnostics(absolutePath, content),\n new Promise<LSPDiagnostic[] | null>((_, reject) => {\n diagTimer = setTimeout(() => reject(new Error('LSP diagnostics timeout')), DIAG_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(diagTimer!));\n // null means no LSP client was available — don't show anything\n if (diagnostics === null) return '';\n if (diagnostics.length === 0) return '';\n\n // Deduplicate by severity + location + message\n const seen = new Set<string>();\n const deduped = diagnostics.filter(d => {\n const key = `${d.severity}:${d.line}:${d.character}:${d.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n // Group diagnostics by severity\n const groups: Record<DiagnosticSeverity, LSPDiagnostic[]> = {\n error: [],\n warning: [],\n info: [],\n hint: [],\n };\n\n for (const d of deduped) {\n groups[d.severity].push(d);\n }\n\n const lines: string[] = ['\\n\\nLSP Diagnostics:'];\n\n const severityLabels: [DiagnosticSeverity, string][] = [\n ['error', 'Errors'],\n ['warning', 'Warnings'],\n ['info', 'Info'],\n ['hint', 'Hints'],\n ];\n\n for (const [severity, label] of severityLabels) {\n const items = groups[severity];\n if (items.length === 0) continue;\n lines.push(`${label}:`);\n for (const d of items) {\n const source = d.source ? ` [${d.source}]` : '';\n lines.push(` ${d.line}:${d.character} - ${d.message}${source}`);\n }\n }\n\n let result = lines.join('\\n');\n\n // Truncate to ~500 tokens (~2000 chars) to avoid bloating tool output\n const maxChars = 2000;\n if (result.length > maxChars) {\n const cutoff = result.lastIndexOf('\\n', maxChars);\n result = result.slice(0, cutoff > 0 ? cutoff : maxChars) + '\\n ... (truncated)';\n }\n\n return result;\n } catch {\n return '';\n }\n}\n","/**\n * Workspace Tracing Utilities\n *\n * Creates and manages WORKSPACE_ACTION spans for workspace tool operations.\n * Each workspace tool wraps its core operation in a span that captures\n * category, operation name, and operation-specific input/output.\n *\n * Data placement follows span conventions:\n * - `input`: what the operation receives (path, command, query, etc.)\n * - `output`: what the operation produces (results, bytes, exit codes, etc.)\n * - `attributes`: span metadata (category, workspaceId, provider, success)\n */\n\nimport type { AnySpan, SkillActionAttributes, WorkspaceActionAttributes } from '../../observability/types/tracing';\nimport { SpanType } from '../../observability/types/tracing';\nimport type { ToolExecutionContext } from '../../tools/types';\nimport type { Workspace } from '../workspace';\n\n/**\n * Options for starting a workspace action span.\n */\nexport interface WorkspaceSpanOptions {\n /** Action category */\n category: WorkspaceActionAttributes['category'];\n /** Operation name (e.g. 'readFile', 'executeCommand') */\n operation: string;\n /** Input data to record on the span (path, command, query, etc.) */\n input?: unknown;\n /** Initial attributes (workspace metadata, provider info) */\n attributes?: Partial<Omit<WorkspaceActionAttributes, 'category'>>;\n}\n\n/**\n * Handle returned by startWorkspaceSpan for ending the span.\n */\nexport interface WorkspaceSpanHandle {\n /** The underlying span (undefined when tracing is not active) */\n span: AnySpan | undefined;\n /** End the span with final attributes and output */\n end(attrs?: Partial<WorkspaceActionAttributes>, output?: unknown): void;\n /** End the span with an error */\n error(err: unknown, attrs?: Partial<WorkspaceActionAttributes>): void;\n}\n\nconst ENV_FIELD_NAMES = new Set(['env', 'environment', 'process_env']);\nconst SECRET_FIELD_PATTERN =\n /(^|[_-])(api[_-]?key|key|token|secret|password|passwd|pwd|credential|credentials|auth|authorization|cookie|session)([_-]|$)/i;\n\nfunction normalizeFieldName(key: string): string {\n return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return Object.prototype.toString.call(value) === '[object Object]';\n}\n\nfunction redactEnv(value: unknown) {\n return {\n redacted: true,\n keys: isPlainObject(value) || Array.isArray(value) ? Object.keys(value).sort() : undefined,\n };\n}\n\nfunction sanitizeWorkspaceTraceData(value: unknown, seen = new WeakSet<object>()): unknown {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n return '[redacted:circular]';\n }\n seen.add(value);\n try {\n return value.map(item => sanitizeWorkspaceTraceData(item, seen));\n } finally {\n seen.delete(value);\n }\n }\n\n if (!isPlainObject(value)) {\n return value;\n }\n\n if (seen.has(value)) {\n return '[redacted:circular]';\n }\n seen.add(value);\n try {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => {\n const normalized = normalizeFieldName(key);\n if (ENV_FIELD_NAMES.has(normalized)) {\n return [key, redactEnv(entry)];\n }\n if (SECRET_FIELD_PATTERN.test(normalized)) {\n return [key, '[redacted]'];\n }\n return [key, sanitizeWorkspaceTraceData(entry, seen)];\n }),\n );\n } finally {\n seen.delete(value);\n }\n}\n\n/**\n * Start a WORKSPACE_ACTION child span from the tool execution context.\n *\n * Returns a handle with `end()` and `error()` methods. If no tracing context\n * is available (no parent span), all operations are safe no-ops.\n *\n * @example\n * ```typescript\n * const span = startWorkspaceSpan(context, workspace, {\n * category: 'filesystem',\n * operation: 'readFile',\n * input: { path },\n * attributes: { filesystemProvider: filesystem.provider },\n * });\n * try {\n * const result = await filesystem.readFile(path);\n * span.end({ success: true }, { bytesTransferred: result.length });\n * return result;\n * } catch (err) {\n * span.error(err);\n * throw err;\n * }\n * ```\n */\nexport function startWorkspaceSpan(\n context: ToolExecutionContext | undefined,\n workspace: Workspace | undefined,\n options: WorkspaceSpanOptions,\n): WorkspaceSpanHandle {\n const currentSpan = context?.tracing?.currentSpan ?? context?.tracingContext?.currentSpan;\n\n if (!currentSpan) {\n return noOpHandle;\n }\n\n const { category, operation, input, attributes } = options;\n\n const span = currentSpan.createChildSpan<SpanType.WORKSPACE_ACTION>({\n type: SpanType.WORKSPACE_ACTION,\n name: `workspace:${category}:${operation}`,\n input: sanitizeWorkspaceTraceData(input),\n attributes: {\n category,\n workspaceId: workspace?.id,\n workspaceName: workspace?.name,\n ...attributes,\n },\n });\n\n return {\n span,\n end(attrs?: Partial<WorkspaceActionAttributes>, output?: unknown) {\n span?.end({\n output: sanitizeWorkspaceTraceData(output),\n attributes: {\n ...attrs,\n },\n });\n },\n error(err: unknown, attrs?: Partial<WorkspaceActionAttributes>) {\n const error = err instanceof Error ? err : new Error(String(err));\n span?.error({\n error,\n attributes: {\n success: false,\n ...attrs,\n },\n });\n },\n };\n}\n\n/** No-op handle when tracing is not available */\nconst noOpHandle: WorkspaceSpanHandle = {\n span: undefined,\n end() {},\n error() {},\n};\n\n/**\n * Options for starting a skill action span.\n */\nexport interface SkillSpanOptions {\n /** Which skill lifecycle operation this span covers */\n operation: SkillActionAttributes['operation'];\n /** Input data to record on the span (skill name, query, line range) */\n input?: unknown;\n /** Initial attributes */\n attributes?: Partial<Omit<SkillActionAttributes, 'operation'>>;\n}\n\n/**\n * Handle returned by startSkillSpan for ending the span.\n */\nexport interface SkillSpanHandle {\n /** The underlying span (undefined when tracing is not active) */\n span: AnySpan | undefined;\n /** End the span with final attributes and output */\n end(attrs?: Partial<SkillActionAttributes>, output?: unknown): void;\n /** End the span with an error */\n error(err: unknown, attrs?: Partial<SkillActionAttributes>): void;\n}\n\n/** No-op handle when tracing is not available */\nconst noOpSkillHandle: SkillSpanHandle = {\n span: undefined,\n end() {},\n error() {},\n};\n\n/**\n * Start a SKILL_ACTION child span from the tool execution context.\n *\n * Skill operations were previously traced as `WORKSPACE_ACTION` with\n * `category: 'skill'`, which only held while skills lived on a workspace.\n * Agent-level skills have no workspace, so skills get their own span type and\n * all five operations (resolve, inject, activate, search, read) share it.\n *\n * Returns a handle with `end()` and `error()`. With no parent span every\n * operation is a safe no-op.\n */\nexport function startSkillSpan(context: ToolExecutionContext | undefined, options: SkillSpanOptions): SkillSpanHandle {\n const currentSpan = context?.tracing?.currentSpan ?? context?.tracingContext?.currentSpan;\n\n if (!currentSpan) {\n return noOpSkillHandle;\n }\n\n const { operation, input, attributes } = options;\n\n const span = currentSpan.createChildSpan<SpanType.SKILL_ACTION>({\n type: SpanType.SKILL_ACTION,\n name: `skill:${operation}`,\n input: sanitizeWorkspaceTraceData(input),\n attributes: { operation, ...attributes },\n });\n\n return {\n span,\n end(attrs?: Partial<SkillActionAttributes>, output?: unknown) {\n span?.end({ output: sanitizeWorkspaceTraceData(output), attributes: { ...attrs } });\n },\n error(err: unknown, attrs?: Partial<SkillActionAttributes>) {\n const error = err instanceof Error ? err : new Error(String(err));\n span?.error({ error, attributes: { success: false, ...attrs } });\n },\n };\n}\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { FileNotFoundError, StaleFileError, WorkspaceReadOnlyError } from '../errors';\nimport type { FileStat, WorkspaceFilesystem } from '../filesystem';\nimport { ApplyPatchError, applyChunks, parsePatch, patchPaths } from './apply-patch-parser';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\n/**\n * Paths a patch writes, used to take write locks and run read-before-write\n * checks before the tool executes. Returns `[]` for a malformed patch so the\n * tool itself can report the parse error.\n */\nexport function getApplyPatchWritePaths(input: { patch?: unknown }): string[] {\n if (typeof input?.patch !== 'string') return [];\n try {\n return patchPaths(parsePatch(input.patch));\n } catch {\n return [];\n }\n}\n\nconst PATCH_NOT_APPLIED = 'Patch not applied, no files were changed:';\n\n/** False when the tool returned a validation failure and touched no file. */\nexport function applyPatchDidWrite(result: unknown): boolean {\n return !(typeof result === 'string' && result.startsWith(PATCH_NOT_APPLIED));\n}\n\ntype PlannedChange =\n | { kind: 'write'; path: string; content: string | Buffer; original?: string; mtime?: Date }\n | { kind: 'delete'; path: string; original: string | Buffer; mtime: Date };\n\nasync function statOrUndefined(filesystem: WorkspaceFilesystem, path: string): Promise<FileStat | undefined> {\n try {\n return await filesystem.stat(path);\n } catch (error) {\n if (error instanceof FileNotFoundError) return undefined;\n throw error;\n }\n}\n\nfunction checkNotStale(path: string, stat: FileStat, expectedMtimes: Record<string, Date> | undefined) {\n const expected = expectedMtimes?.[path];\n if (expected && stat.modifiedAt.getTime() !== expected.getTime()) {\n throw new StaleFileError(path, expected, stat.modifiedAt);\n }\n}\n\nasync function requireExistingFile(\n filesystem: WorkspaceFilesystem,\n path: string,\n expectedMtimes: Record<string, Date> | undefined,\n): Promise<Date> {\n const stat = await statOrUndefined(filesystem, path);\n if (!stat) throw new ApplyPatchError(`${path} does not exist`);\n if (stat.type !== 'file') throw new ApplyPatchError(`${path} is a directory, not a file`);\n checkNotStale(path, stat, expectedMtimes);\n return stat.modifiedAt;\n}\n\nasync function requireMissing(filesystem: WorkspaceFilesystem, path: string): Promise<void> {\n if (await statOrUndefined(filesystem, path)) {\n throw new ApplyPatchError(`${path} already exists`);\n }\n}\n\nexport const applyPatchTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.APPLY_PATCH,\n description: `Create, update, move and delete files in one call by applying a patch. Every change applies, or none do.\n\nFormat:\n*** Begin Patch\n*** Add File: path/to/new-file.ts\n+first line of the new file\n+second line\n*** Update File: path/to/existing.ts\n*** Move to: path/to/renamed.ts\n@@ optional line near the change, e.g. a function signature\n unchanged context line\n-line to remove\n+line to add\n*** Delete File: path/to/obsolete.ts\n*** End Patch\n\nRules:\n- Paths are relative to the workspace root. Each path may appear only once per patch.\n- \"*** Move to:\" is optional and must directly follow \"*** Update File:\".\n- In an update, each line starts with \" \" (context), \"-\" (remove) or \"+\" (add). Include about 3 lines of context around each change so it can be located. Start each further hunk with \"@@\".\n- \"*** End of File\" after a hunk anchors it to the end of the file.\n- Added files must not already exist; updated and deleted files must exist.`,\n outputSchema: z.string(),\n inputSchema: z.object({\n patch: z.string().describe('The full patch text, from \"*** Begin Patch\" to \"*** End Patch\"'),\n }),\n execute: async ({ patch }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.APPLY_PATCH);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'applyPatch',\n input: { patchLength: patch.length },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n if (filesystem.readOnly) {\n throw new WorkspaceReadOnlyError('apply_patch');\n }\n\n const expectedMtimes: Record<string, Date> | undefined = (context as any)?.__expectedMtimes;\n const summary: string[] = [];\n const changes: PlannedChange[] = [];\n\n // Phase 1: validate every operation and compute new contents in memory.\n // Nothing is written until the whole patch is known to apply.\n try {\n const operations = parsePatch(patch);\n for (const op of operations) {\n if (op.type === 'add') {\n await requireMissing(filesystem, op.path);\n changes.push({ kind: 'write', path: op.path, content: op.content });\n summary.push(`A ${op.path}`);\n } else if (op.type === 'delete') {\n const mtime = await requireExistingFile(filesystem, op.path, expectedMtimes);\n changes.push({ kind: 'delete', path: op.path, original: await filesystem.readFile(op.path), mtime });\n summary.push(`D ${op.path}`);\n } else {\n const mtime = await requireExistingFile(filesystem, op.path, expectedMtimes);\n if (op.chunks.length === 0 && op.moveTo) {\n // Pure rename: copy the raw bytes so binary files survive the move.\n await requireMissing(filesystem, op.moveTo);\n const raw = await filesystem.readFile(op.path);\n changes.push({ kind: 'write', path: op.moveTo, content: raw });\n changes.push({ kind: 'delete', path: op.path, original: raw, mtime });\n summary.push(`R ${op.path} -> ${op.moveTo}`);\n continue;\n }\n const original = await filesystem.readFile(op.path, { encoding: 'utf-8' });\n if (typeof original !== 'string') {\n throw new ApplyPatchError(`${op.path} is a binary file and cannot be patched`);\n }\n const updated = applyChunks(original, op.chunks, op.path);\n if (op.moveTo && op.moveTo !== op.path) {\n await requireMissing(filesystem, op.moveTo);\n changes.push({ kind: 'write', path: op.moveTo, content: updated });\n changes.push({ kind: 'delete', path: op.path, original, mtime });\n summary.push(`R ${op.path} -> ${op.moveTo}`);\n } else {\n changes.push({ kind: 'write', path: op.path, content: updated, original, mtime });\n summary.push(`M ${op.path}`);\n }\n }\n }\n } catch (error) {\n if (error instanceof ApplyPatchError) {\n span.end({ success: false });\n return `${PATCH_NOT_APPLIED} ${error.message}`;\n }\n throw error;\n }\n\n // Phase 2: commit. Writes go first so a move never loses its source\n // before the destination exists. On failure, undo what was done.\n const ordered = [...changes.filter(c => c.kind === 'write'), ...changes.filter(c => c.kind === 'delete')];\n const done: PlannedChange[] = [];\n try {\n for (const change of ordered) {\n if (change.kind === 'write') {\n await filesystem.writeFile(change.path, change.content, {\n overwrite: change.original !== undefined,\n expectedMtime: change.mtime,\n });\n } else {\n // deleteFile has no conditional form, so re-check right before removing.\n const current = await filesystem.stat(change.path);\n if (current.modifiedAt.getTime() !== change.mtime.getTime()) {\n throw new StaleFileError(change.path, change.mtime, current.modifiedAt);\n }\n await filesystem.deleteFile(change.path);\n }\n done.push(change);\n }\n } catch (error) {\n const rollbackFailures = await rollback(filesystem, done);\n if (rollbackFailures.length > 0) {\n throw new Error(\n `apply_patch failed while writing (${(error as Error).message}) and could not restore: ${rollbackFailures.join(', ')}`,\n { cause: error },\n );\n }\n throw error;\n }\n\n span.end({ success: true });\n return `Applied patch:\\n${summary.join('\\n')}`;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n\n/** Revert committed changes in reverse order. Returns the paths that could not be restored. */\nasync function rollback(filesystem: WorkspaceFilesystem, done: PlannedChange[]): Promise<string[]> {\n const failures: string[] = [];\n for (const change of [...done].reverse()) {\n try {\n if (change.kind === 'delete') {\n await filesystem.writeFile(change.path, change.original);\n } else if (change.original !== undefined) {\n await filesystem.writeFile(change.path, change.original);\n } else {\n await filesystem.deleteFile(change.path);\n }\n } catch {\n failures.push(change.path);\n }\n }\n return failures;\n}\n","/**\n * AST Edit Tool\n *\n * Provides AST-aware code transformations for workspace files.\n * Uses @ast-grep/napi for syntax-aware pattern matching and transforms.\n *\n * Requires @ast-grep/napi as an optional peer dependency.\n */\n\nimport { createRequire } from 'node:module';\n\nimport { z } from 'zod/v4';\n\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { FileNotFoundError, WorkspaceReadOnlyError } from '../errors';\nimport { emitWorkspaceMetadata, getEditDiagnosticsText, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface Replacement {\n start: number;\n end: number;\n text: string;\n}\n\ninterface TransformResult {\n content: string;\n count: number;\n error?: string;\n}\n\ninterface ImportSpec {\n module: string;\n names: string[];\n isDefault?: boolean;\n}\n\n/**\n * Minimal interface for an ast-grep SgNode.\n * Avoids importing @ast-grep/napi types directly since it's an optional dep.\n */\ninterface SgNode {\n text(): string;\n range(): { start: { index: number }; end: { index: number } };\n findAll(config: { rule: Record<string, unknown> }): SgNode[];\n getMatch(name: string): SgNode | null;\n}\n\n/** Minimal interface for the ast-grep Lang enum values. */\ntype LangValue = unknown;\n\n/** The subset of @ast-grep/napi we use after dynamic import. */\ninterface AstGrepModule {\n parse(lang: LangValue, content: string): { root(): SgNode };\n Lang: Record<string, LangValue>;\n}\n\n// =============================================================================\n// Dynamic Import\n// =============================================================================\n\n// Cache the import result so we only try once\nlet astGrepModule: AstGrepModule | null | undefined;\nlet loadingPromise: Promise<AstGrepModule | null> | undefined;\n\n// Keep the specifier as a parameter so tsdown cannot fold it into a literal dynamic import.\nconst importModule = (moduleName: string) => import(/* @vite-ignore */ /* webpackIgnore: true */ moduleName);\n\n/**\n * Try to load @ast-grep/napi. Returns null if not available.\n * Uses dynamic import to avoid compile-time dependency.\n * Concurrent callers share the same in-flight promise.\n */\nexport async function loadAstGrep(): Promise<AstGrepModule | null> {\n if (astGrepModule !== undefined) {\n return astGrepModule;\n }\n if (!loadingPromise) {\n loadingPromise = (async () => {\n try {\n const mod = await importModule('@ast-grep/napi');\n astGrepModule = { parse: mod.parse, Lang: mod.Lang };\n return astGrepModule;\n } catch {\n astGrepModule = null;\n return null;\n }\n })();\n }\n return loadingPromise;\n}\n\n/**\n * Check if @ast-grep/napi is available without importing it.\n * Useful for deciding whether to create the tool at registration time.\n */\nexport function isAstGrepAvailable(): boolean {\n if (astGrepModule !== undefined) {\n return astGrepModule !== null;\n }\n\n try {\n const req = createRequire(import.meta.url);\n req.resolve('@ast-grep/napi');\n return true;\n } catch {\n return false;\n }\n}\n\n// =============================================================================\n// Language Detection\n// =============================================================================\n\n/**\n * Map file extension to ast-grep Lang enum.\n *\n * Only languages with built-in tree-sitter grammars in @ast-grep/napi are\n * supported. Python, Go, Rust, etc. require separate @ast-grep/lang-* packages\n * which are not currently integrated.\n */\nexport function getLanguageFromPath(filePath: string, Lang: Record<string, LangValue>): LangValue | null {\n const ext = filePath.split('.').pop()?.toLowerCase();\n switch (ext) {\n case 'ts':\n return Lang.TypeScript;\n case 'tsx':\n case 'jsx':\n return Lang.Tsx;\n case 'js':\n return Lang.JavaScript;\n case 'html':\n return Lang.Html;\n case 'css':\n return Lang.Css;\n default:\n return null;\n }\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/** Escape regex metacharacters in a string. */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Rename all identifier occurrences matching `oldName` to `newName`.\n * Not scope-aware: renames all occurrences regardless of scope.\n */\nfunction renameIdentifiers(content: string, root: SgNode, oldName: string, newName: string): TransformResult {\n let modifiedContent = content;\n let count = 0;\n\n const identifiers = root.findAll({\n rule: {\n kind: 'identifier',\n regex: `^${escapeRegex(oldName)}$`,\n },\n });\n\n const replacements: Replacement[] = [];\n const seen = new Set<number>();\n\n for (const id of identifiers) {\n const range = id.range();\n if (seen.has(range.start.index)) continue;\n seen.add(range.start.index);\n replacements.push({ start: range.start.index, end: range.end.index, text: newName });\n count++;\n }\n\n replacements.sort((a, b) => b.start - a.start);\n\n for (const { start, end, text } of replacements) {\n modifiedContent = modifiedContent.slice(0, start) + text + modifiedContent.slice(end);\n }\n\n return { content: modifiedContent, count };\n}\n\n// =============================================================================\n// Transform Functions\n// =============================================================================\n\n/**\n * Build an import statement string from its parts.\n */\nfunction buildImportStatement(defaultName: string | null, namedImports: string[], moduleStr: string): string {\n if (defaultName && namedImports.length > 0) {\n return `import ${defaultName}, { ${namedImports.join(', ')} } from ${moduleStr};`;\n } else if (defaultName) {\n return `import ${defaultName} from ${moduleStr};`;\n }\n return `import { ${namedImports.join(', ')} } from ${moduleStr};`;\n}\n\n/**\n * Merge new names into an existing import statement.\n * Returns null if nothing needs to change.\n */\nfunction mergeIntoExistingImport(\n content: string,\n existingImport: SgNode,\n names: string[],\n isDefault?: boolean,\n): string | null {\n const text = existingImport.text();\n\n // Namespace imports (import * as X from 'mod') cannot be merged into\n if (/^import\\s+\\*\\s+as\\s+/.test(text)) return null;\n\n // Parse existing structure from the import text\n // Matches: import [default] [, { named }] from 'module'\n const defaultMatch = text.match(/^import\\s+(?!type\\s)(?!\\{)(\\w+)/);\n const namedMatch = text.match(/\\{([^}]*)\\}/);\n const moduleMatch = text.match(/([\"'][^\"']+[\"'])\\s*;?\\s*$/);\n\n if (!moduleMatch) return null;\n const moduleStr = moduleMatch[1] ?? '';\n\n let existingDefault = defaultMatch ? (defaultMatch[1] ?? null) : null;\n const existingNamed = namedMatch\n ? (namedMatch[1] ?? '')\n .split(',')\n .map((s: string) => s.trim())\n .filter(Boolean)\n : [];\n\n let newDefault = existingDefault;\n const newNamed = [...existingNamed];\n\n if (isDefault && names.length > 0) {\n // First name is the default import\n if (!existingDefault) {\n newDefault = names[0] ?? null;\n }\n // Remaining names are named imports\n for (const name of names.slice(1)) {\n if (!newNamed.includes(name)) {\n newNamed.push(name);\n }\n }\n } else {\n for (const name of names) {\n if (!newNamed.includes(name)) {\n newNamed.push(name);\n }\n }\n }\n\n // Check if anything changed\n const defaultChanged = newDefault !== existingDefault;\n const namedChanged = newNamed.length !== existingNamed.length;\n if (!defaultChanged && !namedChanged) return null;\n\n const importStatement = buildImportStatement(newDefault, newNamed, moduleStr);\n const range = existingImport.range();\n return content.slice(0, range.start.index) + importStatement + content.slice(range.end.index);\n}\n\n/**\n * Add an import statement to the file.\n * Inserts after the last existing import, or at the beginning if none exist.\n * If the module is already imported, merges new names into it.\n */\nexport function addImport(content: string, root: SgNode, importSpec: ImportSpec): string {\n const { module, names, isDefault } = importSpec;\n\n const imports = root.findAll({ rule: { kind: 'import_statement' } });\n\n // Check if a mergeable import from this module already exists.\n // Skip type-only and namespace imports — they can't be merged with value imports.\n const existingImport = imports.find(imp => {\n const text = imp.text();\n if (/^import\\s+type\\s/.test(text)) return false;\n if (/^import\\s+\\*\\s+as\\s+/.test(text)) return false;\n return text.includes(`'${module}'`) || text.includes(`\"${module}\"`);\n });\n\n if (existingImport) {\n // Try to merge new names into the existing import\n return mergeIntoExistingImport(content, existingImport, names, isDefault) ?? content;\n }\n\n // Build new import statement\n const moduleStr = `'${module}'`;\n const importStatement = buildImportStatement(\n isDefault ? names[0]! : null,\n isDefault ? names.slice(1) : names,\n moduleStr,\n );\n\n // Insert after last import or at file start\n const lastImport = imports.at(-1);\n if (lastImport) {\n const pos = lastImport.range().end.index;\n return content.slice(0, pos) + '\\n' + importStatement + content.slice(pos);\n }\n return importStatement + '\\n\\n' + content;\n}\n\n/**\n * Remove an import by module name.\n * Matches against the import source string.\n */\nexport function removeImport(content: string, root: SgNode, targetName: string): string {\n const imports = root.findAll({ rule: { kind: 'import_statement' } });\n\n for (const imp of imports) {\n const text = imp.text();\n const moduleMatch = text.match(/from\\s+['\"]([^'\"]+)['\"]|import\\s+['\"]([^'\"]+)['\"]/);\n const moduleName = moduleMatch?.[1] ?? moduleMatch?.[2];\n\n if (moduleName === targetName || moduleName?.startsWith(`${targetName}/`)) {\n const range = imp.range();\n const start = range.start.index;\n let end = range.end.index;\n // Remove trailing newline if present\n if (content[end] === '\\n') end++;\n return content.slice(0, start) + content.slice(end);\n }\n }\n\n return content;\n}\n\n/**\n * Pattern-based replacement using AST metavariables.\n * Pattern uses $VARNAME placeholders that match any AST node.\n * Replacement substitutes matched text back in.\n */\nexport function patternReplace(content: string, root: SgNode, pattern: string, replacement: string): TransformResult {\n let modifiedContent = content;\n let count = 0;\n\n try {\n const matches = root.findAll({ rule: { pattern } });\n const replacements: Replacement[] = [];\n\n // Extract metavariables from the pattern once (constant across all matches)\n const metaVars = [...pattern.matchAll(/\\$(\\w+)/g)].map(m => m[1]).filter((v): v is string => v !== undefined);\n\n for (const match of matches) {\n const range = match.range();\n\n // Build replacement text with variable substitution\n let replacementText = replacement;\n for (const varName of metaVars) {\n const matchedNode = match.getMatch(varName);\n if (matchedNode) {\n replacementText = replacementText.replace(new RegExp(`\\\\$${varName}`, 'g'), matchedNode.text());\n }\n }\n\n replacements.push({ start: range.start.index, end: range.end.index, text: replacementText });\n count++;\n }\n\n replacements.sort((a, b) => b.start - a.start);\n\n for (const { start, end, text } of replacements) {\n modifiedContent = modifiedContent.slice(0, start) + text + modifiedContent.slice(end);\n }\n } catch (err) {\n return {\n content: modifiedContent,\n count: 0,\n error: err instanceof Error ? err.message : 'Pattern matching failed',\n };\n }\n\n return { content: modifiedContent, count };\n}\n\n// =============================================================================\n// Tool Definition\n// =============================================================================\n\nexport const astEditTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT,\n description: `Edit code using AST-based analysis for intelligent transformations.\n\nUse \\`transform\\` for structured operations (imports, renames). Use \\`pattern\\`/\\`replacement\\` only for general find-and-replace.\n\nTransforms:\n- add-import: Add or merge imports. Skips duplicates. For default imports, put the default name first in \\`names\\`.\n { transform: \"add-import\", importSpec: { module: \"react\", names: [\"useState\", \"useEffect\"] } }\n { transform: \"add-import\", importSpec: { module: \"express\", names: [\"express\"], isDefault: true } }\n { transform: \"add-import\", importSpec: { module: \"express\", names: [\"express\", \"Router\"], isDefault: true } } → import express, { Router } from 'express'\n- remove-import: Remove an import by module name.\n { transform: \"remove-import\", targetName: \"lodash\" }\n- rename: Rename all occurrences of an identifier (not scope-aware).\n { transform: \"rename\", targetName: \"oldName\", newName: \"newName\" }\n\nPattern replace (for everything else):\n { pattern: \"console.log($ARG)\", replacement: \"logger.debug($ARG)\" }`,\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().describe('The path to the file to edit'),\n pattern: z\n .string()\n .optional()\n .describe('AST pattern to search for (supports $VARIABLE placeholders, e.g., \"console.log($ARG)\")'),\n replacement: z\n .string()\n .optional()\n .describe('Replacement pattern (can use captured $VARIABLES, e.g., \"logger.debug($ARG)\")'),\n transform: z\n .enum(['add-import', 'remove-import', 'rename'])\n .optional()\n .describe('Structured transformation to apply'),\n targetName: z\n .string()\n .optional()\n .describe('Required for remove-import and rename transforms. The current name to target.'),\n newName: z.string().optional().describe('Required for rename transform. The new name to replace targetName with.'),\n importSpec: z\n .object({\n module: z.string().describe('Module to import from'),\n names: z.array(z.string()).min(1).describe('Names to import. For default imports, put the default name first.'),\n isDefault: z.boolean().optional().describe('Whether the first name is a default import'),\n })\n .optional()\n .describe('Required for add-import transform. Specifies the module and names to import.'),\n }),\n execute: async ({ path, pattern, replacement, transform, targetName, newName, importSpec }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'astEdit',\n input: { path, transform, pattern },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n if (filesystem.readOnly) {\n throw new WorkspaceReadOnlyError('ast_edit');\n }\n\n // Load ast-grep (cached after first call)\n const astGrep = await loadAstGrep();\n if (!astGrep) {\n span.end({ success: false });\n return '@ast-grep/napi is not available. Install it to use AST editing.';\n }\n const { parse, Lang } = astGrep;\n\n // Read current content\n let content: string | Buffer;\n try {\n content = await filesystem.readFile(path, { encoding: 'utf-8' });\n } catch (error) {\n if (error instanceof FileNotFoundError) {\n span.end({ success: false });\n return `File not found: ${path}. Use the write file tool to create it first.`;\n }\n throw error;\n }\n\n if (typeof content !== 'string') {\n span.end({ success: false });\n return `Cannot perform AST edits on binary files. Use the write file tool instead.`;\n }\n\n // Parse AST\n const lang = getLanguageFromPath(path, Lang);\n if (!lang) {\n span.end({ success: false });\n return `Unsupported file type for AST editing: ${path}`;\n }\n const ast = parse(lang, content);\n const root = ast.root();\n\n let modifiedContent = content;\n const changes: string[] = [];\n\n if (transform) {\n switch (transform) {\n case 'add-import': {\n if (!importSpec) {\n span.end({ success: false });\n return 'Error: importSpec is required for add-import transform';\n }\n modifiedContent = addImport(content, root, importSpec);\n changes.push(`Added import from '${importSpec.module}'`);\n break;\n }\n\n case 'remove-import': {\n if (!targetName) {\n span.end({ success: false });\n return 'Error: targetName is required for remove-import transform';\n }\n modifiedContent = removeImport(content, root, targetName);\n changes.push(`Removed import '${targetName}'`);\n break;\n }\n\n case 'rename': {\n if (!targetName || !newName) {\n span.end({ success: false });\n return 'Error: targetName and newName are required for rename transform';\n }\n const renameResult = renameIdentifiers(content, root, targetName, newName);\n modifiedContent = renameResult.content;\n changes.push(`Renamed '${targetName}' to '${newName}' (${renameResult.count} occurrences)`);\n break;\n }\n }\n } else if (pattern && replacement !== undefined) {\n const result = patternReplace(content, root, pattern, replacement);\n if (result.error) {\n span.end({ success: false });\n return `Error: AST pattern matching failed: ${result.error}`;\n }\n modifiedContent = result.content;\n changes.push(`Replaced ${result.count} occurrences of pattern`);\n } else if (pattern && replacement === undefined) {\n span.end({ success: false });\n return 'Error: replacement is required when pattern is provided';\n } else if (!pattern && replacement !== undefined) {\n span.end({ success: false });\n return 'Error: pattern is required when replacement is provided';\n } else {\n span.end({ success: false });\n return 'Error: Must provide either transform or pattern/replacement';\n }\n\n // Write back if modified\n const wasModified = modifiedContent !== content;\n if (wasModified) {\n await filesystem.writeFile(path, modifiedContent, {\n overwrite: true,\n expectedMtime: (context as any)?.__expectedMtime,\n });\n }\n\n if (!wasModified) {\n span.end({ success: true });\n return `No changes made to ${path} (${changes.join('; ')})`;\n }\n\n let output = `${path}: ${changes.join('; ')}`;\n output += await getEditDiagnosticsText(workspace, path, modifiedContent);\n span.end({ success: true }, { bytesTransferred: Buffer.byteLength(modifiedContent, 'utf-8') });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","/**\n * Shared media-result helpers for workspace tools.\n *\n * Tools that surface binary media (read_file for media files, the computer\n * screenshot tools) return a MediaToolResult so `toModelOutput` can present\n * the media as a native image/file part while only the `text` header is kept\n * in the stored/displayed result.\n */\n\n/**\n * Internal marker on the tool's result that signals to `toModelOutput`\n * that the payload should be surfaced to the model as a media part (image or\n * binary file) rather than as plain text. We attach this on a wrapper object\n * but only the `text` field is shown to the model (via toModelOutput); the\n * marker is stripped before it ever reaches the model.\n *\n * The shape is intentionally JSON-serialisable so it round-trips through\n * storage layers that snapshot tool results.\n */\nexport type MediaToolResult = {\n __workspaceMedia: true;\n text: string;\n mediaType: string;\n data: string;\n};\n\nexport function isMediaToolResult(value: unknown): value is MediaToolResult {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>).__workspaceMedia === true &&\n typeof (value as Record<string, unknown>).text === 'string' &&\n typeof (value as Record<string, unknown>).mediaType === 'string' &&\n typeof (value as Record<string, unknown>).data === 'string'\n );\n}\n\n/**\n * Default cap (in bytes) on inline media results. Payloads larger than this\n * fall back to text-only output instead of being fully base64-encoded into\n * the model context (and persisted in storage on rehydration). 10 MiB is\n * roughly aligned with provider per-image/per-pdf limits.\n */\nexport const DEFAULT_MAX_MEDIA_BYTES = 10 * 1024 * 1024;\n\n/**\n * Shared `toModelOutput` handler for tools that may return a MediaToolResult.\n * Surfaces the media as a native part; returns undefined for plain string\n * output so we don't store a duplicate copy on providerMetadata.\n */\nexport function mediaToModelOutput(output: unknown) {\n if (isMediaToolResult(output)) {\n return {\n type: 'content' as const,\n value: [\n { type: 'text' as const, text: output.text },\n { type: 'media' as const, data: output.data, mediaType: output.mediaType },\n ],\n };\n }\n return undefined;\n}\n","/**\n * Shared helpers for the workspace computer (desktop) tools.\n *\n * The computer tools delegate to the sandbox's optional `computer` capability\n * (see SandboxComputer). These helpers extract the capability from the tool\n * execution context and format screenshot results as media parts.\n */\n\nimport type { ToolExecutionContext } from '../../tools/types';\nimport type { WORKSPACE_TOOLS } from '../constants';\nimport { SandboxFeatureNotSupportedError } from '../errors';\nimport type { ComputerScreenshot, SandboxComputer, WorkspaceSandbox } from '../sandbox';\nimport { supportsComputer } from '../sandbox';\nimport type { Workspace } from '../workspace';\nimport { requireSandbox } from './helpers';\nimport type { MediaToolResult } from './media';\nimport { DEFAULT_MAX_MEDIA_BYTES } from './media';\nimport type { ComputerToolConfig } from './types';\n\n/** Default for ComputerToolConfig.screenshotAfterAction. */\nexport const DEFAULT_SCREENSHOT_AFTER_ACTION = true;\n\n/** Default for ComputerToolConfig.screenshotDelayMs. */\nexport const DEFAULT_SCREENSHOT_DELAY_MS = 500;\n\ntype ComputerToolName = (typeof WORKSPACE_TOOLS.COMPUTER)[keyof typeof WORKSPACE_TOOLS.COMPUTER];\n\n/**\n * Extract the computer capability from the workspace sandbox in the tool\n * execution context. Throws if the workspace has no sandbox or the sandbox\n * doesn't support the computer capability.\n */\nexport function requireComputer(context: ToolExecutionContext): {\n workspace: Workspace;\n sandbox: WorkspaceSandbox;\n computer: SandboxComputer;\n} {\n const { workspace, sandbox } = requireSandbox(context);\n if (!supportsComputer(sandbox)) {\n throw new SandboxFeatureNotSupportedError('computer');\n }\n return { workspace, sandbox, computer: sandbox.computer };\n}\n\n/** Resolve the per-tool ComputerToolConfig from the workspace tools config. */\nexport function getComputerToolConfig(\n workspace: Workspace,\n toolName: ComputerToolName,\n): ComputerToolConfig | undefined {\n return workspace.getToolsConfig()?.[toolName];\n}\n\n/**\n * Format a screenshot as a MediaToolResult, falling back to text-only output\n * when the image exceeds the configured size cap (so huge base64 payloads\n * don't blow up the model context or storage).\n */\nexport function screenshotToResult(\n screenshot: ComputerScreenshot,\n text: string,\n maxMediaBytes: number,\n): MediaToolResult | string {\n if (screenshot.data.byteLength > maxMediaBytes) {\n return `${text} — screenshot (${screenshot.data.byteLength} bytes, ${screenshot.mediaType}) exceeds maxMediaBytes (${maxMediaBytes}). Returning text only; configure \\`maxMediaBytes\\` on the computer tool to raise this cap.`;\n }\n return {\n __workspaceMedia: true,\n text,\n mediaType: screenshot.mediaType,\n data: Buffer.from(screenshot.data).toString('base64'),\n };\n}\n\n/**\n * Finish a computer action tool: when `screenshotAfterAction` is enabled\n * (default), wait briefly for the UI to react and attach a fresh screenshot\n * to the result so computer-use loops see the resulting desktop state.\n * Screenshot failures never fail the action itself.\n */\nexport async function finishComputerAction(\n workspace: Workspace,\n computer: SandboxComputer,\n toolName: ComputerToolName,\n text: string,\n): Promise<MediaToolResult | string> {\n const config = getComputerToolConfig(workspace, toolName);\n const screenshotAfterAction = config?.screenshotAfterAction ?? DEFAULT_SCREENSHOT_AFTER_ACTION;\n if (!screenshotAfterAction) return text;\n\n const delayMs = config?.screenshotDelayMs ?? DEFAULT_SCREENSHOT_DELAY_MS;\n if (delayMs > 0) {\n await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n\n try {\n const screenshot = await computer.screenshot();\n const maxMediaBytes = config?.maxMediaBytes ?? DEFAULT_MAX_MEDIA_BYTES;\n return screenshotToResult(screenshot, text, maxMediaBytes);\n } catch {\n return `${text} (post-action screenshot failed)`;\n }\n}\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerClickTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.CLICK,\n description:\n 'Left-click at pixel coordinates on the sandbox desktop. Coordinates are measured from the top-left corner of the screen — take a screenshot first to find the right position.',\n inputSchema: z.object({\n x: z.number().int().min(0).describe('X coordinate in pixels from the left edge of the screen'),\n y: z.number().int().min(0).describe('Y coordinate in pixels from the top edge of the screen'),\n }),\n execute: async ({ x, y }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.CLICK);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'click',\n input: { x, y },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.leftClick(x, y);\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.CLICK,\n `Clicked at (${x}, ${y})`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerDoubleClickTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK,\n description:\n 'Double-click (left button) at pixel coordinates on the sandbox desktop. Use for opening files, folders, and applications.',\n inputSchema: z.object({\n x: z.number().int().min(0).describe('X coordinate in pixels from the left edge of the screen'),\n y: z.number().int().min(0).describe('Y coordinate in pixels from the top edge of the screen'),\n }),\n execute: async ({ x, y }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'doubleClick',\n input: { x, y },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.doubleClick(x, y);\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK,\n `Double-clicked at (${x}, ${y})`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerDragTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.DRAG,\n description:\n 'Drag from one position to another on the sandbox desktop: presses the left button at the start coordinates, moves to the end coordinates, and releases. Use for moving windows, selecting text, and drag-and-drop.',\n inputSchema: z.object({\n startX: z.number().int().min(0).describe('X coordinate to start the drag from'),\n startY: z.number().int().min(0).describe('Y coordinate to start the drag from'),\n endX: z.number().int().min(0).describe('X coordinate to drag to'),\n endY: z.number().int().min(0).describe('Y coordinate to drag to'),\n }),\n execute: async ({ startX, startY, endX, endY }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.DRAG);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'drag',\n input: { startX, startY, endX, endY },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.drag({ x: startX, y: startY }, { x: endX, y: endY });\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.DRAG,\n `Dragged from (${startX}, ${startY}) to (${endX}, ${endY})`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerGetScreenInfoTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.GET_SCREEN_INFO,\n description:\n 'Get the sandbox desktop screen dimensions and current mouse cursor position. Use to understand the coordinate space before clicking.',\n inputSchema: z.object({}),\n execute: async (_input, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.GET_SCREEN_INFO);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'getScreenInfo',\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n const [size, cursor] = await Promise.all([computer.getScreenSize(), computer.getCursorPosition()]);\n span.end({ success: true });\n return `Screen size: ${size.width}x${size.height}\\nCursor position: (${cursor.x}, ${cursor.y})`;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerMoveMouseTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE,\n description:\n 'Move the mouse cursor to pixel coordinates on the sandbox desktop without clicking. Use for hover states (tooltips, dropdown menus).',\n inputSchema: z.object({\n x: z.number().int().min(0).describe('X coordinate in pixels from the left edge of the screen'),\n y: z.number().int().min(0).describe('Y coordinate in pixels from the top edge of the screen'),\n }),\n execute: async ({ x, y }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'moveMouse',\n input: { x, y },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.moveMouse(x, y);\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE,\n `Moved mouse to (${x}, ${y})`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerPressKeyTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.PRESS_KEY,\n description:\n 'Press a key or key combination on the sandbox desktop keyboard. Pass a single key (e.g. \"Enter\", \"Tab\", \"Escape\") or an array for a hotkey chord (e.g. [\"ctrl\", \"s\"]).',\n inputSchema: z.object({\n key: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('A single key (e.g. \"Enter\") or an array of keys pressed together as a hotkey (e.g. [\"ctrl\", \"c\"])'),\n }),\n execute: async ({ key }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.PRESS_KEY);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'pressKey',\n input: { key },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.press(key);\n const label = Array.isArray(key) ? key.join('+') : key;\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.PRESS_KEY,\n `Pressed ${label}`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerRightClickTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK,\n description: 'Right-click at pixel coordinates on the sandbox desktop. Use for opening context menus.',\n inputSchema: z.object({\n x: z.number().int().min(0).describe('X coordinate in pixels from the left edge of the screen'),\n y: z.number().int().min(0).describe('Y coordinate in pixels from the top edge of the screen'),\n }),\n execute: async ({ x, y }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'rightClick',\n input: { x, y },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.rightClick(x, y);\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK,\n `Right-clicked at (${x}, ${y})`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { getComputerToolConfig, requireComputer, screenshotToResult } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { DEFAULT_MAX_MEDIA_BYTES, mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerScreenshotTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.SCREENSHOT,\n description:\n 'Take a screenshot of the sandbox desktop display. Returns the current screen as an image. Use this to see the desktop state before and after interacting with it.',\n inputSchema: z.object({}),\n execute: async (_input, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.SCREENSHOT);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'screenshot',\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n const screenshot = await computer.screenshot();\n const config = getComputerToolConfig(workspace, WORKSPACE_TOOLS.COMPUTER.SCREENSHOT);\n const maxMediaBytes = config?.maxMediaBytes ?? DEFAULT_MAX_MEDIA_BYTES;\n const result = screenshotToResult(\n screenshot,\n `Screenshot of the desktop (${screenshot.data.byteLength} bytes, ${screenshot.mediaType})`,\n maxMediaBytes,\n );\n span.end({ success: true }, { bytesTransferred: screenshot.data.byteLength });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerScrollTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.SCROLL,\n description: 'Scroll the sandbox desktop display up or down.',\n inputSchema: z.object({\n direction: z.enum(['up', 'down']).describe('Scroll direction'),\n amount: z.number().int().min(1).optional().describe('Scroll amount in ticks (default: 3)'),\n }),\n execute: async ({ direction, amount }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.SCROLL);\n\n const effectiveAmount = amount ?? 3;\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'scroll',\n input: { direction, amount: effectiveAmount },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.scroll(direction, effectiveAmount);\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.SCROLL,\n `Scrolled ${direction} by ${effectiveAmount}`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerTypeTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.TYPE,\n description:\n 'Type text into the focused element on the sandbox desktop using the keyboard. Click an input field first to focus it. Use the press-key tool for special keys (Enter, Tab, shortcuts).',\n inputSchema: z.object({\n text: z.string().describe('The text to type'),\n }),\n execute: async ({ text }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.TYPE);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'type',\n input: { length: text.length },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await computer.type(text);\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.TYPE,\n `Typed ${text.length} characters`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { finishComputerAction, requireComputer } from './computer-helpers';\nimport { emitWorkspaceMetadata } from './helpers';\nimport { mediaToModelOutput } from './media';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const computerWaitTool = createTool({\n id: WORKSPACE_TOOLS.COMPUTER.WAIT,\n description:\n 'Wait for the sandbox desktop UI to settle (e.g. an application launching or a page loading) before the next action.',\n inputSchema: z.object({\n seconds: z.number().min(0.1).max(30).describe('How long to wait, in seconds (max 30)'),\n }),\n execute: async ({ seconds }, context) => {\n const { workspace, sandbox, computer } = requireComputer(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.COMPUTER.WAIT);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'computer',\n operation: 'wait',\n input: { seconds },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n try {\n await new Promise(resolve => setTimeout(resolve, seconds * 1000));\n const result = await finishComputerAction(\n workspace,\n computer,\n WORKSPACE_TOOLS.COMPUTER.WAIT,\n `Waited ${seconds}s`,\n );\n span.end({ success: true });\n return result;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { WorkspaceReadOnlyError } from '../errors';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const deleteFileTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.DELETE,\n description: 'Delete a file or directory from the workspace filesystem',\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().describe('The path to the file or directory to delete'),\n recursive: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, delete directories and their contents recursively. Required for non-empty directories.'),\n }),\n execute: async ({ path, recursive }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.DELETE);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'delete',\n input: { path, recursive },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n if (filesystem.readOnly) {\n throw new WorkspaceReadOnlyError('delete');\n }\n\n const stat = await filesystem.stat(path);\n if (stat.type === 'directory') {\n await filesystem.rmdir(path, { recursive, force: recursive });\n } else {\n await filesystem.deleteFile(path);\n }\n\n span.end({ success: true });\n return `Deleted ${path}`;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","/**\n * Line Utilities\n *\n * Utility functions for working with line-based content:\n * - Extract lines by range\n * - Convert character positions to line numbers\n * - Format content with line number prefixes\n */\n\n/**\n * Line range where content was found\n */\nexport interface LineRange {\n /** Starting line number (1-indexed) */\n start: number;\n /** Ending line number (1-indexed, inclusive) */\n end: number;\n}\n\n/**\n * Extract lines from content by line range.\n *\n * @param content - The document content\n * @param startLine - Starting line number (1-indexed)\n * @param endLine - Ending line number (1-indexed, inclusive)\n * @returns Object with extracted content and metadata\n */\nexport function extractLines(\n content: string,\n startLine?: number,\n endLine?: number,\n): {\n content: string;\n lines: { start: number; end: number };\n totalLines: number;\n} {\n const allLines = content.split('\\n');\n const totalLines = allLines.length;\n\n // Default to full content\n const start = Math.max(1, startLine ?? 1);\n const end = Math.min(totalLines, endLine ?? totalLines);\n\n if (start > end) {\n return {\n content: '',\n lines: { start: 0, end: 0 },\n totalLines,\n };\n }\n\n // Extract the requested range (convert to 0-indexed)\n const extractedLines = allLines.slice(start - 1, end);\n\n return {\n content: extractedLines.join('\\n'),\n lines: { start, end },\n totalLines,\n };\n}\n\n/**\n * Extract lines using offset/limit style parameters (like Claude Code).\n *\n * @param content - The document content\n * @param offset - Line number to start from (1-indexed, default: 1)\n * @param limit - Maximum number of lines to read (default: all remaining)\n * @returns Object with extracted content and metadata\n */\nexport function extractLinesWithLimit(\n content: string,\n offset?: number,\n limit?: number,\n): {\n content: string;\n lines: { start: number; end: number };\n totalLines: number;\n} {\n const startLine = offset ?? 1;\n const endLine = limit ? startLine + limit - 1 : undefined;\n return extractLines(content, startLine, endLine);\n}\n\n/**\n * Format content with line number prefixes.\n * Output format matches Claude Code: \" 1→content here\"\n *\n * @param content - The content to format\n * @param startLineNumber - The line number of the first line (1-indexed)\n * @returns Formatted content with line numbers\n */\nexport function formatWithLineNumbers(content: string, startLineNumber: number = 1): string {\n const lines = content.split('\\n');\n const maxLineNum = startLineNumber + lines.length - 1;\n const padWidth = Math.max(6, String(maxLineNum).length + 1);\n\n return lines\n .map((line, i) => {\n const lineNum = startLineNumber + i;\n return `${String(lineNum).padStart(padWidth)}→${line}`;\n })\n .join('\\n');\n}\n\n/**\n * Convert a character index to a line number.\n * Useful for converting RAG chunk character offsets to line numbers.\n *\n * @param content - The full document content\n * @param charIndex - The character index (0-indexed)\n * @returns The line number (1-indexed), or undefined if charIndex is out of bounds\n */\nexport function charIndexToLineNumber(content: string, charIndex: number): number | undefined {\n if (charIndex < 0 || charIndex > content.length) {\n return undefined;\n }\n\n // Count newlines before the character index\n let lineNumber = 1;\n for (let i = 0; i < charIndex && i < content.length; i++) {\n if (content[i] === '\\n') {\n lineNumber++;\n }\n }\n\n return lineNumber;\n}\n\n/**\n * Convert character range to line range.\n * Useful for converting RAG chunk character offsets to line ranges.\n *\n * @param content - The full document content\n * @param startCharIdx - Start character index (0-indexed)\n * @param endCharIdx - End character index (0-indexed, exclusive)\n * @returns LineRange (1-indexed) or undefined if indices are out of bounds\n */\nexport function charRangeToLineRange(content: string, startCharIdx: number, endCharIdx: number): LineRange | undefined {\n const startLine = charIndexToLineNumber(content, startCharIdx);\n // For end, we want the line containing the last character (endCharIdx - 1)\n const endLine = charIndexToLineNumber(content, Math.max(0, endCharIdx - 1));\n\n if (startLine === undefined || endLine === undefined) {\n return undefined;\n }\n\n return { start: startLine, end: endLine };\n}\n\n/**\n * Count occurrences of a string in content.\n *\n * @param content - The content to search\n * @param searchString - The string to find\n * @returns Number of occurrences\n */\nexport function countOccurrences(content: string, searchString: string): number {\n if (!searchString) return 0;\n\n let count = 0;\n let position = 0;\n\n while ((position = content.indexOf(searchString, position)) !== -1) {\n count++;\n position += searchString.length;\n }\n\n return count;\n}\n\n/**\n * Replace a string in content, with validation for uniqueness.\n *\n * @param content - The content to modify\n * @param oldString - The string to find and replace\n * @param newString - The replacement string\n * @param replaceAll - If true, replace all occurrences; if false, require unique match\n * @returns Object with result content and metadata\n * @throws Error if oldString is not found or not unique (when replaceAll is false)\n */\nexport function replaceString(\n content: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n): {\n content: string;\n replacements: number;\n} {\n const count = countOccurrences(content, oldString);\n\n if (count === 0) {\n throw new StringNotFoundError(oldString);\n }\n\n if (!replaceAll && count > 1) {\n throw new StringNotUniqueError(oldString, count);\n }\n\n // Escape $ in newString to prevent replacement pattern interpretation.\n // In String.prototype.replace(), $& means \"matched substring\", $$ means literal $, etc.\n // We want literal replacement, so escape all $ as $$.\n const escapedNewString = newString.replace(/\\$/g, '$$$$');\n if (replaceAll) {\n // Replace all occurrences - split/join doesn't interpret $ patterns\n const result = content.split(oldString).join(newString);\n return { content: result, replacements: count };\n }\n // Replace first (and only) occurrence - use escaped string\n const result = content.replace(oldString, escapedNewString);\n return { content: result, replacements: 1 };\n}\n\n/**\n * Error thrown when string is not found during replacement.\n */\nexport class StringNotFoundError extends Error {\n constructor(public readonly searchString: string) {\n super(`The specified text was not found. Make sure you use the exact text from the file.`);\n this.name = 'StringNotFoundError';\n }\n}\n\n/**\n * Error thrown when string appears multiple times but unique match required.\n */\nexport class StringNotUniqueError extends Error {\n constructor(\n public readonly searchString: string,\n public readonly occurrences: number,\n ) {\n super(\n `The specified text appears ${occurrences} times. Provide more surrounding context to make the match unique, or use replace_all to replace all occurrences.`,\n );\n this.name = 'StringNotUniqueError';\n }\n}\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { WorkspaceReadOnlyError } from '../errors';\nimport { charRangeToLineRange, replaceString, StringNotFoundError, StringNotUniqueError } from '../line-utils';\nimport { emitWorkspaceMetadata, getEditDiagnosticsText, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nfunction getEditedLineRanges(content: string, oldString: string, newString: string, replaceAll: boolean): string {\n if (!oldString) return '';\n const ranges: string[] = [];\n let position = 0;\n\n while ((position = content.indexOf(oldString, position)) !== -1) {\n const range = charRangeToLineRange(content, position, position + Math.max(oldString.length, 1));\n if (range) {\n const newLineCount = newString.split('\\n').length;\n const end = range.start + Math.max(newLineCount, range.end - range.start + 1) - 1;\n ranges.push(end === range.start ? String(range.start) : `${range.start}-${end}`);\n }\n position += oldString.length;\n if (!replaceAll) break;\n }\n\n if (ranges.length === 0) return '';\n return ranges.length === 1 ? ` (lines ${ranges[0]})` : ` (lines ${ranges.join(', ')})`;\n}\n\nexport const editFileTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,\n description: `Edit a file by replacing specific text. The old_string must match exactly and be unique in the file.\n\nUsage:\n- Read the file first to get the exact text to replace.\n- By default, read file output includes line number prefixes (e.g., \" 1→\"). Ensure you preserve the exact indentation as it appears AFTER the arrow. Never include any part of the line number prefix in old_string or new_string.\n- Include enough surrounding context (multiple lines) to make old_string unique. If it still isn't unique, include more lines.\n- Use replace_all only when intentionally replacing all occurrences.`,\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().describe('The path to the file to edit'),\n old_string: z.string().describe('The exact text to find and replace. Must be unique in the file.'),\n new_string: z.string().describe('The text to replace old_string with'),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, replace all occurrences. If false (default), old_string must be unique.'),\n }),\n execute: async ({ path, old_string, new_string, replace_all }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'editFile',\n input: { path, replace_all },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n if (filesystem.readOnly) {\n throw new WorkspaceReadOnlyError('edit_file');\n }\n\n const content = await filesystem.readFile(path, { encoding: 'utf-8' });\n\n if (typeof content !== 'string') {\n span.end({ success: false });\n return `Cannot edit binary files. Use the write file tool instead.`;\n }\n\n const shouldReplaceAll = replace_all ?? false;\n const lineRanges = getEditedLineRanges(content, old_string, new_string, shouldReplaceAll);\n const result = replaceString(content, old_string, new_string, shouldReplaceAll);\n await filesystem.writeFile(path, result.content, {\n overwrite: true,\n expectedMtime: (context as any)?.__expectedMtime,\n });\n\n let output = `Replaced ${result.replacements} occurrence${result.replacements !== 1 ? 's' : ''} in ${path}${lineRanges}`;\n output += await getEditDiagnosticsText(workspace, path, result.content);\n span.end({ success: true }, { bytesTransferred: Buffer.byteLength(result.content, 'utf-8') });\n return output;\n } catch (error) {\n if (error instanceof StringNotFoundError) {\n span.end({ success: false });\n return error.message;\n }\n if (error instanceof StringNotUniqueError) {\n span.end({ success: false });\n return error.message;\n }\n span.error(error);\n throw error;\n }\n },\n});\n","import { createHash } from 'node:crypto';\nimport { shellQuote, splitShellCommand, reassembleShellCommand } from '../workspace/sandbox/utils';\nimport type { MastraBrowser } from './browser';\n\n/**\n * Configuration for a browser CLI provider.\n */\nexport interface BrowserCliConfig {\n /** Regex pattern to match the CLI command */\n pattern: RegExp;\n /** Flag used to pass CDP URL to the CLI */\n flag: string;\n /** Flag to pass threadId as session name for isolation */\n sessionFlag?: string;\n /** Command to run before other commands to establish CDP connection */\n warmupCommand?: (cdpUrl: string, threadId: string) => string;\n /** Pattern to detect agent-provided external CDP */\n externalCdpPattern?: RegExp;\n /** Pattern to extract the CDP URL from command (with capture group) */\n externalCdpExtractor?: RegExp;\n}\n\n/**\n * CLI provider patterns for CDP URL injection.\n * Maps CLI command prefixes to their CDP URL flag.\n * All CLIs accept either port number or full WebSocket URL.\n * We use full URL for consistency.\n *\n * warmupCommand: Some CLIs (like agent-browser) need a \"connect\" command\n * to be run first to establish their daemon's CDP connection before other\n * commands will work properly.\n */\nconst CLI_CDP_PATTERNS: Record<string, BrowserCliConfig> = {\n 'agent-browser': {\n pattern: /^agent-browser\\b/,\n flag: '--cdp',\n sessionFlag: '--session',\n // agent-browser daemon needs explicit connect command to establish CDP connection\n // Must include session flag to isolate threads\n warmupCommand: (cdpUrl: string, threadId: string) =>\n `agent-browser --session ${shellQuote(threadId)} connect ${shellQuote(cdpUrl)}`,\n // agent-browser external CDP detection:\n // - \"connect <url>\" subcommand for external CDP\n // - \"--cdp <url>\" with full wss:// URL (not just port) also indicates external CDP\n // External CDP: \"connect <url>\", \"--cdp <url>\", or \"--cdp <port>\"\n externalCdpPattern: /(?:\\bconnect\\s+[\"']?wss?:\\/\\/|--cdp\\s+[\"']?\\S)/,\n // Extract URL from: connect \"wss://...\" or --cdp \"wss://...\" (ports don't have extractable URLs)\n externalCdpExtractor: /(?:\\bconnect|--cdp)\\s+[\"']?(wss?:\\/\\/[^\\s\"']+)[\"']?/,\n },\n 'browser-use': {\n // browser-use CLI installs as multiple aliases: browser, browseruse, bu\n // The skill docs say \"browser-use\" but the primary binary is \"browser\"\n // Order matters: longer matches first to avoid \"browser\" matching before \"browser-use\"\n pattern: /^(?:browser-use|browseruse|browser|bu)\\b/,\n flag: '--cdp-url',\n sessionFlag: '--session',\n // browser-use uses --cdp-url for external CDP\n externalCdpPattern: /--cdp-url\\s+[\"']?\\S+/,\n // Extract URL from: --cdp-url \"wss://...\" or --cdp-url 'wss://...' or --cdp-url wss://...\n externalCdpExtractor: /--cdp-url\\s+[\"']?(wss?:\\/\\/[^\\s\"']+)[\"']?/,\n },\n browse: {\n pattern: /^browse\\b/,\n flag: '--ws',\n // browse uses --ws for external CDP\n externalCdpPattern: /--ws\\s+[\"']?\\S+/,\n // Extract URL from: --ws \"wss://...\" or --ws 'wss://...' or --ws wss://...\n externalCdpExtractor: /--ws\\s+[\"']?(wss?:\\/\\/[^\\s\"']+)[\"']?/,\n },\n};\n\n/**\n * Result of processing a command for browser CLI handling.\n */\nexport interface BrowserCliProcessResult {\n /** The (potentially modified) command to execute */\n command: string;\n /** Warmup commands that need to be run before the main command */\n warmupCommands: string[];\n /** Whether external CDP was detected (agent managing their own browser) */\n usingExternalCdp: boolean;\n /** External CDP URL if detected */\n externalCdpUrl?: string;\n}\n\n/**\n * Handles browser CLI detection, CDP injection, and warmup for execute_command.\n * Centralizes all browser CLI-specific logic that was previously in execute-command.ts.\n */\nexport class BrowserCliHandler {\n /**\n * Track which CLI providers have been warmed up per browser instance and thread.\n * Key format: `${browserId}:${cliName}:${threadId}`\n * Browser ID scopes warmup state so different agents/workspaces don't share state.\n * @internal Exposed for testing\n */\n warmedUpClis = new Set<string>();\n\n /**\n * Track cleanup callbacks for warmed up CLIs to avoid duplicate registrations.\n * Key format: `${browserId}:${cliName}:${threadId}`\n * @internal Exposed for testing\n */\n warmupCleanups = new Map<string, () => void>();\n\n /**\n * Build a warmup key scoped to browser instance.\n */\n private makeWarmupKey(browserId: string, cliName: string, threadId: string): string {\n return `${browserId}:${cliName}:${threadId}`;\n }\n\n /**\n * Check if a command is a browser CLI command and return its config.\n */\n getBrowserCliConfig(command: string): { name: string; config: BrowserCliConfig } | null {\n for (const [name, config] of Object.entries(CLI_CDP_PATTERNS)) {\n if (config.pattern.test(command)) {\n return { name, config };\n }\n }\n return null;\n }\n\n /**\n * Check if any browser CLI command already has a CDP flag specified.\n * If so, the agent is managing their own CDP connection and we should skip injection.\n */\n hasExternalCdpFlag(parts: string[]): boolean {\n for (const part of parts) {\n const match = this.getBrowserCliConfig(part.trim());\n if (match) {\n // Use provider-specific pattern if available, otherwise fall back to flag pattern\n if (match.config.externalCdpPattern) {\n if (match.config.externalCdpPattern.test(part)) {\n return true;\n }\n } else {\n const flagPattern = new RegExp(`${match.config.flag}\\\\s+\\\\S+`);\n if (flagPattern.test(part)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n * Extract external CDP URL from command parts.\n * Returns the first CDP URL found, or null if none.\n */\n extractExternalCdpUrl(parts: string[]): string | null {\n for (const part of parts) {\n const match = this.getBrowserCliConfig(part.trim());\n if (match?.config.externalCdpExtractor) {\n const urlMatch = part.match(match.config.externalCdpExtractor);\n if (urlMatch?.[1]) {\n return urlMatch[1];\n }\n }\n }\n return null;\n }\n\n /**\n * Inject CDP URL and session flag into a single browser CLI command.\n * Returns the modified command or the original if no injection needed.\n */\n private injectCdpUrlIntoSingleCommand(\n command: string,\n cdpUrl: string,\n config: BrowserCliConfig,\n threadId?: string,\n ): string {\n // Check if CDP flag is already present\n const flagPattern = new RegExp(`${config.flag}\\\\s+\\\\S+`);\n if (flagPattern.test(command)) {\n return command; // Already has CDP URL, don't override\n }\n\n // Build injection: CDP URL + session flag (for thread isolation)\n // Use shell escaping to prevent command injection from crafted values\n let injection = `${config.flag} ${shellQuote(cdpUrl)}`;\n if (config.sessionFlag && threadId) {\n // Check if session flag already present\n const sessionPattern = new RegExp(`${config.sessionFlag}\\\\s+\\\\S+`);\n if (!sessionPattern.test(command)) {\n injection += ` ${config.sessionFlag} ${shellQuote(threadId)}`;\n }\n }\n\n // Inject flags after the CLI command name\n return command.replace(config.pattern, `$& ${injection}`);\n }\n\n /**\n * Inject CDP URL and session flag into all browser CLI commands in a potentially\n * chained command string (commands joined by &&, ||, or ;).\n */\n injectCdpUrl(command: string, cdpUrl: string, threadId?: string): string {\n const { header, suffix } = this.getShellHeader(command);\n const headerParts = splitShellCommand(header);\n if (headerParts.parts.some(part => this.isBrowserUseStdinCommand(part))) {\n const modifiedParts = headerParts.parts.map(part => {\n const trimmed = part.trim();\n const cliMatch = this.getBrowserCliConfig(trimmed);\n return cliMatch && !this.isBrowserUseStdinCommand(trimmed)\n ? this.injectCdpUrlIntoSingleCommand(trimmed, cdpUrl, cliMatch.config, threadId)\n : part;\n });\n const transformed = modifiedParts.some((part, index) => part !== headerParts.parts[index])\n ? reassembleShellCommand(modifiedParts, headerParts.operators) + suffix\n : command;\n const name = createHash('sha256')\n .update(JSON.stringify([threadId ?? 'default', cdpUrl]))\n .digest('hex')\n .slice(0, 16);\n return `BU_CDP_WS=${shellQuote(cdpUrl)} BU_NAME=${shellQuote(`mastra-${name}`)} sh -c ${shellQuote(transformed)}`;\n }\n\n const { parts, operators } = splitShellCommand(command);\n\n const modifiedParts = parts.map((part: string) => {\n const trimmed = part.trim();\n const cliMatch = this.getBrowserCliConfig(trimmed);\n if (cliMatch) {\n return this.injectCdpUrlIntoSingleCommand(trimmed, cdpUrl, cliMatch.config, threadId);\n }\n return part; // Keep original (preserves whitespace)\n });\n\n return reassembleShellCommand(modifiedParts, operators);\n }\n\n /**\n * Check if a warmup has been completed for a browser/CLI/thread combination.\n */\n isWarmedUp(browserId: string, cliName: string, threadId: string): boolean {\n return this.warmedUpClis.has(this.makeWarmupKey(browserId, cliName, threadId));\n }\n\n /**\n * Mark a browser/CLI/thread combination as warmed up.\n */\n markWarmedUp(browserId: string, cliName: string, threadId: string): void {\n this.warmedUpClis.add(this.makeWarmupKey(browserId, cliName, threadId));\n }\n\n /**\n * Register a cleanup callback for when a browser closes.\n * The cleanup will remove the warmup state for the given browser/CLI/thread.\n */\n registerWarmupCleanup(browserId: string, cliName: string, threadId: string, browser: MastraBrowser): void {\n const warmupKey = this.makeWarmupKey(browserId, cliName, threadId);\n if (!this.warmupCleanups.has(warmupKey)) {\n const cleanup = browser.onBrowserClosed(() => {\n this.warmedUpClis.delete(warmupKey);\n this.warmupCleanups.delete(warmupKey);\n }, threadId);\n this.warmupCleanups.set(warmupKey, cleanup);\n }\n }\n\n /**\n * Get warmup commands that need to be run for the detected browser CLIs.\n */\n getWarmupCommands(\n browserId: string,\n browserClis: Array<{ name: string; config: BrowserCliConfig }>,\n cdpUrl: string,\n threadId: string,\n ): Array<{ cliName: string; command: string }> {\n const warmups: Array<{ cliName: string; command: string }> = [];\n const seen = new Set<string>();\n\n for (const { name: cliName, config: cliConfig } of browserClis) {\n // Deduplicate: if same CLI appears multiple times in chained command, only warmup once\n if (seen.has(cliName)) continue;\n seen.add(cliName);\n\n if (cliConfig.warmupCommand && !this.isWarmedUp(browserId, cliName, threadId)) {\n warmups.push({\n cliName,\n command: cliConfig.warmupCommand(cdpUrl, threadId),\n });\n }\n }\n\n return warmups;\n }\n\n private getShellHeader(command: string): { header: string; suffix: string } {\n // Join shell continuations in the header only; never inspect a heredoc body.\n let header = '';\n let quote = '';\n let continued = false;\n let hasHeredoc = false;\n const source = command.trimStart();\n let i = 0;\n for (; i < source.length; i++) {\n const char = source[i]!;\n if (char === '\\\\' && quote !== \"'\" && i + 1 < source.length) {\n const next = source[++i]!;\n if (next !== '\\n') {\n header += char + next;\n continued = false;\n }\n continue;\n }\n if (char === '\\n' && !quote) {\n // A pending heredoc starts its payload here, even after a shell operator.\n if (hasHeredoc || !continued) break;\n header += ' ';\n continue;\n }\n if (!quote && (source.slice(i, i + 2) === '&&' || source.slice(i, i + 2) === '||')) {\n header += source.slice(i, i + 2);\n i++;\n continued = true;\n continue;\n }\n if (!quote && source.slice(i, i + 2) === '<<') hasHeredoc = true;\n if (!/\\s/.test(char)) continued = !quote && (char === '|' || char === ';');\n if (char === quote) quote = '';\n else if (!quote && (char === \"'\" || char === '\"')) quote = char;\n header += char;\n }\n return { header, suffix: source.slice(i) };\n }\n\n private isBrowserUseStdinCommand(command: string): boolean {\n const word = String.raw`(?:[^\\s<>;&|\"'\\\\]|\\\\.|\"[^\"]*\"|'[^']*')+`;\n const redirection = String.raw`\\d*(?:<<-?|>>?|<|[<>]&|<>|>\\|)\\s*${word}\\s*`;\n const stdinInvocation = new RegExp(\n String.raw`^\\s*(?:browser-use|browseruse|browser|bu)(?=\\s|[<>]|$)\\s*(?:${redirection})*$`,\n );\n return stdinInvocation.test(command);\n }\n\n /**\n * Process a command for browser CLI handling.\n * Detects browser CLIs, checks for external CDP, and prepares injection.\n *\n * This is the main entry point - call this from execute-command.ts.\n */\n analyzeCommand(command: string): {\n /** Detected browser CLIs in the command */\n browserClis: Array<{ name: string; config: BrowserCliConfig }>;\n /** Command parts split by shell operators */\n parts: string[];\n /** Whether external CDP was detected */\n usingExternalCdp: boolean;\n /** External CDP URL if detected */\n externalCdpUrl: string | null;\n } {\n // Python on stdin is opaque: shell splitting and flag detection would inspect its contents.\n const { header } = this.getShellHeader(command);\n const headerParts = splitShellCommand(header).parts;\n if (headerParts.some(part => this.isBrowserUseStdinCommand(part))) {\n const browserClis = headerParts\n .map(part => this.getBrowserCliConfig(part.trim()))\n .filter((match): match is NonNullable<typeof match> => match !== null);\n const legacyParts = headerParts.filter(part => !this.isBrowserUseStdinCommand(part));\n const usingExternalCdp = this.hasExternalCdpFlag(legacyParts);\n return {\n browserClis,\n parts: [command],\n usingExternalCdp,\n externalCdpUrl: usingExternalCdp ? this.extractExternalCdpUrl(legacyParts) : null,\n };\n }\n\n const { parts } = splitShellCommand(command);\n\n const browserClis = parts\n .map((part: string) => this.getBrowserCliConfig(part.trim()))\n .filter((match): match is NonNullable<typeof match> => match !== null);\n\n const usingExternalCdp = this.hasExternalCdpFlag(parts);\n const externalCdpUrl = usingExternalCdp ? this.extractExternalCdpUrl(parts) : null;\n\n return {\n browserClis,\n parts,\n usingExternalCdp,\n externalCdpUrl,\n };\n }\n}\n\n/**\n * Singleton instance for use across the application.\n * This preserves warmup state across command executions.\n */\nexport const browserCliHandler = new BrowserCliHandler();\n","//#region src/segments.ts\nconst PATTERNS = {\n\twhitespace: /^\\s+$/,\n\tstructuredWhitespace: /\\n\\s/,\n\tcjk: /[\\u4E00-\\u9FFF\\u3400-\\u4DBF\\u3000-\\u30FF\\uFF00-\\uFFEF\\u2E80-\\u2EFF\\u31C0-\\u31EF\\u3200-\\u32FF\\u3300-\\u33FF\\uAC00-\\uD7AF\\u1100-\\u11FF\\u3130-\\u318F\\uA960-\\uA97F\\uD7B0-\\uD7FF]/,\n\tnumeric: /^\\d+$/,\n\tpunctuation: /[.,!?;(){}[\\]<>:/\\\\|@#$%^&*+=`~_\"-]/\n};\nconst TOKEN_SPLIT_PATTERN = new RegExp(`(\\\\s+|${PATTERNS.punctuation.source}+)`);\nconst DEFAULT_CHARS_PER_TOKEN = 6;\nconst SHORT_TOKEN_THRESHOLD = 3;\nconst KANA_CHARS_PER_TOKEN = 1.35;\nconst DEFAULT_LANGUAGE_CONFIGS = [\n\t{\n\t\tpattern: /[äöüßẞ]/i,\n\t\taverageCharsPerToken: 2.6\n\t},\n\t{\n\t\tpattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,\n\t\taverageCharsPerToken: 3\n\t},\n\t{\n\t\tpattern: /[ąćęłńóśźżěščřžýůúďťň]/i,\n\t\taverageCharsPerToken: 2.5\n\t},\n\t{\n\t\tpattern: /[\\u0430-\\u044F\\u0451]/i,\n\t\taverageCharsPerToken: 4\n\t},\n\t{\n\t\tpattern: /[\\u03AC-\\u03CE]/i,\n\t\taverageCharsPerToken: 2.75\n\t},\n\t{\n\t\tpattern: /^\\p{Extended_Pictographic}[\\p{Extended_Pictographic}\\p{Emoji_Component}]*$/u,\n\t\taverageCharsPerToken: .75\n\t}\n];\n/**\n* Walks a text as (segment, estimated token count) pairs. The segments\n* concatenate back to the original text; whitespace segments count zero\n* tokens unless they carry structure (indentation or blank lines).\n*/\nfunction* walkSegments(text, options = {}) {\n\tif (!text) return;\n\tconst resolvedOptions = resolveOptions(options);\n\tfor (const segment of text.split(TOKEN_SPLIT_PATTERN)) if (segment) yield {\n\t\tsegment,\n\t\ttokenCount: estimateSegmentTokens(segment, resolvedOptions)\n\t};\n}\nfunction resolveOptions(options) {\n\treturn {\n\t\tdefaultCharsPerToken: options.defaultCharsPerToken ?? DEFAULT_CHARS_PER_TOKEN,\n\t\tlanguageConfigs: options.languageConfigs ?? DEFAULT_LANGUAGE_CONFIGS\n\t};\n}\nfunction estimateSegmentTokens(segment, { languageConfigs, defaultCharsPerToken }) {\n\tif (PATTERNS.whitespace.test(segment)) return PATTERNS.structuredWhitespace.test(segment) ? 1 : 0;\n\tconst languageCharsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs);\n\tif (languageCharsPerToken !== void 0) return Math.ceil(getCharacterCount(segment) / languageCharsPerToken);\n\tif (PATTERNS.cjk.test(segment)) return estimateCjkTokens(segment);\n\tif (PATTERNS.numeric.test(segment)) return Math.ceil(segment.length / 3);\n\tif (segment.length <= SHORT_TOKEN_THRESHOLD) return 1;\n\tif (PATTERNS.punctuation.test(segment)) return Math.ceil(segment.length / 2);\n\treturn Math.ceil(segment.length / defaultCharsPerToken);\n}\nfunction getLanguageSpecificCharsPerToken(segment, languageConfigs) {\n\tfor (const config of languageConfigs) if (segment.search(config.pattern) !== -1) return config.averageCharsPerToken;\n}\nfunction getCharacterCount(text) {\n\treturn Array.from(text).length;\n}\nfunction estimateCjkTokens(segment) {\n\tlet kanaCount = 0;\n\tlet otherCount = 0;\n\tfor (const character of segment) {\n\t\tconst codePoint = character.codePointAt(0);\n\t\tif (codePoint >= 12352 && codePoint <= 12543) kanaCount++;\n\t\telse otherCount++;\n\t}\n\treturn otherCount + Math.ceil(kanaCount / KANA_CHARS_PER_TOKEN);\n}\n//#endregion\n//#region src/index.ts\n/**\n* Checks if a text string is within a specified token limit\n*/\nfunction isWithinTokenLimit(text, tokenLimit, options) {\n\treturn estimateTokenCount(text, options) <= tokenLimit;\n}\n/** @deprecated Use `estimateTokenCount` instead */\nconst approximateTokenSize = estimateTokenCount;\n/**\n* Estimates the number of tokens in a text string using heuristic rules\n*/\nfunction estimateTokenCount(text, options = {}) {\n\tif (!text) return 0;\n\tlet tokenCount = 0;\n\tfor (const segmentEstimate of walkSegments(text, options)) tokenCount += segmentEstimate.tokenCount;\n\treturn tokenCount;\n}\n/**\n* Extracts a portion of text based on token positions, similar to Array.prototype.slice()\n*/\nfunction sliceByTokens(text, start = 0, end, options = {}) {\n\tif (!text) return \"\";\n\tlet segmentEstimates = walkSegments(text, options);\n\tlet totalTokens = 0;\n\tif (start < 0 || end !== void 0 && end < 0) {\n\t\tconst bufferedEstimates = Array.from(segmentEstimates);\n\t\tfor (const { tokenCount } of bufferedEstimates) totalTokens += tokenCount;\n\t\tsegmentEstimates = bufferedEstimates;\n\t}\n\tconst normalizedStart = start < 0 ? Math.max(0, totalTokens + start) : Math.max(0, start);\n\tconst normalizedEnd = end === void 0 ? Infinity : end < 0 ? Math.max(0, totalTokens + end) : end;\n\tif (normalizedStart >= normalizedEnd) return \"\";\n\tconst parts = [];\n\tlet currentTokenPos = 0;\n\tfor (const { segment, tokenCount } of segmentEstimates) {\n\t\tif (currentTokenPos >= normalizedEnd) break;\n\t\tconst extracted = extractSegmentPart(segment, currentTokenPos, tokenCount, normalizedStart, normalizedEnd);\n\t\tif (extracted) parts.push(extracted);\n\t\tcurrentTokenPos += tokenCount;\n\t}\n\treturn parts.join(\"\");\n}\n/**\n* Splits text into chunks based on token count\n*/\nfunction splitByTokens(text, tokensPerChunk, options = {}) {\n\tif (!text || tokensPerChunk <= 0) return [];\n\tconst overlap = Math.max(0, Math.min(options.overlap ?? 0, tokensPerChunk - 1));\n\tconst chunks = [];\n\tlet currentChunk = [];\n\tlet currentTokenCount = 0;\n\tlet hasUnchunkedSegments = false;\n\tfor (const segmentEstimate of walkSegments(text, options)) {\n\t\tcurrentChunk.push(segmentEstimate);\n\t\tcurrentTokenCount += segmentEstimate.tokenCount;\n\t\thasUnchunkedSegments = true;\n\t\tif (currentTokenCount >= tokensPerChunk) {\n\t\t\tchunks.push(joinSegments(currentChunk));\n\t\t\thasUnchunkedSegments = false;\n\t\t\tif (overlap > 0) {\n\t\t\t\tconst overlapSegments = [];\n\t\t\t\tlet overlapTokenCount = 0;\n\t\t\t\tfor (let i = currentChunk.length - 1; i >= 0 && overlapTokenCount < overlap; i--) {\n\t\t\t\t\tconst overlapCandidate = currentChunk[i];\n\t\t\t\t\toverlapSegments.unshift(overlapCandidate);\n\t\t\t\t\toverlapTokenCount += overlapCandidate.tokenCount;\n\t\t\t\t}\n\t\t\t\tcurrentChunk = overlapSegments;\n\t\t\t\tcurrentTokenCount = overlapTokenCount;\n\t\t\t} else {\n\t\t\t\tcurrentChunk = [];\n\t\t\t\tcurrentTokenCount = 0;\n\t\t\t}\n\t\t}\n\t}\n\tif (currentChunk.length > 0 && hasUnchunkedSegments) chunks.push(joinSegments(currentChunk));\n\treturn chunks;\n}\nfunction joinSegments(segmentEstimates) {\n\tlet joined = \"\";\n\tfor (const { segment } of segmentEstimates) joined += segment;\n\treturn joined;\n}\nfunction extractSegmentPart(segment, segmentTokenStart, segmentTokenCount, targetStart, targetEnd) {\n\tif (segmentTokenCount === 0) return segmentTokenStart >= targetStart && segmentTokenStart < targetEnd ? segment : \"\";\n\tconst segmentTokenEnd = segmentTokenStart + segmentTokenCount;\n\tif (segmentTokenStart >= targetEnd || segmentTokenEnd <= targetStart) return \"\";\n\tconst overlapStart = Math.max(0, targetStart - segmentTokenStart);\n\tconst overlapEnd = Math.min(segmentTokenCount, targetEnd - segmentTokenStart);\n\tif (overlapStart === 0 && overlapEnd === segmentTokenCount) return segment;\n\tconst charStart = Math.floor(overlapStart / segmentTokenCount * segment.length);\n\tconst charEnd = Math.ceil(overlapEnd / segmentTokenCount * segment.length);\n\treturn segment.slice(charStart, charEnd);\n}\n//#endregion\nexport { approximateTokenSize, estimateTokenCount, isWithinTokenLimit, sliceByTokens, splitByTokens };\n","import { sliceByTokens } from 'tokenx';\n\n// Unicode mode matches lone surrogate code points without matching complete pairs.\nconst UNPAIRED_SURROGATE_RE = /[\\uD800-\\uDFFF]/gu;\n\n/**\n * `sliceByTokens` from tokenx cuts on UTF-16 code-unit boundaries, so a cut can\n * land inside a surrogate pair (emoji, CJK ext B+, math alphanumerics) and leave\n * an unpaired surrogate. That is invalid UTF-16: it degrades to U+FFFD on a UTF-8\n * round-trip and strict JSON parsers reject it. Always slice through this helper\n * so every truncation site gets the same repair.\n */\nexport function sliceByTokensSafe(text: string, start: number, end?: number): string {\n return sliceByTokens(text, start, end).replace(UNPAIRED_SURROGATE_RE, '\\uFFFD');\n}\n\n/** `text.slice(start, end)` by UTF-16 index, with the same repair for a cut inside a surrogate pair. */\nexport function sliceSafe(text: string, start?: number, end?: number): string {\n return text.slice(start, end).replace(UNPAIRED_SURROGATE_RE, '\\uFFFD');\n}\n","import { estimateTokenCount } from 'tokenx';\n\nimport { isValidationError } from '../../tools/validation';\nimport { sliceByTokensSafe } from '../../utils/slice-by-tokens';\n\n/** Default number of lines to return (tail). */\nexport const DEFAULT_TAIL_LINES = 200;\n\n/** Default estimated token limit for tool output. Safety net on top of line-based tail. */\nexport const DEFAULT_MAX_OUTPUT_TOKENS = 2_000;\n\n// ---------------------------------------------------------------------------\n// ANSI stripping\n// ---------------------------------------------------------------------------\n\n/**\n * Strip ANSI escape codes from text.\n * Covers CSI sequences (colors, cursor), OSC sequences (hyperlinks), and C1 controls.\n * Based on the pattern from chalk/ansi-regex.\n */\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI control chars are intentional\nconst ANSI_RE =\n /(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|(?:[\\u001B\\u009B][\\[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~])/g;\n\nexport function stripAnsi(text: string): string {\n return text.replace(ANSI_RE, '');\n}\n\n/**\n * `toModelOutput` handler for sandbox tools.\n * Strips ANSI escape codes so the model sees clean text, while the raw\n * output (with colors) is preserved in the stream/TUI.\n *\n * Returns `{ type: 'text', value: '...' }` to match the AI SDK's\n * expected tool-result output format.\n *\n * Mastra validation-error envelopes (e.g. from output-schema validation\n * failures) are tagged as `{ type: 'error-json', value }` so providers\n * receive a valid tool-result output instead of an untagged object.\n *\n * `{ error: string }` results (e.g. substituted by a blocking `beforeToolCall`\n * hook) are tagged as `{ type: 'error-text', value }` so the model sees the reason.\n */\nexport function sandboxToModelOutput(output: unknown): unknown {\n if (typeof output === 'string') {\n return { type: 'text', value: stripAnsi(output) };\n }\n if (isValidationError(output)) {\n return { type: 'error-json', value: output };\n }\n if (typeof output === 'object' && output !== null && typeof (output as { error?: unknown }).error === 'string') {\n return { type: 'error-text', value: (output as { error: string }).error };\n }\n return output;\n}\n\n// ---------------------------------------------------------------------------\n// Tail (line-based truncation)\n// ---------------------------------------------------------------------------\n\n/**\n * Return the last N lines of output, similar to `tail -n`.\n * - `n > 0`: last N lines\n * - `n === 0`: no limit (return all)\n * - `undefined/null`: use DEFAULT_TAIL_LINES\n */\nexport function applyTail(output: string, tail: number | null | undefined): string {\n const { header, body } = splitTail(output, tail);\n return header ? `${header}\\n${body}` : body;\n}\n\ninterface TailSplit {\n /** `[showing last N of M lines]` when lines were dropped, else undefined. */\n header: string | undefined;\n /** The kept lines. */\n body: string;\n /** Line number, in the full output, of the first line of `body`. */\n firstLine: number;\n}\n\nfunction splitTail(output: string, tail: number | null | undefined): TailSplit {\n const unchanged: TailSplit = { header: undefined, body: output, firstLine: 1 };\n if (!output) return unchanged;\n const n = Math.floor(Math.abs(tail ?? DEFAULT_TAIL_LINES));\n if (n === 0) return unchanged; // 0 = no limit (also covers |tail| < 1)\n // Strip trailing newline before splitting so it doesn't count as a line\n const trailingNewline = output.endsWith('\\n');\n const lines = (trailingNewline ? output.slice(0, -1) : output).split('\\n');\n if (lines.length <= n) return unchanged;\n const sliced = lines.slice(-n).join('\\n');\n return {\n header: `[showing last ${n} of ${lines.length} lines]`,\n body: trailingNewline ? sliced + '\\n' : sliced,\n firstLine: lines.length - n + 1,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Token-based truncation (uses tokenx for fast, lightweight estimation)\n// ---------------------------------------------------------------------------\n\n/**\n * Token-based output limit. Truncates output to fit within a token budget.\n * Uses tokenx for fast token estimation and truncates at the token level\n * (not line boundaries) to maximise use of the budget.\n *\n * @param output - The text to truncate\n * @param limit - Maximum tokens (default: DEFAULT_MAX_OUTPUT_TOKENS)\n * @param from - Which end to truncate from:\n * - `'start'` (default): Remove tokens from the start, keep the end\n * - `'end'`: Remove tokens from the end, keep the start\n */\nexport async function applyTokenLimit(\n output: string,\n limit: number = DEFAULT_MAX_OUTPUT_TOKENS,\n from: 'start' | 'end' = 'start',\n): Promise<string> {\n if (!output) return output;\n\n const totalTokens = estimateTokenCount(output);\n if (totalTokens <= limit) return output;\n\n const kept = from === 'start' ? sliceByTokensSafe(output, -limit) : sliceByTokensSafe(output, 0, limit);\n\n const position = from === 'start' ? 'last' : 'first';\n return from === 'start'\n ? `[output truncated: showing ${position} ~${limit} of ~${totalTokens} tokens]\\n${kept}`\n : `${kept}\\n[output truncated: showing ${position} ~${limit} of ~${totalTokens} tokens]`;\n}\n\n/**\n * Head+tail sandwich truncation. Keeps lines from both the start and end\n * of the output, with a truncation notice in the middle.\n * Uses tokenx for fast token estimation.\n *\n * The notice names the dropped lines and the lines kept on each side, so the\n * model can read exactly the missing range instead of re-running the command, e.g.\n * `[...output truncated — dropped lines 24-199; showing first ~200 tokens (lines 1-23) + last ~1800 tokens (lines 200-400) of ~3600 tokens...]`.\n * A line the cut goes through is reported as \"the end of line N\" / \"the start of line N\".\n *\n * @param output - The text to truncate\n * @param limit - Maximum tokens (default: DEFAULT_MAX_OUTPUT_TOKENS)\n * @param headRatio - Fraction of the token budget to allocate to the head (default: 0.1 = 10%)\n */\nexport async function applyTokenLimitSandwich(\n output: string,\n limit: number = DEFAULT_MAX_OUTPUT_TOKENS,\n headRatio: number = 0.1,\n): Promise<string> {\n return sandwich(output, limit, headRatio, 1);\n}\n\n/**\n * Sandwich truncation where line 1 of `output` is line `firstLine` of the text the\n * model asked for (after a line-based tail, the kept lines start part-way in).\n */\nfunction sandwich(output: string, limit: number, headRatio: number, firstLine: number): string {\n if (!output) return output;\n\n const totalTokens = estimateTokenCount(output);\n if (totalTokens <= limit) return output;\n const headBudget = Math.floor(limit * headRatio);\n const tailBudget = limit - headBudget;\n\n // `head` is a prefix and `tail` a suffix of `output` (the surrogate repair keeps lengths).\n let head = headBudget > 0 ? sliceByTokensSafe(output, 0, headBudget) : '';\n let tail = tailBudget > 0 ? sliceByTokensSafe(output, -tailBudget) : '';\n const headEnd = head.length;\n let tailStart = output.length - tail.length;\n // The notice gets its own line, so a line break (`\\n` or `\\r\\n`) at either cut is redundant.\n head = head.replace(/\\r?\\n$/, '');\n if (head.endsWith('\\r') && output[headEnd] === '\\n') head = head.slice(0, -1);\n const tailBreak = tail.startsWith('\\r\\n') ? 2 : tail.startsWith('\\n') ? 1 : 0;\n tail = tail.slice(tailBreak);\n tailStart += tailBreak;\n\n const lines = describeCutLines(output, headEnd, tailStart, firstLine - 1);\n const dropped = lines.dropped ? `dropped ${lines.dropped}; ` : '';\n const notice = `[...output truncated — ${dropped}showing first ~${headBudget} tokens${lines.head} + last ~${tailBudget} tokens${lines.tail} of ~${totalTokens} tokens...]`;\n return [head, notice, tail].filter(Boolean).join('\\n');\n}\n\n/** 1-based line number of the character at `index`. */\nfunction lineAt(text: string, index: number): number {\n let line = 1;\n for (let i = text.indexOf('\\n'); i !== -1 && i < index; i = text.indexOf('\\n', i + 1)) line++;\n return line;\n}\n\nfunction lineRange(from: number, to: number): string {\n return from === to ? `line ${from}` : `lines ${from}-${to}`;\n}\n\nfunction joinClauses(clauses: string[]): string {\n if (clauses.length <= 1) return clauses.join('');\n return `${clauses.slice(0, -1).join(', ')} and ${clauses.at(-1)}`;\n}\n\n/**\n * Describe which lines a sandwich cut kept and dropped. The head keeps\n * `output[0, headEnd)` and the tail keeps `output[tailStart, end)`.\n * `offset` is added to every line number.\n */\nfunction describeCutLines(\n output: string,\n headEnd: number,\n tailStart: number,\n offset: number,\n): { head: string; tail: string; dropped: string } {\n const trailingNewline = output.endsWith('\\n');\n const lastLine = lineAt(output, output.length) - (trailingNewline ? 1 : 0);\n const hasHead = headEnd > 0;\n const hasTail = tailStart < output.length;\n\n // Last line the head reaches, and whether it reaches that line's end.\n const headTo = hasHead ? lineAt(output, headEnd - 1) : 0;\n const headWhole =\n hasHead &&\n (output[headEnd - 1] === '\\n' ||\n headEnd >= output.length ||\n output.startsWith('\\n', headEnd) ||\n output.startsWith('\\r\\n', headEnd));\n // First line the tail reaches, and whether it starts at that line's start.\n const tailFrom = hasTail ? lineAt(output, tailStart) : lastLine + 1;\n const tailWhole = tailStart === 0 || output[tailStart - 1] === '\\n';\n\n const n = (line: number) => line + offset;\n const head = hasHead ? ` (${lineRange(n(1), n(headTo))})` : '';\n const tail = hasTail ? ` (${lineRange(n(tailFrom), n(lastLine))})` : '';\n\n // Token estimates are rounded, so the kept slices can meet or overlap; then nothing was dropped.\n if (hasHead && hasTail && tailStart <= headEnd) return { head, tail, dropped: '' };\n if (hasHead && hasTail && headTo === tailFrom) {\n return { head, tail, dropped: `the middle of line ${n(headTo)}` };\n }\n\n const clauses: string[] = [];\n if (hasHead && !headWhole) clauses.push(`the end of line ${n(headTo)}`);\n if (tailFrom - 1 >= headTo + 1) clauses.push(lineRange(n(headTo + 1), n(tailFrom - 1)));\n if (hasTail && !tailWhole) clauses.push(`the start of line ${n(tailFrom)}`);\n return { head, tail, dropped: joinClauses(clauses) };\n}\n\n/**\n * Tell the model when the sandbox dropped the start of a stream (retention limit),\n * so it doesn't read the newest output as all of it.\n */\nexport function noteDroppedOutput(\n output: string,\n droppedBytes: number | undefined,\n stream: 'stdout' | 'stderr',\n): string {\n if (!droppedBytes) return output;\n const note = `[${stream}: the first ${droppedBytes} bytes were dropped; only the newest output was kept. Redirect output to a file to read all of it.]`;\n return output ? `${note}\\n${output}` : note;\n}\n\n/**\n * Apply both tail (line-based) and token limit (safety net) to output.\n */\nexport async function truncateOutput(\n output: string,\n tail?: number | null,\n tokenLimit?: number,\n tokenFrom?: 'start' | 'end' | 'sandwich',\n): Promise<string> {\n if (tokenFrom === 'sandwich') {\n // Cut the kept lines, not the `[showing last N of M lines]` header, so the\n // notice can number lines as they appear in the full output.\n const { header, body, firstLine } = splitTail(output, tail);\n const cut = sandwich(body, tokenLimit ?? DEFAULT_MAX_OUTPUT_TOKENS, 0.1, firstLine);\n return header ? `${header}\\n${cut}` : cut;\n }\n return applyTokenLimit(applyTail(output, tail), tokenLimit, tokenFrom);\n}\n","import path from 'node:path';\nimport { z } from 'zod/v4';\nimport { browserCliHandler } from '../../browser/cli-handler';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { SandboxFeatureNotSupportedError } from '../errors';\nimport {\n DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES,\n RetainedOutputBuffer,\n} from '../sandbox/process-manager/process-handle';\nimport type { Workspace } from '../workspace';\nimport { coerceNumericString, emitWorkspaceMetadata, requireSandbox } from './helpers';\nimport { DEFAULT_TAIL_LINES, noteDroppedOutput, truncateOutput, sandboxToModelOutput } from './output-helpers';\nimport { startWorkspaceSpan } from './tracing';\n\n/**\n * Base input schema for execute_command (no background param).\n * Extended with `background` in tools.ts when sandbox.processes exists.\n */\nexport const executeCommandInputSchema = z.object({\n command: z\n .string()\n .describe('The shell command to execute (e.g., \"npm install\", \"ls -la src/\", \"cat file.txt | grep error\")'),\n timeout: z\n .preprocess(coerceNumericString, z.number())\n .nullish()\n .describe('Maximum execution time in seconds. Example: 60 for 1 minute.'),\n cwd: z.string().nullish().describe('Working directory for the command'),\n tail: z\n .preprocess(coerceNumericString, z.number().int())\n .nullish()\n .describe(\n `For foreground commands: limit output to the last N lines, similar to tail -n. Defaults to ${DEFAULT_TAIL_LINES}. Use 0 for no limit.`,\n ),\n});\n\n/** Schema with background param included. */\nexport const executeCommandWithBackgroundSchema = executeCommandInputSchema.extend({\n background: z\n .boolean()\n .optional()\n .describe(\n 'Run the command in the background. Returns a PID immediately instead of waiting for completion. Use get_process_output to check on it later.',\n ),\n});\n\n// Listed first so models write the summary before the command itself.\nconst descriptionShape = {\n description: z\n .string()\n .min(1)\n .describe(\n 'Short plain-language description of what this command does, shown to the user in place of the raw command (5-10 words, e.g. \"Running the auth unit tests\"). Write it first, before `command` and the other arguments, so the user sees it while the rest of the call streams in. Write it as the next step in an ongoing narrative: it can build on your previous commands implicitly, e.g. after \"Searching open PRs for failing CI\" the next command can be \"Drilling into the first of 15 failures\".',\n ),\n};\n\n/** Base schema with a required leading `description` (used when `requireDescription` is set). */\nexport const executeCommandWithDescriptionSchema = z.object({\n ...descriptionShape,\n ...executeCommandInputSchema.shape,\n});\n\n/** Background schema with a required leading `description`. */\nexport const executeCommandWithDescriptionAndBackgroundSchema = z.object({\n ...descriptionShape,\n ...executeCommandWithBackgroundSchema.shape,\n});\n\n/** A command whose final pipeline stage is `tail`, e.g. `make test 2>&1 | tail -20`. */\nconst TRAILING_TAIL_PIPE = /(?:^|[^|])\\|\\s*tail(?:\\s[^|;&]*)?$/;\n\n/**\n * POSIX shells report a pipeline's status from its last command, so `cmd | tail -N` exits 0 even\n * when `cmd` fails. Enable `pipefail` (where the shell supports it) for pipelines ending in `tail`\n * so the upstream failure is reported. `tail` reads all of its input, so upstream commands are\n * not cut off by SIGPIPE. LocalSandbox on Windows runs commands through cmd.exe, which has no\n * `set -o`.\n */\nfunction reportUpstreamPipelineFailure(command: string, sandboxProvider: string): string {\n if (sandboxProvider === 'local' && process.platform === 'win32') return command;\n if (!TRAILING_TAIL_PIPE.test(command.trim())) return command;\n return `(set -o pipefail) 2>/dev/null && set -o pipefail; ${command}`;\n}\n\nconst ABORTED_COMMAND_NOTE =\n 'Command aborted: the run was cancelled (by the user or system) while this command was running, so it was killed before it finished.';\nconst CANCELLED_RUN_NOTE = 'The run was cancelled (by the user or system) while this command was running.';\n\n/** Format command streams consistently with get_process_output. */\nfunction formatCommandOutput(stdout: string, stderr: string): string[] {\n const parts: string[] = [];\n\n if (stdout && stderr) {\n parts.push('stdout:', stdout, '', 'stderr:', stderr);\n } else if (stdout) {\n parts.push(stdout);\n } else if (stderr) {\n parts.push('stderr:', stderr);\n }\n\n return parts;\n}\n\n/** Append a terminal status after one blank line without altering streamed output. */\nfunction appendTerminalLine(parts: string[], terminalLine: string): string {\n if (parts.length === 0) return terminalLine;\n\n const output = parts.join('\\n');\n const separator = output.endsWith('\\n\\n') ? '' : output.endsWith('\\n') ? '\\n' : '\\n\\n';\n return `${output}${separator}${terminalLine}`;\n}\n\n/**\n * The directory the workspace's file tools resolve relative paths against, when its\n * filesystem is sandbox-backed and reports one. Only the configured filesystem is\n * consulted: a dynamic filesystem resolver is not invoked just to learn a default cwd, so\n * a sandbox-only tool call still resolves nothing it did not resolve before. Every absent\n * case — no filesystem, no capability — falls back to `undefined`, which keeps the\n * sandbox's own default cwd exactly as before.\n */\nasync function resolveDefaultCwd(workspace: Workspace): Promise<string | undefined> {\n try {\n const root = await workspace.filesystem?.getCommandCwd?.();\n return root?.startsWith('/') ? root : undefined;\n } catch {\n // A filesystem that cannot answer must not fail the command: run it with today's default.\n return undefined;\n }\n}\n\n/**\n * The cwd a command actually runs in. An explicit absolute `cwd` wins, a relative one is\n * resolved under the default root so it means the same thing as a relative path passed to\n * the file tools, and an omitted `cwd` becomes the default root.\n */\nfunction resolveCommandCwd(cwd: string | undefined, defaultCwd: string | undefined): string | undefined {\n if (!cwd) return defaultCwd;\n if (cwd.startsWith('/')) return cwd;\n return defaultCwd ? path.posix.join(defaultCwd, cwd) : cwd;\n}\n\n/** Shared execute function used by both foreground-only and background-capable tool variants. */\nasync function executeCommand(input: Record<string, any>, context: any) {\n let { command } = input;\n const { cwd, tail } = input;\n const timeout = input.timeout != null ? (input.timeout as number) * 1000 : undefined;\n const background = input.background as boolean | undefined;\n const { workspace, sandbox } = requireSandbox(context);\n // Commands and file tools must resolve relative paths against the same directory, or a\n // file written by a shell command is invisible to the file tools (and to the plan card).\n const effectiveCwd = resolveCommandCwd(cwd, await resolveDefaultCwd(workspace));\n\n // Lazy browser launch and CDP URL injection for browser CLI commands\n const browser = workspace.browser;\n const { browserClis, usingExternalCdp, externalCdpUrl } = browserCliHandler.analyzeCommand(command);\n\n if (browser && browserClis.length > 0 && !usingExternalCdp) {\n const threadId = context?.agent?.threadId ?? context?.threadId ?? 'default';\n\n // Launch browser if not already running (for this thread if thread-scoped)\n if (!browser.isBrowserRunning(threadId)) {\n await browser.launch(threadId);\n }\n\n const cdpUrl = browser.getCdpUrl(threadId);\n const browserId = browser.id;\n\n if (cdpUrl) {\n // Run warmup commands for CLIs that need them\n const warmups = browserCliHandler.getWarmupCommands(browserId, browserClis, cdpUrl, threadId);\n for (const { cliName, command: warmupCmd } of warmups) {\n try {\n if (sandbox.executeCommand) {\n await sandbox.executeCommand(warmupCmd, [], { timeout: 10000 });\n }\n // Only mark as warmed up after successful warmup\n browserCliHandler.markWarmedUp(browserId, cliName, threadId);\n // Register cleanup when browser closes\n browserCliHandler.registerWarmupCleanup(browserId, cliName, threadId, browser);\n } catch {\n // Don't mark as warmed up - will retry on next command\n // This allows recovery if the CLI daemon wasn't ready\n }\n }\n\n // Inject CDP URL into all browser CLI commands in the chain\n command = browserCliHandler.injectCdpUrl(command, cdpUrl, threadId);\n }\n } else if (browser && browserClis.length > 0 && usingExternalCdp && externalCdpUrl) {\n // Agent is using their own external CDP - connect BrowserViewer to it for screencast\n const threadId = context?.agent?.threadId ?? context?.threadId ?? 'default';\n try {\n await browser.connectToExternalCdp(externalCdpUrl, threadId);\n } catch {\n // Non-fatal - agent can still use the external CDP, just no screencast\n }\n }\n\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND);\n const toolCallId = context?.agent?.toolCallId;\n const toolConfig = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND];\n const tokenLimit = toolConfig?.maxOutputTokens;\n const tokenFrom = 'sandwich' as const;\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'sandbox',\n operation: background ? 'spawnProcess' : 'executeCommand',\n input: { command, cwd: effectiveCwd, timeout: input.timeout, background },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n // Background mode: spawn via process manager and return immediately\n if (background) {\n if (!sandbox.processes) {\n const err = new SandboxFeatureNotSupportedError('processes');\n span.error(err);\n throw err;\n }\n\n const bgConfig = toolConfig?.backgroundProcesses;\n\n // Resolve abort signal: undefined = use context signal (from agent), null/false = disabled\n const bgAbortSignal =\n bgConfig?.abortSignal === undefined ? context?.abortSignal : bgConfig.abortSignal || undefined;\n\n // Lets hosts route exit notices to the run and thread that started the process.\n // Empty ids count as missing: the tool builder passes `agentId: ''` when\n // there is no agent id. Direct `execute()` calls pass the thread and\n // resource at the top level instead of under `agent`.\n const owner = {\n agentId: context?.agent?.agentId || undefined,\n threadId: context?.agent?.threadId || context?.threadId || undefined,\n resourceId: context?.agent?.resourceId || context?.resourceId || undefined,\n runId: context?.runId || undefined,\n };\n\n // Use `let` so callbacks can reference handle.pid via closure.\n // spawn() resolves before any data events fire (Node event loop guarantees this).\n let handle: Awaited<ReturnType<typeof sandbox.processes.spawn>>;\n handle = await sandbox.processes.spawn(command, {\n cwd: effectiveCwd,\n timeout: timeout ?? undefined,\n abortSignal: bgAbortSignal,\n // A background process collects output rather than being driven over stdin,\n // so close stdin at spawn. Otherwise `rg`/`grep`/`cat` with no path argument\n // reads stdin and never exits.\n stdinMode: 'ignore',\n onStdout: bgConfig?.onStdout\n ? (data: string) => bgConfig.onStdout!(data, { pid: handle.pid, toolCallId, ...owner })\n : undefined,\n onStderr: bgConfig?.onStderr\n ? (data: string) => bgConfig.onStderr!(data, { pid: handle.pid, toolCallId, ...owner })\n : undefined,\n });\n\n // Wire exit callback (fire-and-forget). The observer runs after this tool has\n // already returned the PID, so any failure here has no live call frame to catch\n // it. Own the detached promise: await the callback so both synchronous throws and\n // rejected async callbacks land in the try/catch, and attach a terminal .catch()\n // for a rejected wait(), routing all failures to the logger so\n // neither escapes as a process-terminating unhandled rejection. Observation\n // failures are logged distinctly and never synthesize a successful exit.\n if (bgConfig?.onExit) {\n void handle\n .wait()\n .then(async result => {\n try {\n await bgConfig.onExit!({\n pid: handle.pid,\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n stdoutTruncated: result.stdoutTruncated,\n stderrTruncated: result.stderrTruncated,\n stdoutDroppedBytes: result.stdoutDroppedBytes,\n stderrDroppedBytes: result.stderrDroppedBytes,\n killedByAbort: handle.killedByAbort,\n toolCallId,\n ...owner,\n });\n } catch (callbackError) {\n workspace.logger?.error('Background process onExit callback threw', {\n error: callbackError,\n pid: handle.pid,\n toolCallId,\n });\n }\n })\n .catch(observeError => {\n workspace.logger?.error('Failed to observe background process exit', {\n error: observeError,\n pid: handle.pid,\n toolCallId,\n });\n });\n }\n\n span.end({ success: true }, { pid: Number(handle.pid) || undefined });\n return `Started background process (PID: ${handle.pid})`;\n }\n\n // Foreground mode: execute and wait for completion\n if (!sandbox.executeCommand) {\n const err = new SandboxFeatureNotSupportedError('executeCommand');\n span.error(err);\n throw err;\n }\n\n const startedAt = Date.now();\n // Bounded copies used only on the error path, where the sandbox result is unavailable.\n // Unbounded accumulation here crashes the process with RangeError on very large output.\n const stdout = new RetainedOutputBuffer(DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES);\n const stderr = new RetainedOutputBuffer(DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES);\n // Snapshot the abort state when the command settles: an abort that lands afterwards\n // (while the result is being reported) did not stop the command.\n let abortedWhenSettled = false;\n try {\n const result = await sandbox\n .executeCommand(reportUpstreamPipelineFailure(command, sandbox.provider), [], {\n timeout: timeout ?? undefined,\n cwd: effectiveCwd,\n abortSignal: context?.abortSignal, // foreground processes use agent's abort signal\n onStdout: async (data: string) => {\n stdout.append(data);\n await context?.writer?.custom({\n type: 'data-sandbox-stdout',\n data: { output: data, timestamp: Date.now(), toolCallId },\n transient: true,\n });\n },\n onStderr: async (data: string) => {\n stderr.append(data);\n await context?.writer?.custom({\n type: 'data-sandbox-stderr',\n data: { output: data, timestamp: Date.now(), toolCallId },\n transient: true,\n });\n },\n })\n .finally(() => {\n abortedWhenSettled = context?.abortSignal?.aborted === true;\n });\n\n await context?.writer?.custom({\n type: 'data-sandbox-exit',\n data: {\n exitCode: result.exitCode,\n success: result.success,\n executionTimeMs: result.executionTimeMs,\n killed: result.killed,\n timedOut: result.timedOut,\n toolCallId,\n },\n });\n\n span.end({ success: result.success }, { exitCode: result.exitCode });\n\n const stdoutForModel = noteDroppedOutput(\n await truncateOutput(result.stdout, tail, tokenLimit, tokenFrom),\n result.stdoutDroppedBytes,\n 'stdout',\n );\n const stderrForModel = noteDroppedOutput(\n await truncateOutput(result.stderr, tail, tokenLimit, tokenFrom),\n result.stderrDroppedBytes,\n 'stderr',\n );\n\n if (!result.success) {\n const parts = formatCommandOutput(stdoutForModel, stderrForModel);\n // The exit code of an aborted command is a provider-specific kill code (LocalSandbox\n // reports 128, which also means \"fatal\" for git), so the abort signal is the only\n // reliable way to tell the model why it stopped. `killed: false` means the command\n // exited on its own just before the abort. Only claim a kill when the provider confirms\n // it; missing kill metadata is not confirmation that remote work stopped.\n const aborted = abortedWhenSettled && result.killed !== false && !result.timedOut;\n const abortNote = result.killed === true ? ABORTED_COMMAND_NOTE : CANCELLED_RUN_NOTE;\n const exitLine = `Exit code: ${result.exitCode}`;\n return appendTerminalLine(parts, aborted ? `${abortNote}\\n${exitLine}` : exitLine);\n }\n\n return formatCommandOutput(stdoutForModel, stderrForModel).join('\\n') || '(no output)';\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n await context?.writer?.custom({\n type: 'data-sandbox-exit',\n data: {\n exitCode: -1,\n success: false,\n executionTimeMs: Date.now() - startedAt,\n // -1 is no exit code: the command could not run or be observed, and this says why.\n error: errorMessage,\n toolCallId,\n },\n });\n span.end({ success: false }, { exitCode: -1 });\n const parts = formatCommandOutput(\n noteDroppedOutput(await truncateOutput(stdout.toString(), tail, tokenLimit, tokenFrom), stdout.dropped, 'stdout'),\n noteDroppedOutput(await truncateOutput(stderr.toString(), tail, tokenLimit, tokenFrom), stderr.dropped, 'stderr'),\n );\n const errorLine = `Error: ${errorMessage}\\nExit code: -1`;\n return appendTerminalLine(parts, abortedWhenSettled ? `${CANCELLED_RUN_NOTE}\\n${errorLine}` : errorLine);\n }\n}\n\nconst baseDescription = `Execute a shell command in the workspace sandbox.\n\nExamples:\n \"npm install && npm run build\"\n \"ls -la src/\"\n \"cat config.json | jq '.database'\"\n \"cd /app && python main.py\"\n\nUsage:\n- Commands run in a shell, so pipes, redirects, and chaining (&&, ||, ;) all work.\n- Always quote file paths that contain spaces (e.g., cd \"/path/with spaces\").\n- Use the timeout parameter (in seconds) to limit execution time. Behavior when omitted depends on the sandbox provider.\n- Optionally use cwd to override the working directory. Commands run from the workspace directory if omitted, the same root relative file paths resolve against; a relative cwd is resolved against that directory.`;\n\n/** Foreground-only tool (no background param in schema). */\nexport const executeCommandTool = createTool({\n id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,\n description: baseDescription,\n inputSchema: executeCommandInputSchema,\n outputSchema: z.string(),\n execute: executeCommand,\n toModelOutput: sandboxToModelOutput,\n});\n\nconst backgroundDescription = `${baseDescription}\n\nSet background: true to run long-running commands (dev servers, watchers) without blocking. You'll get a PID to track the process. On a background command, timeout stops the process after that many seconds: leave it out for dev servers and anything else that should keep running.`;\n\n/** Tool with background param in schema (used when sandbox.processes exists). */\nexport const executeCommandWithBackgroundTool = createTool({\n id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,\n description: backgroundDescription,\n inputSchema: executeCommandWithBackgroundSchema,\n outputSchema: z.string(),\n execute: executeCommand,\n toModelOutput: sandboxToModelOutput,\n});\n\n/** Foreground-only tool that requires a leading `description` arg. */\nexport const executeCommandWithDescriptionTool = createTool({\n id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,\n description: baseDescription,\n inputSchema: executeCommandWithDescriptionSchema,\n outputSchema: z.string(),\n execute: executeCommand,\n toModelOutput: sandboxToModelOutput,\n});\n\n/** Background-capable tool that requires a leading `description` arg. */\nexport const executeCommandWithDescriptionAndBackgroundTool = createTool({\n id: WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND,\n description: backgroundDescription,\n inputSchema: executeCommandWithDescriptionAndBackgroundSchema,\n outputSchema: z.string(),\n execute: executeCommand,\n toModelOutput: sandboxToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { FileNotFoundError } from '../errors';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const fileStatTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT,\n description:\n 'Get file or directory metadata from the workspace. Returns existence, type, size, and modification time.',\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().describe('The path to check'),\n }),\n execute: async ({ path }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'stat',\n input: { path },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n const stat = await filesystem.stat(path);\n const modifiedAt = stat.modifiedAt.toISOString();\n\n // oxlint-disable-next-line typescript/no-unnecessary-template-expression -- Preserve eager string coercion before formatting the remaining stat fields.\n const parts = [`${path}`, `Type: ${stat.type}`];\n if (stat.size !== undefined) parts.push(`Size: ${stat.size} bytes`);\n parts.push(`Modified: ${modifiedAt}`);\n span.end({ success: true }, { bytesTransferred: stat.size });\n return parts.join(' ');\n } catch (error) {\n if (error instanceof FileNotFoundError) {\n span.end({ success: false });\n return `${path}: not found`;\n }\n span.error(error);\n throw error;\n }\n },\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { SandboxFeatureNotSupportedError } from '../errors';\nimport { coerceNumericString, emitWorkspaceMetadata, getDynamicSandboxCacheKeyHint, requireSandbox } from './helpers';\nimport { DEFAULT_TAIL_LINES, noteDroppedOutput, truncateOutput, sandboxToModelOutput } from './output-helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nconst LEFT_BEHIND_NOTE =\n 'The command exited, but a process it started is still running and holding its output open. Call kill_process to stop it.';\n\nconst ABORTED_PROCESS_NOTE =\n 'Process aborted: the run that started or was waiting on this process was cancelled (by the user or system), so it was killed before it finished.';\n\nexport const getProcessOutputTool = createTool({\n id: WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT,\n description: `Get the current output (stdout, stderr) and status of a background process by its PID.\n\nUse this after starting a background command with execute_command (background: true) to check if the process is still running and read its output.`,\n toModelOutput: sandboxToModelOutput,\n outputSchema: z.string(),\n inputSchema: z.object({\n pid: z.string().describe('The process ID returned when the background command was started'),\n tail: z\n .preprocess(coerceNumericString, z.number().int())\n .optional()\n .describe(\n `Number of lines to return, similar to tail -n. Positive or negative returns last N lines from end. Defaults to ${DEFAULT_TAIL_LINES}. Use 0 for no limit.`,\n ),\n wait: z\n .boolean()\n .optional()\n .describe(\n 'If true, block until the process exits and return the final output. Useful for short-lived background commands where you want to wait for the result.',\n ),\n }),\n execute: async ({ pid, tail, wait: shouldWait }, context) => {\n const { workspace, sandbox } = requireSandbox(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'sandbox',\n operation: 'getProcessOutput',\n input: { pid, tail, wait: shouldWait },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n const toolCallId = context?.agent?.toolCallId;\n\n try {\n if (!sandbox.processes) {\n throw new SandboxFeatureNotSupportedError('processes');\n }\n const handle = await sandbox.processes.get(pid);\n if (!handle) {\n span.end({ success: false });\n return `No background process found with PID ${pid}.${getDynamicSandboxCacheKeyHint(workspace)}`;\n }\n\n // Emit process info so the UI can display the command\n if (handle.command) {\n await context?.writer?.custom({\n type: 'data-sandbox-command',\n data: { command: handle.command, pid, toolCallId },\n });\n }\n\n // If wait requested, block until process exits with streaming callbacks.\n // The run's abortSignal is forwarded so aborting the run (e.g. a user\n // stop) interrupts a blocking wait instead of outliving the turn: the\n // handle kills the process on abort, mirroring the spawn-time\n // `abortSignal` convention.\n let result: Awaited<ReturnType<typeof handle.wait>> | undefined;\n if (shouldWait && handle.exitCode === undefined) {\n result = await handle.wait({\n abortSignal: context?.abortSignal,\n onStdout: context?.writer\n ? async (data: string) => {\n await context.writer!.custom({\n type: 'data-sandbox-stdout',\n data: { output: data, timestamp: Date.now(), toolCallId },\n transient: true,\n });\n }\n : undefined,\n onStderr: context?.writer\n ? async (data: string) => {\n await context.writer!.custom({\n type: 'data-sandbox-stderr',\n data: { output: data, timestamp: Date.now(), toolCallId },\n transient: true,\n });\n }\n : undefined,\n });\n\n await context?.writer?.custom({\n type: 'data-sandbox-exit',\n data: {\n exitCode: result.exitCode,\n success: result.success,\n executionTimeMs: result.executionTimeMs,\n toolCallId,\n },\n });\n }\n\n // wait() can settle when the command exits while a process it left behind\n // still holds its output; the handle then reports no exit code yet.\n const exitCode = handle.exitCode ?? result?.exitCode;\n const running = exitCode === undefined;\n\n const tokenLimit = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT]?.maxOutputTokens;\n const stdout = noteDroppedOutput(\n await truncateOutput(handle.stdout, tail, tokenLimit, 'sandwich'),\n handle.stdoutDroppedBytes,\n 'stdout',\n );\n const stderr = noteDroppedOutput(\n await truncateOutput(handle.stderr, tail, tokenLimit, 'sandwich'),\n handle.stderrDroppedBytes,\n 'stderr',\n );\n\n if (running && !stdout && !stderr) {\n span.end({ success: true }, { exitCode: handle.exitCode });\n return '(no output yet)';\n }\n\n const parts: string[] = [];\n\n // Only label stdout/stderr when both are present\n if (stdout && stderr) {\n parts.push('stdout:', stdout, '', 'stderr:', stderr);\n } else if (stdout) {\n parts.push(stdout);\n } else if (stderr) {\n parts.push('stderr:', stderr);\n }\n\n if (!running) {\n // The exit code of an aborted process is a provider-specific kill code, so say why it stopped.\n const terminalLines = [\n ...(handle.killedByAbort ? [ABORTED_PROCESS_NOTE] : []),\n ...(handle.exitCode === undefined ? [LEFT_BEHIND_NOTE] : []),\n `Exit code: ${exitCode}`,\n ];\n parts.push(...(parts.length > 0 ? [''] : []), ...terminalLines);\n }\n\n span.end({ success: true }, { exitCode });\n return parts.join('\\n');\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","/**\n * Gitignore support for workspace tools.\n *\n * Applies every `.gitignore` relative to the directory that holds it, the way\n * git does, so a multi-repo workspace root without its own `.gitignore` still\n * honors each repository's rules. `node_modules` is skipped by default.\n */\n\nimport ignore from 'ignore';\n\nimport type { FileEntry, WorkspaceFilesystem } from './filesystem';\nimport { isEnoentError } from './filesystem/fs-utils';\n\nexport type IgnoreFilter = (relativePath: string) => boolean;\n\n/** Maximum concurrent `.gitignore` reads while walking. */\nconst GITIGNORE_READ_CONCURRENCY = 8;\n\nconst NODE_MODULES = /(^|\\/)node_modules(\\/|$)/;\n\nexport interface WorkspaceIgnore {\n /** Whether `path` (in the same form the caller walks with) should be skipped. */\n ignores(path: string, isDirectory: boolean): boolean;\n /**\n * Read the `.gitignore` of each listed directory that has one, so its rules\n * apply to everything below it. Call with a directory's listing before\n * filtering its children.\n */\n addListings(\n listings: Array<[directory: string, entries: readonly Pick<FileEntry, 'name' | 'type'>[] | undefined]>,\n ): Promise<void>;\n /**\n * Read the `.gitignore` of every directory between the target and each of\n * `filePaths`, for results that didn't come from a walk (native grep).\n * Directories already ignored are not read into.\n */\n addParentsOf(filePaths: readonly string[]): Promise<void>;\n}\n\nexport interface LoadWorkspaceIgnoreOptions {\n /** Apply `.gitignore` files (default: true). `node_modules` is skipped either way. */\n gitignore?: boolean;\n /**\n * The path the caller asked for, when it differs from `target` (e.g. a glob\n * whose static base is `target`). `node_modules` is not skipped when it\n * points inside one.\n */\n requestedPath?: string;\n}\n\n/**\n * Load ignore rules for a walk rooted at `target`: the workspace root's\n * `.gitignore` plus those of `target`'s ancestors. The walk adds nested ones\n * with {@link WorkspaceIgnore.addListings}.\n *\n * When `target` is itself ignored (e.g. `dist` or `node_modules/x`), nothing\n * below it is filtered, so callers can still look inside on purpose.\n * Missing nested `.gitignore` files are skipped, and so are unreadable ones;\n * an unreadable root `.gitignore` throws.\n */\nexport async function loadWorkspaceIgnore(\n filesystem: WorkspaceFilesystem,\n target: string,\n options: LoadWorkspaceIgnoreOptions = {},\n): Promise<WorkspaceIgnore> {\n const skipNodeModules = !NODE_MODULES.test(options.requestedPath ?? target);\n const useGitignore = options.gitignore ?? true;\n const rules = new Map<string, ReturnType<typeof ignore>>();\n\n const addFrom = async (directories: string[]) => {\n const pMap = (await import('p-map')).default;\n await pMap(\n directories.filter(directory => !rules.has(pathKey(directory))),\n async directory => {\n const content = await readGitignore(filesystem, directory);\n if (content?.trim()) rules.set(pathKey(directory), ignore().add(content));\n },\n { concurrency: GITIGNORE_READ_CONCURRENCY },\n );\n };\n // Like git, a deeper .gitignore overrides a shallower one, so `!keep.log`\n // in a subdirectory re-includes a file a parent's `*.log` ignored.\n const matchesRules = (path: string, isDirectory: boolean): boolean => {\n const key = pathKey(path);\n const applicable: Array<[relative: string, ig: ReturnType<typeof ignore>]> = [];\n for (const [directory, ig] of rules) {\n let relative: string;\n if (directory === '') relative = key;\n else if (key.startsWith(`${directory}/`)) relative = key.slice(directory.length + 1);\n else continue;\n if (relative) applicable.push([isDirectory ? `${relative}/` : relative, ig]);\n }\n applicable.sort(([a], [b]) => b.length - a.length);\n let ignored = false;\n for (const [relative, ig] of applicable) {\n const result = ig.test(relative);\n if (result.ignored) ignored = true;\n else if (result.unignored) ignored = false;\n }\n return ignored;\n };\n\n let targetIsIgnored = false;\n if (useGitignore) {\n // The root .gitignore must be readable: silently dropping it would widen\n // the scope without telling the caller. Nested ones are best-effort.\n const root = await readRootGitignore(filesystem);\n if (root?.trim()) rules.set('', ignore().add(root));\n await addFrom(ancestorDirectories(target));\n targetIsIgnored = pathKey(target) !== '' && matchesRules(target, true);\n }\n const applyGitignore = useGitignore && !targetIsIgnored;\n const isIgnored = (path: string, isDirectory: boolean) =>\n (skipNodeModules && NODE_MODULES.test(pathKey(path))) || (applyGitignore && matchesRules(path, isDirectory));\n\n return {\n ignores: isIgnored,\n async addListings(listings) {\n if (!applyGitignore) return;\n await addFrom(\n listings\n .filter(([, entries]) => entries?.some(entry => entry.type === 'file' && entry.name === '.gitignore'))\n .map(([directory]) => directory),\n );\n },\n async addParentsOf(filePaths) {\n if (!applyGitignore) return;\n const targetKey = pathKey(target);\n const byDepth = new Map<number, Set<string>>();\n for (const filePath of filePaths) {\n for (const directory of ancestorDirectories(filePath).slice(1)) {\n const key = pathKey(directory);\n if (key === targetKey || (targetKey && !key.startsWith(`${targetKey}/`))) break;\n const depth = key.split('/').length;\n if (!byDepth.has(depth)) byDepth.set(depth, new Set());\n byDepth.get(depth)!.add(directory);\n }\n }\n // Shallowest first, so a directory a parent ignores is never read into.\n for (const depth of [...byDepth.keys()].sort((a, b) => a - b)) {\n await addFrom([...byDepth.get(depth)!].filter(directory => !isIgnored(directory, true)));\n }\n },\n };\n}\n\n/** Rule-matching form of a path: no `./`, leading `/`, or trailing `/`; the root is `''`. */\nfunction pathKey(path: string): string {\n const key = path.replace(/^\\.\\//, '').replace(/^\\/+/, '').replace(/\\/+$/, '');\n return key === '.' ? '' : key;\n}\n\n/** `path` and each directory above it, deepest first, excluding the root. */\nfunction ancestorDirectories(path: string): string[] {\n const directories: string[] = [];\n let current = path.replace(/\\/+$/, '');\n while (current && current !== '.' && current !== '/') {\n directories.push(current);\n const slash = current.lastIndexOf('/');\n current = slash > 0 ? current.slice(0, slash) : slash === 0 ? '/' : '';\n }\n return directories;\n}\n\n/** Read the root `.gitignore`; only a missing file (ENOENT) is treated as absent. */\nasync function readRootGitignore(filesystem: WorkspaceFilesystem): Promise<string | undefined> {\n try {\n const content = await filesystem.readFile('.gitignore', { encoding: 'utf-8' });\n return typeof content === 'string' ? content : undefined;\n } catch (err) {\n if (isEnoentError(err)) return undefined;\n throw err;\n }\n}\n\n/** Read `<directory>/.gitignore`, or undefined when it is missing or unreadable. */\nasync function readGitignore(filesystem: WorkspaceFilesystem, directory: string): Promise<string | undefined> {\n try {\n const content = await filesystem.readFile(`${directory.replace(/\\/+$/, '')}/.gitignore`, { encoding: 'utf-8' });\n return typeof content === 'string' ? content : undefined;\n } catch {\n return undefined;\n }\n}\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { sliceSafe } from '../../utils/slice-by-tokens';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { UnsupportedGrepPatternError } from '../errors';\nimport type { FilesystemGrepResult } from '../filesystem';\nimport { isEnoentError, isEnotdirError, isTextFile } from '../filesystem/fs-utils';\nimport { loadWorkspaceIgnore } from '../gitignore';\nimport type { GlobMatcher } from '../glob';\nimport { createGlobMatcher, extractGlobBase, isGlobPattern } from '../glob';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport { applyTokenLimit } from './output-helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nconst GREP_FILESYSTEM_CONCURRENCY = 8;\n\n/**\n * Wall-clock budget for the host-side directory walk. On remote filesystems\n * every directory and file is a round trip, so an unbounded walk over a large\n * repository can stall an agent run for minutes; past this budget the tool\n * returns what it found so far and says the search is incomplete.\n */\nconst HOST_WALK_BUDGET_MS = 60_000;\n\n/**\n * Options for {@link createGrepTool}.\n */\nexport interface GrepToolOptions {\n /**\n * When true, any filesystem read failure (missing target path, unreadable\n * directory, or unreadable file) throws instead of being silently skipped.\n * Use this when a partial search must not be mistaken for a complete one.\n *\n * This is a construction-time option (not an LLM-visible tool input) so the\n * search contract is fixed by the caller rather than chosen per invocation.\n *\n * @default false\n */\n strict?: boolean;\n}\n\n/**\n * Create a grep tool bound to the given options.\n *\n * By default read failures are reported honestly in the summary (skip counts)\n * rather than throwing. Pass `strict: true` to make any read failure throw.\n */\nexport function createGrepTool(options: GrepToolOptions = {}) {\n const strict = options.strict ?? false;\n return createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.GREP,\n description: `Search file contents using a regex pattern. Walks the filesystem and returns matching lines with file paths and line numbers.\n\nUsage:\n- Basic search: { pattern: \"TODO\" }\n- Regex: { pattern: \"function\\\\s+\\\\w+\\\\(\" }\n- Multiple terms: { pattern: \"TODO|FIXME|HACK\" }\n- Case-insensitive: { pattern: \"error\", caseSensitive: false }\n- Search in directory: { pattern: \"import\", path: \"./src\" }\n- Filter by glob: { pattern: \"import\", path: \"**/*.ts\" }\n- Combined path + glob: { pattern: \"import\", path: \"src/**/*.ts\" }\n- Multiple file types: { pattern: \"import\", path: \"**/*.{ts,tsx,js}\" }\n- Multiple directories: { pattern: \"TODO\", path: \"{src,lib}/**/*.ts\" }\n- With context: { pattern: \"function\", contextLines: 2 }`,\n outputSchema: z.string(),\n inputSchema: z.object({\n pattern: z.string().describe('Regex pattern to search for'),\n path: z\n .string()\n .optional()\n .default('.')\n .describe(\n 'File, directory, or glob pattern to search within (default: \".\"). ' +\n 'A plain path searches that file or directory. ' +\n 'A glob pattern (e.g., \"**/*.ts\", \"src/**/*.test.ts\") filters which files to search.',\n ),\n contextLines: z\n .number()\n .optional()\n .default(0)\n .describe('Number of lines of context to include before and after each match (default: 0)'),\n maxCount: z\n .number()\n .optional()\n .describe(\n 'Maximum matches per file. Moves on to the next file after this many matches. Similar to grep -m flag.',\n ),\n caseSensitive: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether the search is case-sensitive (default: true)'),\n includeHidden: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include hidden files and directories (names starting with \".\") in the search (default: false)'),\n }),\n execute: async (\n { pattern, path: inputPath = '.', contextLines = 0, maxCount, caseSensitive = true, includeHidden = false },\n context,\n ) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.GREP);\n\n // Honor provider-configured text extensions when available; otherwise use\n // the built-in set. Track files skipped solely for an unsupported extension\n // so the summary can distinguish \"no matches\" from \"nothing searched\".\n const isText = (filename: string): boolean =>\n filesystem.isTextFile ? filesystem.isTextFile(filename) : isTextFile(filename);\n let skippedExtensionCount = 0;\n\n // Track read failures so the summary can distinguish a partial/failed search\n // from a genuinely empty one. In `strict` mode these throw instead.\n let skippedReadErrorCount = 0;\n let targetNotFound = false;\n let scannedFileCount = 0;\n\n // The host-side walk stops early (returning partial results) when the run\n // is aborted or, for directory walks, once the time budget is spent.\n let walkDeadline: number | undefined;\n let incomplete: 'aborted' | 'time budget' | undefined;\n const shouldStop = (): boolean => {\n if (!incomplete) {\n if (context?.abortSignal?.aborted) incomplete = 'aborted';\n else if (walkDeadline !== undefined && Date.now() > walkDeadline) incomplete = 'time budget';\n }\n return incomplete !== undefined;\n };\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'grep',\n input: { pattern, path: inputPath, contextLines, maxCount },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n // Guard against excessively long patterns as a cheap ReDoS heuristic\n const MAX_PATTERN_LENGTH = 1000;\n if (pattern.length > MAX_PATTERN_LENGTH) {\n span.end({ success: false });\n return `Error: Pattern too long (${pattern.length} chars, max ${MAX_PATTERN_LENGTH}). Use a shorter pattern.`;\n }\n\n // Validate regex\n let regex: RegExp;\n try {\n regex = new RegExp(pattern, caseSensitive ? 'g' : 'gi');\n } catch (e) {\n span.end({ success: false });\n return `Error: Invalid regex pattern: ${(e as Error).message}`;\n }\n\n // Determine search root and glob filter from the combined path parameter\n let searchPath: string;\n let globMatcher: GlobMatcher | undefined;\n\n if (isGlobPattern(inputPath)) {\n // Path contains glob characters — extract the static base as search root\n searchPath = extractGlobBase(inputPath);\n globMatcher = createGlobMatcher(inputPath, { dot: includeHidden });\n } else {\n searchPath = inputPath;\n }\n\n // The walk below adds nested .gitignore files as it finds them.\n const workspaceIgnore = await loadWorkspaceIgnore(filesystem, searchPath, { requestedPath: inputPath });\n const isIgnored = (path: string, isDirectory: boolean) => workspaceIgnore.ignores(path, isDirectory);\n\n const MAX_LINE_LENGTH = 500;\n const GLOBAL_CAP = 1000;\n const normalizedContextLines = Math.max(0, Math.floor(contextLines));\n\n // Collect files to search\n let filePaths: string[] = [];\n let nativeResults: FilesystemGrepResult[] | undefined;\n\n // Never search inside .git even when explicitly targeted\n const normalizedSearch = searchPath.replace(/\\/$/, '');\n if (normalizedSearch === '.git' || normalizedSearch.endsWith('/.git')) {\n filePaths = [];\n } else {\n // Check if searchPath is a file or directory\n try {\n const stat = await filesystem.stat(searchPath);\n if (stat.type === 'file') {\n // Single file — search it directly. When the user targets an explicit\n // file whose extension isn't recognized as text, report it so the\n // summary distinguishes \"no matches\" from \"file was never searched\".\n if (isText(searchPath)) {\n filePaths = [searchPath];\n } else {\n filePaths = [];\n skippedExtensionCount++;\n }\n } else if (typeof filesystem.grep === 'function') {\n // Directory + native grep capability — one provider call instead of\n // walking the tree and reading every file host-side. Host-side\n // filtering (gitignore/glob/hidden/.git) is applied to the results.\n // Any failure (including UnsupportedGrepPatternError) falls back to\n // the walk below.\n try {\n nativeResults = await filesystem.grep({\n pattern,\n path: searchPath,\n caseSensitive,\n includeHidden,\n maxCountPerFile: maxCount,\n maxTotalMatches: GLOBAL_CAP,\n contextLines: normalizedContextLines,\n });\n } catch (error) {\n nativeResults = undefined;\n // The fallback walk costs one round trip per directory and file on\n // remote filesystems, so make the downgrade visible.\n const reason = error instanceof Error ? error.message : String(error);\n if (error instanceof UnsupportedGrepPatternError) {\n workspace.logger?.info(\n `Native grep on \"${filesystem.provider}\" filesystem could not run pattern \"${pattern}\" (${reason}); falling back to host-side search`,\n );\n } else {\n workspace.logger?.warn(\n `Native grep failed on \"${filesystem.provider}\" filesystem; falling back to host-side search for \"${searchPath}\"`,\n { error: reason },\n );\n }\n }\n }\n\n if (stat.type !== 'file' && !nativeResults) {\n // Directory — walk recursively with bounded concurrent listings\n const entriesByDirectory = new Map<string, Awaited<ReturnType<typeof filesystem.readdir>>>();\n let directoryFrontier = [searchPath];\n walkDeadline = Date.now() + HOST_WALK_BUDGET_MS;\n\n const pMap = (await import('p-map')).default;\n while (directoryFrontier.length > 0 && !shouldStop()) {\n const directoryEntries = await pMap(\n directoryFrontier,\n async dir => {\n // Skip listings not yet started once the walk must stop.\n if (shouldStop()) return undefined;\n try {\n return await filesystem.readdir(dir);\n } catch (err) {\n if (strict) throw err;\n skippedReadErrorCount++;\n return [];\n }\n },\n { concurrency: GREP_FILESYSTEM_CONCURRENCY },\n );\n const nextDirectoryFrontier: string[] = [];\n\n // Read each listed directory's .gitignore before filtering its\n // children, so its rules apply to everything below it.\n await workspaceIgnore.addListings(\n directoryFrontier.map((dir, directoryIndex) => [dir, directoryEntries[directoryIndex]]),\n );\n\n for (let directoryIndex = 0; directoryIndex < directoryFrontier.length; directoryIndex++) {\n const dir = directoryFrontier[directoryIndex]!;\n const entries = directoryEntries[directoryIndex];\n if (!entries) continue;\n entriesByDirectory.set(dir, entries);\n\n for (const entry of entries) {\n if (entry.type !== 'directory' || entry.isSymlink || entry.name === '.git') continue;\n if (!includeHidden && entry.name.startsWith('.')) continue;\n\n const fullPath = dir.endsWith('/') ? `${dir}${entry.name}` : `${dir}/${entry.name}`;\n if (isIgnored(fullPath, true)) continue;\n nextDirectoryFrontier.push(fullPath);\n }\n }\n\n directoryFrontier = nextDirectoryFrontier;\n }\n\n const collectFiles = (dir: string): string[] => {\n const files: string[] = [];\n for (const entry of entriesByDirectory.get(dir) ?? []) {\n // Always skip .git directory — its internals are never useful and waste tokens\n if (entry.type === 'directory' && entry.name === '.git') continue;\n\n // Skip hidden files/dirs unless includeHidden is set\n if (!includeHidden && entry.name.startsWith('.')) continue;\n\n const fullPath = dir.endsWith('/') ? `${dir}${entry.name}` : `${dir}/${entry.name}`;\n\n // Skip gitignored paths\n if (isIgnored(fullPath, entry.type === 'directory')) continue;\n\n if (entry.type === 'file') {\n // Apply glob filter first (createGlobMatcher normalizes leading\n // slashes) so files the user didn't ask for are never considered.\n if (globMatcher && !globMatcher(fullPath)) continue;\n // Skip non-text files. Directory-level skips are intentionally not\n // reported: the native-grep capability path cannot enumerate\n // zero-match unsupported files without a directory walk (which the\n // delegation contract forbids), so a per-directory skip count would\n // diverge between the native and fallback code paths.\n if (!isText(entry.name)) continue;\n files.push(fullPath);\n } else if (entry.type === 'directory' && !entry.isSymlink) {\n files.push(...collectFiles(fullPath));\n }\n }\n return files;\n };\n filePaths = collectFiles(searchPath);\n }\n } catch (err) {\n // Target could not be resolved. A genuinely missing path (ENOENT, or\n // ENOTDIR when a path component is not a directory) is reported as\n // \"not found\"; any other failure (permission, IO) is a read error.\n if (strict) throw err;\n if (isEnoentError(err) || isEnotdirError(err)) {\n targetNotFound = true;\n } else {\n skippedReadErrorCount++;\n }\n filePaths = [];\n }\n }\n\n const outputLines: string[] = [];\n const filesWithMatches = new Set<string>();\n let totalMatchCount = 0;\n let truncated = false;\n let emittedContextHunk = false;\n\n /**\n * Format one file's matches into outputLines. Shared between the native\n * capability path and the host-side walk so output is byte-identical.\n * `getLine` returns the text of a 0-based line index, or undefined when\n * the line is unavailable (out of bounds, or outside provider context).\n */\n const emitFileMatches = (\n filePath: string,\n fileMatches: Array<{ lineIndex: number; columnIndex: number }>,\n getLine: (lineIndex: number) => string | undefined,\n ): void => {\n if (normalizedContextLines > 0) {\n const hunks: Array<{\n start: number;\n end: number;\n matchesByLine: Map<number, number>;\n }> = [];\n\n for (const match of fileMatches) {\n const start = Math.max(0, match.lineIndex - normalizedContextLines);\n const end = match.lineIndex + normalizedContextLines;\n const previousHunk = hunks[hunks.length - 1];\n\n if (previousHunk && start <= previousHunk.end + 1) {\n previousHunk.end = Math.max(previousHunk.end, end);\n previousHunk.matchesByLine.set(match.lineIndex, match.columnIndex);\n } else {\n hunks.push({\n start,\n end,\n matchesByLine: new Map([[match.lineIndex, match.columnIndex]]),\n });\n }\n }\n\n for (const hunk of hunks) {\n if (emittedContextHunk) {\n outputLines.push('--');\n }\n emittedContextHunk = true;\n\n for (let i = hunk.start; i <= hunk.end; i++) {\n const columnIndex = hunk.matchesByLine.get(i);\n const line = getLine(i);\n if (line === undefined) continue;\n\n if (columnIndex !== undefined) {\n let lineContent = line;\n if (lineContent.length > MAX_LINE_LENGTH) {\n lineContent = sliceSafe(lineContent, 0, MAX_LINE_LENGTH) + '...';\n }\n outputLines.push(`${filePath}:${i + 1}:${columnIndex + 1}: ${lineContent}`);\n } else {\n outputLines.push(`${filePath}:${i + 1}- ${line}`);\n }\n }\n }\n } else {\n for (const match of fileMatches) {\n let lineContent = getLine(match.lineIndex) ?? '';\n if (lineContent.length > MAX_LINE_LENGTH) {\n lineContent = sliceSafe(lineContent, 0, MAX_LINE_LENGTH) + '...';\n }\n outputLines.push(`${filePath}:${match.lineIndex + 1}:${match.columnIndex + 1}: ${lineContent}`);\n }\n }\n };\n\n // Format native capability results with the same host-side filtering\n // (gitignore/glob/hidden/.git/text) and limits as the walk path.\n if (nativeResults) {\n // Providers may return ignored files; load the .gitignore files\n // between searchPath and each result before filtering.\n await workspaceIgnore.addParentsOf(\n nativeResults.map(result => {\n const rel = result.path.replace(/^\\.\\//, '');\n return searchPath.endsWith('/') ? `${searchPath}${rel}` : `${searchPath}/${rel}`;\n }),\n );\n for (const result of nativeResults) {\n if (truncated) break;\n\n const rel = result.path.replace(/^\\.\\//, '');\n const segments = rel.split('/');\n if (segments.includes('.git')) continue;\n if (!includeHidden && segments.some(segment => segment.startsWith('.'))) continue;\n // Not counted as a skip — see the directory-walk note above on why\n // per-directory skip reporting is omitted for parity across paths.\n if (!isText(segments[segments.length - 1]!)) continue;\n\n const fullPath = searchPath.endsWith('/') ? `${searchPath}${rel}` : `${searchPath}/${rel}`;\n if (isIgnored(fullPath, false)) continue;\n if (globMatcher && !globMatcher(fullPath)) continue;\n\n const lineTextByIndex = new Map<number, string>();\n const fileMatches: Array<{ lineIndex: number; columnIndex: number }> = [];\n let fileMatchCount = 0;\n\n for (const match of result.matches) {\n const lineIndex = match.line - 1;\n lineTextByIndex.set(lineIndex, match.text);\n match.before?.forEach((text, i) => lineTextByIndex.set(lineIndex - match.before!.length + i, text));\n match.after?.forEach((text, i) => lineTextByIndex.set(lineIndex + 1 + i, text));\n\n filesWithMatches.add(fullPath);\n fileMatches.push({ lineIndex, columnIndex: match.column });\n totalMatchCount++;\n fileMatchCount++;\n\n if (maxCount !== undefined && fileMatchCount >= maxCount) break;\n if (totalMatchCount >= GLOBAL_CAP) {\n truncated = true;\n break;\n }\n }\n\n emitFileMatches(fullPath, fileMatches, i => lineTextByIndex.get(i));\n }\n }\n\n const pMap = (await import('p-map')).default;\n for (\n let batchStart = 0;\n batchStart < filePaths.length && !truncated && !shouldStop();\n batchStart += GREP_FILESYSTEM_CONCURRENCY\n ) {\n const batchPaths = filePaths.slice(batchStart, batchStart + GREP_FILESYSTEM_CONCURRENCY);\n const batchContents = await pMap(\n batchPaths,\n async filePath => {\n if (shouldStop()) return undefined;\n try {\n const raw = await filesystem.readFile(filePath, { encoding: 'utf-8' });\n scannedFileCount++;\n return typeof raw === 'string' ? raw : undefined;\n } catch (err) {\n if (strict) throw err;\n skippedReadErrorCount++;\n return undefined;\n }\n },\n { concurrency: GREP_FILESYSTEM_CONCURRENCY },\n );\n\n for (let fileIndex = 0; fileIndex < batchPaths.length && !truncated; fileIndex++) {\n const filePath = batchPaths[fileIndex]!;\n const content = batchContents[fileIndex];\n if (content === undefined) continue;\n\n const lines = content.split('\\n');\n let fileMatchCount = 0;\n const fileMatches: Array<{ lineIndex: number; columnIndex: number }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const currentLine = lines[i]!;\n // Reset regex lastIndex for each line since we use 'g' flag\n regex.lastIndex = 0;\n const lineMatch = regex.exec(currentLine);\n if (!lineMatch) continue;\n\n filesWithMatches.add(filePath);\n\n fileMatches.push({ lineIndex: i, columnIndex: lineMatch.index });\n\n totalMatchCount++;\n fileMatchCount++;\n\n // Per-file limit (like grep -m)\n if (maxCount !== undefined && fileMatchCount >= maxCount) break;\n\n // Global cap to protect context window\n if (totalMatchCount >= GLOBAL_CAP) {\n truncated = true;\n break;\n }\n }\n\n emitFileMatches(filePath, fileMatches, i => lines[i]);\n }\n }\n\n // Summary line — placed at the top so it's always visible after truncation\n const summaryParts = [`${totalMatchCount} match${totalMatchCount !== 1 ? 'es' : ''}`];\n summaryParts.push(`across ${filesWithMatches.size} file${filesWithMatches.size !== 1 ? 's' : ''}`);\n if (truncated) {\n summaryParts.push(`(truncated at ${GLOBAL_CAP})`);\n }\n if (incomplete) {\n const scanned = `${scannedFileCount} file${scannedFileCount !== 1 ? 's' : ''} scanned`;\n summaryParts.push(\n incomplete === 'aborted'\n ? `(search incomplete: aborted, ${scanned}; results are partial)`\n : `(search incomplete: host-side search stopped after ${HOST_WALK_BUDGET_MS / 1000}s, ${scanned}; results are partial, narrow the path or pattern to search everything)`,\n );\n }\n if (skippedExtensionCount > 0) {\n summaryParts.push(\n `(${skippedExtensionCount} file${skippedExtensionCount !== 1 ? 's' : ''} skipped: unsupported extension)`,\n );\n }\n if (targetNotFound) {\n summaryParts.push('(target path not found: nothing searched)');\n }\n if (skippedReadErrorCount > 0) {\n summaryParts.push(\n `(${skippedReadErrorCount} path${skippedReadErrorCount !== 1 ? 's' : ''} skipped: read error)`,\n );\n }\n const summary = summaryParts.join(' ');\n outputLines.unshift(summary, '---');\n\n const output = await applyTokenLimit(\n outputLines.join('\\n'),\n workspace.getToolsConfig()?.[WORKSPACE_TOOLS.FILESYSTEM.GREP]?.maxOutputTokens,\n 'end',\n );\n span.end({ success: true }, { resultCount: totalMatchCount });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n });\n}\n\n/**\n * Default grep tool (non-strict: read failures are reported in the summary\n * rather than thrown). Use {@link createGrepTool} to opt into strict mode.\n */\nexport const grepTool = createGrepTool();\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { emitWorkspaceMetadata, requireWorkspace } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const indexContentTool = createTool({\n id: WORKSPACE_TOOLS.SEARCH.INDEX,\n description: 'Index content for search. The path becomes the document ID in search results.',\n inputSchema: z.object({\n path: z.string().describe('The document ID/path for search results'),\n content: z.string().describe('The text content to index'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Optional metadata to store with the document'),\n }),\n execute: async ({ path, content, metadata }, context) => {\n const workspace = requireWorkspace(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SEARCH.INDEX);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'search',\n operation: 'index',\n input: { path, contentLength: content.length },\n attributes: {},\n });\n\n try {\n await workspace.index(path, content, { metadata });\n span.end({ success: true }, { bytesTransferred: Buffer.byteLength(content, 'utf-8') });\n return `Indexed ${path}`;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { SandboxFeatureNotSupportedError } from '../errors';\nimport { emitWorkspaceMetadata, getDynamicSandboxCacheKeyHint, requireSandbox } from './helpers';\nimport { truncateOutput, sandboxToModelOutput } from './output-helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nconst KILL_TAIL_LINES = 50;\n\nexport const killProcessTool = createTool({\n id: WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS,\n description: `Kill a background process by its PID.\n\nUse this to stop a long-running background process that was started with execute_command (background: true). Returns the last ${KILL_TAIL_LINES} lines of output.`,\n toModelOutput: sandboxToModelOutput,\n outputSchema: z.string(),\n inputSchema: z.object({\n pid: z.string().describe('The process ID of the background process to kill'),\n }),\n execute: async ({ pid }, context) => {\n const { workspace, sandbox } = requireSandbox(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'sandbox',\n operation: 'killProcess',\n input: { pid },\n attributes: { sandboxProvider: sandbox.provider },\n });\n\n const toolCallId = context?.agent?.toolCallId;\n\n try {\n if (!sandbox.processes) {\n throw new SandboxFeatureNotSupportedError('processes');\n }\n // Snapshot output before kill\n const handle = await sandbox.processes.get(pid);\n\n // Emit command info so the UI can display the original command\n if (handle?.command) {\n await context?.writer?.custom({\n type: 'data-sandbox-command',\n data: { command: handle.command, pid, toolCallId },\n });\n }\n\n const killed = await sandbox.processes.kill(pid);\n\n if (!killed) {\n // A process that was never found has no exit to report.\n if (handle?.exitCode !== undefined) {\n await context?.writer?.custom({\n type: 'data-sandbox-exit',\n data: { exitCode: handle.exitCode, success: false, killed: false, toolCallId },\n });\n }\n span.end({ success: false });\n return `Process ${pid} was not found or had already exited.${getDynamicSandboxCacheKeyHint(workspace)}`;\n }\n\n await context?.writer?.custom({\n type: 'data-sandbox-exit',\n data: { exitCode: handle?.exitCode ?? 137, success: false, killed: true, toolCallId },\n });\n\n const parts: string[] = [`Process ${pid} has been killed.`];\n\n if (handle) {\n const tokenLimit = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS]?.maxOutputTokens;\n const stdout = handle.stdout\n ? await truncateOutput(handle.stdout, KILL_TAIL_LINES, tokenLimit, 'sandwich')\n : '';\n const stderr = handle.stderr\n ? await truncateOutput(handle.stderr, KILL_TAIL_LINES, tokenLimit, 'sandwich')\n : '';\n\n if (stdout) {\n parts.push('', '--- stdout (last output) ---', stdout);\n }\n if (stderr) {\n parts.push('', '--- stderr (last output) ---', stderr);\n }\n }\n\n span.end({ success: true }, { exitCode: handle?.exitCode ?? 137 });\n return parts.join('\\n');\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","/**\n * Tree Formatter\n *\n * Formats directory structures as ASCII tree output.\n * Works with any WorkspaceFilesystem implementation.\n *\n * @example\n * ```typescript\n * import { formatAsTree } from './tree-formatter';\n *\n * const result = await formatAsTree(filesystem, '/', { maxDepth: 3 });\n * console.log(result.tree);\n * // .\n * // src\n * // index.ts\n * // utils\n * // helpers.ts\n * // package.json\n * console.log(result.summary);\n * // \"2 directories, 3 files\"\n * ```\n */\n\nimport type { IMastraLogger } from '../../logger';\nimport { DirectoryNotFoundError, NotDirectoryError } from '../errors';\nimport type { WorkspaceFilesystem, FileEntry } from '../filesystem';\nimport type { IgnoreFilter } from '../gitignore';\nimport { loadWorkspaceIgnore } from '../gitignore';\nimport { createGlobMatcher } from '../glob';\nimport type { GlobMatcher } from '../glob';\n\n/** Maximum concurrent `readdir` calls while walking the tree. */\nconst TREE_FILESYSTEM_CONCURRENCY = 8;\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface TreeOptions {\n /** Maximum recursion depth (default: Infinity). Similar to tree's -L flag. */\n maxDepth?: number;\n /** Show hidden files/directories starting with '.' (default: false). Similar to tree's -a flag. */\n showHidden?: boolean;\n /** List directories only, no files (default: false). Similar to tree's -d flag. */\n dirsOnly?: boolean;\n /** Pattern to exclude from listing (e.g., 'node_modules'). Similar to tree's -I flag. */\n exclude?: string | string[];\n /** Filter by file extension (e.g., '.ts'). Similar to tree's -P flag. */\n extension?: string | string[];\n /** Glob pattern(s) to filter files. Matches against paths relative to the listed directory. Directories always pass through so their contents can be checked. */\n pattern?: string | string[];\n /** Filter function that returns true if a relative path should be ignored. Replaces the `.gitignore` rules when provided. */\n ignoreFilter?: IgnoreFilter;\n /** Respect `.gitignore` files (each relative to its own directory) and skip `node_modules` unless the listing targets one (default: true). */\n respectGitignore?: boolean;\n /** Logger used to report when a native `walk` capability fails and the slower readdir walk is used instead. */\n logger?: Pick<IMastraLogger, 'warn'>;\n}\n\nexport interface TreeResult {\n /** ASCII tree representation */\n tree: string;\n /** Human-readable summary (e.g., \"3 directories, 12 files\") */\n summary: string;\n /** Number of directories found */\n dirCount: number;\n /** Number of files found */\n fileCount: number;\n /** Whether output was truncated due to maxDepth */\n truncated: boolean;\n /** Relative paths for compact output */\n paths: string[];\n}\n\n// =============================================================================\n// Tree Formatting\n// =============================================================================\n\n/**\n * Format a directory as an ASCII tree.\n *\n * @param fs - WorkspaceFilesystem implementation\n * @param path - Root path to format\n * @param options - Formatting options\n * @returns Tree result with formatted string and counts\n */\nexport async function formatAsTree(fs: WorkspaceFilesystem, path: string, options?: TreeOptions): Promise<TreeResult> {\n const maxDepth = options?.maxDepth ?? Infinity;\n const showHidden = options?.showHidden ?? false;\n const dirsOnly = options?.dirsOnly ?? false;\n const exclude = options?.exclude;\n const extension = options?.extension;\n const pattern = options?.pattern;\n const respectGitignore = options?.respectGitignore ?? true;\n\n // Ignore rules: every .gitignore relative to its own directory, plus\n // node_modules unless the listing targets one. A caller-provided\n // ignoreFilter replaces the .gitignore rules. If the user explicitly\n // targets an ignored path (e.g. \"/dist\"), nothing below it is filtered.\n const customFilter = options?.ignoreFilter;\n const workspaceIgnore = respectGitignore\n ? await loadWorkspaceIgnore(fs, path, { gitignore: !customFilter })\n : undefined;\n const isIgnored = (entryPath: string, isDirectory: boolean): boolean => {\n if (workspaceIgnore?.ignores(entryPath, isDirectory)) return true;\n if (!customFilter) return false;\n const relativePath = getRelativePath('', '', entryPath);\n return customFilter(isDirectory ? `${relativePath}/` : relativePath);\n };\n const skipNodeModules = respectGitignore && !/(^|\\/)node_modules(\\/|$)/.test(path);\n\n // Compile glob matcher once before the walk (if pattern provided)\n let globMatcher: GlobMatcher | undefined;\n if (pattern) {\n const patterns = Array.isArray(pattern) ? pattern : [pattern];\n globMatcher = createGlobMatcher(patterns, { dot: showHidden });\n }\n\n const lines: string[] = ['.'];\n const paths: string[] = [];\n let dirCount = 0;\n let fileCount = 0;\n let truncated = false;\n\n // Parse exclude patterns once (like tree's -I flag, supports pipe-separated patterns)\n const excludePatterns = exclude\n ? Array.isArray(exclude)\n ? exclude\n : exclude\n .split('|')\n .map(p => p.trim())\n .filter(Boolean)\n : undefined;\n\n /**\n * Whether the walk should descend into a directory entry. Mirrors the\n * filtering applied before recursion in `buildTree` — directories filtered\n * out there are never listed, so their contents are never needed.\n */\n function shouldDescend(currentPath: string, entry: FileEntry): boolean {\n if (entry.type !== 'directory' || entry.isSymlink) return false;\n if (entry.name === '.git') return false;\n if (!showHidden && entry.name.startsWith('.')) return false;\n if (excludePatterns && excludePatterns.some(pattern => entry.name.includes(pattern))) return false;\n if (isIgnored(joinPath(currentPath, entry.name), true)) return false;\n return true;\n }\n\n // Prefetch all directory listings level-by-level with bounded concurrency,\n // instead of one sequential readdir per directory during tree construction.\n // On remote filesystems each readdir is a network round trip, so a serial\n // walk costs D × RTT for D directories.\n const entriesByPath = new Map<string, FileEntry[]>();\n let rootError: unknown;\n\n const normalizedRoot = path.replace(/\\/$/, '');\n const rootIsGit = normalizedRoot === '.git' || normalizedRoot.endsWith('/.git');\n const shouldWalk = !rootIsGit && maxDepth > 0;\n\n // If the filesystem implements the native bulk `walk` capability, fetch the\n // whole subtree in one provider call and group entries by parent directory.\n // On any failure, fall back to the readdir walk below (which reproduces\n // root-level errors like DirectoryNotFoundError naturally).\n let prefetched = false;\n if (shouldWalk && typeof fs.walk === 'function') {\n try {\n const walkEntries = await fs.walk(path, {\n maxDepth: Number.isFinite(maxDepth) ? maxDepth : undefined,\n includeHidden: showHidden,\n ...(workspaceIgnore && !customFilter ? { includeGitignoreFiles: true } : {}),\n ...(skipNodeModules ? { skipDirectoryNames: ['node_modules'] } : {}),\n });\n entriesByPath.set(path, []);\n for (const entry of walkEntries) {\n const separatorIndex = entry.path.lastIndexOf('/');\n const parentPath = separatorIndex === -1 ? path : joinPath(path, entry.path.slice(0, separatorIndex));\n let siblings = entriesByPath.get(parentPath);\n if (!siblings) {\n siblings = [];\n entriesByPath.set(parentPath, siblings);\n }\n siblings.push(entry);\n // Ensure empty directories have an entry list so recursion terminates cleanly\n if (entry.type === 'directory' && !entry.isSymlink) {\n const dirPath = joinPath(path, entry.path);\n if (!entriesByPath.has(dirPath)) entriesByPath.set(dirPath, []);\n }\n }\n prefetched = true;\n } catch (error) {\n entriesByPath.clear();\n // A missing or non-directory root is a caller error that the readdir\n // fallback re-raises with the same type; only warn about a real\n // provider failure, since the fallback costs one round trip per directory.\n if (!(error instanceof DirectoryNotFoundError) && !(error instanceof NotDirectoryError)) {\n options?.logger?.warn(\n `Native walk failed on \"${fs.provider}\" filesystem; falling back to per-directory readdir walk for \"${path}\"`,\n { error: error instanceof Error ? error.message : String(error) },\n );\n }\n }\n }\n if (prefetched) await workspaceIgnore?.addListings([...entriesByPath.entries()]);\n\n let frontier: Array<{ path: string; depth: number }> = !shouldWalk || prefetched ? [] : [{ path, depth: 0 }];\n\n const pMap = (await import('p-map')).default;\n while (frontier.length > 0) {\n const results = await pMap(\n frontier,\n async dir => {\n try {\n return { entries: await fs.readdir(dir.path) };\n } catch (error) {\n return { error };\n }\n },\n { concurrency: TREE_FILESYSTEM_CONCURRENCY },\n );\n\n // Read each listed directory's .gitignore before deciding what to descend into.\n await workspaceIgnore?.addListings(\n frontier.map((dir, i) => {\n const result = results[i]!;\n return [dir.path, 'entries' in result ? result.entries : undefined];\n }),\n );\n\n const nextFrontier: Array<{ path: string; depth: number }> = [];\n for (let i = 0; i < frontier.length; i++) {\n const { path: dirPath, depth } = frontier[i]!;\n const result = results[i]!;\n if ('error' in result) {\n // At root level (depth 0), propagate errors so users see auth/access issues.\n // For subdirectories, silently skip (permission issues on nested dirs are common).\n if (depth === 0) rootError = result.error;\n continue;\n }\n entriesByPath.set(dirPath, result.entries);\n // Children at depth + 1 >= maxDepth are never listed (only marked truncated)\n if (depth + 1 >= maxDepth) continue;\n for (const entry of result.entries) {\n if (shouldDescend(dirPath, entry)) {\n nextFrontier.push({ path: joinPath(dirPath, entry.name), depth: depth + 1 });\n }\n }\n }\n frontier = nextFrontier;\n }\n\n /**\n * Build tree recursively using tab indentation\n */\n function buildTree(currentPath: string, depth: number): void {\n // Never descend into .git even when explicitly targeted as root\n const normalizedCurrentPath = currentPath.replace(/\\/$/, '');\n if (normalizedCurrentPath === '.git' || normalizedCurrentPath.endsWith('/.git')) {\n return;\n }\n\n if (depth >= maxDepth) {\n truncated = true;\n return;\n }\n\n const entries = entriesByPath.get(currentPath);\n if (!entries) {\n if (depth === 0 && rootError !== undefined) {\n throw rootError;\n }\n return;\n }\n\n // Filter entries\n let filtered = entries;\n\n // Always skip .git directory — its internals are never useful and waste tokens.\n // This is applied before any other filtering so we never traverse into .git.\n filtered = filtered.filter(e => !(e.type === 'directory' && e.name === '.git'));\n\n // Filter hidden files unless showHidden\n if (!showHidden) {\n filtered = filtered.filter(e => !e.name.startsWith('.'));\n }\n\n // Filter by exclude pattern (like tree's -I flag, supports pipe-separated patterns)\n if (excludePatterns) {\n filtered = filtered.filter(e => {\n return !excludePatterns.some(pattern => e.name.includes(pattern));\n });\n }\n\n // Filter by .gitignore rules, node_modules, and any caller-provided ignoreFilter\n filtered = filtered.filter(e => !isIgnored(joinPath(currentPath, e.name), e.type === 'directory'));\n\n // Filter to directories only (like tree's -d flag)\n if (dirsOnly) {\n filtered = filtered.filter(e => e.type === 'directory');\n }\n\n // Filter by extension (only affects files, directories always pass)\n if (extension && !dirsOnly) {\n const extensions = Array.isArray(extension) ? extension : [extension];\n filtered = filtered.filter(e => {\n if (e.type === 'directory') return true;\n return extensions.some(ext => {\n // Support both '.ts' and 'ts' formats\n const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`;\n return e.name.endsWith(normalizedExt);\n });\n });\n }\n\n // Filter by glob pattern (only affects files, directories always pass)\n if (globMatcher && !dirsOnly) {\n filtered = filtered.filter(e => {\n if (e.type === 'directory') return true;\n const relativePath = getRelativePath(path, currentPath, e.name);\n return globMatcher(relativePath);\n });\n }\n\n // Sort: directories first, then alphabetically\n filtered.sort((a, b) => {\n if (a.type === 'directory' && b.type !== 'directory') return -1;\n if (a.type !== 'directory' && b.type === 'directory') return 1;\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n });\n\n const indent = '\\t'.repeat(depth);\n\n for (let i = 0; i < filtered.length; i++) {\n const entry = filtered[i]!;\n\n // Format entry name, including symlink target if present\n const displayName =\n entry.isSymlink && entry.symlinkTarget ? `${entry.name} -> ${entry.symlinkTarget}` : entry.name;\n\n lines.push(`${indent}${displayName}`);\n paths.push(getRelativePath(path, currentPath, entry.name));\n\n if (entry.type === 'directory') {\n dirCount++;\n // Don't recurse into symlinks (matches native tree behavior)\n // This also prevents infinite loops from circular symlinks\n if (!entry.isSymlink) {\n const childPath = joinPath(currentPath, entry.name);\n buildTree(childPath, depth + 1);\n }\n } else {\n fileCount++;\n }\n }\n }\n\n buildTree(path, 0);\n\n // Build summary\n const dirPart = dirCount === 1 ? '1 directory' : `${dirCount} directories`;\n const filePart = fileCount === 1 ? '1 file' : `${fileCount} files`;\n let summary = `${dirPart}, ${filePart}`;\n if (truncated) {\n summary += ` (truncated at depth ${maxDepth})`;\n }\n\n return {\n tree: lines.join('\\n'),\n summary,\n dirCount,\n fileCount,\n truncated,\n paths,\n };\n}\n\n/**\n * Format entries directly (without filesystem access).\n * Useful when you already have the entries and want tree output.\n *\n * @param entries - Flat list of entries with path-like names (e.g., \"dir/subdir/file.txt\")\n * @returns Formatted tree string\n */\nexport function formatEntriesAsTree(entries: Array<{ name: string; type: 'file' | 'directory' }>): string {\n // Build a nested structure from flat paths\n interface TreeNode {\n name: string;\n type: 'file' | 'directory';\n children: Map<string, TreeNode>;\n }\n\n const root: TreeNode = { name: '.', type: 'directory', children: new Map() };\n\n for (const entry of entries) {\n const parts = entry.name.split('/');\n let current = root;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i]!;\n const isLastPart = i === parts.length - 1;\n\n if (!current.children.has(part)) {\n current.children.set(part, {\n name: part,\n type: isLastPart ? entry.type : 'directory',\n children: new Map(),\n });\n }\n current = current.children.get(part)!;\n }\n }\n\n // Render tree\n const lines: string[] = ['.'];\n\n function renderNode(node: TreeNode, depth: number): void {\n const children = Array.from(node.children.values());\n // Sort: directories first, then alphabetically\n children.sort((a, b) => {\n if (a.type === 'directory' && b.type !== 'directory') return -1;\n if (a.type !== 'directory' && b.type === 'directory') return 1;\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n });\n\n const indent = '\\t'.repeat(depth);\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i]!;\n\n lines.push(`${indent}${child.name}`);\n\n if (child.children.size > 0) {\n renderNode(child, depth + 1);\n }\n }\n }\n\n renderNode(root, 0);\n return lines.join('\\n');\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction getRelativePath(rootPath: string, currentPath: string, entryName: string): string {\n const isRootEquivalent = (p: string) => p === '/' || p === '' || p === '.';\n const entryPath =\n currentPath === rootPath || (isRootEquivalent(currentPath) && isRootEquivalent(rootPath))\n ? entryName\n : `${currentPath === '/' ? '' : currentPath}/${entryName}`;\n\n if (isRootEquivalent(rootPath)) {\n // Strip leading './' or '/' so callers always get a clean relative path\n const cleaned = entryPath.replace(/^\\.\\//, '');\n return cleaned.startsWith('/') ? cleaned.slice(1) : cleaned;\n }\n\n const relativePath = entryPath.startsWith(rootPath + '/') ? entryPath.slice(rootPath.length + 1) : entryPath;\n return relativePath || entryPath;\n}\n\n/**\n * Join path segments, handling root paths correctly\n */\nfunction joinPath(base: string, name: string): string {\n if (base === '' || base === './' || base === '.') {\n return name;\n }\n if (base === '/') {\n return `/${name}`;\n }\n return `${base}/${name}`;\n}\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport { applyTokenLimit } from './output-helpers';\nimport { startWorkspaceSpan } from './tracing';\nimport { formatAsTree } from './tree-formatter';\n\nexport const listFilesTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES,\n description: `List files and directories in the workspace filesystem.\nReturns a compact tab-indented listing for efficient token usage.\nOptions mirror common tree command flags for familiarity.\n\nExamples:\n- List workspace root: { path: \".\" }\n- Deep listing: { path: \"src\", maxDepth: 5 }\n- Directories only: { path: \".\", dirsOnly: true }\n- Exclude node_modules: { path: \".\", exclude: \"node_modules\" }\n- Find TypeScript files: { path: \"src\", pattern: \"**/*.ts\" }\n- Find config files: { path: \".\", pattern: \"*.config.{js,ts}\" }\n- Multiple patterns: { path: \".\", pattern: [\"**/*.ts\", \"**/*.tsx\"] }\n\nTo list ALL files, omit the pattern parameter — do NOT pass pattern: \"*\".`,\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().default('.').describe('Directory path to list'),\n maxDepth: z\n .number()\n .optional()\n .default(2)\n .describe('Maximum depth to descend (default: 2). Similar to tree -L flag.'),\n showHidden: z\n .boolean()\n .optional()\n .default(false)\n .describe('Show hidden files starting with \".\" (default: false). Similar to tree -a flag.'),\n dirsOnly: z\n .boolean()\n .optional()\n .default(false)\n .describe('List directories only, no files (default: false). Similar to tree -d flag.'),\n exclude: z.string().optional().describe('Pattern to exclude (e.g., \"node_modules\"). Similar to tree -I flag.'),\n extension: z.string().optional().describe('Filter by file extension (e.g., \".ts\"). Similar to tree -P flag.'),\n pattern: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe(\n 'Glob pattern(s) to filter files. Omit this parameter to list all files (do NOT pass \"*\"). Use \"**/*.ext\" to match files recursively across directories. \"*\" only matches within a single directory level (standard glob). Glob patterns only filter files — directories are always shown to preserve tree structure. Examples: \"**/*.ts\", \"src/**/*.test.ts\", \"*.config.{js,ts}\".',\n ),\n respectGitignore: z\n .boolean()\n .optional()\n .default(true)\n .describe('Respect .gitignore in the listed directory (default: true).'),\n }),\n execute: async (\n { path = '.', maxDepth = 2, showHidden, dirsOnly, exclude, extension, pattern, respectGitignore },\n context,\n ) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES);\n\n // Agents often pass pattern: [] or pattern: '' expecting \"list everything\".\n // Empty/whitespace-only patterns would otherwise filter out every file, or\n // throw from picomatch. Normalize them to undefined so the listing falls back\n // to its unfiltered behavior.\n const normalizedPattern = (() => {\n if (pattern === undefined) return undefined;\n if (Array.isArray(pattern)) {\n const cleaned = pattern.filter(p => typeof p === 'string' && p.trim().length > 0);\n return cleaned.length > 0 ? cleaned : undefined;\n }\n return pattern.trim().length > 0 ? pattern : undefined;\n })();\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'listFiles',\n input: { path, maxDepth, pattern: normalizedPattern },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n const result = await formatAsTree(filesystem, path, {\n maxDepth,\n showHidden,\n dirsOnly,\n exclude: exclude || undefined,\n extension: extension || undefined,\n pattern: normalizedPattern,\n respectGitignore,\n logger: workspace.logger,\n });\n\n const output = await applyTokenLimit(\n `${result.tree}\\n\\n${result.summary}`,\n workspace.getToolsConfig()?.[WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES]?.maxOutputTokens ?? 1_000,\n 'end',\n );\n span.end({ success: true }, { resultCount: result.fileCount });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","/**\n * LSP Inspect Tool\n *\n * Inspect code at a specific position using the Language Server Protocol.\n * The agent provides a file path, line number, and a `<<<` marker in the\n * line content to indicate the cursor position.\n */\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { z } from 'zod/v4';\n\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { requireWorkspace, emitWorkspaceMetadata } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nconst CURSOR_MARKER = '<<<';\n\n/**\n * Get a single line preview from a file at the specified line number.\n * Returns the trimmed line content, or null if the line cannot be read.\n */\nasync function getLinePreview(filePath: string, lineNumber: number): Promise<string | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const line = lines[lineNumber - 1];\n return line?.trim() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction getAbsolutePath(\n workspacePath: string,\n lspRoot: string,\n resolveAbsolutePath?: (path: string) => string | undefined,\n) {\n const resolvedPath = resolveAbsolutePath?.(workspacePath);\n if (resolvedPath) {\n return resolvedPath;\n }\n\n if (path.isAbsolute(workspacePath)) {\n return workspacePath;\n }\n\n return path.resolve(lspRoot, workspacePath);\n}\n\nfunction locationUriToPath(uri: string): string | null {\n if (!uri.startsWith('file://')) {\n return null;\n }\n\n try {\n return fileURLToPath(uri);\n } catch {\n return null;\n }\n}\n\nfunction locationKey(location: { path: string; line: number }): string {\n return `${location.path}:L${location.line}`;\n}\n\n/**\n * Compress a file path by replacing the current working directory prefix with $cwd\n */\nfunction compressPath(filePath: string): string {\n const cwd = process.cwd();\n if (filePath.startsWith(cwd)) {\n return '$cwd' + filePath.slice(cwd.length);\n }\n return filePath;\n}\n\nexport const lspInspectTool = createTool({\n id: WORKSPACE_TOOLS.LSP.LSP_INSPECT,\n description:\n 'Inspect code at a specific symbol position using the Language Server Protocol. ' +\n 'Provide an absolute file path, a 1-indexed line number, and the exact line content with <<< marking the cursor position. ' +\n 'Exactly one <<< marker is required. ' +\n 'Returns hover information, any diagnostics reported on that line, plus definition and implementation locations when available. ' +\n 'Use this for type information, symbol navigation, and go-to-definition; use view to read the surrounding implementation.',\n\n outputSchema: z.object({\n hover: z.object({ value: z.string(), kind: z.string() }).optional(),\n diagnostics: z\n .array(\n z.object({\n severity: z.string(),\n message: z.string(),\n source: z.string().nullable(),\n }),\n )\n .optional(),\n definition: z\n .array(\n z.object({\n location: z.string(),\n preview: z.string().nullable(),\n }),\n )\n .optional(),\n implementation: z.array(z.string()).optional(),\n error: z.string().optional(),\n }),\n\n inputSchema: z.object({\n path: z.string().describe('Absolute path to the file'),\n line: z.number().int().positive().describe('Line number (1-indexed)'),\n match: z\n .string()\n .describe(\n 'Line content with <<< marking the cursor position. ' +\n 'Exactly one <<< marker is required. ' +\n 'Example: \"const foo = <<<bar()\" means cursor is at bar',\n ),\n }),\n\n execute: async ({ path: filePath, line, match }, context) => {\n const workspace = requireWorkspace(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.LSP.LSP_INSPECT);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'lspInspect',\n input: { path: filePath, line },\n attributes: {},\n });\n\n // Parse cursor position from match\n const cursorPositions = [];\n let searchStart = 0;\n while (true) {\n const pos = match.indexOf(CURSOR_MARKER, searchStart);\n if (pos === -1) break;\n cursorPositions.push(pos);\n searchStart = pos + CURSOR_MARKER.length;\n }\n\n if (cursorPositions.length === 0) {\n span.end({ success: false });\n return {\n error: `No <<< cursor marker found in match`,\n };\n }\n\n if (cursorPositions.length > 1) {\n span.end({ success: false });\n return {\n error: `Multiple <<< markers found (found ${cursorPositions.length}, expected 1)`,\n };\n }\n\n // 1-indexed character position (LSP uses 1-indexed)\n const character = cursorPositions[0]! + 1;\n\n // Get the LSP manager\n const lspManager = workspace.lsp;\n if (!lspManager) {\n span.end({ success: false });\n return {\n error: 'LSP is not configured for this workspace. Enable LSP in workspace config to use this tool.',\n };\n }\n\n const absolutePath = getAbsolutePath(\n filePath,\n lspManager.root,\n workspace.filesystem?.resolveAbsolutePath?.bind(workspace.filesystem),\n );\n\n let fileContent = '';\n try {\n fileContent = await fs.readFile(absolutePath, 'utf-8');\n } catch {\n fileContent = '';\n }\n\n // Get client and prepare for querying\n let queryResult;\n try {\n queryResult = await lspManager.prepareQuery(absolutePath);\n } catch (err) {\n span.end({ success: false });\n return {\n error: `Failed to initialize LSP client: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n\n if (!queryResult) {\n span.end({ success: false });\n return {\n error: `No language server available for files of this type: ${filePath}`,\n };\n }\n\n const { client, uri, release } = queryResult;\n\n // LSP uses 0-indexed positions\n const position = { line: line - 1, character: character - 1 };\n\n // Execute queries - minimal output\n const result: Record<string, unknown> = {};\n\n try {\n // Primary query: hover\n const hoverResult = await client.queryHover(uri, position).catch(() => null);\n if (hoverResult) {\n const contents = hoverResult.contents;\n if (contents) {\n if (typeof contents === 'string') {\n result.hover = { value: contents, kind: 'plaintext' };\n } else if (Array.isArray(contents)) {\n // Usually [MarkupContent] or [string]\n const first = contents[0];\n if (typeof first === 'string') {\n result.hover = { value: first, kind: 'plaintext' };\n } else if (first?.value) {\n result.hover = { value: first.value, kind: first.kind ?? 'markdown' };\n }\n } else if (contents.value) {\n result.hover = { value: contents.value, kind: contents.kind ?? 'markdown' };\n }\n }\n }\n\n const diagnosticsPromise = fileContent\n ? Promise.resolve()\n .then(() => {\n client.notifyChange(absolutePath, fileContent, 1);\n return client.waitForDiagnostics(absolutePath, 5000, true);\n })\n .catch(() => [])\n : Promise.resolve([]);\n\n // Secondary queries: diagnostics, definition, and implementation\n const [diagnosticsResult, definitionResult, implResult] = await Promise.all([\n diagnosticsPromise,\n client.queryDefinition(uri, position).catch(() => []),\n client.queryImplementation(uri, position).catch(() => []),\n ]);\n\n if (diagnosticsResult && diagnosticsResult.length > 0) {\n const lineDiagnostics = diagnosticsResult\n .map((diagnostic: any) => ({\n line: typeof diagnostic.line === 'number' ? diagnostic.line : (diagnostic.range?.start?.line ?? -1) + 1,\n severity:\n typeof diagnostic.severity === 'number'\n ? diagnostic.severity === 1\n ? 'error'\n : diagnostic.severity === 2\n ? 'warning'\n : diagnostic.severity === 3\n ? 'info'\n : 'hint'\n : typeof diagnostic.severity === 'string'\n ? diagnostic.severity\n : 'error',\n message: diagnostic.message,\n source: diagnostic.source ?? null,\n }))\n .filter(diagnostic => diagnostic.line === line)\n .map(({ severity, message, source }) => ({ severity, message, source }));\n\n if (lineDiagnostics.length > 0) {\n result.diagnostics = lineDiagnostics;\n }\n }\n\n const definitionLocations = definitionResult\n .map((loc: any) => ({\n uri: loc.uri ?? loc.targetUri,\n range: loc.range ?? loc.targetRange,\n }))\n .map((loc: any) => {\n const resolvedPath = loc.uri ? locationUriToPath(String(loc.uri)) : null;\n return resolvedPath\n ? {\n path: resolvedPath,\n line: (loc.range?.start?.line ?? 0) + 1,\n character: (loc.range?.start?.character ?? 0) + 1,\n }\n : null;\n })\n .filter((loc): loc is { path: string; line: number; character: number } => Boolean(loc))\n .filter(loc => !(loc.path === absolutePath && loc.line === line));\n\n if (definitionLocations.length > 0) {\n const previews = await Promise.all(definitionLocations.map(loc => getLinePreview(loc.path, loc.line)));\n result.definition = definitionLocations.map((loc, i) => ({\n location: `${compressPath(loc.path)}:L${loc.line}:C${loc.character}`,\n preview: previews[i],\n }));\n }\n\n const definitionKeys = new Set(definitionLocations.map(locationKey));\n const implementationLocations = implResult\n .map((loc: any) => ({\n uri: loc.uri ?? loc.targetUri,\n range: loc.range ?? loc.targetRange,\n }))\n .map((loc: any) => {\n const resolvedPath = loc.uri ? locationUriToPath(String(loc.uri)) : null;\n return resolvedPath\n ? {\n path: resolvedPath,\n line: (loc.range?.start?.line ?? 0) + 1,\n character: (loc.range?.start?.character ?? 0) + 1,\n }\n : null;\n })\n .filter((loc): loc is { path: string; line: number; character: number } => Boolean(loc))\n .filter(loc => !definitionKeys.has(locationKey(loc)) && !(loc.path === absolutePath && loc.line === line));\n\n if (implementationLocations.length > 0) {\n result.implementation = implementationLocations.map(\n loc => `${compressPath(loc.path)}:L${loc.line}:C${loc.character}`,\n );\n }\n } catch (err) {\n result.error = `LSP query failed: ${err instanceof Error ? err.message : String(err)}`;\n } finally {\n // Clean up - close the file and release the client lease\n client.notifyClose(absolutePath);\n release();\n }\n\n span.end({ success: !result.error });\n return result;\n },\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { WorkspaceReadOnlyError } from '../errors';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const mkdirTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.MKDIR,\n description: 'Create a directory in the workspace filesystem',\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().describe('The path of the directory to create'),\n recursive: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether to create parent directories if they do not exist'),\n }),\n execute: async ({ path, recursive }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.MKDIR);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'mkdir',\n input: { path, recursive },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n if (filesystem.readOnly) {\n throw new WorkspaceReadOnlyError('mkdir');\n }\n\n await filesystem.mkdir(path, { recursive });\n span.end({ success: true });\n return `Created directory ${path}`;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { extractLinesWithLimit, formatWithLineNumbers } from '../line-utils';\nimport { emitWorkspaceMetadata, requireFilesystem } from './helpers';\nimport type { MediaToolResult } from './media';\nimport { DEFAULT_MAX_MEDIA_BYTES, mediaToModelOutput } from './media';\nimport { applyTokenLimit } from './output-helpers';\nimport { startWorkspaceSpan } from './tracing';\n\n/**\n * Default mime types surfaced to the model as media parts. The list is\n * intentionally the intersection of image formats supported by the major\n * model providers (Anthropic, OpenAI, Gemini) plus `application/pdf`.\n * `image/*` is *not* used so we don't surface exotic subtypes like SVG/BMP\n * that some providers reject. Override `mediaTypes` to broaden this.\n */\nconst DEFAULT_MEDIA_TYPES: string[] = ['image/png', 'image/jpeg', 'image/webp', 'application/pdf'];\n\n/**\n * `application/*` mime types that are actually text content and safe to read\n * as utf-8. Anything not matching `text/*` and not in this list is treated\n * as opaque binary when there's no explicit encoding and no media match.\n */\nconst TEXT_APPLICATION_TYPES = new Set([\n 'application/json',\n 'application/javascript',\n 'application/typescript',\n 'application/xml',\n 'application/graphql',\n 'application/x-sh',\n 'application/x-yaml',\n 'application/yaml',\n 'application/ld+json',\n 'application/sql',\n 'application/jsonl',\n 'application/x-jsonl',\n 'application/ndjson',\n 'application/x-ndjson',\n 'application/jsonlines',\n 'application/json-lines',\n 'application/x-jsonlines',\n 'application/x-php',\n 'application/dart',\n]);\n\n/**\n * Charsets whose bytes decode correctly as utf-8. Text content declared with\n * any other charset (e.g. `utf-16le`) would be garbled by a utf-8 read.\n */\nconst UTF8_COMPATIBLE_CHARSETS = new Set(['utf-8', 'utf8', 'us-ascii', 'ascii']);\n\n/** Matches `; name=value` MIME parameters, keeping quoted values (which may contain `;`) whole. */\nconst MIME_PARAMETER_PATTERN = /;\\s*([^\\s;=]+)\\s*=\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|[^;]*)/g;\n\nfunction getMimeCharset(mimeType: string): string | undefined {\n for (const [, name, value] of mimeType.matchAll(MIME_PARAMETER_PATTERN)) {\n if (name!.toLowerCase() !== 'charset') continue;\n const unquoted = value!.startsWith('\"') ? value!.slice(1, -1).replace(/\\\\(.)/g, '$1') : value!;\n return unquoted.trim().toLowerCase();\n }\n return undefined;\n}\n\nfunction isTextLikeMimeType(mimeType: string | undefined): boolean {\n if (!mimeType) return true;\n const charset = getMimeCharset(mimeType);\n if (charset !== undefined && !UTF8_COMPATIBLE_CHARSETS.has(charset)) return false;\n mimeType = mimeType.split(';', 1)[0]!.trim().toLowerCase();\n // `application/octet-stream` is the catch-all for unknown extensions; we\n // optimistically treat it as text so files like `.log` or `.conf` (which\n // have no registered mime mapping) still get read as utf-8.\n if (mimeType === 'application/octet-stream') return true;\n if (mimeType.startsWith('text/')) return true;\n if (TEXT_APPLICATION_TYPES.has(mimeType)) return true;\n if (mimeType.endsWith('+json') || mimeType.endsWith('+xml')) return true;\n return false;\n}\n\n/**\n * Validates a single `mediaTypes` pattern. Accepts:\n * - `*` or `*/*` — match anything\n * - `type/*` — match all subtypes of a top-level type (e.g. `image/*`)\n * - `type/subtype` — exact mime type (e.g. `application/pdf`, `application/vnd.api+json`)\n *\n * Throws a descriptive error for anything else so misconfigurations surface\n * immediately instead of silently failing to match.\n */\nconst MEDIA_TYPE_PATTERN = /^(?:\\*|\\*\\/\\*|[a-z0-9!#$&^_.+-]+\\/(?:\\*|[a-z0-9!#$&^_.+-]+))$/i;\n\nfunction validateMediaTypePatterns(patterns: string[]): void {\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' || !MEDIA_TYPE_PATTERN.test(pattern)) {\n throw new Error(\n `Invalid \\`mediaTypes\\` pattern: ${JSON.stringify(pattern)}. Expected \\`*\\`, \\`*/*\\`, \\`type/*\\`, or a full mime type like \\`application/pdf\\`.`,\n );\n }\n }\n}\n\n/**\n * Build a predicate from the `mediaTypes` config option.\n * Supports glob patterns (e.g. `'image/*'`), custom functions, and `false`\n * to disable media parts entirely.\n */\nfunction buildMediaTypeCheck(\n config: string[] | ((mimeType: string) => boolean) | false | undefined,\n): (mimeType: string | undefined) => boolean {\n if (config === false) return () => false;\n if (typeof config === 'function') {\n return (mimeType: string | undefined) => (mimeType ? config(mimeType) : false);\n }\n const patterns = config ?? DEFAULT_MEDIA_TYPES;\n validateMediaTypePatterns(patterns);\n return (mimeType: string | undefined) => {\n if (!mimeType) return false;\n return patterns.some(pattern => {\n if (pattern === '*' || pattern === '*/*') return true;\n if (pattern.endsWith('/*')) {\n return mimeType.startsWith(pattern.slice(0, -1));\n }\n return mimeType === pattern;\n });\n };\n}\n\n/** Bytes decoded from the start of a media file to check its signature. PDF allows its header anywhere in the first 1 KiB. */\nconst MEDIA_SNIFF_BYTES = 1024;\n\nconst startsWithBytes = (bytes: Uint8Array, prefix: number[], offset = 0) =>\n bytes.length >= offset + prefix.length && prefix.every((byte, index) => bytes[offset + index] === byte);\n\n/**\n * Media types with a fixed signature, and how to recognize each from a file's first bytes.\n * Other configured types (e.g. SVG, HEIC, audio) have no reliable signature here and are\n * trusted by extension.\n */\nconst MEDIA_SIGNATURES: [mediaType: string, matches: (bytes: Uint8Array) => boolean][] = [\n ['image/png', bytes => startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47])],\n ['image/jpeg', bytes => startsWithBytes(bytes, [0xff, 0xd8, 0xff])],\n // `GIF87a` or `GIF89a`.\n [\n 'image/gif',\n bytes =>\n startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]) ||\n startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38, 0x39, 0x61]),\n ],\n [\n 'image/webp',\n bytes => startsWithBytes(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWithBytes(bytes, [0x57, 0x45, 0x42, 0x50], 8),\n ],\n // A version header such as `%PDF-1.7`, which readers accept anywhere in the first 1 KiB.\n ['application/pdf', bytes => /%PDF-\\d\\.\\d/.test(Buffer.from(bytes).toString('latin1'))],\n];\n\nconst SIGNED_MEDIA_TYPES = new Set([...MEDIA_SIGNATURES.map(([mediaType]) => mediaType), 'image/jpg']);\n\n/**\n * The media type to send for a file whose extension maps to `declared`. For types with a known\n * signature, this is the type the bytes show (so a PNG named `.jpg` goes as `image/png`), or\n * undefined when they show none: an HTML error page saved as `.pdf` is not a PDF, and providers\n * reject it with a 400 that also fails every later call carrying the same history.\n */\nfunction contentMediaType(head: Uint8Array, declared: string): string | undefined {\n if (!SIGNED_MEDIA_TYPES.has(declared.split(';', 1)[0]!.trim().toLowerCase())) return declared;\n return MEDIA_SIGNATURES.find(([, matches]) => matches(head))?.[0];\n}\n\n/** Whether a whole file is UTF-8 text: no NUL bytes and no invalid sequences. */\nfunction isUtf8Text(content: Uint8Array): boolean {\n if (content.includes(0)) return false;\n try {\n new TextDecoder('utf-8', { fatal: true }).decode(content);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const readFileTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.READ_FILE,\n description:\n 'Read a file from the workspace filesystem. Text files come back as text — use offset/limit to read a line range from large files. Supported media files come back as a native file part you can view directly. Other binary files return only their metadata (path, size, mime type) since their raw contents are not useful to read.',\n outputSchema: z.union([\n z.string(),\n z.object({\n __workspaceMedia: z.literal(true),\n text: z.string(),\n mediaType: z.string(),\n data: z.string(),\n }),\n ]),\n inputSchema: z.object({\n path: z.string().describe('The path to the file to read (e.g., \"data/config.json\")'),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\n 'Line number to start reading from (1-indexed). Only used when reading text files; ignored for media and other binary files. Defaults to line 1 if omitted.',\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\n 'Maximum number of lines to read. Only used when reading text files; ignored for media and other binary files. Defaults to the end of the file if omitted.',\n ),\n showLineNumbers: z\n .boolean()\n .optional()\n .default(true)\n .describe(\n 'Prefix each line with its line number. Only used when reading text files; ignored for media and other binary files. Defaults to true if omitted.',\n ),\n encoding: z\n .enum(['utf-8', 'utf8', 'base64', 'hex', 'binary'])\n .optional()\n .describe(\n \"Usually omit this — text files and supported media are handled automatically. Pass `base64` or `hex` to get the file's raw bytes encoded as text when you need to inspect an unsupported binary file that would otherwise only return metadata (e.g. checking a file header or magic bytes).\",\n ),\n }),\n execute: async ({ path, encoding, offset, limit, showLineNumbers }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.READ_FILE);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'readFile',\n input: { path, encoding, offset, limit },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n const stat = await filesystem.stat(path);\n\n const readFileConfig = workspace.getToolsConfig()?.[WORKSPACE_TOOLS.FILESYSTEM.READ_FILE];\n const shouldReturnAsMedia = buildMediaTypeCheck(readFileConfig?.mediaTypes);\n\n // Whether the file is surfaced as media is decided from the file's mime\n // type and the `mediaTypes` config — NOT from the absence of the optional\n // `encoding` argument. Strict-schema providers always populate optional\n // parameters, so gating this branch on `!encoding` made media parts\n // unreachable for them and turned `mediaTypes`/`maxMediaBytes` into dead\n // config (#23896). Read as base64 and return a MediaToolResult so\n // `toModelOutput` can surface it as a file/image part the model can\n // natively consume.\n // Set when the extension says media but the bytes don't, and the bytes read as text.\n let mislabeledNote: string | undefined;\n if (shouldReturnAsMedia(stat.mimeType)) {\n const maxMediaBytes = readFileConfig?.maxMediaBytes ?? DEFAULT_MAX_MEDIA_BYTES;\n if (stat.size <= maxMediaBytes) {\n const base64 = (await filesystem.readFile(path, { encoding: 'base64' })) as string;\n const head = Buffer.from(base64.slice(0, Math.ceil(MEDIA_SNIFF_BYTES / 3) * 4), 'base64');\n const mediaType = contentMediaType(head, stat.mimeType!);\n if (mediaType && shouldReturnAsMedia(mediaType)) {\n const header = `${stat.path} (${stat.size} bytes, ${mediaType})`;\n span.end({ success: true }, { bytesTransferred: stat.size });\n return {\n __workspaceMedia: true,\n text: header,\n mediaType,\n data: base64,\n } satisfies MediaToolResult;\n }\n // The extension says media but the content isn't. Never send it as media: show text\n // content as text, and only metadata for anything else, unless `encoding` was given.\n const mismatch = `the extension says ${stat.mimeType}, but the content is ${mediaType ?? 'not a valid file of that type'}`;\n // The whole file, not just its head: binary content can follow a first KiB of ASCII.\n if (isUtf8Text(Buffer.from(base64, 'base64'))) {\n mislabeledNote = mismatch;\n } else if (!encoding) {\n span.end({ success: true }, { bytesTransferred: 0 });\n return `${stat.path} (${stat.size} bytes) — ${mismatch}, so it was not sent as media. Pass an explicit \\`encoding\\` (e.g. \\`hex\\`) to read the raw bytes.`;\n }\n } else if (!encoding) {\n // Oversized media: avoid materializing huge base64 strings (and\n // persisting them through storage on rehydration). Return metadata-only\n // unless the caller explicitly asked for raw bytes via `encoding`, in\n // which case fall through to the raw read path below.\n span.end({ success: true }, { bytesTransferred: 0 });\n return `${stat.path} (${stat.size} bytes, ${stat.mimeType}) — exceeds maxMediaBytes (${maxMediaBytes}). Returning metadata only; configure \\`maxMediaBytes\\` on the read_file tool to raise this cap.`;\n }\n }\n\n // When the caller didn't ask for a specific encoding and the file is\n // a binary type that's neither text-readable nor in `mediaTypes`,\n // return metadata only so the agent knows about the file without\n // dumping useless base64 into the conversation.\n if (!encoding && !mislabeledNote && !isTextLikeMimeType(stat.mimeType)) {\n span.end({ success: true }, { bytesTransferred: 0 });\n return `${stat.path} (${stat.size} bytes, ${stat.mimeType ?? 'unknown'}) — binary file not readable as text. Pass an explicit \\`encoding\\` (e.g. \\`base64\\`) to read the raw bytes, or configure \\`mediaTypes\\` on the read_file tool to surface it as a media part.`;\n }\n\n const effectiveEncoding = (encoding as BufferEncoding) ?? 'utf-8';\n const fullContent = await filesystem.readFile(path, { encoding: effectiveEncoding });\n\n const isTextEncoding = !encoding || encoding === 'utf-8' || encoding === 'utf8';\n\n const tokenLimit = readFileConfig?.maxOutputTokens;\n\n if (!isTextEncoding) {\n const output = await applyTokenLimit(\n `${stat.path} (${stat.size} bytes, ${effectiveEncoding})\\n${fullContent}`,\n tokenLimit,\n 'end',\n );\n span.end({ success: true }, { bytesTransferred: stat.size });\n return output;\n }\n\n if (typeof fullContent !== 'string') {\n const output = await applyTokenLimit(\n `${stat.path} (${stat.size} bytes, base64)\\n${fullContent.toString('base64')}`,\n tokenLimit,\n 'end',\n );\n span.end({ success: true }, { bytesTransferred: stat.size });\n return output;\n }\n\n const hasLineRange = offset !== undefined || limit !== undefined;\n const result = extractLinesWithLimit(fullContent, offset, limit);\n\n const shouldShowLineNumbers = showLineNumbers !== false;\n const hasExtractedLines = result.lines.start !== 0 || result.lines.end !== 0;\n const formattedContent =\n shouldShowLineNumbers && hasExtractedLines\n ? formatWithLineNumbers(result.content, result.lines.start)\n : result.content;\n\n let header: string;\n if (hasLineRange) {\n header = `${stat.path} (lines ${result.lines.start}-${result.lines.end} of ${result.totalLines}, ${stat.size} bytes)`;\n } else {\n header = `${stat.path} (${stat.size} bytes)`;\n }\n if (mislabeledNote) header += ` — ${mislabeledNote}; showing it as text`;\n\n const output = await applyTokenLimit(`${header}\\n${formattedContent}`, tokenLimit, 'end');\n span.end({ success: true }, { bytesTransferred: stat.size });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n // For plain string output, mediaToModelOutput returns undefined so we don't\n // store a duplicate copy on providerMetadata.mastra.modelOutput — the\n // original string result is already what the model sees.\n toModelOutput: mediaToModelOutput,\n});\n","import { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { emitWorkspaceMetadata, requireWorkspace } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const searchInputSchema = z.object({\n query: z.string().describe('The search query string'),\n topK: z.number().optional().default(5).describe('Maximum number of results to return'),\n mode: z\n .enum(['bm25', 'vector', 'hybrid'])\n .optional()\n .describe('Search mode: bm25 for keyword search, vector for semantic search, hybrid for both combined'),\n minScore: z.number().optional().describe('Minimum score threshold (0-1 for normalized scores)'),\n});\n\nexport const searchTool = createTool({\n id: WORKSPACE_TOOLS.SEARCH.SEARCH,\n description:\n 'Search indexed content in the workspace. Supports keyword (BM25), semantic (vector), and hybrid search modes.',\n outputSchema: z.string(),\n inputSchema: searchInputSchema,\n execute: async ({ query, topK, mode, minScore }, context) => {\n const workspace = requireWorkspace(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.SEARCH.SEARCH);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'search',\n operation: 'search',\n input: { query, topK, mode, minScore },\n attributes: {},\n });\n\n try {\n // Resolve effective mode before searching — fall back gracefully if requested\n // mode isn't supported (e.g. 'hybrid' requested but only BM25 configured)\n const effectiveMode =\n mode === 'hybrid' && !workspace.canHybrid\n ? workspace.canVector\n ? 'vector'\n : 'bm25'\n : mode === 'vector' && !workspace.canVector\n ? 'bm25'\n : (mode ?? (workspace.canHybrid ? 'hybrid' : workspace.canVector ? 'vector' : 'bm25'));\n\n const results = await workspace.search(query, {\n topK,\n mode: effectiveMode as 'bm25' | 'vector' | 'hybrid' | undefined,\n minScore,\n });\n\n const lines = results.map(r => {\n const lineInfo = r.lineRange ? `:${r.lineRange.start}-${r.lineRange.end}` : '';\n return `${r.id}${lineInfo}: ${r.content}`;\n });\n\n lines.push('---');\n lines.push(`${results.length} result${results.length !== 1 ? 's' : ''} (${effectiveMode} search)`);\n\n span.end({ success: true }, { resultCount: results.length });\n return lines.join('\\n');\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","import nodePath from 'node:path';\nimport { z } from 'zod/v4';\nimport { createTool } from '../../tools';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { WorkspaceReadOnlyError } from '../errors';\nimport { emitWorkspaceMetadata, getEditDiagnosticsText, requireFilesystem } from './helpers';\nimport { startWorkspaceSpan } from './tracing';\n\nexport const writeFileTool = createTool({\n id: WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,\n description: 'Write content to a file in the workspace filesystem. Creates parent directories if needed.',\n outputSchema: z.string(),\n inputSchema: z.object({\n path: z.string().describe('The path where to write the file (e.g., \"data/output.txt\")'),\n content: z.string().describe('The content to write to the file'),\n overwrite: z.boolean().optional().default(true).describe('Whether to overwrite the file if it already exists'),\n }),\n execute: async ({ path, content, overwrite }, context) => {\n const { workspace, filesystem } = requireFilesystem(context);\n await emitWorkspaceMetadata(context, WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE);\n\n const span = startWorkspaceSpan(context, workspace, {\n category: 'filesystem',\n operation: 'writeFile',\n input: { path, overwrite, contentLength: content.length },\n attributes: { filesystemProvider: filesystem.provider },\n });\n\n try {\n if (filesystem.readOnly) {\n throw new WorkspaceReadOnlyError('write_file');\n }\n\n await filesystem.writeFile(path, content, {\n overwrite,\n expectedMtime: (context as any)?.__expectedMtime,\n });\n\n const size = Buffer.byteLength(content, 'utf-8');\n let output = `Wrote ${size} bytes to ${path}`;\n // An absolute path can be mapped somewhere else (e.g. `/tmp/x` into\n // `<workspace>/tmp/x`). Name the real location so later commands find it.\n // Compare without normalizing: a shell can't follow `missing/../x` when\n // `missing` doesn't exist, so that path still needs the resolved form.\n const resolvedPath = nodePath.isAbsolute(path) ? filesystem.resolveAbsolutePath?.(path) : undefined;\n if (resolvedPath && resolvedPath !== path) {\n output += ` (resolved to ${resolvedPath})`;\n }\n output += await getEditDiagnosticsText(workspace, path, content);\n span.end({ success: true }, { bytesTransferred: size });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n});\n","/**\n * Workspace Tools — Factory\n *\n * Creates the built-in workspace tools for agents. Individual tools are\n * defined in their own files; this module applies WorkspaceToolsConfig\n * (enabled, requireApproval, requireReadBeforeWrite) and injects workspace\n * into the tool execution context.\n */\n\nimport { posix as posixPath } from 'node:path';\nimport { z } from 'zod/v4';\nimport type { ToolBackgroundConfig } from '../../background-tasks/types';\nimport { RequestContext } from '../../request-context';\nimport type { WorkspaceToolName } from '../constants';\nimport { WORKSPACE_TOOLS } from '../constants';\nimport { FileNotFoundError, FileReadRequiredError } from '../errors';\nimport { deriveReadScope, InMemoryFileReadTracker, InMemoryFileWriteLock } from '../filesystem';\nimport type { FileReadTracker, FileWriteLock, WorkspaceFilesystem } from '../filesystem';\nimport type { WorkspaceSandbox } from '../sandbox';\nimport { supportsComputer } from '../sandbox';\nimport type { Workspace } from '../workspace';\nimport { applyPatchDidWrite, applyPatchTool, getApplyPatchWritePaths } from './apply-patch';\nimport { isAstGrepAvailable, astEditTool } from './ast-edit';\nimport { computerClickTool } from './computer-click';\nimport { computerDoubleClickTool } from './computer-double-click';\nimport { computerDragTool } from './computer-drag';\nimport { computerGetScreenInfoTool } from './computer-get-screen-info';\nimport { computerMoveMouseTool } from './computer-move-mouse';\nimport { computerPressKeyTool } from './computer-press-key';\nimport { computerRightClickTool } from './computer-right-click';\nimport { computerScreenshotTool } from './computer-screenshot';\nimport { computerScrollTool } from './computer-scroll';\nimport { computerTypeTool } from './computer-type';\nimport { computerWaitTool } from './computer-wait';\nimport { deleteFileTool } from './delete-file';\nimport { editFileTool } from './edit-file';\nimport {\n executeCommandTool,\n executeCommandWithBackgroundTool,\n executeCommandWithDescriptionAndBackgroundTool,\n executeCommandWithDescriptionTool,\n} from './execute-command';\nimport { fileStatTool } from './file-stat';\nimport { getProcessOutputTool } from './get-process-output';\nimport { createGrepTool } from './grep';\nimport type { GrepToolOptions } from './grep';\nimport { indexContentTool } from './index-content';\nimport { killProcessTool } from './kill-process';\nimport { listFilesTool } from './list-files';\nimport { lspInspectTool } from './lsp-inspect';\nimport { mkdirTool } from './mkdir';\nimport { readFileTool } from './read-file';\nimport { searchInputSchema, searchTool } from './search';\nimport type {\n WorkspaceToolsConfig,\n DynamicToolConfigValue,\n ToolConfigContext,\n ToolConfigWithArgsContext,\n WorkspaceToolHooks,\n} from './types';\nexport type {\n WorkspaceToolConfig,\n WorkspaceToolsConfig,\n ExecuteCommandToolConfig,\n BackgroundProcessConfig,\n BackgroundProcessMeta,\n BackgroundProcessExitMeta,\n ToolConfigContext,\n ToolConfigWithArgsContext,\n DynamicToolConfigValue,\n WorkspaceToolHookContext,\n WorkspaceToolBeforeHookResult,\n WorkspaceToolAfterHookContext,\n WorkspaceToolHooks,\n} from './types';\nimport { writeFileTool } from './write-file';\n\n/**\n * Resolve a DynamicToolConfigValue to a boolean.\n * If it's a function, calls it with the provided context.\n * On error, returns the safeDefault.\n */\nasync function resolveDynamicValue<TContext>(\n value: DynamicToolConfigValue<TContext> | undefined,\n context: TContext | undefined,\n safeDefault: boolean,\n): Promise<boolean> {\n if (value === undefined) return safeDefault;\n if (typeof value === 'boolean') return value;\n if (!context) return safeDefault;\n try {\n return await value(context);\n } catch (error) {\n console.warn('[Workspace Tools] Dynamic config function threw, using safe default:', error);\n return safeDefault;\n }\n}\n\nfunction hasFilesystemConfig(workspace: Workspace): boolean {\n if (typeof (workspace as any)?.hasFilesystemConfig === 'function') {\n return (workspace as any).hasFilesystemConfig();\n }\n return !!workspace.filesystem;\n}\n\nfunction hasSandboxConfig(workspace: Workspace): boolean {\n if (typeof (workspace as any)?.hasSandboxConfig === 'function') {\n return (workspace as any).hasSandboxConfig();\n }\n return !!workspace.sandbox;\n}\n\n/**\n * Normalize a requestContext value to a plain Record.\n * Callers may pass a Map-like RequestContext (with `.entries()`) or a plain\n * object. Dynamic config functions always receive a plain object so that\n * bracket-notation access (`requestContext['key']`) works consistently.\n */\nfunction toPlainRequestContext(requestContext: unknown): Record<string, unknown> {\n if (!requestContext) return {};\n if (typeof (requestContext as any).entries === 'function') {\n return Object.fromEntries((requestContext as any).entries());\n }\n return requestContext as Record<string, unknown>;\n}\n\n/** Resolved tool config with `enabled` as a boolean and execution-time values as raw config. */\nexport interface ResolvedToolConfig {\n enabled: boolean;\n requireApproval: DynamicToolConfigValue<ToolConfigWithArgsContext>;\n background?: ToolBackgroundConfig;\n requireReadBeforeWrite?: DynamicToolConfigValue<ToolConfigWithArgsContext>;\n maxOutputTokens?: number;\n name?: string;\n hooks?: WorkspaceToolHooks;\n}\n\n/**\n * Resolves the effective configuration for a specific tool.\n *\n * Resolution order (later overrides earlier):\n * 1. Built-in defaults (enabled: true, requireApproval: false)\n * 2. Top-level config (tools.enabled, tools.requireApproval)\n * 3. Per-tool config (tools[toolName].enabled, tools[toolName].requireApproval)\n *\n * `enabled` is resolved to a boolean immediately (requires context if dynamic).\n * `requireApproval` and `requireReadBeforeWrite` are passed through as-is\n * for execution-time evaluation (they may need args).\n */\nexport async function resolveToolConfig(\n toolsConfig: WorkspaceToolsConfig | undefined,\n toolName: WorkspaceToolName,\n context?: ToolConfigContext,\n): Promise<ResolvedToolConfig> {\n let enabled: DynamicToolConfigValue = true;\n let requireApproval: DynamicToolConfigValue<ToolConfigWithArgsContext> = false;\n let background: ToolBackgroundConfig | undefined;\n let requireReadBeforeWrite: DynamicToolConfigValue<ToolConfigWithArgsContext> | undefined;\n let maxOutputTokens: number | undefined;\n let name: string | undefined;\n const hooks = toolsConfig?.hooks;\n\n if (toolsConfig) {\n if (toolsConfig.enabled !== undefined) {\n enabled = toolsConfig.enabled;\n }\n if (toolsConfig.requireApproval !== undefined) {\n requireApproval = toolsConfig.requireApproval;\n }\n\n const perToolConfig = toolsConfig[toolName];\n if (perToolConfig) {\n if (perToolConfig.enabled !== undefined) {\n enabled = perToolConfig.enabled;\n }\n if (perToolConfig.requireApproval !== undefined) {\n requireApproval = perToolConfig.requireApproval;\n }\n if (perToolConfig.background !== undefined) {\n background = perToolConfig.background;\n }\n if (perToolConfig.requireReadBeforeWrite !== undefined) {\n requireReadBeforeWrite = perToolConfig.requireReadBeforeWrite;\n }\n if (perToolConfig.maxOutputTokens !== undefined) {\n maxOutputTokens = perToolConfig.maxOutputTokens;\n }\n if (perToolConfig.name !== undefined) {\n name = perToolConfig.name;\n }\n }\n }\n\n // Resolve `enabled` now (tool-listing time) — safe default: false (fail-closed)\n const resolvedEnabled = await resolveDynamicValue(enabled, context, false);\n\n return {\n enabled: resolvedEnabled,\n requireApproval,\n background,\n requireReadBeforeWrite,\n maxOutputTokens,\n name,\n hooks,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Wrapper helpers\n// ---------------------------------------------------------------------------\n\ntype ResolveTargets = { filesystem?: boolean; sandbox?: boolean };\n\n/**\n * Resolve the effective workspace for tool execution. When a dynamic resolver\n * is configured for a requested provider (no static instance), resolves it from\n * requestContext and returns a proxy workspace that exposes the resolved value.\n * Returns the workspace unchanged when no resolution is needed, so tools that\n * don't touch a given provider don't pay the cost of calling its resolver.\n */\nasync function resolveEffectiveWorkspace(\n workspace: Workspace,\n context: any,\n targets: ResolveTargets,\n): Promise<Workspace> {\n workspace.lastAccessedAt = new Date();\n\n const needsFilesystem = !!(targets.filesystem && !workspace.filesystem && hasFilesystemConfig(workspace));\n const needsSandbox = !!(targets.sandbox && !workspace.sandbox && hasSandboxConfig(workspace));\n if (!needsFilesystem && !needsSandbox) return workspace;\n\n const requestContext: RequestContext = context?.requestContext ?? new RequestContext();\n const overrides: { filesystem?: WorkspaceFilesystem; sandbox?: WorkspaceSandbox } = {};\n\n if (needsFilesystem) {\n const resolvedFs = await workspace.resolveFilesystem({ requestContext });\n if (resolvedFs) overrides.filesystem = resolvedFs;\n }\n\n if (needsSandbox) {\n const resolvedSandbox = await workspace.resolveSandbox({ requestContext });\n if (resolvedSandbox) overrides.sandbox = resolvedSandbox;\n }\n\n if (!overrides.filesystem && !overrides.sandbox) return workspace;\n\n return new Proxy(workspace, {\n get(target: any, prop: string | symbol) {\n if (prop === 'filesystem' && overrides.filesystem) return overrides.filesystem;\n if (prop === 'sandbox' && overrides.sandbox) return overrides.sandbox;\n return target[prop];\n },\n });\n}\n\n/**\n * Clone a standalone tool with config overrides and inject workspace into context.\n * `targets` declares which providers the tool needs resolved per request.\n */\nfunction wrapTool(tool: any, workspace: Workspace, targets: ResolveTargets): any {\n return {\n ...tool,\n execute: async (input: any, context: any = {}) => {\n const effectiveWorkspace = await resolveEffectiveWorkspace(context?.workspace ?? workspace, context, targets);\n const enrichedContext = { ...context, workspace: effectiveWorkspace };\n return tool.execute(input, enrichedContext);\n },\n };\n}\n\n/**\n * Wrap a tool with read-before-write tracking (readTracker).\n *\n * - mode 'read': records the read after execution\n * - mode 'write': checks before execution, clears after\n */\nfunction wrapWithReadTracker(\n tool: any,\n workspace: Workspace,\n readTracker: FileReadTracker,\n config: { requireReadBeforeWrite?: DynamicToolConfigValue<ToolConfigWithArgsContext> },\n mode: 'read' | 'write',\n getWritePaths?: (input: any) => string[],\n didWrite?: (result: unknown) => boolean,\n): any {\n return {\n ...tool,\n execute: async (input: any, context: any = {}) => {\n const effectiveWorkspace = await resolveEffectiveWorkspace(context?.workspace ?? workspace, context, {\n filesystem: true,\n });\n let enrichedContext: any = { ...context, workspace: effectiveWorkspace };\n const fs: WorkspaceFilesystem | undefined = effectiveWorkspace.filesystem;\n // Filesystem resolution is dynamic (per request context), so the scope\n // must be derived here from the resolved filesystem — read records only\n // count for the filesystem they were read from.\n const scope = fs ? deriveReadScope(fs) : undefined;\n\n // Pre-execution: enforce read-before-write policy and/or attach\n // optimistic-concurrency mtime for write tools.\n const writePaths: string[] = getWritePaths ? getWritePaths(input) : [input.path];\n if (mode === 'write' && fs) {\n // Both the read-first gate and the optimistic-concurrency mtime check\n // follow requireReadBeforeWrite: unset or false skips them. A dynamic\n // function that throws resolves to true (fail-closed).\n const shouldRequireRead =\n config.requireReadBeforeWrite !== undefined &&\n (await resolveDynamicValue(\n config.requireReadBeforeWrite,\n { args: input, requestContext: enrichedContext.requestContext ?? {}, workspace: effectiveWorkspace },\n true,\n ));\n const expectedMtimes: Record<string, Date> = {};\n for (const path of shouldRequireRead ? writePaths : []) {\n // Optimistic concurrency: attach the mtime from the last read\n // *before* stat so it's preserved even when the file has been\n // deleted externally (stat throws FileNotFoundError). Records from a\n // different filesystem scope must not leak their mtime here.\n const record = await readTracker.getReadRecord(path);\n if (record && record.scope === scope) {\n expectedMtimes[path] = record.modifiedAtRead;\n }\n\n try {\n const stat = await fs.stat(path);\n\n // Policy gate: require the agent to have read the file first.\n const check = await readTracker.needsReRead(path, stat.modifiedAt, scope);\n if (check.needsReRead) {\n throw new FileReadRequiredError(path, check.reason!);\n }\n } catch (error) {\n if (!(error instanceof FileNotFoundError)) {\n throw error;\n }\n // Missing file: if a read record exists the expectedMtime is\n // already attached, so downstream writeFile can treat this as\n // stale. Otherwise it's a genuinely new file.\n }\n }\n\n if (getWritePaths) {\n enrichedContext = { ...enrichedContext, __expectedMtimes: expectedMtimes };\n } else if (expectedMtimes[input.path]) {\n enrichedContext = { ...enrichedContext, __expectedMtime: expectedMtimes[input.path] };\n }\n }\n\n const result = await tool.execute(input, enrichedContext);\n\n // Post-execution: track reads / clear write records\n if (mode === 'read' && fs) {\n try {\n const stat = await fs.stat(input.path);\n await readTracker.recordRead(input.path, stat.modifiedAt, scope);\n } catch {\n // Ignore stat errors for tracking\n }\n } else if (mode === 'write' && (didWrite?.(result) ?? true)) {\n for (const path of writePaths) {\n await readTracker.clearReadRecord(path);\n }\n }\n\n return result;\n },\n };\n}\n\n/**\n * Wrap a tool with a per-file write lock.\n *\n * The lock serializes the entire execute pipeline (including any\n * read-before-write checks) so concurrent calls to the same path\n * run one at a time.\n */\nfunction wrapWithToolHooks(\n tool: any,\n hooks: WorkspaceToolHooks,\n toolName: string,\n workspaceToolName: WorkspaceToolName,\n): any {\n return {\n ...tool,\n execute: async (input: any, context: any = {}) => {\n const hookContext = { toolName, workspaceToolName, input, context };\n const beforeResult = await hooks.beforeToolCall?.(hookContext);\n if (beforeResult?.proceed === false) {\n return beforeResult.output;\n }\n\n let output: unknown;\n try {\n output = await tool.execute(input, context);\n } catch (error) {\n await hooks.afterToolCall?.({ ...hookContext, output, error });\n throw error;\n }\n\n await hooks.afterToolCall?.({ ...hookContext, output });\n return output;\n },\n };\n}\n\nfunction wrapWithWriteLock(tool: any, writeLock: FileWriteLock, getWritePaths?: (input: any) => string[]): any {\n return {\n ...tool,\n execute: async (input: any, context: any = {}) => {\n if (getWritePaths) {\n // Take one lock per path in a stable order so two multi-file calls\n // can't each hold a lock the other is waiting for.\n const keys = [...new Set(getWritePaths(input).map(p => posixPath.normalize(p.replace(/\\\\/g, '/'))))].sort();\n const run = (i: number): Promise<any> =>\n i === keys.length ? tool.execute(input, context) : writeLock.withLock(keys[i]!, () => run(i + 1));\n return run(0);\n }\n if (!input.path) {\n throw new Error('wrapWithWriteLock: input.path is required');\n }\n return writeLock.withLock(input.path, () => tool.execute(input, context));\n },\n };\n}\n\nconst ALL_WORKSPACE_TOOL_NAMES = Object.values(WORKSPACE_TOOLS).flatMap(group =>\n Object.values(group),\n) as WorkspaceToolName[];\n\n/**\n * True when every workspace tool is disabled by static configuration, so no\n * tool config needs resolving. Dynamic `enabled` functions and per-tool\n * `enabled` overrides are never short-circuited.\n */\nfunction isStaticallyDisabled(toolsConfig: WorkspaceToolsConfig | undefined): boolean {\n if (toolsConfig?.enabled !== false) return false;\n return ALL_WORKSPACE_TOOL_NAMES.every(name => toolsConfig[name]?.enabled === undefined);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates workspace tools that will be auto-injected into agents.\n *\n * @param workspace - The workspace instance to bind tools to\n * @param configContext - Optional tool config context\n * @param options - Optional tool construction options (e.g. grep strict mode)\n * @returns Record of workspace tools\n */\nexport async function createWorkspaceTools(\n workspace: Workspace,\n configContext?: Omit<ToolConfigContext, 'requestContext'> & {\n requestContext?: unknown;\n readTracker?: FileReadTracker;\n },\n options?: { grep?: GrepToolOptions },\n) {\n // Seed fallback context so dynamic enabled functions always get called,\n // even if the caller omits configContext. Normalize requestContext so\n // user-provided functions always receive a plain Record, not a Map.\n // readTracker is factory-internal (read-before-write tracking) and is not\n // exposed to user dynamic-config functions.\n let effectiveConfigContext: ToolConfigContext;\n let contextReadTracker: FileReadTracker | undefined;\n if (configContext) {\n const { readTracker: providedReadTracker, ...rest } = configContext;\n contextReadTracker = providedReadTracker;\n effectiveConfigContext = { ...rest, requestContext: toPlainRequestContext(configContext.requestContext) };\n } else {\n effectiveConfigContext = { requestContext: {}, workspace };\n }\n const tools: Record<string, any> = {};\n const toolsConfig = workspace.getToolsConfig();\n if (isStaticallyDisabled(toolsConfig)) return tools;\n const isReadOnly = workspace.filesystem?.readOnly ?? false;\n\n // Shared write lock — serializes concurrent writes to the same file path.\n // `timeoutMs: undefined` falls back to the lock's own default (30s).\n // Created on first use so disabled tools don't allocate it.\n let writeLock: FileWriteLock | undefined;\n const getWriteLock = () =>\n (writeLock ??= new InMemoryFileWriteLock({\n timeoutMs: toolsConfig?.writeLockTimeoutMs,\n }));\n\n // Shared read tracker — records reads so the requireReadBeforeWrite policy\n // (read-first gate and mtime checking) can be enforced. The agent provides a thread-scoped, storage-backed\n // tracker when it has thread identity and Mastra storage (records survive\n // suspend/resume, later turns, and process restarts); otherwise tracking\n // is per-run.\n // Created on first use, then shared by every tool from this call.\n let readTracker: FileReadTracker | undefined = contextReadTracker;\n const getReadTracker = () => (readTracker ??= new InMemoryFileReadTracker());\n\n // Helper: add a tool with config-driven filtering. `createTool` is only\n // invoked once the tool is known to be enabled, so disabled tools cost\n // nothing to prepare.\n const addTool = async (\n name: WorkspaceToolName,\n createTool: () => any,\n opts?: {\n requireWrite?: boolean;\n readTrackerMode?: 'read' | 'write';\n useWriteLock?: boolean;\n targets?: ResolveTargets;\n isAvailable?: () => boolean;\n /** Only register when the tool's own `enabled` is set; top-level `enabled` doesn't turn it on. */\n optIn?: boolean;\n /** Every path the call writes, for tools that touch more than `input.path`. */\n getWritePaths?: (input: any) => string[];\n /** Whether a successful result actually changed files; read records are kept when it didn't. */\n didWrite?: (result: unknown) => boolean;\n },\n ) => {\n if (opts?.optIn && toolsConfig?.[name]?.enabled === undefined) return;\n const config = await resolveToolConfig(toolsConfig, name, effectiveConfigContext);\n if (!config.enabled) return;\n if (opts?.requireWrite && isReadOnly) return;\n if (opts?.isAvailable && !opts.isAvailable()) return;\n const tool = createTool();\n\n // Handle dynamic requireApproval: if it's a function, store as needsApprovalFn\n // and set requireApproval to true so the execution pipeline knows to check\n let wrapped: any;\n if (typeof config.requireApproval === 'function') {\n const approvalFn = config.requireApproval;\n wrapped = {\n ...tool,\n requireApproval: true,\n needsApprovalFn: async (\n args: Record<string, unknown>,\n ctx?: {\n requestContext?: Record<string, unknown> | { entries(): Iterable<[string, unknown]> };\n workspace?: object;\n },\n ) =>\n resolveDynamicValue(\n approvalFn,\n {\n args,\n requestContext: toPlainRequestContext(ctx?.requestContext),\n workspace: ctx?.workspace ?? workspace,\n },\n true,\n ),\n };\n } else {\n wrapped = { ...tool, requireApproval: config.requireApproval };\n }\n\n if (config.background) {\n wrapped = { ...wrapped, background: config.background };\n }\n\n if (opts?.readTrackerMode) {\n wrapped = wrapWithReadTracker(\n wrapped,\n workspace,\n getReadTracker(),\n config,\n opts.readTrackerMode,\n opts.getWritePaths,\n opts.didWrite,\n );\n } else {\n wrapped = wrapTool(wrapped, workspace, opts?.targets ?? {});\n }\n\n // Use custom name if provided, otherwise use the default constant name\n const exposedName = config.name ?? name;\n if (tools[exposedName]) {\n throw new Error(\n `Duplicate workspace tool name \"${exposedName}\": tool \"${name}\" conflicts with an already-registered tool. ` +\n `Check your tools config for duplicate \"name\" values.`,\n );\n }\n // When the tool is renamed, update its id to match so fallback-by-id\n // resolution (in tool-call-step, llm-execution-step, etc.) won't allow\n // the model to call the tool using the old default name.\n if (exposedName !== name && 'id' in wrapped) {\n wrapped = { ...wrapped, id: exposedName };\n }\n\n if (config.hooks) {\n wrapped = wrapWithToolHooks(wrapped, config.hooks, exposedName, name);\n }\n\n // Write lock is outermost — serializes the entire enriched execute pipeline\n if (opts?.useWriteLock) {\n wrapped = wrapWithWriteLock(wrapped, getWriteLock(), opts.getWritePaths);\n }\n\n tools[exposedName] = wrapped;\n };\n\n // Filesystem tools — add when filesystem is available (static instance or resolver function)\n if (hasFilesystemConfig(workspace)) {\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE, () => readFileTool, { readTrackerMode: 'read' });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE, () => writeFileTool, {\n requireWrite: true,\n readTrackerMode: 'write',\n useWriteLock: true,\n });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE, () => editFileTool, {\n requireWrite: true,\n readTrackerMode: 'write',\n useWriteLock: true,\n });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES, () => listFilesTool, { targets: { filesystem: true } });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.DELETE, () => deleteFileTool, {\n requireWrite: true,\n useWriteLock: true,\n targets: { filesystem: true },\n });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT, () => fileStatTool, { targets: { filesystem: true } });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.MKDIR, () => mkdirTool, {\n requireWrite: true,\n targets: { filesystem: true },\n });\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.GREP, () => createGrepTool(options?.grep), {\n targets: { filesystem: true },\n });\n\n // AST edit tool (only if @ast-grep/napi is available at runtime)\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT, () => astEditTool, {\n requireWrite: true,\n readTrackerMode: 'write',\n useWriteLock: true,\n isAvailable: isAstGrepAvailable,\n });\n\n // Multi-file patch tool — opt-in only, so existing agents keep write_file/edit_file\n await addTool(WORKSPACE_TOOLS.FILESYSTEM.APPLY_PATCH, () => applyPatchTool, {\n requireWrite: true,\n readTrackerMode: 'write',\n useWriteLock: true,\n optIn: true,\n getWritePaths: getApplyPatchWritePaths,\n didWrite: applyPatchDidWrite,\n });\n }\n\n // Search tools\n if (workspace.canBM25 || workspace.canVector) {\n // Build a dynamic search tool that only exposes modes the workspace supports.\n // This prevents the LLM from picking an unsupported mode (e.g. 'hybrid' when\n // only BM25 is configured), rather than relying solely on runtime fallback.\n await addTool(WORKSPACE_TOOLS.SEARCH.SEARCH, () => {\n const availableModes = [\n workspace.canBM25 ? 'bm25' : null,\n workspace.canVector ? 'vector' : null,\n workspace.canHybrid ? 'hybrid' : null,\n ].filter((m): m is 'bm25' | 'vector' | 'hybrid' => m !== null);\n\n return {\n ...searchTool,\n inputSchema: searchInputSchema.extend({\n mode: z\n .enum(availableModes as [(typeof availableModes)[number], ...(typeof availableModes)[number][]])\n .optional()\n .describe(`Search mode: ${availableModes.join(', ')}`),\n }),\n };\n });\n await addTool(WORKSPACE_TOOLS.SEARCH.INDEX, () => indexContentTool, { requireWrite: true });\n }\n\n const requireCommandDescription = toolsConfig?.[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]?.requireDescription === true;\n const backgroundExecuteCommandTool = requireCommandDescription\n ? executeCommandWithDescriptionAndBackgroundTool\n : executeCommandWithBackgroundTool;\n\n if (workspace.sandbox) {\n if (workspace.sandbox.executeCommand) {\n // Pick the right tool variant based on whether processes are available\n const foregroundExecuteCommandTool = requireCommandDescription\n ? executeCommandWithDescriptionTool\n : executeCommandTool;\n const baseTool = workspace.sandbox.processes ? backgroundExecuteCommandTool : foregroundExecuteCommandTool;\n await addTool(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND, () => baseTool, { targets: { sandbox: true } });\n }\n\n // Background process tools (only when process manager is available)\n if (workspace.sandbox.processes) {\n await addTool(WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT, () => getProcessOutputTool, {\n targets: { sandbox: true },\n });\n await addTool(WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS, () => killProcessTool, { targets: { sandbox: true } });\n }\n\n // Computer (desktop) tools — only when the sandbox supports the computer\n // capability. Not offered for dynamic sandbox resolvers (no static\n // instance) since the capability can't be detected at tool-listing time.\n if (supportsComputer(workspace.sandbox)) {\n await addTool(WORKSPACE_TOOLS.COMPUTER.SCREENSHOT, () => computerScreenshotTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.CLICK, () => computerClickTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.DOUBLE_CLICK, () => computerDoubleClickTool, {\n targets: { sandbox: true },\n });\n await addTool(WORKSPACE_TOOLS.COMPUTER.RIGHT_CLICK, () => computerRightClickTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.MOVE_MOUSE, () => computerMoveMouseTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.DRAG, () => computerDragTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.TYPE, () => computerTypeTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.PRESS_KEY, () => computerPressKeyTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.SCROLL, () => computerScrollTool, { targets: { sandbox: true } });\n await addTool(WORKSPACE_TOOLS.COMPUTER.GET_SCREEN_INFO, () => computerGetScreenInfoTool, {\n targets: { sandbox: true },\n });\n await addTool(WORKSPACE_TOOLS.COMPUTER.WAIT, () => computerWaitTool, { targets: { sandbox: true } });\n }\n } else if (hasSandboxConfig(workspace)) {\n await addTool(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND, () => backgroundExecuteCommandTool, {\n targets: { sandbox: true },\n });\n await addTool(WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT, () => getProcessOutputTool, {\n targets: { sandbox: true },\n });\n await addTool(WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS, () => killProcessTool, { targets: { sandbox: true } });\n }\n\n // LSP tools — only when LSP is configured and initialized on this workspace.\n // Needs the filesystem resolved so lsp_inspect can map paths via the\n // request's filesystem (resolveAbsolutePath) on dynamic-filesystem workspaces.\n if (workspace.lsp) {\n await addTool(WORKSPACE_TOOLS.LSP.LSP_INSPECT, () => lspInspectTool, { targets: { filesystem: true } });\n }\n\n return tools;\n}\n","/**\n * Language Detection\n *\n * Maps file extensions to LSP language identifiers.\n * Browser-safe — no Node.js dependencies.\n */\n\n/**\n * Maps file extensions (including the dot) to LSP language identifiers.\n */\nexport const LANGUAGE_EXTENSIONS: Record<string, string> = {\n // TypeScript/JavaScript\n '.ts': 'typescript',\n '.tsx': 'typescriptreact',\n '.js': 'javascript',\n '.jsx': 'javascriptreact',\n '.mjs': 'javascript',\n '.cjs': 'javascript',\n\n // Python\n '.py': 'python',\n '.pyi': 'python',\n\n // Go\n '.go': 'go',\n\n // Rust\n '.rs': 'rust',\n\n // C/C++\n '.c': 'c',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.h': 'c',\n '.hpp': 'cpp',\n\n // Java\n '.java': 'java',\n\n // JSON\n '.json': 'json',\n '.jsonc': 'jsonc',\n\n // YAML\n '.yaml': 'yaml',\n '.yml': 'yaml',\n\n // Markdown\n '.md': 'markdown',\n\n // HTML/CSS\n '.html': 'html',\n '.css': 'css',\n '.scss': 'scss',\n '.sass': 'sass',\n '.less': 'less',\n};\n\n/**\n * Get the LSP language ID for a file path based on its extension.\n * Returns undefined if the extension is not recognized.\n *\n * When `customExtensions` is provided, it is checked first, allowing\n * custom servers to register new file extensions or override built-in mappings.\n */\nexport function getLanguageId(filePath: string, customExtensions?: Record<string, string>): string | undefined {\n const dotIndex = filePath.lastIndexOf('.');\n if (dotIndex === -1) return undefined;\n const ext = filePath.substring(dotIndex);\n return customExtensions?.[ext] ?? LANGUAGE_EXTENSIONS[ext];\n}\n","/**\n * LSP Client\n *\n * JSON-RPC client wrapper for communicating with language servers.\n * Uses dynamic imports for vscode-jsonrpc and vscode-languageserver-protocol\n * to keep them as optional dependencies.\n *\n * Spawns LSP servers via a SandboxProcessManager, so it works with any\n * sandbox backend (local, E2B, etc.) that has a process manager.\n */\n\nimport { createRequire } from 'node:module';\nimport { pathToFileURL, fileURLToPath } from 'node:url';\n\nimport type { ProcessHandle, SandboxProcessManager } from '../sandbox/process-manager';\nimport type { LSPServerDef } from './types';\n\n// =============================================================================\n// Dynamic Import\n// =============================================================================\n\n/** Cached module references — undefined means not yet checked, null means unavailable */\nlet jsonrpcModule:\n | {\n StreamMessageReader: any;\n StreamMessageWriter: any;\n createMessageConnection: any;\n }\n | null\n | undefined;\nlet lspProtocolModule:\n | {\n TextDocumentIdentifier: any;\n Position: any;\n }\n | null\n | undefined;\n\n/**\n * Check if vscode-jsonrpc is available without importing it.\n * Synchronous check — safe to call at registration time.\n */\nexport function isLSPAvailable(): boolean {\n if (jsonrpcModule !== undefined) {\n return jsonrpcModule !== null;\n }\n\n try {\n const req = createRequire(import.meta.url);\n req.resolve('vscode-jsonrpc/node');\n req.resolve('vscode-languageserver-protocol');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Load vscode-jsonrpc and vscode-languageserver-protocol.\n * Returns null if not available. Caches result after first call.\n */\nexport async function loadLSPDeps(): Promise<{\n StreamMessageReader: any;\n StreamMessageWriter: any;\n createMessageConnection: any;\n TextDocumentIdentifier: any;\n Position: any;\n} | null> {\n if (jsonrpcModule !== undefined && lspProtocolModule !== undefined) {\n if (jsonrpcModule === null || lspProtocolModule === null) return null;\n return { ...jsonrpcModule, ...lspProtocolModule };\n }\n\n try {\n const req = createRequire(import.meta.url);\n const jsonrpc = req('vscode-jsonrpc/node');\n const protocol = req('vscode-languageserver-protocol');\n jsonrpcModule = {\n StreamMessageReader: jsonrpc.StreamMessageReader,\n StreamMessageWriter: jsonrpc.StreamMessageWriter,\n createMessageConnection: jsonrpc.createMessageConnection,\n };\n lspProtocolModule = {\n TextDocumentIdentifier: protocol.TextDocumentIdentifier,\n Position: protocol.Position,\n };\n return { ...jsonrpcModule, ...lspProtocolModule };\n } catch {\n jsonrpcModule = null;\n lspProtocolModule = null;\n return null;\n }\n}\n\n// =============================================================================\n// URI Helpers\n// =============================================================================\n\n/** Convert a filesystem path to a properly encoded file:// URI. */\nfunction toFileUri(fsPath: string): string {\n return pathToFileURL(fsPath).toString();\n}\n\n/**\n * Normalize a file:// URI to a canonical fs-path-based key for diagnostics\n * map storage/lookup. On Windows, different LSP servers emit different\n * canonical forms for the same path (e.g. `file:///C:/...` vs\n * `file:///c%3A/...`), so we convert back to an OS path and compare those\n * instead of comparing URI strings directly.\n */\nexport function diagnosticsKey(uriOrPath: string): string {\n let fsPath: string;\n try {\n fsPath = uriOrPath.startsWith('file:') ? fileURLToPath(uriOrPath) : uriOrPath;\n } catch {\n return uriOrPath;\n }\n // Normalize Windows drive-letter paths so they compare equal regardless of\n // drive-letter casing or whether fileURLToPath produced a leading slash\n // (e.g. '/C:/Users/...' vs 'C:/Users/...' vs 'c:\\\\Users\\\\...'), independent\n // of the OS this code happens to run on.\n const driveMatch = fsPath.match(/^[\\\\/]?([a-zA-Z]):([\\\\/].*)$/);\n if (driveMatch) {\n return `${driveMatch[1]!.toLowerCase()}:${driveMatch[2]}`;\n }\n return fsPath;\n}\n\n// =============================================================================\n// Timeout Helper\n// =============================================================================\n\nasync function withTimeout<T>(promise: Promise<T>, ms: number, errorMessage: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout>;\n return Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n timer = setTimeout(() => reject(new Error(errorMessage)), ms);\n }),\n ]).finally(() => clearTimeout(timer!));\n}\n\n// =============================================================================\n// LSP Client\n// =============================================================================\n\n/**\n * Wraps a JSON-RPC connection to a single LSP server process.\n * Uses a SandboxProcessManager to spawn the server process.\n */\nexport class LSPClient {\n private connection: any = null;\n private handle: ProcessHandle | null = null;\n private serverDef: LSPServerDef;\n private workspaceRoot: string;\n private processManager: SandboxProcessManager;\n private diagnostics: Map<string, any[]> = new Map();\n private initializationOptions: Record<string, unknown> | null = null;\n private supportsPullDiagnostics: boolean = false;\n\n constructor(serverDef: LSPServerDef, workspaceRoot: string, processManager: SandboxProcessManager) {\n this.serverDef = serverDef;\n this.workspaceRoot = workspaceRoot;\n this.processManager = processManager;\n }\n\n /** Whether the underlying server process is still running. */\n get isAlive(): boolean {\n return this.handle !== null && this.handle.exitCode === undefined;\n }\n\n /** Name of the LSP server. */\n get serverName(): string {\n return this.serverDef.name;\n }\n\n /**\n * Initialize the LSP connection — spawns the server and performs the handshake.\n */\n async initialize(initTimeout: number = 10000): Promise<void> {\n const deps = await loadLSPDeps();\n if (!deps) {\n throw new Error('LSP dependencies (vscode-jsonrpc) are not available');\n }\n const { StreamMessageReader, StreamMessageWriter, createMessageConnection } = deps;\n\n const command = this.serverDef.command(this.workspaceRoot);\n if (!command) {\n throw new Error('Failed to resolve LSP server command');\n }\n this.handle = await this.processManager.spawn(command, { cwd: this.workspaceRoot });\n\n const initializationOptions = this.serverDef.initialization?.(this.workspaceRoot);\n\n const reader = new StreamMessageReader(this.handle.reader);\n const writer = new StreamMessageWriter(this.handle.writer);\n // vscode-jsonrpc's Connection.sendRequest re-throws stream write errors inside\n // an `async` promise executor. That throw rejects the executor's own implicit\n // promise (which nothing awaits) instead of the request promise, so when the\n // server process dies mid-write (e.g. EPIPE), it surfaces as an unhandled\n // rejection and crashes the host process. Swallow write rejections here: the\n // error still reaches the connection's error handler via the writer's\n // handleError, and every request we send is wrapped in a timeout, so callers\n // get a clean timeout error instead of a fatal crash.\n const originalWrite = writer.write.bind(writer);\n writer.write = (msg: unknown) => originalWrite(msg).catch(() => {});\n this.connection = createMessageConnection(reader, writer);\n\n // Silently ignore stream destroyed errors during shutdown\n this.connection.onError(() => {});\n\n // Listen for published diagnostics\n this.connection.onNotification('textDocument/publishDiagnostics', (params: any) => {\n this.diagnostics.set(diagnosticsKey(params.uri), params.diagnostics);\n });\n\n this.connection.listen();\n\n // Build initialize params\n const initParams: any = {\n processId: process.pid,\n rootUri: toFileUri(this.workspaceRoot),\n workspaceFolders: [\n {\n name: 'workspace',\n uri: toFileUri(this.workspaceRoot),\n },\n ],\n capabilities: {\n window: { workDoneProgress: true },\n workspace: { configuration: true },\n textDocument: {\n publishDiagnostics: {\n relatedInformation: true,\n tagSupport: { valueSet: [1, 2] },\n versionSupport: false,\n },\n synchronization: {\n didOpen: true,\n didChange: true,\n dynamicRegistration: false,\n willSave: false,\n willSaveWaitUntil: false,\n didSave: false,\n },\n completion: {\n dynamicRegistration: false,\n completionItem: {\n snippetSupport: false,\n commitCharactersSupport: false,\n documentationFormat: ['markdown', 'plaintext'],\n deprecatedSupport: false,\n preselectSupport: false,\n },\n },\n definition: { dynamicRegistration: false, linkSupport: true },\n typeDefinition: { dynamicRegistration: false, linkSupport: true },\n implementation: { dynamicRegistration: false, linkSupport: true },\n references: { dynamicRegistration: false },\n documentHighlight: { dynamicRegistration: false },\n documentSymbol: { dynamicRegistration: false, hierarchicalDocumentSymbolSupport: true },\n codeAction: {\n dynamicRegistration: false,\n codeActionLiteralSupport: {\n codeActionKind: {\n valueSet: [\n 'quickfix',\n 'refactor',\n 'refactor.extract',\n 'refactor.inline',\n 'refactor.rewrite',\n 'source',\n 'source.organizeImports',\n ],\n },\n },\n },\n hover: { dynamicRegistration: false, contentFormat: ['markdown', 'plaintext'] },\n },\n },\n };\n\n if (initializationOptions) {\n initParams.initializationOptions = initializationOptions;\n this.initializationOptions = initializationOptions;\n }\n\n // Handle workspace/configuration requests\n this.connection.onRequest('workspace/configuration', (params: any) => {\n return params.items?.map(() => ({})) || [];\n });\n\n // Handle window/workDoneProgress/create requests\n this.connection.onRequest('window/workDoneProgress/create', () => null);\n\n // Handle client/registerCapability requests (TS 7+ sends these during init)\n this.connection.onRequest('client/registerCapability', () => null);\n\n let initTimer: ReturnType<typeof setTimeout>;\n const initResult: any = await Promise.race([\n this.connection.sendRequest('initialize', initParams),\n new Promise((_, reject) => {\n initTimer = setTimeout(() => reject(new Error('LSP initialize request timed out')), initTimeout);\n }),\n ]).finally(() => clearTimeout(initTimer!));\n\n // Detect pull diagnostics support (TS 7+ native LSP uses this instead of push)\n if (initResult?.capabilities?.diagnosticProvider) {\n this.supportsPullDiagnostics = true;\n }\n\n // Send initialized notification\n this.connection.sendNotification('initialized', {});\n\n // Send workspace/didChangeConfiguration\n this.connection.sendNotification('workspace/didChangeConfiguration', {\n settings: this.initializationOptions ?? {},\n });\n }\n\n /**\n * Notify the server that a document has been opened.\n */\n notifyOpen(filePath: string, content: string, languageId: string): void {\n if (!this.connection) return;\n const uri = toFileUri(filePath);\n this.diagnostics.delete(diagnosticsKey(uri));\n this.connection.sendNotification('textDocument/didOpen', {\n textDocument: { uri, languageId, version: 0, text: content },\n });\n }\n\n /**\n * Notify the server that a document has changed.\n */\n notifyChange(filePath: string, content: string, version: number): void {\n if (!this.connection) return;\n this.connection.sendNotification('textDocument/didChange', {\n textDocument: { uri: toFileUri(filePath), version },\n contentChanges: [{ text: content }],\n });\n }\n\n /**\n * Wait for diagnostics to arrive for a file.\n *\n * For servers that support pull diagnostics (e.g. TypeScript 7+ native LSP),\n * sends a `textDocument/diagnostic` request directly instead of waiting for\n * push notifications.\n *\n * For push-based servers (e.g. TypeScript ≤6 via typescript-language-server),\n * returns as soon as diagnostics are available. To avoid returning a premature\n * empty array (servers may publish `[]` first while still analysing), empty\n * results trigger a short settle window: polling continues for up to `settleMs`\n * (default 500ms) to see if non-empty diagnostics arrive. Non-empty results\n * are returned immediately.\n */\n async waitForDiagnostics(\n filePath: string,\n timeoutMs: number = 5000,\n waitForChange: boolean = false,\n settleMs: number = 500,\n ): Promise<any[]> {\n if (!this.connection) return [];\n\n // Pull diagnostics: request directly from the server\n if (this.supportsPullDiagnostics) {\n try {\n const result: any = await withTimeout(\n this.connection.sendRequest('textDocument/diagnostic', {\n textDocument: { uri: toFileUri(filePath) },\n }),\n timeoutMs,\n 'Pull diagnostics request timed out',\n );\n const items = result?.items ?? [];\n // Mirror into the diagnostics map so later lookups see the same\n // data regardless of whether the server pushes or pulls.\n this.diagnostics.set(diagnosticsKey(toFileUri(filePath)), items);\n return items;\n } catch {\n return [];\n }\n }\n\n // Push diagnostics: poll the diagnostics map populated by publishDiagnostics\n const uri = diagnosticsKey(toFileUri(filePath));\n const startTime = Date.now();\n const initialDiagnostics = this.diagnostics.get(uri);\n let emptyReceivedAt: number | undefined;\n\n while (Date.now() - startTime < timeoutMs) {\n const currentDiagnostics = this.diagnostics.get(uri);\n\n if (waitForChange) {\n // Compare by reference — the notification handler sets a new array each time\n if (currentDiagnostics !== undefined && currentDiagnostics !== initialDiagnostics) {\n return currentDiagnostics;\n }\n } else if (currentDiagnostics !== undefined) {\n // Non-empty — the server has real results, return immediately\n if (currentDiagnostics.length > 0) return currentDiagnostics;\n // Empty — start a settle window. The server may have published a\n // clearing notification before the real analysis results arrive.\n if (emptyReceivedAt === undefined) emptyReceivedAt = Date.now();\n if (Date.now() - emptyReceivedAt >= settleMs) return currentDiagnostics;\n }\n\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n\n return waitForChange ? initialDiagnostics || [] : this.diagnostics.get(uri) || [];\n }\n\n /**\n * Notify the server that a document was closed.\n */\n notifyClose(filePath: string): void {\n if (!this.connection) return;\n const uri = toFileUri(filePath);\n this.diagnostics.delete(diagnosticsKey(uri));\n this.connection.sendNotification('textDocument/didClose', {\n textDocument: { uri },\n });\n }\n\n /**\n * Query hover information at a position.\n */\n async queryHover(uri: string, position: { line: number; character: number }, timeoutMs: number = 5000): Promise<any> {\n if (!this.connection) return null;\n return withTimeout(\n this.connection.sendRequest('textDocument/hover', { textDocument: { uri }, position }),\n timeoutMs,\n 'Hover request timed out',\n );\n }\n\n /**\n * Query definition(s) at a position.\n */\n async queryDefinition(\n uri: string,\n position: { line: number; character: number },\n timeoutMs: number = 5000,\n ): Promise<any[]> {\n if (!this.connection) return [];\n const result = await withTimeout(\n this.connection.sendRequest('textDocument/definition', { textDocument: { uri }, position }),\n timeoutMs,\n 'Definition request timed out',\n );\n if (!result) return [];\n return Array.isArray(result) ? result : (result as any).uri ? [result] : [];\n }\n\n /**\n * Query type definition(s) at a position.\n */\n async queryTypeDefinition(\n uri: string,\n position: { line: number; character: number },\n timeoutMs: number = 5000,\n ): Promise<any[]> {\n if (!this.connection) return [];\n const result = await withTimeout(\n this.connection.sendRequest('textDocument/typeDefinition', { textDocument: { uri }, position }),\n timeoutMs,\n 'Type definition request timed out',\n );\n if (!result) return [];\n return Array.isArray(result) ? result : (result as any).uri ? [result] : [];\n }\n\n /**\n * Query implementation(s) at a position.\n */\n async queryImplementation(\n uri: string,\n position: { line: number; character: number },\n timeoutMs: number = 5000,\n ): Promise<any[]> {\n if (!this.connection) return [];\n const result = await withTimeout(\n this.connection.sendRequest('textDocument/implementation', { textDocument: { uri }, position }),\n timeoutMs,\n 'Implementation request timed out',\n );\n if (!result) return [];\n return Array.isArray(result) ? result : (result as any).uri ? [result] : [];\n }\n\n /**\n * Shutdown the connection and kill the process.\n */\n async shutdown(): Promise<void> {\n if (this.connection) {\n try {\n if (this.handle && this.handle.exitCode === undefined) {\n let shutdownTimer: ReturnType<typeof setTimeout>;\n await Promise.race([\n this.connection.sendRequest('shutdown'),\n new Promise((_, reject) => {\n shutdownTimer = setTimeout(() => reject(new Error('Shutdown request timed out')), 1000);\n }),\n ]).finally(() => clearTimeout(shutdownTimer!));\n this.connection.sendNotification('exit');\n }\n } catch {\n // Ignore shutdown errors\n }\n try {\n this.connection.dispose();\n } catch {\n // Ignore dispose errors\n }\n this.connection = null;\n }\n\n if (this.handle) {\n try {\n await this.handle.kill();\n } catch {\n // Ignore kill errors\n }\n this.handle = null;\n }\n\n this.diagnostics = new Map();\n }\n}\n","/**\n * Built-in LSP Server Definitions\n *\n * Defines how to locate language servers and build command strings for supported languages.\n * Server definitions are pure data — they don't spawn processes themselves.\n * The LSPClient uses a SandboxProcessManager to spawn from these command strings.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, parse } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { getLanguageId } from './language';\nimport type { CustomLSPServer, LSPConfig, LSPServerDef } from './types';\n\n/** Check if a binary exists on PATH. */\nfunction whichSync(binary: string): boolean {\n try {\n const cmd = process.platform === 'win32' ? 'where' : 'which';\n execFileSync(cmd, [binary], { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Try to resolve a module from the given directory, then fall back to process.cwd().\n * Returns the createRequire instance that succeeded, or null.\n */\nfunction resolveRequire(root: string, moduleId: string): { require: NodeRequire; resolved: string } | null {\n // Try from root first\n try {\n const req = createRequire(pathToFileURL(join(root, 'package.json')));\n return { require: req, resolved: req.resolve(moduleId) };\n } catch {\n // fall through\n }\n // Try from cwd as fallback\n try {\n const req = createRequire(pathToFileURL(join(process.cwd(), 'package.json')));\n return { require: req, resolved: req.resolve(moduleId) };\n } catch {\n return null;\n }\n}\n\n/**\n * Extend resolveRequire to also search additional directories after root and cwd.\n * Each entry in searchPaths should be a directory whose node_modules contains the module.\n */\nfunction resolveRequireFromPaths(\n root: string,\n moduleId: string,\n searchPaths?: string[],\n): { require: NodeRequire; resolved: string } | null {\n const fromBase = resolveRequire(root, moduleId);\n if (fromBase) return fromBase;\n\n for (const searchPath of searchPaths ?? []) {\n try {\n const req = createRequire(pathToFileURL(join(searchPath, 'package.json')));\n return { require: req, resolved: req.resolve(moduleId) };\n } catch {\n // try next\n }\n }\n\n return null;\n}\n\n/** Find a binary in node_modules/.bin, searching root, cwd, then any searchPaths. */\nfunction resolveNodeBin(root: string, binary: string, searchPaths?: string[]): string | undefined {\n const local = join(root, 'node_modules', '.bin', binary);\n const cwd = join(process.cwd(), 'node_modules', '.bin', binary);\n if (existsSync(local)) return local;\n if (existsSync(cwd)) return cwd;\n for (const dir of searchPaths ?? []) {\n const p = join(dir, 'node_modules', '.bin', binary);\n if (existsSync(p)) return p;\n }\n return undefined;\n}\n\n/**\n * Walk up from a starting directory looking for any of the given markers.\n * Returns the first directory that contains a marker, or null.\n */\nexport function walkUp(startDir: string, markers: string[]): string | null {\n let current = startDir;\n const fsRoot = parse(current).root;\n\n while (true) {\n for (const marker of markers) {\n if (existsSync(join(current, marker))) {\n return current;\n }\n }\n if (current === fsRoot) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n\n return null;\n}\n\n/**\n * Async version of walkUp that uses a filesystem's exists() method.\n * Works with any filesystem (local, S3, GCS, composite) that implements exists().\n */\nexport async function walkUpAsync(\n startDir: string,\n markers: string[],\n fs: { exists(path: string): Promise<boolean> },\n): Promise<string | null> {\n let current = startDir;\n const fsRoot = parse(current).root;\n\n while (true) {\n for (const marker of markers) {\n if (await fs.exists(join(current, marker))) {\n return current;\n }\n }\n if (current === fsRoot) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n\n return null;\n}\n\n/** Default markers used to find a project root when no server-specific markers are available. */\nconst DEFAULT_MARKERS = [\n 'tsconfig.json',\n 'package.json',\n 'pyproject.toml',\n 'go.mod',\n 'Cargo.toml',\n 'composer.json',\n '.git',\n];\n\n/**\n * Find a project root by walking up from a starting directory.\n * Uses default markers (tsconfig.json, package.json, go.mod, etc.).\n * Used by Workspace to resolve the default LSP root at construction time.\n */\nexport function findProjectRoot(startDir: string): string | null {\n return walkUp(startDir, DEFAULT_MARKERS);\n}\n\n/**\n * Async version of findProjectRoot that uses a filesystem's exists() method.\n * Works with any filesystem (local, S3, GCS, composite) that implements exists().\n */\nexport async function findProjectRootAsync(\n startDir: string,\n fs: { exists(path: string): Promise<boolean> },\n): Promise<string | null> {\n return walkUpAsync(startDir, DEFAULT_MARKERS, fs);\n}\n\n/**\n * Build an extension → language ID map from custom server definitions.\n * Each extension is mapped to the first language ID of the server that declares it.\n *\n * When multiple servers declare the same extension, the last server wins\n * (iteration order of `Object.values`). A warning is emitted on collision\n * so the user can spot misconfiguration.\n */\nexport function buildCustomExtensions(servers?: Record<string, CustomLSPServer>): Record<string, string> {\n if (!servers) return {};\n const extensions: Record<string, string> = {};\n for (const server of Object.values(servers)) {\n const languageId = server.languageIds[0];\n if (!languageId) continue;\n for (const ext of server.extensions) {\n const existing = extensions[ext];\n if (existing && existing !== languageId) {\n console.warn(\n `[LSP] Extension \"${ext}\" is claimed by language \"${existing}\" and \"${languageId}\" (server \"${server.id}\") — using \"${languageId}\"`,\n );\n }\n extensions[ext] = languageId;\n }\n }\n return extensions;\n}\n\n/**\n * Convert a public custom server config to an internal server definition.\n */\nfunction toServerDef(custom: CustomLSPServer): LSPServerDef {\n return {\n id: custom.id,\n name: custom.name,\n languageIds: custom.languageIds,\n markers: custom.markers,\n command: () => custom.command,\n initialization: custom.initializationOptions ? () => custom.initializationOptions! : undefined,\n };\n}\n\n/**\n * Build a set of server definitions that incorporate LSP config overrides.\n *\n * Resolution order per server:\n * 1. `config.binaryOverrides[id]` — explicit binary command override\n * 2. Project `node_modules/.bin/` binary\n * 3. `process.cwd()` `node_modules/.bin/` binary\n * 4. `config.searchPaths` `node_modules/.bin/` binary lookup\n * 5. Global PATH lookup (system-installed binaries)\n * 6. `config.packageRunner` — package runner fallback (off by default)\n *\n * `config.searchPaths` also extends TypeScript module resolution\n * (used to locate typescript/lib/tsserver.js for TS ≤6, and tsc for TS 7+).\n *\n * When `config.servers` is provided, custom servers are merged after built-in\n * definitions. Custom servers with the same ID as a built-in will replace it.\n */\nexport function buildServerDefs(config?: LSPConfig): Record<string, LSPServerDef> {\n const { binaryOverrides, searchPaths, packageRunner } = config ?? {};\n\n const builtins: Record<string, LSPServerDef> = {\n typescript: {\n id: 'typescript',\n name: 'TypeScript Language Server',\n languageIds: ['typescript', 'typescriptreact', 'javascript', 'javascriptreact'],\n markers: ['tsconfig.json', 'package.json'],\n command: (root: string): string | undefined => {\n if (binaryOverrides?.typescript) return binaryOverrides.typescript;\n\n const hasTsServer = !!resolveRequireFromPaths(root, 'typescript/lib/tsserver.js', searchPaths);\n\n if (hasTsServer) {\n // TS ≤6: use the typescript-language-server wrapper around tsserver.js\n const bin = resolveNodeBin(root, 'typescript-language-server', searchPaths);\n if (bin) return `${bin} --stdio`;\n if (whichSync('typescript-language-server')) return 'typescript-language-server --stdio';\n if (packageRunner) return `${packageRunner} typescript-language-server --stdio`;\n return undefined;\n }\n\n // TS 7+: tsserver.js no longer exists; the native tsc speaks LSP directly.\n // Guard on the installed typescript version so we never pass --lsp to an\n // older tsc that happens to be on PATH when typescript isn't installed.\n const pkg = resolveRequireFromPaths(root, 'typescript/package.json', searchPaths);\n if (!pkg) return undefined;\n const manifest = pkg.require(pkg.resolved) as { version?: string; bin?: string | Record<string, string> };\n if (!(parseInt(manifest.version ?? '', 10) >= 7)) return undefined;\n // Run the validated package's own bin entry directly instead of a\n // node_modules/.bin shim or PATH lookup — a shim found elsewhere is not\n // guaranteed to point at the install whose version we just checked.\n // This also covers hoisted/monorepo and pnpm layouts, where the usable\n // shim and the resolved package live in different directories.\n const binRel = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.tsc;\n if (!binRel) return undefined;\n const tscEntry = join(dirname(pkg.resolved), binRel);\n if (!existsSync(tscEntry)) return undefined;\n return `node ${tscEntry} --lsp --stdio`;\n },\n initialization: (root: string) => {\n // Only TS ≤6 needs the tsserver.path hint; TS 7+ native LSP doesn't use it\n const ts = resolveRequireFromPaths(root, 'typescript/lib/tsserver.js', searchPaths);\n if (!ts) return undefined;\n return { tsserver: { path: ts.resolved, logVerbosity: 'off' } };\n },\n },\n\n eslint: {\n id: 'eslint',\n name: 'ESLint Language Server',\n languageIds: ['typescript', 'typescriptreact', 'javascript', 'javascriptreact'],\n markers: [\n 'package.json',\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc.yml',\n '.eslintrc.yaml',\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.ts',\n ],\n command: (root: string): string | undefined => {\n if (binaryOverrides?.eslint) return binaryOverrides.eslint;\n const bin = resolveNodeBin(root, 'vscode-eslint-language-server', searchPaths);\n if (bin) return `${bin} --stdio`;\n if (whichSync('vscode-eslint-language-server')) return 'vscode-eslint-language-server --stdio';\n if (packageRunner) return `${packageRunner} vscode-eslint-language-server --stdio`;\n return undefined;\n },\n },\n\n python: {\n id: 'python',\n name: 'Python Language Server (Pyright)',\n languageIds: ['python'],\n markers: ['pyproject.toml', 'setup.py', 'requirements.txt', 'setup.cfg'],\n command: (root: string): string | undefined => {\n if (binaryOverrides?.python) return binaryOverrides.python;\n const bin = resolveNodeBin(root, 'pyright-langserver', searchPaths);\n if (bin) return `${bin} --stdio`;\n if (whichSync('pyright-langserver')) return 'pyright-langserver --stdio';\n if (packageRunner) return `${packageRunner} pyright-langserver --stdio`;\n return undefined;\n },\n },\n\n go: {\n id: 'go',\n name: 'Go Language Server (gopls)',\n languageIds: ['go'],\n markers: ['go.mod'],\n command: (): string | undefined => {\n if (binaryOverrides?.go) return binaryOverrides.go;\n return whichSync('gopls') ? 'gopls serve' : undefined;\n },\n },\n\n rust: {\n id: 'rust',\n name: 'Rust Language Server (rust-analyzer)',\n languageIds: ['rust'],\n markers: ['Cargo.toml'],\n command: (): string | undefined => {\n if (binaryOverrides?.rust) return binaryOverrides.rust;\n return whichSync('rust-analyzer') ? 'rust-analyzer --stdio' : undefined;\n },\n },\n };\n\n if (config?.servers) {\n for (const custom of Object.values(config.servers)) {\n builtins[custom.id] = toServerDef(custom);\n }\n }\n\n return builtins;\n}\n\n/**\n * Built-in LSP server definitions with no config overrides.\n * Use `buildServerDefs(config)` when you need binaryOverrides, searchPaths, or packageRunner.\n */\nexport const BUILTIN_SERVERS: Record<string, LSPServerDef> = buildServerDefs();\n\n/**\n * Get all server definitions that can handle the given file.\n * Filters by language ID match only — the manager resolves the root and checks command availability.\n * Pass `defs` to use config-aware server definitions from `buildServerDefs()`.\n * Pass `customExtensions` to recognize file extensions registered by custom servers.\n */\nexport function getServersForFile(\n filePath: string,\n disabledServers?: string[],\n defs?: Record<string, LSPServerDef>,\n customExtensions?: Record<string, string>,\n): LSPServerDef[] {\n const languageId = getLanguageId(filePath, customExtensions);\n if (!languageId) return [];\n\n const disabled = new Set(disabledServers ?? []);\n const servers = defs ?? BUILTIN_SERVERS;\n\n return Object.values(servers).filter(server => !disabled.has(server.id) && server.languageIds.includes(languageId));\n}\n","/**\n * LSP Manager\n *\n * Per-workspace manager that owns LSP server clients.\n * NOT a singleton — each Workspace instance creates its own LSPManager.\n *\n * Resolves the project root per-file by walking up from the file's directory\n * using language-specific markers defined on each server (e.g. tsconfig.json\n * for TypeScript, go.mod for Go). Falls back to the default root when\n * walkup finds nothing.\n */\n\nimport path from 'node:path';\n\nimport type { SandboxProcessManager } from '../sandbox/process-manager';\nimport { LSPClient } from './client';\nimport { getLanguageId } from './language';\nimport { buildCustomExtensions, buildServerDefs, getServersForFile, walkUp, walkUpAsync } from './servers';\nimport type { DiagnosticSeverity, LSPConfig, LSPDiagnostic, LSPServerDef } from './types';\n\nconst CLIENT_LEASE_ACQUIRE_TIMEOUT_MS = 5000;\nconst CLIENT_LEASE_SHUTDOWN_TIMEOUT_MS = 5000;\n\n/** Map LSP DiagnosticSeverity (numeric) to our string severity */\nfunction mapSeverity(severity: number | undefined): DiagnosticSeverity {\n switch (severity) {\n case 1:\n return 'error';\n case 2:\n return 'warning';\n case 3:\n return 'info';\n case 4:\n return 'hint';\n default:\n return 'warning';\n }\n}\n\nexport class LSPManager {\n private clients: Map<string, LSPClient> = new Map();\n private initPromises: Map<string, Promise<void>> = new Map();\n private clientInitQueue: Promise<void> = Promise.resolve();\n private clientLeaseAcquisitionQueue: Promise<void> = Promise.resolve();\n private activeClientLeases: Map<LSPClient, number> = new Map();\n private clientLeaseWaiters: Set<() => void> = new Set();\n private shutdownPromise?: Promise<void>;\n private shuttingDown = false;\n private fileLocks: Map<string, Promise<void>> = new Map();\n private processManager: SandboxProcessManager;\n private _root: string;\n private config: LSPConfig;\n private serverDefs: Record<string, LSPServerDef>;\n private customExtensions: Record<string, string>;\n private filesystem?: {\n exists(path: string): Promise<boolean>;\n };\n\n constructor(\n processManager: SandboxProcessManager,\n root: string,\n config: LSPConfig = {},\n filesystem?: {\n exists(path: string): Promise<boolean>;\n },\n ) {\n if (\n config.maxOpenClients !== undefined &&\n (!Number.isInteger(config.maxOpenClients) || config.maxOpenClients < 1)\n ) {\n throw new RangeError('maxOpenClients must be a positive integer');\n }\n\n this.processManager = processManager;\n this._root = root;\n this.config = config;\n this.serverDefs = buildServerDefs(config);\n this.customExtensions = buildCustomExtensions(config.servers);\n this.filesystem = filesystem;\n }\n\n /** Default project root (fallback when per-file walkup finds nothing). */\n get root(): string {\n return this._root;\n }\n\n /**\n * Resolve the project root for a given file path using the server's markers.\n * Uses the workspace filesystem when available (supports remote filesystems),\n * falls back to sync walkUp (local disk) otherwise.\n */\n private async resolveRoot(filePath: string, markers: string[]): Promise<string> {\n const fileDir = path.dirname(filePath);\n if (this.filesystem) {\n return (await walkUpAsync(fileDir, markers, this.filesystem)) ?? this._root;\n }\n return walkUp(fileDir, markers) ?? this._root;\n }\n\n /** Mark a client as most recently used. */\n private touchClient(key: string, client: LSPClient): void {\n this.clients.delete(key);\n this.clients.set(key, client);\n }\n\n /** Shut down idle least recently used clients until another one can be opened. */\n private async ensureClientCapacity(): Promise<boolean> {\n const maxOpenClients = this.config.maxOpenClients;\n if (maxOpenClients === undefined) return !this.shuttingDown;\n\n while (this.clients.size >= maxOpenClients) {\n if (this.shuttingDown) return false;\n\n const oldestIdle = Array.from(this.clients.entries()).find(([, client]) => !this.activeClientLeases.has(client));\n if (!oldestIdle) {\n if (!(await this.waitForClientLeaseRelease(CLIENT_LEASE_ACQUIRE_TIMEOUT_MS))) return false;\n continue;\n }\n\n const [key, client] = oldestIdle;\n this.clients.delete(key);\n await client.shutdown().catch(() => {});\n }\n\n return !this.shuttingDown;\n }\n\n /** Acquire a client and lease it before another capped acquisition can evict it. */\n private async acquireClientLease(\n acquire: (onAcquired: (client: LSPClient) => void) => Promise<LSPClient | null>,\n ): Promise<{ client: LSPClient; release: () => void } | null> {\n const previous = this.clientLeaseAcquisitionQueue;\n let finishAcquisition!: () => void;\n const current = new Promise<void>(resolve => {\n finishAcquisition = resolve;\n });\n this.clientLeaseAcquisitionQueue = previous.then(() => current);\n\n await previous;\n try {\n if (this.shuttingDown) return null;\n\n const client = await acquire(acquired => {\n this.activeClientLeases.set(acquired, (this.activeClientLeases.get(acquired) ?? 0) + 1);\n });\n if (!client) return null;\n let released = false;\n return {\n client,\n release: () => {\n if (released) return;\n released = true;\n\n const remaining = (this.activeClientLeases.get(client) ?? 1) - 1;\n if (remaining > 0) {\n this.activeClientLeases.set(client, remaining);\n return;\n }\n\n this.activeClientLeases.delete(client);\n this.wakeClientLeaseWaiters();\n },\n };\n } finally {\n finishAcquisition();\n }\n }\n\n /** Keep an acquired client alive while an operation is using it. */\n private async withClientLease<T>(\n acquire: (onAcquired: (client: LSPClient) => void) => Promise<LSPClient | null>,\n operation: (client: LSPClient) => Promise<T>,\n ): Promise<T | null> {\n const lease = await this.acquireClientLease(acquire);\n if (!lease) return null;\n\n try {\n return await operation(lease.client);\n } finally {\n lease.release();\n }\n }\n\n private wakeClientLeaseWaiters(): void {\n const waiters = Array.from(this.clientLeaseWaiters);\n this.clientLeaseWaiters.clear();\n waiters.forEach(resolve => resolve());\n }\n\n /** Wait for a lease release without allowing leaked leases to block new clients indefinitely. */\n private async waitForClientLeaseRelease(timeoutMs: number): Promise<boolean> {\n return new Promise<boolean>(resolve => {\n let settled = false;\n let timeout: ReturnType<typeof setTimeout>;\n const finish = (released: boolean): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n this.clientLeaseWaiters.delete(onRelease);\n resolve(released);\n };\n const onRelease = (): void => finish(true);\n\n timeout = setTimeout(() => finish(false), timeoutMs);\n this.clientLeaseWaiters.add(onRelease);\n });\n }\n\n /** Wait for active operations to release their clients, then force teardown after a bounded delay. */\n private async waitForClientLeasesToDrain(): Promise<void> {\n if (this.activeClientLeases.size === 0) return;\n\n await new Promise<void>(resolve => {\n let timeout: ReturnType<typeof setTimeout>;\n const checkLeases = (): void => {\n if (this.activeClientLeases.size > 0) {\n this.clientLeaseWaiters.add(checkLeases);\n return;\n }\n\n clearTimeout(timeout);\n resolve();\n };\n\n timeout = setTimeout(() => {\n this.clientLeaseWaiters.delete(checkLeases);\n resolve();\n }, CLIENT_LEASE_SHUTDOWN_TIMEOUT_MS);\n this.clientLeaseWaiters.add(checkLeases);\n });\n }\n\n /**\n * Acquire a per-file lock so that concurrent getDiagnostics calls for the\n * same file are serialized (preventing interleaved open/change/close) and\n * are served in the order they arrived. Different files run in parallel.\n */\n private async acquireFileLock(filePath: string): Promise<() => void> {\n // Chain onto the tail of any existing lock for this file to form a FIFO\n // queue. Waiting on a single shared promise instead would still serialize\n // callers, but a caller arriving in the same turn as a release could take\n // the lock ahead of longer-waiting ones, and every release would wake all\n // waiters rather than just the next.\n const previous = this.fileLocks.get(filePath) ?? Promise.resolve();\n\n let release!: () => void;\n const current = new Promise<void>(resolve => {\n release = resolve;\n });\n\n // The new tail resolves only after the whole chain up to and including this\n // holder has released.\n const tail = previous.then(() => current);\n this.fileLocks.set(filePath, tail);\n\n // Wait for all predecessors to finish before this caller holds the lock.\n await previous;\n\n return () => {\n release();\n // Drop the map entry only if nobody chained after us, to avoid leaks.\n if (this.fileLocks.get(filePath) === tail) {\n this.fileLocks.delete(filePath);\n }\n };\n }\n\n /**\n * Initialize an LSP client for the given server definition and project root.\n * Handles timeout, deduplication of concurrent init calls, and caching.\n */\n private async initClient(\n serverDef: LSPServerDef,\n projectRoot: string,\n key: string,\n onAcquired?: (client: LSPClient) => void,\n ): Promise<LSPClient | null> {\n if (this.shuttingDown) return null;\n\n // In-progress initialization — wait for it\n if (this.initPromises.has(key)) {\n await this.initPromises.get(key);\n const client = this.shuttingDown ? null : (this.clients.get(key) ?? null);\n if (client) onAcquired?.(client);\n return client;\n }\n\n const initialize = async (): Promise<void> => {\n if (!(await this.ensureClientCapacity())) return;\n const initTimeout = this.config.initTimeout ?? 15000;\n let timedOut = false;\n let client: LSPClient | undefined;\n let cleanupPromise: Promise<void> | undefined;\n const cleanupClient = async (): Promise<void> => {\n if (!client) return;\n cleanupPromise ??= client.shutdown().catch(() => {});\n await cleanupPromise;\n cleanupPromise = undefined;\n };\n const startPromise = (async () => {\n client = new LSPClient(serverDef, projectRoot, this.processManager);\n try {\n await client.initialize(initTimeout);\n } catch (error) {\n await cleanupClient();\n throw error;\n }\n if (timedOut || this.shuttingDown) {\n await cleanupClient();\n return;\n }\n this.clients.set(key, client);\n })();\n startPromise.catch(() => {}); // prevent unhandled rejection if timeout wins\n\n try {\n let initTimer: ReturnType<typeof setTimeout>;\n await Promise.race([\n startPromise,\n new Promise<void>((_, reject) => {\n initTimer = setTimeout(() => reject(new Error('LSP client initialization timed out')), initTimeout + 1000);\n }),\n ]).finally(() => clearTimeout(initTimer!));\n } catch (err) {\n timedOut = true;\n await cleanupClient();\n this.clients.delete(key);\n const command = serverDef.command(projectRoot);\n const hint = this.config.binaryOverrides?.[serverDef.id]\n ? ` (using binaryOverrides: \"${this.config.binaryOverrides[serverDef.id]}\")`\n : command\n ? ` (command: \"${command}\")`\n : '';\n console.warn(`[LSP] Failed to start ${serverDef.name}${hint}: ${err instanceof Error ? err.message : err}`);\n }\n\n if (client && this.clients.get(key) === client) {\n onAcquired?.(client);\n }\n };\n\n // A configured cap requires serialized initialization so concurrent calls\n // cannot all observe spare capacity and exceed the process limit.\n const initPromise = this.config.maxOpenClients === undefined ? initialize() : this.clientInitQueue.then(initialize);\n if (this.config.maxOpenClients !== undefined) {\n this.clientInitQueue = initPromise.catch(() => {});\n }\n this.initPromises.set(key, initPromise);\n\n try {\n await initPromise;\n return this.clients.get(key) || null;\n } finally {\n this.initPromises.delete(key);\n }\n }\n\n /**\n * Get or create an LSP client for a file path.\n * Resolves the project root per-file using the server's markers.\n * Returns null if no server is available.\n */\n private async getClientInternal(\n filePath: string,\n onAcquired?: (client: LSPClient) => void,\n ): Promise<LSPClient | null> {\n if (this.shuttingDown) return null;\n\n const servers = getServersForFile(filePath, this.config.disableServers, this.serverDefs, this.customExtensions);\n if (servers.length === 0) return null;\n\n // Prefer well-known language servers\n const serverDef =\n servers.find(\n s =>\n s.languageIds.includes('typescript') ||\n s.languageIds.includes('javascript') ||\n s.languageIds.includes('python') ||\n s.languageIds.includes('go'),\n ) ?? servers[0]!;\n\n const projectRoot = await this.resolveRoot(filePath, serverDef.markers);\n if (this.shuttingDown) return null;\n\n // Check if the server's command is available at this root\n if (serverDef.command(projectRoot) === undefined) return null;\n\n const key = `${serverDef.name}:${projectRoot}`;\n\n // Existing client — check liveness before returning\n if (this.clients.has(key)) {\n const existing = this.clients.get(key)!;\n if (!existing.isAlive) {\n this.clients.delete(key);\n existing.shutdown().catch(() => {});\n } else {\n this.touchClient(key, existing);\n onAcquired?.(existing);\n return existing;\n }\n }\n\n return this.initClient(serverDef, projectRoot, key, onAcquired);\n }\n\n /**\n * Get LSP client ready to query a file.\n * Opens the file in the client so queries can be made. Call `release` after\n * closing the file to allow the client to be evicted.\n * Returns null when no LSP client is available.\n */\n async prepareQuery(filePath: string): Promise<{\n client: LSPClient;\n uri: string;\n languageId: string;\n serverName: string;\n release: () => void;\n } | null> {\n const lease = await this.acquireClientLease(onAcquired => this.getClientInternal(filePath, onAcquired));\n if (!lease) return null;\n\n const { client, release } = lease;\n const languageId = getLanguageId(filePath, this.customExtensions);\n if (!languageId) {\n release();\n return null;\n }\n\n try {\n // Open the file (content doesn't matter for position queries, but server may need it)\n const fs = await import('node:fs/promises');\n let content = '';\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n content = '';\n }\n\n client.notifyOpen(filePath, content, languageId);\n\n // Use the same URI format as notifyOpen (pathToFileURL for proper encoding)\n const { pathToFileURL } = await import('node:url');\n const uri = pathToFileURL(filePath).toString();\n return { client, uri, languageId, serverName: client.serverName, release };\n } catch (error) {\n release();\n throw error;\n }\n }\n\n /**\n * Convenience method: open file, send content, wait for diagnostics, return normalized results.\n * Returns null when no LSP client is available; otherwise returns diagnostics\n * (or an empty array on runtime failures after client acquisition).\n * Uses a per-file lock to serialize concurrent calls for the same file.\n */\n async getDiagnostics(filePath: string, content: string): Promise<LSPDiagnostic[] | null> {\n const release = await this.acquireFileLock(filePath);\n try {\n return await this.withClientLease(\n onAcquired => this.getClientInternal(filePath, onAcquired),\n async client => {\n const languageId = getLanguageId(filePath, this.customExtensions);\n if (!languageId) return [];\n\n // Open + change → triggers diagnostics\n client.notifyOpen(filePath, content, languageId);\n client.notifyChange(filePath, content, 1);\n\n const diagnosticTimeout = this.config.diagnosticTimeout ?? 5000;\n let rawDiagnostics: any[];\n try {\n rawDiagnostics = await client.waitForDiagnostics(filePath, diagnosticTimeout);\n } finally {\n client.notifyClose(filePath);\n }\n\n return rawDiagnostics.map((d: any) => ({\n severity: mapSeverity(d.severity),\n message: d.message,\n line: (d.range?.start?.line ?? 0) + 1, // LSP is 0-indexed, we report 1-indexed\n character: (d.range?.start?.character ?? 0) + 1,\n source: d.source,\n }));\n },\n );\n } catch {\n return [];\n } finally {\n release();\n }\n }\n\n /**\n * Get diagnostics from ALL matching language servers for a file.\n * Deduplicates results by (line, character, message).\n * Individual server failures don't block other servers.\n */\n async getDiagnosticsMulti(filePath: string, content: string): Promise<LSPDiagnostic[]> {\n if (this.shuttingDown) return [];\n\n const servers = getServersForFile(filePath, this.config.disableServers, this.serverDefs, this.customExtensions);\n if (servers.length === 0) return [];\n\n const release = await this.acquireFileLock(filePath);\n try {\n const languageId = getLanguageId(filePath, this.customExtensions);\n if (!languageId) return [];\n\n const allDiagnostics: LSPDiagnostic[] = [];\n\n const results = await Promise.allSettled(\n servers.map(async serverDef => {\n const projectRoot = await this.resolveRoot(filePath, serverDef.markers);\n if (serverDef.command(projectRoot) === undefined) return [];\n\n const key = `${serverDef.name}:${projectRoot}`;\n\n const diagnostics = await this.withClientLease(\n async onAcquired => {\n // Existing client — check liveness\n if (this.clients.has(key)) {\n const existing = this.clients.get(key)!;\n if (!existing.isAlive) {\n this.clients.delete(key);\n existing.shutdown().catch(() => {});\n } else {\n this.touchClient(key, existing);\n onAcquired(existing);\n return existing;\n }\n }\n\n return this.initClient(serverDef, projectRoot, key, onAcquired);\n },\n client => this.collectDiagnostics(client, filePath, content, languageId),\n );\n return diagnostics ?? [];\n }),\n );\n\n for (const result of results) {\n if (result.status === 'fulfilled') {\n allDiagnostics.push(...result.value);\n }\n }\n\n // Deduplicate by (line, character, message)\n const seen = new Set<string>();\n return allDiagnostics.filter(d => {\n const key = `${d.line}:${d.character}:${d.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n } finally {\n release();\n }\n }\n\n /**\n * Collect diagnostics from a single client for a file.\n */\n private async collectDiagnostics(\n client: LSPClient,\n filePath: string,\n content: string,\n languageId: string,\n ): Promise<LSPDiagnostic[]> {\n client.notifyOpen(filePath, content, languageId);\n client.notifyChange(filePath, content, 1);\n\n const diagnosticTimeout = this.config.diagnosticTimeout ?? 5000;\n let rawDiagnostics: any[];\n try {\n rawDiagnostics = await client.waitForDiagnostics(filePath, diagnosticTimeout);\n } finally {\n client.notifyClose(filePath);\n }\n\n return rawDiagnostics.map((d: any) => ({\n severity: mapSeverity(d.severity),\n message: d.message,\n line: (d.range?.start?.line ?? 0) + 1,\n character: (d.range?.start?.character ?? 0) + 1,\n source: d.source,\n }));\n }\n\n /**\n * Shutdown all managed LSP clients.\n */\n shutdownAll(): Promise<void> {\n if (this.shutdownPromise) return this.shutdownPromise;\n\n this.shuttingDown = true;\n this.wakeClientLeaseWaiters();\n this.shutdownPromise = (async () => {\n // Drain acquisition and initialization before taking the final client\n // snapshot. New acquisitions are rejected once shuttingDown is set.\n await Promise.allSettled([...this.initPromises.values(), this.clientInitQueue, this.clientLeaseAcquisitionQueue]);\n await this.waitForClientLeasesToDrain();\n await Promise.allSettled(Array.from(this.clients.values()).map(client => client.shutdown()));\n this.clients.clear();\n this.initPromises.clear();\n this.activeClientLeases.clear();\n this.fileLocks.clear();\n // Everything is drained and cleared — return the manager to its\n // fresh-constructed state so it can spawn clients again. This makes\n // shutdownAll() a \"stop\" rather than a one-way door: Workspace.stop()\n // relies on the same manager accepting clients after a restart.\n this.shuttingDown = false;\n this.shutdownPromise = undefined;\n })();\n\n return this.shutdownPromise;\n }\n}\n","import type { BlobStore } from '../../storage/domains/blobs/base';\nimport type { SkillVersionTree } from '../../storage/types';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from './skill-source';\n\n/**\n * Trim leading `.`/`/`/`\\` characters and trailing `/`/`\\` separators from a\n * path. Index scan instead of regex to avoid backtracking (CodeQL\n * js/polynomial-redos).\n */\nfunction trimPathEdges(path: string): string {\n let start = 0;\n let end = path.length;\n while (start < end && (path[start] === '.' || path[start] === '/' || path[start] === '\\\\')) start++;\n while (end > start && (path[end - 1] === '/' || path[end - 1] === '\\\\')) end--;\n return path.slice(start, end);\n}\n\n/**\n * A SkillSource implementation that reads skill files from a versioned\n * content-addressable blob store, using a SkillVersionTree manifest.\n *\n * This is used by production agents to read from published skill versions\n * rather than the live filesystem. The SkillVersionTree maps file paths\n * to blob hashes, and the BlobStore provides the actual content.\n */\nexport class VersionedSkillSource implements SkillSource {\n readonly #tree: SkillVersionTree;\n readonly #blobStore: BlobStore;\n readonly #versionCreatedAt: Date;\n\n /** Computed set of directory paths from the tree entries */\n readonly #directories: Set<string>;\n\n constructor(tree: SkillVersionTree, blobStore: BlobStore, versionCreatedAt: Date) {\n this.#tree = tree;\n this.#blobStore = blobStore;\n this.#versionCreatedAt = versionCreatedAt;\n this.#directories = this.#computeDirectories();\n }\n\n /**\n * Compute all directory paths implied by the file tree.\n * For a file at \"references/api.md\", this adds \"\" (root), \"references\".\n */\n #computeDirectories(): Set<string> {\n const dirs = new Set<string>();\n dirs.add(''); // root\n dirs.add('.'); // root alias\n\n for (const filePath of Object.keys(this.#tree.entries)) {\n const parts = filePath.split('/');\n // Add all parent directories\n for (let i = 1; i < parts.length; i++) {\n dirs.add(parts.slice(0, i).join('/'));\n }\n }\n return dirs;\n }\n\n /**\n * Normalize a path by stripping leading/trailing slashes and dots.\n */\n #normalizePath(path: string): string {\n return trimPathEdges(path);\n }\n\n async exists(path: string): Promise<boolean> {\n const normalized = this.#normalizePath(path);\n // Check if it's a file\n if (this.#tree.entries[normalized]) return true;\n // Check if it's a directory\n return this.#directories.has(normalized);\n }\n\n async stat(path: string): Promise<SkillSourceStat> {\n const normalized = this.#normalizePath(path);\n const name = normalized.split('/').pop() || normalized || '.';\n\n // Check if it's a file in the tree\n const entry = this.#tree.entries[normalized];\n if (entry) {\n return {\n name,\n type: 'file',\n size: entry.size,\n createdAt: this.#versionCreatedAt,\n modifiedAt: this.#versionCreatedAt,\n mimeType: entry.mimeType,\n };\n }\n\n // Check if it's a directory\n if (this.#directories.has(normalized)) {\n return {\n name,\n type: 'directory',\n size: 0,\n createdAt: this.#versionCreatedAt,\n modifiedAt: this.#versionCreatedAt,\n };\n }\n\n throw new Error(`Path not found in skill version tree: ${path}`);\n }\n\n async readFile(path: string): Promise<string | Buffer> {\n const normalized = this.#normalizePath(path);\n const entry = this.#tree.entries[normalized];\n\n if (!entry) {\n throw new Error(`File not found in skill version tree: ${path}`);\n }\n\n const blob = await this.#blobStore.get(entry.blobHash);\n if (!blob) {\n throw new Error(`Blob not found for hash ${entry.blobHash} (file: ${path})`);\n }\n\n // Decode base64-encoded binary content back to Buffer\n if (entry.encoding === 'base64') {\n return Buffer.from(blob.content, 'base64');\n }\n\n return blob.content;\n }\n\n async readdir(path: string): Promise<SkillSourceEntry[]> {\n const normalized = this.#normalizePath(path);\n\n if (!this.#directories.has(normalized)) {\n throw new Error(`Directory not found in skill version tree: ${path}`);\n }\n\n const prefix = normalized === '' ? '' : normalized + '/';\n const seen = new Set<string>();\n const entries: SkillSourceEntry[] = [];\n\n for (const filePath of Object.keys(this.#tree.entries)) {\n if (!filePath.startsWith(prefix)) continue;\n\n // Get the next segment after the prefix\n const remaining = filePath.slice(prefix.length);\n const nextSegment = remaining.split('/')[0];\n if (!nextSegment || seen.has(nextSegment)) continue;\n seen.add(nextSegment);\n\n // If there's more after the next segment, it's a directory\n const isDirectory = remaining.includes('/');\n entries.push({\n name: nextSegment,\n type: isDirectory ? 'directory' : 'file',\n });\n }\n\n return entries;\n }\n\n async realpath(path: string): Promise<string> {\n return this.#normalizePath(path);\n }\n}\n","import type { BlobStore } from '../../storage/domains/blobs/base';\nimport type { SkillVersionTree } from '../../storage/types';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from './skill-source';\nimport { VersionedSkillSource } from './versioned-skill-source';\n\n/**\n * A skill entry for the composite source.\n * Each entry represents one skill's versioned tree, mounted under a directory name.\n */\nexport interface VersionedSkillEntry {\n /** Directory name for this skill (used as the subdirectory under the root) */\n dirName: string;\n /** The skill version's file tree manifest */\n tree: SkillVersionTree;\n /** When this version was created */\n versionCreatedAt: Date;\n}\n\n/**\n * A SkillSource that composes multiple versioned skill trees into a virtual directory.\n *\n * Each skill is mounted under a directory name, so the composite source looks like:\n * / (root - virtual)\n * /brand-guidelines/ (skill 1 root)\n * /brand-guidelines/SKILL.md (skill 1 files from blob store)\n * /tone-of-voice/ (skill 2 root)\n * /tone-of-voice/SKILL.md (skill 2 files from blob store)\n *\n * This allows WorkspaceSkillsImpl to discover skills normally by scanning the root\n * for subdirectories containing SKILL.md.\n *\n * Can also include a fallback source for \"live\" skills that read from the filesystem.\n */\nexport class CompositeVersionedSkillSource implements SkillSource {\n readonly #sources: Map<string, VersionedSkillSource> = new Map();\n readonly #fallback?: SkillSource;\n readonly #fallbackSkills: Set<string>;\n readonly #maxVersionCreatedAt: Date;\n\n constructor(\n entries: VersionedSkillEntry[],\n blobStore: BlobStore,\n options?: {\n /** Fallback source for \"live\" skills that read from the filesystem */\n fallback?: SkillSource;\n /** Skill directory names that should be served from the fallback source */\n fallbackSkills?: string[];\n },\n ) {\n let maxTime = 0;\n for (const entry of entries) {\n this.#sources.set(entry.dirName, new VersionedSkillSource(entry.tree, blobStore, entry.versionCreatedAt));\n const t = entry.versionCreatedAt.getTime();\n if (t > maxTime) maxTime = t;\n }\n this.#maxVersionCreatedAt = maxTime > 0 ? new Date(maxTime) : new Date(0);\n this.#fallback = options?.fallback;\n this.#fallbackSkills = new Set(options?.fallbackSkills ?? []);\n }\n\n #normalizePath(path: string): string {\n // Strip any leading '.', '/', '\\' and any trailing '/', '\\' without\n // using a regex to avoid polynomial backtracking on attacker-crafted\n // paths like many leading slashes or dots.\n let start = 0;\n while (start < path.length) {\n const c = path.charCodeAt(start);\n if (c === 46 /* '.' */ || c === 47 /* '/' */ || c === 92 /* '\\' */) {\n start++;\n } else {\n break;\n }\n }\n let end = path.length;\n while (end > start) {\n const c = path.charCodeAt(end - 1);\n if (c === 47 /* '/' */ || c === 92 /* '\\' */) {\n end--;\n } else {\n break;\n }\n }\n return start === 0 && end === path.length ? path : path.slice(start, end);\n }\n\n /**\n * Route a path to the correct source.\n * Returns the source and the remaining path within that source.\n */\n #routePath(path: string): { source: SkillSource; subPath: string; mountDir: string } | null {\n const normalized = this.#normalizePath(path);\n\n // Root: handled by this source directly\n if (normalized === '') return null;\n\n const segments = normalized.split('/');\n const skillDir = segments[0]!;\n const subPath = segments.slice(1).join('/');\n\n // Check if this skill should use the fallback source\n if (this.#fallbackSkills.has(skillDir) && this.#fallback) {\n return { source: this.#fallback, subPath: normalized, mountDir: '' };\n }\n\n // Check if this skill has a versioned source\n const versionedSource = this.#sources.get(skillDir);\n if (versionedSource) {\n return { source: versionedSource, subPath, mountDir: skillDir };\n }\n\n // Try the fallback for unknown paths\n if (this.#fallback) {\n return { source: this.#fallback, subPath: normalized, mountDir: '' };\n }\n\n return null;\n }\n\n async exists(path: string): Promise<boolean> {\n const normalized = this.#normalizePath(path);\n\n // Root always exists\n if (normalized === '') return true;\n\n const route = this.#routePath(path);\n if (!route) return false;\n\n return route.source.exists(route.subPath);\n }\n\n async stat(path: string): Promise<SkillSourceStat> {\n const normalized = this.#normalizePath(path);\n\n // Root directory\n if (normalized === '') {\n return {\n name: '.',\n type: 'directory',\n size: 0,\n createdAt: this.#maxVersionCreatedAt,\n modifiedAt: this.#maxVersionCreatedAt,\n };\n }\n\n const route = this.#routePath(path);\n if (!route) {\n throw new Error(`Path not found in composite skill source: ${path}`);\n }\n\n return route.source.stat(route.subPath);\n }\n\n async readFile(path: string): Promise<string | Buffer> {\n const route = this.#routePath(path);\n if (!route) {\n throw new Error(`File not found in composite skill source: ${path}`);\n }\n\n return route.source.readFile(route.subPath);\n }\n\n async readdir(path: string): Promise<SkillSourceEntry[]> {\n const normalized = this.#normalizePath(path);\n\n // Root: list all mounted skill directories\n if (normalized === '') {\n const entries: SkillSourceEntry[] = [];\n const seen = new Set<string>();\n\n for (const dirName of this.#sources.keys()) {\n entries.push({ name: dirName, type: 'directory' });\n seen.add(dirName);\n }\n\n // Also list fallback skills\n for (const dirName of this.#fallbackSkills) {\n if (!seen.has(dirName)) {\n entries.push({ name: dirName, type: 'directory' });\n seen.add(dirName);\n }\n }\n\n return entries;\n }\n\n const route = this.#routePath(path);\n if (!route) {\n throw new Error(`Directory not found in composite skill source: ${path}`);\n }\n\n return route.source.readdir(route.subPath);\n }\n\n async realpath(path: string): Promise<string> {\n const normalized = this.#normalizePath(path);\n if (normalized === '') return '';\n\n const route = this.#routePath(path);\n if (!route) {\n throw new Error(`Path not found in composite skill source: ${path}`);\n }\n\n const realSubPath = route.source.realpath ? await route.source.realpath(route.subPath) : route.subPath;\n return [route.mountDir, realSubPath].filter(Boolean).join('/');\n }\n}\n","import type { BlobStore } from '../../storage/domains/blobs/base';\nimport type {\n SkillVersionTree,\n SkillVersionTreeEntry,\n StorageBlobEntry,\n StorageSkillFileNode,\n StorageSkillSnapshotType,\n} from '../../storage/types';\nimport { extractSkillFrontmatter } from './schemas';\nimport type { SkillSource, SkillSourceEntry } from './skill-source';\n\n/**\n * Result of collecting a skill's filesystem tree.\n * Contains the tree manifest, the blob entries to store, and parsed SKILL.md fields.\n */\nexport interface SkillPublishResult {\n /** Denormalized snapshot fields parsed from SKILL.md frontmatter */\n snapshot: Omit<StorageSkillSnapshotType, 'tree'>;\n /** Content-addressable file tree manifest */\n tree: SkillVersionTree;\n /** Blob entries to store (already deduplicated by hash) */\n blobs: StorageBlobEntry[];\n /** UI-facing nested file tree (folders + files with content) for the stored skill record */\n files: StorageSkillFileNode[];\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Compute SHA-256 hex hash of content (string or Buffer).\n */\nasync function hashContent(content: string | Buffer): Promise<string> {\n const bytes = typeof content === 'string' ? new TextEncoder().encode(content) : content;\n const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', data));\n return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Simple extension-based MIME type detection.\n */\nfunction detectMimeType(filename: string): string | undefined {\n const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase();\n const mimeTypes: Record<string, string> = {\n '.md': 'text/markdown',\n '.txt': 'text/plain',\n '.json': 'application/json',\n '.yaml': 'text/yaml',\n '.yml': 'text/yaml',\n '.sh': 'text/x-shellscript',\n '.py': 'text/x-python',\n '.js': 'text/javascript',\n '.ts': 'text/typescript',\n '.html': 'text/html',\n '.css': 'text/css',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.svg': 'image/svg+xml',\n };\n return mimeTypes[ext];\n}\n\n/**\n * Whether a MIME type represents binary content that cannot be safely stored as UTF-8 text.\n */\nfunction isBinaryMimeType(mimeType: string | undefined): boolean {\n if (!mimeType) return false;\n // Text-based types are safe for UTF-8\n if (mimeType.startsWith('text/')) return false;\n // JSON and YAML are text-safe\n if (mimeType === 'application/json') return false;\n // SVG is XML-based text\n if (mimeType === 'image/svg+xml') return false;\n // Everything else (image/png, image/jpeg, application/octet-stream, etc.) is binary\n return true;\n}\n\ninterface WalkedFile {\n path: string;\n /** Text content (UTF-8) or raw binary content (Buffer) */\n content: string | Buffer;\n /** Whether this file is binary */\n isBinary: boolean;\n}\n\n/**\n * Recursively walk a directory in a SkillSource, returning all files\n * with their relative paths and content. Binary files are returned as Buffers.\n */\nasync function walkSkillDirectory(\n source: SkillSource,\n basePath: string,\n currentPath: string = basePath,\n): Promise<WalkedFile[]> {\n const entries: SkillSourceEntry[] = await source.readdir(currentPath);\n const files: WalkedFile[] = [];\n\n for (const entry of entries) {\n const entryPath = joinPath(currentPath, entry.name);\n\n if (entry.type === 'directory') {\n const subFiles = await walkSkillDirectory(source, basePath, entryPath);\n files.push(...subFiles);\n } else {\n const rawContent = await source.readFile(entryPath);\n const relativePath = entryPath.substring(basePath.length + 1);\n const mimeType = detectMimeType(entry.name);\n const isBinary = isBinaryMimeType(mimeType);\n\n if (isBinary) {\n // Keep binary content as Buffer\n const buf = Buffer.isBuffer(rawContent) ? rawContent : Buffer.from(rawContent, 'utf-8');\n files.push({ path: relativePath, content: buf, isBinary: true });\n } else {\n // Text content as string\n const content = typeof rawContent === 'string' ? rawContent : rawContent.toString('utf-8');\n files.push({ path: relativePath, content, isBinary: false });\n }\n }\n }\n\n return files;\n}\n\n/**\n * Trim slashes from a segment without regex backtracking (CodeQL js/polynomial-redos).\n */\nfunction trimSlashes(segment: string, trimLeading: boolean): string {\n let start = 0;\n let end = segment.length;\n if (trimLeading) {\n while (start < end && segment[start] === '/') start++;\n }\n while (end > start && segment[end - 1] === '/') end--;\n return segment.slice(start, end);\n}\n\n/**\n * Join path segments using forward slashes.\n */\nfunction joinPath(...segments: string[]): string {\n return segments\n .map((seg, i) => trimSlashes(seg, i > 0))\n .filter(Boolean)\n .join('/');\n}\n\n/**\n * Collect file paths under a specific subdirectory prefix.\n */\nfunction collectSubdirPaths(allPaths: string[], subdir: string): string[] {\n const prefix = subdir + '/';\n return allPaths.filter(p => p.startsWith(prefix)).map(p => p.substring(prefix.length));\n}\n\n/**\n * Build a nested folder/file tree from a flat list of walked files for the\n * UI-facing `files` column on the stored skill record. Binary file content is\n * base64-encoded so it can round-trip through the string-typed `content` field.\n */\nfunction buildSkillFileNodes(files: WalkedFile[]): StorageSkillFileNode[] {\n const root: StorageSkillFileNode[] = [];\n\n for (const file of files) {\n const segments = file.path.split('/').filter(Boolean);\n if (segments.length === 0) continue;\n\n let cursor = root;\n for (let i = 0; i < segments.length - 1; i++) {\n const segment = segments[i]!;\n let folder = cursor.find(node => node.type === 'folder' && node.name === segment);\n if (!folder) {\n folder = { name: segment, type: 'folder', children: [] };\n cursor.push(folder);\n }\n if (!folder.children) folder.children = [];\n cursor = folder.children;\n }\n\n const fileName = segments[segments.length - 1]!;\n const content = file.isBinary\n ? (Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content)).toString('base64')\n : (file.content as string);\n cursor.push({ name: fileName, type: 'file', content });\n }\n\n return root;\n}\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * A flat file entry used by snapshot parsing helpers.\n * Path is the skill-relative path (e.g. `SKILL.md`, `references/foo.md`).\n */\nexport interface SkillSnapshotFile {\n path: string;\n content: string | Buffer;\n}\n\n/**\n * Parse a flat array of skill files into a denormalized snapshot.\n *\n * Finds `SKILL.md`, parses its YAML frontmatter into structured fields\n * (name, description, license, compatibility, metadata), and uses the\n * markdown body as `instructions`. Discovers `references/`, `scripts/`,\n * and `assets/` subdirectory paths from the file list.\n *\n * Used by both the publish flow (which has files from a SkillSource walk)\n * and the registry install flow (which has files fetched from an external\n * registry like skills.sh). The Agent Skills spec puts metadata in\n * frontmatter and agent-facing prose in the body — this helper enforces\n * that split so frontmatter never leaks into the runtime instructions.\n *\n * @throws if `SKILL.md` is missing from the file list\n */\nexport function parseSkillSnapshotFromFiles(files: SkillSnapshotFile[]): Omit<StorageSkillSnapshotType, 'tree'> {\n const skillMdFile = files.find(f => f.path === 'SKILL.md');\n if (!skillMdFile) {\n throw new Error('SKILL.md not found in skill files');\n }\n\n const skillMdContent =\n typeof skillMdFile.content === 'string' ? skillMdFile.content : skillMdFile.content.toString('utf-8');\n const { metadata: frontmatter, instructions } = extractSkillFrontmatter(skillMdContent);\n\n const allPaths = files.map(f => f.path);\n const references = collectSubdirPaths(allPaths, 'references');\n const scripts = collectSubdirPaths(allPaths, 'scripts');\n const assets = collectSubdirPaths(allPaths, 'assets');\n\n return {\n name: frontmatter.name,\n description: frontmatter.description,\n instructions,\n license: frontmatter.license,\n compatibility: frontmatter.compatibility,\n metadata: frontmatter.metadata,\n ...(references.length > 0 ? { references } : {}),\n ...(scripts.length > 0 ? { scripts } : {}),\n ...(assets.length > 0 ? { assets } : {}),\n };\n}\n\n/**\n * Collect a skill from a SkillSource for publishing.\n * Walks the skill directory, hashes all files, parses SKILL.md frontmatter,\n * and returns everything needed to create a new version.\n *\n * @param source - The SkillSource to read from (live filesystem or any other source)\n * @param skillPath - Path to the skill directory (containing SKILL.md)\n */\nexport async function collectSkillForPublish(source: SkillSource, skillPath: string): Promise<SkillPublishResult> {\n // 1. Walk the skill directory recursively, reading all files\n const files = await walkSkillDirectory(source, skillPath);\n\n // 2. Build tree entries and blob entries, deduplicating blobs by hash\n const treeEntries: Record<string, SkillVersionTreeEntry> = {};\n const blobMap = new Map<string, StorageBlobEntry>();\n const now = new Date();\n\n for (const file of files) {\n const hash = await hashContent(file.content);\n const mimeType = detectMimeType(file.path);\n\n if (file.isBinary) {\n // Binary file: store as base64-encoded string\n const buf = Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content);\n const size = buf.length;\n const base64Content = buf.toString('base64');\n\n treeEntries[file.path] = {\n blobHash: hash,\n size,\n mimeType,\n encoding: 'base64',\n };\n\n if (!blobMap.has(hash)) {\n blobMap.set(hash, {\n hash,\n content: base64Content,\n size,\n mimeType,\n createdAt: now,\n });\n }\n } else {\n // Text file: store as UTF-8 string\n const content = file.content as string;\n const size = Buffer.byteLength(content, 'utf-8');\n\n treeEntries[file.path] = {\n blobHash: hash,\n size,\n mimeType,\n };\n\n if (!blobMap.has(hash)) {\n blobMap.set(hash, {\n hash,\n content,\n size,\n mimeType,\n createdAt: now,\n });\n }\n }\n }\n\n const tree: SkillVersionTree = { entries: treeEntries };\n const blobs = Array.from(blobMap.values());\n const fileNodes = buildSkillFileNodes(files);\n\n // 3. Parse SKILL.md frontmatter and discover references/scripts/assets paths\n let snapshot: Omit<StorageSkillSnapshotType, 'tree'>;\n try {\n snapshot = parseSkillSnapshotFromFiles(files);\n } catch (err) {\n // Surface the skill path to make the error easier to debug\n if (err instanceof Error && err.message.includes('SKILL.md not found')) {\n throw new Error(`SKILL.md not found in ${skillPath}`);\n }\n throw err;\n }\n\n return { snapshot, tree, blobs, files: fileNodes };\n}\n\n/**\n * Publish a skill: collect files, store blobs, create version.\n * This is the full publish flow.\n *\n * @param source - The SkillSource to read from\n * @param skillPath - Path to the skill directory\n * @param blobStore - Where to store file blobs\n */\nexport async function publishSkillFromSource(\n source: SkillSource,\n skillPath: string,\n blobStore: BlobStore,\n): Promise<SkillPublishResult> {\n const result = await collectSkillForPublish(source, skillPath);\n // Store blobs in batch\n await blobStore.putMany(result.blobs);\n return result;\n}\n","/**\n * Skill Tools — Factory\n *\n * Creates the built-in skill tools for agents. These tools let the model\n * discover and read skill instructions on demand.\n *\n * Design: stateless. The `skill` tool returns the full skill instructions\n * in its tool result — no activation state tracking needed. Instructions\n * persist naturally in conversation history. If context gets compacted,\n * the model just calls the tool again.\n */\n\nimport { z } from 'zod/v4';\n\nimport { createTool } from '../../tools';\nimport { extractLines } from '../line-utils';\nimport { startSkillSpan } from '../tools/tracing';\nimport type { Skill, SkillsContext, WorkspaceSkills } from './types';\n\n// =============================================================================\n// Factory\n// =============================================================================\n\n/**\n * Create all skill tools for a workspace with skills.\n * Returns an empty object if the workspace has no skills.\n *\n * Tools are added at the Agent level (like workspace tools), not inside\n * a processor, to avoid losing tool execute functions on serialization.\n */\nexport function createSkillTools(skills: WorkspaceSkills) {\n return {\n skill: createSkillTool(skills),\n skill_search: createSkillSearchTool(skills),\n skill_read: createSkillReadTool(skills),\n };\n}\n\n/**\n * Format a skill into the activation payload: instructions followed by\n * any references/scripts/assets listings. Shared between the `skill` tool\n * and explicit user activations so both paths produce identical output.\n */\nexport function formatSkillActivation(skill: Skill): string {\n const parts = [skill.instructions];\n\n if (skill.references?.length) {\n parts.push(`\\n\\n## References\\n${skill.references.map(r => `- references/${r}`).join('\\n')}`);\n }\n if (skill.scripts?.length) {\n parts.push(`\\n\\n## Scripts\\n${skill.scripts.map(s => `- scripts/${s}`).join('\\n')}`);\n }\n if (skill.assets?.length) {\n parts.push(`\\n\\n## Assets\\n${skill.assets.map(a => `- assets/${a}`).join('\\n')}`);\n }\n\n return parts.join('');\n}\n\n// =============================================================================\n// Individual Tools\n// =============================================================================\n\n/** Above this many skills, a not-found skill lists suggestions instead of every skill. */\nconst MAX_LISTED_SKILLS = 20;\nconst MAX_SUGGESTED_SKILLS = 5;\n\nasync function getScopedSkills(skills: WorkspaceSkills, requestContext?: object): Promise<WorkspaceSkills> {\n return skills.getScoped\n ? skills.getScoped({ requestContext: requestContext as SkillsContext['requestContext'] })\n : skills;\n}\n\n/**\n * Resolve a skill identifier (name or path) to a Skill.\n * The `skills.get()` method handles both name-based lookup (with tie-breaking)\n * and path-based lookup (escape hatch for disambiguation).\n *\n * Calls `maybeRefresh()` first so edits on disk are picked up between tool\n * invocations without restarting the server. Refresh is gated by an internal\n * staleness check + cooldown, so the cost is a small directory `stat` rather\n * than a full re-walk. File-level reloads (SKILL.md content edits) only\n * trigger when the workspace is configured with `checkSkillFileMtime: true`.\n */\nasync function resolveSkill(\n skills: WorkspaceSkills,\n identifier: string,\n): Promise<{ skill: Skill } | { notFound: string }> {\n await skills.maybeRefresh();\n\n const skill = await skills.get(identifier);\n if (skill) return { skill };\n\n const notFound = `Skill \"${identifier}\" not found.`;\n const allSkills = await skills.list();\n if (allSkills.length <= MAX_LISTED_SKILLS) {\n const skillEntries = allSkills.map(s => `${s.name} (${s.path})`);\n return { notFound: `${notFound} Available skills: ${skillEntries.join(', ')}` };\n }\n\n // Listing every skill would put the whole catalog into the conversation, so suggest\n // the closest matches instead and point the model at skill_search.\n // Search by the last path segment: earlier segments (\"skills/\") match every skill.\n const name = identifier.split('/').filter(Boolean).pop() ?? '';\n const query = name.replace(/[-_.]+/g, ' ').trim();\n // An empty query would \"match\" the first few skills, so don't suggest anything\n const matches = query\n ? await skills.search(query, { topK: MAX_SUGGESTED_SKILLS, includeReferences: false }).catch(() => [])\n : [];\n const suggestions = [...new Set(matches.map(m => `${m.skillName} (${m.skillPath})`))];\n const closest = suggestions.length > 0 ? ` Closest matches: ${suggestions.join(', ')}.` : '';\n return { notFound: `${notFound}${closest} Use the \\`skill_search\\` tool to find other skills.` };\n}\n\nfunction createSkillTool(skills: WorkspaceSkills) {\n const tool = createTool({\n id: 'skill',\n description:\n \"Activate a skill to load its full instructions. You should activate skills proactively when they are relevant to the user's request without asking for permission first.\",\n inputSchema: z.object({\n name: z\n .string()\n .describe('The name or path of the skill to activate. Use the path when multiple skills share the same name.'),\n }),\n execute: async ({ name }, context) => {\n const span = startSkillSpan(context, {\n operation: 'activate',\n input: { name },\n attributes: { skillName: name },\n });\n\n try {\n const scopedSkills = await getScopedSkills(skills, context?.requestContext);\n const result = await resolveSkill(scopedSkills, name);\n\n if ('notFound' in result) {\n span.end({ success: false });\n return result.notFound;\n }\n\n const { skill } = result;\n const output = formatSkillActivation(skill);\n\n span.end({ success: true });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n });\n\n return tool;\n}\n\nfunction createSkillSearchTool(skills: WorkspaceSkills) {\n const tool = createTool({\n id: 'skill_search',\n description:\n 'Search skills by name, description, and content. Use it to find which skill to load with the `skill` tool, or to find specific details inside skills.',\n inputSchema: z.object({\n query: z.string().describe('The search query'),\n skillNames: z.array(z.string()).optional().describe('Optional list of skill names to search within'),\n topK: z.number().optional().describe('Maximum number of results to return (default: 5)'),\n }),\n execute: async ({ query, skillNames, topK }, context) => {\n const span = startSkillSpan(context, {\n operation: 'search',\n input: { query, skillNames, topK },\n attributes: {},\n });\n\n try {\n const scopedSkills = await getScopedSkills(skills, context?.requestContext);\n await scopedSkills.maybeRefresh();\n const results = await scopedSkills.search(query, { topK, skillNames });\n\n if (results.length === 0) {\n span.end({ success: true }, { resultCount: 0 });\n return 'No results found.';\n }\n\n span.end({ success: true }, { resultCount: results.length });\n return results\n .map(r => {\n const preview = r.content.substring(0, 200) + (r.content.length > 200 ? '...' : '');\n // Reference hits name their file so the model can pass it to skill_read\n const file = r.source !== 'SKILL.md' ? ` ${r.source}` : '';\n const location = r.lineRange ? ` (lines ${r.lineRange.start}-${r.lineRange.end})` : '';\n return `[${r.skillName}]${file}${location} (score: ${r.score.toFixed(2)})\\n${preview}`;\n })\n .join('\\n\\n');\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n });\n\n return tool;\n}\n\nfunction createSkillReadTool(skills: WorkspaceSkills) {\n const tool = createTool({\n id: 'skill_read',\n description:\n 'Read a file from a skill directory (references, scripts, or assets). The path is relative to the skill root.',\n inputSchema: z.object({\n skillName: z\n .string()\n .describe('The name or path of the skill. Use the path when multiple skills share the same name.'),\n path: z\n .string()\n .describe('Path to the file relative to the skill root (e.g. \"references/colors.md\", \"scripts/run.sh\")'),\n startLine: z\n .number()\n .optional()\n .describe('Starting line number (1-indexed). If omitted, starts from the beginning.'),\n endLine: z\n .number()\n .optional()\n .describe('Ending line number (1-indexed, inclusive). If omitted, reads to the end.'),\n }),\n execute: async ({ skillName, path, startLine, endLine }, context) => {\n const span = startSkillSpan(context, {\n operation: 'read',\n input: { skillName, path, startLine, endLine },\n attributes: { skillName },\n });\n\n try {\n const scopedSkills = await getScopedSkills(skills, context?.requestContext);\n // Resolve skill by name or path (get() handles both with tie-breaking)\n const resolved = await resolveSkill(scopedSkills, skillName);\n if ('notFound' in resolved) {\n span.end({ success: false });\n return resolved.notFound;\n }\n const resolvedPath = resolved.skill.path;\n\n // Every accessor resolves the same skill-root-relative path; getAsset is the only one\n // that returns the raw bytes instead of decoding them as UTF-8, so read through it and\n // classify the bytes here. Going through getReference first would lossily decode any\n // binary file before getAsset was reached.\n const bytes = await scopedSkills.getAsset(resolvedPath, path);\n\n if (bytes === null) {\n const refs = (await scopedSkills.listReferences(resolvedPath)).map(f => `references/${f}`);\n const scriptsList = (await scopedSkills.listScripts(resolvedPath)).map(f => `scripts/${f}`);\n const assets = (await scopedSkills.listAssets(resolvedPath)).map(f => `assets/${f}`);\n const allFiles = [...refs, ...scriptsList, ...assets];\n const fileList = allFiles.length > 0 ? `\\nAvailable files: ${allFiles.join(', ')}` : '';\n span.end({ success: false });\n return `File \"${path}\" not found in skill \"${skillName}\".${fileList}`;\n }\n\n // Binary if it contains NUL bytes or is not valid UTF-8 (e.g. PNGs, PDFs — which are\n // often NUL-free). Report the exact byte size and never put mojibake in model context.\n const text = bytes.toString('utf-8');\n const isBinary = bytes.includes(0) || !bytes.equals(Buffer.from(text, 'utf-8'));\n if (isBinary) {\n const fullPath = `${resolved.skill.path}/${path}`;\n span.end({ success: true }, { bytesTransferred: bytes.length });\n return `Binary file: ${fullPath} (${bytes.length} bytes)`;\n }\n\n const result = extractLines(text, startLine, endLine);\n\n // An empty range is indistinguishable from a failed read, so the model keeps paginating\n if (result.lines.start === 0 && result.lines.end === 0) {\n const reason =\n (startLine ?? 1) > result.totalLines\n ? `Requested startLine ${startLine} is past the end of the file. The file has been fully read; stop paginating.`\n : `Requested range ${startLine}-${endLine} is empty because startLine is greater than endLine.`;\n span.end({ success: true }, { bytesTransferred: 0 });\n return `File \"${path}\" has ${result.totalLines} lines (valid range 1-${result.totalLines}). ${reason}`;\n }\n\n // Header ranged reads so the model sees EOF coming instead of overshooting to find it\n const output =\n startLine !== undefined || endLine !== undefined\n ? `${path} (lines ${result.lines.start}-${result.lines.end} of ${result.totalLines})\\n${result.content}`\n : result.content;\n\n span.end({ success: true }, { bytesTransferred: Buffer.byteLength(result.content, 'utf-8') });\n return output;\n } catch (err) {\n span.error(err);\n throw err;\n }\n },\n });\n\n return tool;\n}\n","/**\n * Workspace Class\n *\n * A Workspace combines a Filesystem and a Sandbox to provide agents\n * with a complete environment for storing files and executing code.\n *\n * Users pass provider instances directly to the Workspace constructor.\n *\n * @example\n * ```typescript\n * import { LocalFilesystem, Workspace } from '@mastra/core/workspace';\n * import { E2BSandbox } from '@mastra/e2b';\n * import { S3Filesystem } from '@mastra/s3';\n *\n * // Local filesystems use paths relative to their base directory.\n * const localWorkspace = new Workspace({\n * filesystem: new LocalFilesystem({ basePath: './workspace' }),\n * });\n *\n * await localWorkspace.init();\n * await localWorkspace.filesystem?.writeFile('app.py', 'print(\"Hello locally!\")');\n *\n * // Mounted cloud filesystems use their absolute mount paths.\n * const cloudWorkspace = new Workspace({\n * mounts: {\n * '/code': new S3Filesystem({ bucket: 'my-code', region: 'us-east-1' }),\n * },\n * sandbox: new E2BSandbox(),\n * });\n *\n * await cloudWorkspace.init();\n * await cloudWorkspace.filesystem?.writeFile('/code/app.py', 'print(\"Hello from E2B!\")');\n * const result = await cloudWorkspace.sandbox?.executeCommand?.('python3', ['app.py'], { cwd: '/code' });\n * ```\n */\n\nimport * as path from 'node:path';\nimport type { MastraBrowser } from '../browser';\nimport type { IMastraLogger } from '../logger';\nimport type { DefinitionSource } from '../observability';\nimport { RequestContext } from '../request-context';\nimport type { MastraVector } from '../vector';\n\nimport { WorkspaceError, SearchNotAvailableError, WorkspaceNotReadyError } from './errors';\nimport { CompositeFilesystem, LocalFilesystem } from './filesystem';\nimport type { WorkspaceFilesystem, FilesystemInfo } from './filesystem';\nimport { MastraFilesystem } from './filesystem/mastra-filesystem';\nimport { resolvePathPattern } from './glob';\nimport type { ReaddirEntry } from './glob';\nimport { callLifecycle } from './lifecycle';\nimport { findProjectRoot, isLSPAvailable, LSPManager } from './lsp';\nimport type { LSPConfig } from './lsp/types';\nimport type { WorkspaceSandbox, OnMountHook } from './sandbox';\nimport { LocalSandbox } from './sandbox/local-sandbox';\nimport { MastraSandbox } from './sandbox/mastra-sandbox';\nimport type {\n BM25Config,\n BM25SearchConfig,\n TokenizeOptions,\n Embedder,\n SearchOptions,\n SearchResult,\n IndexDocument,\n} from './search';\nimport { SearchEngine, splitIntoChunks } from './search';\nimport type { WorkspaceSkills, SkillsResolver, SkillSource } from './skills';\nimport {\n WorkspaceSkillsImpl,\n ResolvedSourceWorkspaceSkills,\n LocalSkillSource,\n SKILL_SCOPE_DOCUMENT_PREFIX,\n} from './skills';\nimport type { WorkspaceToolsConfig } from './tools';\nimport type { WorkspaceStatus } from './types';\n\n/** Workspace instructions for a resolver-backed sandbox in `'placeholder'` mode. */\nconst DYNAMIC_SANDBOX_INSTRUCTIONS =\n 'Dynamic sandbox configured. Shell commands execute in a request-scoped sandbox resolved at tool execution time.';\n\n// =============================================================================\n// Workspace Configuration\n// =============================================================================\n\n/**\n * A function that resolves a WorkspaceFilesystem dynamically based on request context.\n * Called on each tool invocation, allowing different filesystems per request.\n */\nexport type WorkspaceFilesystemResolver = (context: {\n requestContext: RequestContext;\n}) => WorkspaceFilesystem | Promise<WorkspaceFilesystem>;\n\n/**\n * A function that resolves a WorkspaceSandbox dynamically based on request context.\n * Called on each tool invocation, allowing different sandboxes per request.\n *\n * The caller owns the returned sandbox's lifecycle.\n */\nexport type WorkspaceSandboxResolver = (context: {\n requestContext: RequestContext;\n}) => WorkspaceSandbox | Promise<WorkspaceSandbox>;\n\n/**\n * How a resolver-backed sandbox contributes to workspace instructions:\n * `'placeholder'` (default) emits stable text without calling the resolver,\n * `'resolve'` uses the resolved sandbox's instructions, a function returns\n * custom text from `requestContext` without resolving.\n */\nexport type DynamicSandboxInstructions =\n | 'placeholder'\n | 'resolve'\n | ((context: { requestContext: RequestContext }) => string);\n\n/**\n * Produces a stable cache key (e.g. a thread or tenant id) for a resolver-backed\n * sandbox. Resolved sandboxes are memoized per key instead of per RequestContext\n * instance. Return `undefined` to fall back to per-RequestContext memoization.\n */\nexport type WorkspaceSandboxCacheKey = (context: { requestContext: RequestContext }) => string | undefined;\n\n/**\n * Configuration for creating a Workspace.\n * Users pass provider instances directly.\n *\n * Generic type parameters allow the workspace to preserve the concrete types\n * of filesystem and sandbox providers, so accessors return the exact type\n * you passed in.\n */\nexport interface WorkspaceConfig<\n TFilesystem extends WorkspaceFilesystem | undefined = WorkspaceFilesystem | undefined,\n TSandbox extends WorkspaceSandbox | undefined = WorkspaceSandbox | undefined,\n TMounts extends Record<string, WorkspaceFilesystem> | undefined = undefined,\n> {\n /** Unique identifier (auto-generated if not provided) */\n id?: string;\n\n /** Human-readable name */\n name?: string;\n\n /**\n * Filesystem provider instance, or a resolver function for dynamic per-request filesystems.\n *\n * Static: Pass a LocalFilesystem, AgentFS, or any WorkspaceFilesystem instance.\n * Dynamic: Pass a function `({ requestContext }) => WorkspaceFilesystem` to resolve\n * a different filesystem per request. The resolver is called at tool execution time.\n *\n * Extend MastraFilesystem for automatic logger integration (static instances only).\n */\n filesystem?: TFilesystem | WorkspaceFilesystemResolver;\n\n /**\n * Sandbox provider instance, or a resolver function for dynamic per-request sandboxes.\n *\n * Static: Pass a LocalSandbox, ComputeSDKSandbox, or any WorkspaceSandbox instance.\n * Dynamic: Pass a function `({ requestContext }) => WorkspaceSandbox` to resolve\n * a different sandbox per request. The resolver is called at tool execution time.\n *\n * When using a resolver, the caller owns the returned sandbox's lifecycle.\n * Mounts and `lsp: true` are incompatible with a resolver.\n *\n * Extend MastraSandbox for automatic logger integration (static instances only).\n */\n sandbox?: TSandbox | WorkspaceSandboxResolver;\n\n /**\n * Controls how a resolver-backed `sandbox` contributes to workspace instructions.\n * Defaults to `dynamicSandbox: 'placeholder'`. No effect on a static sandbox.\n * See {@link DynamicSandboxInstructions}.\n */\n instructions?: {\n dynamicSandbox?: DynamicSandboxInstructions;\n };\n\n /**\n * Stable cache key for a resolver-backed `sandbox`, so background-process tools\n * reach the same sandbox across requests. No effect on a static sandbox.\n * See {@link WorkspaceSandboxCacheKey}.\n */\n sandboxCacheKey?: WorkspaceSandboxCacheKey;\n\n /**\n * Mount multiple filesystems at different paths.\n * Creates a CompositeFilesystem that routes operations based on path.\n *\n * When a sandbox is configured, filesystems are automatically mounted\n * into the sandbox at their respective paths during init().\n *\n * Use the `onMount` hook to skip or customize mounting for specific filesystems.\n *\n * The concrete mount types are preserved — use `workspace.filesystem.mounts.get()`\n * for typed access to individual mounts.\n *\n * @example\n * ```typescript\n * const workspace = new Workspace({\n * sandbox: new E2BSandbox({ timeout: 60000 }),\n * mounts: {\n * '/data': new S3Filesystem({ bucket: 'my-data', ... }),\n * '/skills': new S3Filesystem({ bucket: 'skills', readOnly: true, ... }),\n * },\n * });\n *\n * await workspace.init();\n * workspace.filesystem // CompositeFilesystem<{ '/data': S3Filesystem, '/skills': S3Filesystem }>\n * workspace.filesystem.mounts.get('/data') // S3Filesystem\n * ```\n */\n mounts?: TMounts;\n\n /**\n * Hook called before mounting each filesystem into the sandbox.\n *\n * Return values:\n * - `false` - Skip mount entirely (don't mount this filesystem)\n * - `{ success: true }` - Hook handled the mount successfully\n * - `{ success: false, error?: string }` - Hook attempted mount but failed\n * - `undefined` / no return - Use provider's default mount behavior\n *\n * This is useful for:\n * - Skipping specific filesystems (e.g., local filesystems in remote sandbox)\n * - Custom mount implementations\n * - Syncing files instead of FUSE mounting\n *\n * Note: If your hook handles the mount, you're responsible for the entire\n * implementation. The sandbox provider won't do any additional tracking.\n *\n * @example Skip local filesystems\n * ```typescript\n * const workspace = new Workspace({\n * sandbox: new E2BSandbox(),\n * mounts: {\n * '/data': new S3Filesystem({ bucket: 'data', ... }),\n * '/local': new LocalFilesystem({ basePath: './data' }),\n * },\n * onMount: ({ filesystem }) => {\n * if (filesystem.provider === 'local') return false;\n * },\n * });\n * ```\n *\n * @example Custom mount implementation\n * ```typescript\n * onMount: async ({ filesystem, mountPath, config, sandbox }) => {\n * if (config?.type === 's3') {\n * await sandbox.executeCommand?.('my-s3-mount', [mountPath]);\n * return { success: true };\n * }\n * }\n * ```\n */\n onMount?: OnMountHook;\n\n // ---------------------------------------------------------------------------\n // Browser Configuration\n // ---------------------------------------------------------------------------\n\n /**\n * Browser provider for web automation.\n *\n * Must be a `MastraBrowser` instance with `providerType: 'cli'` (e.g., `BrowserViewer`).\n * SDK providers (`AgentBrowser`, `StagehandBrowser`) are not supported here —\n * use `Agent.browser` for SDK providers.\n *\n * The browser is launched via Playwright and exposes a CDP URL that CLI tools\n * (`agent-browser`, `browser-use`, `browse`) can connect to.\n *\n * @example\n * ```typescript\n * import { BrowserViewer } from '@mastra/browser-viewer';\n *\n * const workspace = new Workspace({\n * sandbox: new LocalSandbox({ cwd: './workspace' }),\n * browser: new BrowserViewer({\n * cli: 'agent-browser',\n * headless: false,\n * }),\n * });\n * ```\n */\n browser?: MastraBrowser;\n\n // ---------------------------------------------------------------------------\n // Search Configuration\n // ---------------------------------------------------------------------------\n\n /**\n * Vector store for semantic search.\n * When provided along with embedder, enables vector and hybrid search. A store that generates\n * embeddings itself, such as `MongoDBVector` with `autoEmbed`, needs no embedder.\n */\n vectorStore?: MastraVector;\n\n /**\n * Embedder function for generating vectors.\n * Required when vectorStore is provided, unless the store generates embeddings itself.\n */\n embedder?: Embedder;\n\n /**\n * Enable BM25 keyword search.\n * Pass `true` for defaults, a {@link BM25Config} for custom k1/b parameters,\n * or a `{ bm25?, tokenize? }` object to also customise tokenization.\n *\n * The `tokenize` field accepts a {@link TokenizeOptions} object that lets you\n * tune how text is split into tokens (e.g. for CJK or other non-Latin scripts).\n *\n * @example\n * ```ts\n * new Workspace({\n * bm25: {\n * k1: 1.5,\n * b: 0.75,\n * tokenize: { removePunctuation: false, minLength: 1 },\n * },\n * });\n * ```\n */\n bm25?: boolean | BM25Config | { bm25?: BM25Config; tokenize?: TokenizeOptions };\n\n /**\n * Custom index name for the vector store.\n * If not provided, defaults to a sanitized version of `${id}_search`.\n *\n * Must be a valid SQL identifier for SQL-based stores (PgVector, LibSQL):\n * - Start with a letter or underscore\n * - Contain only letters, numbers, or underscores\n * - Maximum 63 characters\n *\n * @example 'my_workspace_vectors'\n */\n searchIndexName?: string;\n\n /**\n * Paths to auto-index on init().\n * Files in these directories will be indexed for search.\n * @example ['docs', 'support']\n */\n autoIndexPaths?: string[];\n\n /**\n * Paths where skills are located.\n * Workspace will discover SKILL.md files in these directories.\n *\n * Can be a static array of paths or a function that returns paths\n * dynamically based on request context (e.g., user tier, tenant).\n *\n * @example Static paths\n * ```typescript\n * skills: ['skills', 'node_modules/@myorg/skills']\n * ```\n *\n * @example Dynamic paths\n * ```typescript\n * skills: (ctx) => {\n * const tier = ctx.requestContext?.get('userTier');\n * return tier === 'premium'\n * ? ['skills/basic', 'skills/premium']\n * : ['skills/basic'];\n * }\n * ```\n */\n skills?: SkillsResolver;\n\n /**\n * Custom SkillSource to use for skill discovery.\n * When provided, this source is used instead of the workspace filesystem or LocalSkillSource.\n *\n * Use `VersionedSkillSource` to read skills from the content-addressable blob store,\n * serving a specific published version without touching the live filesystem.\n *\n * @example\n * ```typescript\n * import { VersionedSkillSource } from '@mastra/core/workspace';\n *\n * const workspace = new Workspace({\n * skills: ['skills'],\n * skillSource: new VersionedSkillSource(tree, blobStore, versionCreatedAt),\n * });\n * ```\n */\n skillSource?: SkillSource;\n\n /**\n * Check SKILL.md file mtime in addition to directory mtime for staleness detection.\n *\n * When enabled, allows hot-reload detection of in-place SKILL.md edits\n * (e.g., fixing a validation error or updating a skill description).\n *\n * Trade-off: This doubles the stat() calls per skill during staleness checks.\n * Recommended for local development only. Not recommended for cloud storage\n * backends (S3, etc.) where stat() calls have higher latency.\n *\n * @default false\n */\n checkSkillFileMtime?: boolean;\n\n // ---------------------------------------------------------------------------\n // LSP Configuration\n // ---------------------------------------------------------------------------\n\n /**\n * Enable LSP diagnostics for edit tools.\n *\n * When enabled, edit tools (edit_file, write_file, ast_edit) will append\n * type errors, warnings, and other diagnostics from language servers after edits.\n *\n * LSP requires a sandbox with a process manager (`sandbox.processes`) to spawn\n * language server processes. It works with any sandbox backend (local, E2B, etc.).\n *\n * Requires optional peer dependencies: `vscode-jsonrpc`, `vscode-languageserver-protocol`,\n * and the relevant language server (e.g. `typescript-language-server` for TypeScript).\n *\n * - `true` — Enable with defaults\n * - `LSPConfig` object — Enable with custom timeouts/settings\n *\n * @default undefined (disabled)\n */\n lsp?: boolean | LSPConfig;\n\n // ---------------------------------------------------------------------------\n // Tool Configuration\n // ---------------------------------------------------------------------------\n\n /**\n * Per-tool configuration for workspace tools.\n * Controls which tools are enabled and their safety settings.\n *\n * This replaces the provider-level `requireApproval` and `requireReadBeforeWrite`\n * settings, allowing more granular control per tool.\n *\n * @example\n * ```typescript\n * tools: {\n * mastra_workspace_read_file: {\n * enabled: true,\n * requireApproval: false,\n * },\n * mastra_workspace_write_file: {\n * enabled: true,\n * requireApproval: true,\n * requireReadBeforeWrite: true,\n * },\n * mastra_workspace_execute_command: {\n * enabled: true,\n * requireApproval: true,\n * },\n * }\n * ```\n */\n tools?: WorkspaceToolsConfig;\n\n // ---------------------------------------------------------------------------\n // Lifecycle Options\n // ---------------------------------------------------------------------------\n\n /** Auto-sync between fs and sandbox (default: false) */\n autoSync?: boolean;\n\n /** Timeout for individual operations in milliseconds */\n operationTimeout?: number;\n}\n\n// Re-export WorkspaceStatus from types\nexport type { WorkspaceStatus } from './types';\n\n/**\n * A Workspace with any combination of filesystem, sandbox, and mounts.\n * Use this when you need to accept any Workspace regardless of its generic parameters.\n */\nexport type AnyWorkspace = Workspace<WorkspaceFilesystem | undefined, WorkspaceSandbox | undefined, any>;\n\n/** A workspace entry in the Mastra registry, enriched with source metadata. */\nexport interface RegisteredWorkspace {\n workspace: Workspace;\n source: 'mastra' | 'agent';\n agentId?: string;\n agentName?: string;\n /** Where the registering agent is defined, for agent workspaces. */\n agentSource?: DefinitionSource;\n}\n\n// =============================================================================\n// Path Context Types\n// =============================================================================\n\n/**\n * Information about how filesystem and sandbox paths relate.\n * Used by agents to understand how to access workspace files from sandbox code.\n */\nexport interface PathContext {\n /** Filesystem details (if available) */\n filesystem?: {\n provider: string;\n /** Absolute base path on disk (for local filesystems) */\n basePath?: string;\n };\n\n /** Sandbox details (if available) */\n sandbox?: {\n provider: string;\n /** Working directory for command execution */\n workingDirectory?: string;\n };\n\n /**\n * Human-readable instructions for how to access filesystem files from sandbox code.\n * Combined from filesystem and sandbox provider instructions.\n */\n instructions: string;\n}\n\nexport interface WorkspaceInfo {\n id: string;\n name: string;\n status: WorkspaceStatus;\n createdAt: Date;\n lastAccessedAt: Date;\n\n /** Filesystem info (if available) */\n filesystem?: FilesystemInfo & {\n totalFiles?: number;\n totalSize?: number;\n };\n\n /** Sandbox info (if available) */\n sandbox?: {\n provider: string;\n status: string;\n resources?: {\n memoryMB?: number;\n memoryUsedMB?: number;\n cpuCores?: number;\n cpuPercent?: number;\n diskMB?: number;\n diskUsedMB?: number;\n };\n };\n}\n\n/**\n * Maximum concurrent `readFile` calls when batch-loading files for search auto-indexing\n * (`batchReadFiles`).\n */\nconst FS_READ_CONCURRENCY = 8;\n/** Mirrors SearchEngine.search default when no topK is supplied. */\nconst DEFAULT_SEARCH_TOP_K = 10;\n\n/**\n * Parse the user-facing `bm25` config union into the `BM25SearchConfig` shape\n * that `SearchEngine` expects.\n */\nfunction parseBM25Config(\n bm25: boolean | BM25Config | { bm25?: BM25Config; tokenize?: TokenizeOptions },\n): BM25SearchConfig {\n if (typeof bm25 === 'boolean') return {};\n if ('bm25' in bm25 || 'tokenize' in bm25) {\n return {\n bm25: (bm25 as { bm25?: BM25Config }).bm25,\n tokenize: (bm25 as { tokenize?: TokenizeOptions }).tokenize,\n };\n }\n return { bm25: bm25 as BM25Config };\n}\n\n// =============================================================================\n// Workspace Class\n// =============================================================================\n\n/**\n * Provides agents with filesystem and execution capabilities through configured providers.\n *\n * Supply a filesystem, a sandbox, or both. File operations require a filesystem;\n * command execution requires a sandbox.\n *\n * @example\n * ```typescript\n * import { Workspace, LocalFilesystem } from '@mastra/core/workspace';\n *\n * const workspace = new Workspace({\n * filesystem: new LocalFilesystem({ basePath: './my-workspace' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/core/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Workspace documentation](https://mastra.ai/docs/workspace/overview)\n * if packaged docs are unavailable.\n */\nexport class Workspace<\n TFilesystem extends WorkspaceFilesystem | undefined = WorkspaceFilesystem | undefined,\n TSandbox extends WorkspaceSandbox | undefined = WorkspaceSandbox | undefined,\n TMounts extends Record<string, WorkspaceFilesystem> | undefined = undefined,\n> {\n readonly id: string;\n readonly name: string;\n readonly createdAt: Date;\n lastAccessedAt: Date;\n\n private _status: WorkspaceStatus = 'pending';\n private _destroyPromise?: Promise<void>;\n private _stopPromise?: Promise<void>;\n private readonly _fs?: WorkspaceFilesystem;\n private readonly _filesystemResolver?: WorkspaceFilesystemResolver;\n private readonly _sandbox?: WorkspaceSandbox;\n private readonly _sandboxResolver?: WorkspaceSandboxResolver;\n // Per-request memoization so one resolver call serves both instructions and tool execution.\n private readonly _filesystemRequestCache = new WeakMap<RequestContext, Promise<WorkspaceFilesystem>>();\n private readonly _sandboxRequestCache = new WeakMap<RequestContext, Promise<WorkspaceSandbox>>();\n // Resolver memoization keyed by sandboxCacheKey (survives RequestContext churn).\n private readonly _sandboxKeyCache = new Map<string, Promise<WorkspaceSandbox>>();\n private readonly _sandboxCacheKey?: WorkspaceSandboxCacheKey;\n private readonly _dynamicSandboxInstructions: DynamicSandboxInstructions;\n private readonly _browser?: MastraBrowser;\n private readonly _config: WorkspaceConfig<TFilesystem, TSandbox, TMounts>;\n private readonly _searchEngine?: SearchEngine;\n private _skills?: WorkspaceSkills;\n /** Set as soon as `destroy()` begins, and never cleared. */\n private _teardownStarted = false;\n private _lsp?: LSPManager;\n private _logger?: IMastraLogger;\n\n constructor(config: WorkspaceConfig<TFilesystem, TSandbox, TMounts>) {\n this.id = config.id ?? this.generateId();\n this.name = config.name ?? `workspace-${this.id.slice(0, 8)}`;\n this.createdAt = new Date();\n this.lastAccessedAt = new Date();\n\n this._config = config;\n\n if (typeof config.sandbox === 'function') {\n this._sandboxResolver = config.sandbox as WorkspaceSandboxResolver;\n } else {\n this._sandbox = config.sandbox;\n }\n this._sandboxCacheKey = config.sandboxCacheKey;\n this._dynamicSandboxInstructions = config.instructions?.dynamicSandbox ?? 'placeholder';\n\n // Setup mounts - creates CompositeFilesystem and informs sandbox\n if (config.mounts && Object.keys(config.mounts).length > 0) {\n // Validate: can't use both filesystem and mounts\n if (config.filesystem) {\n throw new WorkspaceError('Cannot use both \"filesystem\" and \"mounts\"', 'INVALID_CONFIG');\n }\n if (this._sandboxResolver) {\n throw new WorkspaceError(\n 'Cannot use \"mounts\" with a dynamic sandbox resolver. ' +\n 'Mounts are attached to a sandbox instance at construction time. ' +\n 'Either pass a static sandbox instance, or have your resolver return a sandbox with its mounts already configured.',\n 'INVALID_CONFIG',\n );\n }\n\n // Warn: contained: false is incompatible with mounts\n for (const [mountPath, fs] of Object.entries(config.mounts)) {\n if (fs instanceof LocalFilesystem && !fs.contained) {\n console.warn(\n `[Workspace] LocalFilesystem at mount \"${mountPath}\" has contained: false, which is incompatible with mounts. ` +\n `CompositeFilesystem strips mount prefixes and produces absolute paths (e.g. \"/file.txt\"), ` +\n `which a non-contained LocalFilesystem interprets as real host paths instead of paths ` +\n `relative to basePath. Use contained: true (default) or allowedPaths for specific exceptions.`,\n );\n }\n }\n\n this._fs = new CompositeFilesystem({ mounts: config.mounts });\n if (this._sandbox?.mounts) {\n // Inform sandbox about mounts so it can process them on start()\n this._sandbox.mounts.setContext({ sandbox: this._sandbox, workspace: this as unknown as Workspace });\n this._sandbox.mounts.add(config.mounts);\n if (config.onMount) {\n this._sandbox.mounts.setOnMount(config.onMount);\n }\n }\n } else if (typeof config.filesystem === 'function') {\n // Reject class constructors — a common mistake is passing the class itself instead of an instance\n if (/^class\\s/.test(Function.prototype.toString.call(config.filesystem))) {\n throw new WorkspaceError(\n 'filesystem received a class constructor instead of an instance or resolver function. ' +\n 'Pass an instance (e.g., new LocalFilesystem(...)) or a resolver function (({ requestContext }) => fs).',\n 'INVALID_CONFIG',\n );\n }\n // Dynamic filesystem resolver — stored separately, no static _fs instance\n this._filesystemResolver = config.filesystem as WorkspaceFilesystemResolver;\n } else {\n this._fs = config.filesystem;\n }\n\n // Validate and store browser provider\n if (config.browser) {\n if (config.browser.providerType !== 'cli') {\n throw new WorkspaceError(\n `Workspace.browser requires a CLI provider (providerType: 'cli'), but got '${config.browser.providerType}'. ` +\n `SDK providers should be used with Agent.browser instead.`,\n 'INVALID_CONFIG',\n this.id,\n );\n }\n this._browser = config.browser;\n }\n\n // Validate vector search config - a vectorStore needs an embedder unless it embeds server-side\n const embedsServerSide = !config.embedder && config.vectorStore?.isSelfEmbedding === true;\n if (config.vectorStore && !config.embedder && !embedsServerSide) {\n throw new WorkspaceError('vectorStore requires an embedder', 'INVALID_SEARCH_CONFIG');\n }\n\n // Create search engine if search is configured\n if (config.bm25 || (config.vectorStore && (config.embedder || embedsServerSide))) {\n const buildIndexName = (): string => {\n // Sanitize default name: replace all non-alphanumeric chars with underscores.\n // A store that embeds server-side keeps its index apart from one holding client-supplied vectors.\n const defaultName = `${this.id}_search${embedsServerSide ? '_selfembed' : ''}`.replace(/[^a-zA-Z0-9_]/g, '_');\n const indexName = config.searchIndexName ?? defaultName;\n\n // Validate SQL identifier format\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)) {\n throw new WorkspaceError(\n `Invalid searchIndexName: \"${indexName}\". Must start with a letter or underscore, and contain only letters, numbers, or underscores.`,\n 'INVALID_SEARCH_CONFIG',\n this.id,\n );\n }\n if (indexName.length > 63) {\n throw new WorkspaceError(\n `searchIndexName exceeds 63 characters (got ${indexName.length})`,\n 'INVALID_SEARCH_CONFIG',\n this.id,\n );\n }\n return indexName;\n };\n\n this._searchEngine = new SearchEngine({\n bm25: config.bm25 ? parseBM25Config(config.bm25) : undefined,\n vector:\n config.vectorStore && (config.embedder || embedsServerSide)\n ? {\n vectorStore: config.vectorStore,\n embedder: config.embedder,\n indexName: buildIndexName(),\n }\n : undefined,\n });\n }\n\n // Initialize LSP if configured and a process manager is available\n if (config.lsp) {\n const processes = this._sandbox?.processes;\n if (this._sandboxResolver) {\n console.warn(\n `[Workspace \"${this.name}\"] lsp: true is incompatible with a dynamic sandbox resolver — LSP needs a process manager at construction time, but the sandbox is resolved per request. LSP disabled.`,\n );\n } else if (!this._sandbox) {\n console.warn(\n `[Workspace \"${this.name}\"] lsp: true requires a sandbox with a process manager. No sandbox configured — LSP disabled.`,\n );\n } else if (!processes) {\n console.warn(\n `[Workspace \"${this.name}\"] lsp: true requires a sandbox with a process manager. Sandbox \"${this._sandbox.name ?? 'unknown'}\" does not provide one — LSP disabled.`,\n );\n } else if (!isLSPAvailable()) {\n console.warn(\n `[Workspace \"${this.name}\"] lsp: true requires vscode-jsonrpc and vscode-languageserver-protocol packages. Install them to enable LSP diagnostics.`,\n );\n } else {\n const lspConfig = config.lsp === true ? {} : config.lsp;\n const defaultRoot = lspConfig.root ?? findProjectRoot(process.cwd()) ?? process.cwd();\n this._lsp = new LSPManager(processes, defaultRoot, lspConfig, this._fs);\n }\n }\n\n // Validate at least one provider is given\n // Note: skills alone is also valid - uses LocalSkillSource for read-only skills\n if (!this._fs && !this._filesystemResolver && !this._sandbox && !this._sandboxResolver && !this.hasSkillsConfig()) {\n throw new WorkspaceError('Workspace requires at least a filesystem, sandbox, or skills', 'NO_PROVIDERS');\n }\n }\n\n private generateId(): string {\n return `ws-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n private hasSkillsConfig(): boolean {\n return (\n this._config.skills !== undefined && (typeof this._config.skills === 'function' || this._config.skills.length > 0)\n );\n }\n\n get status(): WorkspaceStatus {\n return this._status;\n }\n\n /**\n * Compact span representation. Without it, the trace serializer would walk the\n * workspace's config and its filesystem/sandbox providers, which can hold credentials.\n */\n serializeForSpan(): { id: string; name: string; status: WorkspaceStatus } {\n return { id: this.id, name: this.name, status: this._status };\n }\n\n /**\n * The filesystem provider (if configured).\n *\n * Returns the concrete type you passed to the constructor.\n * When `mounts` is used instead of `filesystem`, returns `CompositeFilesystem`\n * parameterized with the concrete mount types.\n */\n get filesystem(): [TMounts] extends [Record<string, WorkspaceFilesystem>]\n ? CompositeFilesystem<TMounts>\n : TFilesystem {\n return this._fs as any;\n }\n\n /**\n * The sandbox provider (if configured).\n *\n * Returns the concrete type you passed to the constructor.\n */\n get sandbox(): TSandbox {\n return this._sandbox as any;\n }\n\n /**\n * The browser provider (if configured).\n *\n * Returns the MastraBrowser instance (must be a CLI provider like BrowserViewer).\n */\n get browser(): MastraBrowser | undefined {\n return this._browser;\n }\n\n /**\n * Get the per-tool configuration for this workspace.\n * Returns undefined if no tools config was provided.\n */\n getToolsConfig(): WorkspaceToolsConfig | undefined {\n return this._config.tools;\n }\n\n /**\n * The LSP manager (if configured, initialized, and a process manager is available).\n * Returns undefined if LSP is not configured, deps are missing, or sandbox has no process manager.\n */\n get lsp(): LSPManager | undefined {\n return this._lsp;\n }\n\n /**\n * Update the per-tool configuration for this workspace.\n * Takes effect on the next `createWorkspaceTools()` call.\n *\n * @example\n * ```typescript\n * // Disable write tools for read-only mode\n * workspace.setToolsConfig({\n * mastra_workspace_write_file: { enabled: false },\n * mastra_workspace_edit_file: { enabled: false },\n * });\n *\n * // Re-enable all tools\n * workspace.setToolsConfig(undefined);\n * ```\n */\n setToolsConfig(config: WorkspaceToolsConfig | undefined): void {\n this._config.tools = config;\n }\n\n /**\n * Returns true if a filesystem is configured, either as a static instance or a resolver function.\n */\n hasFilesystemConfig(): boolean {\n return this._fs !== undefined || this._filesystemResolver !== undefined;\n }\n\n /**\n * Resolve the filesystem for a given request context.\n * When a resolver function is configured, calls it with the provided requestContext.\n * When a static filesystem is configured, returns it directly.\n * Returns undefined if no filesystem is configured.\n */\n async resolveFilesystem({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): Promise<WorkspaceFilesystem | undefined> {\n if (!this._filesystemResolver) return this._fs;\n let pending = this._filesystemRequestCache.get(requestContext);\n if (!pending) {\n pending = Promise.resolve().then(() => this._filesystemResolver!({ requestContext }));\n this._filesystemRequestCache.set(requestContext, pending);\n // Don't keep a failure around: a transient resolver error would otherwise\n // disable filesystem and skill tools for the rest of the request.\n pending.catch(() => {\n if (this._filesystemRequestCache.get(requestContext) === pending) {\n this._filesystemRequestCache.delete(requestContext);\n }\n });\n }\n return pending;\n }\n\n /**\n * Returns true if a sandbox is configured, either as a static instance or a resolver function.\n */\n hasSandboxConfig(): boolean {\n return this._sandbox !== undefined || this._sandboxResolver !== undefined;\n }\n\n /**\n * Returns true when the sandbox is resolved dynamically per request.\n */\n hasSandboxResolver(): boolean {\n return this._sandboxResolver !== undefined;\n }\n\n /**\n * Returns true when resolver-backed sandboxes are cached by a stable key.\n */\n hasSandboxCacheKey(): boolean {\n return this._sandboxCacheKey !== undefined;\n }\n\n /**\n * Resolve the sandbox for a given request context. Calls the resolver function\n * if configured, otherwise returns the static sandbox (or undefined). Results\n * are memoized by `sandboxCacheKey` when set, else per RequestContext instance.\n */\n async resolveSandbox({ requestContext }: { requestContext: RequestContext }): Promise<WorkspaceSandbox | undefined> {\n if (!this._sandboxResolver) return this._sandbox;\n\n const cacheKey = this._sandboxCacheKey?.({ requestContext });\n if (cacheKey != null) {\n let keyed = this._sandboxKeyCache.get(cacheKey);\n if (!keyed) {\n keyed = Promise.resolve().then(() => this._sandboxResolver!({ requestContext }));\n this._sandboxKeyCache.set(cacheKey, keyed);\n keyed.catch(() => {\n if (this._sandboxKeyCache.get(cacheKey) === keyed) {\n this._sandboxKeyCache.delete(cacheKey);\n }\n });\n }\n return keyed;\n }\n\n let pending = this._sandboxRequestCache.get(requestContext);\n if (!pending) {\n pending = Promise.resolve().then(() => this._sandboxResolver!({ requestContext }));\n this._sandboxRequestCache.set(requestContext, pending);\n pending.catch(() => {\n if (this._sandboxRequestCache.get(requestContext) === pending) {\n this._sandboxRequestCache.delete(requestContext);\n }\n });\n }\n return pending;\n }\n\n /**\n * Clear cached resolver-backed sandboxes stored by `sandboxCacheKey`.\n *\n * This only clears the keyed cache. Per-RequestContext WeakMap entries are\n * garbage-collection managed and cannot be cleared by this method.\n *\n * The workspace does not own resolver-returned sandboxes, so this only drops\n * references from the workspace cache. Callers remain responsible for\n * destroying any sandbox instances they created.\n */\n clearSandboxCache(cacheKey?: string): void {\n if (cacheKey === undefined) {\n this._sandboxKeyCache.clear();\n return;\n }\n this._sandboxKeyCache.delete(cacheKey);\n }\n\n /**\n * Access skills stored in this workspace.\n * Skills are SKILL.md files discovered from the configured skillPaths.\n *\n * Returns undefined if no skillPaths are configured.\n *\n * @example\n * ```typescript\n * const skills = await workspace.skills?.list();\n * const skill = await workspace.skills?.get('skills/brand-guidelines');\n * const results = await workspace.skills?.search('brand colors');\n * ```\n */\n get skills(): WorkspaceSkills | undefined {\n // Skills require skills config\n if (!this.hasSkillsConfig()) {\n return undefined;\n }\n\n this.assertSearchWritable();\n\n // Lazy initialization\n if (!this._skills) {\n const baseConfig = {\n skills: this._config.skills!,\n searchEngine: this._searchEngine,\n validateOnLoad: true,\n assertAvailable: () => this.assertSearchWritable(),\n checkSkillFileMtime: this._config.checkSkillFileMtime,\n };\n\n // Priority: explicit skillSource > resolved filesystem (per request) > static filesystem\n // > LocalSkillSource (read-only from local disk, only when no filesystem is configured)\n if (!this._config.skillSource && this._filesystemResolver) {\n this._skills = new ResolvedSourceWorkspaceSkills({\n ...baseConfig,\n source: async ({ requestContext }) => {\n const fs = await this.resolveFilesystem({ requestContext: requestContext ?? new RequestContext() });\n if (!fs) {\n throw new WorkspaceError(\n 'Filesystem resolver returned no filesystem; cannot discover skills',\n 'FILESYSTEM_NOT_RESOLVED',\n this.id,\n );\n }\n return fs;\n },\n });\n } else {\n this._skills = new WorkspaceSkillsImpl({\n ...baseConfig,\n source: this._config.skillSource ?? this._fs ?? new LocalSkillSource(),\n });\n }\n }\n\n return this._skills;\n }\n\n // ---------------------------------------------------------------------------\n // Search Capabilities\n // ---------------------------------------------------------------------------\n\n /**\n * Check if BM25 keyword search is available.\n */\n get canBM25(): boolean {\n return this._searchEngine?.canBM25 ?? false;\n }\n\n /**\n * Check if vector semantic search is available.\n */\n get canVector(): boolean {\n return this._searchEngine?.canVector ?? false;\n }\n\n /**\n * Check if hybrid search is available.\n */\n get canHybrid(): boolean {\n return this._searchEngine?.canHybrid ?? false;\n }\n\n // ---------------------------------------------------------------------------\n // Search Operations\n // ---------------------------------------------------------------------------\n\n /**\n * Index content for search.\n * The path becomes the document ID in search results.\n *\n * @param path - File path (used as document ID)\n * @param content - Text content to index\n * @param options - Index options (metadata, type hints)\n * @throws {SearchNotAvailableError} if search is not configured\n */\n async index(\n path: string,\n content: string,\n options?: {\n type?: 'text' | 'image' | 'file';\n mimeType?: string;\n metadata?: Record<string, unknown>;\n startLineOffset?: number;\n },\n ): Promise<void> {\n this.assertSearchWritable();\n if (!this._searchEngine) {\n throw new SearchNotAvailableError();\n }\n this.lastAccessedAt = new Date();\n\n const doc: IndexDocument = {\n id: path,\n content,\n metadata: {\n type: options?.type,\n mimeType: options?.mimeType,\n ...options?.metadata,\n },\n startLineOffset: options?.startLineOffset,\n };\n\n await this._searchEngine.index(doc);\n }\n\n /**\n * Search indexed content.\n *\n * @param query - Search query string\n * @param options - Search options (topK, mode, filters)\n * @returns Array of search results\n * @throws {SearchNotAvailableError} if search is not configured\n */\n async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {\n if (!this._searchEngine) {\n throw new SearchNotAvailableError();\n }\n this.lastAccessedAt = new Date();\n\n // Documents tagged with `skillScope` belong to request-scoped skill views\n // (dynamic paths or resolver-backed filesystems). They are only meaningful\n // through `skills.getScoped(...).search()`; exposing them here would leak\n // one request's skills into another's unscoped workspace search. Exclude\n // them in the vector query so persisted records from previous processes do\n // not consume topK before filtering. BM25 ignores the vector filter, so\n // over-fetch its currently indexed scoped documents before post-filtering.\n const scopedCount = this._searchEngine.countByPrefix(SKILL_SCOPE_DOCUMENT_PREFIX);\n const topK = options?.topK ?? DEFAULT_SEARCH_TOP_K;\n const unscopedFilter = { skillScope: { $exists: false } };\n const filter = options?.filter ? { $and: [options.filter, unscopedFilter] } : unscopedFilter;\n const results = await this._searchEngine.search(query, {\n ...options,\n topK: topK + scopedCount,\n filter,\n });\n return results.filter(result => result.metadata?.skillScope === undefined).slice(0, topK);\n }\n\n /**\n * Rebuild the search index from filesystem paths without starting the sandbox.\n *\n * Defaults to the configured `autoIndexPaths`, or accepts explicit paths for a\n * one-off rebuild. Paths can be plain directories, single files, or glob patterns.\n * Uses resolvePathPattern for unified resolution: file matches are indexed directly,\n * and directory matches are recursed. Does nothing when search is not configured,\n * the workspace has no static filesystem, or no paths are provided.\n */\n async rebuildSearchIndex(paths: string[] = this._config.autoIndexPaths ?? []): Promise<void> {\n this.assertSearchWritable();\n if (!this._searchEngine || !this._fs || paths.length === 0) {\n return;\n }\n\n // Clear existing BM25 index\n this._searchEngine.clear();\n\n // Adapt filesystem readdir to the ReaddirEntry interface\n const readdir = async (dir: string): Promise<ReaddirEntry[]> => {\n const entries = await this._fs!.readdir(dir);\n return entries.map(e => ({ name: e.name, type: e.type, isSymlink: e.isSymlink }));\n };\n\n // Index all files from specified paths (track across patterns to avoid re-indexing overlaps)\n const indexedPaths = new Set<string>();\n for (const pathOrGlob of paths) {\n try {\n const resolved = await resolvePathPattern(pathOrGlob, readdir);\n const filesToIndex = new Set<string>();\n const directoryRoots: string[] = [];\n for (const entry of resolved) {\n if (entry.type === 'file') {\n filesToIndex.add(entry.path);\n continue;\n }\n // Skip directories already covered by a parent directory\n const alreadyCovered = directoryRoots.some(root => entry.path === root || entry.path.startsWith(`${root}/`));\n if (!alreadyCovered) directoryRoots.push(entry.path);\n }\n // Index direct file matches first so they aren't lost if a directory scan fails\n const indexed = await this.indexFilesForSearch(\n Array.from(filesToIndex).filter(filePath => !indexedPaths.has(filePath)),\n );\n for (const filePath of indexed) indexedPaths.add(filePath);\n\n for (const dir of directoryRoots) {\n try {\n const files = (await this.getAllFiles(dir)).filter(filePath => !indexedPaths.has(filePath));\n const indexed = await this.indexFilesForSearch(files);\n for (const filePath of indexed) indexedPaths.add(filePath);\n } catch {\n // Skip directories that can't be read\n }\n }\n } catch {\n // Skip paths that don't exist or can't be read\n }\n }\n }\n\n /**\n * Load file contents for search indexing in parallel (bounded by {@link FS_READ_CONCURRENCY}).\n * Paths that cannot be read as UTF-8 text are omitted (same behavior as {@link indexFileForSearch}).\n */\n private async batchReadFiles(files: string[]): Promise<Array<{ filePath: string; docs: IndexDocument[] }>> {\n if (!this._fs || files.length === 0) {\n return [];\n }\n\n const fs = this._fs;\n const { default: pMap, pMapSkip } = await import('p-map');\n return pMap(\n files,\n async (filePath): Promise<{ filePath: string; docs: IndexDocument[] } | typeof import('p-map').pMapSkip> => {\n try {\n const content = (await fs.readFile(filePath, { encoding: 'utf-8' })) as string;\n const chunks = splitIntoChunks(content);\n const docs: IndexDocument[] =\n chunks.length === 1\n ? [{ id: filePath, content }]\n : chunks.map((chunk, i) => ({\n id: `${filePath}#chunk-${i}`,\n content: chunk.content,\n startLineOffset: chunk.startLine,\n metadata: { sourceFile: filePath },\n }));\n return { filePath, docs };\n } catch {\n return pMapSkip as typeof import('p-map').pMapSkip;\n }\n },\n { stopOnError: false, concurrency: FS_READ_CONCURRENCY },\n );\n }\n\n /**\n * Batch-read paths and {@link SearchEngine.indexMany}\n *\n * @returns paths that were indexed successfully.\n * @remarks Falls back to one-at-a-time indexing on failure of {@link SearchEngine.indexMany}\n */\n private async indexFilesForSearch(paths: string[]): Promise<string[]> {\n const engine = this._searchEngine;\n if (!engine) return [];\n try {\n const entries = await this.batchReadFiles(paths);\n const pMap = (await import('p-map')).default;\n // Clear stale single-doc/chunked entries from previous indexing passes.\n await pMap(entries, ({ filePath }) => engine.removeSource(filePath), {\n concurrency: FS_READ_CONCURRENCY,\n });\n const docs = entries.flatMap(({ docs }) => docs);\n await engine.indexMany(docs);\n return entries.map(({ filePath }) => filePath);\n } catch {\n const indexed: string[] = [];\n for (const filePath of paths) {\n const id = await this.indexFileForSearch(filePath);\n if (id !== undefined) {\n indexed.push(id);\n }\n }\n return indexed;\n }\n }\n\n /**\n * Index a single file for search. Skips files that can't be read as text.\n * Large files are automatically split into chunks to stay within embedding\n * model token limits.\n *\n * @returns `filePath` when indexed, or `undefined` if read/index failed.\n */\n private async indexFileForSearch(filePath: string): Promise<string | undefined> {\n let content: string;\n try {\n content = (await this._fs!.readFile(filePath, { encoding: 'utf-8' })) as string;\n } catch {\n // Skip files that can't be read as text (e.g. binary files, invalid UTF-8)\n return;\n }\n\n // Clear stale single-doc/chunked entries from previous indexing passes.\n await this._searchEngine!.removeSource(filePath);\n\n const chunks = splitIntoChunks(content);\n\n if (chunks.length === 1) {\n try {\n await this._searchEngine!.index({ id: filePath, content });\n return filePath;\n } catch (error) {\n this._logger?.warn(`Failed to index file \"${filePath}\" for search`, { error });\n return;\n }\n }\n\n let anyIndexed = false;\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i]!;\n try {\n await this._searchEngine!.index({\n id: `${filePath}#chunk-${i}`,\n content: chunk.content,\n startLineOffset: chunk.startLine,\n metadata: { sourceFile: filePath },\n });\n anyIndexed = true;\n } catch (error) {\n this._logger?.warn(`Failed to index chunk ${i} of file \"${filePath}\" for search`, { error });\n }\n }\n return anyIndexed ? filePath : undefined;\n }\n\n private async getAllFiles(\n dir: string,\n depth: number = 0,\n maxDepth: number = 10,\n filesystem: WorkspaceFilesystem | undefined = this._fs,\n ): Promise<string[]> {\n if (!filesystem || depth >= maxDepth) return [];\n\n const files: string[] = [];\n const entries = await filesystem.readdir(dir);\n\n for (const entry of entries) {\n const fullPath = dir === '.' || dir === '' ? entry.name : `${dir}/${entry.name}`;\n if (entry.type === 'file') {\n files.push(fullPath);\n } else if (entry.type === 'directory' && !entry.isSymlink) {\n // Skip symlink directories to prevent infinite recursion from cycles\n files.push(...(await this.getAllFiles(fullPath, depth + 1, maxDepth, filesystem)));\n }\n }\n\n return files;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Initialize the workspace.\n * Starts the sandbox, initializes the filesystem, and auto-mounts filesystems.\n *\n * Resolver-backed providers are skipped because there is no instance until\n * the resolver runs.\n */\n async init(): Promise<void> {\n this._status = 'initializing';\n\n try {\n if (this._fs) {\n await callLifecycle(this._fs, 'init');\n }\n\n if (this._sandbox) {\n await callLifecycle(this._sandbox, 'start');\n }\n\n // Note: Browser is NOT launched here - it's launched lazily in execute-command\n // when a browser CLI command is detected. This matches SDK provider behavior\n // and enables thread-scoped browsers.\n\n // Auto-index files if autoIndexPaths is configured\n if (this._searchEngine && this._config.autoIndexPaths && this._config.autoIndexPaths.length > 0) {\n await this.rebuildSearchIndex(this._config.autoIndexPaths ?? []);\n }\n\n this._status = 'ready';\n } catch (error) {\n this._status = 'error';\n throw error;\n }\n }\n\n /**\n * Reject search writes once teardown has begun, so that a late caller cannot\n * repopulate an index that `destroy()` has already released.\n *\n * Keyed off `_teardownStarted` rather than `_status`: a failed teardown ends\n * in `'error'`, which is also the status of a failed `init()`, and the index\n * has been released either way once `destroy()` has run.\n */\n private assertSearchWritable(): void {\n if (this._teardownStarted) {\n throw new WorkspaceNotReadyError(this.id, this._status);\n }\n }\n\n /**\n * Stop the workspace's live resources without destroying them.\n *\n * Shuts down LSP clients, closes the browser, and stops the sandbox\n * (`stop`, not `destroy` — remote providers pause/suspend so the sandbox\n * can be resumed later; {@link LocalSandbox} kills its background\n * processes). The workspace itself stays usable: filesystem, search index,\n * and skills are untouched, and a later sandbox operation may start the\n * sandbox again.\n *\n * This is what `Mastra.shutdown()` calls for registered workspaces, so a\n * process restart suspends remote sandboxes instead of deleting them.\n */\n async stop(): Promise<void> {\n if (this._teardownStarted || this._status === 'destroyed') {\n return;\n }\n // Coalesce concurrent stop() calls onto one in-flight teardown, same as\n // destroy() does with _destroyPromise.\n if (this._stopPromise) {\n return await this._stopPromise;\n }\n\n this._stopPromise = this._performStop();\n try {\n await this._stopPromise;\n } finally {\n this._stopPromise = undefined;\n }\n }\n\n private async _performStop(): Promise<void> {\n // Shutdown LSP before the sandbox — LSP clients need running processes\n // to send shutdown/exit. The manager is kept: shutdownAll() drains its\n // clients and resets it, so it spawns clients again on the next\n // diagnostics request.\n if (this._lsp) {\n try {\n await this._lsp.shutdownAll();\n } catch {\n // LSP shutdown errors are non-blocking\n }\n }\n\n // Close browser before the sandbox\n if (this._browser) {\n try {\n await this._browser.close();\n } catch {\n // Browser close errors are non-blocking\n }\n }\n\n if (this._sandbox) {\n await callLifecycle(this._sandbox, 'stop');\n }\n }\n\n /**\n * Destroy the workspace and clean up all resources.\n */\n async destroy(): Promise<void> {\n if (this._status === 'destroyed') {\n return;\n }\n if (this._status === 'destroying' && this._destroyPromise) {\n return await this._destroyPromise;\n }\n\n this._teardownStarted = true;\n this._status = 'destroying';\n // Assigned before any await so a concurrent destroy() during the\n // stop-drain below joins this promise instead of starting a second\n // destroy path.\n this._destroyPromise = (async () => {\n // Let an in-flight stop() settle before destructive cleanup so the two\n // teardowns never interleave on the same LSP manager, browser, and\n // sandbox.\n if (this._stopPromise) {\n await this._stopPromise.catch(() => {});\n }\n await this._performDestroy();\n })();\n\n try {\n await this._destroyPromise;\n } finally {\n this._destroyPromise = undefined;\n }\n }\n\n private async _performDestroy(): Promise<void> {\n try {\n // Shutdown LSP before sandbox — LSP clients need running processes to send shutdown/exit\n if (this._lsp) {\n try {\n await this._lsp.shutdownAll();\n } catch {\n // LSP shutdown errors are non-blocking\n }\n this._lsp = undefined;\n }\n\n // Close browser before sandbox\n if (this._browser) {\n try {\n await this._browser.close();\n } catch {\n // Browser close errors are non-blocking\n }\n }\n\n if (this._sandbox) {\n await callLifecycle(this._sandbox, 'destroy');\n }\n\n if (this._fs) {\n await callLifecycle(this._fs, 'destroy');\n }\n\n this.clearSandboxCache();\n\n this._status = 'destroyed';\n } catch (error) {\n this._status = 'error';\n throw error;\n } finally {\n // Release indexed content. The search engine holds the full text of every\n // indexed document, and the skills registry holds the source of every\n // loaded skill version; without this a destroyed workspace keeps them\n // alive for the lifetime of the process. Done in `finally` so a failed\n // resource shutdown above cannot pin the index either.\n this._searchEngine?.clear();\n this._skills = undefined;\n }\n }\n\n /**\n * Get workspace information.\n * @param options.includeFileCount - Whether to count total files (can be slow for large workspaces)\n */\n async getInfo(options?: {\n includeFileCount?: boolean;\n requestContext?: RequestContext;\n resolveDynamicProviders?: boolean;\n }): Promise<WorkspaceInfo> {\n const info: WorkspaceInfo = {\n id: this.id,\n name: this.name,\n status: this._status,\n createdAt: this.createdAt,\n lastAccessedAt: this.lastAccessedAt,\n };\n\n const shouldResolveDynamicProviders = options?.resolveDynamicProviders ?? true;\n // Prefer a provider already resolved for this request. When getInfo runs on\n // the effective workspace proxy during tool execution, `this.filesystem` is\n // the resolved instance, so metadata stays accurate without re-resolving.\n const filesystem =\n (this.filesystem as WorkspaceFilesystem | undefined) ??\n (this._filesystemResolver && shouldResolveDynamicProviders\n ? await this.resolveFilesystem({ requestContext: options?.requestContext ?? new RequestContext() })\n : undefined);\n\n if (filesystem) {\n const fsInfo = await filesystem.getInfo?.();\n info.filesystem = {\n id: fsInfo?.id ?? filesystem.id,\n name: fsInfo?.name ?? filesystem.name,\n provider: fsInfo?.provider ?? filesystem.provider,\n readOnly: fsInfo?.readOnly ?? filesystem.readOnly,\n status: fsInfo?.status,\n error: fsInfo?.error,\n icon: fsInfo?.icon,\n metadata: fsInfo?.metadata,\n };\n\n if (options?.includeFileCount) {\n try {\n const files = await this.getAllFiles('.', 0, 10, filesystem);\n info.filesystem.totalFiles = files.length;\n } catch {\n // Ignore errors - filesystem may not support listing\n }\n }\n } else if (this._filesystemResolver) {\n info.filesystem = {\n id: `${this.id}-dynamic-filesystem`,\n name: 'DynamicFilesystem',\n provider: 'dynamic',\n status: 'pending',\n };\n }\n\n // `this.sandbox` picks up a sandbox already resolved for this request when\n // getInfo runs on the effective workspace proxy. getInfo never invokes the\n // sandbox resolver itself — resolver-backed sandboxes can provision real\n // infrastructure, so resolving stays a tool-execution concern.\n const sandbox = this.sandbox as WorkspaceSandbox | undefined;\n if (sandbox) {\n const sandboxInfo = await sandbox.getInfo?.();\n info.sandbox = {\n provider: sandbox.provider,\n status: sandboxInfo?.status ?? sandbox.status,\n resources: sandboxInfo?.resources,\n };\n } else if (this._sandboxResolver) {\n info.sandbox = { provider: 'dynamic', status: 'pending' };\n }\n\n return info;\n }\n\n /**\n * Get human-readable instructions describing the workspace environment.\n *\n * When both a sandbox with mounts and a filesystem exist, each mount path\n * is classified as sandbox-accessible (state === 'mounted') or\n * workspace-only (pending / mounting / error / unsupported). When there's\n * no sandbox or no mounts, falls back to provider-level instructions.\n *\n * @param opts - Optional options including request context for per-request customisation\n * @returns Combined instructions string (may be empty)\n */\n private getInstructionsForProviders(\n filesystem: WorkspaceFilesystem | undefined,\n sandbox: WorkspaceSandbox | undefined,\n opts?: { requestContext?: RequestContext },\n ): string {\n const parts: string[] = [];\n\n // Sandbox-level instructions (working directory, provider type)\n const sandboxInstructions = sandbox?.getInstructions?.(opts);\n if (sandboxInstructions) parts.push(sandboxInstructions);\n\n // Mount state overlay: check actual MountManager state\n const mountEntries = sandbox?.mounts?.entries;\n if (mountEntries && mountEntries.size > 0) {\n const sandboxAccessible: string[] = [];\n const workspaceOnly: string[] = [];\n const workingDir = sandbox instanceof LocalSandbox ? sandbox.workingDirectory : undefined;\n\n for (const [mountPath, entry] of mountEntries) {\n const fsName = entry.filesystem.displayName || entry.filesystem.provider;\n const access = entry.filesystem.readOnly ? 'read-only' : 'read-write';\n\n // Resolve mount path against workingDirectory when available\n // so the LLM sees the actual usable path (e.g. /tmp/sandbox/s3 instead of /s3)\n const displayPath = workingDir ? path.join(workingDir, mountPath.replace(/^\\/+/, '')) : mountPath;\n\n if (entry.state === 'mounted' || entry.state === 'pending' || entry.state === 'mounting') {\n // mounted: ready now. pending/mounting: will be ready when sandbox starts\n // (executeCommand triggers ensureRunning which processes pending mounts)\n sandboxAccessible.push(` - ${displayPath}: ${fsName} (${access})`);\n } else {\n // error, unsupported, unavailable — NOT accessible in sandbox\n workspaceOnly.push(` - ${mountPath}: ${fsName} (${access})`);\n }\n }\n\n if (sandboxAccessible.length) {\n parts.push(`Sandbox-mounted filesystems (accessible in shell commands):\\n${sandboxAccessible.join('\\n')}`);\n }\n if (workspaceOnly.length) {\n parts.push(\n `Workspace-only filesystems (use file tools, NOT available in shell commands):\\n${workspaceOnly.join('\\n')}`,\n );\n }\n } else {\n // No mounts or no sandbox — fall back to filesystem-level instructions\n const fsInstructions = filesystem?.getInstructions?.(opts);\n if (fsInstructions) parts.push(fsInstructions);\n }\n\n return parts.join('\\n\\n');\n }\n\n getInstructions(opts?: { requestContext?: RequestContext }): string {\n return this.getInstructionsForProviders(this._fs, this._sandbox, opts);\n }\n\n /**\n * Get human-readable instructions describing the workspace environment.\n *\n * Resolves a dynamic filesystem per request. A resolver-backed sandbox is not\n * resolved here unless `instructions.dynamicSandbox` is `'resolve'`.\n */\n async getInstructionsAsync(opts?: { requestContext?: RequestContext }): Promise<string> {\n const requestContext = opts?.requestContext ?? new RequestContext();\n const filesystem = this._filesystemResolver ? await this.resolveFilesystem({ requestContext }) : this._fs;\n const resolvedOpts = { ...opts, requestContext };\n\n // Resolver-backed sandbox: emit placeholder text without calling the resolver.\n if (this._sandboxResolver && this._dynamicSandboxInstructions !== 'resolve') {\n const sandboxText =\n typeof this._dynamicSandboxInstructions === 'function'\n ? this._dynamicSandboxInstructions({ requestContext })\n : DYNAMIC_SANDBOX_INSTRUCTIONS;\n const fsText = this.getInstructionsForProviders(filesystem, undefined, resolvedOpts);\n return [sandboxText, fsText].filter(Boolean).join('\\n\\n');\n }\n\n const sandbox = this._sandboxResolver ? await this.resolveSandbox({ requestContext }) : this._sandbox;\n return this.getInstructionsForProviders(filesystem, sandbox, resolvedOpts);\n }\n\n /**\n * Get information about how filesystem and sandbox paths relate.\n * Useful for understanding how to access workspace files from sandbox code.\n *\n * @deprecated Use {@link getInstructions} instead. `getInstructions()` is\n * mount-state-aware and feeds into the system message via\n * `WorkspaceInstructionsProcessor`.\n *\n * @returns PathContext with paths and instructions from providers\n */\n getPathContext(): PathContext {\n return this.getPathContextForProviders(this._fs, this._sandbox);\n }\n\n private getPathContextForProviders(\n filesystem: WorkspaceFilesystem | undefined,\n sandbox: WorkspaceSandbox | undefined,\n ): PathContext {\n const fsInstructions = filesystem?.getInstructions?.();\n const sandboxInstructions = sandbox?.getInstructions?.();\n\n return {\n filesystem: filesystem\n ? {\n provider: filesystem.provider,\n basePath: filesystem.basePath,\n }\n : undefined,\n sandbox: sandbox\n ? {\n provider: sandbox.provider,\n workingDirectory: sandbox instanceof LocalSandbox ? sandbox.workingDirectory : undefined,\n }\n : undefined,\n instructions: [fsInstructions, sandboxInstructions].filter(Boolean).join(' '),\n };\n }\n\n // ---------------------------------------------------------------------------\n // Logger Integration\n // ---------------------------------------------------------------------------\n\n /**\n * Set the logger for this workspace and propagate to providers.\n * Called by Mastra when the logger is set.\n * @internal\n */\n /** Logger set by Mastra, if any. */\n get logger(): IMastraLogger | undefined {\n return this._logger;\n }\n\n __setLogger(logger: IMastraLogger): void {\n this._logger = logger;\n\n // Propagate logger to filesystem provider if it extends MastraFilesystem\n // Skip when using a resolver — no static instance to set logger on\n if (this._fs instanceof MastraFilesystem) {\n this._fs.__setLogger(logger);\n }\n\n // Propagate logger to sandbox provider if it extends MastraSandbox\n if (this._sandbox instanceof MastraSandbox) {\n this._sandbox.__setLogger(logger);\n }\n }\n}\n","import type { JSONSchema7 } from 'json-schema';\nimport type { PublicSchema, StandardSchemaWithJSON } from '../schema';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '../schema';\nimport type { MastraSandbox } from './sandbox/mastra-sandbox';\n\n/**\n * Brand every `FactorySandbox` carries. A `Symbol.for` key so two copies of\n * `@mastra/core` in one process agree on it. Factory detects the contract by\n * this brand alone, never by `instanceof` or by the presence of `create`.\n */\nexport const FACTORY_SANDBOX_BRAND = Symbol.for('mastra.factory.sandbox');\n\n/** A repository's clone URL and a fresh short-lived credential for it. */\nexport interface FactoryRepositoryAccess {\n cloneUrl: string;\n authorization?: { scheme: 'bearer'; token: string; username?: string };\n}\n\n/**\n * Everything factory knows about a session's sandbox needs: the whole\n * contract between factory and the host's `FactorySandbox`. Factory owns\n * intent; the provider owns resolving `sessionId` to a runnable VM.\n */\nexport interface FactorySandboxContext {\n /** Stable session id, the sandbox identity. */\n sessionId: string;\n /**\n * Id of the factory the session belongs to. Hosts use it to scope what a\n * sandbox receives to one factory, e.g. a credential only one factory's\n * sessions should see. Absent for a session created before factories.\n */\n factoryId?: string;\n /**\n * Display name of the factory the session belongs to, for logs and readable\n * config. Names can be edited and are not unique, so scope secrets by\n * `factoryId`, never by name. Absent when `factoryId` is.\n */\n factoryName?: string;\n /**\n * The provider's physical sandbox id persisted from a prior start, when the\n * session has been started before. Providers that reattach by physical id\n * (e.g. Railway) MUST forward it to the sandbox constructor so resume\n * reattaches the original VM instead of provisioning a replacement. E2B and\n * Platform accept it as a deterministic-reattach optimization. Undefined on\n * a session's first ever start.\n */\n sandboxId?: string;\n /** owner/name of the repository, when the session is repo-backed. */\n repoFullName?: string;\n /**\n * Configured repo setup command, when present. Part of a repo template's\n * identity: a different setup command produces a different template.\n */\n setupCommand?: string;\n /**\n * Resolves the session repository's clone URL and a fresh short-lived\n * credential for it. Providers use it for authenticated work that runs\n * outside the VM: resolving a private repo's head, or cloning it during\n * a template build. The credential is minted per call (installation\n * tokens expire in about an hour); never an org PAT.\n *\n * `undefined` when the session has no repository, which is how a provider\n * knows to build no repo template. The key is always present so that\n * passing the whole context to a provider helper keeps working when this\n * field changes, instead of silently resolving to \"no repository\".\n */\n getRepositoryAccess: (() => Promise<FactoryRepositoryAccess>) | undefined;\n /**\n * Every repository of the session's factory environment, in position\n * order, when the factory has one. Same shape and semantics as the repo\n * templates' `repos` option: each entry resolves its own access and runs\n * its own setup inside its clone at `<workingDirectory>/<repo>`. Mutually\n * exclusive with `getRepositoryAccess`, which is `undefined` whenever this\n * is set. Absent for a session whose factory has no environment repository.\n */\n repos?: Array<{ getRepositoryAccess: () => Promise<FactoryRepositoryAccess>; setupCommand?: string | string[] }>;\n /** Command run once at the workspace root after every repository is set up (`repos` only). */\n workspaceSetupCommand?: string | string[];\n /** A failing repository setup is recorded and the build continues (`repos` only). */\n continueOnSetupFailure?: boolean;\n /** Absolute workspace root the repositories check out under; the provider default when absent. */\n workingDirectory?: string;\n /**\n * Resolves the commit a repository's template should pin, given its clone\n * URL and the credential minted for it. Absent means the provider resolves\n * the default branch head itself.\n */\n resolveHead?: (cloneUrl: string, token?: string) => Promise<string | undefined>;\n /**\n * Environment for template builds and setup steps only, never for runtime\n * commands. Providers keep it out of template identity and out of the\n * image, and may ignore it when their builder can't do that.\n */\n buildEnv?: Record<string, string>;\n /**\n * Opaque id that changes whenever `buildEnv` changes. Providers include it\n * in template identity so an edit rebuilds the template. Never derived\n * from the values.\n */\n buildEnvRevision?: string;\n}\n\n/**\n * Status of one environment template build as the provider reports it.\n * `unknown` is for a build id the provider can no longer resolve (for\n * example after a restart with only in-memory state); factory treats it as\n * not ready.\n */\nexport type FactorySandboxBuildStatus = 'pending' | 'building' | 'ready' | 'failed' | 'unknown';\n\n/** What `builds.start` returns right after a build is requested. */\nexport interface FactorySandboxBuildStart {\n buildId: string;\n status: FactorySandboxBuildStatus;\n templateId?: string;\n}\n\n/** One build as the provider reports it, by id or in a listing. */\nexport interface FactorySandboxBuild {\n buildId: string;\n status: FactorySandboxBuildStatus;\n templateId?: string;\n startedAt?: string;\n finishedAt?: string;\n error?: string;\n logs?: string[];\n}\n\n/**\n * Optional capability: the provider can build the environment template ahead\n * of any session and report on it. `get` and `list` take the settings because\n * template identity includes the template-affecting settings. A provider\n * without `list` has no build history.\n */\nexport interface FactorySandboxBuilds<TSettings> {\n start(ctx: FactorySandboxContext, settings: TSettings): Promise<FactorySandboxBuildStart>;\n get(ctx: FactorySandboxContext, settings: TSettings, buildId: string): Promise<FactorySandboxBuild>;\n list?(ctx: FactorySandboxContext, settings: TSettings): Promise<FactorySandboxBuild[]>;\n}\n\n/** The settings schema of a provider with nothing to tune. */\nconst NO_SETTINGS = { type: 'object', properties: {}, additionalProperties: false } as const satisfies PublicSchema;\n\n/**\n * The one object a host hands factory for its sandboxes. Extend it to get the\n * brand. It owns the session sandbox constructor, the repo template factory, the schema of user-tunable\n * settings, and optionally the builds capability.\n *\n * `create` is synchronous and returns a `MastraSandbox`: factory constructs\n * the sandbox inside a synchronous memo and relies on the base class for the\n * start lifecycle and the runtime env. Construction must be cheap and\n * side-effect-free; VMs are provisioned on `start()` only. Local sandboxes\n * should root their `workingDirectory` at a per-session directory.\n *\n * `settings` is authored in any flavor `PublicSchema` accepts (zod, JSON\n * Schema, or a Standard Schema that can emit JSON Schema). Factory normalizes\n * it and serves the input-side JSON Schema on the wire. Every field must be\n * optional: an absent setting means the provider default. Providers may\n * ignore `ctx.resolveHead` and resolve heads themselves.\n */\nexport abstract class FactorySandbox<TSettings extends Record<string, unknown> = Record<string, unknown>> {\n /** Brand factory detects the class by; never test by shape. */\n readonly [FACTORY_SANDBOX_BRAND] = true as const;\n /** Provider id, e.g. `platform`, `e2b`, `docker`, `local`, `custom`. */\n abstract readonly provider: string;\n /** Defaults to no settings; override with the provider's schema. */\n readonly settings: PublicSchema<TSettings> = NO_SETTINGS as PublicSchema<TSettings>;\n abstract create(ctx: FactorySandboxContext, settings: TSettings): MastraSandbox;\n /**\n * The environment's repo template for the given context and settings, in\n * the provider's own resolver shape. Absent when the provider builds no\n * template ahead of a session.\n */\n template?(ctx: FactorySandboxContext, settings: TSettings): unknown;\n readonly builds?: FactorySandboxBuilds<TSettings>;\n}\n\n/** True for any object carrying the `FactorySandbox` brand. */\nexport function isFactorySandbox(value: unknown): value is FactorySandbox {\n return (\n typeof value === 'object' &&\n value !== null &&\n FACTORY_SANDBOX_BRAND in value &&\n (value as Record<symbol, unknown>)[FACTORY_SANDBOX_BRAND] === true\n );\n}\n\n/** What factory tells its clients about the configured sandbox. */\nexport interface FactorySandboxDescription {\n provider: string;\n settingsSchema: JSONSchema7;\n capabilities: {\n template: boolean;\n builds: { available: boolean; history: boolean };\n };\n}\n\n/** The settings schema as a Standard Schema with JSON Schema output. */\nexport function normalizeFactorySandboxSettings(sandbox: FactorySandbox): StandardSchemaWithJSON {\n return toStandardSchema(sandbox.settings as PublicSchema);\n}\n\n/** The wire description of a `FactorySandbox`: provider, JSON Schema settings, capabilities. */\nexport function describeFactorySandbox(sandbox: FactorySandbox): FactorySandboxDescription {\n return {\n provider: sandbox.provider,\n settingsSchema: standardSchemaToJSONSchema(normalizeFactorySandboxSettings(sandbox), {\n target: 'draft-07',\n io: 'input',\n }),\n capabilities: {\n template: typeof sandbox.template === 'function',\n builds: {\n available: sandbox.builds !== undefined,\n history: typeof sandbox.builds?.list === 'function',\n },\n },\n };\n}\n"],"ignoreList":[45],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAgB,WAAW,KAAqB;CAC9C,IAAI,0BAA0B,KAAK,GAAG,GAAG,OAAO;CAChD,OAAO,IAAI,IAAI,QAAQ,MAAM,OAAO,EAAE;AACxC;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBAAkB,SAAmC;CACnE,MAAM,QAAk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